content
stringlengths
22
815k
id
int64
0
4.91M
def test_reduce_rows(): """Tests the `reduce_rows` function.""" matrix = tf.constant( [[30.0, 25.0, 10.0], [15.0, 10.0, 20.0], [25.0, 20.0, 15.0]], tf.float32, ) actual = reduce_rows(matrix) expected = tf.constant( [[20.0, 15.0, 0.0], [5.0, 0.0, 10.0], [10.0, 5.0, 0.0]], tf.f...
5,332,500
def _vmf_normalize(kappa, dim): """Compute normalization constant using built-in numpy/scipy Bessel approximations. Works well on small kappa and mu. """ num = np.power(kappa, dim / 2.0 - 1.0) if dim / 2.0 - 1.0 < 1e-15: denom = np.power(2.0 * np.pi, dim / 2.0) * i0(kappa) else: ...
5,332,501
def twitter_map(): """ Gets all the required information and returns the start page or map with people locations depending on input """ # get arguments from url account = request.args.get('q') count = request.args.get('count') if account and count: # create map and add custom st...
5,332,502
def path_states(node): """The sequence of states to get to this node.""" if node in (cutoff, failure, None): return [] return path_states(node.parent) + [node.state]
5,332,503
def find_named_variables(mapping): """Find correspondance between variable and relation and its attribute.""" var_dictionary = dict() for relation_instance in mapping.lhs: for i, variable in enumerate(relation_instance.variables): name = relation_instance.relation.name field ...
5,332,504
def attribute_formatter(attribute): """ translate non-alphabetic chars and 'spaces' to a URL applicable format :param attribute: text string that may contain not url compatible chars (e.g. ' 무작위의') :return: text string with riot API compatible url encoding (e.g. %20%EB%AC%B4%EC%9E%91%EC%9C%84%EC%9D%98) ...
5,332,505
def feature_evaluation(X: pd.DataFrame, y: pd.Series, output_path: str = ".") -> NoReturn: """ Create scatter plot between each feature and the response. - Plot title specifies feature name - Plot title specifies Pearson Correlation between feature and response - P...
5,332,506
def applyRequests(ram, requests): """ request has to be tuple (WRITE, addr, data) or (READ, addr) data can be only 0 or 1 (because width of data port is 1) """ for req in requests: m = req[0] if m == WRITE: data = req[2] assert data == 1 or data == 0 ...
5,332,507
def maestro_splits(): """ Get list of indices for each split. Stolen from my work on Perceptual Evaluation of AMT Resynthesized. Leve here for reference. """ d = asmd.Dataset().filter(datasets=['Maestro']) maestro = json.load(open(MAESTRO_JSON)) train, validation, test = [], [], [] ...
5,332,508
def get_choice_selectivity(trials, perf, r): """ Compute d' for choice. """ N = r.shape[-1] L = np.zeros(N) L2 = np.zeros(N) R = np.zeros(N) R2 = np.zeros(N) nL = 0 nR = 0 for n, trial in enumerate(trials): if not perf.decisions[n]: con...
5,332,509
def author_productivity(pub2author_df, colgroupby = 'AuthorId', colcountby = 'PublicationId', show_progress=False): """ Calculate the total number of publications for each author. Parameters ---------- pub2author_df : DataFrame, default None, Optional A DataFrame with the author2publication...
5,332,510
def smoothed_epmi(matrix, alpha=0.75): """ Performs smoothed epmi. See smoothed_ppmi for more info. Derived from this: #(w,c) / #(TOT) -------------- (#(w) / #(TOT)) * (#(c)^a / #(TOT)^a) ==> #(w,c) / #(TOT) -------------- (#(w) * #(c)^a) / #(TOT)^(a+1)) ==> #(w,c) ...
5,332,511
def encode(input, errors='strict'): """ convert from unicode text (with possible UTF-16 surrogates) to wtf-8 encoded bytes. If this is a python narrow build this will actually produce UTF-16 encoded unicode text (e.g. with surrogates). """ # method to convert surrogate pairs to unicode cod...
5,332,512
def forgot_password(request, mobile=False): """Password reset form. This view sends an email with a reset link. """ if request.method == "POST": form = PasswordResetForm(request.POST) valid = form.is_valid() if valid: form.save(use_https=request.is_secure(), ...
5,332,513
def rl_forward_char() -> None: """Move forward a character. This acts like readline's forward-char. """ bridge.forward_char()
5,332,514
def test_tracker_dealer(): """Test TrackerDealer.""" # test TrackerDealer with TrackerUD trackers = [[TrackerUD(None, 1, 1, 0.06, 0.02, 20, np.inf, 1) for _ in range(2)] for _ in range(3)] dealer_ud = TrackerDealer(callback, trackers) # can't respond to a trial twice ...
5,332,515
def test_run_suite(irunner, sync): """Test running a single test suite.""" ret = irunner.run_test_suite("test_1", "Suite", await_results=sync) if not sync: assert ret.result() is None # The test report should have been updated as a side effect. assert irunner.report["test_1"]["Suite"].pass...
5,332,516
def rotation_components(x, y, eps=1e-12, costh=None): """Components for the operator Rotation(x,y) Together with `rotation_operator` achieves best memory complexity: O(N_batch * N_hidden) Args: x: a tensor from where we want to start y: a tensor at which we want to finish ...
5,332,517
def erode(np_image_bin, struct_elem='rect', size=3): """Execute erode morphological operation on binaryzed image Keyword argument: np_image_bin -- binaryzed image struct_elem: cross - cross structural element rect - rectangle structural element circ -- cricle structural element(...
5,332,518
def test_converter_conversion_item_initialization( conversion_item, expected_dest, expected_src, expected_transfomers, expected_raw_input, ): """Tests the ConversionItem initialization.""" assert conversion_item.dest == expected_dest assert conversion_item.src == expected_src for i,...
5,332,519
def from_argparse_args( cls: Type[ParseArgparserDataType], args: Union[Namespace, ArgumentParser], **kwargs: Any ) -> ParseArgparserDataType: """Create an instance from CLI arguments. Eventually use varibles from OS environement which are defined as "PL_<CLASS-NAME>_<CLASS_ARUMENT_NAME>" Args: ...
5,332,520
def setup_counter_and_timer(nodemap): """ This function configures the camera to setup a Pulse Width Modulation signal using Counter and Timer functionality. By default, the PWM signal will be set to run at 50hz, with a duty cycle of 70%. :param nodemap: Device nodemap. :type nodemap: INodeMap...
5,332,521
def concat(l1, l2): """ Join two possibly None lists """ if l1 is None: return l2 if l2 is None: return l1 return l1 + l2
5,332,522
def main(): """Main Fuction""" parser = ArgumentParser() group = parser.add_mutually_exclusive_group() group.add_argument('-s', '--speed', type=Decimal, help="Speed expressed as a multiple of the speed of light. \ Speed of light = 1") group.add_argument(...
5,332,523
def raise_ParseList_error(call_location_string): """ Handle problems found at some point during the coding/evaluation of ParseList, and is called when the problem seems sufficiently important that the record should not be coded. Logs the error and raises HasParseError. """ #global SentenceID, V...
5,332,524
def get_model_data(n_samples=None, ratio=None): """ Provides train and validation data to train the model. If n_samples and ratio are not None, it returns data according to the ratio between v1 and v2. V1 is data comming from the original distribution of SIRD parameters, and V2 is data comming from ...
5,332,525
def skip(): """ Decorator for marking test function that should not be executed.""" def wrapper(fn): fn.__status__ = "skip" return fn return wrapper
5,332,526
def upload_original_to(instance, filename): """ Return the path this file should be stored at. """ filename_base, filename_ext = os.path.splitext(filename) filename_ext = filename_ext.lower() origin_path = instance.release_agency_slug if '--' in instance.release_agency_slug: agency_slug, o...
5,332,527
def _GetThumbnailType(destination_id): """Returns the thumbnail type for the destination with the id.""" destination_type = _GetDestinationType(destination_id) if destination_type == _DestinationType.HOTSPOT: return _ThumbnailType.PRETTY_EARTH else: return _ThumbnailType.GEOMETRY_OUTLINE
5,332,528
def rmproj(): """ Remove project """ run('cd {root_dir} && vagrant destroy -f'.format(**VARS)) run('rm {root_dir} -rf'.format(**VARS))
5,332,529
def template_4_bc(template) -> None: """Apply the displacement boundary conditions for case 3 Parameters ---------- template : template The unit template parameters """ # Add the boundary conditions modify.add_bc_fd_edge("yy1", "y", "y", 0, 0) modify.add_bc_fd_edge...
5,332,530
def barchart(bins, values, xlabel, ylabel, title, name=None, ticks=None): """Wapper around the matplotlib bar function. Useful when we need bars from multiple trends. Parameters ---------- bins : np.array x values of where the bars should reside 1-D array values : np.array heigh...
5,332,531
def cli(p_articles, count, path): """ Generate fake data to populate database. """ click.echo('Working...') if p_articles: random_title = [] for _ in range(count): random_title.append(fake.company()) random_title = list(set(random_title)) while True: ...
5,332,532
def auto_differential_demo(): """ 自动微分示例 - Tensor 是包的核心类 - requires_grad 为 True 来跟踪对其的所有操作,完成计算之后,使用 .backward() 方法来自动计算所有梯度 - 停止 tensor 历史记录的跟踪,使用 .detach() 方法,将其计算历史记录分离,防止未来的计算被跟踪 - grad_fn 保存张量被创建时候的函数引用,如果自己创建张量,则为 None :return: """ x = torch.ones(2, 2, requires_grad=True) ...
5,332,533
async def postAsync(text: str, *, url: str = "auto", config: ConfigOptions = ConfigOptions(), timeout: float = 30.0, retries: int = 3): """Alias function for AsyncHaste().post(...)""" return await AsyncHaste().post(text, url=url, config=config, timeout=timeout, retries=retries)
5,332,534
def parse_bibtex(file, build_dir): """ Parse merged bibtex file again with customization to clean citations. @type file: .bib file @param file: file to be parsed @type build_dir: file path @param build_dir: where to save """ parser = BibTexParser() parser.customization = custom...
5,332,535
def SetupSSHKeys(config_path, private_key_path, public_key_path): """Setup the pair of the ssh key for acloud.config. User can use the default path: "~/.ssh/acloud_rsa". Args: config_path: String, acloud config path. private_key_path: Path to the private key file. ...
5,332,536
def gpu_load_acquisition_csv(acquisition_path, **kwargs): """ Loads acquisition data Returns ------- GPU DataFrame """ chronometer = Chronometer.makeStarted() cols = [ 'loan_id', 'orig_channel', 'seller_name', 'orig_interest_rate', 'orig_upb', 'orig_loan_term', 'orig_date',...
5,332,537
def test_check_maxfail_1(testdir, example): """ Should stop after first failed check """ result = testdir.runpytest("--maxfail=1") result.assert_outcomes(failed=1, passed=0) result.stdout.fnmatch_lines(["*AssertionError: one*"])
5,332,538
def get_flows_src_dst_address_pairs(device, flow_monitor): """ Gets flows under flow_monitor and returns source and destination address pairs Args: device ('obj'): Device to use flow_monitor ('str'): Flow monitor name Raises: N/A Returns: [(...
5,332,539
def imthresh(im, thresh): """ Sets pixels in image below threshold value to 0 Args: im (ndarray): image thresh (float): threshold Returns: ndarray: thresholded image """ thresh_im = im.copy() thresh_im[thresh_im < thresh] = 0 return thresh_im
5,332,540
def test_geometry_collection_iteration(): """test if feature collection is iterable""" gc = FeatureCollection(features=[test_feature, test_feature]) iter(gc)
5,332,541
def set_serv_parms(service, args): """ Set the service command line parameters in Registry """ import _winreg uargs = [] for arg in args: uargs.append(unicoder(arg)) try: key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, _SERVICE_KEY + service) _winreg.SetValueEx(key, _SE...
5,332,542
def isRenderNode(): # type: () -> bool """ Returns ------- bool """ return flavor() == 'Render'
5,332,543
def test_clean_data_contains_instance_value(): """ Test values from instances remain when not in data. """ data = {'first_name': 'John'} fields = ['job_title', 'first_name'] class Job(object): job_title = 'swamper' first_name = '' class Swamper(BaseSwamper): def bui...
5,332,544
def download_datasets(force=False): """ Download all datasets required for project. - force: force dataset download even if dataset has been previously downloaded. """ download_enron_email_dataset(force) download_ud120_project(force)
5,332,545
def write_image(image_base64: str, filepath: pathlib.Path) -> None: """ Write an image to a file. Args: image_base64: Image encoded in Base64 filepath: Output image file path """ with open(filepath, "wb") as f: f.write(base64.b64decode(image_base64))
5,332,546
def wrap_application(app: App, wsgi: WSGICallable) -> WSGICallable: """Wrap a given WSGI callable in all active middleware.""" for middleware_instance in reversed(ACTIVE_MIDDLEWARES): wsgi = middleware_instance(app, wsgi) return wsgi
5,332,547
def cal_rpn(imgsize, featuresize, scale, gtboxes): """ Args: imgsize: [h, w] featuresize: the size of each output feature map, e.g. [19, 19] scale: the scale factor of the base anchor to the feature map, e.g. [32, 32] gtboxes: ground truth boxes in the image, shape of [N, 4]. ...
5,332,548
def main(data, context): """Triggered from a message on a Cloud Pub/Sub topic. Args: data (dict): Event payload. context (google.cloud.functions.Context): Metadata for the event. """ try: current_time = datetime.utcnow() log_message = Template('Cloud Function was trigger...
5,332,549
def run(args): """This function is called by a user to recover or reset their primary one-time-password secret. This is used, e.g. if a user has changed their phone, or if they think the secret has been compromised, or if they have lost the secret completely (in which case they will need...
5,332,550
def adjust_price(iteration, current_price, global_start, last_tx_time): """ Function that decides to lower or increase the price, according to the time of previous transaction and the progress in reaching TARGET in TARGET_TIME. Args: iteration (int) - Number of previous successful transa...
5,332,551
def read_csv_batch(file: str, offset, cnt, **read_csv_params): """ Args: file: offset: cnt: read_csv_params: Returns: """ read_csv_params = copy(read_csv_params) if read_csv_params is None: read_csv_params = {} try: usecols = read_csv_param...
5,332,552
def fault_ack_faults_by_dn(cookie, in_dns): """ Auto-generated UCSC XML API Method. """ method = ExternalMethod("FaultAckFaultsByDn") method.cookie = cookie method.in_dns = in_dns xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
5,332,553
def provides(name=None, needs: List[str] = None): """A shortcut for defining a factory function that also needs dependencies itself.""" if not needs: needs = [] def decorator(f): decorated = _needs(*needs)(f) set(name or f.__name__, decorated) return f re...
5,332,554
def clip_xyxy_to_image(x1, y1, x2, y2, height, width): """Clip coordinates to an image with the given height and width.""" x1 = np.minimum(width - 1.0, np.maximum(0.0, x1)) y1 = np.minimum(height - 1.0, np.maximum(0.0, y1)) x2 = np.minimum(width - 1.0, np.maximum(0.0, x2)) y2 = np.minimum(height - 1...
5,332,555
def build_url(urlo, base, end, url_whitespace, url_case): """ Build and return a valid url. Parameters ---------- urlo A ParseResult object returned by urlparse base base_url from config end end_url from config url_whitespace ur...
5,332,556
def AnomalyDicts(anomalies, v2=False): """Makes a list of dicts with properties of Anomaly entities.""" bisect_statuses = _GetBisectStatusDict(anomalies) return [GetAnomalyDict(a, bisect_statuses.get(a.bug_id), v2) for a in anomalies]
5,332,557
def remove_links(txt: str): """ Remove weblinks from the text """ pattern = r'[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)' txt = re.sub(pattern, " ", txt) txt = re.sub('http|https', " ", txt) return txt
5,332,558
def timefn(fn): """Times a function and stores the result in LOG variables""" @wraps(fn) def inside(*args, **kwargs): start = timer() result = fn(*args, **kwargs) end = timer() gv.TIME_LOG += f'Fn : {fn.__name__} - {end - start}\n' return result return inside
5,332,559
def get_tweet_stream(output_file, twitter_credentials): """ This function is given and returns a "stream" to listen to tweets and store them in output_file To understand how this function works, check it against the code of twitter_streaming in part00_preclass :param output_file: the file where the ret...
5,332,560
def delete(review_id): """Delete a review. Args: review_id: ID of the review to be deleted. """ review = get_by_id(review_id) with db.engine.connect() as connection: connection.execute(sqlalchemy.text(""" DELETE FROM review WHERE id = :review_i...
5,332,561
def conv3d_3x3(filters, stride=1, padding=1, kernel_initializer=None, bias_initializer=None, name=None): """3D convolution with padding.""" return keras.Sequential([ layers.ZeroPadding3D(padding), layers.Conv3D(filters, ...
5,332,562
def get_available_quests(user, num_quests): """Get the quests the user could participate in.""" quests = [] for quest in Quest.objects.exclude(questmember__user=user).order_by('priority'): if quest.can_add_quest(user) and not quest.completed_quest(user): quests.append(quest) ...
5,332,563
def height(): """ Default window height """ return get_default_height()
5,332,564
def no_adjust_tp_func_nb(c: AdjustTPContext, *args) -> float: """Placeholder function that returns the initial take-profit value.""" return c.curr_stop
5,332,565
def inverse_theoretical_laser_position(y, a, b, c): """ theoretical angular position of the wire in respect to the laser position """ return np.pi - a - np.arccos((b - y) / c)
5,332,566
def ad_roc(y_true, y_score): """ Compute ROC-curve. """ fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true, y_score, pos_label=1, drop_intermediate=False) return fpr, tpr, thresholds
5,332,567
def check_reachability(gateway): # from https://stackoverflow.com/questions/2953462/pinging-servers-in-python """ Returns True if host (str) responds to a ping request. Remember that a host may not respond to a ping (ICMP) request even if the host name is valid. """ time.sleep(15) # Option f...
5,332,568
def greedy_decoding(baseline_transformer, src_representations_batch, src_mask, trg_field_processor, max_target_tokens=100): """ Supports batch (decode multiple source sentences) greedy decoding. Decoding could be further optimized to cache old token activations because they can't look ahead and so addi...
5,332,569
def _parse_cell_type(cell_type_arg): """ Convert the cell type representation to the expected JVM CellType object.""" def to_jvm(ct): return _context_call('_parse_cell_type', ct) if isinstance(cell_type_arg, str): return to_jvm(cell_type_arg) elif isinstance(cell_type_arg, CellType): ...
5,332,570
def _extract_line(args): """Implements the BigQuery extract magic used to extract table data to GCS. The supported syntax is: %bigquery extract -S|--source <table> -D|--destination <url> <other_args> Args: args: the arguments following '%bigquery extract'. Returns: A message about whether the...
5,332,571
def Ht(mu, q=None, t=None, pi=None): """ Returns the symmetric Macdonald polynomial using the Haiman, Haglund, and Loehr formula. Note that if both `q` and `t` are specified, then they must have the same parent. REFERENCE: - J. Haglund, M. Haiman, N. Loehr. *A combinatorial formula ...
5,332,572
def is_generic_alias_of(to_check, type_def): """ :param to_check: the type that is supposed to be a generic alias of ``type_def`` if this function returns ``True``. :param type_def: the type that is supposed to be a generic version of ``to_check`` if this function returns \ ``True``. ...
5,332,573
def train_PCA(X,n_dims,model='pca'): """ name: train_PCA Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. It uses the LAPACK implementation of the full SVD or a randomized truncated SVD by the method of Halko et al. 2009, ...
5,332,574
def find_song(hash_dictionary, sample_dictionary, id_to_song): """ Run our song matching algorithm to find the song :param hash_dictionary: :param sample_dictionary: :param id_to_song: :return max_frequencies, max_frequencies_keys: """ offset_dictionary = dict() for song_id in id_to_...
5,332,575
def plot_percentage( contacts, parameters="Description", t_detail=1, n_t_cells=100, save=False, palette="deep", context="notebook", ): """Plot final percentage of T cells in contact with DC""" t_cells_in_contact = contacts.drop_duplicates(["Track_ID", "Run", parameters]) contacts...
5,332,576
def phedex_url(api=''): """Return Phedex URL for given API name""" return 'https://cmsweb.cern.ch/phedex/datasvc/json/prod/%s' % api
5,332,577
def upgrade(): """upgrade to this revision""" op.execute("CREATE SCHEMA data") op.execute("CREATE EXTENSION IF NOT EXISTS postgis") # Create collections table op.create_table( "collections", sa.Column("id", sa.VARCHAR(1024), nullable=False, primary_key=True), sa.Column("stac...
5,332,578
def extract_emails(fname, email='Email Address', outfile="emails_from_mailchimp.txt", nofile=False, nolog=False, sort=True): """ Extract e-mail addresses from a CSV-exported MailChimp list. :param fname: the input .csv file :param email: the header of the column co...
5,332,579
def continuations(tree, *, syntax, expander, **kw): """[syntax, block] call/cc for Python. This allows saving the control state and then jumping back later (in principle, any time later). Some possible use cases: - Tree traversal (possibly a cartesian product of multiple trees, with the curr...
5,332,580
def get_autotune_level() -> int: """Get the autotune level. Returns: The autotune level. """ return int(os.environ.get("BAGUA_AUTOTUNE", 0))
5,332,581
def DNA_dynamic_pressure(y, r, h, yunits='kT', dunits='m', opunits='kg/cm^2'): """Estimate peak pynamic overpressure at range r from a burst of yield y using the the Defense Nuclear Agency 1kT standard free airburst overpressure, assuming an ideal surface. Many real-world surfaces are not ideal (most, in the opinio...
5,332,582
def revcumsum(U): """ Reverse cumulative sum for faster performance. """ return U.flip(dims=[0]).cumsum(dim=0).flip(dims=[0])
5,332,583
def http_trace_parser_hook(request): """ Retrieves the propagation context out of the request. Uses the honeycomb header, with W3C header as fallback. """ honeycomb_header_value = honeycomb.http_trace_parser_hook(request) w3c_header_value = w3c.http_trace_parser_hook(request) if honeycomb_header...
5,332,584
def format_attn(attention_tuples: tuple): """ Input: N tuples (N = layer num) Each tuple item is Tensor of shape Batch x num heads x from x to Output: Tensor of shape layer x from x to (averaged over heads) """ # Combine tuples into large Tensor, then avg return torch.cat([l for l...
5,332,585
def fit_gaussian2d(img, coords, boxsize, plot=False, fwhm_min=1.7, fwhm_max=30, pos_delta_max=1.7): """ Calculate the FWHM of an objected located at the pixel coordinates in the image. The FWHM will be estimated from a cutout with the specified boxsize. Parameters ------...
5,332,586
def _ensure_aware(series, tz_local): """Convert naive datetimes to timezone-aware, or return them as-is. Args: tz_local (str, pytz.timezone, dateutil.tz.tzfile): Time zone for time which timestamps will be converted to. If the series already has local timezone info, it is returned as-is. ""...
5,332,587
def one_mask(df, mask_type, sample_type, data, logger=None): """ return a vector of booleans from the lower triangle of a matching-matrix based on 'mask_type' :param df: pandas.DataFrame with samples as columns :param str mask_type: A list of strings to specify matching masks, or a minimum distance to mask...
5,332,588
def compute_epsilon(steps): """Computes epsilon value for given hyperparameters.""" if FLAGS.noise_multiplier == 0.0: return float('inf') orders = [1 + x / 10. for x in range(1, 100)] + list(range(12, 64)) sampling_probability = FLAGS.batch_size / NB_TRAIN rdp = compute_rdp(q=sampling_probability, ...
5,332,589
def test_website_migrate(): """TODO:""" pass
5,332,590
def extract_tumblr_posts(client, nb_requests, search_query, before, delta_limit): """Extract Tumblr posts with a given emotion. Parameters: client: Authenticated Tumblr client with the pytumblr package. nb_requests: Number of API request. search_query: Emotion to search for. ...
5,332,591
def total_curtailment_expression_rule(mod, g, tmp): """ **Expression Name**: GenVar_Total_Curtailment_MW **Defined Over**: GEN_VAR_OPR_TMPS Available energy that was not delivered There's an adjustment for subhourly reserve provision: 1) if downward reserves are provided, they will be called up...
5,332,592
def write_pred_kaggle_file(y, outfname, le): """Writes the predictions in Kaggle format. Given the unlabeled object, classifier, outputfilename, and the speech object, this function write the predictions of the classifier on the unlabeled data and writes it to the outputfilename. The speech object is required ...
5,332,593
def transpose(m): """Compute the inverse of `m` Args: m (Matrix3): Returns: Matrix3: the inverse """ return Matrix3(m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
5,332,594
def reverse_string(string): """Solution to exercise C-4.16. Write a short recursive Python function that takes a character string s and outputs its reverse. For example, the reverse of "pots&pans" would be "snap&stop". """ n = len(string) def recurse(idx): if idx == 0: ...
5,332,595
def result_to_df(model, data, path: str = None, prediction: str = 'prediction', residual: str = 'residual') -> pd.DataFrame: """Create result data frame. Args: model (Union[NodeModel, StagewiseModel]): Model instance. data (MRData): Data object...
5,332,596
def auto(frmt, minV = None, maxV = None): """ Generating regular expressions for integer, real, date and time. :param format: format similar to C printf function (description below) :param min: optional minimum value :param max: optional maximum value :return: regular expression for a given for...
5,332,597
def tf_box_3d_diagonal_length(boxes_3d): """Returns the diagonal length of box_3d Args: boxes_3d: An tensor of shape (N x 7) of boxes in box_3d format. Returns: Diagonal of all boxes, a tensor of (N,) shape. """ lengths_sqr = tf.square(boxes_3d[:, 3]) width_sqr = tf.square(box...
5,332,598
async def employment_plot(current_city:City): """ Visualize employment information for city - see industry breakdown and employment type ### Query Parameters - city ### Response JSON string to render with react-plotly.js """ city = validate_city(current_city) city_data = CityDa...
5,332,599