content
stringlengths
22
815k
id
int64
0
4.91M
def categorical_onehot_binarizer(feature, feature_scale=None, prefix='columns', dtype='int8'): """Transform between iterable of iterables and a multilabel format, sample is simple categories. Args: feature: pd.Series, sample feature. feature_scale: list, feature categories list. pre...
17,000
def mtp_file_list2(): """ Returns the output of 'mtp-files' as a Python list. Uses subprocess. """ cmd_str = "sudo mtp-files" try: result = subprocess.check_output(shlex.split(cmd_str)) except subprocess.CalledProcessError as e: log.error("Could not execute: %s" % str(e)) re...
17,001
def test_get_unexisting_hotel_01(): """ Test getting an unexisting hotel. """ last_hotel = client.get("/hotels/last/").json() hotel_id = last_hotel["hotel"]["id"] + 1 expect = { 'detail': "Hotel not found", } response = client.get(f"/hotels/{hotel_id}") assert response.status_code...
17,002
def test_harman_political(): """Test module harman_political.py by downloading harman_political.csv and testing shape of extracted data has 8 rows and 8 columns """ test_path = tempfile.mkdtemp() x_train, metadata = harman_political(test_path) try: assert x_train.shape == (8, 8) except: shutil...
17,003
def add_selfloops(adj_matrix: sp.csr_matrix, fill_weight=1.0): """add selfloops for adjacency matrix. >>>add_selfloops(adj, fill_weight=1.0) # return an adjacency matrix with selfloops # return a list of adjacency matrices with selfloops >>>add_selfloops(adj, adj, fill_weight=[1.0, 2.0]) Paramet...
17,004
def create_new_profile(ctx): """Create a configuration profile""" create_profile(ctx.obj.config_dir) config_files = load_config_profiles(ctx.obj.config_dir) config = choose_profile(config_files) es_client = setup_elasticsearch_client(config["okta_url"]) # Update the Dorothy class object with t...
17,005
def handle(event, _ctxt): """ Handle the Lambda Invocation """ response = { 'message': '', 'event': event } ssm = boto3.client('ssm') vpc_ids = ssm.get_parameter(Name=f'{PARAM_BASE}/vpc_ids')['Parameter']['Value'] vpc_ids = vpc_ids.split(',') args = { 'vpc_ids': vp...
17,006
def _get_indice_map(chisqr_set): """Find element with lowest chisqr at each voxel """ #make chisqr array of dims [x,y,z,0,rcvr,chisqr] chisqr_arr = np.stack(chisqr_set,axis=5) indice_arr = np.argmin(chisqr_arr,axis=5) return indice_arr
17,007
def _train(params, fpath, hyperopt=False): """ :param params: hyperparameters. Its structure is consistent with how search space is defined. See below. :param fpath: Path or URL for the training data used with the model. :param hyperopt: Use hyperopt for hyperparameter search during training. :retur...
17,008
def noct_synthesis(spectrum, freqs, fmin, fmax, n=3, G=10, fr=1000): """Adapt input spectrum to nth-octave band spectrum Convert the input spectrum to third-octave band spectrum between "fc_min" and "fc_max". Parameters ---------- spectrum : numpy.ndarray amplitude rms of the one-sided...
17,009
def get_model_prediction(model_input, stub, model_name='amazon_review', signature_name='serving_default'): """ no error handling at all, just poc""" request = predict_pb2.PredictRequest() request.model_spec.name = model_name request.model_spec.signature_name = signature_name request.inputs['input_in...
17,010
def test_organization_4(base_settings): """No. 4 tests collection for Organization. Test File: organization-example-mihealth.json """ filename = base_settings["unittest_data_dir"] / "organization-example-mihealth.json" inst = organization.Organization.parse_file( filename, content_type="appl...
17,011
def edit_image_data(item): """Edit image item data to file""" try: # Spyder 2 from spyderlib.widgets.objecteditor import oedit except ImportError: # Spyder 3 from spyder.widgets.variableexplorer.objecteditor import oedit oedit(item.data)
17,012
def _make_feature_stats_proto( common_stats, feature_name, q_combiner, num_values_histogram_buckets, is_categorical, has_weights ): """Convert the partial common stats into a FeatureNameStatistics proto. Args: common_stats: The partial common stats associated with a feature. feature_name: T...
17,013
def serial_chunked_download( d_obj: Download, end_action: Optional[Action] = None, session: Optional[requests.Session] = None, *, progress_data: Optional[DownloadProgressSave] = None, start: int = 0, end: int = 0, chunk_id: Optional[int] = 0, ) -> bool: """Downloads a file using a si...
17,014
def get_device(): """ Returns the id of the current device. """ c_dev = c_int_t(0) safe_call(backend.get().af_get_device(c_pointer(c_dev))) return c_dev.value
17,015
def plotLatentsSweep(yhat,nmodels=1): """plotLatentsSweep(yhat): plots model latents and a subset of the corresponding stimuli, generated from sweepCircleLatents() ---e.g.,--- yhat, x = sweepCircleLatents(vae) plotCircleSweep(yhat,x) alternatively, plotLatents...
17,016
def calc_lipophilicity(seq, method="mean"): """ Calculates the average hydrophobicity of a sequence according to the Hessa biological scale. Hessa T, Kim H, Bihlmaier K, Lundin C, Boekel J, Andersson H, Nilsson I, White SH, von Heijne G. Nature. 2005 Jan 27;433(7024):377-81 The Hessa scale has been calcul...
17,017
def get_enrollments(username, include_inactive=False): """Retrieves all the courses a user is enrolled in. Takes a user and retrieves all relative enrollments. Includes information regarding how the user is enrolled in the the course. Args: username: The username of the user we want to retriev...
17,018
async def connections_accept_request(request: web.BaseRequest): """ Request handler for accepting a stored connection request. Args: request: aiohttp request object Returns: The resulting connection record details """ context = request.app["request_context"] outbound_handl...
17,019
def test_list_of_tasks(): """ Test that a list of tasks can be set as a switch condition """ with Flow(name="test") as flow: condition = Condition() true_branch = [SuccessTask(), SuccessTask()] false_branch = SuccessTask() ifelse(condition, true_branch, false_branch) ...
17,020
def nearest(x, base=1.): """ Round the inputs to the nearest base. Beware, due to the nature of floating point arithmetic, this maybe not work as you expect. INPUTS x : input value of array OPTIONS base : number to which x should be rounded """ return np.round...
17,021
def sort_nesting(list1, list2): """Takes a list of start points and end points and sorts the second list according to nesting""" temp_list = [] while list2 != temp_list: temp_list = list2[:] # Make a copy of list2 instead of reference for i in range(1, len(list1)): if list2[i] > ...
17,022
def confusion_matrix(Y_hat, Y, norm=None): """ Calculate confusion matrix. Parameters ---------- Y_hat : array-like List of data labels. Y : array-like List of target truth labels. norm : {'label', 'target', 'all', None}, default=None Normalization on resulting matrix. Must be one of: - 'l...
17,023
def reroot(original_node: Tree, new_node: Tree): """ :param original_node: the node in the original tree :param new_node: the new node to give children new_node should have as chldren, the relations of original_node except for new_node's parent """ new_node.children = [ Tree(relation.l...
17,024
def test_precursormz_match_tolerance2_array(): """Test with array and tolerance=2.""" spectrum_1 = Spectrum(mz=numpy.array([], dtype="float"), intensities=numpy.array([], dtype="float"), metadata={"precursor_mz": 100.0}) spectrum_2 = Spectrum(mz=numpy.arr...
17,025
def thue_morse_sub(n): """ generate Thue-Morse sequence using substitution system: 0 -> 01 1 -> 10 See http://mathworld.wolfram.com/Thue-MorseSequence.html""" pass
17,026
def test_calculate_results(scoring, expected_results_columns): """Test the calculation of the experiment's results.""" MSCV.set_params(scoring=scoring) scoring_cols = _define_binary_experiment_parameters(MSCV)[1] results = _calculate_results(MSCV, DATASETS, scoring_cols) assert len(results) == len(P...
17,027
def update_users(): """Sync LDAP users with local users in the DB.""" log_uuid = str(uuid.uuid4()) start_time = time.time() patron_cls = current_app_ils.patron_cls patron_indexer = PatronBaseIndexer() invenio_users_updated_count = 0 invenio_users_added_count = 0 # get all CERN users f...
17,028
def GenerateDictionary(input_file, ngraph_size): """Generates the G2P (G2NG) dictionary.""" words = set() with io.open(input_file, mode='rt', encoding='utf-8') as text: for line in text: for word in line.split(): words.add(word) words = list(words) words.sort() if 'SENTNCE-END' in words: ...
17,029
def gen_maven_artifact( name, artifact_name, artifact_id, artifact_target, javadoc_srcs, packaging = "jar", artifact_target_libs = [], is_extension = False): """Generates files required for a maven artifact. Args: name: The name associated...
17,030
def main(): """ Main - entry point for service node """ log.info("Service node initializing") app = create_app() # run app using either socket or tcp sn_socket = config.getCmdLineArg("sn_socket") if sn_socket: # use a unix domain socket path # first, make sure the sock...
17,031
def test_help(tool_cls): """ Check that all command line tools have a --help option that explains the usage. As per argparse default, this help text always starts with `usage:`. """ tool = tool_cls() try: tool.run("--help") except SystemExit as e: pass if not has...
17,032
def opt(dfs, col='new', a=1, b=3, rlprior=None, clprior=None): """Returns maximum likelihood estimates of the model parameters `r` and `c`. The optimised parameters `r` and `c` refer to the failure count of the model's negative binomial likelihood function and the variance factor introduced by each pre...
17,033
def unpackage_datasets(dirname, dataobject_format=False): """ This function unpackages all sub packages, (i.e. train, valid, test) You should use this function if you want everything args: dirname: directory path that has the train, valid, test folders in it dataobject_format: used for d...
17,034
def test_parse_entry_brackets1() -> None: """ """ entry = "{house,building, skyscraper, booth, hovel, tower, grandstand}" classes = parse_entry(entry) gt_classes = [ "house", "building", "skyscraper", "booth", "hovel", "tower", "grandstand", ...
17,035
def get_command_view( is_running: bool = False, stop_requested: bool = False, commands_by_id: Sequence[Tuple[str, cmd.Command]] = (), ) -> CommandView: """Get a command view test subject.""" state = CommandState( is_running=is_running, stop_requested=stop_requested, commands_...
17,036
def test_read_python_code(mock_bytes_to_intel_hex, mock_read_flash): """.""" python_code_hex = "\n".join( [ ":020000040003F7", ":10E000004D509600232041646420796F7572205032", ":10E010007974686F6E20636F646520686572652E21", ":10E0200020452E672E0A66726F6D206D6...
17,037
def _split_by_size(in_fastq, split_size, out_dir): """Split FASTQ files by a specified number of records. """ existing = _find_current_split(in_fastq, out_dir) if len(existing) > 0: return existing def new_handle(num): base, ext = os.path.splitext(os.path.basename(in_fastq)) ...
17,038
def get_node_ip_addresses(ipkind): """ Gets a dictionary of required IP addresses for all nodes Args: ipkind: ExternalIP or InternalIP or Hostname Returns: dict: Internal or Exteranl IP addresses keyed off of node name """ ocp = OCP(kind=constants.NODE) masternodes = ocp.g...
17,039
def code_block( code: str = None, path: str = None, language_id: str = None, title: str = None, caption: str = None ): """ Adds a block of syntax highlighted code to the display from either the supplied code argument, or from the code file specified by the path ar...
17,040
def fill_cache(msg="Fetching cache"): """Fill the cache with the packages.""" import os # pylint: disable=import-outside-toplevel import requests # pylint: disable=import-outside-toplevel from rich.progress import Progress # pylint: disable=import-outside-toplevel all_packages_url = f"{base_url...
17,041
def house_filter(size, low, high): """ Function that returns the "gold standard" filter. This window is designed to produce low sidelobes for Fourier filters. In essence it resembles a sigmoid function that smoothly goes between zero and one, from short ...
17,042
def PToData(inGFA, data, err): """ Copy host array to data Copys data from GPUFArray locked host array to data * inFA = input Python GPUFArray * data = FArray containing data array * err = Obit error/message stack """ ################################################################...
17,043
def download_vendor_image(image): """ Downloads specified vendor binary image Args: image (str): Path of image filename to begin downloading Returns: """ # TODO Prevent sending hidden files return send_from_directory(os.path.join(_AEON_TOPDIR, 'vendor_images'), image)
17,044
def test_atomic_string_length_4_nistxml_sv_iv_atomic_string_length_5_1(mode, save_output, output_format): """ Type atomic/string is restricted by facet length with value 1000. """ assert_bindings( schema="nistData/atomic/string/Schema+Instance/NISTSchema-SV-IV-atomic-string-length-5.xsd", ...
17,045
def maker(sql_connection, echo=False): """ Get an sessionmaker object from a sql_connection. """ engine = get_engine(sql_connection, echo=echo) m = orm.sessionmaker(bind=engine, autocommit=True, expire_on_commit=False) return m
17,046
def ntohs(*args,**kw): """ntohs(integer) -> integer Convert a 16-bit integer from network to host byte order.""" pass
17,047
def test_auth(request): """Tests authentication worked successfuly.""" return Response({"message": "You successfuly authenticated!"})
17,048
def streak_condition_block() -> Block: """ Create block with 'streak' condition, when rotation probability is low and target orientation repeats continuously in 1-8 trials. :return: 'Streak' condition block. """ return Block(configuration.STREAK_CONDITION_NAME, streak_rotations...
17,049
def resolve_appinstance(request, appinstanceid, permission='base.change_resourcebase', msg=_PERMISSION_MSG_GENERIC, **kwargs): """ Resolve the document by the provided primary key and check the optional permissio...
17,050
def test_star(genome, force): """Create star index.""" assert os.path.exists(genome.filename) force = True if force == "overwrite" else False if cmd_ok("STAR"): p = StarPlugin() p.after_genome_download(genome) dirname = os.path.dirname(genome.filename) index_dir = os.pat...
17,051
def statementTVM(pReact): """Use this funciton to produce the TVM statemet""" T,V,mass = pReact.T,pReact.volume,pReact.mass statement="\n{}: T: {:0.2f} K, V: {:0.2f} m^3, mass: {:0.2f} kg".format(pReact.name,T,V,mass) return statement
17,052
def fill_NaNs_with_nearest_neighbour(data, lons, lats): """At each depth level and time, fill in NaN values with nearest lateral neighbour. If the entire depth level is NaN, fill with values from level above. The last two dimensions of data are the lateral dimensions. lons.shape and lats.shape = (data.s...
17,053
def transform_type_postorder(type_signature, transform_fn): """Walks type tree of `type_signature` postorder, calling `transform_fn`. Args: type_signature: Instance of `computation_types.Type` to transform recursively. transform_fn: Transformation function to apply to each node in the type tree ...
17,054
def get_job_output(job_id: Optional[pulumi.Input[str]] = None, location: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[Optional[str]]] = None, view: Optional[pulumi.Input[Optional[str]]] = None, opts: Optional[pulumi.Invoke...
17,055
def check_stack_feature(stack_feature, stack_version): """ Given a stack_feature and a specific stack_version, it validates that the feature is supported by the stack_version. :param stack_feature: Feature name to check if it is supported by the stack. For example: "rolling_upgrade" :param stack_version: Versio...
17,056
def test_publish_does_not_exist(client, mocked_apis): """ Test behavior if a release is published and one of the summary rows do not exist """ db = boto3.resource('dynamodb') release_table = db.Table('release-summary') study_table = db.Table('study-summary') with patch('requests.get') a...
17,057
def get_random_action_weights(): """Get random weights for each action. e.g. [0.23, 0.57, 0.19, 0.92]""" return np.random.random((1, NUM_ACTIONS))
17,058
def rpg_radar2nc(data, path, larda_git_path, **kwargs): """ This routine generates a daily NetCDF4 file for the RPG 94 GHz FMCW radar 'LIMRAD94'. Args: data (dict): dictionary of larda containers path (string): path where the NetCDF file is stored """ dt_start = h.ts_to_dt(data['Ze...
17,059
def load_ssl_user_from_request(request): """ Loads SSL user from current request. SSL_CLIENT_VERIFY and SSL_CLIENT_S_DN needs to be set in request.environ. This is set by frontend httpd mod_ssl module. """ ssl_client_verify = request.environ.get('SSL_CLIENT_VERIFY') if ssl_client_verify != ...
17,060
def redirect_stream_via_fd(stream, to=os.devnull): """ Redirects given stream to another at file descriptor level. """ assert stream is not None stream_fd = _fileno(stream) # copy stream_fd before it is overwritten # NOTE: `copied` is inheritable on Windows when duplicating a standard stream w...
17,061
def test_to_wkt(): """ Tilsvarende test_from_wkt() """ with pytest.raises(Exception): geometry.to_wkt({"coordinates": [10.2, 56.1], "type": "Punkt"})
17,062
def get_all_users(): """Gets all users""" response = user_info.get_all_users() return jsonify({'Users' : response}), 200
17,063
def open_mailbox_maildir(directory, create=False): """ There is a mailbox here. """ return lazyMaildir(directory, create=create)
17,064
def TANH(*args) -> Function: """ Returns the hyperbolic tangent of any real number. Learn more: https//support.google.com/docs/answer/3093755 """ return Function("TANH", args)
17,065
def update_item_orders(begin_order, t_task, projects, api, cmd_count): """Update tasks' order that are greater than `begin_order`.""" for task in t_tasks.values(): if is_in_the_same_proj(task, projects) and task['item_order'] >= begin_order: api.items.get_by_id(task['id']).update(item_order=...
17,066
def value_frequencies_chart_from_blocking_rules( blocking_rules: list, df: DataFrame, spark: SparkSession, top_n=20, bottom_n=10 ): """Produce value frequency charts for the provided blocking rules Args: blocking_rules (list): A list of blocking rules as specified in a Splink settings d...
17,067
def getOfflineStockDataManifest(): """Returns manifest for the available offline data. If manifest is not found, creates an empty one. Returns: A dict with the manifest. For example: {'STOCK_1': {'first_available_date': datetime(2016, 1, 1), 'last_available_date': ...
17,068
def count_tags(request, t, t_old, tag_dict): """ при сохранении документа пересчитать кол-во тегов в облаке t-скорее всего тег вызывается в save_tags 1) получает документ где хранится облако тегов 2) идем по тегам и если есть """ tags = request.db.conf.find_one({"_id":'tags_'+tag_dict[4:]}) # получает докумен...
17,069
def test_dbt_build_select(profiles_file, dbt_project_file, model_files): """Test execution of DbtBuildOperator selecting all models.""" op = DbtBuildOperator( task_id="dbt_task", project_dir=dbt_project_file.parent, profiles_dir=profiles_file.parent, select=[str(m.stem) for m in ...
17,070
def align_buf(buf: bytes, sample_width: bytes): """In case of buffer size not aligned to sample_width pad it with 0s""" remainder = len(buf) % sample_width if remainder != 0: buf += b'\0' * (sample_width - remainder) return buf
17,071
def update_alert(): """ Make Rest API call to security graph to update an alert """ if flask.request.method == 'POST': flask.session.pop('UpdateAlertData', None) result = flask.request.form flask.session['VIEW_DATA'].clear() alert_data = {_: result[_] for _ in result} # Iterate ...
17,072
def simulate_bet(odds, stake): """ Simulate the bet taking place assuming the odds accurately represent the probability of the event :param odds: numeric: the odds given for the event :param stake: numeric: the amount of money being staked :return: decimal: the returns from the bet """ proba...
17,073
def lrcn(num_classes, lrcn_time_steps, lstm_hidden_size=200, lstm_num_layers=2): """ Args: num_classes (int): Returns: torch.nn.modules.module.Module """ class TimeDistributed(nn.Module): def __init__(self, layer, time_steps): super(TimeDistributed, self).__init...
17,074
def index_document(connection, doc_id, content): """对document建立反向索引""" words = tokenize(content) pipe = connection.pipeline(True) for word in words: pipe.sadd('idx:' + word, doc_id) return len(pipe.execute())
17,075
def get_incar_magmoms(incarpath,poscarpath): """ Read in the magnetic moments in the INCAR Args: incarpath (string): path to INCAR poscarpath (string): path to POSCAR Returns: mof_mag_list (list of floats): magnetic moments """ mof_mag_list = [] init_mof = read(poscarpath) with open(incarpath,'r') as in...
17,076
def add_security_groups(t): """Given a template will add database and web server security groups. These security groups will be able accessibly externally and from private subnets.""" t.add_resource( SecurityGroup( 'LinuxServer', GroupDescription='Enable SSH access via port 2...
17,077
def main(config_path=None): """ The main entry point for the unix version of dogstatsd. """ # Deprecation notice from utils.deprecations import deprecate_old_command_line_tools deprecate_old_command_line_tools() COMMANDS_START_DOGSTATSD = [ 'start', 'stop', 'restart', ...
17,078
def test_get_file_succeeds_with_valid_resource_path(client, request_headers): """ Tests that response is okay when valid resource path is requested. Args: client (FlaskClient): a test client created by a fixture. request_headers (dict): a header created by a fixture. """ res = clie...
17,079
def remove_report_from_plist(plist_file_obj, skip_handler): """ Parse the original plist content provided by the analyzer and return a new plist content where reports were removed if they should be skipped. If the remove failed for some reason None will be returned. WARN !!!! If the 'files'...
17,080
def writeAllSynchronous( tagPaths, # type: List[String] values, # type: List[Any] timeout=45000, # type: Optional[int] ): # type: (...) -> None """Performs a synchronous write to multiple tags. Synchronous means that execution will not continue until this function has completed, so you w...
17,081
def assert_allclose( actual: Tuple[float, numpy.float64], desired: Tuple[float, numpy.float64] ): """ usage.statsmodels: 2 """ ...
17,082
def _resize_event(event, params): """Handle resize event.""" size = ','.join([str(s) for s in params['fig'].get_size_inches()]) set_config('MNE_BROWSE_RAW_SIZE', size, set_env=False) _layout_figure(params)
17,083
def propagate_memlets_sdfg(sdfg): """ Propagates memlets throughout an entire given SDFG. :note: This is an in-place operation on the SDFG. """ # Reset previous annotations first reset_state_annotations(sdfg) for state in sdfg.nodes(): propagate_memlets_state(sdfg, state) prop...
17,084
def doctest_profile(): """Test for profile. >>> @profilehooks.profile ... def sample_fn(x, y, z): ... print("%s %s %s" % (x, y, z)) ... return x + y * z You can call that function normally >>> r = sample_fn(1, 2, z=3) 1 2 3 >>> r 7 ...
17,085
def print_arguments(args): """none""" print('----------- Configuration Arguments -----------') for arg, value in sorted(vars(args).items()): print('%s: %s' % (arg, value)) print('------------------------------------------------')
17,086
def isTask(item): # pragma: no cover """Is the given item an OmniFocus task?""" return item.isKindOfClass_(taskClass)
17,087
def add2grouppvalue_real1(): """ add2grouppvalue_real1 description: Uses the raw data from real_data_1.csv to compute p-values for 2 group comparisons on a bunch of pairs of groups and using all 3 stats tests Test fails if there are any errors or if the shape of any of the following sta...
17,088
def cox_cc_loss(g_case: Tensor, g_control: Tensor, shrink : float = 0., clamp: Tuple[float, float] = (-3e+38, 80.)) -> Tensor: """Torch loss function for the Cox case-control models. For only one control, see `cox_cc_loss_single_ctrl` instead. Arguments: g_case {torch.Tensor} --...
17,089
def vector_field(mesh, v): """ Returns a np.array with values specified by `v`, where `v` should be a iterable of length 3, or a function that returns an iterable of length 3 when getting the coordinates of a cell of `mesh`. """ return field(mesh, v, dim=3)
17,090
def is_fav_recipe(request): """ Handles the requests from /ajax/is_fav_recipe/ Checks if a :model:`matega.recipe` is a saved recipe for a :model:'matega.user' **Data** Boolean if :model:`matega.recipe` is a saved recipe for :model:'matega.user' """ user_id = int(request.GET.get('user_id', N...
17,091
def people_interp(): """ <enumeratedValueSet variable="People"> <value value="500"/> </enumeratedValueSet> Integer between 1 and 500 """ return f'<enumeratedValueSet variable="People"> <value value="%s"/> </enumeratedValueSet>'
17,092
def check_lint(path, lint_name="md"): """lint命令及检测信息提取,同时删除中间文档xxx_lint.md或者xxx_lint.py""" error_infos = [] lint_ext = "_lint.md" if lint_name == "md" else "_lint.py" check_command = "mdl -s mdrules.rb" if lint_name == "md" else "pylint -j 4" if lint_name == "md": convert_to_markdown(p...
17,093
def through_omas_s3(ods, method=['function', 'class_method'][1]): """ Test save and load S3 :param ods: ods :return: ods """ filename = 'test.pkl' if method == 'function': save_omas_s3(ods, filename, user='omas_test') ods1 = load_omas_s3(filename, user='omas_test') els...
17,094
def read_packages(filename): """Return a python list of tuples (repository, branch), given a file containing one package (and branch) per line. Comments are excluded """ lines = load_order_file(filename) packages = [] for line in lines: if "," in line: # user specified a branch ...
17,095
def find_min(x0, capacities): """ (int list, int list) --> (int list, int) Find the schedule that minimizes the passenger wait time with the given capacity distribution Uses a mixture of Local beam search and Genetic Algorithm Returns the min result """ scores_and_schedules = [] # ...
17,096
def test_spectrum_getters_return_copies(): """Test if getters return (deep)copies so that edits won't change the original entries.""" spectrum = Spectrum(mz=numpy.array([100.0, 101.0], dtype="float"), intensities=numpy.array([0.4, 0.5], dtype="float"), metadata={"...
17,097
def delta_eta_with_gaussian(analysis: "correlations.Correlations") -> None: """ Plot the subtracted delta eta near-side. """ # Setup fig, ax = plt.subplots(figsize = (8, 6)) for (attribute_name, width_obj), (correlation_attribute_name, correlation) in \ zip(analysis.widths_delta_eta, analys...
17,098
def mult_by_scalar_func( raster_path, scalar, target_nodata, target_path): """Multiply raster by scalar.""" nodata = pygeoprocessing.get_raster_info(raster_path)['nodata'][0] pygeoprocessing.raster_calculator( [(raster_path, 1), (scalar, 'raw'), (nodata, 'raw'), (target_nodata, 'raw...
17,099