content
stringlengths
22
815k
id
int64
0
4.91M
def has_conformer(molecule, check_two_dimension=False): """ Check if conformer exists for molecule. Return True or False Parameters ---------- molecule check_two_dimension: bool, optional. Default False If True, will also check if conformation is a 2D conformation (all z coordinates are ...
5,331,100
def pad_sequence(yseqs, batch_first=False, padding_value=0): """Numpy implementation of torch.pad_sequence Args: yseqs (np.ndarray): List of array. (B, *) batch_first (bool): padding_value (int, optional): Padding value. Defaults to 0. Returns: np.ndarray Examples: ...
5,331,101
def http(app): """Flask test client.""" with app.test_client() as client: yield client
5,331,102
async def fetch_sequence_id(session: _session.Session) -> int: """Fetch sequence ID.""" params = { "limit": 0, "tags": ["INBOX"], "before": None, "includeDeliveryReceipts": False, "includeSeqID": True, } log.debug("Fetching MQTT sequence ID") # Same doc id as ...
5,331,103
def test_missing_txn_request(ledger_no_genesis): """ Testing LedgerManager's `_missing_txns` """ ledger = ledger_no_genesis for i in range(20): txn = random_txn(i) ledger.add(txn) # Callbacks don't matter in this test ledger_info = LedgerInfo(0, ledger, *[None] * 6) asse...
5,331,104
def main(args=None): """ Processes command line parameters into options and files, then checks or update FITS DATASUM and CHECKSUM keywords for the specified files. """ errors = 0 fits_files = handle_options(args or sys.argv[1:]) setup_logging() for filename in fits_files: erro...
5,331,105
def parse_transceiver_dom_sensor(output_lines): """ @summary: Parse the list of transceiver from DB table TRANSCEIVER_DOM_SENSOR content @param output_lines: DB table TRANSCEIVER_DOM_SENSOR content output by 'redis' command @return: Return parsed transceivers in a list """ result = [] p = re...
5,331,106
def patches_from_ed_script(source, re_cmd=re.compile(r'^(\d+)(?:,(\d+))?([acd])$')): """Converts source to a stream of patches. Patches are triples of line indexes: - number of the first line to be replaced - one plus the number of the last line to be replaced - list of lin...
5,331,107
def superimposition_matrix( v0: np.ndarray, v1: np.ndarray, scaling: bool = False, usesvd: bool = True ) -> np.ndarray: """ Return matrix to transform given vector set into second vector set. Args: ---- v0: shape (3, *) or (4, *) arrays of at least 3 vectors. v1: shape (...
5,331,108
def add_verbosity(parser, quiet=True): """Add the verbosity and quiet options. parser[in] the parser instance quiet[in] if True, include the --quiet option (default is True) """ parser.add_option("-v", "--verbose", action="count", dest="verbosity", ...
5,331,109
def get_graph_metadata(graph_id: int): """Returns the metadata for a single graph. This is automatically generated by the datasource classes. Parameters ---------- graph_id : int Graph ID. Returns 404 if the graph ID is not found Returns ------- Dict A dictionary r...
5,331,110
def username_exists(username, original=""): """Returns true if the given username exists.""" return username != original and User.objects.filter(username=username).count() > 0
5,331,111
def set_n_jobs(n_jobs: int, x_df: pd.DataFrame) -> int: """ Sets the number of n_jobs, processes to run in parallel. If n_jobs is not specified, the max number of CPUs is used. If n_jobs is set to a higher amount than the number of observations in x_df, n_jobs is rebalanced to match the length of x_df. ...
5,331,112
def group_node_intro_times(filt, groups, n_sents): """ Returns lists of addition times of nodes into particular groups """ devs = [[] for _ in range(len(set(groups)))] for i in range(len(groups)): intro = int(filt[i, i]) devs[groups[i]].append(intro/n_sents) # still normalize additi...
5,331,113
def svn_client_version(): """svn_client_version() -> svn_version_t const *""" return _client.svn_client_version()
5,331,114
def split_dataset_into_train_val_test(save: bool = False) -> None: """Split single-label into training/validation/testing sets.""" # Random index shuffling. pdb_ids = list( tools.read_dict( os.path.join(constants.DATASETS_DIR, 'dataset_single.csv'))) indexes = np.arange(len(pdb_ids))...
5,331,115
def get_slice_name(data_dir, imname, delta=0): """Infer slice name with an offset""" if delta == 0: imname = imname + '.npy' #print('imname0000',imname ) return imname delta = int(delta) dirname, slicename = imname.split(os.sep) #slice_idx = int(slicename[:-4]) slice_idx...
5,331,116
async def test_platform_manually_configured(hass): """Test that we do not discover anything or try to set up a gateway.""" assert ( await async_setup_component( hass, cover.DOMAIN, {"cover": {"platform": deconz.DOMAIN}} ) is True ) assert deconz.DOMAIN not in hass.dat...
5,331,117
def download(name, destination=None, chunksize=4096, force=False): """ Checks if there is an actual version of the specified file on the device, and if not, downloads it from servers. Files, theirs checksums and links to them must be specified in the tps.downloader._content dictionary. :param n...
5,331,118
def getportnum(port): """ Accepts a port name or number and returns the port number as an int. Returns -1 in case of invalid port name. """ try: portnum = int(port) if portnum < 0 or portnum > 65535: logger.error("invalid port number: %s" % port) portnum = -1...
5,331,119
async def test_snips_service_intent(hass): """Test ServiceIntentHandler via Snips.""" await async_mock_mqtt_component(hass) hass.states.async_set("light.kitchen", "off") calls = async_mock_service(hass, "light", "turn_on") result = await async_setup_component(hass, "snips", {"snips": {}}) asser...
5,331,120
def getParafromMinibatchModel(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001, num_epochs = 1500, minibatch_size = 32, print_cost = True): """ Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX. Arguments: X_train -- training set, of s...
5,331,121
def add_land( ax=None, scale="10m", edgecolor=None, facecolor=None, linewidth=None, **kwargs ): """Add land to an existing map Parameters ---------- ax : matplotlib axes object, optional scale : str, optional Resolution of NaturalEarth data to use ('10m’, ‘50m’, or ‘110m'). edgecolo...
5,331,122
def EnsureDispatch(prog_id, bForDemand = 1): # New fn, so we default the new demand feature to on! """Given a COM prog_id, return an object that is using makepy support, building if necessary""" disp = win32com.client.Dispatch(prog_id) if not disp.__dict__.get("CLSID"): # Eeek - no makepy support - try and build ...
5,331,123
def _parallel_predict_log_proba(estimators, estimators_features, X, n_classes): """Private function used to compute log probabilities within a job.""" n_samples = X.shape[0] log_proba = np.empty((n_samples, n_classes)) log_proba.fill(-np.inf) all_classes = np.arange(n_classes, dtype=np.int) for...
5,331,124
def _get_circles(img, board, pattern): """ Get circle centers for a symmetric or asymmetric grid """ h = img.shape[0] w = img.shape[1] if len(img.shape) == 3 and img.shape[2] == 3: mono = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: mono = img flag = cv2.CALIB_CB_SYMMETRI...
5,331,125
def _default_achievement_page(asoup): """ Parses the default steam achievement page Most pages use this """ for ach_row in asoup.find_all(class_="achieveRow"): yield achievement_row_parser(ach_row)
5,331,126
def sort_coords(coords: np.ndarray) -> np.ndarray: """Sort coordinates based on the angle with first coord from the center. Args: coords (np.ndarray): Coordinates to be sorted. The format of coords is as follows. np.array([[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]] Returns: ...
5,331,127
def test_knn_class_with_invalid_params_fit_correctly(): """ The function define a chain with incorrect parameters in the K-nn classification model. During the training of the chain, the parameter 'n_neighbors' is corrected """ samples_amount = 100 k_neighbors = 150 features_options = {'informa...
5,331,128
def to_fraction(value, den_limit=65536): """ Converts *value*, which can be any numeric type, an MMAL_RATIONAL_T, or a (numerator, denominator) tuple to a :class:`~fractions.Fraction` limiting the denominator to the range 0 < n <= *den_limit* (which defaults to 65536). """ try: # int...
5,331,129
def find_closest(myList, myNumber): """ Returns closest value to myNumber. If two numbers are equally close, return the smallest number. # adapted from # https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value """ sortList = sorted(myList) ...
5,331,130
def plot_grid_res(): """The effect of a finer grid""" halo = myname.get_name(7, True) savefile = "boxhi_grid_cutoff_H2_32678.hdf5" ahalo = dp.PrettyBox(halo, 5, nslice=30, savefile=savefile) ahalo.plot_column_density(color="blue", ls="--", moment=True) # savefile = path.join(halo,"snapdir_003/bo...
5,331,131
def remove_uuid_file(file_path, dry=False): """ Renames a file without the UUID and returns the new pathlib.Path object """ file_path = Path(file_path) name_parts = file_path.name.split('.') if not is_uuid_string(name_parts[-2]): return file_path name_parts.pop(-2) new_path = fi...
5,331,132
def run_app(): """ Run application. """ config_file = 'config.json' host = 'localhost' port = 3028 if len(sys.argv) > 1: config_file = sys.argv[1] if len(sys.argv) > 2: host = sys.argv[2] if len(sys.argv) > 3: port = int(sys.argv[3]) print(f"Loading config from ...
5,331,133
def get_9x9x9_scramble(n=120): """ Gets a random scramble (SiGN notation) of length `n` for a 9x9x9 cube. """ return _MEGA_SCRAMBLER.call("megaScrambler.get999scramble", n)
5,331,134
def youku(link): """Find youku player URL.""" pattern = r'http:\/\/v\.youku\.com\/v_show/id_([\w]+)\.html' match = re.match(pattern, link) if not match: return None return 'http://player.youku.com/embed/%s' % match.group(1)
5,331,135
def get_default_service_account(project: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDefaultServiceAccountResult: """ Use this data source to retrieve default service account for this project :param str project: The project ID. If it is...
5,331,136
def combinationSum(candidates, target): """ :type candidates: List[int] :type target: int :rtype: List[List[int]] """ result = [] candidates = sorted(candidates) def dfs(remain, stack): if remain == 0: result.append(stack) return for item in candidates: if item > remain: break if stack...
5,331,137
def create_file(webdav_storage): """ Creates a file with a unique prefix in the WebDAV storage """ from django.core.files.base import ContentFile from django_webdav_storage.compat import PY3, TEXT_TYPE def inner(filename, content=b'', prefix=''): if all((PY3, isinstance(content, TEXT_TY...
5,331,138
def get_Xy(sentence): """将 sentence 处理成 [word1, w2, ..wn], [tag1, t2, ...tn]""" words_tags = re.findall('(.)/(.)', sentence) if words_tags: words_tags = np.asarray(words_tags) words = words_tags[:, 0] tags = words_tags[:, 1] return words, tags # 所有的字和tag分别存为 data / label ...
5,331,139
def write_json_to_file(directory_string, json_content): """ Get the contents of a JSON file. If it doesn't exist, create and populate it with specified or default JSON content. :param directory_string: The relative directory string (ex: database/secrets.json) :type directory_string: str :param ...
5,331,140
def write_zip_file(full_path, zipfile_instance, arcname=None): """ Writes the directory, file or symbolic link using the zipfile instance works with write_to_zip() Args: full_path: full path to file, dir or symlink zipfile_instance: instance of a zipfile created with w or a arcn...
5,331,141
async def test_saving_loading(hass): """Test saving and loading JSON.""" data = hass_auth.Data(MOCK_PATH, None) data.add_user('test-user', 'test-pass') data.add_user('second-user', 'second-pass') with patch(JSON__OPEN_PATH, mock_open(), create=True) as mock_write: await hass.async_add_job(d...
5,331,142
def create_gap_token(rowidx=None): """returns a gap Token Parameters ---------- rowidx: int (Optional) row id Returns ------- Token """ return TT.Token(token_type=SupportedDataTypes.GAP, value='', rowidx=rowidx)
5,331,143
def normalize_readthrough_dates(app_registry, schema_editor): """Find any invalid dates and reset them""" db_alias = schema_editor.connection.alias app_registry.get_model("bookwyrm", "ReadThrough").objects.using(db_alias).filter( start_date__gt=models.F("finish_date") ).update(start_date=models....
5,331,144
def forward_ssh_ports( args, # type: IntegrationConfig ssh_connections, # type: t.Optional[t.List[SshConnectionDetail]] playbook, # type: str target_state, # type: t.Dict[str, t.Tuple[t.List[str], t.List[SshProcess]]] target, # type: IntegrationTarget host_type, # t...
5,331,145
def clear_cache(): """每次运行前都清除 cache""" check_url.cache_clear()
5,331,146
def test_ambiguous_label_pk(setup_codes, parameter_type): """Situation: LABEL of entity_02 is exactly equal to ID of entity_01. Verify that using an ambiguous identifier gives precedence to the ID interpretation Appending the special ambiguity breaker character will force the identifier to be treated as a ...
5,331,147
def get_local_bricks(volume: str) -> Result: """ Return all bricks that are being served locally in the volume volume: Name of the volume to get local bricks for """ vol_info = volume_info(volume) if vol_info.is_err(): return Err(vol_info.value) local_ip = get_local_ip() ...
5,331,148
def delegate_remote(args, exclude, require, integration_targets): """ :type args: EnvironmentConfig :type exclude: list[str] :type require: list[str] :type integration_targets: tuple[IntegrationTarget] """ parts = args.remote.split('/', 1) platform = parts[0] version = parts[1] ...
5,331,149
def unionWCT(m=6, n=6): """ @ worst-case family union where @m>=2 and n>=2 and k=3 :arg m: number of states :arg n: number of states :type m: integer :type n: integer :returns: two dfas :rtype: (DFA,DFA)""" if n < 2 or m < 2: raise TestsError("number of states must both gr...
5,331,150
def set_device_parameters(request): """Set up the class.""" def fin(): request.cls.device.close() request.addfinalizer(fin) request.cls.driver = OriginalDriver request.cls.patched_driver = PatchedDriver request.cls.vendor = 'ibm' parent_conftest.set_device_parameters(request)
5,331,151
def week_changes (after, before, str_dates, offset = 0, limit = 3) : """Yield all elements of `str_dates` closest to week changes.""" return unit_changes (after, before, str_dates, "week", offset, limit)
5,331,152
def getHiddenStatus(data): """ 使用Gaussian HMM对数据进行建模,并得到预测值 """ cols = ["r_5", "r_20", "a_5", "a_20"] model = GaussianHMM(n_components=3, covariance_type="full", n_iter=1000, random_state=2010) model.fit(data[cols]) hiddenStatus = model.predict(data[cols]) return hiddenStatus
5,331,153
def format_time(data, year): """Format any time variables in US. Parameters ---------- data : pd.DataFrame Data without time formatting. year : int The `year` of the wave being processed. Returns ------- data : pd.DataFrame Data with time formatting. """ ...
5,331,154
def get_connection(sid): """ Attempts to connect to the given server and returns a connection. """ server = get_server(sid) try: shell = spur.SshShell( hostname=server["host"], username=server["username"], password=server["password"], por...
5,331,155
def compare_apertures(reference_aperture, comparison_aperture, absolute_tolerance=None, attribute_list=None, print_file=sys.stdout, fractional_tolerance=1e-6, verbose=False, ignore_attributes=None): """Compare the attributes of two apertures. Parameters ---------- reference_aperture comparison_aper...
5,331,156
def tail(filename: str, nlines: int = 20, bsz: int = 4096) -> List[str]: """ Pure python equivalent of the UNIX ``tail`` command. Simply pass a filename and the number of lines you want to load from the end of the file, and a ``List[str]`` of lines (in forward order) will be returned. This function...
5,331,157
def initialized(name, secret_shares=5, secret_threshold=3, pgp_keys=None, keybase_users=None, unseal=True): """ Ensure that the vault instance has been initialized and run the initialization if it has not. :param name: The id used for the state definition :param secret_shares: THe nu...
5,331,158
def plot(plot, x, y, **kwargs): """ Adds series to plot. By default this is displayed as continuous line. Refer to matplotlib.pyplot.plot() help for more info. X and y coordinates are expected to be in user's data units. Args: plot: matplotlib.pyplot Plot to which series sho...
5,331,159
def assert_not_has_text(output, text): """ Asserts specified output does not contain the substring specified by the argument text.""" assert output is not None, "Checking not_has_text assertion on empty output (None)" assert output.find(text) < 0, "Output file contains unexpected text '%s'" % text
5,331,160
def glyph_by_hershey_code(hershey_code): """ Returns the Hershey glyph corresponding to `hershey_code`. """ glyph = glyphs_by_hershey_code.get(hershey_code) if glyph is None: raise ValueError("No glyph for hershey code %d" % hershey_code) return glyph
5,331,161
def _get_prefab_from_address(address): """ Parses an address of the format ip[:port] and return return a prefab object connected to the remote node """ try: if ':' in address: ip, port = address.split(':') port = int(port) else: ip, port = add...
5,331,162
def interval_to_errors(value, low_bound, hi_bound): """ Convert error intervals to errors :param value: central value :param low_bound: interval low bound :param hi_bound: interval high bound :return: (error minus, error plus) """ error_plus = hi_bound - value error_minus = value ...
5,331,163
def actionSetHelperNodeNoRecur(s, l, st, t): """ Set as helper node which is not recursively processed by editor and renderers even if it is unknown """ if t.name != None: t.helperNode = True t.helperRecursive = False else: t[0].helperNode = True t[0].he...
5,331,164
def log_enabled_arg(request: Any) -> bool: """Using different log messages. Args: request: special fixture that returns the fixture params Returns: The params values are returned one at a time """ return cast(bool, request.param)
5,331,165
def test_set_and_get_property_from_clr(): """Test setting and getting clr-accessible properties from the clr.""" t = ExampleClrClass() assert t.GetType().GetProperty("X").GetValue(t) == 3 assert t.GetType().GetProperty("Y").GetValue(t) == 3 * 2 t.GetType().GetProperty("X").SetValue(t, 4) assert ...
5,331,166
def do(args): """ Main entry point """ reset = args.reset git_worktree = qisrc.parsers.get_git_worktree(args) sync_ok = git_worktree.sync() if not sync_ok: sys.exit(1) git_projects = qisrc.parsers.get_git_projects(git_worktree, args, defa...
5,331,167
def expsign(sign, exp): """ optimization of sign ** exp """ if sign == 1: return 1 assert sign == -1 return -1 if exp % 2 else 1
5,331,168
def convert_format(tensors, kind, target_kind): """Converts data from format 'kind' to one of the formats specified in 'target_kind' This allows us to convert data to/from dataframe representations for operators that only support certain reprentations """ # this is all much more difficult because o...
5,331,169
def template2path(template, params, ranges=None): """Converts a template and a dict of parameters to a path fragment. Converts a template, such as /{name}/ and a dictionary of parameter values to a URL path (string). Parameter values that are used for buildig the path are converted to strings usin...
5,331,170
def calculate_total_matched( market_book: Union[Dict[str, Any], MarketBook] ) -> Union[int, float]: """ Calculate the total matched on this market from the amounts matched on each runner at each price point. Useful for historic data where this field is not populated :param market_book: A market book ei...
5,331,171
def parse_args(args): """Build parser object with options for sample. Returns: Python argparse parsed object. """ parser = argparse.ArgumentParser( description="A VCF editing utility which adds ref and all sequences to a SURVIVOR fasta file.") parser.add_argument("--reference-fasta...
5,331,172
def _newline_to_ret_token(instring): """Replaces newlines with the !RET token. """ return re.sub(r'\n', '!RET', instring)
5,331,173
def _ComputeLineCounts(old_lines, chunks): """Compute the length of the old and new sides of a diff. Args: old_lines: List of lines representing the original file. chunks: List of chunks as returned by patching.ParsePatchToChunks(). Returns: A tuple (old_len, new_len) representing len(old_lines) and...
5,331,174
def dirac_api_client(host="localhost", port=18861): """RPC DIRAC API client context.""" conn = rpyc.connect(host, port, config={"allow_public_attrs": True}) try: yield conn.root.dirac_api finally: conn.close()
5,331,175
def __check_session_gap_expired_time(session_gap, expired_time, flink_window_type): """ 校验窗口配置项:统计频率 :param session_gap: 间隔时间 :param expired_time: 过期时间 :param flink_window_type: 窗口类型 """ if flink_window_type == SESSION: # 间隔时间(单位:s) if session_gap not in [0, 10, 30, 60, 180,...
5,331,176
def _read_int(file_handle, data_size): """ Read a signed integer of defined data_size from file. :param file_handle: The file handle to read from at current position :param data_size: The data size in bytes of the integer to read :returns: The integer read and decoded """ return int.from_...
5,331,177
def quaternion_to_matrix(quat): """OI """ qw = quat[0][0] qx = quat[1][0] qy = quat[2][0] qz = quat[3][0] rot = numpy.array([[1 - 2*qy*qy - 2*qz*qz, 2*qx*qy - 2*qz*qw, 2*qx*qz + 2*qy*qw], [2*qx*qy + 2*qz*qw, 1 - 2*qx*qx - 2*qz*qz, 2*qy*qz - 2*qx*qw], [2*qx*qz - 2*qy*qw, 2*qy*qz + 2*qx*qw...
5,331,178
def start_metrics_process(): """ Start metrics process that performs periodic monitoring activities :return: None """ stop_metrics_process() #start metrics watcher oneagent_filepath = os.path.join(os.getcwd(),'agent.py') args = ['python{0}'.format(sys.version_info[0]), oneagent_fil...
5,331,179
def get_cart_from_request(request, create=False): """Returns Cart object for current user. If create option is True, new cart will be saved to db""" cookie_token = request.get_signed_cookie( Cart.COOKIE_NAME, default=None) if request.user.is_authenticated(): user = request.user ...
5,331,180
def make_concrete_rule(rule_no, zone_map, direction, zone, rule, concrete_port): """Take a rule and create a corresponding concrete rule.""" def make_rule(target_zone, port): return ConcreteRule(source_rules=[rule], rule_no=rule_no, target_zone=target_zone, direction=directi...
5,331,181
def downcast(df: pd.DataFrame, signed_columns: List[str] = None) -> pd.DataFrame: """ Automatically check for signed/unsigned columns and downcast. However, if a column can be signed while all the data in that column is unsigned, you don't want to downcast to an unsigned column. You can explicitly pass ...
5,331,182
def gen_even_BMS_tree(fanout): """This generalization hierarchy for BMS-WebView-2.dat is defined according to even fan-out (average distribution). For large dataset fanout = 5, for small dataset fanout = 4 """ need_static = False static_value = [] BMS_tree = open('data/treefile_BMS.txt', '...
5,331,183
def get_setting(name): """ Hook for getting Django settings and using properties of this file as the default. """ me = sys.modules[__name__] return getattr(settings, name, getattr(me, name, None))
5,331,184
def test_parse_hello_world_template(): """Extract commands and output files from the 'Hello world' template.""" template = WorkflowTemplate.from_dict(doc=util.read_object(TEMPLATE_HELLOWORLD)) steps, args, output_files = parser.parse_template(template=template, arguments={'names': 'names.txt', 'sleeptime': ...
5,331,185
def checkCrowDist(comment,dist,expectedCrowDist): """ Check the consistency of the crow distributions @ In, comment, string, a comment @ In, dist, instance, the distribution to inquire @ In, expectedCrowDist, dict, the dictionary of the expected distribution (with all the parameters) @ Out, None ...
5,331,186
def entity_type(entity: dict) -> Optional[str]: """ Safely get the NGSI type of the given entity. The type, if present, is expected to be a string, so we convert it if it isn't. :param entity: the entity. :return: the type string if there's an type, `None` otherwise. """ return maybe_ma...
5,331,187
def read_private_key_data(bio): """ Read enough data from bio to fully read a private key. (The data read is thrown away, though.) This is required since the format does not contain the actual length of the privately-serialized private key data. The knowledge of what to read for each key type...
5,331,188
def list_check(lst): """Are all items in lst a list? >>> list_check([[1], [2, 3]]) True >>> list_check([[1], "nope"]) False """ t = [1 if isinstance(x, list) else 0 for x in lst] return len(lst) == sum(t)
5,331,189
def check_for_peaks_in_residual(vel, data, errors, best_fit_list, dct, fitted_residual_peaks, signal_ranges=None, signal_mask=None, force_accept=False, params_min=None, params_max=None, noise_spike_mask=None): """Try fit...
5,331,190
def build_encoded_manifest_from_nested_directory( data_directory_path: str, ) -> Dict[str, EncodedVideoInfo]: """ Creates a dictionary from video_id to EncodedVideoInfo for encoded videos in the given directory. Args: data_directory_path (str): The folder to ls to find encoded video...
5,331,191
def test_photoslibrary_hidden(photoslib): """ Test hidden """ import time import photoscript # due to pytest weirdness, need to create a new photoslib object # to get hide and hidden to work as they would in a real script photoslib.quit() photoslib = photoscript.PhotosLibrary() photosl...
5,331,192
def assert_different_renderings(expected_width, expected_height, documents): """ Render HTML documents to PNG and check that no two documents render the same. Each document is passed as a (name, html_source) tuple. """ pixels_list = [] for name, html in documents: _doc, pixels = ht...
5,331,193
def derive_question(doc): """ Return a string that rephrases an action in the doc in the form of a question. 'doc' is expected to be a spaCy doc. """ verb_chunk = find_verb_chunk(doc) if not verb_chunk: return None subj = verb_chunk['subject'].text obj = verb_chunk['object'].text if verb_chunk['verb'].tag_ ...
5,331,194
def install_cover(disc, only_from_cache=False): """ Installs the symbolic links in the moOde directories making the cover arts accessible for the web site. """ cover = get_cover(disc,only_from_cache) dest = moode_cd_dir(disc) if cover is not None: source = cache_dir(disc) else...
5,331,195
def recover_label(pred_variable, gold_variable, mask_variable, label_alphabet, word_recover, sentence_classification=False): """ input: pred_variable (batch_size, sent_len): pred tag result gold_variable (batch_size, sent_len): gold result variable mask_variable (batch_si...
5,331,196
def RegenerateOverview(*args, **kwargs): """ RegenerateOverview(Band srcBand, Band overviewBand, char const * resampling="average", GDALProgressFunc callback=0, void * callback_data=None) -> int """ return _gdal.RegenerateOverview(*args, **kwargs)
5,331,197
def compute_divergences( corpus, load_src, _log, _run, max_length=None, word_emb_path="wiki.id.vec", src_key_as_lang=False, device="cpu", batch_size=16, ): """Compute divergences of source taggers a la Heskes (1998).""" if max_length is None: max_length = {} samp...
5,331,198
def assert_set_equality(set1: Set[Any], set2: Set[Any]) -> None: """Assert that the sets are the same.""" diff1 = set1.difference(set2) diff2 = set2.difference(set1) if diff1 or diff2: error_message_list = ["Expected sets to have the same keys."] if diff1: error_message_list...
5,331,199