content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def fake_map_matrix_T_without_enemy(map, mySide): """ 伪造一个没有敌方坦克的地图类型矩阵 WARNING: 首先检查是不是对方 tank ,因为可能遇到对方已经死亡或者两方坦克重合 这种时候如果己方坦克恰好在这个位置,就会被删掉,assert 不通过 """ map_ = map oppSide = 1 - mySide cMatrixMap = map_.matrix_T.copy() for oppTank in map_.tanks[oppSide]: if (...
3930ce8bf3dffb2f5f0edac44afa5f8d112a6cac
3,631,600
def dict_factory(cursor, row): """ Factory function to convert a sqlite3 result row in a dictionary :param cursor: cursor object :param row: a row object :return: dictionary representation of the row object """ d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row...
133ac7df43b8bf2b173257c3ca2ed095def84a90
3,631,601
def ndcgREval(data, gt, gf): """ Compute NDCG@R, where R is the number of relevant documents """ ideal = generate_ideal(gt,gf) dcgScore = dcg(data[:(gt)]) norm = dcg(ideal[:(gt)][:len(data)]) if(norm == 0): print('norm=0 in ndcgREval') return dcgScore / norm
4583fb030ab9548bbc30726090e4ea9ad31f9dca
3,631,602
def create_modifiers(y_position): """Create all creatable modifiers""" def create(): for mod in rt.modifier.classes: try: created = mod() print(created) box = create_box() rt.addModifier(box, created) yield box ...
2eb8f02304d79ce3f948a8150c1de51f8cfb8dcb
3,631,603
from typing import List def queue_busy_workers(queue: str) -> List[str]: """ This function counts the number of busy workers for a given queue. """ return [ worker.name for worker in rq.Worker.all(queue=queue) if worker.state == "busy" ]
77de2195323420a664f2a3e16aad7200c5317b49
3,631,604
def coste(theta, X, Y): """ cost function computes J(theta) for a given dataset """ m = np.shape(X)[0] H = sigmoid((np.dot(X,theta))) J = -1/m * ( np.log(H).transpose().dot(Y) + np.log(1-H).transpose().dot(1-Y)) return J
21de5da396c5778842eb81abda8a7ab2a974426b
3,631,605
import torch def test_simhash_table(): """Tests the HashCounter.""" # pylint: disable=too-many-locals,unused-variable num_hash_buckets = 4 debug = True class HashFn(object): """A mock hash function. Big-endian.""" codes = None buckets = None @staticmethod ...
f943d5da82acbb288327c29969e7d53c569de300
3,631,606
import re def replace_php_define(text, define, value): """ Replaces a named constaint (define) in PHP code. Args: text (str) : The PHP code to process. define (str) : Name of the named constant to modify. value (int,str) : Value to set the 'define' to. Returns: ...
02e3194d6fb83958d525651cdca6e3cec1cf3bb7
3,631,607
import logging def setup_logging(name: str, level=logging.DEBUG, json_logging=True) -> Logger: """ Sets up root logger. """ if json_logging: setup_json_logging(level) else: setup_plain_logging(level) # disable useless logging from flask logging.getLogger('werkzeug').setLev...
2ba66ceaeac1ee04d403df576ba67781c7b87d2d
3,631,608
def data_method(func): """ Decorate object methods by tagging them as data methods. The generated data class will have the decorated methods in them. .. code:: python >>> from objetto.applications import Application >>> from objetto.objects import Object, attribute, data_method ...
2a41d343265c0f745242c0e8a369473e22413f8f
3,631,609
def get_frontend_names(): """Return the names of all supported frontends Returns ------- list : list of str A list of frontend names as strings """ return [frontend.name() for frontend in ALL_FRONTENDS]
c251ea7361987d8f9acaa31e3dbfd805a965d94c
3,631,610
import os import inspect def get_spec_file_path(step_class): """ Given a STep (sub)class, divine and return the full path to the corresponding spec file. Use the fact that by convention, the spec file is in the same directory as the `step_class` source file. It has the name of the Step (sub)cla...
55c0df8873322c8d31e728ea02d721df1deb2abe
3,631,611
from gkutils.commonutils import getColour, getColourStats import json def getColourPlotData(g, r, i, z, y): """Collect the colour info from input filter data for plotting""" colourPlotLimits = {} coloursJSON = [] grColour = [] riColour = [] izColour = [] colourPlotLabels = [{'label': 'g-...
37192d4d10ff2cc454d41ae7c91b2e9e87b98d4e
3,631,612
def show(*args, **kwargs): """Wrapper for make_figure()""" return make_figure(*args, **kwargs)
143d1778fd3dbf1e63612bafafa596d86632c969
3,631,613
def set_title(node, title): """Sets the title of a link or image node. Returns 1 on success, 0 on failure. Args: node (cmark_node): The node to set the title attribute on title (string): Title as string Returns: int: 0 on failure, 1 on success """ title=to_c_string(...
b6d1b289e22a768914436ab9a30e2f7036415ad1
3,631,614
def get_image(filename, convert_rgb=True): """Returns numpy array of an image""" image = Image.open(filename) # sometime image data is gray. if convert_rgb: image = image.convert("RGB") else: image = image.convert("L") image = np.array(image) return image
e7d760515cae8309dd7c5fe65c27eeaf0759391d
3,631,615
def find_order_to_apply_confirmation(domain, location): """ Tries to find the EmergencyOrder that the receipt confirmation applies to. :param domain: the domain to search :param location: the SQLLocation that the confirmation is coming from :return: the EmergencyOrder that the confirmation should ap...
8ec732ae4338ff6fdde73096127f6bafb66f41bb
3,631,616
def tiny(tmpdir): """Create a tiny fake brain.""" # This is a minimal version of what we need for our viz-with-timeviewer # support currently subject = 'test' subject_dir = tmpdir.mkdir(subject) surf_dir = subject_dir.mkdir('surf') rng = np.random.RandomState(0) rr = rng.randn(4, 3) ...
9cf3999cf343f2d2005613e668223183e57d4955
3,631,617
import glob def find_exp_parameters(cfg, logger): """ Extracts experimental parameters. """ hemi, space = cfg['hemi'], cfg['space'] space_idf = f'hemi-{hemi}*.func.gii' if 'fs' in space else 'desc-preproc_bold.nii.gz' # Use all possible participants if not provided if cfg['subject'] is None: ...
a72a4c84cc1660005c31ecf65978c07cc5795420
3,631,618
import sys def create_universe(code, infilepath_or_buffer=None, sids=None, from_universes=None, exclude_delisted=False, append=False, replace=False): """ Create a universe of securities. Parameters ---------- code : str, required the code to assign to the universe (low...
cc265828146ccd3d625a487f5fb8ad3d04a55d9f
3,631,619
def onroot_vc(t, y, solver): """ onroot function to reset the solver back at the start, but keep the current velocity as long as the time is less than a given amount """ if t > 28: # we have found 4 interruption points, so we stop return 1 solver.reinit_IC(t, [Y0, y[1]]) return 0
aaabfcc4f06bd48fa2dd8858ffbec4b7d01e886f
3,631,620
def _only_one_selected(*args): """Test if only one item is True.""" return sum(args) == 1
9966cc7c2cde16c689f29ba2add80b2cddce56e7
3,631,621
import re def get_org_files(rcfile): """Get a list of org files from a 'vimrc' file.""" with open(rcfile, 'r') as vimrc: data = vimrc.read() orgfiles = re.search(r'org_agenda_files\s=.*?\[.*?\]', data, re.DOTALL).group() orgfiles = orgfiles.split('[')[1].split(', ') orgfiles = [slugify(x) ...
0ca189535490a56b986060ab2634597aa40c1442
3,631,622
def transform_and_crop_coordinate(coordinate, transform=None, offset=None, theta=None, inverse=True, name=None): """ Transforms a single coordinate then applies a crop offset. You probably don't need to use this, just call random_projection_transform() and then transform_and_crop_image(). Please not...
42acdd0af71144fab240304e256dbf8522d4aa9c
3,631,623
from typing import Dict from typing import Any def parse_direct_to_payload( logger: OchronaLogger, direct: str, config: OchronaConfig ) -> Dict[str, Any]: """ Parses direct input string as PEP-508 compliant file and outputs a JSON payload. :param logger: A configured `OchronaLogger` instance :para...
975eac5df3108a5765b78880535427c100bb2cc7
3,631,624
from typing import Iterator from typing import List def build_uncertainty_calibrator( calibration_method: str, uncertainty_method: str, regression_calibrator_metric: str, interval_percentile: int, calibration_data: MoleculeDataset, calibration_data_loader: MoleculeDataLoader, models: Itera...
fe71921c0dfda06405101b2d5acdd514b5235ddc
3,631,625
def generate_new_diversity_plots(otu_table_fs, gg_f, mapping_f, mapping_category='Sample_Type', min_num_samples=11, category_values_to_exclude=None, verbose=False): """Will exclude 'NA...
02632d4e22c5c4740ebb536e182f7bb24820c170
3,631,626
def tile_data3d(data,(lentZ,lentY,lentX)): """ Tile sparky data into 1D numpy array Parameters: * data Three-dimensional data array * lentZ Z (w1) dimention tile size * lentY Y (w2) dimention tile size * lentX X (w3) dimention tile size Returns 1D numpy array of floats ...
9544fe1ac4a42588bc143d6aaf55be31d382b34e
3,631,627
from typing import Optional from typing import Iterable from typing import Dict import itertools def do_lock( project: Project, strategy: str = "all", tracked_names: Optional[Iterable[str]] = None, requirements: Optional[Dict[str, Dict[str, Requirement]]] = None, ) -> Dict[str, Candidate]: """Perf...
535d82bd9d98eab55ea6e8325c1586df41bad427
3,631,628
import scipy def sparse_to_vector(vector: scipy.sparse.spmatrix): """ Converts one dimensional sparse matrix to a vector array to allow more features. :param vector: Vector as a sparse matrix (x,1) or (1,x). :return: Vector as an one dimensional array (x,). """ return np.ravel(vector.toarray()...
43fd27f48eea91754d95f86a631024a8b07a1a86
3,631,629
def uncentered_operator(X, func, center=None, fill=None, **kwargs): """Only apply the operator on a centered patch In some cases, for example symmetry, an operator might not make sense outside of a centered box. This operator only updates the portion of `X` inside the centered region. Parameters ...
f166e16ea7e0438c8af5e28a86afd71c4ec375f1
3,631,630
def _get_range_and_pstring(variable, mean_cube, tropopause=False): """Get range for color bar and print string.""" if variable == "Air Temperature": print_var = "Temperature [K]" set_range = np.linspace(180, 230, 21) elif variable == "Geopotential Height": print_var = "Geopotential H...
ce3370929d490ae3636d5959a6e9b6ecbfe61110
3,631,631
def merge_storage(df, cons, prod, stor): """Merge positve storage in consumption and negative part in the production """ _df = df.copy() assert not _df.isnull().values.any(), 'Include NaN values' _df[prod] = _df[prod] - _df[stor].clip(upper=0) _df[cons] = _df[cons] + _df[stor].clip(lower=0) ...
28daaf07ecd6a83259388020e044017415a93201
3,631,632
from typing import Mapping from re import T import glob import os def load_page_data(img_dir: str, current_obj: Mapping[T, T]) -> Mapping[T, T]: """ Iterate through the img directory, and retrieve the page level data """ page_data = [] for f in glob.glob(f'{img_tmp}/*'): page_obj = {} ...
6b47f944a1a5d9b6c6e6c9aa097ee812b7aff100
3,631,633
from calendar import isleap from datetime import datetime def numeric_date(dt=None): """ Convert datetime object to the numeric date. The numeric date format is YYYY.F, where F is the fraction of the year passed Parameters ---------- dt: datetime.datetime, None date of to be convert...
1a369bb8824db3f885b1af269f0d86eba5103769
3,631,634
def specific_clean_cell_lst(): """Clean a list of cells - column cells""" # List of strings col_cells = request.json["cells"] col_type = request.json["coltype"] clean_cells = fix_specific(col_cells, col_type) return clean_cells
e61e17dc311516bed179cde6a4b9cecaab4420de
3,631,635
def compress_sym(sym_expanded, make_symmetric=True): """Compress symmetric matrix to a vector. Similar to scipy.spatial.squareform, but also contains the diagonal. Parameters ---------- sym_expanded : nd-array, shape (size, size) Input matrix to compress. make_symmetric : bool (de...
f2d5b7ce91c18ae3730feda002cdcc76ad0540e7
3,631,636
def get_cc_biz_id_by_app(fta_application_id): """ 通过fta_application_id获取cc_id """ app = session.query(AlarmApplication).filter_by( app_id=fta_application_id, is_deleted=False, is_enabled=True).first() if app: return app.cc_biz_id else: return None
597bd8dd170c42d19166e9db64c80bf490fb7a2d
3,631,637
from pathlib import Path def get_csv_filename(folder="zips"): """ Returns the Path of the csv-file stored in zips-folder """ csvs = [f for f in Path(folder).iterdir() if f.suffix == ".csv"] if len(csvs) >= 1: return csvs[0] else: logger.error(f"CSV-file missing") raise ...
d7e811ef15174d29c9514c2eeaa853e9da4996e8
3,631,638
import random import string def generate_random_id(start: str = ""): """ Generates a random alphabetic id. """ result = "".join(random.SystemRandom().choices(string.ascii_lowercase, k=16)) if start: result = "-".join([start, result]) return result
f818ecf7ba4296a3ad010ef20bc5e286036bb56d
3,631,639
def add_supplementary_xml(element: etree, config: dict) -> etree: """Add arbitrary xml from configuration object to xml Args: element (etree): original xml document config (dict): standard ReadAlong-Studio configuration Returns: etree: xml with supplemental markup """ if "x...
2b554a5de0b43731c75ccd7bf311591a3b51001d
3,631,640
def get_client_names(worksheet) -> list: """Get list of client names from Excel worksheet.""" num_rows = worksheet.max_row names = [] for i in range(2, num_rows+1): cell_obj = worksheet.cell(row=i, column=1) if cell_obj.value not in names: names.append(cell_obj.value) r...
6da6e52ed10e84ae79119c511e063114bb61b334
3,631,641
def as_json(dictionary): """ Object hook used in order to create the right object reading a JSON. :param dictionary: Dict, Dictionary to analyze. :return: The right object represented in the JSON. """ if "first_name" in dictionary: return User(**dictionary) elif "update_id" in dictio...
ed5f386e3c37a363cbec0e026960628d827462a4
3,631,642
def coefficient_map(cv: xr.DataArray) -> xr.DataArray: """ Return the coefficient map :param cv: cost volume :type cv: xarray.Dataset, with the data variables cost_volume 3D xarray.DataArray (row, col, disp) :return: the coefficient map :rtype : 2D DataArray (row, col) """ row = cv.coor...
32179fff71635283394226ffac2ee9c0ba7f0f3d
3,631,643
def transpose(a, axes=None): """ Reverse or permute the axes of an array; returns the modified array. For an array a with two axes, transpose(a) gives the matrix transpose. Parameters ---------- a : array_like Input array. axes : tuple or list of ints, optional If specified...
d51bc442e71f52c08b38cff98275540528e178be
3,631,644
def post_token(): """ <url>/notifications/api/PushToken Get Device Tokens for notifications """ token = request.json.get('token') deviceId = request.json.get('deviceId') user = User.query.filter_by(token=token).first() device = DevicesNotificationHandlers.query.filter_by(user_id=user.i...
3e287f339500c02e91e5a6512878178686ec3a22
3,631,645
from datetime import datetime import pytz def get_timestamp() -> str: """ Получение текущей временной метки """ return datetime.datetime.now(pytz.utc).strftime('%Y.%m.%d %H:%M:%S %z').strip()
093b2275d5dc1381eb69a3b845702715e5b8281f
3,631,646
from brambox.boxes.annotations import Annotation def as_anno(class_id, x_center, y_center, w, h, Win, Hin): """ Construct an BramBox annotation using the basic YOLO box format """ anno = Annotation() anno.class_id = class_id anno.x_top_left = (x_center - w / 2) * Win anno.y_top_left = (y_c...
e46f6b626bf500da0b2c63a4d093ad392e9a9b3a
3,631,647
def parse_testcase_xml(testcase): """ Flatten fields of interest from a TestCase XML element into a dict, where anything not found is None """ # We need to emit only Unicode things, but we may get str or Unicode # depending on if the parser thinks we have UTF-8 or ASCII data in a field. ...
e93d629f0953cecd30ce4a7241a8f6a1db76fb06
3,631,648
def build_coco_results(dataset, image_ids, rois, class_ids, scores): """Arrange results to match COCO specs in http://cocodataset.org/#format rois: [num_instance, (y1, x1, y2, x2, class_id)] in image coordinates. image_ids: [num_instances] class_ids: [num_instances] scores: (optional) confidence sc...
ac25c6e6a4ed45b976ff06369edaa13c8f5fcdb7
3,631,649
import requests def get_instance_ip(compute_url, instance_id, token): """ Retrieve the IPs of the running instance """ url = "%s/servers/%s/ips" % (compute_url, instance_id) headers = {"X-Auth-Token": "%s" % token, "Content-type": "application/json"} curl = requests.get(url=url, headers=headers) ...
224e916f574869023e540d6a4913acd7541c7942
3,631,650
def _domain_map(z, satu, mapType=0): """domain color the array `z`, with the mapping type `mapType`, using saturation `s`. Currently there is only one domain coloring type """ h = _hue(z) s = satu*_np.ones_like(h, _np.float) v = _absolute_map(_np.absolute(z)) hsv_map = _np.dstack((h, s, ...
a422d2b463a97afdcae18f820f2ac7462f54ce91
3,631,651
from typing import Callable def provider(provided_dependency_name: _Name = None, **named_dependencies: _Name) -> Callable[[_ProviderMethod], _ProviderMethod]: """ Method decorator for instance provider methods in a module class. The provider method can take parameters representing dependencie...
52ef1a7a65b93b498ecfbb1b3173effc91de8e67
3,631,652
def _num_to_words(num): """ Turkish converter Params: num(int/long): number to be converted Returns: wordString """ units = ['', u'bir', u'iki', u'üç', u'dört', u'beş', u'altı', u'yedi', u'sekiz', u'dokuz'] teens = ['', u'onbir', u'oniki', u'onüç', u'ondört', u'onbeş', u'on...
14adb62d17f2089127ca9b90f1d884063c028adf
3,631,653
def get_vehicle_txn(session, vehicle_id): """ For when you just want a single vehicle. Arguments: session {.Session} -- The active session for the database connection. vehicle_id {String} -- The vehicle's `id` column. Returns: {dict} or {None} -- Contains vehicle information fo...
5f7f3c773e40f567a060015f2c8e5c043b6cb1f5
3,631,654
import six def slugify(value): """ Slugify a string (even if it contains non-ASCII chars) """ # Re-map some strings to avoid important characters being stripped. Eg # remap 'c++' to 'cpp' otherwise it will become 'c'. for k, v in settings.OSCAR_SLUG_MAP.items(): value = value.replace(...
53273bd3f6ae2418736a22a2780581d1974dc92b
3,631,655
def upper(value: str): # Only one argument. """Converts a string into all uppercase""" return value.upper()
8ec4c4ed284bc8d823e356db7749a4c98a00b194
3,631,656
from typing import Dict from typing import List def _create_sorted_hash_list(data: Dict, hash_function: str) -> List[Dict]: """Create a sorted sha256 hash list.""" out = [] for obj in data: hash = _create_json_hash(obj, hash_function=hash_function) out.append(hash) out.sort() retur...
2efbac4652bf2db975513610956445c932543d11
3,631,657
def disease_function_subset(ipa, network_dir, printing=False): """ Returns a disease subset of functions. A function is considered a disease if its lowercase name is the same as its class and its name is not a function category. Build must be run first """ disease_names = set() for function ...
83370f5dd6a6245d4fc2dc988c43beec110a3f48
3,631,658
import torch def map_tensor(x, func): """ Apply function @func to torch.Tensor objects in a nested dictionary or list or tuple. Args: x (dict or list or tuple): a possibly nested dictionary or list or tuple func (function): function to apply to each tensor Returns: y (dic...
38675f836fcb462946e03054b74051e7ccea882e
3,631,659
import os import json def get_keyname_to_fingerprint(): """Get a map of pub key filename to fingerprint""" trusted_keys_dir = get_trusted_keys_dir() filepath = os.path.join(trusted_keys_dir, _KEYNAME_TO_FINGERPRINT_FILE) with open(filepath, "r") as fi: keyname_to_fingerprint = json.load(fi) ...
77a04a1c7f9d53846a6e6fc11652508b5f406be6
3,631,660
def xor(a,b): """ XOR two strings of same length""" assert len(a) == len(b) x = [] for i in range(len(a)): x.append( chr(ord(a[i])^ord(b[i]))) return ''.join(x)
cbe3d32883dc5516821711181c7f5d52194d89de
3,631,661
def wmts2twmsbox_scale(scale_denominator, col, row): """ Returns TWMS equivalent bounding box based on TILECOL and TILEROW. Arguments: scale_denominator -- WMTS scale denominator value from getCapabilities. col -- WMTS TILECOL value. row -- WMTS TILEROW value. """ print ...
9660f5a1b3b9eecf5623d70c9b32861ab2e8dd88
3,631,662
import hashlib import yaml def get_hash(x, length=16): """Return hash of x.""" return hashlib.sha224(yaml.dump(dict(key=x)).encode()).hexdigest()[:length]
e13c278ef649e2d8c213580d5ccc27ae64d72027
3,631,663
def make_unhealthy(): """Sets the server to simulate an 'unhealthy' status.""" global _is_healthy _is_healthy = False template = render_template('index.html', hostname=gethostname(), zone=_get_zone(), template=...
c379b14b1a924bc81c31b74a322d6ddde67421d8
3,631,664
def filtreDonner(liste) : """ Fonction qui va filtrer les donner. Cette fonction va filtrer les donners inutiles mot trop frequent ... param : liste[string] -> liste chaine de caractere a filtrer return : liste[string] -> liste chaine de caractere filtrer. """ return liste
b7e5f04a6645895a16c44f3f477ecc9d9a8ecef1
3,631,665
import os.path def get_include(): """ Return the directory that contains the dpctl *.h header files. Extension modules that need to be compiled against dpctl should use this function to locate the appropriate include directory. """ return os.path.join(os.path.dirname(__file__), "include")
0d63b857071ce118dd8206187fddbf59d2d86583
3,631,666
def get_problem_set(dataset,LABELNAME,labels,i2s): """Aggregate labels and associated article/domain information by chosen classification task Arguments - dataset: a list of article text (the corpus) - LABELNAME: a string given by user input identifying the classification task - labels: a dict ...
3f65f75e1d8fcde54babd5d236dc179955fb3fe7
3,631,667
def hello_world(text: str) -> str: """Print and return input.""" print(text) return text
7bfcb8e9cfccdf5fad8c702f97f6b7c4e56c7682
3,631,668
def NestedGroupKFold(model, X, y, parameter_grid, groups, class_weights, scorer=make_scorer(accuracy_score), inner_cv=GroupKFold(n_splits=4), outer_cv=GroupKFold(n_splits=4)): """ Implements a nested version of GroupKFold cross-validation using GridSearchCV to evaluate models that nee...
7fec0ff05ee002212432cb6fee414013ba079e6d
3,631,669
def create_vespa_query(query, text_processor, number_videos): """ Create the body of a Vespa query. :param query: a string representing the query. :param text_processor: an instance of `TextProcessor` to convert string to embedding. :param number_videos: Number of videos to return. :return: bod...
b5d5ead2b31244220a41474758b463910e9d8e9a
3,631,670
def _thumb_from_pixel_clusters(images, mask, h, w, use_distance_from_centroid=False): """ Alternate implementation. Results are sharper, but noisier """ # 6-color # colors = np.array([[1, 0, 1, 0], [1, 0, 0, 0], [1, 1, 0, 0], # [0, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 0]], # ...
a91440006ac42208ffaca71f6889f5b7ca1c9dcf
3,631,671
def get_rtClock(): """ Instanziiert ein Real Time Clock Objekt """ return rtc.SDL_DS3231()
9a854aba4e6986f7ed56fb058a368ad629d5c3e1
3,631,672
def create_draft(service, user_id, message_body): """Create and insert a draft email. Print the returned draft's message and id. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message_bo...
6ea595383349b74d5265b569b25a6e10b9748c6c
3,631,673
def analyze_files(file_list): """return info for each file in a list that if it passed in analyzedir? passed in basedir? the results are the same?""" result = map(lambda f: (f,)+analyze(f, analyzedir, basedir), file_list) return result
bd8be9c6a9047921670546eea5667c312e5fe26d
3,631,674
from . import default_logger import time def profiling(func): """Decorator to mark a function for profiling. The time and memory usage will be recorded and printed. Example: .. highlight:: python .. code-block:: python @profiling def foo(): print(1) """ @wraps(...
36c83e39743336be49436f4cfcc8891040288f54
3,631,675
import psutil import math def find_no_of_workers(maxworkers, sys_share=0): """ Find the optimal number of workers for MP such that system does not crash. Parameters ---------- maxworkers : Int. Maximum number of workers allowed. Returns ------- workers : Int. Workers used. sys_sh...
ebb5140d6099ef6600a2373a12e18747ccdaddbd
3,631,676
from typing import Callable from typing import Dict from typing import Any import tqdm from typing import Literal def from_rdflib( graph: Graph, literal_cleaning_func: Callable = None, kg_name: str = None, multi_value: Callable = None, ) -> KG: """Create forayer knowledge graph object from rdflib ...
a3dae2f4586603de9a5b52c45715591c31d386fc
3,631,677
def video_player(obj): """ Receives object with 'video' FileField and returns HTML5 player. """ return {'object': obj}
197c16e2ff16777634cfad327c08df571481ed09
3,631,678
def wait_for(scope, prompt): """ Waits until the response of the remote host contains the given pattern. :type prompt: regex :param prompt: The prompt pattern. """ conn = scope.get('__connection__') conn.expect(prompt) scope.define(__response__=conn.response) return True
10c95350b4c2aa4ad8fe9bce040efc461f461ca0
3,631,679
from typing import Callable from re import T import requests import time def retry_temporary_errors( download_func: Callable[[SelfWithConfig, DownloadRequest], T] ) -> Callable[[SelfWithConfig, DownloadRequest], T]: """Decorator function for handling server and connection errors""" backoff_coefficient = 3...
3bbaeee3c440691f7a66c75a81d0ed83f80ae02f
3,631,680
def get_first_order_indices(param_names, sim_id_params, all_results): """ Sobol method - First Order Indices Equations from https://en.wikipedia.org/wiki/Variance-based_sensitivity_analysis TODO: CS: This is exploration and is not complete (or even correct). """ params_outcomes = [ (s...
f598af62b597d376488de404b3d146e5cea9f4fd
3,631,681
def render_list_categories(): """ METHOD=GET. Renders Category Page. """ categories = session.query(Category).order_by(asc(Category.name)).all() return render_template('categories/list.html', categories=categories)
45cb527a9188f10957e276952bf56ebd1b2b59ae
3,631,682
import time def perform_install(pspec, is_upgrade=False, force=False, quiet=False): """ Args: pspec (PackageSpec): Package spec to install is_upgrade (bool): If True, intent is an upgrade (not a new install) force (bool): If True, check latest version even if recently checked q...
557deda9249bb0b117f3cc820d3d6d8009988940
3,631,683
import re def tokens_to_str(message, section='body'): """ Takes one section of a message as specified by key param and returns it in string format to be joined with other messages for summarization, printing, id creation (future). """ body = message[section] new_mess = '' if isins...
4b8f57060dfe110a2a0e2c767a73966cc1d5abdb
3,631,684
def azip(*aiterables): """async version of izip with parallel iteration""" return _azip(*aiterables, fillvalue=None, stop_any=True)
8b296a1775ee54d0a1d44997b3dd7682a8da434f
3,631,685
def collect_data( bids_dir, participant_label, bids_validate=True, bids_filters=None, ): """ Uses pybids to retrieve the input data for a given participant Examples -------- >>> bids_root, _ = collect_data(str(datadir / 'ds054'), '100185', ... bids_va...
5f654e4fb6b145e7ad34e238b1ad9e992e426b6e
3,631,686
def filter_features(input_features, **kwargs): """ Args: input_features: A Geojson feature collection Returns: A json of two geojson feature collections: passed and failed """ if type(input_features) is DictType: if input_features.get("features"): return iterate...
69c1f517b8344a6a493d41228a4e249eb385aaab
3,631,687
import functools def polygon_wrapper(func): """ Wrapper function to perform the setup and teardown of polygon attributes before and after creating the polygon. Keyword arguments: func (function) -- the function to draw the polygon. """ @functools.wraps(func) def draw_polygon(self...
76056e41c36a2c15dcb8a2e05cc4ec4c1beb68dc
3,631,688
def compose_base_find_query(user_id: str, administrator: bool, groups: list): """ Compose a query for filtering reference search results based on user read rights. :param user_id: the id of the user requesting the search :param administrator: the administrator flag of the user requesting the search ...
2f398930603093ddc59e0c6ba4956e7d46a7758d
3,631,689
def test_prevent_links(): """Returning None from any callback should remove links or prevent them from being created.""" def no_new_links(attrs, new=False): if new: return None return attrs def no_old_links(attrs, new=False): if not new: return None ...
ad78f384621d301d1ce8c7339f4648bf2517c7f9
3,631,690
def intersection (l, r) : """Compute intersection of lists `l` and `r`. >>> intersection (range (4), range (2,5)) [2, 3] """ r_set = set (r) return [x for x in l if x in r_set]
36d7003587204814b6e09ec093f2a6715e87a500
3,631,691
def filter_df_on_ncases(df, case_id_glue="case:concept:name", max_no_cases=1000): """ Filter a dataframe keeping only the specified maximum number of cases Parameters ----------- df Dataframe case_id_glue Case ID column in the CSV max_no_cases Maximum number of cases...
5f8532ebe465d7b80934b35ef8d3925217f4e355
3,631,692
def welcome(): """List all available api routes.""" return ( f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start<br/>" f"/api/v1.0/start/end" )
fd95f362d1e39ac6485e97ee0a77d318f3011bb8
3,631,693
import ftplib import os def pdbDownload( file_list, hostname=HOSTNAME, directory=DIRECTORY, prefix=PREFIX, suffix=SUFFIX ): """ Download all pdb files in file_list and unzip them. """ success = True # Log into server print("Connecting...") ftp = ftplib.FTP() ftp.connect(hostname)...
d1845f2f7bc0befa6b2138034bba3b56311e9c50
3,631,694
def decode(s): """doc me""" for encoding in "utf-8-sig", "utf-16": try: return s.decode(encoding) except UnicodeDecodeError: continue return s.decode("latin-1")
40ce76e5067e591eb1e433f18c4d574a7235ab4e
3,631,695
def Quantum_Vibrational_S(Temperature, wavenumbers): """ Funciton to calculate the quantum vibrational entropy at a given temperature **Required Inputs Temperature = single temperature in Kelvin to determine the vibrational entropy (does not work at 0 K) wavenumbers = array of wavenumber (in order w...
be0b760db66651ff95bcb1614d17573bbfa80941
3,631,696
def _open(full_path, state, year, variety, database='SID'): """Returns a handle using python's builtin open() function; however, it will skip past any non-content rows as specified within. This is necessary because HCUP files very occasionally have bonus content, typically a data use notice, and it...
b7a236433122a051abc913f34112b4250908b508
3,631,697
def summon(self: Client, entity: str, pos: Vec3 = None, nbt: dict = None) -> str: """Summons an entity.""" return self.run('summon', entity, pos, nbt)
651adcb3f0ec1e8d1efef0ba79bfe1f4e208c3f9
3,631,698
def get_inner_html(node): """Gets the inner HTML of a node, including tags.""" children = ''.join(etree.tostring(e).decode('utf-8') for e in node) if node.text is None: return children return node.text + children
467af19497a12744851ddadbb6fbf138cf846809
3,631,699