content
stringlengths
22
815k
id
int64
0
4.91M
def options(): """ pylbm command line options """ parser = ArgumentParser() logging = parser.add_argument_group('log') logging.add_argument("--log", dest="loglevel", default="WARNING", choices=['WARNING', 'INFO', 'DEBUG', 'ERROR'], help="Set the ...
9,800
def omni_load(dates, level, downloadonly=False, varformat=None, get_support_data=False, prefix='', suffix=''): """Loads OMNI data into pytplot variables""" file_list = omni_filename(dates, level) # 1. Download files count = 0 downloaded_files = [] for remotef, localf in file_list...
9,801
def compte_var(f, var): """compte le nombre d'apparition de la variable var dans f""" n = f.nb_operandes() if n == 0: v = f.get_val() if v == var: return 1 else: return 0 elif n == 1: f2 = (f.decompose())[0] return compte_var(f2,...
9,802
def inject_vars(): # 函数名可以随意修改 """模板上下文处理函数""" from watchlist.models import User user = User.query.first() # 用户对象 if not user: user = User() user.name = 'BL00D' return locals()
9,803
def try_parse_section(text: str, section_name: str) -> str: """ Parse a section. Return an empty string if section not found. Args: text (str): text section_name (str): section's name Returns: (str): section """ try: return parse_section(text, section_name) ...
9,804
def client_code2(component1: ComponentInterface, component2: ComponentInterface) -> None: """ Thanks to the fact that the child-management operations are declared in the base Component class, the client code can work with any component, simple or complex, without depending on their concrete classes. ...
9,805
def on_handshake(bot): """Hook function called when the bot starts, after handshake with the server. Here the bot already knows server enforced dimensions (defined in server side bots.cfg file). This is called right before starting to poll for tasks. It's a good time to do some final initialization or clean...
9,806
def run_all(base_logdir): """Generate waves of the shapes defined above. For each wave, creates a run that contains summaries. Arguments: base_logdir: the directory into which to store all the runs' data """ waves = [ ("sine_wave", sine_wave), ("square_wave", square_wave), ...
9,807
def test_power(): """Test computing and saving PSD.""" fmin = 0.1 fmax = 300 compute_and_save_psd(raw_fname, fmin, fmax, method='welch') compute_and_save_psd(raw_fname, fmin, fmax, method='multitaper')
9,808
def get_location_based_lifers(web_page): """ a method that takes in a web page and returns back location frequency for lifers and lifer details. """ bs4_object = BeautifulSoup(web_page, html_parser) table_list = bs4_object.find_all('li', class_=myebird_species_li_class) lifer_data_list = [] ...
9,809
def parse_show_qos_queue_profile(raw_result): """ Parse the show command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the 'show qos queue-profile' command in a \ dictionary: for 'show qos queue-profile': :: { ...
9,810
def glVertex3sv(v): """ v - seq( GLshort, 3) """ if 3 != len(v): raise TypeError(len(v), "3-array expected") _gllib.glVertex3sv(v)
9,811
def plot_png(num_x_points=50): """ renders the plot on the fly. """ fig = Figure() axis = fig.add_subplot(1, 1, 1) x_points = range(num_x_points) axis.plot(x_points, [random.randint(1, 30) for x in x_points]) output = io.BytesIO() FigureCanvasAgg(fig).print_png(output) return Respon...
9,812
def render_message(session, window, msg, x, y): """Render a message glyph. Clears the area beneath the message first and assumes the display will be paused afterwards. """ # create message box msg = GlyphCoordinate(session, msg, x, y) # clear existing glyphs which intersect for gl...
9,813
def part_one(filename='input.txt', target=2020): """Satisfies part one of day one by first sorting the input rows so we can avoid the worst case O(n**2). We incur O(n log n) to do the sort followed by a brute force search with short circuiting if the sum exceeds our target. This is possible since we kno...
9,814
def get_urls(name, version=None, platform=None): """ Return a mapping of standard URLs """ dnlu = rubygems_download_url(name, version, platform) return dict( repository_homepage_url=rubygems_homepage_url(name, version), repository_download_url=dnlu, api_data_url=rubygems_api_...
9,815
def add_spot_feature (model, feature, name, short_name, dimension, is_int): """ Add a new spot feature to the model object. This must be done for custom features added using spot.putFeature to get properly integrated into the model. The trackmate model object is modified in-place. """ feature_model = model.getF...
9,816
def getEHfields(m1d, sigma, freq, zd, scaleUD=True, scaleValue=1): """Analytic solution for MT 1D layered earth. Returns E and H fields. :param discretize.base.BaseMesh, object m1d: Mesh object with the 1D spatial information. :param numpy.ndarray, vector sigma: Physical property of conductivity correspond...
9,817
def nested_tags(dst_client, run_ids_mapping): """ Set the new parentRunId for new imported child runs. """ for _,(dst_run_id,src_parent_run_id) in run_ids_mapping.items(): if src_parent_run_id: dst_parent_run_id,_ = run_ids_mapping[src_parent_run_id] dst_client.set_tag(ds...
9,818
def write_dataset(src_dir, dst_file, limit_rows=0): """Reads JSON files downloaded by the Crawler and writes a CSV file from their data. The CSV file will have the following columns: - repo_id: Integer - issue_number: Integer - issue_title: Text - issue_body_md: Text, in Markdown format, ca...
9,819
def repeated(f, n): """Returns a function that takes in an integer and computes the nth application of f on that integer. Implement using recursion! >>> add_three = repeated(lambda x: x + 1, 3) >>> add_three(5) 8 >>> square = lambda x: x ** 2 >>> repeated(square, 2)(5) # square(square(...
9,820
def method_functions(): """ Returns a dictionary containing the valid method keys and their corresponding dispersion measure functions. """ return _available
9,821
def get_file_names(maindir, sessid, expid, segid, date, mouseid, runtype="prod", mouse_dir=True, check=True): """ get_file_names(maindir, sessionid, expid, date, mouseid) Returns the full path names of all of the expected data files in the main directory for the specified session a...
9,822
def get_key_vault_output(name: Optional[pulumi.Input[str]] = None, resource_group_name: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetKeyVaultResult]: """ Use this data source to access information about an ...
9,823
def generate_auth_token(): """Generate a token using jwt. Returns: token. """ key = PRIVATE_KEY data = {'appId': APPLICATION_ID} token = jwt.encode(data, key, algorithm='RS256') return token
9,824
def dict_expand(d: Dict[Any, Any]) -> List[Dict[Any, Any]]: """Converts a dictionary of lists to a list of dictionaries. The resulting list will be of the same length as the longest dictionary value. If any values are not lists then they will be repeated to the required length. Args: d: Th...
9,825
def get_asexual_lineage_num_discrete_state_changes(lineage, attribute_list): """Get the number of discrete state changes from an asexual lineage. State is described by the aggregation of all attributes give by attribute list. Args: lineage (networkx.DiGraph): an asexual lineage attribute_l...
9,826
def check_downloaded(dataset: str, directory: str = None) -> bool: """ Check whether dataset is downloaded Args: dataset (str): String of dataset's name, e.g. ml-100k, bx directory (str, optional): String of directory of downloaded data. Defaults to None...
9,827
def do_main(title): """main skeleton""" filename = title + "_ref" lst = read_distr_list(filename + ".txt") with open(filename + ".csv", "wt") as fout: for (ex, name, args) in lst: d = to_scipy_dist(name, args) m = d.mean() v = d.var() ent = d.entropy() x25 = d.ppf(0.25) x50 = d.ppf(0.50) ...
9,828
def enterprise_1_9_installer() -> Path: """ Return the path to an installer for DC/OS Enterprise 1.9. """ return Path('/tmp/dcos_generate_config_1_9.ee.sh')
9,829
def Laplacian(n): """ Create Laplacian on 2-dimensional grid with n*n nodes """ B = forward_diff_matrix(n) D = -B.T @ B Dx = sparse.kron(sparse.eye(n), D).tocsr() Dy = sparse.kron(D, sparse.eye(n)).tocsr() return Dx + Dy
9,830
def move_clip_down(base_node, clip, comparison_response): """ Moves a given clip to a lower node the the redblack search/sort tree. If possible it recursively moves the clip multiple steps down, but usually just goes one step. Raises NewNodeNeeded if it hits the bottom of the tree. """ # Okay, t...
9,831
def LookupGitSVNRevision(directory, depth): """ Fetch the Git-SVN identifier for the local tree. Parses first |depth| commit messages. Errors are swallowed. """ if not IsGitSVN(directory): return None git_re = re.compile(r'^\s*git-svn-id:\s+(\S+)@(\d+)') proc = RunGitCommand(directory, ['log', '-' ...
9,832
def collect_jars( dep_targets, dependency_analyzer_is_off = True, unused_dependency_checker_is_off = True, plus_one_deps_is_off = True): """Compute the runtime and compile-time dependencies from the given targets""" # noqa if dependency_analyzer_is_off: return _collect_...
9,833
def describe_vpn_gateways(DryRun=None, VpnGatewayIds=None, Filters=None): """ Describes one or more of your virtual private gateways. For more information about virtual private gateways, see Adding an IPsec Hardware VPN to Your VPC in the Amazon Virtual Private Cloud User Guide . See also: AWS API Docum...
9,834
def _checkBounds(_datetimes,datetimes): """ """ dt_min=np.min(datetimes) dt__min=np.min(_datetimes) dt_max=np.max(datetimes) dt__max=np.max(_datetimes) if dt_min <dt__min:raise Exception("{} is below reference datetimes {}".format(dt_min,dt__min)) if dt_max >dt__max:raise Exception("{} is above refere...
9,835
def _cred1_adapter(user=None, password=None): """Just a sample adapter from one user/pw type to another""" return dict(user=user + "_1", password=password + "_2")
9,836
def prepare(path, dest): """ Extend file and prepend dictionary to it """ with open(path, 'rb') as f: data = f.read() prepare_file(data, dest)
9,837
def acc_metric(y_true, y_pred): """ Accuracy """ diff = K.abs(y_pred - y_true) * 5000 return K.mean(diff, axis=-1)
9,838
def prepare_env(): """This function implements main logic of preparation Virtual machines for Kubernetes installation: * Read configs from files. * Validates Nutanix environment. * Prepare base Virtual Machine. * Clone base Virtual Machine. * Turn on Virtual Machines. * Read Virtual Mac...
9,839
def whereSnippet(snippet): """ Show which snippets (note the plural) would be used, in order of precedence. """ logger.debug("Called whereSnippet(%s)..." % snippet)
9,840
def promote(source, dest): """Promote the docker image from SOURCE to DEST. Promote a docker image, for example promote the docker image for the local environment to the dev environment. Promoting a docker images involves re-tagging the image locally with the proper label and then pushing the image...
9,841
async def confirm(message: discord.Message, fallback: str = None) -> bool: """ Helper function to send a checkmark reaction on a message. This would be used for responding to a user that an action completed successfully, without sending a whole other message. If a checkmark reaction cannot be added,...
9,842
def get_layer_version( lambda_client: BaseClient, layer_name: str, version: int, ) -> "definitions.LambdaLayer": """Retrieve the configuration for the specified lambda layer.""" return definitions.LambdaLayer( lambda_client.get_layer_version( LayerName=layer_name, Ver...
9,843
def get_detail_msg(detail_url): """ 2.获取某个职位的详细数据 :param detail_url: 职位详细页面的url :return: 职位数据 """ # print('请求的详细地址是:' + detail_url) response = requests.get(detail_url, headers=HEADERS) html_element = etree.HTML(response.text) position = {} # 【数据】获取职位标题 title = html_element.xpath('//tr[@class="h"]/td/text()...
9,844
def wizard_process_received_form(form): """ Processing of form received during the time measure Expected result example: {1: '00:43.42', 2: '00:41.35', 3: '00:39.14', 4: '00:27.54'} """ lines = {key.split('_')[1]: value.split('_')[1] for key, value in form.items() if key.startswith("line")} # print(...
9,845
def tmp_file(request): """ Create a temporary file with a FASTQ suffix. :param request: SubRequest with ``param`` member which has \ a FASTQ suffix :type request: _pytest.fixtures.SubRequest :return: path to temporary file :rtype: str or unicode """ _, tmp_file = tempfile.mkstemp(pr...
9,846
def getsource(obj,is_binary=False): """Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to co...
9,847
def test_mix_cells_from_gds_and_from_function2(): """Ensures not duplicated cell names. when cells loaded from GDS and have the same name as a function with @cell decorator """ c = gf.Component("test_mix_cells_from_gds_and_from_function") c << gf.c.mzi() c << gf.import_gds(gdspath) c.wri...
9,848
def take_screenshot(): """Saves a screenshot of the current window in the 'screenshots' directory.""" timestamp = f"{pd.Timestamp('today'):%Y-%m-%d %I-%M %p}" path = ''.join(( './screenshots/', 'screenshot ', timestamp, '.png') ) driver.save_screenshot(path)
9,849
def extract_sector_id(room): """Given a room identifier of the form: 'aaa-bbb-cc-d-e-123[abcde]' Return the sector id: '123' """ m = re.search(r'(?P<sector_id>\d+)', room) return m.group('sector_id') if m else None
9,850
def test_Covmat(): """ Test the Covmat function by checking that its inverse function is Qmat """ n = 1 B = np.random.rand(n, n) + 1j * np.random.rand(n, n) B = B + B.T sc = find_scaling_adjacency_matrix(B, 1) idm = np.identity(2 * n) X = Xmat(n) Bsc = sc * B A = np.block([[...
9,851
def splitext_all(_filename): """split all extensions (after the first .) from the filename should work similar to os.path.splitext (but that splits only the last extension) """ _name, _extensions = _filename.split('.')[0], '.'.join(_filename.split('.')[1:]) return(_name, "."+ _extensions)
9,852
def catch(func, *args, **kw): """Catch most exceptions in 'func' and prints them. Use to decorate top-level functions and commands only. """ # d: print("calling %s with args %s, %s" % (func.__name__, args, kw)) try: return func(*args, **kw) except Exception as e: print(e) ...
9,853
def tag_in_tags(entity, attribute, value): """ Return true if the provided entity has a tag of value in its tag list. """ return value in entity.tags
9,854
def generate_finding_title(title): """ Generate a consistent title for a finding in AWS Security Hub * Setup as a function for consistency """ return "Trend Micro: {}".format(title)
9,855
def makeHexagon(x,y,w,h): """Return hexagonal QPolygon. (x,y) is top left coner""" points=[] cos=[1.,0.5,-0.5,-1,-0.5,0.5] sin=[0,0.866025,0.866025,0,-0.866025,-0.866025] for i in range(len (cos)): points.append(QPoint(x+w*cos[i],y+h*sin[i])) return QPolygonF(points)
9,856
def save_conv_output(activations, name): """ Saves layer output in activations dict with name key """ def get_activation(m, i, o): activations[name] = F.relu(o).data.cpu().numpy() return get_activation
9,857
async def get_profile_xp(user_id: int): """ Get a user's profile xp. :param user_id: Discord User ID """ return (await self.conn.fetchrow("SELECT profilexp FROM currency.levels WHERE userid = $1", user_id))[0]
9,858
def tryrmcache(dir_name, verbose=False): """ removes all __pycache__ starting from directory dir_name all the way to leaf directory Args: dir_name(string) : path from where to start removing pycache """ # directory_list = list() is_removed = False for root, dirs, _ in os.walk(di...
9,859
def extract_codeblocks(): """Extract CodeBlocks files from archive to test directory. """ remove_test_directory("codeblocks-*") remove_test_directory("[Cc]ode[Bb]locks") extract_test_tar("codeblocks*.gz", "codeblocks*.tar", ["*.cpp", "*.cxx", "*.h"]) rename_test_directory("codeblocks-*", "CodeBl...
9,860
def _add_msg_to_file(filename, msg): """Add the message to the specified file Args: filename (str): path to the file msg (str): message to be appended to the file """ with open(filename, 'a+') as f: f.write('{0}\n'.format(msg))
9,861
def validate_raw_data(data: Optional[UserPackage]) -> bool: """Returns False if invalid data""" # NOTE: add more validation as more fields are required if data is None or data.contribs is None: return False if ( data.contribs.total_stats.commits_count > 0 and len(data.contribs.t...
9,862
def pretty_print_scene_objects(scene): """Pretty prints scene objects. Args: scene: Scene graph containing list of objects """ for index, ii in enumerate(scene['objects']): print_args = (index, ii['shape'], ii['color'], ii['size'], ii['material']) print('\t%d : %s-%s-%s-%s' % print_args)
9,863
def extractTheSunIsColdTranslations(item): """ Parser for 'The Sun Is Cold Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if '108 maidens' in item['tags']: return buildReleaseMessageWithType(ite...
9,864
async def main(): """Turn on the fan light.""" async with aiomodernforms.ModernFormsDevice("192.168.3.197") as fan: await fan.update() print(fan.status) await fan.light( on=LIGHT_POWER_ON, brightness=50, sleep=datetime.now() + timedelta(minutes=2), ...
9,865
def to_device(x, device): """Cast a hierarchical object to pytorch device""" if isinstance(x, torch.Tensor): return x.to(device) elif isinstance(x, dict): for k in list(x.keys()): x[k] = to_device(x[k], device) return x elif isinstance(x, list) or isinstance(x, tuple)...
9,866
def test_dwpli(): """Test the Debiased WPLI algorithm.""" # Groundtruth expected = np.load("groundtruth/fc/dwpli.npy") expected = np.nan_to_num(expected) # Data data = np.load("sample_data/fc/eeg_32chans_10secs.npy") # Run csdparams = {"NFFT": 256, "noverlap": 256 / 2.0} dwpliv =...
9,867
def git_show_oneline(obj): """Returns: One-line description of a git object `obj`, which is typically a commit. https://git-scm.com/docs/git-show """ return exec_headline(['git', 'show', '--oneline', '--quiet', obj])
9,868
def like_post(): """ Like a post """ try: # This will prevent old code from adding invalid post_ids post_id = int(request.args.get('post_id', '-1')) if post_id < 0: return "No Post Found to like!" vote = (db_session.query(Vote) .filter(and_(Vote.object...
9,869
def login_post(): """Obdelaj izpolnjeno formo za prijavo""" # Uporabniško ime, ki ga je uporabnik vpisal v formo username = bottle.request.forms.user # Izračunamo MD5 hash geslo, ki ga bomo spravili password = password_md5(bottle.request.forms.psw) # Preverimo, ali se je uporabnik pravilno prij...
9,870
def parse_symbol_file(filepath, fapi=None): """Read in stock symbol list from a text file. Args: filepath: Path to file containing stock symbols, one per line. fapi: If this is supplied, the symbols read will be conformed to a financial API; currently 'google' or 'yahoo'. Retur...
9,871
def trader_tactic_snapshot(symbol, strategy, end_dt=None, file_html=None, fq=True, max_count=1000): """使用聚宽的数据对任意标的、任意时刻的状态进行策略快照 :param symbol: 交易标的 :param strategy: 择时交易策略 :param end_dt: 结束时间,精确到分钟 :param file_html: 结果文件 :param fq: 是否复权 :param max_count: 最大K线数量 :return: trader """...
9,872
def preprocess(batch): """ Add zero-padding to a batch. """ tags = [example.tag for example in batch] # add zero-padding to make all sequences equally long seqs = [example.words for example in batch] max_length = max(map(len, seqs)) seqs = [seq + [PAD] * (max_length - len(seq)) for seq in seqs...
9,873
def policy_update(updated_policies, removed_policies=None, policies=None, **kwargs): """Policy update task This method is responsible for updating the application configuration and notifying the applications that the change has occurred. This is to be used for the dcae.interfaces.policy.policy_update o...
9,874
def append_include_as(include_match): """Convert ``#include x`` to ``#include x as y``, where appropriate; also, convert incorrect "as" statements. See INCLUDE_AS dict for mapping from resource to its "as" target. Parameters ---------- include_match : re._pattern_type Match produced by ...
9,875
def get_user_profiles(page=1, limit=10): """Retrieves a list of user profiles. :param page: Page number :type page: int :param limit: Maximum number of results to show :type limit: int :returns: JSON string of list of user profiles; status code :rtype: (str, int) """ # initialize q...
9,876
def _repository(): """Helper dependency injection""" db = sqlite3.connect('covid_database.db', isolation_level=None) return CovidTestDataRepository(db)
9,877
def f(x): """Cubic function.""" return x**3
9,878
def test_polynomial(): """Interpolate f(x) = 1 + 2x + 3x**2.""" f = np.polynomial.polynomial.Polynomial((1, 2, 3)) x = np.arange(0, 1000, 0.01) y = np.array([f(i) for i in x]) interpolater = cubicspline.Interpolater(x, y) for x_ in np.asarray([0, 1, 0.0998, 456, 666.666, 998.501, 999.98, 99.989...
9,879
def req_cache(*args, **kwargs): """ Cache decorate for `ruia.Request` class :param args: :param kwargs: :return: """ fetch_func = args[0] @wraps(fetch_func) async def wrapper(self, delay=True): cache_resp = None url_str = f"{self.url}:{self.method}" req_url...
9,880
def display_df(df: Union[pd.DataFrame, pandas.io.formats.style.Styler]) -> pd.DataFrame: """Plot a dataframe with `max_rows` set to None aka infinity, optionally print the DataFrame's head with the given number.""" options = { "display.max_rows": None, "display.max_colwidth": None, "...
9,881
def test_fields_value(test_endpoint): """Test that ValueError is raised if invalid fields values are passed.""" with pytest.raises(ValueError): test_endpoint.filters = False
9,882
def correct_anomalies(peaks, alpha=0.05, save_name=""): """ Outlier peak detection (Grubb's test) and removal. Parameters ---------- peaks : array vector of peak locations alpha : real significance level for Grubb's test save_name : str filename to save peaks as to, ...
9,883
def svn_wc_walk_entries(*args): """ svn_wc_walk_entries(char path, svn_wc_adm_access_t adm_access, svn_wc_entry_callbacks_t walk_callbacks, void walk_baton, svn_boolean_t show_hidden, apr_pool_t pool) -> svn_error_t """ return apply(_wc.svn_wc_walk_entries, args)
9,884
def extract_torrents(provider, client): """ Main torrent extraction generator for non-API based providers Args: provider (str): Provider ID client (Client): Client class instance Yields: tuple: A torrent result """ definition = definitions[provider] definition = get_al...
9,885
def dlp_to_datacatalog_builder( taskgroup: TaskGroup, datastore: str, project_id: str, table_id: str, dataset_id: str, table_dlp_config: DlpTableConfig, next_task: BaseOperator, dag, ) -> TaskGroup: """ Method for returning a Task Group for scannign a table with DLP, and creating B...
9,886
def upload_assessors(xnat, projects, resdir, num_threads=1): """ Upload all assessors to XNAT :param xnat: pyxnat.Interface object :param projects: list of projects to upload to XNAT :return: None """ # Get the assessor label from the directory : assessors_list = get_assessor_list(proje...
9,887
def save_txt(content, filename, append=False, empty=False): """ Save the content onto a file. :param content: (string) the string content to save. :param filename: (string) the absolute file path. :param append: (bool) if True, append to an existing file. :param empty: (bool) if True, the file i...
9,888
def dedent(ind, text): """ Dedent text to the specific indentation level. :param ind: common indentation level for the resulting text (number of spaces to append to every line) :param text: text that should be transformed. :return: ``text`` with all common indentation removed, and then the specifie...
9,889
def since(timestamp=None, directory=os.getcwd()): # noqa WPS404, B008 """since.""" if not timestamp: return WRONG_ARGUMENT try: timestamp = int(timestamp) except Exception: return WRONG_ARGUMENT if not os.path.exists(directory): return 'dir not found' dir_content...
9,890
def get_vendor(request): """ Returns the ``JSON`` serialized data of the requested vendor on ``GET`` request. .. http:get:: /get_vendor/ Gets the JSON serialized data of the requested vendor. **Example request**: .. sourcecode:: http GET /get...
9,891
def ensure_bin_str(s): """assert type of s is basestring and convert s to byte string""" assert isinstance(s, basestring), 's should be string' if isinstance(s, unicode): s = s.encode('utf-8') return s
9,892
def test_plot_water_levels(): """ Task 2E by Tian Ern """ # did not test matplotlib figure due to several challenges assert True
9,893
def test_item_setitem(supported_value): """Properties can be set.""" instance = holocron.Item() instance["x"] = supported_value instance["y"] = 42 assert instance["x"] == supported_value assert instance["y"] == 42 assert instance == holocron.Item(x=supported_value, y=42)
9,894
def _word_accuracy(pred_data, ref_data): """compute word-level accuracy""" pred_size = len(pred_data) ref_size = len(ref_data) if pred_size <= 0 or ref_size <= 0: raise ValueError("size of predict or reference data is less than or equal to 0") if pred_size != ref_size: raise ValueErr...
9,895
def cli(ffmpeg, source): """FFMPEG capture frame as image.""" stream = Test(ffmpeg_bin=ffmpeg) stream.run_test( input_source=source, )
9,896
def check_interface(interface: str) -> str: """ Check that the interface we've been asked to run on actually exists """ log = logging.getLogger(inspect.stack()[0][3]) discovered_interfaces = [] for iface in os.listdir("/sys/class/net"): iface_path = os.path.join("/sys/class/net", iface) ...
9,897
def api_retrieve_part(pt_id): """ Allows the client to call "retrieve" method on the server side to retrieve the part from the ledger. Args: pt_id (str): The uuid of the part Returns: type: str String representing JSON object which allows the client to know that ...
9,898
def test_missing_manifest_link(): """Test that missing linked manifests are properly flagged.""" err = ErrorBundle() package = MockXPI({ "chrome.manifest": "tests/resources/submain/linkman/base1.manifest"}) submain.populate_chrome_manifest(err, package) chrome = err.get_resource("chrome.ma...
9,899