content
stringlengths
22
815k
id
int64
0
4.91M
def move_songpos(context, songpos, to): """See :meth:`move_range`.""" songpos = int(songpos) to = int(to) context.core.tracklist.move(songpos, songpos + 1, to)
18,700
def photo_fit_bprior(time, ptime, nflux, flux_err, guess_transit, guess_ew, rho_star, e, w, directory, nwalk, nsteps, ndiscard, plot_transit=True, plot_burnin=True, plot_corner=True, plot_Tburnin=True, plot_Tcorner=True): """Fit eccentricity for a planet. Applies Bayesian beta-dist prior from Kipping 2014 ...
18,701
def ClientInit(): """Run all startup routines for the client.""" registry_init.RegisterClientActions() stats_collector_instance.Set(default_stats_collector.DefaultStatsCollector()) config_lib.SetPlatformArchContext() config_lib.ParseConfigCommandLine() client_logging.LogInit() all_parsers.Register() ...
18,702
def runSwitchVerifier(node_address): """Wrap the SwitchVerifier binary. Configuration parameters of the switchVerifier binary are retrieved from the driverHPESettings class. """ logger.debug("Running switchVerifier binary") # Run switchVerifier -c config.json -k pub.key -conf refconf -json [ip...
18,703
def unary_op(op, suty): """/Users/mahmoud/src/py-in-java/pycryptodome/lib/transform.py /Users/mahmoud/src/py2star/transform1.py Converts a method like: ``self.failUnless(True)`` to asserts.assert_that(value).is_true() """ sut = _codegen.code_for_node(suty.value) return cst.parse_expression...
18,704
def canny_edges(image, minedges=5000, maxedges=15000, low_thresh=50, minEdgeRadius=20, maxEdgeRadius=None): """ Compute Canny edge detection on an image """ t0 = time.time() dx = ndimage.sobel(image,0) dy = ndimage.sobel(image,1) mag = numpy.hypot(dx, dy) mag = mag / mag.max() ort = numpy.arctan2(dy, dx) e...
18,705
def test_exception_connection_error(port): """ ConnectionError exception raising test. Wrong network address, firewall or rest api connection limit ... """ array = hpestorapi.StoreServ('wrong-address', 'user', 'password', ssl=False, port=port) with pytest.raises(requests.exceptions.ConnectionErr...
18,706
def test_classifier(executable): """Test the classification task.""" num_machines = 2 data = create_data(task='binary-classification') partitions = np.array_split(data, num_machines) train_params = { 'objective': 'binary', 'num_machines': num_machines, } clf = DistributedMock...
18,707
def reduce_false_positives(txt_file_path, mean_brightness_retained_patches, max_fp, output_folder_path, out_filename, mapping_centers_masks): """If more than "max_fp" candide centers were predicted, this function reduces this number to exactly "max_fp", retaining only the most probable (i.e. brightest) candidat...
18,708
def scale_matrix(t): """ Given a d-dim vector t, returns (d+1)x(d+1) matrix M such that left multiplication by M on a homogenuous (d+1)-dim vector v scales v by t (assuming the last coordinate of v is 1). """ t = asarray(t).ravel() d = len(t) m = identity(d+1) for i in xrange(d): ...
18,709
def validate_rule_paths(sched: schedule.Schedule) -> schedule.Schedule: """A validator to be run after schedule creation to ensure each path contains at least one rule with a temperature expression. A ValueError is raised when this check fails.""" for path in sched.unfold(): if path.is_final an...
18,710
def descendants(ctx, *args, **kwargs): """Recursively get all children of an Interface.""" callbacks.list_subcommand( ctx, display_fields=DISPLAY_FIELDS, my_name=ctx.info_name )
18,711
def check_input_array(xarr,shape=None,chunks=None,\ grid_location=None,ndims=None): """Return true if arr is a dataarray with expected shape, chunks at grid_location attribute. Raise an error if one of the tests fails. Parameters ---------- xarr : xarray.DataArray xarra...
18,712
def test_load_dump(engine): """_load and _dump should be symmetric""" user = User(id="user_id", name="test-name", email="email@domain.com", age=31, joined=datetime.datetime.now(datetime.timezone.utc)) serialized = { "id": {"S": user.id}, "age": {"N": "31"}, "name": {"...
18,713
def ancestor_width(circ, supp, verbose=False): """ Args: circ(list(list(tuple))): Circuit supp(list): List of integers Returns: int: Width of the past causal cone of supp """ circ_rev= circ[::-1] supp_coded = 0 for s in supp: supp_coded |= (1<<s) for uni...
18,714
def find_genes( interactions, fragment_database_fp, gene_bed_fp, gene_dict_fp, output_dir, suppress_intermediate_files=False): """Identifies genes in fragments that interact with SNP fragments. Args: interactions: The dictionary fragements that interact w...
18,715
def get_bprop_argmax(self): """Generate bprop for Argmax""" def bprop(x, out, dout): return (zeros_like(x),) return bprop
18,716
def register_extensions(app): """Register models.""" db.init_app(app) login_manager.init_app(app) # flask-admin configs admin.init_app(app) admin.add_view(ModelView(User)) admin.add_view(ModelView(Role)) login_manager.login_view = 'auth.login' @login_manager.user_loader def lo...
18,717
def get_description(): """ Return a dict describing how to call this plotter """ desc = dict() desc['cache'] = 86400 desc['description'] = """This plot presents a histogram of the change in some observed variable over a given number of hours.""" desc['arguments'] = [ dict(type='zstation'...
18,718
def extract_content(basepath, exclude=None): """ Get all non-comment lines from BUILD files under the given basepath. :param Path basepath: The path to recursively crawl :param list exclude: The paths to exclude :rtype: str """ if basepath.is_file(): content = basepath.read_text(err...
18,719
def read_format_from_metadata(text, ext): """Return the format of the file, when that information is available from the metadata""" metadata = read_metadata(text, ext) rearrange_jupytext_metadata(metadata) return format_name_for_ext(metadata, ext, explicit_default=False)
18,720
def request_requires_retry(err: Exception) -> bool: """Does the error mean that a retry should be performed?""" if not isinstance(err, ClientError): return False code = err.response.get('Error', {}).get('Code', '').lower() message = err.response.get('Error', {}).get('Message', '') # This cov...
18,721
def update_DMSP_ephemeris(self, ephem=None): """Updates DMSP instrument data with DMSP ephemeris Parameters ---------- ephem : pysat.Instrument or NoneType dmsp_ivm_ephem instrument object Returns --------- Updates 'mlt' and 'mlat' """ # Ensure the right ephemera is loade...
18,722
def show_all_in_dict(dict): """ Print all the key in dict. Arguments: dict -- a dictionary needed to be print it's key. """ print('We know the birthdays of:') for key in dict: print(key)
18,723
def to_jd(y, m, d, method=None): """Convert Armenian date to Julian day count. Use the method of Sarkawag if requested.""" # Sanity check values legal_date(y, m, d, method) yeardays = (m - 1) * 30 + d if method == "sarkawag": # Calculate things yeardelta = y - 533 leapdays = ...
18,724
def unitVector(vector): """ Returns the unit vector of a given input vector. Params: vector -> input vector. Returns: numpy.array(). """ # Divide the input vector by its magnitude. return vector / np.linalg.norm(vector)
18,725
def find_poly_intervals(p): """ Find the intervals of 1D-polynomial (numpy.polynomial) where the polynomial is negative. """ assert(np.abs(p.coef[-1]) > 1e-14) r=p.roots() # remove imaginary roots, multiple roots, and sort r=np.unique(np.extract(np.abs(r.imag)<1e-14, r).real) ints = [] ...
18,726
def user_numforms_next(*args): """ user_numforms_next(p) -> user_numforms_iterator_t Move to the next element. @param p (C++: user_numforms_iterator_t) """ return _ida_hexrays.user_numforms_next(*args)
18,727
def test_task_test_all(): """Test task_test_all.""" result = task_test_all() actions = result['actions'] assert len(actions) == 1 assert str(actions[0]).endswith('" --ff -vv')
18,728
def main(): """ annotate a file with the neearest features in another. """ p = argparse.ArgumentParser(description=__doc__, prog=sys.argv[0]) p.add_argument("-a", dest="a", help="file to annotate") p.add_argument("-b", dest="b", help="file with annotations") p.add_argument("--upstream", dest...
18,729
def list_cms() -> Dict[Text, CalculationModule]: """List all cms available on a celery queue.""" app = get_celery_app() try: app_inspector = app.control.inspect() nodes = app_inspector.registered("cm_info") except (redis.exceptions.ConnectionError, kombu.exceptions.OperationalError) as e...
18,730
def _a_in_b(first, second): """Check if interval a is inside interval b.""" return first.start >= second.start and first.stop <= second.stop
18,731
def validate(val_loader, c_model, r_model, c_criterion, r_criterion): """ One epoch's validation. : param val_loader: DataLoader for validation data : param model: model : param criterion: MultiBox loss : return: average validation loss """ c_model.eval() # eval mode disables dropout ...
18,732
def test_monotonic(example_df): """Columns that should be monotonic but are not""" example_df['cycle_number'] = [2, 1] with raises(ValueError) as exc: CyclingData.validate_dataframe(example_df) assert 'monotonic' in str(exc) example_df['cycle_number'] = [1, 1] CyclingData.validate_dataf...
18,733
def radixsort(list, k=10, d=0): """ Sort the list. This method has been used to sort punched cards. @param k: number different characters in a number (base) @param d: maximum number of digits of list elements """ if len(list) == 0: return [] elif d == 0: d = max...
18,734
def create_datacatalog(glue_client): """ used to create a data catalog """ # TODO: # check if this is needed # and to be improved accordingly response = glue_client.create_data_catalog( Name="string", Type="LAMBDA" | "GLUE" | "HIVE", Description="Test catalog", ...
18,735
def feature_stat_str(x, y, delimiter='~', n_lines=40, width=20): """Compute the input feature's sample distribution in string format for printing. The distribution table returned (in string format) concains the sample sizes, event sizes and event proportions of each feature value. Parameters -----...
18,736
def dice_similarity_u(output, target): """Computes the Dice similarity""" #batch_size = target.size(0) total_dice = 0 output = output.clone() target = target.clone() # print('target:',target.sum()) for i in range(1, output.shape[1]): target_i = torch.zeros(target.shape) targe...
18,737
def establish_service(): """ Authorizes and establishes the Gmail service using the API. :return: authorized Gmail service instance """ # If modifying these scopes, delete the file token.pickle. SCOPES = ['https://www.googleapis.com/auth/gmail.send'] creds = None # The file token.pickl...
18,738
def get_meaning(searchterm): """ Fetches the meaning of the word specified :param searchterm: the word for which you want to fetch the meaning :return: json object of the meaning """ # finds the input field by id in the webpage sbox = driver.find_element_by_id('word') sbox.clear(...
18,739
def set_permissions_manager(permissions_manager): """Set the IPermissionsManager implementation to use.""" global _permissions_manager _permissions_manager = permissions_manager
18,740
def main(): """Main logic""" # logger.info("Check hour range: {}:00:00 - {}:00:00".format(start_hour, end_hour)) with open(LIST_YAML_PATH, encoding="utf8") as list_file: yml_data = yaml.load(list_file, Loader=yaml.FullLoader) # Add schedule for each item for item_obj in yml_data: #...
18,741
def cat_artifact(cache_path, pk, artifact_rpath): """Print the contents of a cached artefact.""" db = get_cache(cache_path) with db.cache_artefacts_temppath(pk) as path: artifact_path = path.joinpath(artifact_rpath) if not artifact_path.exists(): click.secho("Artifact does not ex...
18,742
def test_xdawn_picks(): """Test picking with Xdawn.""" data = np.random.RandomState(0).randn(10, 2, 10) info = create_info(2, 1000., ('eeg', 'misc')) epochs = EpochsArray(data, info) xd = Xdawn(correct_overlap=False) xd.fit(epochs) epochs_out = xd.apply(epochs)['1'] assert epochs_out.inf...
18,743
def get_state(entity_id): """ Return the state of an entity """ try: entity_state = '' entity_state = Gb.hass.states.get(entity_id).state if entity_state in IOS_TRIGGER_ABBREVIATIONS: state = IOS_TRIGGER_ABBREVIATIONS[entity_state] else: state = G...
18,744
def show(): """ show source data """ SUP = "".join(str(i) * 10 for i in range(ALL//10))[:ALL] METR = "0123456789" * (ALL//10) print ("\n" + SUP) print (METR, EOL) for s in a: print (" " * (s[1]-1), "*" * s[0], EOL, end="") print (METR, "\n"+SUP, EOL)
18,745
def loss_eval(net, data, labels, numclass=2, rs=40): """Evaluate the network performance on test samples""" loss = np.zeros([labels.shape[0]]) for i in range(len(loss)): label_input = condition_reshape( label=labels[i,np.newaxis], numclass=numclass, imgshape=(rs, rs)) img_est = n...
18,746
def send_instructions(message): """/start, /help""" msg_content: str = ( "*Available commands:*\n\n/download - downloads pinterest images" ) bot.send_message( message.chat.id, msg_content, parse_mode="markdown", )
18,747
def wide_resnet101(input_shape, num_classes, dense_classifier=False, pretrained=False): """ return a ResNet 101 object """ return _resnet('resnet101', BottleNeck, [3, 4, 23, 3], 64 * 2, num_classes, dense_classifier, pretrained)
18,748
def is_empty(ir: irast.Base) -> bool: """Return True if the given *ir* expression is an empty set or an empty array. """ return ( isinstance(ir, irast.EmptySet) or (isinstance(ir, irast.Array) and not ir.elements) or ( isinstance(ir, irast.Set) and ir.e...
18,749
def read_official_corner_lut(filename, y_grid='lat_grid', x_grid='lon_grid', x_corners = ['nwlon', 'swlon', 'selon', 'nelon'], y_corners = ['nwlat', 'swlat', 'selat', 'nelat']): """ Read a MATLAB file containing corner point lookup data. Returns lons, lats, corner_lut. lons, lats: ...
18,750
def get_component_name(job_type): """Gets component name for a job type.""" job = data_types.Job.query(data_types.Job.name == job_type).get() if not job: return '' match = re.match(r'.*BUCKET_PATH[^\r\n]*-([a-zA-Z0-9]+)-component', job.get_environment_string(), re.DOTALL) if not match:...
18,751
def group_by(source: ObservableBase, key_mapper, element_mapper=None) -> ObservableBase: """Groups the elements of an observable sequence according to a specified key mapper function and comparer and selects the resulting elements by using a specified function. 1 - observable.group_by(lambda x: x.id) ...
18,752
def quit_program(): """Quit program""" clear_screen() sys.exit()
18,753
def gauss_pdf(x, norm, mu, sigma): """ The method calculates the value of the Gaussian probability density function (using matplotlib routines) for a value/array x. for a given mean (mu) and standard deviation (sigma). The results is normalized (multiplied by) 'norm', and so 'norm' should equal ...
18,754
def max_dbfs(sample_data: np.ndarray): """Peak dBFS based on the maximum energy sample. Args: sample_data ([np.ndarray]): float array, [-1, 1]. Returns: float: dBFS """ # Peak dBFS based on the maximum energy sample. Will prevent overdrive if used for normalization. return rms_...
18,755
def close_managers(): """ Do cleanup on all the cookie jars """ for prefix in MANAGERS: MANAGERS[prefix].cookie_jar.store_cookies() print("done closing manager...", prefix) print("EXITING...\n\n\n\n\n\n\n\n\n\n") _exit(0)
18,756
def youngGsmatchwinners(atpmatches): """calculates young grand slam match winners""" matches=atpmatches[(atpmatches['tourney_level'] == 'G') & (atpmatches['winner_age'] < 18)] print(matches[['tourney_date','tourney_name','winner_name', 'winner_age', 'loser_name','loser_age']].to_csv(sys.stdout,index=False))
18,757
def createOrUpdateAppUser(accountID=None): """ """ accountUser = User.objects.get(pk=accountID) if accountUser: accountUser.clientes.update_or_create()
18,758
def get_deltaF_v2(specfile, res, spec_res, addpix=int(10), CNR=None, CE=None, MF_corr=True, domask=True): """Get the optical depth and return the realistic mock spectra specfile : Address to the spectra. It should be in the foramt as the fale_spectra outputs spec_res : spectral resolution in units of voxel...
18,759
def quick_amplitude(x, y, x_err, y_err): """ Assume y = ax Calculate the amplitude only. """ #x[x<0] = 1E-5 #y[y<0] = 1E-5 xy = x*y xx = x*x xy[xy<0] = 1E-10 A = np.ones(x.shape[0]) for i in np.arange(5): weight = 1./(np.square(y_err)+np.square(A).reshape(A.size,1)*n...
18,760
def get_password(config, name): """Read password""" passfile = config.passstore / name with open(passfile, 'r') as fd: return fd.read()
18,761
def attribute_string(s): """return a python code string for a string variable""" if s is None: return "\"\"" # escape any ' characters #s = s.replace("'", "\\'") return "\"%s\"" % s
18,762
def inflate_cell(cell, distance): """ Expand the current cell in all directions and return the set. """ newset = set(cell) if distance==0: return(newset) # recursively call this based on the distance for offset in direction.all_offsets(): # FIXME: If distance is large t...
18,763
def log_exception(logger, err): # pylint: disable=unused-variable """ Log a general exception """ separator = "\n" exception_name = type(err).__name__ exception_message = str(err) string_buffer = ( "Exception:", "Name: {0}.".format(exception_name), "Message: {0}.".fo...
18,764
def read_dfcpp_test_results(d4cpp_output_dir): """ Returns test results """ test_results = {} for dir_name in os.listdir(d4cpp_output_dir): path_to_dir = os.path.join(d4cpp_output_dir, dir_name) if not os.path.isdir(path_to_dir): continue case = dir_name.split('-'...
18,765
def poi(request, id=None): """ */entry/pois/<id>*, */entry/pois/new* The entry interface's edit/add/delete poi view. This view creates the edit page for a given poi, or the "new poi" page if it is not passed an ID. It also accepts POST requests to create or edit pois. If called with DELETE...
18,766
def relativeScope(fromScope, destScope): """relativeScope variant that handles invented fromScopes""" rs = idlutil.relativeScope(fromScope, destScope) if rs[0] is None: try: rd = idlast.findDecl(destScope) except idlast.DeclNotFound: return rs new_rs = rs ...
18,767
def srbt(peer, pkts, inter=0.1, *args, **kargs): """send and receive using a bluetooth socket""" s = conf.BTsocket(peer=peer) a,b = sndrcv(s,pkts,inter=inter,*args,**kargs) s.close() return a,b
18,768
def p_specification_1(t): """specification : definition specification | program_def specification""" t[0] = Specification(t[1], t[2])
18,769
def export(state, from_dir, filter): """Export grades for uploading.""" grading_manager = GradingManager(state.get_assignment(), from_dir, filter) if not grading_manager.submission_count(): raise click.ClickException('no submissions match the filter given!') state.grades = [grade for grade in...
18,770
def testgetpars(times=range(5000), lmodel='alpha', pmodel='quadratic', beta=0.07, nradii=101, n=[4,101], disp=0, optimize=None, save=False, ret=True, test=False, corr='tor', d=0.01, a=0.52, Ra=1.50): """Use data Ip, Btw, Btave(, and perhaps B0_MSE) values for range of indices times to generate value...
18,771
def version(): """ The function that gets invoked by the subcommand "version" """ click.echo(f"Python {platform.python_version()}\n" f"{{ cookiecutter.project_slug }} {__version__}")
18,772
def rotation_matrix_from_vectors(vector1, vector2): """ Finds a rotation matrix that can rotate vector1 to align with vector 2 Args: vector1: np.narray (3) Vector we would apply the rotation to vector2: np.narray (3) Vector that will ...
18,773
def disconnect(): """Disconnect from pop and smtp connexion""" cpop = connectPop() csmtp = connectSmtp() cpop.quit() #close connection, mark messages as read csmtp.close()
18,774
def read_LUT_SonySPI1D(path: str) -> Union[LUT1D, LUT3x1D]: """ Read given *Sony* *.spi1d* *LUT* file. Parameters ---------- path *LUT* path. Returns ------- :class:`colour.LUT1D` or :class:`colour.LUT3x1D` :class:`LUT1D` or :class:`LUT3x1D` class instance. Example...
18,775
def _compare_manifests(path_local, path_irods, logger): """Compare manifests at paths ``path_local`` and ``path_irods``.""" # Load file sizes and checksums. info_local = {} with open(path_local, "rt") as inputf: for line in inputf: if line.startswith("#") or line.startswith("%"): ...
18,776
def test_fee_estimate(flat_fee, prop_fee_cli, max_lin_imbalance_fee, target_amount, expected_fee): """ Tests the backwards fee calculation. """ capacity = TA(10_000) prop_fee = ppm_fee_per_channel(ProportionalFeeAmount(prop_fee_cli)) imbalance_fee = None if max_lin_imbalance_fee > 0: # This...
18,777
def jaxpr_replicas(jaxpr) -> int: """The number of replicas needed for a jaxpr. For a eqn, multiply the `axis_size` with the `jaxpr_replicas` of the subjaxprs. For a list of eqns, take the maximum number of replicas. """ if isinstance(jaxpr, core.ClosedJaxpr): jaxpr = jaxpr.jaxpr return max(unsafe_map(...
18,778
def tokens2ELMOids(tokens, sent_length): """ Transform input tokens to elmo ids. :param tokens: a list of words. :param sent_length: padded sent length. :return: numpy array of elmo ids, sent_length * 50 """ elmo_ids = batch_to_ids([tokens]).squeeze(0) pad_c = (0, 0, 0, sent_length - elm...
18,779
def change_order_line_quantity(line, new_quantity): """Change the quantity of ordered items in a order line.""" line.quantity = new_quantity line.save() if not line.delivery_group.get_total_quantity(): line.delivery_group.delete() order = line.delivery_group.order if not order.get_item...
18,780
def load_configs(default, user): """Read the given config file paths into their respective config object.""" default_config.read(default) user_config.read(user) global default_config_path global user_config_path default_config_path = default user_config_path = user
18,781
def log(content): """Prints out a string prepended by the current timestamp""" print('\033[0;33m' + str(datetime.now()) + "\033[00m " + str(content))
18,782
def write_mapfile(stream, fh, checksum_func=None): """ Write an esgpublish mapfile from a stream of tuples (filepath, drs). :param checksum_func: A callable of one argument (path) which returns (checksum_type, checksum) or None """ for path, drs in stream: file_stat = os.stat(path) ...
18,783
def get_section_endpoints(section_name): """Get the [lon, lat] endpoints associated with a pre-defined section e.g. >> pt1, pt2 = get_section_endpoints('Drake Passage') pt1 = [-68, -54] pt2 = [-63, -66] These sections mirror the gcmfaces definitions, see gcmfaces/gcmfaces_calc...
18,784
def get_vm_metrics(monitor_client, resource_id): """Get metrics for the given vm. Returns row of cpu, disk, network activity""" today = datetime.utcnow().date() last_week = today - timedelta(days=7) metrics_data = monitor_client.metrics.list( resource_id, timespan="{}/{}".format(last_w...
18,785
def geo_api(): """ GeoAPI fixture data. See more at: http://doc.pytest.org/en/latest/fixture.html """ return GeoApi(os.getenv("TEST_AIRBUS_API_KEY"))
18,786
def current_time_id(): """ Returns the current time ID in milliseconds """ return int(round(time.time() * 1000))
18,787
def get_db(): """ Connects to the database. Returns a database object that can be queried. """ if 'db' not in g: g.db = sqlite3.connect( 'chemprop.sqlite3', detect_types=sqlite3.PARSE_DECLTYPES ) g.db.row_factory = sqlite3.Row return g.db
18,788
def test_invariance_tests(kwargs, model, dummy_house): """ Keeping all except 1 feature at a time the same Changing these features a bit should not result in a noticeable difference in the models prediction with the ground truth """ changed_score, unchanged_score = get_test_case( dummy_h...
18,789
def test_concurrent_persistent_group(dev, apdev): """Concurrent P2P persistent group""" logger.info("Connect to an infrastructure AP") hostapd.add_ap(apdev[0]['ifname'], { "ssid": "test-open", "channel": "2" }) dev[0].global_request("SET p2p_no_group_iface 0") dev[0].connect("test-open", key_mgmt="N...
18,790
def computePatientConfusionMatrix(patient_prediction_location, patient_ground_truth_location, labels_names_file): """ @brief: Compute the patient confusion matrix given the location of its prediction and ground truth. @param patient_prediction_location : folder containing the prediction data @para...
18,791
async def ping_server(): """ Ping Server =========== Returns the message "The Optuna-server is alive!" if the server is running. Parameters ---------- None Returns ------- msg : str A message witnessing that the server is running. """ msg = 'The Optuna-server is alive!' return msg
18,792
def treynor(rp: np.ndarray, rb: np.ndarray, rf: np.ndarray) -> np.ndarray: """Returns the treynor ratios for all pairs of p portfolios and b benchmarks Args: rp (np.ndarray): p-by-n matrix where the (i, j) entry corresponds to the j-th return of the i-th portfolio rb (np.ndarray): b-b...
18,793
def virus_tsne_list(tsne_df, virus_df): """ return data dic """ tsne_df.rename(columns={"Unnamed: 0": "barcode"}, inplace=True) df = pd.merge(tsne_df, virus_df, on="barcode", how="left") df["UMI"] = df["UMI"].fillna(0) tSNE_1 = list(df.tSNE_1) tSNE_2 = list(df.tSNE_2) virus_UMI = lis...
18,794
def sometimes(aug): """ Return a shortcut for iaa.Sometimes :param aug: augmentation method :type aug: iaa.meta.Augmenter :return: wrapped augmentation method :rtype: iaa.meta.Augmenter """ return iaa.Sometimes(0.5, aug)
18,795
def test_BLPS_02_AC(): """ simple binary lens with extended source and different methods to evaluate magnification - version with adaptivecontouring """ params = mm.ModelParameters({ 't_0': t_0, 'u_0': u_0, 't_E': t_E, 'alpha': alpha, 's': s, 'q': q, 'rho': rho}) model = ...
18,796
def rev_to_b10(letters): """Convert an alphabet number to its decimal representation""" return sum( (ord(letter) - A_UPPERCASE + 1) * ALPHABET_SIZE**i for i, letter in enumerate(reversed(letters.upper())) )
18,797
def AddPath(match): """Helper for adding file path for WebRTC header files, ignoring other.""" file_to_examine = match.group(1) + '.h' # TODO(mflodman) Use current directory and find webrtc/. for path, _, files in os.walk('./webrtc'): for filename in files: if fnmatch.fnmatch(filename, file_to_examine...
18,798
def emailcallback(pattern, line, lines, filename): """Send an email with the log context, when there is a match.""" _dum, just_the_name = os.path.split(filename) subject = "{} in {}".format(pattern, just_the_name) body = ''.join(lines) SendEmail(subject, body).start() logger.info("{} in {}".form...
18,799