content
stringlengths
22
815k
id
int64
0
4.91M
def test_add_b047_add_b047_v(mode, save_output, output_format): """ TEST :Adhoc XSD: : id="72597" description="xsd: valid xml and xsd" """ assert_bindings( schema="msData/additional/test72597.xsd", instance="msData/additional/test72597.xml", class_name="Root", version="1....
64,400
def setup(): """ Initializes the hook queues for the sys module. This method will automatically be called on the first registration for a hook to the system by either the registerDisplay or registerExcept functions. """ global _displayhooks, _excepthooks if _displayhooks is not None: ...
64,401
def QR_algorithm_shift_Givens_double(A): """The QR algorithm with largest value shift for finding eigenvalues. Using Givens rotations for finding RQ. :param A: The square matrix to find eigenvalues of. :type A: :py:class:`numpy.ndarray` :return: The eigenvalues. :rtype: list """ # Fi...
64,402
def create_user(client, jwt, project_role='developer'): """Create user and return user object. project_role allowed values: developer, manager, cto """ response = _create_user_(client, jwt, project_role=project_role) user = json.loads(response.data) return user
64,403
def load_scc_from_cache( scc: List[MypyFile], result: BuildResult, mapper: genops.Mapper, ctx: DeserMaps, ) -> ModuleIRs: """Load IR for an SCC of modules from the cache. Arguments and return are as compile_scc_to_ir. """ cache_data = { k.fullname: json.loads( result...
64,404
def p_elseif_stmt(p): """ elseif_stmt : | ELSE stmt_list_opt | ELSEIF expr sep stmt_list_opt elseif_stmt """ if len(p) == 1: p[0] = node.stmt_list() elif len(p) == 3: p[0] = p[2] elif len(p) == 6: p[0] = node.if_stmt(cond_expr=p[2], ...
64,405
def GetFolderUriPath(folder): """Return the URI path of a GCP folder.""" return GetParentUriPath('folders', folder)
64,406
def ffs(model, df, selected_columns=None, target_column="min_offer", df_to_xy_kwargs=None, cv=3, ravel_target=True, n_jobs=-2, enforced_target_values=None, early_stop=2): """ Forward feature selection """ if selected_columns is None: selected_columns = [col for col in df.columns if col != target...
64,407
def CreateHDFStudyFile(file_name: str, *ignored_args) -> bool: """aux function for mocking salome.myStudy.SaveAs it ignores arguments for multifile and mode (ascii or binary) TODO do a type check on the "file_name"? => salome seems to only work with "str" """ if not file_name.endswith(".hdf"): ...
64,408
async def test_setting_unique_id( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_luftdaten: MagicMock ) -> None: """Test we set unique ID if not set yet.""" mock_config_entry.unique_id = None mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry....
64,409
def diff_list(l1, l2): """Returns side by side equality test""" return [False if i1==i2 else True for (i1, i2) in zip(l1, l2)]
64,410
def process_metadata(full_dict): """Convert an extended system dictionary, as obtained through __dict__, to a reduced one that can be written to a file Parameters ---------- full_dict: dict """ reduced_dict = {} for key, param_obj in full_dict.items(): if key[0] == '_': ...
64,411
def submit( description, analysis_mode='analysis', tool='ace_api', tool_instance='ace_api:{}'.format(socket.getfqdn()), type='generic', company_id=None, event_time=None, details={}, observables=[], tags=[], files=[], queue='default', instructions=None, *args, **...
64,412
def pack_language(language): """Pack language in a two-byte tuple.""" return pack_language_or_region(language, 'a')
64,413
def create(**kwargs): """ 创建EmailClient实例 :param kwargs: :param smtp_server: smtp发送邮件服务器 :param msg_from: 发件人邮箱 :param password: 发件人授权码 :param msg_from_format: 发件人格式化显示文案 :param msg_to: 收件人邮箱列表 :param msg_subject: 邮件主题 :param msg_content: 邮件内容 :param attach_file: 邮件附件 :pa...
64,414
def c_output_free_funs(header, impl, intro, cfg): """writes callables declarations/definitions""" s = sig.c_signature(cfg) funcs = [(s.get(f),f) for f in intro.exported_freefunctions()] funcs.sort() header.write('\n/* ==== free functions ==== */\n') for csig, free_fun in funcs: header.wr...
64,415
def infer_with_cpu(frame, network): """ Run inference using opencv dnn interface. :param image: resized frame :return: """ # MobileNetSSD Expects 300x300 resized frames blob = cv.dnn.blobFromImage(frame, 0.00784, (Config.model_image_height, Config.model_image_width), (127.5, 127.5, 127.5), ...
64,416
def protein_substitution(annotation, score): """ Returns an array with the MIN and the MAX value of the given ProteinSubstitutionScore. Empty array if not found. :type annotation: str :param annotation: Annotation field :type score: str :param score: :rtype: :return: """ jc = ...
64,417
def calculate_weights_posterior(designmtx, targets, beta, m0, S0): """ Calculates the posterior distribution (multivariate gaussian) for weights in a linear model. parameters ---------- designmtx - 2d (N x M) array of inputs (data-matrix or design-matrix) where N is the number of data-p...
64,418
def cal_item_sim(user_click, user_click_time): """ Args: user_click:dict ,key userid value [itemid1, itemid2] Return: dict, key:itemid_i, value dict, value_key itemid_j, value_value simscore """ co_appear = {} item_user_click_time = {} for user, itemlist in user_click.items()...
64,419
def get_routes(vehicles: List[int], stops: List[int]): """ Create dict of vehicles (key) and their routes (value). :vehicles: list of vehicle identities (same order as demand) :stops: list of stop numbers (same order as vehicles) return dict """ counts = {} for vehicle in v...
64,420
def expand_port_range(port_range): """Expands a port range. From https://cloud.google.com/compute/docs/reference/beta/firewalls, ports can be of the form "<number>-<number>". Args: port_range (string): A string of format "<number_1>-<number_2>". Returns: list: A list of string integer...
64,421
def parse_common_header(sff_file): """Parse a Common Header section from a binary SFF file. Keys in the resulting dict are identical to those defined in the Roche documentation. As a side effect, sets the position of the file object to the end of the Common Header section. """ h = comm...
64,422
def test_files_are_tracked_in_lfs(runner, client): """Test files added from a Git repo are tacked in Git LFS.""" filename = 'CHANGES.rst' # create a dataset result = runner.invoke(cli, ['dataset', 'create', 'dataset']) assert 0 == result.exit_code, result.output + str(result.stderr_bytes) # add...
64,423
def quadrupedGuide(*args): """Import the basic quadruped template""" path = os.path.dirname(component.__file__) pm.importFile(os.path.join(path, "_templates", "quadruped.ma"))
64,424
def load_features(features_path): """ Reading the features from disk. :param features_path: Location of feature JSON. :return features: Feature hash table. """ features = json.load(open(features_path)) features = {str(k): [str(val) for val in v] for k, v in features.items()} return featu...
64,425
def _geodesic_parcel_centroid(vertices, faces, inds): """ Calculates parcel centroids based on surface distance Parameters ---------- vertices : (N, 3) Coordinates of vertices defining surface faces : (F, 3) Triangular faces defining surface inds : (R,) Indices of `v...
64,426
def progress_bar(progress, size = 20): """ Returns an ASCII progress bar. :param progress: A floating point number between 0 and 1 representing the progress that has been completed already. :param size: The width of the bar. .. code-block:: python >>> ui.progress_bar(0.5, 10) ...
64,427
def _main(argv): """Main function (entry point for command-line use).""" import argparse parser = argparse.ArgumentParser() parser.add_argument('app', metavar='APP', help='Path to NumericCholesky binary') parser.add_argument('--iterations', type=int, default=100, ...
64,428
def backlog_list_wikis(client: BacklogAPI, project: str): """プロジェクト配下のwikiをリストする :param client: API Client :type client: BacklogAPI :param project: プロジェクトIDもくしはプロジェクトキー :type project: str """ return client.wiki.list( projectIdOrKey=project )
64,429
def model_to_json(model): """ Serialize a model to Json: - model: the model object to serialize. Return: the json as a string """ dictionnary = model_to_dict(model) return json.dumps(dictionnary, cls=DjangoJSONEncoder)
64,430
def print_stepdb(df) -> pd.DataFrame: """create summary DataFrame from step info db Parameters ---------- df : DataFrame outcome of cal_stepinfo with duration, ap_ptp, ml_ptp, balance, LR Returns ------- pd.DataFrame summary dataframe for one patient """ res = pd.D...
64,431
def test_vsys_efm_backup(proxy, vsysId, efmId, backupId): """ Extended Function Module (EFM) Backup """ #result = proxy.RestoreEFM(vsysId, efmId, backupId) #result = proxy.DestroyEFMBackup(vsysId, efmId, backupId) pass
64,432
def get_kmer(record_dict, chromosome, position, k=3, pos='mid'): """ Given a dictionary (in memory) of fasta sequences this function will return a kmer of length k centered about pos at a certain genomic position in an identified dictionary key i.e. chromosome. Parameters ---------- record_...
64,433
async def test_discovery_with_device_update(hass, mqtt_mock, caplog, device_reg): """Test discovery, update and removal of notify service with a device config.""" # Initial setup data = '{ "command_topic": "test_topic", "name": "My notify service", "targets": ["target1", "target2"], "device":{"identifiers"...
64,434
def blend_images(img0: NDArrayByte, img1: NDArrayByte, alpha: float = 0.7) -> NDArrayByte: """Alpha-blend two images together. Args: img0: uint8 array of shape (H,W,3) img1: uint8 array of shape (H,W,3) alpha: Alpha blending coefficient. Returns: uint8 array of shape (H,W,3...
64,435
def hasblocks(hashlist): """Determines which blocks are on this server""" print("HasBlocks()") return hashlist
64,436
def new_project(selenium): """Creates a new project object. Returns: lib.page.widget.ProjectInfo """ project_page = conftest_utils.create_lhn_object( selenium, constants.element.Lhn.PROJECTS) yield project_page
64,437
def make_matched_rows(num_records): """Make multiple interaction CSV rows that should pass contact matching.""" adviser = AdviserFactory( first_name='Adviser for', last_name='Matched interaction', ) service = random_service() communication_channel = random_communication_channel() ...
64,438
def msg_start(*msg): """ Prints an start message """ global START_TIME START_TIME = datetime.datetime.now() label = colors.purple("START") _msg(label, *msg)
64,439
def group(nsample, xyz, points): """ Input: nsample: scalar xyz: input points position data, [B, N, C] points: input points data, [B, N, D] Return: new_xyz: sampled points position data, [B, 1, C] new_points: sampled points data, [B, 1, N, C+D] """ B, N, C = x...
64,440
async def test_siren(hass, client, aeotec_zw164_siren, integration): """Test the siren entity.""" node = aeotec_zw164_siren state = hass.states.get(SIREN_ENTITY) assert state assert state.state == STATE_OFF # Test turn on with default await hass.services.async_call( "siren", ...
64,441
def sample_neuron(samp_num, burnin, sigma_J, S, D_i, ro, thin=0, save_all=True): """ This function uses the Gibbs sampler to sample from w, gamma and J :param samp_num: Number of samples to be drawn :param burnin: Number of samples to burn in :param sigma_J: variance of the J slab :param S: Neurons...
64,442
def init_open_face_module(): """Initiate the open face module.""" global args global align global net openface_path = common.OPENFACE_PATH modelDir = os.path.join(openface_path, "models") dlibModelDir = os.path.join(modelDir, "dlib") openfaceModelDir = os.path.join(modelDir, "openface"...
64,443
def test_get_provider_with_grace_period_grace_period_lock_not_acquired(): """Test for _get_provider_with_grace_period when entry is in grace period. When the entry is in grace_period and we do not acquire the lock, we should not go to the provider store """ store = MockProviderStore() name = "mater...
64,444
def lookup_angles(system, angles, temperature): """Parse the equilibrium angles and force constants of specified angles from a openmm.System. Parameters ---------- system : openmm.System The system object that contains all potential and constraint definitions. angles : np.ndarray ...
64,445
def get_schema_file_name() -> Text: """ Returns: Text: get schema filename """ # TODO (Alex): remove hardcoded schema name SCHEMA_NAME = 'stats.tfdv' return SCHEMA_NAME
64,446
def get_submissions_dir(ds): """Return pathobj of directory where all the submission packs live""" return ds.pathobj / GitRepo.get_git_dir(ds.path) / 'datalad' / 'htc'
64,447
def read_readme(): """Load the project readme.""" with open("README.md") as readme: return readme.read()
64,448
def set_func_trace_options(*args): """set_func_trace_options(int options)""" return _idaapi.set_func_trace_options(*args)
64,449
def page_not_found(e): """ Render the 404 error page""" return flask.render_template("404.html")
64,450
def test_safe_load_non_strict_json(): """ Scenario: Dictionary should be prepared from json string. Given: - json as string. When: - Preparing dictionary from string. Then: - Ensure valid json should be loaded successfully. """ from GoogleCloudSCC import safe_load_non_strict_j...
64,451
def gam_prophoto(rgb): """ Convert an array of linear-light prophoto-rgb in the range 0.0-1.0 to gamma corrected form. Transfer curve is gamma 1.8 with a small linear portion. https://en.wikipedia.org/wiki/ProPhoto_RGB_color_space """ result = [] for i in rgb: # Mirror linear nat...
64,452
def param_list(cls, m_name, a_type): """ Generate the parameter list (no parens) for an a_type accessor @param cls The class name @param m_name The member name @param a_type One of "set" or "get" or TBD """ member = of_g.unified[cls]["union"][m_name] m_type = member["m_type"] params ...
64,453
def pad_tensor(vec: torch.Tensor, pad: int, dim: int) -> torch.Tensor: """ args: vec - tensor to pad pad - the size to pad to dim - dimension to pad return: a new tensor padded to 'pad' in dimension 'dim' """ if pad - vec.size(dim) == 0: # reach max no need to pad (...
64,454
def get_2D_transformation(testSession : Session, refSessions : "list[Session]"): """returns a list of possible poses along with their confidence methods: 1: Cross referencing 2 refenrence images with one test sesison image 2: Matching 2 reference images to retrieve 3D points, then p...
64,455
def test_getcached(): """Returning a cached plug works""" node = cmdx.createNode("transform") assert_equals(node["translate"], (0.0, 0.0, 0.0)) assert_equals(node["rotate"], (0.0, 0.0, 0.0)) node["tx"] = 5 assert_equals(node["tx"], 5) node["tx"] = 10 assert_equals(node["tx", cmdx.Cached]...
64,456
def project_to_pointcloud(frame, ri, camera_projection, range_image_pose, calibration): """ Create a pointcloud in vehicle space from LIDAR range image. """ beam_inclinations = compute_beam_inclinations(calibration, ri.shape[0]) beam_inclinations = np.flip(beam_inclinations) extrinsic = np.array(calibr...
64,457
def model_verbose_name_plural(model): """ Returns the pluralized verbose name of a model instance or class. """ return model_options(model).verbose_name_plural
64,458
def sample_gmmhmm(gmmhmm, n_sim): """ Simulate from a GMMHMM. Returns ------- states : ndarray of shape (n_sim,) The sequence of states obs : ndarray of shape (n_sim, K) The generated observations (vectors of length K) """ states = [] obs = [] state = np.argm...
64,459
def cli(): """RISC-V PVP tool to manage co-verification flow.""" pass
64,460
def main(): """ main entrance """ mutator = PermuteFingerprints() for line in sys.stdin: mutator.permute(line.strip()) for fingerprint in mutator.aslist(): print fingerprint
64,461
async def unload(extension_name : str): """attempt to load an extension (plugin""" # extension_name = botcogs.<module_name> extension_name = extension_name.strip() try: bot.unload_extension(extension_name) except Exception as e: await bot.say("Failed to unload cog " + extension_name ...
64,462
def take_fullscreen_capture(): """Capture monitor.""" image_filename: str = random_char(amount=10) image_path: str = f"{Settings.image_folder}{now:%Y}/{now:%m}" image_url: str = f"{Settings.image_url}{now:%Y}/{now:%m}/{image_filename}.{Settings.file_extension}" create_folder_if_not_exist(path=image...
64,463
def upload_file_to_s3_by_job_id(file_path, content_type="text/html", extra_message=None): """ Uploads a file to bokeh-travis s3 bucket under a job_id folder """ s3_filename = join(job_id, file_path) return upload_file_to_s3(file_path, s3_filename, content_type, extra_message)
64,464
def Log(category, action, **kwargs): """Schedules a task to upload an event to GA.""" payload = json.dumps(dict(category=category, action=action, **kwargs)) task_scheduler.AddTask(queue_name=QUEUE_NAME, payload=payload)
64,465
def p_exclusive_or_expression(p): """exclusive_or_expression : and_expression | exclusive_or_expression EXPONENT and_expression""" if len(p) == 2: p[0] = p[1] else: fname, entry, args = resolve_function_name_uniform_types(p[2], [p[1], p[3]]) p[0] = { "value": fname, ...
64,466
def do_web_cert(af_ip_pairs, url, task, *args, **kwargs): """ Check the web server's certificate. """ try: results = {} for af_ip_pair in af_ip_pairs: results[af_ip_pair[1]] = cert_checks( url, ChecksMode.WEB, task, af_ip_pair, *args, **kwargs) except Sof...
64,467
def get_model(model_name): """Gets model by name.""" return load_generator(model_name)
64,468
def build_eip(prefix, template, vpc, instance): """ Adds an Elastic IP to the template and its value to the CF outputs. """ eip = ec2.EIP("%sEIP" % prefix) eip.InstanceId = Ref(instance) eip.Domain = "vpc" if isinstance(vpc, ec2.VPC): eip.DependsOn = resource_title.vpc_gateway_title(...
64,469
def test_parametric_unit_discovery( generic_data, long_datum, unitless_dtype, expected_dtype, nrows ): """Check that the correct unit (e.g. month, day, second) is discovered from the data when a user specifies a unitless datetime.""" # Unit should be "D" (days) due to last entry data = [generic_data...
64,470
def test_message(): """ Test if the Message constructor initializes an object with correct member variables. """ message = Message(1, "Head of Message 1", "Content of Message 1") assert_equal(message.id, 1) assert_equal(message.head, "Head of Message 1") assert_equal(message.content, "Conten...
64,471
def test_raw_html_644a(): """ Test case 644a: variation of 644 with extra indent """ # Arrange source_markdown = """foo <!-- this is a comment - with hyphen -->""" expected_tokens = [ "[para(1,1):\n ]", "[text(1,1):foo :]", "[raw-html(1,5):!-- this is a\n\a \a\x03\acom...
64,472
def walk_files(root_dir): """Iterates under all the files under root_dir, yielding their filepath.""" import os for base_dir, dirs, filenames in os.walk(root_dir): for filename in filenames: yield os.path.join(base_dir, filename)
64,473
def process_abides_order_stream(stream_bz2, symbol, out_dir, date): """ Writes ABIDES stream data into pandas DataFrame required by plotting programs. """ stream_df = pd.read_pickle(stream_bz2, compression='bz2').reset_index() write_df = convert_stream_to_format(stream_df, fmt="plot-scripts") write_df =...
64,474
def qhline(widget): # http://stackoverflow.com/questions/5671354/how-to-programmatically-make-a-horizontal-line-in-qt # solution """ Create a horizontal line Parameters ---------- widget: widget containing the QFrame to be created """ line = QFrame(widget) line.setFram...
64,475
def rolling_ball( reader: BioReader, writer: BioWriter, ball_radius: int, light_background: bool, ): """ Applies the rolling-ball algorithm from skimage to perform background subtraction. This function processes the image in tiles and, therefore, scales to images of any size. ...
64,476
def load_start_time(start_time_file, vid): """ load start time Args: start_time_file: str vid: str, video Returns: int, start time """ df_start_time = csv_read(start_time_file).set_index("video_name") if vid not in df_start_time.index: print("Error: ", vid,...
64,477
def test_dcos_config_azure(tmp_path): """ Second replacement is used. """ root_path = tmp_path / 'root' values = { 'windows_dcos_install_path': str(root_path), 'color': 'red', 'provider': 'azure', 'escaped': '"true"', } dcos_config_path = tmp_path / 'dcos-conf...
64,478
def create_bus(net, level, name, zone=None): """ Create a bus on a given network :param net: the given network :param level: nominal pressure level of the bus :param name: name of the bus :param zone: zone of the bus (default: None) :return: name of the bus """ try: assert l...
64,479
def pdf_handler(logger, pdf_file_name, search_object): """ pdf_handler Reads the pfd and applies transformation rules to extract matching texts and creates a new pdf out of it. :param logger: :param pdf_file_name: :param search_object: :return: """ logger.info("THREAD - pdf_handler -...
64,480
def instantiate_domains(domains, encoding_cnt): """create domain for fields we want to encode. """ instantiated = {} for d in domains: if "/encoding/*" in d: for i in range(encoding_cnt): instantiated[d.replace("/encoding/*", "/encoding/{}".format(i))] = domains[d] else: instantiated[d] = domains[d] r...
64,481
def read_float(data): """ Read 4 bytes of data as `float`. Parameters ---------- data : io.BufferedReader File open to read in binary mode Returns ------- float Python float """ s_type = "=%s" % get_type("float") return struct.unpack(s_type, data.read(4))[0]
64,482
def yt8m(is_training): """YT8M dataset configs.""" return DataConfig( name='yt8m', num_classes=3862, feature_sizes=[1024, 128], feature_names=["rgb", "audio"], max_frames=300, segment_labels=False, segment_size=5, is_training=is_training, split='train' if is_training else 'valid'...
64,483
def _filter_checkerboard_roi(xyz, centroid): """Filters out the data outside the region of interest defined by the checkerboard centroid. Args: xyz: a numpy array of X, Y and Z point cloud coordinates. centroid: a numpy array of X, Y and Z checkerboard centroid coordinates. Returns: ...
64,484
def importable_test_py_files(folder): """Finds all .py files in tests/ folder, used for auto-import validation""" for fname in os.listdir(folder): fpath = os.path.join(folder, fname) if os.path.isdir(fpath): for x in importable_test_py_files(fpath): yield x e...
64,485
def dock_panel(panel_name, base_url=DEFAULT_BASE_URL): """Dock a panel back into the UI of Cytoscape. Args: panel_name (str): Name of the panel. Multiple ways of referencing panels is supported: (WEST == control panel, control, c), (SOUTH == table panel, table, ta), (SOUTH_WEST == tool panel...
64,486
def density(temp): """ Calculating density of water due to given temperature (Eq. 3.11) :param temp: temperature prediction Y[d, t] at depth d and time t :return: corresponding density prediction """ return 1000 * (1 - ((temp + 288.9414) * (temp - 3.9863) ** 2) / (508929.2 * (temp + 68.12963)))
64,487
def create_savu_config_documentation(savu_base_path): """Look at the available commands inside savu_config Create a rst text file for each. """ reference_file_path = f"{savu_base_path}doc/source/reference/" command_file_path = f"{reference_file_path}savu_config_commands.rst" with open(command_f...
64,488
def distance2bbox(points, distance, max_shape=None): """Decode distance prediction to bounding box. Args: points (Tensor): Shape (n, 3), [t, x, y]. distance (Tensor): Distance from the given point to 4 boundaries (left, top, right, bottom, frDis, 4point, bkDis, 4point). max_...
64,489
def paren_matcher_less_space(s: str, open_index: int) -> int: """ Solution: Iterate through the s from the open_paren index, keeping track of how many remaining open parens there are. When we get to 0, return the index. Complexity: Time: O(n) - Iterate through our string once Space: O(1) - We take a slice of th...
64,490
def J_W3(x, y): """ Jacobian for the third layer weights. There is no need to edit this function. """ # First get all the activations and weighted sums at each # layer of the network. a0, z1, a1, z2, a2, z3, a3 = network_function(x) # We'll use the variable J to store parts of our result...
64,491
def projection_from_matrix(matrix, pseudo=False): """Return projection plane and perspective point from projection matrix. Return values are same as arguments for projection_matrix function: point, normal, direction, perspective, and pseudo. >>> point = numpy.random.random(3) - 0.5 >>> normal = nu...
64,492
def is_debug(): """Return True iff the alert level is at least at debugging.""" return cfg.level >= L_DEBUG
64,493
def detect_encoding(filename, limit_byte_check=-1): """Return file encoding.""" try: with open(filename, 'rb') as input_file: encoding = _detect_encoding(input_file.readline) # Check for correctness of encoding. with open_with_encoding(filename, encoding) as input_fi...
64,494
def _partition(lst: list, pivot: object) -> Tuple[list, list]: """Return a partition of <lst> with the chosen pivot. Return two lists, where the first contains the items in <lst> that are <= pivot, and the second is the items in <lst> that are > pivot. """ smaller = [] bigger = [] for item...
64,495
def split_arguments(args, splitter_name=None, splitter_index=None): """Split list of args into (other, split_args, other) between splitter_name/index and `--` :param args: list of all arguments :type args: list of str :param splitter_name: optional argument used to split out specific args :type spl...
64,496
def cumulative_laplace_norm(input): """ Args: input: [B, C, F, T] Returns: """ batch_size, num_channels, num_freqs, num_frames = input.size() input = input.reshape(batch_size * num_channels, num_freqs, num_frames) step_sum = torch.sum(input, dim=1) # [B * C, F, T] => [B, T] cum...
64,497
def requirements(package): """ Build a dictionary with the external dependencies of the {{{project.name}}} project """ # build the package instances packages = [ package(name='python', optional=False), ] # build a dictionary and return it return {{ package.name: package for p...
64,498
def weighted_average_std(grp, weight_col, select_cols=None): """ Based on http://stackoverflow.com/a/2415343/190597 (EOL) """ tmp = grp.select_dtypes(include=[np.number]) weights = tmp[weight_col] if select_cols is not None: values = tmp[select_cols] else: values = tmp.drop(w...
64,499