content
stringlengths
22
815k
id
int64
0
4.91M
def iris_to_df(iris): """ Make dataframe for multiclass classification from iris data""" X, y = iris.data, iris.target iris_column_data = X.T.tolist() iris_column_names = ["col" + str(idx) for idx in range(X.shape[1])] data = {} for ind, iris_data_column in enumerate(iris_column_data): d...
5,306,700
def format_feedback(feedback_row, study): """Updates the feedback dict with the new information.""" formatted_feedback_row = { "success": { study.get_single_field(field["field_id"]).field_name: field["field_value"] for field in feedback_row["success"] }, "failed":...
5,306,701
def build_geometry(self): """Compute the curve (Line) needed to plot the object. The ending point of a curve is the starting point of the next curve in the list Parameters ---------- self : SlotW11 A SlotW11 object Returns ------- curve_list: list A list of 7 Segmen...
5,306,702
def main(argv): """Main aplication method""" parms = dict() parms = define_general_parms(parms) # parms setting manual fixed or catched by console if not argv: # Event-log parms parms['gl']['file'] = 'BPI_Challenge_2017_W_Two_TS.xes' else: # Catch parms by console ...
5,306,703
def COVERAGE(path=None): """path to coverage executable""" if not path: path = 'coverage' if not isinstance(path, str): raise ValueError("expected a string value") env.add(coverage_path=path)
5,306,704
def generate_sar_wsamp_array(laygen, objectname_pfix, workinglib, sar_name, placement_grid, routing_grid_m3m4, routing_grid_m4m5, routing_grid_m4m5_basic_thick, routing_grid_m5m6, routing_grid_m5m6_thick, routing_grid_m5m6_basic_thick, ...
5,306,705
def validcolor(c): """Takes a color and makes it valid by clamping each value between 0 and 255""" try: ret = [clamp(int(v+0.5), 0, 255) for v in c] return type(c)(ret) except TypeError: return clamp(int(v+0.5), 0, 255)
5,306,706
def give_me_the_record(primary_id, swissprot_file): """ Return a single record given with the primary id :param primary_id: A primary id :param swissprot_file: A swissprot file :return: A record with accession == primary id """ with open(swissprot_file, 'r') as fh: for record in Swis...
5,306,707
def update_cekit_jdbc_extension_images(version, confirm): """ Update the rhpam cekit jdbc extension image to the given version. :param version: version to set into the module :param confirm: if true will save the changes otherwise will print the proposed changes """ print("Updating CeKot JDBC e...
5,306,708
def fetch_local_files(stime, etime, localdirfmt, localdict, outdir, fnamefmt, back_time=relativedelta(years=1), remove=False): """ A routine to locate and retrieve file names from locally stored SuperDARN radar files that fit the input criteria. Example ------- Fetches on...
5,306,709
def test_xdg_config_dirs_relative(monkeypatch: MonkeyPatch) -> None: """Test xdg_config_dirs when XDG_CONFIG_DIRS is relative paths.""" monkeypatch.setenv("XDG_CONFIG_DIRS", "rela/tive:ano/ther") assert xdg.xdg_config_dirs() == [Path("/etc/xdg")]
5,306,710
def get_access_token(config): """ Get an access token for the logged in user """ keyring_cache = KeyringCredentialCache(config.issuer, config.orgname) refresh_token = keyring_cache.get_refresh_token() payload = { "grant_type": "refresh_token", "refresh_token": refresh_token, ...
5,306,711
def ms_graph_users(licensed=False): """Query the Microsoft Graph REST API for on-premise user accounts in our tenancy. Passing ``licensed=True`` will return only those users having >0 licenses assigned. """ token = ms_graph_client_token() headers = { "Authorization": "Bearer {}".format(token...
5,306,712
def protect_def_name(defName): """Convert a DEF name to be supported in Webots.""" protectedDefName = clean_string(defName) if len(protectedDefName) > 0 and protectedDefName[0].isdigit(): protectedDefName = "_" + protectedDefName return protectedDefName
5,306,713
def get_blog(id: str) -> Tuple: """ Function used to fetch particular blog or return error if it is doesn't exist. :param id: blog id :return: tuple of (blog object or any error) """ blog, error = _get_blog_obj(id) if not error: blog = [blog_schema.dump(blog)] return {"blogs...
5,306,714
def test_update_member_not_present(mdb, member, authority): """Check update_member against a member not in the database. It should raise a MemberNotFoundError in this case. """ mdb.mocksql_connect().cursor().fetchall.side_effect = [[], []] with pytest.raises(socman.MemberNotFoundError): mdb...
5,306,715
def padded_cross_entropy_loss(logits, labels, smoothing, vocab_size): """Calculate cross entropy loss while ignoring padding. Args: logits: Tensor of size [batch_size, length_logits, vocab_size] labels: Tensor of size [batch_size, length_labels] smoothing: Label smoothing constant, used to det...
5,306,716
def test_4d_user_pid(mocker: MockerFixture) -> None: """Test that PidConfiguration.json is loaded properly.""" mocker.patch("builtins.open", side_effect=FileNotFoundError) with pytest.raises(NoCredentialsError): FourDCredentials._get_user_pid() mocker.patch( "builtins.open", ret...
5,306,717
def ATL06_to_dataframe(FILENAME, beams=DEFAULT_BEAMS, groups=DEFAULT_GROUPS, **kwargs): """ Reads ICESat-2 ATL06 (Land Ice Along-Track Height Product) data files Arguments --------- FILENAME: full path to ATL06 file Keyword Arguments ----------------- beams: ATLAS beam groups ...
5,306,718
def test_string(): """ Dumping and loading a string """ filename, mode = 'test.h5', 'w' string_obj = "The quick brown fox jumps over the lazy dog" dump(string_obj, filename, mode) string_hkl = load(filename) assert isinstance(string_hkl, str) assert string_obj == string_hkl
5,306,719
def get_neighboring_connectivity(cm: np.ndarray) -> List[float]: """ Get how strong neighboring classes are connected. Parameters ---------- cm : np.ndarray Returns ------- con : List[float] """ con = [] n = len(cm) for i in range(n - 1): con.append(cm[i][i + 1]...
5,306,720
def vertical_scatter_ba(results, targets, ylim=(70, 100), violin=False, minorticks=False, percentage=True, **kwargs): """Plot a vertical scatter plot of balanced accuracies. results: Results object. targets: Target labels. ylim: (lower, upper) y axis. violin: Plot a violin p...
5,306,721
def autocov(x): """ Calculate the auto-covariance of a signal. This assumes that the signal is wide-sense stationary Parameters ---------- x: 1-d float array The signal Returns ------- nXn array (where n is x.shape[0]) with the autocovariance matrix of the signal x Not...
5,306,722
def set_apex_params(local_rank): """ Setting distributed parameters for Apex """ if 'WORLD_SIZE' in os.environ: world_size = int(os.environ['WORLD_SIZE']) global_rank = int(os.environ['RANK']) print('GPU {} has Rank {}'.format( local_rank, global_rank)) torch.cud...
5,306,723
def correlation(self, column_a, column_b): """ Calculate correlation for two columns of current frame. Parameters ---------- :param column_a: (str) The name of the column from which to compute the correlation. :param column_b: (str) The name of the column from which to compute the correlation....
5,306,724
def load_library(): """Loads the MagickWand library. :returns: the MagickWand library and the ImageMagick library """ libpath = None system = platform.system() magick_home = os.environ.get('MAGICK_HOME') if magick_home: if system == 'Windows': libpath = 'CORE_RL_wand_....
5,306,725
def get_ax(rows=1, cols=1, size=8): """Return a Matplotlib Axes array to be used in all visualizations in the notebook. Provide a central point to control graph sizes. Change the default size attribute to control the size of rendered images """ _, ax = plt.subplots(rows, cols, figsize=(size...
5,306,726
def workflow(func, **kwargs): """ Desc :param func: :param kwargs: :return: """ def inner(*args, **kwargs): """ Desc :param args: :param kwargs: :return: """ logging.debug("workflow args: %s %s",str(args), str(kwargs)) if 'cpu'...
5,306,727
def multiply(a, b, out=None, increment=False, stream=None): """Element-wise product of `a` and `b`.""" dtype = a.dtype if out is None: out = gpuarray.zeros(a.shape, dtype=dtype) assert a.size == b.size assert a.dtype == b.dtype == out.dtype block = (min(a._block[0], a.size), 1, 1) ...
5,306,728
def uv2spd_dir(u,v): """ converts u, v meteorological wind components to speed/direction where u is velocity from N and v is velocity from E (90 deg) usage spd, dir = uv2spd_dir(u, v) """ import numpy as np spd = np.zeros_like(u) dir = np.zeros_like(u) spd = np.sqrt(...
5,306,729
def adjacency_mat(x_all, y_all, ox, oy, rr): """ Function that creates the adjacency matrix from the edges and points with the no restriction method """ n = len(x_all) A = np.zeros((n, n)) road_map = [] for i in range(n): temp = [] for j in range(n): if i ==...
5,306,730
def install_requirements(req_file): """ Parse `requirements.txt` line by line and install each requirement. Confirm with user before installing them. """ try: with open(req_file, 'r') as f: requirements = f.readlines() requirements = [x.strip() for x in requirements] print('Modules to be installed: ') ...
5,306,731
def get_file_list(dir, pattern, suffix, sort_order): """ Makes a sorted list of files with fully-qualified path which have pattern in the filename, and end with suffix. Sorted in the order specified. NOTE: does NOT use index files to make list. """ dir_list = os.listdir(dir) filtered_list ...
5,306,732
def resume_verify_mirror(tf, rn): """ Resume the verifying and rescraping process, neeed to import task file :param tf: File descriptor of the task file :param rn: Number of times of rretry """ with codecs.open(tf, mode='r', encoding='utf-8') as failure_file: run_info = json.load(failure...
5,306,733
def calcEOAutomorphisms(tree) : """ Computes the size of the automorphism group of the input :py:obj:`tree`. We think of :py:obj:`tree` as a rooted tree, whose vertices are decorated by degrees and which has additional "exterior" edges of two distinct types, corresponding to the boundary and the interior markings,...
5,306,734
def cisco_ios_simple_config(): """Creares raw cisco config of comments etc.""" with open( CISCO_IOS_SIMPLE_CONFIG_PATH, mode="r", errors="ignore", encoding="ascii" ) as config_file: raw_config = config_file.readlines() config = [] for line in raw_config: line = line.rstrip() ...
5,306,735
def test___str__(json_bytes_data: TypingJsonBytesData): """Test __str__ pass-through for different variants.""" string = str(json_bytes_data["json_bytes"]) assert string assert "None" not in string
5,306,736
def main(): """Doc""" lemmatizer = WordNetLemmatizer() print(lemmatizer.lemmatize("cats")) print(lemmatizer.lemmatize("cacti")) print(lemmatizer.lemmatize("geese")) print(lemmatizer.lemmatize("rocks")) print(lemmatizer.lemmatize("python")) print(lemmatizer.lemmatize("better", pos="a"))...
5,306,737
def RRIMAPublicDashboard(request,id=0): """ :param request: :param id: :return: """ ## retrieve program model = Program program_id = id getProgram = Program.objects.all().filter(id=program_id) ## retrieve the coutries the user has data access for countries = getCountry(requ...
5,306,738
def get_workflows_requests(module): """Returns all requests for specified workflow""" return Request.objects.filter(module_ref=module)
5,306,739
def cwd_hg_version(short=False): """Get the Mercurial changeset hash of the repository that contains the current working directory. If ``short`` is True, the short (12-character) form of the changeset hash will be returned. If the current working copy of the repository is modified, a plus sign is append...
5,306,740
def parse_idf(content: str) -> dict: """Parse an IDF file into a dictionary.""" sections = content.rstrip().split(';') sub_sections: List[List[str]] = [] obj_dict: Dict[str, List[List[str]]] = {} for sec in sections: sec_lines = sec.splitlines() _lines = [] for sl in sec_line...
5,306,741
async def remove_all_roles(bot, user): """ Removes all self-assignable roles from user """ all_user_roles = user.roles roles_to_remove = [] for r in all_user_roles: if is_accessible_role(r.name): roles_to_remove.append(r) await client.remove_roles(user, *roles_to_remove)
5,306,742
def _make_item_rec_sys_data(review_data): """ Generates item_rec_sys_data by obfuscating customer ids. Parameters ---------- review_data: combined_data. Yields ------ item_rec_sys_data.csv Returns ------- item_rec_sys_data. """ item_rec_sys_data = revi...
5,306,743
def system_order(tf: scipysig.dlti) -> tuple: """Returns the order of the numerator and denominator of a transfer function Parameters ---------- tf : scipy.signal.dlti discrete time rational transfer function Returns ---------- (num, den): tuple Tuple containing the o...
5,306,744
def drvit_small_patch16_384(pretrained=False, **kwargs): """ ViT-Small (ViT-S/16) NOTE I've replaced my previous 'small' model definition and weights with the small variant from the DeiT paper """ model_kwargs = dict(patch_size=16, embed_dim=384, depth=12, num_heads=6, **kwargs) model = _create_visi...
5,306,745
def pdist_block(pdist_vec, i, j): """Slice the pdist ndarray as if it were a squareform matrix. Args: pdist_vec: ndarray output from pdist() i: ndarray row index of matrix j: ndarray col index Returns: (i.size, j.size) ndarray from distance matrix """ col_ind, row_ind = np.meshgrid(...
5,306,746
def test_metadata(): """Test setting image metadata.""" np.random.seed(0) data = np.random.random((10, 15)) layer = Image(data) assert layer.metadata == {} layer = Image(data, metadata={'unit': 'cm'}) assert layer.metadata == {'unit': 'cm'}
5,306,747
def ufile_put_url(bucket, key): """ 采用普通上传方法上传UCloud UFile文件的url :param bucket: string类型, 待创建的空间名称 :param key: string类型, 在空间中的文件名 :return: string类型, 普通上传UFile的url """ return 'http://{0}{1}/{2}'.format(bucket, config.get_default('upload_suffix'), key)
5,306,748
def build_assemblenet_model( input_specs: tf.keras.layers.InputSpec, model_config: cfg.AssembleNetModel, num_classes: int, l2_regularizer: Optional[tf.keras.regularizers.Regularizer] = None): """Builds assemblenet model.""" input_specs_dict = {'image': input_specs} backbone = build_assemblenet_v1(...
5,306,749
async def post_donation(donation_id: str) -> tuple: """Post donations to their respective third party APIs If the donation has already been posted, it will not be posted again. """ donation = await get_donation(donation_id) if not donation: return (jsonify({"message": "Donation not found!"}...
5,306,750
def predict_in_batches( model: transformers.models, tokenizer, dataset: List[str], batch_size: int = 4 ) -> List[int]: """Predicts the labels for the entries in dataset using the model passed :param model: the model to use for prediction :param tokenizer: the tokenizer used for the model :param data...
5,306,751
def _on_isolate_select(cmd): """ Executed when an 'isolateSelect' command was detected. """ # isolate selected if " 1 " in cmd: m2u.core.editor.isolate_selected() # un-isolate elif " 0 " in cmd: # TODO: un-isolate is not really unhideAll, it is unhiding all # objects that ...
5,306,752
def remove_punctuation(sentence: str, punctuation: str = None): """ Default Punctuation -> [',', '!', '#', '$', '%', "'", '*', '+', '-', '.', '/', '?', '@', '\\', '^', '_', '~'] """ punctuation = punctuation or ''.join(PUNCTUATION) for x in punctuation: sentence = sentence.replace(x, '') ...
5,306,753
def get_digest_for(changelogs, before_date=None, after_date=None, limit_versions=5): """Before date and after date are inclusive.""" # search packages which have changes after given date # we exclude unreleased changes from digest # because they ...
5,306,754
def count_time(func): """类中使用的计时装饰器""" def inner(*args, **kwargs): print('{} 进程数据处理开始'.format(os.getpid())) start_time = time.time() result = func(*args, **kwargs) end_time = time.time() print('{} 进程数据处理完成,处理数据用时:{}'.format(os.getpid(), end_time - start_time)) re...
5,306,755
def p2m( leaves, nleaves, key_to_index, key_to_leaf_index, sources, source_densities, source_index_pointer, multipole_expansions, nequivalent_points, x0, r0, alpha_outer, check_surface, ncheck_points, ...
5,306,756
async def test_dimmer_off(dimmer, hass, config): """Test light off.""" feature_mock, entity_id = dimmer def initial_update(): feature_mock.is_on = True feature_mock.async_update = AsyncMock(side_effect=initial_update) await async_setup_entity(hass, config, entity_id) feature_mock.asyn...
5,306,757
def get_version(): """Returns version""" return pkg_resources.get_distribution("rosetta-cipher").version
5,306,758
def good_fft_number(goal): """pick a number >= goal that has only factors of 2,3,5. FFT will be much faster if I use such a number""" assert goal < 1e5 choices = [2**a * 3**b * 5**c for a in range(17) for b in range(11) for c in range(8)] return min(x for x in choic...
5,306,759
def invoke_pytorch_helper_function(ecr_image, sagemaker_regions, helper_function, helper_function_args): """ Used to invoke SM job defined in the helper functions in respective test file. The ECR image and the sagemaker session are passed explictly depending on the AWS region. This function will rerun ...
5,306,760
def adjust_image_resolution(data): """Given image data, shrink it to no greater than 1024 for its larger dimension.""" output_large = cStringIO.StringIO() output_default = cStringIO.StringIO() output_tiny = cStringIO.StringIO() try: im0 = Image.open(cStringIO.StringIO(data)) ...
5,306,761
def connect_to_ecs(env): """ Return boto connection to the ecs in the specified environment's region. """ rh = env.resource_handler.cast() wrapper = rh.get_api_wrapper() client = wrapper.get_boto3_client( 'ecs', rh.serviceaccount, rh.servicepasswd, env.aws_region ...
5,306,762
def test_complex_pydantic_model(): """ Test actual Pydantic models, with different annotation types. """ example = textwrap.dedent( ''' from __future__ import annotations from datetime import datetime from decimal import Decimal from typing import TYPE_CHECKING ...
5,306,763
def dsa_sign(message, private, constants=None): """DSA signs the bytestring `message` with the given private key and returns the signature (r, s) using the hash SHA1""" p, q, g = get_dsa_constants(constants) while True: k = random.randint(1, q - 1) r = pow(g, k, p) % q if r == 0:...
5,306,764
def _pytesmo_to_qa4sm_results(results: dict) -> dict: """ Converts the new pytesmo results dictionary format to the old format that is still used by QA4SM. Parameters ---------- results : dict Each key in the dictionary is a tuple of ``((ds1, col1), (d2, col2))``, and the values...
5,306,765
def test_group_reuse(): """We can re-use a group.""" grp = Group([ Docker('py35', image='python:3.5'), Docker('py36', image='python:3.6') ]) with grp: grp.call(time.time) grp.call(time.time)
5,306,766
def provision_greengrass(arguments: argparse) -> dict: """Orchstrates and completes all provisioning processes based on incoming validated argument list :param arguments: Validated command line arguments :type arguments: argparse :return: Results from provisioning steps :rtype: dict """...
5,306,767
def on_message(client, userdata, msg): """ On message receiving the corresponding Json will be pushed into a list to be processed later by archiver function """ if msg.payload is None: logger.warning("Empty (None) payload received") return try: data = json.loads(msg.payl...
5,306,768
def invite_account_to_organization(Target=None, Notes=None): """ Sends an invitation to another account to join your organization as a member account. Organizations sends email on your behalf to the email address that is associated with the other account's owner. The invitation is implemented as a Handshake wh...
5,306,769
def infotodict(seqinfo): """Heuristic evaluator for determining which runs belong where allowed template fields - follow python string module: item: index within category subject: participant id seqitem: run number during scanning subindex: sub index within group """ info = {'test':[]...
5,306,770
def load_vgg(sess, vgg_path): """ Load Pretrained VGG Model into TensorFlow. :param sess: TensorFlow Session :param vgg_path: Path to vgg folder, containing "variables/" and "saved_model.pb" :return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out, layer7_out) """...
5,306,771
def grab_svg(scene): """ Return a SVG rendering of the scene contents. Parameters ---------- scene : :class:`CanvasScene` """ svg_buffer = QBuffer() gen = QSvgGenerator() gen.setOutputDevice(svg_buffer) items_rect = scene.itemsBoundingRect().adjusted(-10, -10, 10, 10) if ...
5,306,772
def get_bel_node_uniprot(): """Get UniProt related eBEL nodes.""" b = Bel() conf = { 'rid': "@rid.asString()", 'name': "name", 'namespace': "namespace", 'bel': "bel", 'uniprot_accession': "uniprot" } sql = "SELECT " sql += ', '.join([f"{v} as {k}" for k, v...
5,306,773
def decode_ori_batch(ori, b): """Decode a batch of orientation (ori) using the pre-computed orientation decode variable (b) based on the histogram (see pre_compute_ori_decode) """ ori = ori.cpu() batch_size = ori.size(0) ori_avg = torch.zeros((batch_size, 4), dtype=torch.float32) h_avg = t...
5,306,774
def receive_email(msg_str): """ Given a string representation of an email message, parses it into a :class:`~kiki.message.KikiMessage`. Returns a (message, created) tuple, where ``created`` is False if the message was already in the database. """ received = datetime.now() python_msg = message_from_string(msg_str...
5,306,775
def test_event_not_for_dist_git_namespace(caplog): """ When the update event not from the configured dist-git namespace, the event is ignored and the logs indicate this. """ ( flexmock(os) .should_receive("getenv") .with_args("D2S_DIST_GIT_NAMESPACE", "rpms") .and_ret...
5,306,776
def handle_deleted_file(uuid): """ Handles a filesystem delete based on UUID.""" loc = os.path.join(settings.UPLOAD_DIRECTORY, uuid) shutil.rmtree(loc)
5,306,777
def rotated_array_search(input_list, number): """ Find the index by searching in a rotated sorted array """ high = len(input_list) - 1 low = 0 while low <= high: mid = (low + high) // 2 if input_list[mid] == number: return mid elif input_list[mid] < number <= ...
5,306,778
def tmatch2(**kwargs): """ keywords are: in1 string, The location of the first input table. This may take one of the following forms: - A filename. - A URL. in2 string, The location of the second input table. Th...
5,306,779
def parse_sentence_spacy(sentence_text, sentence_entities): """ :param sentence_text: :param sentence_entities: :return: """ # Use spacy to parse a sentence for e in sentence_entities: idx = sentence_entities[e][0] sentence_text = sentence_text[:idx[0] - 1] + sen...
5,306,780
def check_for_deprecated_generators(main, file): """ Check if the conan file if using some deprecated generator :param main: Output stream :param file: Conanfile path """ conan_instance, _, _ = conan_api.Conan.factory() dict_generators = conan_instance.inspect(path=file, attributes=["generators...
5,306,781
def sec_server(request): """ Builds a server instance with the event loop running in a thread. """ # Check mongo testing.check_active_mongo_server() storage_name = "qcf_local_server_auth_test" with testing.pristine_loop() as loop: # Build server, manually handle IOLoop (no start/...
5,306,782
def get_chat_members_count(chat_id, **kwargs): """ Use this method to get the number of members in a chat. :param chat_id: Unique identifier for the target chat or username of the target channel (in the format @channelusername) :param kwargs: Args that get passed down to :class:`TelegramBotRPCRequest` ...
5,306,783
def sample_tag(user, name='Sample tag'): """Create and reutn a sample tag""" return Tag.objects.create(user=user, name=name)
5,306,784
def _unpack_keypoints(keypoints): """Unpack the keypoints into an array of coordinates. Args: keypoints: a list of `cv2.KeyPoint`s Returns: an n x 2 array of [row, col] coordinates """ return np.array([[kp.pt[1], kp.pt[0]] for kp in keypoints])
5,306,785
def test_seller_xfer_sum_of_outputs_greater_than_inputs( helpers, initial_mint_inner, addresses_inner ): """ Amount used in outputs greater than the amount held by inputs, hence it will be rejected """ seq_no = get_seq_no(initial_mint_inner) [seller_address, user1_address] = addresse...
5,306,786
def get_videos(): """Return a json array of all videos available on the site, built by fetching each page sequentially until there are no more pages.""" videos = [] page = 0 end_of_pages = False while not end_of_pages: page += 1 url = "http://pyvideo.org/api/v2/video?page=%s" % s...
5,306,787
def input_mon(ctx): """ Monitors all pins for changes. Expects ANSI terminal color. """ click.echo("Ctrl-\\ to quit") d = CM119_IO(ctx.obj["vid"], ctx.obj["pid"]) d.set_dir({pin: "I" for pin in range(1, 9)}) # All GPIOs as inputs def pin_formatter(pin_name, state): """Helper function for ...
5,306,788
def mapd_server(): """Ensure a mapd server is running, optionally starting one if none""" if _check_open(): # already running before pytest started pass else: raise RuntimeError( "Unable to connect to OmniSci server at {}".format(heavydb_host) )
5,306,789
def make_fake_symbol_from_data_type( data_type, symbol_pragma_text, *, name='$(SYMBOL)', pragma_name: str = 'pytmc', data_area_index=0, tmc=None, create_data_area_if_needed=True): """ Create a :class:`_FakeSymbol` from the given data type. Parameters ---------- data_...
5,306,790
def has_at_least_one_share_class(filing_json, filing_type) -> Optional[str]: # pylint: disable=too-many-branches """Ensure that share structure contain at least 1 class by the end of the alteration or IA Correction filing.""" if filing_type in filing_json['filing'] and 'shareStructure' in filing_json['filing']...
5,306,791
def get_image_table(nova_endpoint=None): """ :param nova_endpoint: :return: """ image_list = PrettyTable() image_list.field_names = ["ID", "Name", "Format", "Size", "Min Ram", "Mind Disk", "location", "adpter type", "status", "checksum"] glance_list = nova_en...
5,306,792
def color_thresholding(img, thresh_h=None, thresh_s=None, thresh_l=None): """ Crete image mask using color thresholding. :param img: source bgr image :param thresh_h: tuple(min,max), hue threshold in HSL color space :param thresh_s: tuple(min,max), saturation threshold in HSL color space :retur...
5,306,793
def no_matplotlib(monkeypatch): """ Mock an import error for matplotlib""" import_orig = builtins.__import__ def mocked_import(name, globals, locals, fromlist, level): """ """ if name == 'matplotlib.pyplot': raise ImportError("This is a mocked import error") return impor...
5,306,794
def _get_center_context( context_window_type, walks, n_walks, walk_len, window_length, padding_id ): """Get center and context pairs from a sequence window_type = {-1,0,1} specifies the type of context window. window_type = 0 specifies a context window of length window_length that extends both left ...
5,306,795
def get_files(pga_id): """ Get all uploaded YAML files as a dictionary. :return: dict of uploaded YAML files as JSON """ files_dict = utils.get_uploaded_files_dict(pga_id) return jsonify(files_dict)
5,306,796
def show(): """ Show figure :return: None """ pyplot.show()
5,306,797
def convert_mask_to_pick(mask, sample_rate, threshold): """Convert a first breaks `mask` into an array of arrival times. The mask has shape (n_traces, trace_length), each its value represents a probability of corresponding index along the trace to follow the first break. A naive approach is to define the f...
5,306,798
def create_tqdm_reader(reader, max_reads=None): """Wrap an iterable in a tqdm progress bar. Args: reader: The iterable to wrap. max_reads: Max number of items, if known in advance. Returns: The wrapped iterable. """ import tqdm return tqdm.tqdm(reader, total=max...
5,306,799