content
stringlengths
22
815k
id
int64
0
4.91M
def histogram_log( *, x_data: Sequence, bins: Optional[Union[Sequence, int]] = None, bin_width_initial: Optional[float] = None, bin_width_factor: Optional[float] = None, x_min: Optional[float] = None, x_max: Optional[float] = None, density: bool = True, x_align: Optional[str] = None,...
5,289,600
def calculate_TimeOfDay_field(sublayer_object, time_field, time_of_day): """Set the TimeOfDay field to a specific time of day""" expression = '"' + str(time_of_day) + '"' # Unclear why a DATE field requires a string expression, but it does. arcpy.management.CalculateField(sublayer_object, time_field, ex...
5,289,601
def test_is_union_instance(instance): """ Тест метода _is_union_instance() который возвращает True если значение имеет тип одного из типов кортежа Union, и False если нет. """ annotation = Optional[int] value = 1 assert instance._is_union_instance(value, annotation) value = None ...
5,289,602
def get_variants_from_log_trace_idx(log, parameters=None): """ Gets a dictionary whose key is the variant and as value there is the list of traces indexes that share the variant Parameters ---------- log Log parameters Parameters of the algorithm, including: Para...
5,289,603
async def test_partitioning_asynchronous(): """ensure that tensor partitioning does not interfere with asynchronous code""" tensors = [torch.randn(2048, 2048), torch.randn(1024, 4096), torch.randn(4096, 1024), torch.randn(30_000, 1024)] peer_fractions = [0.4, 0.3, 0.2, 0.1] partition = TensorPartContai...
5,289,604
def test_normalize_arg_error(): """ markup.decoder.text.TextDecoder().normalize() checks arguments """ inst = _decoder.TextDecoder('utf-8') with raises(TypeError): inst.normalize()
5,289,605
def mark_entry_as_read_groups(request_ctx, group_id, topic_id, entry_id, forced_read_state=None, **request_kwargs): """ Mark a discussion entry as read. No request fields are necessary. On success, the response will be 204 No Content with an empty body. :param request_ctx: The request...
5,289,606
def has_capability(capability, jobboard_job=None): """ Check if the local machine has the specified capability :param str capability: The capability to evaluate :param obj jobboard_job: TaskFlow jobboard job :return bool capable: True if it has the capability, False if not """ # If the job i...
5,289,607
def test_verify( signing_key_hex: str, message_digest_hex: str, signature_hex: str, module: t.Any, ): """Verify known good signatures.""" signing_key_bytes = bytes.fromhex(signing_key_hex) signing_key = module.make_signing_key(signing_key_bytes) verifying_key = module.derive_verifying_ke...
5,289,608
def tceil(tensor: T.Tensor) -> T.Tensor: """ Return a tensor with ceilinged elements. Args: tensor: A tensor. Returns: tensor: A tensor rounded up to the next integer (still floating point). """ return numpy.ceil(tensor)
5,289,609
def CommitPositionFromBuildProperty(value): """Extracts the chromium commit position from a builders got_revision_cp property.""" # Match a commit position from a build properties commit string like # "refs/heads/master@{#819458}" test_arg_commit_position_re = r'\{#(?P<position>\d+)\}' match = re.search(t...
5,289,610
def test_ap_ft(dev, apdev): """WPA2-PSK-FT AP""" ssid = "test-ft" passphrase="12345678" params = ft_params1(ssid=ssid, passphrase=passphrase) hapd0 = hostapd.add_ap(apdev[0], params) params = ft_params2(ssid=ssid, passphrase=passphrase) hapd1 = hostapd.add_ap(apdev[1], params) run_roam...
5,289,611
def dqn_mlp_network(hidden_sizes: List[int], num_actions: int) -> NetworkFn: """DQN MLP """ def net_fn(inputs): network = hk.Sequential([ dqn_mlp_torso(hidden_sizes), dqn_mlp_value_head(num_actions) ]) # return QNetworkOutputs(q_values=network...
5,289,612
def create_item( granule_href: str, read_href_modifier: Optional[ReadHrefModifier] = None, archive_format: Format = Format.SAFE, ) -> pystac.Item: """Create a STC Item from a Sentinel-1 GRD scene. Args: granule_href (str): The HREF to the granule. This is expected to be a path t...
5,289,613
def save_sino_as_img(fname, proj, cmap='gray', log=None): """ proj: [nangles, H, W] """ idx1 = proj.shape[0]//4 idxs = [0, idx1, idx1*2, idx1*3] for cnt, i in enumerate(idxs): try: file_name = f"{fname[:-4]}_{str(cnt)}.png" if cmap == 'gray' and cnt != 1: ...
5,289,614
def batch_gather(values, indices): """Returns batched `tf.gather` for every row in the input.""" unpacked = zip(tf.unstack(values), tf.unstack(indices)) result = [tf.gather(value, index) for value, index in unpacked] return tf.stack(result)
5,289,615
def datatype_from_column_expression(c): """Determine a datatype from a column or column expression""" datatype = "unknown" try: if hasattr(c, "type") and c.type: # Check supported column types if isinstance(c.type, String): datatype = "str" elif is...
5,289,616
def get_and_insert_coordinates(): """ This function get coordinate from API and insert them in db. """ record = query_empty_coordinates() for r in record: coordinates = (get_coordinates(localisation_formatting(r[0]))) print(coordinates) if coordinates[0] is not None and coord...
5,289,617
def context_top_elems(cur_elem, dict_result): """ Given a list of elements, return the object that is in the dict at that point dict_result = {'root': {'list1': ['dict1': {key: ""} ] } cur_elem = ['root', 'list1', 'dict1'] Should return a reference to a dict that is dict_result['dict1'] """ ...
5,289,618
def example_data(): """Example data.""" return { 'id': 'eng', 'title': {'en': 'English', 'da': 'Engelsk'}, 'description': {'en': 'Text', 'da': 'Tekst'}, 'icon': 'file-o', 'props': { 'datacite_type': 'Text', }, }
5,289,619
def rand_q() -> ElementModQ: """ Generate random number between 0 and Q. :return: Random value between 0 and Q """ return ElementModQ(randbelow(get_small_prime()))
5,289,620
def _process_image_files(name, directory, all_records, num_shards): """Process and save list of images as TFRecord of Example protos. Args: name: string, unique identifier specifying the data set directory: string; the path of all datas all_records: list of string tuples; the first of each tuple is the...
5,289,621
def update_gloss(request, glossid): """View to update a gloss model from the jeditable jquery form We are sent one field and value at a time, return the new value once we've updated it.""" if not request.user.has_perm('dictionary.change_gloss'): return HttpResponseForbidden("Gloss Update Not Al...
5,289,622
def PEditFD (inUV, outUV, err): """ Frequency-domain editing of UV data - produces FG table Editing is done independently for each visibility channel. First clipping is done on correlator and Vpol amplitudes. Following this, an average and RMS is determined for each channel in each timeAvg per...
5,289,623
def setup_scanner(hass, config, see, discovery_info=None): """Setup an endpoint for the GPSLogger application.""" hass.http.register_view(GPSLoggerView(see)) return True
5,289,624
def test_trans_3d(api_all): """ Test that 3D transformations behaves as expected """ api_entry = f"/{api_all}/trans/EPSG:4258/EPSG:25832/56.0,12.0,30.0" expected = { "v1": 687071.4391094431, "v2": 6210141.326748009, "v3": 30.0, "v4": None, } _assert_coordinate...
5,289,625
def calculate_antenna_visibility_limits(target,station,referenceephemtime,plusminusdays=1., elevation_limit_deg=15., interpsteps=100, alwaysup_fmt='nan', timeformat='ephem', LST_PT=False, verbose=False): """ Calculate the previous and next time within e.g. 24hrs when a target reaches a specified elevation ...
5,289,626
def traverse_tree(t, parent_name=""): """ Returns the list of all names in tree. """ if parent_name: full_node_name = parent_name + "/" + t.name else: full_node_name = t.name if (t.children is None): result = [full_node_name] else: result = [full_node_name ...
5,289,627
def test_wvalue_exceptions(): """Test wvalue function exceptions.""" AI(peng.wvalue, "wave", "a", 5) wobj = std_wobj(dep_name="wobj") exmsg = "Argument `indep_var` is not in the independent variable vector range" AE(peng.wvalue, ValueError, exmsg, wobj, 0) AE(peng.wvalue, ValueError, exmsg, wobj...
5,289,628
def create_permissions(): """ Create the can_carry_over and can_admin permissions. """ from django.contrib.auth.models import Permission from django.contrib.contenttypes.models import ContentType from pbs.prescription.models import Prescription ct = ContentType.objects.get_for_model(Prescri...
5,289,629
def walkModuleNames(moduleName): """ Iterates the names of each module inside of and including moduleName. This only recognizes modules with the .py extension.""" ignoreNames = ["project"] def iter(moduleName, modulePath, isDir): if isDir: names = os.listdir(module...
5,289,630
def s3_retrieve(key_path: str, study_object_id: str, raw_path:bool=False, number_retries=3) -> bytes: """ Takes an S3 file path (key_path), and a study ID. Takes an optional argument, raw_path, which defaults to false. When set to false the path is prepended to place the file in the appropriate study_id f...
5,289,631
def oddeven_merge_sort(length): """ "length" is the length of the list to be sorted. Returns a list of pairs of indices starting with 0 """ assert is_power_of_2(length) for each in oddeven_merge_sort_range(0, length - 1): yield each
5,289,632
def _get_latlon(grid, dbz_fname): """ Generates latitude and longitude arrays. Parameters ---------- grid : Grid Py-ART grid object. dbz_fname : str Reflectivity field name. Returns ------- longitude : ndarray Array of coordinates for all points. latitud...
5,289,633
def db(database): """Creates a new database session for a test. Scope: function You must use this fixture if your test connects to the database. The fixture will set a save point and rollback all changes performed during the test (this is much faster than recreating the entire database). """ ...
5,289,634
def pad_stride(x: np.ndarray, w_r_shape, stride_i) -> np.ndarray: """ :param x: (bs, ch_o, h_o, w_o) :param w_r_shape: (bs, ch_i, h_k, w_k) :param stride_i: (int, int) :return: """ bs, ch_o, h_o, w_o = x.shape _, _, h_k, w_k = w_r_shape h_st, w_st = stride_i if h_st == 1 and w_...
5,289,635
def slack_pipeline(importer, trainer, evaluator, formatter, alerter): """Train and evaluate a model and post the test accuracy to slack.""" X_train, X_test, y_train, y_test = importer() model = trainer(X_train=X_train, y_train=y_train) test_acc = evaluator(X_test=X_test, y_test=y_test, model=model) ...
5,289,636
def attribute_fetcher(context, user_id): """ Read a user from the Dashboard private userdb and return an update dict to let the Attribute Manager update the use in the central eduid user database. :param context: Plugin context, see plugin_init above. :param user_id: Unique identifier :typ...
5,289,637
def generate_cookie(username, address, environment_ids=None, methods=None, eternal=False, settings_path=None): """ Generate and return a cookie with the given information. username should be the username of the cookie user. environment_ids should be an iterable of environment ID rest...
5,289,638
def zip_lists(xs: Optional[ListNode], ys: Optional[ListNode]) -> Optional[ListNode]: """ Return the head of a linked list that represents the pair-wise combination of the given linked lists. If one list runs out of ListNodes, append the remainder of the other list. >>> xs = ListNode(1...
5,289,639
def extract_pdeep_mod(mod_pep, mod_ident='bracket', mod_trans=True): """ input: '_C[Carbamidomethyl (C)]DM[Oxidation (M)]EDER_' output: 'CDMEDER', '1,Carbamidomethyl[C];3,Oxidation[M];' """ stripped_pep, mod = rapid_kit.split_mod(modpep=mod_pep, mod_ident=mod_ident) if mod_trans: mod = t...
5,289,640
def create_conversion_dict(): """ -> parse the variable_description.xml file and return a dictionnary for the discretization procedure: variable_name : Possible_Values : Binary_Values -> use for convert posible values of a variable into binary values -> return a dictionnary """ description_file_name = "PARAMET...
5,289,641
def water_toluene_material_stream(): """ Create a homogeneous material_stream model """ pp_ = pp_water() pp_.addPropertyPackage(pp_toluene()) class material_stream(MaterialStream): def __init__(self, name, description, pp=None): super().__init__(name, description, prope...
5,289,642
def GetPolyCoords(geometry,coord_type): """ ===================================================== getPolyCoords(geometry,coord_type) ===================================================== Returns Coordinates of Polygon using the Exterior of the Polygon. inputs: 1- geometry: ...
5,289,643
def db2local(save_file="/opt/lavector/components/json.mongo", collect='label_corpus', use_cache=True): """ 从MongoDB 获取数据,保存到save_file中, mongo结果, 模型准确率为:0.6782511210762332 :param save_file: :param collect: label_corpus 获取成分的词的标注 :return: """ # 配置client, 如果存在,并且使用cache,那么直接返回结果 if use_cach...
5,289,644
def delete_playlist(playlist_id): """ Deletes a Todo with id = id """ dao = MusicDao() error, is_deleted = dao.delete_playlist(playlist_id) return error, is_deleted
5,289,645
def test_find_all_templates_by_no_templates(app): """Test create account.""" with app.app_context(): with patch('os.listdir') as mock_list_of_files: mock_list_of_files.return_value = [] templates = TemplateService.find_all_templates() print(templates) asse...
5,289,646
def _gatk_base_recalibrator(broad_runner, dup_align_bam, ref_file, platform, dbsnp_file, intervals, data): """Step 1 of GATK recalibration process, producing table of covariates. For GATK 4 we use local multicore spark runs: https://github.com/broadinstitute/gatk/issues/2345 ...
5,289,647
def poa_horizontal_ratio(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth): """ Calculates the ratio of the beam components of the plane of array irradiance and the horizontal irradiance. Input all angles in degrees. Parameters ---------- surface_tilt : n...
5,289,648
def _breakend_orientation(strand1, strand2): """Convert BEDPE strand representation of breakpoints into VCF. | strand1 | strand2 | VCF | +----------+----------+--------------+ | + | - | t[p[ ]p]t | | + | + | t]p] t]p] | | - | - | [p[t [...
5,289,649
def test_unpickable_error_find_document(): """Check error messages for pickledb""" class UnpickableClass: i_am_not_pickable = None unpickable_doc = { "_id": 2, "a_pickable": 1, "b_unpickable": UnpickableClass(), "c_pickable": 3, } def make_pickable(uid): ...
5,289,650
def _parallel_blocks(out_image, band_list, ii, jj, y_offset, x_offset, nn_rows, nn_cols, left, top, cellY, ...
5,289,651
def addConfig(): """ 增加配置文件 :return: """ add_path = getLocalFile(FLAGS.add) to_path = getLocalFile(FLAGS.to) handleAddConfig(add_path, to_path)
5,289,652
def launch_tor_with_config(config, tor_cmd = 'tor', completion_percent = 100, init_msg_handler = None, timeout = DEFAULT_INIT_TIMEOUT, take_ownership = False, close_output = True): """ Initializes a tor process, like :func:`~stem.process.launch_tor`, but with a customized configuration. This writes a temporary to...
5,289,653
def test_medians(max_workers): """ Test TemporalStats medians """ test_stats = TemporalStats.all(RES_H5, DATASET, statistics='median', res_cls=WindResource, max_workers=max_workers) res_data = R...
5,289,654
def shell(command, input_text=None, stdin=PIPE, stdout=PIPE, stderr=PIPE): """ Creates and executes a new process using provided command. Notes: • if command's type is str then it will be executed using /bin/sh. • if input_text was provided then it will be used as input for shell command whic...
5,289,655
def agent(): """ Generate data for an AI to learn how to play solitaire """ data = [] for i in range(NB_GAMES): solitaire = Solitaire_Engine() samples = [] while not solitaire.is_over(): print("Game "+ str(i+1)+ " - Turn "+str(solitaire.time+1)) if le...
5,289,656
def val_net(net, dataloader): """Compute accuracy on validation set.""" net.eval() correct = 0.0 total = 0.0 with torch.no_grad(): for i, data in enumerate(dataloader): # Get the inputs, keeping batch size x, y = data # cuda() is...
5,289,657
def encode_game_log(year, log, dataset_dir, discard_dir, pon_dir, kan_dir, kita_dir, riichi_dir, discard_count, pon_count, kan_count, kita_count, riichi_count): """ :param year: String :param log: Tenhou JSON game log object :param dataset_dir: Dataset directory ...
5,289,658
def update_existing_stock(vol,vendor,part,vehicle): """ Update existing document data by document ID :param document_id: :param data: :return: """ conn = sqlite3.connect(DATBASE_LOCATION) cur = conn.cursor() cur.execute('''UPDATE Stats SET stock = stock - (?...
5,289,659
def main(): """ This sample script will show how to work with the device configurations using NETCONF and RESTCONF """ # retrieve the device capabilities using RESTCONF print('Device Capabilities via RESTCONF: ') capabilities = netconf_restconf.restconf_get_capabilities(IOS_XE_HOST, IOS_XE_USER...
5,289,660
def _get_presence_coconstraints(object_spec): """ Get presence co-constraint info from the given object specification. This includes the groups and dependencies. :param object_spec: The object specification :return: A 2-tuple with (a) the group co-constraint mapping from group name to const...
5,289,661
def tableToCSV(input_table, csv_filepath, fld_to_remove_override=[], keep_fields=[]): """Returns the file path of a csv containing the attributes table of a shapefile or other table""" fld_list = arcpy.ListFields(input_table) fld_names = [str(fld.name) for fld in fld_list] # Either delete specified fie...
5,289,662
def delete_doc(id): """Deletes a single document from the current collection by its id.""" es_index = collections.current().es_index index_url = f'{ES_URL}/{es_index}' resp = requests.delete(f'{index_url}/{DOCUMENT_TYPE}/{id}') check_response(resp)
5,289,663
def sigmoid_derivative(x): """ Actual derivative: S'(x) = S(x)(1-S(x)) but the inputs have already gone through the sigmoid function. """ return x * (1 - x)
5,289,664
def _build_container_hosts(container_affinity, container_hosts, type_and_name, inventory, host_type, container_type, container_host_type, physical_host_type, config, is_metal, assignment): """Add in all of hte host associations into in...
5,289,665
def copy_logfile_to_gcs(logfile: str, output_dir: str): """Copies a logfile from local to gcs storage.""" try: with open(logfile, 'r') as log_reader: out_log = os.path.join(output_dir, constants.LOGFILE) with tf.io.gfile.GFile(out_log, 'w') as gcs_logfile: log = log_reader.read() gcs...
5,289,666
def get_lint_messages_by_level(raw_lint_feedback_str): """ Gets lists of lint messages grouped by message level (brief, main, extra). Each message in a list is for a particular error / warning type e.g. E501. A message might be consolidated (e.g. foo has prob; bar has prob etc) or be a composite m...
5,289,667
def merge_again(other, script): """ Merge the two DataFrames for other and script together again, but keeping distinct rows for the cumulated levenshtein distances for each category (other and script). Returns DataFrame. """ data = other.merge(script, how="left", on="line") data.rename(c...
5,289,668
def _get_roi_id(db, offset, shape, exp_name=None): """Get database ROI ID for the given ROI position within the main image5d. Args: db (:obj:`sqlite.ClrDB`): Database object. offset (List[int]): ROI offset in z,y,x. shape (List[int]): ROI shape in z,y,x. exp_name (str): Name...
5,289,669
def train_and_predict_rnn_nn(model, num_hiddens, init_gru_state, corpus_indices, vocab, device, num_epochs, num_steps, lr, clipping_theta, batch_size, prefixes, num_layers=1): """Train a RNN model and predict the next item in the sequence.""" loss ...
5,289,670
def sdf2xyz(sdf_string): """Convert a sdf string to a xyz string.""" atoms = get_ind_from_sdfline(sdf_string.split('\n')[3])[0] coord = [str(atoms)+('\n')] for i in range(4, 4+atoms): x = float(sdf_string.split('\n')[i].split()[0]) y = float(sdf_string.split('\n')[i].split()[1]) ...
5,289,671
def iso(fabric_width, fabric_height): """ Calculate robot iso speed :param fabric_width: float fabric width :param fabric_height: float fabric height :return: float quasi state robot speed, float transient state robot speed, float relevant speed """ # Import here for optimization import ...
5,289,672
def hikUpdateTool(): """ This method refreshes the HumanIK tool UI so that it fits the current HumanIK character. """ pass
5,289,673
def parse_utc_timestamp(timestamp): """ 解析服务器发回来的 UTC 时间戳 形如: 2017-07-28T08:28:47.776Z Return: - time datetime.datetime """ UTC_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" utcTime = datetime.datetime.strptime(timestamp, UTC_FORMAT) localTime = utcTime + datetime.timedelta(hours=8) ...
5,289,674
def remove_loclist(loclist): """ remove the previous set of Orbit-Count files """ for elem in loclist: try: os.remove(os.path.join(config['local.data'], elem[-1])) # the following is also logged by the watch process # logging.info('[%s] -- Deleted: %s', no...
5,289,675
def _parse_mapping_file(lines, strip_quotes=True, suppress_stripping=False): """Parser for map file that relates samples to metadata. Format: header line with fields optionally other comment lines starting with # tab-delimited fields Parameters ---------- lines : iterable o...
5,289,676
def laplacian_kernel(X, Y=None, gamma=None): """Compute the laplacian kernel between X and Y. The laplacian kernel is defined as:: K(x, y) = exp(-gamma ||x-y||_1) for each pair of rows x in X and y in Y. Read more in the :ref:`User Guide <laplacian_kernel>`. .. versionadded:: 0.17 Parame...
5,289,677
def subset_dict(d, selected_keys): """Given a dict {key: int} and a list of keys, return subset dict {key: int} for only key in keys. If a selected key is not in d, set its value to 0""" return {key: (0 if key not in d else d[key]) for key in selected_keys}
5,289,678
def transformer( string: str, model, generate_length: int = 30, leed_out_len: int = 1, temperature: float = 1.0, top_k: int = 100, burnin: int = 15, batch_size: int = 5, ): """ Use pretrained transformer models to generate a string given a prefix string. https://github.com/ny...
5,289,679
def init(filename): """Create an empty CHANGELOG file.""" # Check if the file already exists if os.path.isfile(filename): click.echo(f'The CHANGELOG file already exists!') raise click.Abort # Ask the user for the initial version of their project first_v_num: str = questionary.text( ...
5,289,680
def exception_handler(function: Callable) -> Callable: """ Wrapping function in try-except expression Args: function (Callable): Function, you want to wrap Returns: Callable: Function wrapper """ def try_except_wrapper(*args: Any, **kwargs: Any) -> Optional[Any]: """ ...
5,289,681
def test_parser_events(hsd_input, expected_events): """Test valid parser events""" testhandler = _TestEventHandler() parser = hsd.HsdParser(eventhandler=testhandler) hsdfile = io.StringIO(hsd_input) parser.parse(hsdfile) assert testhandler.events == expected_events
5,289,682
def save_state(push, commit, agent_name, delta): """ Saves dialogflow.com agent's state (Intents/Entities) as json files """ return save_state_internal(push, commit, agent_name, delta=delta)
5,289,683
def ccColor2(cc): """ this function returns a different color depending on the type of the CC-point. Useful for visualizing CL or CC points """ if cc.type==cam.CCType.FACET: col = (1,0,1) elif cc.type == cam.CCType.VERTEX: col = (1,1,0) elif cc.type == cam.CCType.EDGE: co...
5,289,684
def _json_dumps_fallback(value): # type: (Any) -> Any """ Fallback handler for json.dumps to handle objects json doesn't know how to serialize. """ try: # This is what structlog's json fallback does return value.__structlog__() except AttributeError: return repr(value...
5,289,685
def Floyd(graph, s, e): """弗洛伊德算法""" end = len(graph[0]) for k in range(end): for i in range(end): for j in range(end): # 更新经过i点的最短路径 if graph[i][j] > graph[i][k]+graph[k][j]: graph[i][j] = graph[i][k]+graph[k][j] # 查看最短路劲 print...
5,289,686
def Extrema_CurveTool_DN(*args): """ :param C: :type C: Adaptor3d_Curve & :param U: :type U: float :param N: :type N: int :rtype: gp_Vec """ return _Extrema.Extrema_CurveTool_DN(*args)
5,289,687
def main(): """Main script that runs the bot""" data_dir = '/mnt/c/Users/oscar/Documents/Stocks/' delay = 0.5 # (s) holdings = {'Net Worth': 1000000,'Cash': 1000000} ticker_files = [f for f in listdir(data_dir) if isfile(join(data_dir, f))] tickers = [f[:-4] for f in ticker_files if f[-4:] =...
5,289,688
def handle_order(self, order): """ """
5,289,689
def read_grey(filename, channel=0): """ Read an image file and return the red component (or component specified by channel) of the image. This is used to get an nxm greyscale image from a file saved in rgb or rgba format. Args: filename: Name of image file to read channel: Index of rgb...
5,289,690
def test_nonexistent_csv_path_raises( section_name, all_generated_configs_toml_path_pairs ): """test that a FileNotFoundError is raised when csv_path does not exist""" for config_toml, toml_path in all_generated_configs_toml_path_pairs: if section_name.lower() in toml_path.name: break #...
5,289,691
def convert_to_logit(param_value, pparam): """First convert any parameters that aren't probs to probs; then convert to logit""" # Convert params to probs if they aren't already: if pparam == "RAT_COEFF_TOM": param_value = param_value/20 elif pparam == "LOOK_AHEAD_STEPS_TOM": #TODO: Bett...
5,289,692
def lt(): """ performs a < """ global ptr if ptr <= 0: raise ValueError, "Segmentation fault!" ptr -= 1
5,289,693
def test_singlepfline_asfreqimpossible(freq, newfreq, kind): """Test if changing frequency raises error if it's impossible.""" periods = {"H": 200, "15T": 2000, "D": 20}[freq] i = pd.date_range("2020-04-06", freq=freq, periods=periods, tz="Europe/Berlin") pfl = dev.get_singlepfline(i, kind) with py...
5,289,694
def test_data3_important_metadata(dimap): """ Test important metadata parameters """ # Check extracted data is correct expected = 'DIMAP' assert dimap.metadata_format == expected, assert_error(expected, dimap.metadata_format) expected = '2.12.1' assert dimap.metadata_version == expected...
5,289,695
def create_nodes(df): """Create the network nodes for the cleaned trains DataFrame.""" def _group_nodes(group): assert ( len(group["countryCode"].unique()) == 1 ), "station exists in multiple countries" counts = group.shape[0] type_freq = group["type"].value_counts(n...
5,289,696
def read_html(): """Return simple HTML response.""" text = f'<html><body><h1>Hello! Today date is {date.today()}</h1></body></html>' return HTMLResponse(text)
5,289,697
def delete(params): """Deletes one category identified by the --dsid and --catid parameters.""" dsid = params.get("--dsid", "missing_id") catid = params.get("--catid", "missing_id") rsp = server.categories.delete(dsid, catid) if rsp is None: reportApiError(server, f"Failure attempting to d...
5,289,698
def xtest_wuch1a(): """Test wuch1a find_aligned_pairs(nll_matrix_ch1, numb=30).""" filename = r"tests/nll_matrix_wuch1.pkl" with open(filename, "rb") as fhandle: nll_matrix_ch1 = pickle.load(fhandle) # old gen_nllmatrix nll_matrix_ch1 = nll_matrix_ch1.T assert nll_matrix_ch1.shape == (...
5,289,699