content
stringlengths
22
815k
id
int64
0
4.91M
def truncate_patch_version(version): """Return just the major and minor versions from `version`.""" split_version = version.split(".") return "{}.{}".format(split_version[0], split_version[1])
5,293,000
def CGz(Omega, k, l, m, f, N2, w=0): """ Vertical Group Speed (includes vertical flow but is 0 by default) """ K2 = k**2 + l**2 + m**2 return (-1*(k**2 + l**2) * m * (N2 - f**2)) / (K2**2 * Omega)
5,293,001
def AUT_SetSearchArea(dCenterHz, dCenterV, dRangeHz, dRangeV, bEnabled=1): """ [GeoCom **p62**] Define the position and dimensions and activates the PowerSearch window. :returns: [error, RC, parameters] * error=0 and RC=0 if the request is successful * error=1 if not :rtype: list """...
5,293,002
def generalized_advantage_estimate( rewards: Tensor, old_values: Tensor, new_values: Tensor, dones: Tensor, gamma: float = 0.99, gae_lambda: float = 0.95, dtype: str = "torch", ) -> Tuple[Tensor, Tensor]: """ Generalized advantage estimate of a trajectory: https://towardsdatascience....
5,293,003
async def is_lover(self, author, fetch=False, resp=None): """Checks if the user is Lover on my server.""" return await check_if_role(self, author, fetch, resp, config["LOVER_ROLE"])
5,293,004
def test_correct_strings( parse_tokens, assert_errors, default_options, code, ): """Ensures that correct strings are fine.""" file_tokens = parse_tokens(code) visitor = WrongStringConcatenationVisitor( default_options, file_tokens=file_tokens, ) visitor.run() assert_err...
5,293,005
def estimate_aps_onnx(onnx: str, X_c = None, X_d = None, data = None, C: Sequence = None, D: Sequence = None, L: Dict[int, Set] = None, S: int = 100, delta: float = 0.8, seed: int = None, types: Tuple[np.dtype, np.dtype] = (None, None), input_type: int = 1, input_names: Tuple...
5,293,006
def _get_membership(max_radius_a, radis_a, radius_b, len_a, u, epsilon) -> Tuple[np.ndarray, np.ndarray]: """ Calculates the membership and noise values based on pre-computed radius values :return: -[0] membership values for class "a" -[1] noise values for class "a" """ membership = np.zero...
5,293,007
def davis_sponge_h_timescale(X, Y): """Produce the sponge timescale file used by Davis et al. (2014).""" sponge_h_timescale = np.zeros(X.shape, dtype=np.float64) sponge_h_timescale[Y<480e3] = 1/(1.*30.*86400.) # six month relaxation time plt.figure() plt.pcolormesh(X,Y,sponge_h_timescale*86400.*30....
5,293,008
def get_key_value_list(lines): """ Split lines at the first space. :param lines: lines from trackhub file :return: [(name, value)] where name is before first space and value is after first space """ result = [] for line in lines: line = line.strip() if line: parts...
5,293,009
def handle_model_import(amoptd, results): """Handle any errors flagged up by importing models and set any options based on the type of models.""" error_msg = None if results.error: error_msg = "Error importing models: {}".format(results.error) elif results.homologs and not amoptd['homologs']: ...
5,293,010
def sendEmail_thru_mailjet_api(From, To, Cc, Bcc, Subject, text_body, html_body, attachments=[], caller_area={}): """ sendEmail_thru_mailjet_api """ _process_name = 'sendEmail_thru_mailjet_api' _process_entity = 'email' _process_action = 'send_email' _process_msgID = f'process:[{_process_nam...
5,293,011
def one_hot_encode(label, label_values): """ Convert a segmentation image label array to one-hot format by replacing each pixel value with a vector of length num_classes # Arguments label: The 2D array segmentation image label label_values # Returns A 2D array with t...
5,293,012
def nmea0183_readout_handler(): """ Reads all available NMEA0183 sentences through serial connection. """ ret = {} # Read lines from serial connection lines = conn.read_lines() if not lines: log.warn("No NMEA0183 sentences available") return ret # Parse NMEA sentences...
5,293,013
def main(): """Run an experiment in the cloud.""" logs.initialize() parser = argparse.ArgumentParser( description='Begin an experiment that evaluates fuzzers on one or ' 'more benchmarks.') all_benchmarks = benchmark_utils.get_all_benchmarks() all_fuzzers = fuzzer_utils.get_fuzzer_...
5,293,014
def write_scores(path, approach_name, project, scores): """writes the scores to a csv file""" if not path.endswith('/') and len(path)>0: path += '/' file_name = path+approach_name+'.csv' values = [] values.append(project) for score_value in scores.values(): values.append(score_va...
5,293,015
def test_generate_lockfile_without_python_backend() -> None: """Regression test for https://github.com/pantsbuild/pants/issues/14876.""" run_pants( [ "--backend-packages=pants.backend.experimental.cc.lint.clangformat", "--clang-format-lockfile=cf.lock", "generate-lock...
5,293,016
def summarize_results(result,task): """ creates a summary of the result as dict """ summary={ #'Csc':data['pairwise_contact_matrix'], #'Cpop':data['population_contact_matrix'], #'Xmean':data['prior_shape_model'], 'n':result.n, 'd':resu...
5,293,017
def omw_stats(): """ statistics about wordnet as a big graph """ ### get language selected_lang = int(_get_cookie('selected_lang', 1)) ### get hypernym graph hypernym_dict=fetch_graph() G = nx.DiGraph(hypernym_dict, name='OMW') info = nx.info(G).splitlines() cycles = list(...
5,293,018
def get_data_field(thing_description, data_field_list): """Get the field specified by 'data_field_list' from each thing description Args: data_field_list(list): list of str that specified the hierarchical field names For example, if the parameter value is ['foo', 'bar', 'foobar'], then this...
5,293,019
def get_anchor_labels(anchors, coords, config): """ Generates the anchor labels for tranining the PPN. Returns y_conf, y_reg. anchors The list of anchor coordinates generated from get_anchors(). coords The list of ground truth point coordinates. config The configuration...
5,293,020
def cliview_conf_mos(cookie, in_additional_methods, in_commit, in_configs, in_hierarchical=YesOrNo.FALSE): """ Auto-generated UCSC XML API Method. """ method = ExternalMethod("CliviewConfMos") method.cookie = cookie method.in_additional_methods = in_additional_methods method.in_commit = in_commit ...
5,293,021
def limpieza_texto(texto, lista_palabras=[], lista_expresiones=[], ubicacion_archivo=None, n_min=0, quitar_numeros=True, quitar_acentos=False, tokenizador=None, momento_stopwords='ambos'): """Limpieza completa de texto. Esta función hace una limpieza exhaustiva del texto de ent...
5,293,022
def get_speed_formatted_str(speed): """ Returns the speed with always two whole numbers and two decimal value. Example: 03.45 Args: speed (float): The actual speed of the car Returns: str: The text format of the speed """ speed_str = "{:0.2f}".format(round(speed, 2)) return s...
5,293,023
def _from_string_with_informative_exceptions(env: jinja2.Environment, text: str) -> jinja2.Template: """ Parse the jinja2 template raising more informative exceptions if there are any. :param env: global jinja2 environment :param text: text of the template :return: parsed template """ synta...
5,293,024
def _make_trace_requests(parity_hosts, blocks): """ Make requests to get trace by the same parameters as in _make_requests """ def request(block_number): return { "jsonrpc": "2.0", "id": "trace_{}".format(block_number), "method": "trace_block", "pa...
5,293,025
def _pool_add(tasks, newtask): """ Add a new task to a pool, then drain any finished tasks at the start of the pool. :param tasks: a list contiaining either lists or tuples, the last element of which is a task submitted to the pool. Altered. :param newtask: a list or tuple to add to the po...
5,293,026
def ccw(A, B, C): """ Check if a point C is counter-clockwise to AB. """ return (C[1] - A[1])*(B[0]-A[0]) > (B[1]-A[1])*(C[0]-A[0])
5,293,027
def stack_remove(name: str): """Removes a stack. Due to limitations of the Docker SDK this calls the actual Docker CLI.""" proc = call(["docker", "stack", "rm", name]) if proc.returncode is not 0: logging.error("`docker stack remove` exited with non-zero exit code.") return False return ...
5,293,028
def evaluate(model, loss_func, dl): """ The function to evaluate the trained model with test set and to calculate test accuracy and loss :param model: Trained model checkpoint file :param loss_func: Cross entropy loss :param dl: Test dataset :return: Function return after calculating the total T...
5,293,029
def inverted_dummy_template_operations(wires): """The expected inverted operations for the dummy template.""" ops = [] for wire in reversed(wires): ops.append(qml.RY(1, wires=[wire])) ops.append(qml.RX(-1, wires=[wire])) return ops
5,293,030
def AsQuotedString(input_string): """Convert |input_string| into a quoted string.""" subs = [ ('\n', '\\n'), ('\t', '\\t'), ("'", "\\'") ] # Go through each substitution and replace any occurrences. output_string = input_string for before, after in subs: output_string = output_string....
5,293,031
def certificate_chain_from_printcert(printcert: str) -> List[Certificate]: """ This function parses the output of 'keytool -printcert' and creates a list of Certificate objects. The input to this function is the output of keytool_printcert :param printcert: the string output of 'keytool -printcert...
5,293,032
async def ws_connection(): """Connection with client. """ LOGGER.debug('A client connected') await websocket.accept() while True: data = await websocket.receive() LOGGER.debug('Recive data from client: %s', data)
5,293,033
def square(x: array, /) -> array: """ Squares (``x_i * x_i``) each element ``x_i`` of the input array ``x``. Parameters ---------- x: array input array. Should have a numeric data type. Returns ------- out: array an array containing the evaluated result for each element...
5,293,034
def make_scatter_plot(dataframe, input_feature, target, slopes=[], biases=[], model_names=[]): """ Creates a scatter plot of input_feature vs target along with the models. Args: dataframe: the dataframe to visualize input_feature: the input feature to be used for the x-axis targ...
5,293,035
def accumulating_product_acc(items): """Calculate the accumulating product of a list. Uses itertools.accumulate. Arguments: items {[list]} -- List of numbers. Returns: [list] -- List of accumulating products. """ return list(accumulate(items, func=mul))
5,293,036
def test_create_issue_from_repo_fork( mocker: MockerFixture, domain_gh_conn_settings: List[cs.GhConnectionSettings], mock_github3_login: MockerFixture, domain_issue: i.Issue, ) -> None: """It gives a message error telling it is a fork.""" exception_mock = mocker.Mock() exception_mock.json.re...
5,293,037
def check_cardinality(df, cat_cols, threshold=8): """ Check categorical cardinality Checks the cardinality of categorical features of a given dataset. Returns two dictionaries, one for features with low cardinality and another for features with high cardinality. The low/high cardinality criteria ca...
5,293,038
def _treelist(root, child, exclude, include): """ Recursive function that does the actual work of `treelist`. """ src_dir = root if child: src_dir = path.join(src_dir, child) files = [] for filename in os.listdir(src_dir): part = filename if child: ...
5,293,039
def tocp2k(fhandle, yaml): """ Generate a CP2K input file based on JSON (or YAML) file """ if yaml: from ruamel.yaml import YAML yaml = YAML() tree = yaml.load(fhandle) else: tree = json.load(fhandle) cp2k_generator = CP2KInputGenerator() for line in cp2...
5,293,040
def loadBalance(obj, src_node_id, dst_node_ids, sealed_segment_ids, timeout): """Do load balancing operation from source query node to destination query node.""" res = obj.loadBalance(src_node_id, dst_node_ids, sealed_segment_ids, timeout) click.echo(res)
5,293,041
def draw_grid(data, img_width, img_height, tile_size): """Draw a white grid on an original image labelled version, depending on its tile splitting, *i.e.* draw vertical and horizontal lines each `tile_size` pixels. Parameters ---------- data : numpy.array Labelled version of an image ...
5,293,042
def get_application_serializer(instance, **kwargs): """ Returns an instantiated serializer based on the instance class type. Custom serializers can be defined per application type. This function will return the one that is set else it will return the default one. :param instance: The instance where...
5,293,043
def create_snapshot(_user_id): """Creates a new FAQ snapshot. @param _user_id: author's identifier @return: 201: a new_uuid as a flask/response object \ with application/json mimetype. @raise 400: misunderstood request """ # Store new snapshot id = snapshot_service.create_snapshot(_user_...
5,293,044
def flow_duration(ds): """Compute the flow duration for a given dataset""" # NOTE: This exists in prms_objfcn.py # See http://pubs.usgs.gov/sir/2008/5126/section3.html # for the approach used to compute the flow duration # We only want valid values, sort the values in descending order ...
5,293,045
def build_index(): """ Builds the substr index. :return: None """ global sequence, mer_index mer_index = Index(sequence, 30)
5,293,046
def GetImmediateSupertypes(n, layers='core'): """Get this type's immediate supertypes, i.e. that we are subClassOf.""" if n==None: return None sups = GetTargets( Unit.GetUnit("rdfs:subClassOf", True), n, layers=layers) if (n.isDataType() or n.id == "DataType"): sups += GetTargets( Unit.G...
5,293,047
def add_type(instance): """ Adds a new type matcher instance to the supported types. Args: instance: Type inherited instance. Returns: None """ if not isinstance(instance, Type): raise TypeError('instance must inherit from filetype.types.Type') types.insert(0, inst...
5,293,048
def test_atomic_token_max_length_1_nistxml_sv_iv_atomic_token_max_length_2_1(mode, save_output, output_format): """ Type atomic/token is restricted by facet maxLength with value 919. """ assert_bindings( schema="nistData/atomic/token/Schema+Instance/NISTSchema-SV-IV-atomic-token-maxLength-2.xsd"...
5,293,049
def get_engine_sqlite(path) -> Engine: """Get a SQLite on-disk database engine.""" return create_engine(f"sqlite+pysqlite:///{path}", echo=True, future=True)
5,293,050
def view_file(parent, title, filename, encoding, modal=True, wrap='word', _utest=False): """Create text viewer for text in filename. Return error message if file cannot be read. Otherwise calls view_text with contents of the file. """ try: with open(filename, 'r', enc...
5,293,051
def transform_poses_to_base(config, poses): """ Transform the poses to the base frame with settings specified in the config :param config: :param poses: :return: """ ## initialize base to cam transformation tf_t_BC = Vector3(config['base_to_cam_pose']['translation']['x'], config['base_to...
5,293,052
def create_occurrence(create_reservation): """Return a callable which lets you create reservation occurrences.""" def _create_occurrence(start_dt=None, end_dt=None, room=None): params = {} if start_dt is not None: params['start_dt'] = start_dt if end_dt is not None: ...
5,293,053
def register_corrector(cls=None, *, name=None): """A decorator for registering corrector classes.""" def _register(cls): if name is None: local_name = cls.__name__ else: local_name = name if local_name in _CORRECTORS: raise ValueError(f'Already regist...
5,293,054
def general_net_center(feat_model, identity_model, center_model, img_shape): """Returns a keras Model for training with classification, metric learning and center losses Args: feat_model: keras Model for feature extracting identity_model: keras Model for classification img_shape: t...
5,293,055
def make_cache_key(path=None, key_prefix="view/%s"): """ This function mostly emulates Flask-Caching's `make_cache_key` function so we can delete cached api responses. Over time this function may be replaced with a cleaner custom cache implementation. :param path: :param key_prefix: :return: ...
5,293,056
def orient_tract_kmeans(bundle): """Ensure the startpoints to be always higher than the endpoints. """ points = compute_endpoints(bundle) kmeans = KMeans(n_clusters=2, random_state=0).fit(points) class0_up = (kmeans.cluster_centers_[0][2] > kmeans.cluster_centers_[1][2]) #constraint on the z axis oriented_bundle ...
5,293,057
def handle_monthly_new(src_root: str, j: Dict[str, Any], month_range: int = 12) -> None: """Shows # of new housenumbers / month.""" ret = [] prev_count = 0 prev_month = "" for month_offset in range(month_range, -1, -1): # datetime.timedelta does not support months month_delta = datet...
5,293,058
def create_flagellum(idx, phase, phase_speed, translation, rotation, flag_radius, longitude_grid, azimuth_grid): """ :param phase_speed: integer; will be multiplied by default frequency :param longitude_grid: how man :param azimuth_grid: number of grid points (integer) :return: ...
5,293,059
def _pretty_print_literal(literal: Literal): """Render a literal.""" return render_literal_value(literal.value)
5,293,060
def make_point(x, y, as_geom=False): """ Make a GeoJSON point. if as_geom, then return a shapely geometry instead. """ geojson = {"type": "Point", "coordinates": [x, y]} return geometry.shape(geojson) if as_geom else geojson
5,293,061
def test_validate_md_pt_sc(session, desc, valid, reg_type, message_content): """Assert that new MD, PT, SC registration type validation works as expected.""" # setup json_data = copy.deepcopy(FINANCING) json_data['type'] = reg_type del json_data['trustIndenture'] if desc == DESC_MISSING_GC: ...
5,293,062
def two_week_working_hour(dept_info): """ convert workingHour into two week's everyday slot """ today = datetime.datetime.today() weekday = today.weekday() workingHour = json.loads(dept_info.workingHour) schedule = [] for i in range(14): if workingHour[(weekday+i+1)%7][0]: ...
5,293,063
def bot_has_role_permissions(perm1: hikari.Permissions, *perms: hikari.Permissions) -> Check: """ Prevents the command from being used if the bot is missing any of the required role permissions. Args: perm1 (:obj:`hikari.Permissions`): Permission to check for. *perms (:obj:`hikari.Permi...
5,293,064
def save_credential(credential): """ Function to save user ---------- user """ credential.save_credential()
5,293,065
def multi_year(ctx, years): """ Map means for a given year """ ctx.invoke(multi_yr_means_cmd, years=years)
5,293,066
def make_data(T, fs): """ Function to make data args: T: time fs: sampling rate return: t: number of samples x: data """ nsamples = int(T * fs) t = np.linspace(0, T, nsamples, endpoint=False) a = 0.025 f0 = 550.0 x = 0.07 * np.sin(2 * np.pi * 1.2 *...
5,293,067
def parse_veh_comp(xmldoc): """parses the vehicle composition from the VISSIM data :param xmldoc: input VISSIM xml :type xmldoc: xml.dom.minidom.Document :return: relevant VISSIM vehicleComposition data :rtype: dict of list of dict """ veh_cmp_d = dict() # local vehicle co...
5,293,068
def obscore_loader_gama_sdss(fname): """ This is a specutils loader which adds obscore information to a SDSS spectra in the GAMA survey """ spec = Spectrum1D.read(fname, format="SDSS-I/II spSpec") spec.meta["obscore"] = {} obscore = spec.meta["obscore"] hdr = spec.meta["header"] ob...
5,293,069
def get_conn(config: NamedTuple) -> connector.MySQLConnection: """ Accept parsed configuration data and create mysql connector :param config: :return: """ return connector.connect( host=config.db.host, database=config.db.database, user=config.db.user, passwd=config.db.pa...
5,293,070
def test_async_test(testdir): """`override` decorator works for async tests.""" testdir.makepyfile( """ import pytest from settings import config pytestmark = pytest.mark.asyncio @config.override(INTEGER=123) async def test_override_per_test(): assert config.INTEGER == 123 ...
5,293,071
def uniq_table_id(): """Return a unique table ID based on the current time in ms. Returns: str: in format `U<timestamp_ns>` """ return f'U{time.time_ns()}'
5,293,072
def real_basins(func, interval, npoints): """Plot func over the real interval and the basins of attraction with npoints resolution""" x = sp.linspace(interval[0], interval[1], npoints) y = sp.array(map(func, x)) #import available colors in colors = pyplot.cm.colors.cnames.keys() #remove b...
5,293,073
def _get_real_env_hack_hack_hack(): """ Get the real, currently-being-configured libtbx.env environment. This is not libtbx.env, because although libtbx.env_config.environment.cold_start does: self.pickle() libtbx.env = self the first time there is an "import libtbx.load_env" this e...
5,293,074
def wms_query_eq(expected, actual): """ >>> wms_query_eq('bAR=baz&foo=bizz&bbOX=0,0,100000,100000', 'foO=bizz&BBOx=-.0001,0.01,99999.99,100000.09&bar=baz') True >>> wms_query_eq('bAR=baz&foo=bizz&bbOX=0,0,100000,100000', 'foO=bizz&BBOx=-.0001,0.01,99999.99,100000.11&bar=baz') False >>> wms_query...
5,293,075
def get_server_url_for_path(p): """ gets the url corresponding to a given file or directory path p : path to convert into a url returns the url path for the filepath p """ load_environment() fname = os.path.basename(p) rel_path = os.path.relpath(p, os.environ['NOTEBOOK_HOME']) url ...
5,293,076
def _replace_batch_norm_with_bias_add( g, # type: graph.Graph match_info, # type: Dict[str, node.Node] offset # type: np.ndarray ): # type: (...) -> None """ Replace the fused batch normalization node in the graph with a BiasAdd node that applies the offset from the original normalizat...
5,293,077
def reverseFillUp(layer: list, qubits=None): """ Fill up till the list is of equal size """ if qubits is None: qubits = range(len(layer)) lens = [len(layer[qubit]) for qubit in qubits] for qubit in qubits: if max(lens) - len(layer[qubit]) != 0: N = [None] * (max(len...
5,293,078
def increase_serialnumber(): """Increments version of neighbour-list by 1""" global serial_number serial_number += 1
5,293,079
async def backup(ctx, server: str, *backup_name: str): """Creates a backup of the world file for the specified server. This is a filesystem backup, and typically cannot be restored from in-game. """ pass
5,293,080
def test_list_g_year_max_length_3_nistxml_sv_iv_list_g_year_max_length_4_5(mode, save_output, output_format): """ Type list/gYear is restricted by facet maxLength with value 8. """ assert_bindings( schema="nistData/list/gYear/Schema+Instance/NISTSchema-SV-IV-list-gYear-maxLength-4.xsd", ...
5,293,081
def parse_args(): """ parse command line arguments :return dict: dictionary of parameters """ argparser = argparse.ArgumentParser() argparser.add_argument('--config_file', type=str, default=os.path.join('./configs/', 'turtlebot_navigate.yaml')) argparser.add_argument('--num_iterations', t...
5,293,082
def split_dataframe_by_position(df, splits): """ Takes a dataframe and an integer of the number of splits to create. Returns a list of dataframes. """ dataframes = [] index_to_split = len(df) // splits #print(index_to_split) start = 0 end = index_to_split for split in range(split...
5,293,083
def address_in_network(ip: str, net: str) -> bool: """Is an address in a network """ # If IP and net mask are not compatible, return False if is_ipv6(ip) != is_ipv6(net): return False # Convert ips to int i_ip = ip_to_bits(ip) total_bits = 32 if not is_ipv6(ip) else 128 netpart...
5,293,084
def get_service_url(host, port, path=constants.PATH): """ Construct a service URL from host, port and path :param host: (string) the service host (aka server) IP :param port: (int) port on which to connect to the service :param path: (string) API endpoint (default to /mnist/classify/) :return: (...
5,293,085
def eigcov(data): """ Return eigen values and vectors of covariance matrix """ eigenValues, eigenVectors = np.linalg.eig(np.cov(data)) idx = eigenValues.argsort()[::-1] eigenValues = eigenValues[idx] eigenVectors = eigenVectors[:,idx] return eigenValues, eigenVectors
5,293,086
def index_relation_types(dataset): """Classify relations into 1-N, M-1, 1-1, M-N. According to Bordes et al. "Translating embeddings for modeling multi-relational data.", NIPS13. Adds index `relation_types` with list that maps relation index to ("1-N", "M-1", "1-1", "M-N"). """ if "relati...
5,293,087
def init_celery(celery, app): """ initial celery object wraps the task execution in an application context """ celery.config_from_object(celeryconfig) class ContextTask(celery.Task): def __call__(self, *args, **kwds): with app.app_context(): return self.run(*args...
5,293,088
def _validate(submission): """ Validates submission against a set of rules. """ title = submission.title.lower() if ShowerThought.objects.filter(post_id=submission.id).exists(): # sometimes posts are chosen for two days because they fall right on the cusp logging.warning("Post has al...
5,293,089
def display_codes(codes, indv_stem_plots=True, input_and_recon=None, data_pt_per_fig=None, plot_title=""): """ Visualizes tranform codes Parameters ---------- codes : ndarray(float32, size=(b, s) OR size=(b, s, sh, sw) The codes for a batch of size b. b shouldn't be too large unless y...
5,293,090
async def info(ctx): """Information about this bot""" servercount = len(bot.guilds) emb = (discord.Embed(title='{}'.format(bot.user), description= 'A bot made for fun by Kuuhaku#4503 \nCoded in discord.py rewrite' '\nThis bot is in: {} servers'.format(servercount), colour=0xEC40DF)) await ctx.se...
5,293,091
def java_tokenize(snippets, labels=None): """ This function parses a list of java code snippets into a list of lists of tokens. Args: snippets: Java code snippets in a list of strings. labels: (Default value = None) a list of labels for code snippets Returns: X: a list of lists of...
5,293,092
def patch_load_cfg(monkeypatch): """ A fixture that returns a function which will patch 'utils.load_cfg_file' when called in a test The caller can specify the dict that should be returned when 'load_cfg_file' is called against these two paths: * "templatesTEST/_cfg.yml" * "templatesTEST/service...
5,293,093
def test_sigma_dut_dpp_qr_resp_5(dev, apdev): """sigma_dut DPP/QR responder (conf index 5)""" run_sigma_dut_dpp_qr_resp(dev, apdev, 5)
5,293,094
def journal_write(session, k, v): """Write a new journal entry. This is expected to be used in the precommit, so is a part of a larger transaction. It doesn't commit itself. """ entry = VppEtcdJournal(k=k, v=v) session.add(entry) session.flush()
5,293,095
async def main(): """You will need to add your api key!""" destiny = pydest.Pydest('api-key') activity1 = await destiny.decode_hash(60002467, 'DestinyActivityDefinition') await destiny.update_manifest() activity2 = await destiny.decode_hash(80726883, 'DestinyActivityDefinition') print("Activit...
5,293,096
def _get_instance_shape( instance_dict: Union[TaggedDict, Dict[str, Any]] ) -> Union[List[int], None]: """Get the shape of an ASDF instance from its tagged dict form. Parameters ---------- instance_dict The yaml node to evaluate. Returns ------- List A numpy-style shape...
5,293,097
async def test_generate_startlist_for_event_no_contestants_differ_from_races( client: _TestClient, mocker: MockFixture, token: MockFixture, event: dict, format_configuration: dict, raceclasses: List[dict], raceplan_interval_start: dict, contestants: List[dict], request_body: dict, ) ...
5,293,098
def decode_cobs(in_bytes): """Decode a string using Consistent Overhead Byte Stuffing (COBS). Input should be a byte string that has been COBS encoded. Output is also a byte string. A cobs.DecodeError exception will be raised if the encoded data is invalid.""" if isinstance(in_bytes, s...
5,293,099