content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import cplex import io def run_and_read_cplex(n, problem_fn, solution_fn, solver_logfile, solver_options, warmstart=None, store_basis=True): """ Solving function. Reads the linear problem file and passes it to the cplex solver. If the solution is successful it returns variable solu...
77a9e12509cde2e40287bab49ffb7f226ce3c2e2
3,633,500
def deharmonize(audio_data, sfreq, shift, high=False, audio_min_freq=200.0, decompose="none"): """Deharmonize audio data using full signal FFT Args: audio_data(numpy.ndarray): Audio data in a NumPy array sfreq(float): Sampling frequency in Hz shift(float): Linear shift i...
4e7f05d42673ca7cb9c468a9de14d35d83166ee0
3,633,501
def get_max_sushi(m, features, combs, rank_dict): """ Specifically for DTS :param model: gpflow model :param features: sushi features :param rank_dict: dictionary from sushi idx to place in ranking :return: tuple (index of max sushi, rank) """ y_vals = m.predict_y(combs)[0] num_discr...
a1e214c00db7df45d231e9a3f4aa8da544037dc9
3,633,502
import os import logging import time def get_multi_media(shelter_id=0, category_id=2, section = 'Identification'): """ Get pictures for the shelter sent by Dropzone via a POST request. """ first = True ImageFile.LOAD_TRUNCATED_IMAGES = True imgwidth = 1280 shelter = Shelter.query.fil...
2d70f9318d062e9b98ff3413fa76c1e683ef20a4
3,633,503
def is_watchman_supported(): """ Return ``True`` if watchman is available.""" if WIN: # for now we aren't bothering with windows sockets return False try: sockpath = get_watchman_sockpath() return bool(sockpath) except Exception: return False
7681ba911456196ad01774e0607bd81872e4b82a
3,633,504
def geolocation(data_base, year, latitude, longitude, geofunc): """ Function for geolocating points from database and calculating distance from them to the given user point. >>> 33.5 <= geolocation(pd.DataFrame([["Film1", 2020, "Some info",\ "Los Angeles California USA"]], columns \ = ["name",...
ecd619b23d0f72c29b164f7fdbf498b41f25c0f0
3,633,505
import os def get_clip_details(file_path: str) -> (int, float, int, int): """ Gets a clip's duration, frame rate and dimensions (width, height). :param file_path: The absolute path to a clip. :return: Duration in seconds, frame rate in FPS and width and height in pixels. This is given in...
9c49a79cbf93481f68ea34b43b550842598bbca1
3,633,506
import shutil import os def notebook(live_mock_server, test_dir): """This launches a live server, configures a notebook to use it, and enables devs to execute arbitrary cells. See tests/test_notebooks.py """ @contextmanager def notebook_loader(nb_path, kernel_name="wandb_python", save_code=True,...
1930792965a3b3492cefca8f1a583754164b103f
3,633,507
from typing import OrderedDict def read_dig_polhemus_isotrak(fname, ch_names=None, unit='m'): """Read Polhemus digitizer data from a file. Parameters ---------- fname : str The filepath of Polhemus ISOTrak formatted file. File extension is expected to be '.hsp', '.elp' or '.eeg'. ...
d048f1f83844bc591a301c046f3c25494ffd0339
3,633,508
def gt_comparison_plot(data, mu=None, sig=None, k=3.3e11, x_c = None): """ Generate the comparison Zipf plot for the data. Parameters ---------- data : array_like Size of each firm, where size is measured by sales, value added, number of employees or some other variable. k : f...
64a30fd6bf77edbd89ed3194838e518a1022cc11
3,633,509
def make_cache_key(instance): """Construct a cache key for the instance.""" prefix = '{}:{}:{}'.format( instance._meta.app_label, instance._meta.model_name, instance.pk ) return '{}:{}'.format(prefix, str(uuid4()))
6a83d20c94e26ece5ca3d98ad8cb70dd17fa5ea7
3,633,510
import os import pickle def load_model(filename: str, model_dir=config.MODEL_DIR) -> nn.Module: """ Load the model from a pickle. :param filename: name of the file :param model_dir: directory in which the file is located :return: """ with open(os.path.join(model_dir, filename), 'rb') as f:...
02bdefdaf5ba24bcd9174ad57cd895a6bcf0a551
3,633,511
def CalculateMediationPEEffect(PointEstimate2, PointEstimate3): """Calculate derived effects from simple mediation model. Given parameter estimates from a simple mediation model, calculate the indirect effect, the total effect and the indirect effects Parameters ---------- PointEstimate2 : ...
d2247985e46a78bc3333983e09a1030fd59f139d
3,633,512
def get_engine(db_dir_name, echo=False, path_str=None): """数据库引擎""" if path_str: path = path_str else: path = db_path(db_dir_name) engine = create_engine('sqlite:///' + path, echo=echo) return engine
c3f35e7a52619c9ef5e1414efdbebcaebb8b8bd3
3,633,513
def init_websauna(config_uri: str, sanity_check: bool=False, console_app=False, extra_options=None) -> Request: """Initialize Websauna WSGI application for a command line oriented script. :param config_uri: Path to config INI file :param sanity_check: Perform database sanity check on start :param con...
2d56ce6afa1ede2c69c92422cb360e856d84b007
3,633,514
def ts_glm_ridge_pipeline(): """ Return pipeline with the following structure: glm \ -> ridge -> final forecast lagged - ridge / Where glm - Generalized linear model """ node_glm = PrimaryNode("glm") node_lagged = PrimaryNode("lagged") node_ridge_1 = S...
41a6ce2e280ca6a89ba482715ab9bcdc807c0d29
3,633,515
import os def read_validation_annotations(validation_dir): """Reads validation data annotations.""" return read_tiny_imagenet_annotations( os.path.join(validation_dir, 'val_annotations.txt'), os.path.join(validation_dir, 'images'))
6e586a1321db4c13c3ca0d2fb34f92ebfbd62c7b
3,633,516
def norm1to1(operator, n_samples=10000, mxBasis="gm", return_list=False): """ Returns the Hermitian 1-to-1 norm of a superoperator represented in the standard basis, calculated via Monte-Carlo sampling. Definition of Hermitian 1-to-1 norm can be found in arxiv:1109.6887. """ if mxBasis == 'gm': ...
f0ad0d6a89ab9c3ec275c5ea5ce1a343d275f625
3,633,517
def _load_image_gdal(image_path, value_scale=1.0): """ using gdal to read image, especially for remote sensing multi-spectral images :param image_path: string, image path :param value_scale: float, default 1.0. the data array will divided by the 'value_scale' :return: array of shape (height, width, ban...
94d8ce48f069bc311637237d805fd140604cffc2
3,633,518
def f1_chantler(element, energy, _larch=None, **kws): """returns real part of anomalous x-ray scattering factor for a selected element and input energy (or array of energies) in eV. Data is from the Chantler tables. Values returned are in units of electrons arguments --------- element: at...
76b5143e3d9be69ae6f7f8ee246669ee3da9fe08
3,633,519
def rgb_to_hex(red_component=None, green_component=None, blue_component=None): """Return color as #rrggbb for the given color tuple or component values. Can be called as TUPLE VERSION: rgb_to_hex(COLORS['white']) or rgb_to_hex((128, 63, 96)) COMPONENT VERSION rgb_to_hex(64, 183, 22) ...
37f5216f7f22f82072db6980541a815d87d02ef3
3,633,520
def remove(predicate, seq): """ Return those items of sequence for which predicate(item) is False >>> def iseven(x): ... return x % 2 == 0 >>> list(remove(iseven, [1, 2, 3, 4])) [1, 3] """ return filterfalse(predicate, seq)
2953386f289894e4f5a052d1f67087dcf4631a3a
3,633,521
def average_coords(coords_list): """Calculate average coords Parameters ---------- coords_list : list[skrobot.coordinates.Coordinates] Returns ------- coords_average : skrobot.coordinates.Coordinates """ q_list = [c.quaternion for c in coords_list] q_average = averageQuaternion...
3a3e59685311042a91295760ec025e12916c34d5
3,633,522
def lowpassfilter(input_vect, width=101): """ Computes a low-pass filter of an input vector. This is done while properly handling NaN values, but at the same time being reasonably fast. Algorithm: provide an input vector of an arbitrary length and compute a running NaN median over a box o...
1b71ac8f0a2fc61b0cd3d5ab9e1f218471b3569c
3,633,523
def n_keywords(data): """Return the number of keywords. Arguments --------- data: asreview.data.ASReviewData An ASReviewData object with the records. Return ------ int: The statistic """ if data.keywords is None: return None return np.average([len(keywor...
d2692c1e040cf659dcc6eb1aa7c5718d52a345d8
3,633,524
def flatten_reshape(variable, name=''): """Reshapes high-dimension input to a vector. [batch_size, mask_row, mask_col, n_mask] ---> [batch_size, mask_row * mask_col * n_mask] Parameters ---------- variable : a tensorflow variable name : a string or None An optional name to attach to thi...
933ec231c15f91122db755f9bac98679cdf9864e
3,633,525
def register_command(data): """Remote command registration service. This has to be enabled by liquer.commands.enable_remote_registration() WARNING: Remote command registration allows to deploy arbitrary python code on LiQuer server, therefore it is a HUGE SECURITY RISK and it only should be used if oth...
c9b764e6f2758ad4cc90aced854421d7d83ece9e
3,633,526
import json def add_noise(dgen_list, noise): """Add noise decorators to the DataGenerators from `dgen_list` list. Parameters ---------- dgen_list : list of IDataGenerator A list of DataGenerators to be decorated. noise : list of dict or dict or None Noise configuration. If...
f716211ad9f1d35e66845e0887aafa5955575b4b
3,633,527
import random import json def index(): """ Web app index page. It renders two pictures about the data. One bar chart and word cloud. """ # extract data needed for visuals # TODO: Below is an example - modify to extract data for your own visuals genre_counts = df.groupby('genre').coun...
10509856618e9f09c273d20b617e948448623a8e
3,633,528
from pathlib import Path def open(table_file: str, table_map_file: str = None) -> pd.DataFrame: """ Opens a dynamo table file, returning a DynamoTable object :param table_file: :return: dataframe """ # Read into dataframe df = pd.read_csv(table_file, header=None, delim_whitespace=True) ...
7dca5cfc2c3c6201730b99db13680bed81b51a4b
3,633,529
def _evaluate_tags(pcluster_config, preferred_tags=None): """ Merge given tags to the ones defined in the configuration file and convert them into the Key/Value format. :param pcluster_config: PclusterConfig, it can contain tags :param preferred_tags: tags that must take the precedence before the confi...
d23e4c29b463736fa23a65c977e16734b235c4c9
3,633,530
def dict_view(request): """ 字典管理 """ return render_mako_context(request, '/system_permission/dictmgr.html')
56b8b80fb56c032f319f23754c3926cadf74ddc6
3,633,531
def rot_ETA(eta: float) -> np.ndarray: """Return rotation matrix corresponding to eta axis. Parameters ---------- eta: float eta axis angle Returns ------- np.ndarray Rotation matrix as a NumPy array. """ return z_rotation(-eta)
07e3c42f40bba0d73b4718eaa2d56b17e3dffd8e
3,633,532
def show_lists(chat_id): """ It shows all the lists of the given user :param chat_id: :return: """ lists = notelistmodel.find_all_lists(mongodb, chat_id) return {"text": monkeyview.lists_view(lists), "parse_mode": "Markdown"}
b72df596357e0174294589eab413fa1f8f8da840
3,633,533
import logging def test_params_from_fw_spec(tempdir, files, dtool_config, default_create_dataset_task_spec, default_freeze_dataset_task_spec): """Will create dataset with some task parameters pulled from fw_spec.""" logger = logging.getLogger(__name__)...
16bff2b0c79b332211283c53e9ca6630b0ce809a
3,633,534
from re import T def import_string(path: str) -> T.Any: """ Import a dotted Python path to a class or other module attribute. ``import_string('foo.bar.MyClass')`` will return the class ``MyClass`` from the package ``foo.bar``. """ name, attr = path.rsplit('.', 1) return getattr(import_modu...
3475a6081d64f656ec2c50b74f9314d519d18dee
3,633,535
from re import T def inbox(): """ RESTful CRUD controller for the Inbox - all Inbound Messages are visible here """ if not auth.s3_logged_in(): session.error = T("Requires Login!") redirect(URL(c="default", f="user", args = "login", ...
486640ebdb1a142f22ac146479fa36c289a8e1be
3,633,536
def glorot_uniform_sigm(shape): """ Glorot style weight initializer for sigmoid activations. Like keras.initializations.glorot_uniform(), but with uniform random interval like in Deeplearning.net tutorials. They claim that the initialization random interval should be +/- sqrt(6 / (fan_in...
4cd3a3f40e276aba5b16726af4ce28adefe25748
3,633,537
def pytest_report_header(config): """Display cachedir with --cache-show and if non-default.""" if config.option.verbose > 0 or config.getini("cache_dir") != ".pytest_cache": cachedir = config.cache._cachedir # TODO: evaluate generating upward relative paths # starting with .., ../.. if s...
d859b89b11015623a9dd2bc159c855b896d27ee7
3,633,538
def params(kernels, time, target, target_frame, observer, corr): """Input parameters from WGC API example.""" return { 'kernels': kernels, 'times': time, 'target': target, 'target_frame': target_frame, 'observer': observer, 'aberration_correction': corr, }
d030ad459b294a268c8bc3a851a32495dcbf5c02
3,633,539
import re import os def extract_thresholds_of_intensity_criteria(data_path, sub_ses_test, patch_side, new_spacing, out_folder, n_parallel_jobs, overlapping, prints=True): """This function computes the threshold to use for the extraction of the vessel-like negative patches (i.e. the negative patches that rough...
8da250d5c25b338d19d1e68b1b27b12a8221b467
3,633,540
def group_activity_list( group_id: str, limit: int, offset: int, include_hidden_activity: bool = False, ) -> list[Activity]: """Return the given group's public activity stream. Returns activities where the given group or one of its datasets is the object of the activity, e.g.: "{USER}...
aaab03202571e3eb562fc3b8ec663ac58cc69ab0
3,633,541
def rotMatrixfromXYZ(station, mode='LBA'): """Return a rotation matrix which will rotate a station to (0,0,1)""" loc = station.antField.location[mode] longRotMat = rotationMatrix(0., 0., -1.*np.arctan(loc[1]/loc[0])) loc0 = np.dot(longRotMat, loc) latRotMat = rotationMatrix(0., np.arctan(loc0[0,2]/l...
a6df1bc5bc0cd8752cbd71c025a1b5208d1b8a34
3,633,542
import logging def geo_info_for_geo_name( geo_name: str, username: str = CONFIG["geonames_username"] ) -> GeoInfo: """Get geo information (latitude and longitude) for given region name.""" logging.info("Decoding latitude and longitude of '{}'...".format(geo_name)) gn = geocoders.GeoNames(username=user...
e6827ae4b0e3297311dd16fc3a98865bcc7fc252
3,633,543
def char_accuracy(predictions, targets, rej_char, streaming=False): """Computes character level accuracy. Both predictions and targets should have the same shape [batch_size x seq_length]. Args: predictions: predicted characters ids. targets: ground truth character ids. rej_char: the character id use...
caccf28fab0aa4127da7b30d95f380452b713974
3,633,544
import json def read_cities_db(fname="world-cities_json.json"): """Read a database file containing names of cities from different countries. Source: https://pkgstore.datahub.io/core/world-cities/world-cities_json/data/5b3dd46ad10990bca47b04b4739a02ba/world-cities_json.json """ with open(fname) as f: ...
1edb970e329e7781cebb61853a13a6f45d349250
3,633,545
def ConcatWith(x, dim, tensor): """ A wrapper around `tf.concat` to support `LinearWrap` :param x: the input tensor :param dim: the dimension along which to concatenate :param tensor: a tensor or list of tensor to concatenate with x. x will be at the beginning :return: tf.concat(dim, [x]...
8d15e008f8e2ec70c2d875a9bb5dcb1786d011ed
3,633,546
def strip_df(data: pd.DataFrame) -> np.ndarray: """Strip dataframe from all index levels to only contain values. Parameters ---------- data : :class:`~pandas.DataFrame` input dataframe Returns ------- :class:`~numpy.ndarray` array of stripped dataframe without index ""...
3cd04b6b6cf144ac63854fbbab5ffa3784ccd707
3,633,547
def isRef(obj): """ """ if isinstance(obj, dict) == True and '_REF' in obj: return obj['_REF'] else: return False
0f1ad92cfafff5dcbc9e90e8544956b05c3452ec
3,633,548
from pathlib import Path from typing import Dict from typing import Tuple import pickle def collect_genes_with_confidence( query: str, *, cache_file: Path = None, client: Neo4jClient, ) -> Dict[Tuple[str, str], Dict[str, Tuple[float, int]]]: """Collect gene sets based on the given query. Para...
18f949c1613f05b242a27dff7d16722af4d6bbf6
3,633,549
import copy def intervals_disjoint(intvs): """ Given a list of complex intervals, check whether they are pairwise disjoint. EXAMPLES:: sage: from sage.rings.polynomial.complex_roots import intervals_disjoint sage: a = CIF(RIF(0, 3), 0) sage: b = CIF(0, RIF(1, 3)) sage...
ebe3208f1af22f7001d3dee10a2dca6a68558cc8
3,633,550
def _get_registered_typelibs(match='HEC River Analysis System'): """ adapted from pywin32 # Copyright (c) 1996-2008, Greg Stein and Mark Hammond. """ # Explicit lookup in the registry. result = [] key = win32api.RegOpenKey(win32con.HKEY_CLASSES_ROOT, "TypeLib") try: num = 0 ...
88d5cf576454793678b275826d4087e5bcd263e4
3,633,551
def head(content, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", transla...
6ed2622a53b3e3df8254cd6bfbc41cad296dea8c
3,633,552
def standardize(dataset, verbose=True): """ remove all source-specific columns, keeping only those that occur in all repo sources. also adds extra columns with default values """ found = False for source, extra_features in EXTRA_FEATURES.items(): if all(feat in dataset.features for feat in extr...
f057c9d98c0525f4536053c20c0467ae2e8b6287
3,633,553
def mark(tv,stars=None,rad=3,auto=False,color='m',new=False,exit=False): """ Interactive mark stars on TV, or recenter current list Args : tv : TV instance from which user will mark stars stars = : existing star table auto= (bool) : if True, recentroid from existing posit...
66a291c564329a878aea7658cd9fc071cc303d0b
3,633,554
def result_summary_info(request,object_id): """Present a result summary""" object = get_object_or_404(Results.ResultSummaryList, pk=object_id) protocolfields={} for (fieldname, text, cond) in [("version_intolerant", "Version Intolerant", Results.ResultCondition.RESULTC_VERSION_INTOLERANT), ("extension...
1036fad0d52435912579e9680f5037a8aa052e53
3,633,555
def stackplot(data, add, xlabel='', ylabel='', cmap='Spectral', figsize=(3, 4.5), lw=1, plot=True): """ Plots a stack plot of selected spectras. :type data: list[float] :param data: Data to in the plot. :type add: float :param add: displacement, or difference, between each curve...
959118905abbfada9d4af3ac0a8ab414b00a9ffe
3,633,556
import torch def batch_detect(net, img_batch, device): """ Inputs: - img_batch: a numpy array of shape (Batch size, Channels, Height, Width) """ B, C, H, W = img_batch.shape orig_size = min(H, W) # BB, HH, WW = img_batch.shape # if img_batch if isinstance(img_batch, torch.Tens...
e20de1e4f3915e2e377e790f7e6cb3df5d76b5cb
3,633,557
def int_to_binary(x, n): """Convert an integer into its binary representation Args: x (int): input integer n (int): number of leading zeros to display Returns: (str) binary representation """ if type(x) != int: raise ValueError('x must be an integer.') return f...
c3d68a798f84988290bd4e845a5bcc015872b054
3,633,558
import os def read_requirements(): """Parse requirements from requirements.txt.""" requirements_path = os.path.join('.', 'requirements.txt') with open(requirements_path, 'r') as f: requirements = [line.rstrip() for line in f] return requirements
bc4282532c74d5c2f2bd9cd225b7604d0924035d
3,633,559
def convert_examples_to_features(examples, tokenizer, max_seq_length, max_program_length, is_training, op_list, op_list_si...
d7024a0ff97d94a5c2aa32e63230e972584fb1d2
3,633,560
def negative_mean_successiness(c): """Negative mean successiness over the course of the trial.""" if c.needed_control_arm_events.size > 1: center = float(c.needed_control_arm_events.mean()) width = float(c.needed_control_arm_events.std()) else: center = float(c.needed_control_arm_events) width = c...
ac6e07076c422ef524f46583edd41eff48f6733e
3,633,561
def determina_putere(n): """ Determina ce putere a lui 2 este prima cea mai mare decat n :param (int) n: numarul de IP-uri necesare citit de la tastatura :return (int) putere: puterea lui 2 potrivita """ putere = 1 while 2**putere < n+2: putere += 1 return put...
85e2c1dcd2ea5d86b5db3c6ced28dd65e244c467
3,633,562
def attribute_rename_cmd(oldattr, newattr): """ Rename an attribute. If it's not present nothing is done, and its value is kept. That's it. $ cjio myfile.city.json attribute_rename oldAttr newAttr info """ def processor(cm): utils.print_cmd_status('Rename attribute: "%s" =>...
b48e0e90bbb75cdf9828e21c115b758250f433e2
3,633,563
from datetime import datetime def editItemInCategory(item_id): """ Edit an item in a given category.""" if 'username' not in login_session: sMsg = "You are not authorized to perform this '%s' " % ('edit item category') sMsg += "action because you are not logged in. You are being redirected to login." flash...
ed2f51eea2713271f82440599edd90f015820b24
3,633,564
def factorial(n, show=False): """ -> Calcula o Fatorial de um número. :param n: O número a ser calculado. :param show: (opcional) Mostra ou não a conta. :return: O valor do Fatorial de um número n. """ f = 1 for c in range(n, 0, -1): if show: print(c, end='') ...
4e2928b2e2b197e40aacd8ec1b18c9afee42e229
3,633,565
def parse_commands(log_content): """ parse cwl commands from the line-by-line generator of log file content and returns the commands as a list of command line lists, each corresponding to a step run. """ command_list = [] command = [] in_command = False line = next(log_content) wh...
dff555cd0ec84619425fc05e4c8892c603bcc994
3,633,566
from datetime import datetime import ssl import logging import time def wait_for_operation(client, project, op_id, timeout=datetime.timedelta(hours=1), polling_interval=datetime.timedelta(seconds=5), sta...
a7487beda110d1b5d52d8073d58fb6a33b0997a2
3,633,567
import re def regex_closest_match(regex: str, string: str) -> str: """Find the longest version of regex that matches something in string.""" no_match = True modified_regex = regex while no_match: # TODO: there may be a better way to do this rather than a try-except (perhaps using sre_parse to...
2154fe51c874fd910e8f5da8b1c687cc598e5cab
3,633,568
def bij_connected_comps(components): """Set of connected planar graphs (possibly derived) to nx.PlanarEmbedding.""" res = nx.PlanarEmbedding() for g in components: g = g.underive_all() g = g.to_planar_embedding() res = nx.PlanarEmbedding(nx.compose(res, g)) return res
7f705f25756e114c91bbff9a09880d5bfb8d37ee
3,633,569
from typing import Tuple def render_responses(intent: Intent, language_data: IntentLanguageData) -> Tuple[IntentResponseDict, str]: """ Return a copy of responses in `language_data` where intent parameter references are replaced with their values from the given :class:`Intent` instance. Args: ...
4e83d1b75b25d8e3ab7d030890744f0081c02c10
3,633,570
import os def sp_cpu(file): """Read single-point output for cpu time.""" spe, program, data, cpu = None, None, [], None if os.path.exists(os.path.splitext(file)[0] + '.log'): with open(os.path.splitext(file)[0] + '.log') as f: data = f.readlines() elif os.path.exists(os.path.split...
ca9cb22b0981b3a14eafdd2637eccbe448597432
3,633,571
def cropseq(indexes, l, stride): """generate chunked silencer sequence according to loaded index""" print('Generating silencer samples with length {} bps...'.format(l)) silencers = list() i = 0 for index in indexes: try: [sampleid, chrkey, startpos, endpos, _] = index exc...
09bac76a6209398cdb5cb230be7aa18f5f895204
3,633,572
import tqdm def generate_claims(model, gen_dset, dl, tokenizer, device): """ Run generation using the given model on the given dataset :param model: BART model to use for generation :param gen_dset: The original dataset :param dl: A dataloader to use for generation :param tokenizer: A tokenize...
0f042101ca6c864249c62e1934a9c58f0b21f9e7
3,633,573
def to_geojson(series): """Return a GeoJSON geometry collection from the series (must be in EPSG:4326). Did not use the builtin for the series since it introduces a lot of bloat. """ return { "type": "GeometryCollection", "geometries": series.apply(lambda x: x.__geo_interface__).to_list...
2ebdc001ed7a6fb3ee6e6cac9fc7722e19518e20
3,633,574
import os import subprocess def check_kafka_ready(expected_brokers, timeout, config, bootstrap_broker_list=None, zookeeper_connect=None, security_protocol=None): """Waits for a Kafka cluster to be ready and have at least the expected_brokers to present. This commands uses the Java docker-utils libra...
ca8aa8a1c8a51b0885bd887bb4a8bc8854160c3c
3,633,575
import copy async def copy_context(ctx: commands.Context, *, author=None, channel=None, **kwargs): """ Returns a new Context with changed message properties. """ # copy the message and update the attributes alt_message: discord.Message = copy.copy(ctx.message) alt_message._update(kwargs) ...
78a82922a7740cfcdad0e17a0f85a16ee53a068e
3,633,576
def getConstraintWeightAttr(leader, constraint): """ Return the weight attribute from a constraint that corresponds to a specific leader node. Args: leader (PyNode): A node that is one of the leaders of a constraint constraint (PyNode): A constraint node """ for i, target in enu...
e53ef981f505f1c8fc21fff7b71605764d6da3e0
3,633,577
import sys def load_data(dataset_str): """ Loads input data from gcn/data directory ind.dataset_str.x => the feature vectors of the training instances as scipy.sparse.csr.csr_matrix object; ind.dataset_str.tx => the feature vectors of the test instances as scipy.sparse.csr.csr_matrix object; ind....
d629e3ceb8f8b030526f15294309b95636e90838
3,633,578
def approximate_mds(dists): """Approximate multidimensional scaling (MDS) Estimate the inter-node distance matrix from source node distances as described in "Iterative Geometry Calibration from Distance Estimates for Wireless Acoustic Sensor Networks" (https://arxiv.org/abs/2012.06142). Subsequentl...
6f2aef5e71c439990840143089fa9cc941a81c2c
3,633,579
def build_resnet_fpnindi_backbone(cfg, input_shape: ShapeSpec): """ Args: cfg: a detectron2 CfgNode Returns: backbone (Backbone): backbone module, must be a subclass of :class:`Backbone`. """ bottom_up = build_resnet_backbone(cfg, input_shape) in_features = cfg.MODEL.FPN.IN_FEAT...
40329cfb0d414305e7d38966b41e352cc44c6535
3,633,580
from typing import Tuple from typing import Any def _get_min_max_outputs(node: BaseNode, fw_info: FrameworkInfo) -> Tuple[Any, Any]: """ Return the min/max output values of a node if known. If one of them (or both of them) is unknown - return None instead of a value. Args: ...
c43992c9b2cd64b9970766fe06d6d0c6af3a6954
3,633,581
def remove_stop_words(document): """Returns document without stop words""" document = ' '.join([i for i in document.split() if i not in stop]) return document
c4385790901f09eadeac67dc1035a12bedf8cb45
3,633,582
def Ion_Flux_Relabeling(h,q): """ Oh no! Commander Lambda's latest experiment to improve the efficiency of her LAMBCHOP doomsday device has backfired spectacularly. She had been improving the structure of the ion flux converter tree, but something went terribly wrong and the flux chains exploded. ...
8d8694722c8a8d6dcf4aabad3d677fb059d252d9
3,633,583
def process_line(line, previous_state): """ Read line, split it before opening brackets if not in quotes nor escaped and add '\n' in the end of new lines. """ # opening bracket and/or quote can start in other line brackets = previous_state.brackets in_quotes = pr...
24b997f61263563a67f58a65f2e070c1b21ee478
3,633,584
def parse_tape6(tape6="TAPE6.OUT"): """Parses an ORIGEN 2.2 TAPE6.OUT file. Parameters ---------- tape6 : str or file-like object Path or file to read the tape6 file from. Returns ------- results : dict Dictionary of parsed values. Warnings -------- This method...
5082ee35ce8198db680c0b7be86d703c4c349402
3,633,585
def property_values_to_string(pv,extra_indentation = 0): """ Parameters ---------- pv : OrderedDict Keys are properties, values are values """ # Max length keys = pv[::2] values = pv[1::2] values = ['"%s"' %x if isinstance(x,_Quotes) else x for x in values] key_lengths...
0a8f5b188f74d1779c871a843eb7394631162fc4
3,633,586
def parse_cmdline(): """parse command line arguments""" parser = ArgumentParser( description="dtbTool version " + str(QCDT_VERSION)) parser.add_argument("input_dir", help="Input directory") parser.add_argument("-o", "--output-file", type=FileType('wb'), required=True, ...
4f2cf506c4463b19859403de0aac0707d4ad5050
3,633,587
def __build_vocab(nlp, datasets): """ Generates the encoder vocabulary (natural language tokens), decoder vocabulary (programming language tokens) and stack vocabulary (terminal and non-terminal symbols, tokens) by parsing each source and target example in each split. :param nlp: nl pro...
d162169874a1f82779641615658aa5be52aafb81
3,633,588
import os def file_contains_exact_text(filename, text): """Returns True iff the file exists and it already contains the given text.""" if not os.path.isfile(filename): return False with open(filename, "r") as infile: intext = infile.read() return text == intext return False
49bbb86c30a5df5d41e78cd64ddb58d44eaaf899
3,633,589
from typing import Optional from typing import Dict def get_profile(key: str) -> Optional[Dict]: """Fetch user profile. Arguments: --------- key: User's database key. Returns: --------- Profile dictionary if exists else None. """ return BASE_PROFILE.get(key=key)
0bf1d86707b14735afb6b832d41b63a25650985e
3,633,590
def rectangle_centered( w: int = 1, h: int = 1, x: None = None, y: None = None, layer: int = 0 ) -> Component: """ a rectangle size (x, y) in layer bad naming with x and y. Replaced with w and h. Keeping x and y for now for backwards compatibility .. plot:: :include-source: imp...
a61c07a87c6b1a6d347ddc104863657eafd305ad
3,633,591
from datetime import datetime def sched_time_to_dt(timeStr, targetDate): """Converts a GTFS schedule time string to a datetime Note that a GTFS time may be more than 24 hours, in which case the function removes 24 from the hours part of the time and increases the date part of the datetime by 1 Args: t...
9fb43c4e19d050480649b39f1ac9a79f617338b7
3,633,592
def get_arxiv_csl(*, arxiv_id): """ Generate a CSL Item for an unversioned arXiv identifier using arXiv's OAI_PMH v2.0 API <https://arxiv.org/help/oa>. This endpoint does not support versioned `arxiv_id`. """ # XML namespace prefixes ns_oai = "{http://www.openarchives.org/OAI/2.0/}" ns_a...
54fcf1df4b6963a95788a1cdf3306d583fe0b8e6
3,633,593
from typing import Mapping from typing import Sequence import math def _equivalent_data_structures(reference, struct_2): """Compare arbitrary data structures for equality. ``reference`` is expected to be the reference data structure. Cannot handle set like data structures. """ if isinstance(refer...
57ecaa315a1f9a516b4ac2c2528f0f207fffab6f
3,633,594
def _find_line_bounding_boxes(line_segmentation: np.ndarray): """Given a line segmentation, find bounding boxes for connected-component regions corresponding to non-0 labels.""" def _find_line_bounding_boxes_in_channel(line_segmentation_channel: np.ndarray) -> np.ndarray: line_activation_image = cv2.di...
f0a41d5b569601db6eaa4ca061bddbfe6b6c88fa
3,633,595
def split_items(items, num_groups): """Splits a list of items into ``num_groups`` groups fairly (i.e. every item is assigned to exactly one group and no group is more than one item larger than any other).""" per_set = len(items) / float(num_groups) assert per_set >= 1, "At least one set will be empt...
0e5af3c5d3e394b328bef63b5287bd673fef0241
3,633,596
from typing import OrderedDict import json def generate_tool_flow(tool: GladierBaseTool, modifiers): """Generate a flow definition for a Gladier Tool based on the defined ``funcx_functions``. Accepts modifiers for funcx functions""" flow_moder = FlowModifiers([tool], modifiers, cls=tool) flow_states...
1ae457676ee2bfaa872f237036261bbfbdc644fb
3,633,597
def paralellLines(M,axis=1,labels=(), interactive=True, title="",show=True): """ Makes an optionally interactive paralell Lines plot. M: Matrix to visualise. axis: Axis of data values to plot. Needs to be either 1 or 0. Defaults to 1. labels: Labels of the axes to plot. inte...
a3ff1f1faa0e1704df24aac0024330458b037027
3,633,598
import types import pandas def hpat_pandas_series_dropna(self, axis=0, inplace=False): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.dropna Limitations ----------- - Parameter ``inplace`` is currently unsupported b...
9389f3cb90d22435133f04b3c48f761c65eceee3
3,633,599