content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Iterable from typing import Dict from typing import Sequence import hashlib import mmap def verify_checksums(sources: Iterable[str], hashes: Dict[str, Sequence[str]]) -> bool: """Verify checksums for local files. Prints a message whenever there is a mismatch. Args: sources: An...
95abd66c3e6a007b8df8b2caaecde8a85a1f0886
39,457
def fix_pipe_arg(*args): """Use this function so that if a pipe is passed to it it will automatically use its open function wprk in progress""" print(args) new_args = [] for arg in args: if(type(arg) is Pipe): new_args.append(arg.open) else: new_args...
60fc14e8d16e143f5705d440b963dc143bb74291
39,458
def _list_setitem_with_number(data, number_index, value): """ Assigns value to list. Inputs: data (list): Data of type lis. number_index (Number): Index of data. value (Number): Value given. Outputs: list, type is the same as the element type of data. """ return...
00502cf0cf4f1df0b639ba2d40369f1eee4deb79
39,459
def convert_numpy_data_to_polydata(data, header, TNB=None, PT=None): """Converting a range of data to a vtk array. Args: data (numpy.ndarray): Data array. header (list): A list of names for each array. TNB (numpy.ndarray): Data array. PT (numpy.ndarray): Data array. Returns...
734efe64cc4dc3ffccf44c6bc5d7a729b7c87b83
39,460
def _get(url): """ Convert a URL into it's response (a *str*). """ if PYTHON_3: req = request.Request(url, headers=HEADER) response = request.urlopen(req) return response.read().decode('utf-8') else: req = urllib2.Request(url, headers=HEADER) response = urllib...
1906b7a5b6e6d285871373bf9b7095daa6ac8c8f
39,461
import types def fun_compose(g, f): """Function composition using the geach combinator for the appropriate type, defined above.""" if (not (g.type.functional() and f.type.functional() and g.type.left == f.type.right)): raise types.TypeMismatch(g, f, "Function composition type constrai...
97b2cd77ad9daeddf2ca45343cfe2e0b6814f70f
39,462
async def async_api_set_percentage(hass, config, directive, context): """Process a set percentage request.""" entity = directive.entity percentage = int(directive.payload['percentage']) service = None data = {ATTR_ENTITY_ID: entity.entity_id} if entity.domain == fan.DOMAIN: service = fa...
1f67845b681f5703927b1282dc85a1998c97a2d9
39,463
def login_user(username, password): """ Logs in a user Arguments: username <str>: The username of the user password <str>: The password of the user """ query = f""" SELECT * FROM users WHERE username = '{username}' AND password_hash = '{password}'; """ return ...
addd2e5a47db9d9f31a22f0e04be88fbd9101bb0
39,464
import urllib def rapids(expr): """ Fire off a Rapids expression. :param expr: The rapids expression (ascii string). :return: The JSON response of the Rapids execution """ result = H2OConnection.post_json("Rapids", ast=urllib.quote(expr)) if result['error'] is not None: raise EnvironmentError("rapi...
2b9a2be9253f77cf14f07b0034e9a125c32b4fb4
39,465
def get_aqi_pm10_24h(pm10_24h: float) -> (int, str, str): """ Calculates PM10 (24h) India AQI :param pm10_24h: PM10 average (24h), μg/m3 :return: PM10 India AQI, Effect message, Caution message """ cp = __round_down(pm10_24h) return __get_aqi_general_formula_texts(cp, IN_PM10_24H, IN_AQI_EF...
3a6591a0879c06103a9517da4d5187611364c9b9
39,466
import requests def add_user_to_role(user_id, role_id): """ Add a role to a user. Requires server role management. """ auth_headers = { "Authorization": f"Bot {DISCORD_BOT_TOKEN}", } url = f"{DISCORD_API_BASE_URL}/guilds/{DISCORD_GUILD_ID}/members/{user_id}/roles/{role_id}" response = requ...
c07df2fe8a428cae1504580d794d661356f95e9b
39,467
def format_rehydrate_payload(micro_form_data, application_id, page_name): """ Returns information in a JSON format that provides the POST body for the utilisation of the save and return functionality in the XGovFormBuilder Parameters: micro_form_data (dict): application data to refo...
29016442a8ea15c783c480afb4866c61e20acb6d
39,469
def get_p_train_step(): """Wraps train_step with jax.pmap.""" p_train_step = jax.pmap(train_step, axis_name='batch', static_broadcasted_argnums=(3, 4)) return p_train_step
44512bf016aa74178d9d959642a6b2e0bdca8cc0
39,471
def proper_case(package_name): """Properly case project name from pypi.org.""" # Hit the simple API. r = _get_requests_session().get( f"https://pypi.org/pypi/{package_name}/json", timeout=0.3, stream=True ) if not r.ok: raise OSError(f"Unable to find package {package_name} in PyPI re...
a560b53449be8c65c46b63f17defe260591655a5
39,472
from datetime import datetime import requests import base64 def predict(url): """ Returns predicted label. params: link or image bytes """ # generating filename datetimeObj = datetime.now() # if url if as https://miro.medi... if "https" in url: response = requests.get(...
755b787440b837ba6d02a048a09b3ffe26e170a0
39,473
import warnings def read_inputs(nomefile, key_strings, n_lines = None, itype = None, defaults = None, verbose=False): """ Standard reading for input files. Searches for the keys in the input file and assigns the value to variable. :param keys: List of strings to be searched in the input file. :param d...
22db8d5199ced509938ff4570274c95e64d51100
39,474
def _fn_tan_ ( self , b = 1 ) : """ Tangent function: f = tan(ab) >>> f = >>> a = f.tan ( ) >>> a = f.tan ( b ) >>> a = tan ( f ) """ return _fn_make_fun_ ( self , b , Ostap.MoreRooFit.Tan , ...
0d7c4567f8854bcadd2762d602863bcea8e407b2
39,477
def error_output_bf(number_of_parameters, parameters_file_name): """Write the optimized error values into the params file near the corresponding parameter identicator""" try: file2 = open(parameters_file_name, "a+") #file2.seek(0) #position2 = file2.tell() ...
4c9641719e463dc2c1470983a807664339db1775
39,478
from typing import Dict from typing import Union from typing import List async def test_locator_do_work_transfer_request_fc_its_over_9000(config, mocker): """Test that _do_work_transfer_request processes each file it gets back from the File Catalog.""" logger_mock = mocker.MagicMock() lta_rc_mock = mocker...
7838ca5704db67346da2c61234035f88ae23e154
39,479
def get_weekday_type(date_to_test): """Gets the weekday of a date Parameters ---------- date_to_test : date Date of a day in ayear Returns ------- daytype : str holiday or working day Note ---- Bank holidays are defined for the year 2002 - 2015. The whole week ...
ed8c11d3c5ce16c823eccfe3a27435e0a9c1a7dc
39,480
def multi_head(heads, loss_weights=None): """Creates a MultiHead stemming from same logits/hidden layer. Args: heads: list of Head objects. loss_weights: optional list of weights to be used to merge losses from each head. All losses are weighted equally if not provided. Returns: A instance o...
85e6a388168bfae8b4ce83155fba378fce42e136
39,481
import logging def alarm_content() -> str: """ Determines alarm content and adds it to alarm. Checks whether the news and weather briefing tickboxes have been ticked. If they have been ticked it will poll the corresponding api and provide the corresponding information when the alarm goes off. If ...
3d186336cad87ac205bcdccbdc0bb54c7450c039
39,482
import logging def map_package_to_dataset(package, portal_url): """Mapea un diccionario con metadatos de cierto 'package' de CKAN a un diccionario con metadatos de un 'dataset' según el estándar data.json.""" dataset = dict() resources = package["resources"] groups = package["groups"] tags = p...
48369c4221b358e2094fc04e6b5be1862d1306c5
39,483
def op_abs(x): """Returns the absolute value of a mathematical object.""" if isinstance(x, list): return [op_abs(a) for a in x] else: return abs(x)
62d337b11e20b863064d90c563161bc802418abb
39,484
def add_column(colname, desc=None): """Adds column in the form of dict.""" return {'name': colname, 'desc': desc}
e0b985f71e17bfef6096d1433c84b5c163d343ff
39,485
def mc_rollout( steps, checkpoint, environment, env_name, callbacks, loggers, output_dir, input_config, step_tolerance=1000000, algorithm="PPO", multi_agent=False, ): """ Monte Carlo rollout. Currently set to return brief summary of rewards and metrics. """ c...
f592eb546d69be6f5c72d894b3801a9f3ed99f7a
39,486
def VerifyDependents(pe_name, dependents, delay_loaded, list_file, verbose): """Compare the actual dependents to the expected ones.""" scope = {} try: execfile(list_file, scope) except: raise Error("Failed to load " + list_file) # The dependency files have dependencies in two section - dependents and...
903d028fb24a51e2ed4733de578a8a4f95ee61a4
39,487
import tqdm def word_by_category_cooccurrence(corpus, labels, tokenizer=None, min_count=0., max_count=None, max_words=None): """ Devuelve la matriz de coocurrencias entre palabras y la categoría a la que pertence el documento. Es decir, las filas de la matriz son las palabras y las columnas son t...
06ded3c07cc6580e729898bffab56e307249ca91
39,488
def timeit(fn): """ Timing decorator """ def timed(*args, **kwawgs): ts = time.time() result = fn(*args, **kwawgs) te = time.time() print '[time] %r: %2.2f sec' % \ (fn.__name__, te-ts) return result return timed
fa09fac6ffff7d8c642d1c15ecd2154c56c6463f
39,489
import re def ucnstring_to_python(ucn_string): """Return string with Unicode UCN (e.g. "U+4E00") to native Python Unicode (u'\\u4e00'). """ res = re.findall(r"U\+[0-9a-fA-F]*", ucn_string) for r in res: ucn_string = ucn_string.replace(text_type(r), text_type(ucn_to_unicode(r))) ucn_st...
3bf25a80f7c432e13631779fbec1bd3123693a49
39,490
def LOSToRedshift(xLOS, vLOS, H, split=False): """ Input: line of sight distances (Mpc), velocities (km/s) and Hubble constant. Output: relativistic (Doppler) and cosmological (Hubble) redshifts if split = True, otherwise the sum of these (default). """ c = 3.0e5 zREL = np.sqrt((1+vLOS/...
c4cbd6159f551e5d29757227903b15dff8a48c18
39,491
def keypoint_change_coordinate_frame(keypoints, window, scope=None): """Changes coordinate frame of the keypoints to be relative to window's frame. Given a window of the form [y_min, x_min, y_max, x_max], changes keypoint coordinates from keypoints of shape [num_instances, num_keypoints, 2] to be relative to t...
66ecf2d6f22b9d6c14f374ab8e4e6e1a2e4df342
39,492
def build_dataloaders(args, random_state=None): """ Build dataloaders according to experiment args Parameters ---------- args : argparse.Namespace Experiment arguments random_state : np.random.RandomState, optional (default: None) Optional random state for reproducibility in tra...
c0daea5e4dfb37bee7691ff1c58e61c0d2fd67d4
39,493
import re from datetime import datetime def calc_cutoff_date(keep): """given a retention period, calculates the date before which files should be deleted""" keep_match = re.fullmatch(keep_re, keep) if keep_match is None: raise RuntimeError("KEEP must be in the format <number>[dw]") keep_ran...
40a11c37d358dabdb7b4a6fe14d82e029bafc57b
39,494
def traveling_salesperson(pos_list, restarts=100000, beam_search=True, k=4, nstart=None, verbose=False, ): """ Finds an approximate solution to the travelin...
df3c2d00b5378bad872bfad962d817a8e6a8e54e
39,495
def readPatterns(sequence): """Read in the patterns to be matched. """ seqs = {} seqfile = open(sequence) for line in seqfile: toks = line.strip().split() if len(toks) != 2: print "Number of tokens on line is not 2. Kill!!!", line sys.exit(1) seqs[toks...
097df7957cfc9b3642a12510bb485659b3b0627d
39,497
def construct_parameters(**kwargs): """Translates data to a format suitable for Zabbix API Args: **kwargs: Arguments passed to the module. Returns: A dictionary of arguments in a format that is understandable by Zabbix API. """ if kwargs['mappings'] is None: return dict( ...
56b3805f1ea7b524a79107dd3c7df333a8c9026d
39,498
def _extreact_qml_file_info(file): """Returns file object in QML-ready format""" return { "name": file["name"], "path": file["path"], "isFile": file["is_file"], "isDir": file["is_dir"], "level": file["level"] }
4d28a0c1e440023ca887a693a2aea5dbd71d336b
39,499
def check_cn_match(sv_list, cn_increase, cn_decrease, final_cn): """ Check that the CNV combination produces the right final copy number. """ if sv_list == []: return False initial_cn = 2 for sv in sv_list: if sv in cn_increase: initial_cn += 1 if sv in cn_dec...
a9d45b1421b5b6f5ce085df7e2f0c8040bffd163
39,500
def rotateMatrix(m): """ rotate matrix :param m: matrix :type m: list of list of integers :return: rotated matrix :rtype: list of list """ for i in range(int(len(m) / 2)): last_layer = len(m) - i - 1 for j in range(i, last_layer): offset = j - i to...
198c8c28c29c49fee1d26d603e52ec2da43d82a5
39,501
def u_crit_switch_lat_hh80(thermal_ro): """Where RCE and AMC winds are equal in Held Hou 1980 model.""" return np.rad2deg(np.arccos((((1 + 2*thermal_ro)**-0.25))))
998d183e56fd3d423fa7b8f227558030f02ac9cb
39,504
import re def GetUniqueName(context, name): """ Fixup any sbsar naming collision """ foundName = False nameCount = 1 lastChar = '' for sb in context.scene.loadedSbsars: if sb.name.startswith(name): foundName = True # find the highest value suffix on the name ...
fe8b868ec791af091eb0e78abea2549b7e724adf
39,505
def _make_text_table( explainer_values, normalized_values, pipeline_features, original_features, top_k, include_explainer_values=False, algorithm="shap", ): """Make a table displaying the explainer values for a prediction. Args: explainer_values (dict): Dictionary mapping th...
78a5c4422958bfac20c1ff4c05f26dee155bd4c5
39,506
def find_best_ncut(G, x, y, cell_to_idx=None, mut_to_idx=None): """ Given bipartite graph G, 1-dimensional representation x of "left" vertices, 1-dimensional representation y of "right" vertices, exhaustively finds the cut-points in these 1D representations that minimizes the normalized cut. """ i2...
2b9b11a9f892fbfcec2fae3befe9833db87834a7
39,507
from .constants import a_cc, beta def triaxial_strain(magnetic_field): """Triaxial strain corresponding to a homogeneous pseudo-magnetic field Parameters ---------- magnetic_field : float Intensity of the pseudo-magnetic field to induce. """ def field_to_strain(field): return...
6435017f83c84a7880b808c717fa66016c707893
39,508
def get_least_sig_bit(band): """Return the least significant bit in color value""" mask = 0x1 last_bit = band & mask return str(last_bit)
9d56bc5fdbf613f31bf7b21ee08f4f753b3a92db
39,510
def _str(val): """ Ensures that the val is the default str() type for python2 or 3 """ if str == bytes: if isinstance(val, str): return val else: return str(val) else: if isinstance(val, str): return val else: return str...
d1c56751d2b7ef732a0048749e01f4c08e88d0f8
39,511
def CurrentColumn(): """Returns the 0-based current column. Do NOT access the CurrentColumn in vim.current.line. It doesn't exist yet when the cursor is at the end of the line. Only the chars before the current column exist in vim.current.line. """ # vim's columns are 1-based while vim.current.line...
98e2a1f5ef572d9cdacc63289ba23f3eac6f755f
39,512
def sort_data_mnist( x_train, y_train, x_test, y_test, num_points_per_task, test_points_per_task, n_tasks=10, shift=1, ): """ Sorts data into training and testing data sets for each task. Generalized for MNIST datasets and different task numbers. """ # reformat data ...
50ddd8031ba47001e0d098ed80bfc87cf2eaca8a
39,513
def show_confmap_grid(net, X, Y, plot=True, save_path=None, show_figure=False): """ Shows predictions from the model using every channel in the confmap. """ if X.ndim == 2: X = X[None,...,None] if X.ndim == 3: if X.shape[0] == 1: # missing singleton channel X = X[..., No...
2a58de790069636732abebec39020e2110721f8c
39,514
def make_sign_from_network(Network): """ Make an NxN numpy array describing the interaction sign between edges Input: Network - DSGRN network object Output: numpy array with 1 if j->i, -1 if j-|i, and 0 otherwise. """ N = Network.size() sign = np.zeros([N,N]) for j in ra...
96fc6c9ac72c62f8c8927b188df26235f9c58ab3
39,515
def open_file(filename, mode): """Open json file for the current user and given filename, and mode.""" return open('users/' + user_info['username'] + '/' + filename + '.json', mode, encoding='utf-8')
e71f3c722ba11a6f88e9e6cfb7fd329a62f3e1d7
39,516
def rc4(data, key): """RC4 encryption and decryption method.""" S, j, out = list(range(256)), 0, [] for i in range(256): j = (j + S[i] + ord(key[i % len(key)])) % 256 S[i], S[j] = S[j], S[i] i = j = 0 for ch in data: i = (i + 1) % 256 j = (j + S[i]) % 256 S[...
8c77874bcf3be7f5a01bf23b33f8a1cce0d18630
39,517
def test(img, r=3, d=8, option="single"): """Standardized Tester Parameters ---------- img : np.array Input binary image to run DBScan on Keyword Arguments ----------------- r : int Ball radius for DBScan d : int Density threshold; how many neighbors must be pre...
3142dc5351d86a732615bf15ab1ce9931c1eb713
39,518
def binomial_ci(series, alpha=0.05, method="wilson", side="both"): """Returns a binomial confidence interval Computes a binomial confidence interval based on boolean data. A symbolic wrapper for statsmodels.stats.proportion.proportion_confint. Args: series (pandas.Series): Column to summarize;...
fc528d05d5eceded41ed68b81d63fd61c35456fa
39,520
def _redirect_func_check_failed(request): """ 跳转功能权限检测失败的提示页面 """ url = '%saccount/check_failed/?code=func_check' % settings.SITE_URL if request.is_ajax(): # ajax跳转页面,需要借助settings.js实现页面跳转或redirect跳转。 resp = HttpResponse(status=402, content=url) return resp else: ...
176336045ae27bab92a9286743bb01d9c4fae51b
39,521
def I(box): """ Integrate even function over a box """ level = 0 ub = [] return Ir(box, level, ub)
0611e2d89ea4421c34b74dcf84a1552c98131d9e
39,522
import importlib def register_models(app): """All database models need to be registered for Flask-Migrate to see them""" for model in [ "biography", "comments", "contacts", "downloads", "guestbook", "news", "people", "photos", "releases",...
51e134fb5bce61fd4dba12d815561cd4ebf63396
39,523
def encode_data(data, tokenizer, punctuation_enc): """ Converts words to (BERT) tokens and puntuation to given encoding. Note that words can be composed of multiple tokens. """ X = [] Y = [] for line in data: word, punc = line.split() punc = punc.strip() tokens = tok...
ad1a866f8f165f037cf6c85c8f60a4fd15eb570f
39,524
import torch def superpixel_mask(img, mod_specific = True): """ assume dim 0 of img is the batch_size SLIC - K-Means based image segmentation https://scikit-image.org/docs/dev/auto_examples/segmentation/plot_segmentations.html :param input: Input image, which can be 2D or 3D, and grayscale or mult...
da422b706eecd2b44d96e5b5d5fbce4d4ddfe382
39,526
def get_experiment_random_states_data(): """Get the data for random states experiment Params: episode: int The episode for which the data of an experiment instance shall be returned Returns: exp_data: dict The experiment data. For further explanation ...
85c8ca47e1a6423a86e7cf7bc3d1694b9c63957d
39,527
def _private_key_filename(file_prefix): """ Construct the name of a file for use in storing a private key. :param str file_prefix: base file name for the private key (without the extension) :return: private key filename :rtype: str """ return file_prefix + ".key"
66f0bf0dfb3250c81c56220f50438debd74852bf
39,529
import itertools def possible_jp(decay_chain, max_J=2): """get possible resonances jp of J <= max_J""" ret = [] A = decay_chain.top outs = decay_chain.outs jp_list = [jp_seq(max_J) for _ in decay_chain.inner] ret = {} for jps in itertools.product(*jp_list): res_map = {} fo...
b3722316ed07c854e452a7b3995245b0778d9d0a
39,530
import socket def set_mock_context(msg, monkeypatch, writerfqdn='test.bar.example.com'): """ establish the mock context for our testing """ print("================ %s ================" % msg) # pylint: disable=bad-continuation props = { 'writerfqdn': writerfqdn, 'use_existing': False, 'readerf...
b5243906f711837a54bd16444c5ede07f7639928
39,531
def default(mol, gerebtzoff = True): """ Calculates the QED descriptor using average descriptor weights and Gregory Gerebtzoff parameters. """ return weights_mean(mol, gerebtzoff)
e6e8ec956bdc365101a9c54cb5e65ae9326c8a03
39,532
def build_context_residual(offxml, molfile, dihedrals): """Builds context for the openmm calculation keeping the dihedral frozen and the specific energy contributions from the dihedral zeroed out Parameters ---------- offxml: forcefield file molfile: molecule file in sdf format dihedrals: li...
9973eded35fbe6aa468ec4c32559b16e7dc70afc
39,533
import torch def sparse_tensor_to_sparse_adj(x: torch.Tensor) -> sp.csr_matrix: """Converts a SparseTensor to a Scipy sparse matrix (CSR matrix).""" x = x.coalesce() data = x.values().detach().cpu().numpy() indices = x.indices().detach().cpu().numpy() shape = tuple(x.size()) return sp.csr_matr...
3480c0a10d1dcd28b8c75693d305c86cee45bb04
39,534
def preprocess(question): """Do all steps of question preprocessing. Args: question (str): Original question in natural language. ctx_entities (list): Context entities. Returns: str: Question lower, without punctuation and with stopwords replaced by wildcards. """ ...
745542ae9117f7381d4952f5ffebbdf98de161bd
39,535
def create_body(arch, pretrained=True, cut=-2): """ Cut off the body of a typically pretrained `model` at `cut` or as specified by `body_fn` """ model = arch(pretrained) if pretrained: freeze(model) return nn.Sequential(*list(model.children())[:cut])
ed984542e204e93401e6de5872e8f25772a94a06
39,537
from io import StringIO def get_stock_basics(date=None): """ 获取沪深上市公司基本情况 Parameters date:日期YYYY-MM-DD,默认为上一个交易日,目前只能提供2016-08-09之后的历史数据 Return -------- DataFrame code,代码 name,名称 industry,细分行业 area,地区 pe,市盈率 ...
c2c296b311630637df7cf5c2991b08cb4af72210
39,538
def denormalize_image(image): """ Undo normalization of image. """ image = (image / 2) + 0.5 return image
c49a1465d89e317a1c8013969fbee913bf705f4a
39,540
def find_overlapping_selections(selections, selection_strings): """ Given a list of atom selections (:py:class:`scitbx.array_family.flex.bool` arrays) and corresponding selection strings, inspect the selections to determine whether any two arrays overlap. Returns a tuple of the first pair of selection string...
fffd25a98cbb2184d372c5904718f30cd7c97d1a
39,541
def compute_pdf(obs, histogram): """ Compute the PDF of the given observable histogram """ (_, _, bin_size) = constants.HISTOG_PARAM_TABLE[obs] pdf = histogram / sum(histogram) / bin_size return pdf
b7fb65e02838edcf264a332c1969904aeb954c05
39,543
from typing import Any def day_lte(query: int, field_name: str, object: Any) -> bool: """ Check if value of object is less than or equal to value of query """ return _datetime_lte(query, getattr(object, field_name).day)
ce0466aae8825366db0ec0c65fb8bb6311f0f800
39,544
def dot(x,y): """ dot product of two vectors """ return tf.reduce_sum(tf.multiply(x,y))
3a08ad41b0e04760b583f8146c4ecdb4db706f08
39,545
import imghdr def check_bmp(input_file_name): """ Check if filename is a BMP file :param input_file_name: input file name :type input_file_name: string :return whether the file is .bmp :rtype boolean """ return 'bmp' == imghdr.what(input_file_name)
3a8749832418d3976825a79a0bd89c7a77649fe8
39,546
def mediapackage_channels(region): """ Return the MediaPackage channels for the given region. Tags included. """ items = [] service_name = 'mediapackage' if region in boto3.Session().get_available_regions(service_name): service = boto3.client(service_name, region_name=region, config=...
2f59c573b9bec22ddc9badc57abd407bb9a8c61f
39,547
def doc_fb_threshold_filter(threshold, session, docs = None, with_fb = True): """ Filter documents by feedback value threshold: float, the threshold value session: Session, docs: DocumentList, the documents to be considered with_fb: Boolean, if True, then those without feedback values are ...
3eec4e7e2716869eaa573c78f53bbd2085c55913
39,548
def time2char(qr_time, dico): """ Calcule le code alphanumérique à partir d'un datetime. Parameters: qr_time (dt): le datetime à convertir dico (str): le dictionnaitre pour décoder le code (correspondance entre lettre et chiffre) Returns: str: Code alphanumérique """ ...
b3b5542d3b9a2c3fed38fd031b1520beaa00499f
39,550
from typing import List from re import T from typing import Callable from typing import Tuple def enumerate_spans( sentence: List[T], offset: int = 0, max_span_width: int = None, min_span_width: int = 1, filter_function: Callable[[List[T]], bool] = None, ) -> List[Tuple[int, int]]: """ Giv...
7e832fb700ed142e136d3cb0e19b78f44ba14ad9
39,551
import requests def create_quay_org(endpoint, token, org_name): """ Creates an organization in quay Args: endpoint (str): Quay endpoint url token (str): Super user token org_name (str): Organization name Returns: bool: True in case org creation is successful """ ...
edcda0b836fc72283fa042af831e9dcdbf726adb
39,552
async def create_recipe_tag( tag: TagIn, session: Session = Depends(generate_session), current_user=Depends(get_current_user) ): """ Creates a Tag in the database """ return db.tags.create(session, tag.dict())
7456d32724b4b3d4f305952978c065c802c099a5
39,553
def update_weights(point_to_weight, misclassified_points, error_rate): """Given a dictionary mapping training points to their old weights, a list of training points misclassified by the current weak classifier, and the error rate of the current weak classifier, returns a dictionary mapping training poin...
176570f92f56a37581c9ef2b53c1db001d0ae897
39,554
def edge_intersect(p1, q1, edge): """Return True if edge from A, B interects edge. http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/""" p2 = edge.p1 q2 = edge.p2 o1 = ccw(p1, q1, p2) o2 = ccw(p1, q1, q2) o3 = ccw(p2, q2, p1) o4 = ccw(p2, q2, q1) # General case...
6a46d9fbce89f980008ae2049920177178dda7b9
39,555
def get_reversibles_in_direction(color, size, board, x, y, direction): """ Get Reversibles in Direction """ ret = [] next_x, next_y = x, y dx, dy = direction while True: next_x, next_y = next_x + dx, next_y + dy if in_range(size, next_x, next_y): next_value = bo...
525d1bf08c67195036933b824afeb4f8bfd71fc7
39,556
def full_batch_mc(N): """Build computations to use the full batch and the GGN-MC.""" return BaseComputations( extension_cls_directions=SqrtGGNMC, extension_cls_second=SqrtGGNMC, subsampling_first=None, subsampling_directions=None, subsampling_second=None, verbose=...
ed33c598885f95d59b437997786155b15f64a33d
39,557
def enabled(serviceName): """Return True if serviceName is enabled in the run level 3""" return hasRunLevel(serviceName, 3)
eb8b0913c5d06626fa8c10e9c94e849f60a137fc
39,558
def as_mb(in_size: int) -> int: """ Converter functions to convert the size in bytes to megabytes. """ conv = 1024 * 1024 return in_size // conv
af771ea9da7b7d6285cc5a2d3f6ba8873298b9ac
39,559
def _mp_ParameterGrid_getitem(self, ind): """Get the parameters that would be ``ind``th in iteration Parameters ---------- ind : int The iteration index Returns ------- params : dict of str to any Equal to list(self)[ind] """ # This is used to make discrete sampling...
a7c6edb9aa3c3101d0f622701c844032dfafa591
39,560
def mycv2_cvt_gray(img): """ 将图片转换为灰度图 :param img: numpy.ndarray() :return: """ channels = img.shape[2] if channels == 3: return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) elif channels == 4: return cv2.cvtColor(img, cv2.COLOR_BGRA2GRAY) else: # channels == 2...
a44d0a4e9a1fb78a3fc940cd6b60a79a7c618fa3
39,561
def find_cea_coord(header,phi_c,lambda_c,nx,ny,dx,dy): """Convert the index to CCD coordinate (xi,eta)""" nx = int(nx) ny = int(ny) # Array of CEA coords x = [] y = [] for j in range(ny): col = [] row = [] for i in range(nx): col.append(np.radians((i-(nx...
7cb7df07df8c2d4962ec52d4ac574fe242e57f6a
39,562
import socket def allowed_gai_family(): """ https://github.com/shazow/urllib3/blob/master/urllib3/util/connection.py """ return socket.AF_INET #* this to force use ipv4 (issue with ipv6, get 2s delay)
97d983d7c573ba73a2833ca07513a37ce17b521d
39,563
from typing import Callable def build_dict_from_file(path: PosixPath, value_func: Callable = str) -> dict: """Build dictionary from file of key, value pairs separated by tab character. Args: path (PosixPath): Path to dictionary-containing text file value_func (Callable): Function to run over each value Retur...
d2d4f6504f0115c7a8fa22bd115b2bf65f3c5130
39,564
def _get_list_pairs(pairs, idx_class_dict, num_feature): """Creates flattened list of (repeated) pairs. The indexing corresponds with the flattened list of T values and the flattened list of p-values obtained from _get_list_signif_scores(). Arguments: pairs: [(int, int)] list of pa...
fbdff91f18587894a15a9eeb77fc1427779bc6ae
39,565
def sign_out(addon_id): """ Usage: addon.xml --- <import addon="plugin.video.youtube" version="6.1.0"/> --- .py --- import youtube_registration import youtube_authentication youtube_registration.register_api_keys(addon_id='plugin.video.example', ...
9c6b8fd9d66e603e6efc7828a239d0a660e75ec0
39,566
def ldns_dnssec_rrsets_contains_type(*args): """LDNS buffer.""" return _ldns.ldns_dnssec_rrsets_contains_type(*args)
edd31e9608c16acd2523e6310f59901acf3a0153
39,567
import typing from typing import List def parameters_from_proto(msg: Parameters) -> typing.Parameters: """.""" tensors: List[bytes] = list(msg.tensors) return typing.Parameters(tensors=tensors, tensor_type=msg.tensor_type)
2986010677112746ee830fe540e43e8f262a81e3
39,568
def create_loopback_interface(interface_name, vrf="default", ipv4=None, interface_desc=None, **kwargs): """ Perform a PUT and/or POST call to create a Loopback Interface table entry for a logical L3 Interface. If the Loopback Interface already exists and an IPv4 address is given, the function will update th...
a9161ad8c75ad92ac54bdf760fd34c7a0cf0e5ff
39,569
from typing import Tuple def _detail_collection_tuple(worker: AbstractWorker, my_tuple: Tuple) -> Tuple: """ This function is designed to operate in the opposite direction of _simplify_collection. It takes a tuple of simple python objects and iterates through it to determine whether objects in the col...
1e6b01fcb8826aece99a1d4cdf07f37833d80ddf
39,570
def fake_check(name='fake_check', tags=None, is_active=True, run_return=None, run_exception=None, run_logs=None, run_files=None, changed=False, get_var_return=None): """Returns a new class that is compatible with OpenShiftCheck for testing.""" _name, _tags = name, tags class FakeCheck(objec...
1524269a81a9389e17f8d597e040f7165281aef9
39,571