content
stringlengths
22
815k
id
int64
0
4.91M
def test_photon_source_hdf5_to_mesh(): """Tests the function photon source_h5_to_mesh.""" if not HAVE_PYMOAB: raise SkipTest filename = os.path.join(thisdir, "files_test_alara", "phtn_src") photon_source_to_hdf5(filename, chunkshape=(10,)) assert_true(os.path.exists(filename + '.h5')) ...
5,307,300
def all_candidate_sampler(true_classes, num_true, num_sampled, unique, seed=None, name=None): """Generate the set of all classes. Deterministically generates and returns the set of all possible classes. For testing purposes. There is no need to use this, since you might as well use f...
5,307,301
def iter_multi_items(mapping): """Iterates over the items of a mapping yielding keys and values without dropping any from more complex structures. """ if isinstance(mapping, MultiDict): for item in mapping.iteritems(multi=True): yield item elif isinstance(mapping, dict): ...
5,307,302
def _ilabel_to_state(labels, num_labels, ilabel_log_probs): """Project ilabel log probs to state log probs.""" num_label_states = _get_dim(labels, 1) blank = ilabel_log_probs[:, :, :1] blank = array_ops.tile(blank, [1, 1, num_label_states + 1]) one_hot = array_ops.one_hot(labels, depth=num_labels) one_hot ...
5,307,303
def test_collection_append(): """Does Collection.append() work?""" lc = LightCurve(time=np.arange(1, 5), flux=np.arange(1, 5), flux_err=np.arange(1, 5), targetid=500) lc2 = LightCurve(time=np.arange(10, 15), flux=np.arange(10, 15), flux_err=np.arange(10, 15), targeti...
5,307,304
def multi_threading_conversion(list_of_args): """ transforms a list of args into 5 args before calling conversion function :param list_of_args: list of args :return: None """ conversion_from_list_of_files(list_of_args[0], list_of_args[1], list_of_args[2], list_of_args[3], list_of_args[4])
5,307,305
def loads(filepath, schemapath=None): """ This function loads a JSON file validating its contents against a given schema. For the validation, the library "jsonschema" is used. """ with open(filepath, 'r') as file: json_object = json.load(file) if schemapath: _log.info(f"Validat...
5,307,306
def add_dims_to_array(image: np.ndarray) -> np.ndarray: """Adds 2 extra dimensions to the image array. The 1st dimension indicates the number of images per sample. The 4th dimension indicates that the image is in grayscale (single channel). Args: image (np.ndarray): The input image. Return...
5,307,307
def TimestampFromTicks(ticks): """Construct an object holding a timestamp value from the given ticks value (number of seconds since the epoch). This function is part of the `DBAPI 2.0 specification <http://www.python.org/dev/peps/pep-0249/>`_. :rtype: :class:`datetime.datetime` """ return ...
5,307,308
def plot(item, measurements, fig, subplot=111): """Plot something?""" ax = fig.add_subplot(subplot) ax.scatter(range(len(measurements)), measurements) ax.set_title('average ' + item[2])
5,307,309
def get_matlab(): """ Return a running MatlabProcess instance. """ global _proc if _proc is None: path = os.path.dirname(__file__) model_path = os.path.join(path, 'model') # _proc = matlab_proc.MatlabProcess(cwd=model_path) _proc = matlab.engine.start_matlab() _pr...
5,307,310
def _step(context, text): """ :type context: HackedContext """ assert text in context.driver.current_url,\ u'"{}"" was not in the current url: {}'.format(text, context.driver.current_url)
5,307,311
def get_mouseState(): """ get current mouse activation state """ with open('/home/noah/.config/i3/mousestate') as fp: arr = fp.readlines() if len(arr) > 0: if arr[0] == "0": return {'full_text' : '%s' % "", 'name' : 'mousestate', "color": "#888888"} elif...
5,307,312
def prefix_as_comment(comment_prefix, text): """Adds comment prefixes to new lines in comments """ return text.replace('\n', '\n' + comment_prefix)
5,307,313
def test_wild017_wild017_v1_xml(mode, save_output, output_format): """ Valid restriction of wildcards Restricted type disallows more namespaces than the base type disallows """ assert_bindings( schema="saxonData/Wild/wild017.xsd", instance="saxonData/Wild/wild017.v1.xml", cla...
5,307,314
def list_all_measurement_stations(json_dir): """Returns a list of the GIC measurement stations available. Parameters: ----------- json_dir :: str Directory containing json files for all stations with measurements. Returns: -------- all_st :: list List of all stations in jso...
5,307,315
def get_transform(opt): """Basic process to transform PIL image to torch tensor""" transform_list = [] osize = [opt.loadSize[0], opt.loadSize[1]] fsize = [opt.fineSize[0], opt.fineSize[1]] if opt.isTrain: if opt.resize_or_crop == 'resize_and_crop': transform_list.append(transform...
5,307,316
def create_10fold_cross_validation_fig(s, logging): """Create figure showing ROC curve for each fold in a 10-fold validation. The underlying data is created by run_10fold_cross_validation. If this has not been run, it will return a file-not-found error. Parameters ---------- s : dict S...
5,307,317
def list_datamaskdef(ranger_client: RangerClient, service_type: str): """ Returns `dataMaskDef` properties from service definitions. """ return ranger_client.get_servicedefs_by_type(service_type)
5,307,318
async def TrimSquareAndResize(file: io.BytesIO, save_path: pathlib.Path, resize_width_and_height: int = 400): """ 正方形の 400×400 の PNG にトリミング&リサイズして保存する関数 ref: https://note.nkmk.me/python-pillow-basic/ ref: https://note.nkmk.me/python-pillow-image-resize/ ref: https://note.nkmk.me/python-pillow-image-...
5,307,319
def get_balanced_batches( n_trials, rng, shuffle, n_batches=None, batch_size=None ): """Create indices for batches balanced in size (batches will have maximum size difference of 1). Supply either batch size or number of batches. Resulting batches will not have the given batch size but rather the nex...
5,307,320
def qualified_version() -> str: """Get the qualified version of this module.""" return f"Meilisearch Python (v{__version__})"
5,307,321
def indentsize(line): """Return the indent size, w spaces, at the start of a line of text.""" expline = line.expandtabs() zwróć len(expline) - len(expline.lstrip())
5,307,322
def global_init_fx() -> None: """ Session scoped auto-use plugin for loading CLI flags, configuration settings, and preparing the logging system. This fixture does not provide a value. """ PLUGIN_MANAGER.register(ConfigReceiver, "testing_config_recv") # fetch the CLI argument _path = cl...
5,307,323
def remove_brackets(s): """Remove brackets [] () from text """ return re.sub(r'[\(\(].*[\)\)]', '', s)
5,307,324
def read_dataset(path, **filter_by): """Filters by filter_by if given, or reads entire dataset. path is a string in dot notation showing which fields the data is under (eg. 'raw.obj_pit'). competition is the competition code. **filter_by is of the form foo=bar and is the key value pair to filter da...
5,307,325
def gaussian_gru_policy_tf_ppo_benchmarks(): """Run benchmarking experiments for Gaussian GRU Policy on TF-PPO.""" iterate_experiments(gaussian_gru_policy, MuJoCo1M_ENV_SET, seeds=_seeds)
5,307,326
def test_result(): """Test callback process_result.""" def pr(value): return value + 1 command = Command("method", "path", {}, process_result=pr) assert command.result is None assert command.raw_result is None command.process_result(0) assert command.result == 1 assert command...
5,307,327
def make_lines(data, precision=None): """Extract points from given dict. Extracts the points from the given dict and returns a Unicode string matching the line protocol introduced in InfluxDB 0.9.0. """ lines = [] static_tags = data.get('tags') for point in data['points']: elements ...
5,307,328
def on_enter(event_data): """ Coarse focusing state. Will do a coarse focus for each camera and move to the scheduling state. """ pocs = event_data.model pocs.next_state = 'parking' coarse_focus_timeout = pocs.get_config("focusing.coarse.timeout") # Do the autofocusing pocs.say("Coars...
5,307,329
def subdivide_joint(joint1 = None, joint2 = None, count = 1, prefix = 'joint', name = 'sub_1', duplicate = False): """ Add evenly spaced joints inbetween joint1 and joint2. Args: joint1 (str): The first joint. If None given, the first selected joint. joint2 (str): The second joint...
5,307,330
def red(message, bold=False): """ Color in red """ return colour('red', message, bold)
5,307,331
def create_datediff_test_df(): """Create DataFrame for DateDifferenceTransformer tests.""" df = pd.DataFrame( { "a": [ datetime.datetime(1993, 9, 27, 11, 58, 58), datetime.datetime(2000, 3, 19, 12, 59, 59), datetime.datetime(2018, 11, 10, 11, ...
5,307,332
def get_channel_id(channel_name, channel_type): """ Fetches the ID of a Slack Channel or User Args: channel_name: (string) The name of the channel / name of user / slack id of channel/user channel_type: (string) The Channel type, either "user" or "channel" or "slack_id" Returns: ...
5,307,333
def minify_placeholders(msg): """Expand placeholder values where possible. An example input object: { "message": "Unable to parse destination: $DEST$", "placeholders": { "dest": { "content": "$1", "example": "invalid.destination" } } ...
5,307,334
def test_dpp_proto_auth_req_no_i_proto_key(dev, apdev): """DPP protocol testing - no I-proto key in Auth Req""" run_dpp_proto_auth_req_missing(dev, 12, "Missing required Initiator Protocol Key attribute")
5,307,335
def createLimit(name, maxValue): """Create a new Limit with the given name and max value. :type name: str :param name: the name of the new Limit :type maxValue: int :param maxValue: the maximum number of running frames for this limit :rtype: opencue.wrappers.limit.Limit :return: the newly c...
5,307,336
def update_feature_set_deployment_status(db: Session, fset_id: int, deploy_status: bool): """ Updates the deployment status of a feature set (for example, if someone is undeploying an fset). :param db: SqlAlchemy Session :param fset_id: Feature Set ID """ db.query(models.FeatureSet).filter(mode...
5,307,337
def get_bounding_box(vehicle, camera, sensor_transform): """ Get vehicle bounding box and project to sensor image. Args: -vehicle (carla.vehicle or ObstacleVehicle): vehicle object. -camera (carla.sensor.camera.rgb): The CARLA sensor object. -sensor_transform (carla.Transform): senso...
5,307,338
def test_crash_during_event_checkpointing(workflow_start_regular_shared): """Ensure that if the cluster dies while the event is being checkpointed, we properly re-poll for the event.""" _storage = storage.get_global_storage() """Ensure that we don't re-call poll_for_event after `event_checkpointed` ...
5,307,339
def calcAbsolutePercentageError(actualResult, forecastResult): """ Calculates Absolute Percentage error. returns float """ return (abs((actualResult - forecastResult)/actualResult)) * 100
5,307,340
def seed_toasters(number_of_toasters): """Create the initial toasters so it doesn't start empty""" for _ in range(number_of_toasters): while True: row = randint(0, 8) col = randint(0, 8) if evaluate_position(row, col): break tilegrid[col, row] ...
5,307,341
def main(*args: str) -> None: """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. :param args: command line arguments """ options = {} # Process global args and prepare generator args parser gen_factory = pagegenerators.GeneratorFactory() ...
5,307,342
def section_areas(neurite): """Section areas.""" return _map_sections(sf.section_area, neurite)
5,307,343
def set_type_labelling(node, type_label): """ Sets type labelling of the given node :param node: str :param type_label: str """ if not type_label or type_label not in maya_constants.TYPE_LABELS or not attribute_exists(node, 'type'): return False type_index = maya_constants.TYPE_LAB...
5,307,344
def dataset(paths_or_factories, filesystem=None, partitioning=None, format=None): """ Open a dataset. Parameters ---------- paths_or_factories : path or list of paths or factory or list of factories Path to a file or to a directory containing the data files, or a list of...
5,307,345
def main(): """Entry point.""" session = requests.Session() atexit.register(on_exit, session) parser = argparse.ArgumentParser(description='Download file from Illumina BaseSpace.') def check_tries_within_range(arg): try: value = int(arg) except ValueError: r...
5,307,346
def get_references(content: str) -> Set[URI]: """Get the unique set of references in a string.""" return set(URI(ref) for ref in re_ref.findall(content))
5,307,347
def array_intersection(arrays_list, fields): """ Find and return the intersecting entries in multiple arrays. Parameters ---------- arrays_list : :obj:`iterable` Iterable of input structured arrays fields : :obj:`iterable` Iterable of fields to use to decide if entires are inte...
5,307,348
def numeric_density(pressure: FloatLike, temperature: float = 300) -> FloatLike: """Calculate numeric density of a gas. Args: pressure (float): pressure in mTorr temperature (float): temperature Returns: float: Numeric density (atoms per cubic meter) """ return pressure * M...
5,307,349
def is_postgres_connected() -> bool: """ Check we can reach the main postgres and perform a super simple query Returns `True` if so, `False` otherwise """ try: with connections[DEFAULT_DB_ALIAS].cursor() as cursor: cursor.execute("SELECT 1") except DjangoDatabaseError: ...
5,307,350
def match_hyperparameter(hp, parameters): """ Given a partial hyperparameter name hp find the corresponding full name in parameters """ matches = [] for par in parameters: if hp == par: matches.append(par) if len(matches) != 1: raise ValueError('{} matches found for ...
5,307,351
def initialize_MESSENGERdata(datapath): """Store data from IDL summary files in a database. The IDL summary files were provided by Aimee Merkel. Two tables are created for each species (Ca, Na, and Mg): *xxuvvsdata* and *xxuvvspointing* where xx is the species. See :doc:`database_fields` for a ...
5,307,352
def current_week() -> int: """Compute today's MAVEN science week number. """ return week_from_date(datetime.date.today())
5,307,353
def download_status(): """ 监测 global / local 是否执行完毕, 是否可以下载的状态 :return: """ print("download_status\n") if (Common.reg_status.get("global") == "true" and Common.reg_status.get( "local") == "no local") or ( Common.reg_status.get("global") == "true" and Common.reg_st...
5,307,354
def _organize_runs_by_lane(run_info): """Organize run information collapsing multiplexed items by lane. Lane is the unique identifier in a run and used to combine multiple run items on a fastq lane, separable by barcodes. """ items = _normalize_barcodes(run_info["details"]) items_by_lane = coll...
5,307,355
def test_wheel(virtualenv, cache_dir, use_static_requirements, src_dir): """ test building and installing a bdist_wheel package """ # Let's create the testing virtualenv with virtualenv as venv: venv.run(venv.venv_python, "setup.py", "clean", cwd=src_dir) venv.run( venv.v...
5,307,356
def can_embed_image(repo, fname): """True if we can embed image file in HTML, False otherwise.""" if not repo.info.embed_images: return False return ("." in fname) and ( fname.split(".")[-1].lower() in ["jpg", "jpeg", "png", "gif"] )
5,307,357
def write_verilog_sop(tt, filename, modulename='ckt'): """Writes the truth table to a verilog file by computing the SOP for each output""" inputs, outputs = _get_io_names(tt.num_inputs, tt.num_outputs) with open(filename, 'w') as f: f.write(_get_header(inputs, outputs, modulename)) for...
5,307,358
def pin_dependencies(): """ Create requirement*.txt """ with safe_cd(SRC): def write_reqs(filename: str, command: str): result = execute_get_text(command) lines = result.split("\n") with open(filename, "w") as output_reqs: for i, line in enumer...
5,307,359
def test_process_cod_filing(app, session): """Assert that an AR filling can be applied to the model correctly.""" from legal_api.models import Business, Director, Filing from entity_filer.worker import process_filing # vars payment_id = str(random.SystemRandom().getrandbits(0x58)) identifier = ...
5,307,360
def should_sync_model(model): """ whether or not the given Django model is something the i18n sync should process. We care about models that: - extend the Internationalizable model defined by this module - are not proxy models (unless the model explicitly opts in to translation) """ ...
5,307,361
def get_modal_triggers(offend_atoms, implied_modalities): """ :param offend_atoms: set of offending modal atoms at given w :param implied_box: set of tuples representing implied boxes and implied diamonds :return set of antecedent atoms in modal implications """ triggers = set() for atom i...
5,307,362
def plot_cm(conf_mat, labels, output_path): """ :param conf_mat: Confusion matrix with items counts :type conf_mat: numpy.ndarray :param labels: Symmetric row/column labels :type labels: list[str] :param output_path: Path to save generated figure. :type output_path: str :return: :...
5,307,363
def to_24bit_gray(mat: np.ndarray): """returns a matrix that contains RGB channels, and colors scaled from 0 to 255""" return np.repeat(np.expand_dims(_normalize(mat) * 255, axis=2), 3, axis=2).astype(np.uint8)
5,307,364
def _events_available_in_scheduled_slot(events, slots, X, **kwargs): """ Constraint that ensures that an event is scheduled in slots for which it is available """ slot_availability_array = lpu.slot_availability_array(slots=slots, events=event...
5,307,365
def check_client_ip_and_token_ip(request): """ Checking client ip with token ip """ if request.auth is None: return False if getattr(request.auth, 'payload') is None: return False token_real_ip = request.auth.payload.get(api_settings.USER_IP_CLAIM, '') real_ip = get_real_ip...
5,307,366
def _find_file_or_404(path, force): """Gets the full path and extension, or raises 404.""" try: return _find_file(path, force) except ValueError: abort(404)
5,307,367
def calc_qs(temp, pres): """ Elemental Function to determine the precipitation estimate for each value of tempreature and omega at each grid point. (func to be used in starmap multithreading) ------------------ Input : temp : temperature value at a grid point. omega_da : vertical velocit...
5,307,368
def exit_func(): """ Sends broadcast "exit" message to port 68 """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.sendto("exit", ("<broadcast>", IPORT)) sock.close()
5,307,369
def datetime_to_isoformat(dt): #============================= """ Convert a Python datetime to an ISO 8601 representation. :param dt: A Python :class:~`datetime.datetime`. :return: A string representation of the date and time formatted as ISO 8601. """ iso = dt.isoformat() if iso.endswith('+00:00'): retu...
5,307,370
def om_wrapper(J, initial_DVs, dJ, H, bounds, **kwargs): """ Custom optimization wrapper to use OpenMDAO optimizers with dolfin-adjoint. Follows the API as defined by dolfin-adjoint. Parameters ---------- J : object Function to compute the model analysis value at a design point...
5,307,371
def command(*args, **kwargs): """ Message command hook """ def _command_hook(func): add_plugin_function(plugin_function( func, callback_type.CMD, kwargs, inspect.stack()[2][1])) return func # this decorator is being used directly if len(args) == 1 and callable(args[0...
5,307,372
def deprecated(since, message='', name='', alternative='', pending=False, addendum='', removal=''): """ Decorator to mark a function or a class as deprecated. Parameters ---------- since : str The release at which this API became deprecated. This is required. mess...
5,307,373
def analyse_args( analyser: Analyser, opt_args: Args, sep: str, nargs: int, action: Optional[ArgAction] = None, ) -> Dict[str, Any]: """ 分析 Args 部分 Args: analyser: 使用的分析器 opt_args: 目标Args sep: 当前命令节点的分隔符 nargs: Args参数个数 action:...
5,307,374
def pytest_fixture_setup(fixturedef, request): """Support async fixtures.""" func = fixturedef.func # Fix aiolib fixture if fixturedef.argname == 'aiolib': def fix_aiolib(*args, **kwargs): """Convert aiolib fixture value to a tuple.""" aiolib = func(*args, **kwargs) ...
5,307,375
def ghia(reposlug, strategy, dry_run, config_auth, config_rules): """CLI tool for automatic issue assigning of GitHub issues""" token = config_auth ghia_patterns = config_rules ghia_patterns.set_strategy(strategy) ghia_patterns.set_dry_run(dry_run) req = GhiaRequests(token, reposlug) issue...
5,307,376
def test_aws_availability(): """ Test if aws s3 is available """ s3_status = os.system('aws s3 ls s3://stpubdata --request-payer requester > /tmp/aws.x') if s3_status == 0: s3_sync = 'cp' # As of late October 2018, 's3 sync' not working with 'stpubdata' else: s3_sync = False # ...
5,307,377
def calculate_character_error_rate(groundtruth, transcription): """Calculate character error rate""" groundtruth = normalize_sentence(groundtruth) transcription = normalize_sentence(transcription) return ed.eval(transcription, groundtruth) / len(groundtruth)
5,307,378
def notify(fut: Optional[asyncio.Future], result: Any = None) -> None: """Set :class:`asyncio.Future` result if future exists and is not done.""" # can be used to turn a Future into a lockless, single-consumer condition, # for multi-consumer use asyncio.Condition if fut is not None and not fut.done(): ...
5,307,379
def occupancy_over_time(output_dir, scenario_parameters, operator_attributes, dir_names, op_id, show=False, bin_size=DEF_TEMPORAL_RESOLUTION, evaluation_start_time=None, evaluation_end_time=None): """ this function creates a plot of the different vehicle occupancies over time :param oupu...
5,307,380
def read_file(): """Read kamonohashi config file. If not exists or invalid, raise Exception. :rtype: dict """ require_login = "Log into KAMONOHASHI first to use 'account login' command." if os.path.exists(config_file_path): logging.info('open config file %s', config_file_path) with ...
5,307,381
def parse_commamd (cmd): """Parses a command provide from the command line. Parses a command found on the command line. I Args: cmd: The command, e.g. `paste` or `type:hello` Returns: a list of command, data """ parts = cmd.split(":") data = ":".join(parts[1:]) return (parts[...
5,307,382
def _merge_dataset_polarity_scores() -> pd.DataFrame: """ Merges the dataset of news articles annotated with named entities with the pre-calculated polarity scores. """ dataset = _load_dataset_with_entities() polarity_scores = _load_polarity_scores() utils.get_logger().debug('Data loading: Adding polar...
5,307,383
def main(): """ This fuction calls json_analysis and creates cycle if user wants to do it again """ json_analysis(read_file()) cicle = input("Do you want to do it again? (Yes or No): ") if cicle == "Yes": main() else: pass
5,307,384
def read_dataset_json(path): """ Read playlists from dataset json file Parameters: - path - absolute path of the file """ with open(path, "r") as f: data = json.load(f) return data["playlists"]
5,307,385
def bench_local_versus_global_import(): """ Write two python files that loop over a test function that uses some external module. One version imports the dependency globally at startup, the other does a lazy import of the module inside the function. We time how long this takes over several tes...
5,307,386
def classification_set(target_dir, train_dirs, test_dirs): """ collect annotation files in target dir (target_dir/data_dir/class_dir/image_file) :param target_dir: root path that contains data set :param train_dirs: directory list used for train data :param test_dirs: directory list used for test da...
5,307,387
def createJntTweak(mesh, parentJnt, ctlParent): """Create a joint tweak Args: mesh (mesh): The object to deform with the tweak parentJnt (dagNode): The parent for the new joint ctlParent (dagNode): The parent for the control. """ if not isinstance(mesh, list): mesh = [me...
5,307,388
def test_product_misspelt_capture_error_task( infiles, outfile): """ FILE_PART mispelt as FILE_PART """ with open(outfile, "w") as p: pass
5,307,389
def _factor(lexer): """Return a factor expression.""" tok = _expect_token(lexer, FACTOR_TOKS) # '~' F toktype = type(tok) if toktype is OP_not: return ('not', _factor(lexer)) # '(' EXPR ')' elif toktype is LPAREN: expr = _expr(lexer) _expect_token(lexer, {RPAREN}) ...
5,307,390
def pad_string(data, size, padding_character=' ', direction='left'): """This new function will determine if it will pad to the left or the right by using an if statement.""" if direction == 'left': data.rjust(size, padding_character) elif data == 'right': data.ljust(size, padding_character) ...
5,307,391
def read_ascii_ply(filename): """Reads a PLY file encoded in ASCII format. NOTE: this util method is not intended to be comprehensive PLY reader and serves as part of demo application. Args: filename: path to a PLY file to read. Returns: numpy `[dim_1, 3]` array of vertices, `[dim_1, 3]` array of c...
5,307,392
def get_all_products(): """ Get all products from the database. """ products = Product.select() for product in products: text = f"{product.id} - {product.title} - {product.price} - {product.availability}" # noqa print(text) BOT.send_message(chat_id=CHAT_ID, text=text)
5,307,393
def to_sql(dialect: Dialect, model: SqlModel) -> str: """ Give the sql to query the given model :param dialect: SQL Dialect :param model: model to convert to sql :return: executable select query """ compiler_cache: Dict[str, List['SemiCompiledTuple']] = {} return _to_sql_materialized_nod...
5,307,394
def disttar_suffix(env, sources): """tar archive suffix generator""" env_dict = env.Dictionary() if env_dict.has_key("DISTTAR_FORMAT") and env_dict["DISTTAR_FORMAT"] in ["gz", "bz2"]: return ".tar." + env_dict["DISTTAR_FORMAT"] else: return ".tar"
5,307,395
def _data_qubit_parity(q: complex) -> bool: """To optimally interleave operations, it's useful to split into a checkerboard pattern.""" return (q.real // 2 + q.imag) % 2 != 0
5,307,396
def normalize(word): """ Normalizes the word for synsets() or Sentiwordnet[] by removing diacritics (PyWordNet does not take unicode) and replacing spaces with underscores. """ if not isinstance(word, str): word = str(word) if not isinstance(word, str): try: word = wo...
5,307,397
def test_put_copy_many_files_gcp(tmpdir, conn_cnx, db_parameters): """[gcp] Puts and Copies many files.""" # generates N files number_of_files = 10 number_of_lines = 1000 tmp_dir = generate_k_lines_of_n_files(number_of_lines, number_of_files, tmp_dir=str(tmpdir.mkdir('data'))) table_name = rando...
5,307,398
def get_traits_by_germplasm(germplasmId): # noqa: E501 """Returns all phenotypes for a germplasm that we have # noqa: E501 :param germplasmId: Unique database ID for the germplasm :type germplasmId: str :rtype: List[Phenotype] """ return 'do some magic!'
5,307,399