content
stringlengths
22
815k
id
int64
0
4.91M
def toy_classification(return_X_y=True, n=5000): """toy classification dataset with irrelevant features fitting a logistic model on this data and performing a model summary should reveal that features 2,3,4 are not significant. Parameters ---------- return_X_y : bool, if True, returns ...
75,900
def describe_frameworks(serv, args, blueprint_name): """ Function used to answer to DescribeFrameworks requests :param serv: Service object :param args: parameters of the TJS request :return: request response """ exceptions = [] arg_version = args.get("version") # TOD...
75,901
async def client_get_configuration(response: Response, request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST), configname:str=Query(..., title=opasConfig.TITLE_ADMINCONFIGNAME, description=opasConfig...
75,902
def cross_entropy_seq(logits, target_seqs, batch_size=None): """Returns the expression of cross-entropy of two sequences, implement softmax internally. Normally be used for fixed length RNN outputs, see `PTB example <https://github.com/tensorlayer/tensorlayer/blob/master/example/tutorial_ptb_lstm.py>`__. P...
75,903
def recurse_files(dir: PathLike, *, channel: Channel = None) -> Channel: """ Starts a worker thread that finds all files in `dir` (recursively) and writes them to a :obj:`Channel`. Each file found is written as a :obj:`pathlib.Path` object. :param dir: The directory to search. :param channel: C...
75,904
def test_simpleunit_as_str(): """Casting a SimpleUnit as a string should return the ``for_print`` value. """ unit = SUTest_Simple('a') assert str(unit) == 'a[PR]'
75,905
def search_and_replace_queries(config): """Search and replace all query descriptions by a key (its checksum) in the configuration dictionary. It's a generator, only a query is replaced at each call. Args: config: A configuration dictionary with query descriptions. Returns: A ...
75,906
def generate_thumbnail(project: QgsProject, thumbnail_filename: Path) -> None: """Create a thumbnail for the project As from https://docs.qgis.org/3.16/en/docs/pyqgis_developer_cookbook/composer.html#simple-rendering Args: project (QgsProject) thumbnail_filename (Path) """ logging....
75,907
def _choose_prior( fun_params0: Union[pn.RandomVariable, np.ndarray, None] ) -> pn.RandomVariable: """ Initialize the prior distribution over the parameters. Sets up a prior distribution if no prior or only a point estimate for the parameters of the latent quadratic function is given. Paramete...
75,908
def image_build(ctx, arch='amd64', tag=AGENT_TAG, push=False): """ Build the docker image """ dca_binary = glob.glob(os.path.join(BIN_PATH, "datadog-cluster-agent")) # get the last debian package built if not dca_binary: print("No bin found in {}".format(BIN_PATH)) print("See cl...
75,909
def test_doi_migration(dataset_metadata): """Test migration of id with doi.""" dataset = Dataset.from_jsonld( dataset_metadata, client=LocalClient('.'), ) assert is_doi(dataset.identifier) assert urljoin( 'https://localhost', 'datasets/' + quote(dataset.identifier, safe='') ...
75,910
def write_stems( path, data, sample_rate=44100, writer=StreamsWriter(stem_names=None) ): """Write stems from numpy Tensor Args: path: str Output file_name of the stems file. Note that the extension of the path determines the used output container format (e.g. mp4...
75,911
def njit_accumulated_matrix(s1, s2, mask): """Compute the accumulated cost matrix score between two time series. Parameters ---------- s1 : array, shape = (sz1,) First time series. s2 : array, shape = (sz2,) Second time series mask : array, shape = (sz1, sz2) Mask. Unc...
75,912
def configuration_path(): """File created by bin/combine.""" return 'config/swagger-combine.yml'
75,913
def padlist(container, size, default=None): """Pad list with default elements. Examples: >>> first, last, city = padlist(['George', 'Costanza', 'NYC'], 3) ('George', 'Costanza', 'NYC') >>> first, last, city = padlist(['George', 'Costanza'], 3) ('George', 'Costanza', None) ...
75,914
def _conv1(in_channels, out_channels, bias=False): """point-wise convolution""" return nn.Conv1d(in_channels, out_channels, kernel_size=1, bias=bias)
75,915
def pad_to_length(sequences, length, value=0): """Pads sequences to being the same length, truncating right if they are longer. Attributes ---------- sequences the sequences to pad length : int the length to pad to value the value to use to pad Returns ------- ...
75,916
def test_system_label(logging_mixin, energy, system, activity, expected): """ Test system labels. """ assert labels.system_label(energy = energy, system = system, activity = activity) == expected
75,917
def comp_pca(usnap, n_trunc, detrend=True): """Perform Principal Component Analysis on data. Parameters ---------- usnap : array Data array, size (n_pts, n_dim). n_trunc : integer The number of PCA dimensions to be retained. detrend : boolean, optional Whether or not to...
75,918
def generate_thickness_gradient(ri, ro, T1, T2, Tdot_hot, hold, Tdot_cold = None, hold_together = 0.0, delay = 0.0): """ Generate our usual through-wall temperature gradient Parameters: ri inner radius ro outer radius T1 initial temperature ...
75,919
def get_user_details( client, upi: str, uid: str ): """ :param client: :param upi: :param uid: """ try: response = client.admin_get_user( UserPoolId=upi, Username=uid ) logger.info(f"get_user_details() response:") p...
75,920
def output_to_firrtl(open_file, rom_blocks=None, block=None): """ Output the block as FIRRTL code to the output file. :param open_file: File to write to :param rom_blocks: List of ROM blocks to be initialized :param block: Block to use (defaults to working block) If ROM is initialized in PyRTL cod...
75,921
def delete_data_for_ita_driver(): """ テストで使用したデータの削除 """ module = import_module('web_app.models.ITA_models') ItaDriver = getattr(module, 'ItaDriver') ItaActionHistory = getattr(module, 'ItaActionHistory') ItaDriver.objects.filter(last_update_user='pytest',).delete() ItaActionHistory.obj...
75,922
def Fk(shear_stress, temperature, Tath=700, Uk=0.33 * 1.60217657e-19, sigmap=900*1e6): """ Parameters ---------- shear_stress : ndarray of shape (N,) CRSS or maximum shear stress (in Pa or Nm-2) temperature : float Temperature (in Kelvin) Tath : float The athermal tempera...
75,923
def main(): """ Main function for running bird-eye view monitoring. Attributes ---------- video : str Path of the source demo video model : str path of the TensorRT runtime model conf_threshold : float Threshold valu...
75,924
def increment(lhs, ctx): """Element › (num) -> lhs + 1 (str) -> replace spaces with 0s """ ts = vy_type(lhs) return { NUMBER_TYPE: lambda: lhs + 1, str: lambda: lhs.replace(" ", "0"), }.get(ts, lambda: vectorise(increment, lhs, ctx=ctx))()
75,925
def test_rms(): """:func:`~discO.core.statistic.rms`""" x = np.linspace(0, 1, num=49) * u.kpc vf_x = np.ones(len(x)) * u.km / u.s points = coord.CartesianRepresentation((x, x, x)) vf = CartesianVectorField(points, vf_x=vf_x, vf_y=vf_x, vf_z=vf_x) got = statistic.rms(vf) assert got == np.s...
75,926
def _indices_3d_numba(f, y, x, py, px, t, nt, interp=True): """Compute time and space indices of parametric line in ``f`` function using numba. Refer to ``_indices_3d`` for full documentation. """ tdecscan = f(y, x, t, py, px) if not interp: sscan = (tdecscan >= 0) & (tdecscan < nt) else...
75,927
def render(): """ Render cron file :return: a str representation of the cron file """ j2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(resources.TEMPLATES_PATH)) tpl = j2_env.get_template(resources.CRON_TPL_YAML) # TODO obtain cron urls from validation.main/app_base.yaml instead o...
75,928
def request_url(URL): """HTTP GET request and load into json""" r = requests.get(URL) if r.status_code == requests.codes.ok: return json.loads(r.text) else: r.raise_for_status()
75,929
def getMultiTenantPath(api_name, method, app_name): """ This function will return the invoke path for a given api and http method (for a multi tenant setup) :param api_name: Name of the API :param method: Method of the API :param app_name: Name of the application :return: Invoke path """ ...
75,930
def get_txs_list(count=100, skip=0, filter={}): """ Fetch list of txs """ response = requests.post( httpprovider, data=json.dumps( { "jsonrpc": "2.0", "id": 8, "method": "tx_list", "params": ...
75,931
def generate_test_data(): """Used by tests/generate_test_data.sh to generate tests/data/gather_tb/. "tests/data/gather_tb/" should contain 4 Tensorboard run directories ("sb_tb/" and "tb/" for each of two trials in the search space below). """ sacred_ex_name = "expert_demos" run_name = "TEST" ...
75,932
def deep_tissue_segmentation( x, template=None, registration_map=None ): """ modified slightly more efficient deep atropos that also handles the extra CSF issue. returns segmentation and probability images. see the tissues csv available from get_data. x: input image template: MNI space templa...
75,933
def parse_command_line_arguments(): """Parse command line arguments, checking their values.""" parser = argparse.ArgumentParser(description='') parser.add_argument('--model', default="./results/bert", help="the name of the model/checkpoint to be used for the classifier (e.g. ./results/checkpoint") pars...
75,934
def debug_list(test_list): """Print out contents of a list. Prints out the number of current item and its contents. Loops through entire list. Args: test_list (list): List to be printed out. List test from https://stackoverflow.com/questions/1835018/how-to-check-if- an-obj...
75,935
def beta_utility_gen(X, x_max, a, b): """ Beta distribution over utility value X : value of Vertical Illuminance (EV) at which to find the utility function value x_max : max value of EV to be considered for getting the proper Beta distribution a: Beta distribution parameter b : Beta distribution...
75,936
def question(conversation): """Counts whether each utterance in the given conversation contains a question (yes: 1, no: 0)""" num_turns = len(conversation) is_question_in_utterance = np.zeros(num_turns) for i, utterance in enumerate(conversation): if any(question_word in utterance for question_...
75,937
def run_app() -> None: """ Runs the app """ app.run_server(debug=True)
75,938
def insert_new_artist(cursor, name, is_vocalist, is_composer): """ Insert a new artist in the database """ sql_insert_artist = "INSERT INTO artists(name, vocalist, composer) VALUES(?, ?, ?);" run_sql_command(cursor, sql_insert_artist, [name, is_vocalist, is_composer]) return cursor.lastrowid
75,939
def parse_arguments(argv): """Command line parse.""" parser = argparse.ArgumentParser() parser.add_argument('--fig_mode', type=str, default=None, help='Plot experiment figures.') return parser.parse_args()
75,940
def predict(notes, onsets, n_tracks, states): """Predict the labels.""" # Create the prediction array predictions = np.zeros(len(notes), int) # Initialize states (recording the time until when each track is active) track_states = np.zeros(n_tracks, int) if states else None # Initialize last pi...
75,941
def getTower(creep, maxEnergyPercentage = 0.7): """ Gets the closest tower in the same room as a creep :param creep: The creep to run :param maxEnergyPercentage: The max energy percentage of total that the tower is allowed to have, between 0 and 1. 0 means only totally empty towers, 1 means only full to...
75,942
def set_default_port(port: int): """Set the global value of the default port to use. Should only be called just after imports.""" global default_port default_port = port
75,943
def png_encode(input, compress_level=3): """ Encode the image with PNG encoder. Args: img (:class:`numpy.ndarray`): uint8 color image array quality (int): quality for JPEG compression Returns bytes: encoded image data """ assert len(input.shape) == 3 and input.shape[2] in [3, 4...
75,944
def _send_command(params, settings): """Send a command to the NVP API.""" params["VERSION"] = "64.4" params["USER"] = settings["USERID"] params["PWD"] = settings["PASSWORD"] params["SIGNATURE"] = settings["SIGNATURE"] keys = params.keys() keys.sort() pairs = [(k,params[k]) for k in keys]...
75,945
def find_chimera_indices(G): """Attempts to determine the Chimera indices of the nodes in graph G. See the `chimera_graph()` function for a definition of a Chimera graph and Chimera indices. Parameters ---------- G : NetworkX graph Should be a single-tile Chimera graph. Returns ...
75,946
def ini_to_json(in_file, out_file=None): """ Convert Deltares ini to json file. If out_file is left empty, it returns the json as dictionairy """ # print("Script directory : %s" % _script_dir) # print("Start directory : %s" % start_dir) # print("Working directory: %s" % current_dir) ...
75,947
def namespace(prefix): """Decorator that prefixes named variables. Args: prefix (str): Prefix to prepend to the name of named variables. """ def decorator(f_): @wraps(f_) def wrapped_f(*args, **kw_args): # Replace all variable containers with their namespace variant...
75,948
def cli(data_config_file: str, app_config_file: str, user: str, password: str): """This module generates parquets with regional annotation pathology data from DSA TABLE SCHEMA - project_name: name of DSA collection - slide_id: slide id. synonymous with image_id - user: username of the annotator for...
75,949
def serialize_representacion(declaracion): """ # $ref: '#/components/schemas/representaciones' """ representaciones = declaracion.representaciones_set.all() to_be_add = [] for represent in representaciones: titular = serialize_tipo_relacion(represent.cat_tipos_relaciones_personales) ...
75,950
def calc_area(l, w): """ params: l and w are both real positive numbers representing the length and width of a rectangle """ if l <= 0 or w <= 0: raise ValueError return l * w
75,951
def settings(request): # pylint: disable=unused-argument """Settings context_processor.""" db_settings = {} default_settings = { 'title': 'Just another blog', 'tagline': '', } options = Option.objects.all() for option in options: db_settings[option.name] = option.value ...
75,952
def get_games(soup=None): """Uses bs4 to get list of games on Steam Marketplace. Argument: (Optionally) soup: bs4 object to search on. Returns: Array of objects, containing all games on marketplace. """ if not isinstance(soup, BeautifulSoup): soup = get_page('') #empty sea...
75,953
def print_summary(targets): """ Return 0 if all test passed Return 1 if all test completed but one or more failed Return 2 if one or more tests did not complete or was not detected """ passed = 0 failed = 0 tested = 0 expected = 0 return_code = 3 print("---------------------...
75,954
def get_names(line): """ достаем из строки имена наташей """ names = [] matches = EXTRACTOR(line.title()) for match in matches: fact = match.fact.as_json if "first" in fact.keys() and "middle" in fact.keys() and "last" in fact.keys(): name = fact["first"][0].upper() + "." + f...
75,955
def logical_or(a, b): """A version of tf.logical_or that eagerly evaluates if possible.""" a_value = get_static_value(a) if a_value is not None: if np.isscalar(a_value): if a_value: return a_value else: return _maybe_static(b) else: return a_value | _maybe_static(b) els...
75,956
def offline_orphaned_jobs(es_url, dry_run=False): """Set jobs with job-queued or job-started state to job-offline if not synced with celery task state.""" # get redis connection set_redis_pool() global POOL rd = StrictRedis(connection_pool=POOL) # get celery task result serializer cont...
75,957
def test_list_batch_change_summaries_with_list_batch_change_summaries_with_no_changes_passes(): """ Test successfully getting an empty list of summaries when user has no batch changes """ client = VinylDNSClient(VinylDNSTestContext.vinyldns_url, "listZeroSummariesAccessKey", "listZeroSummariesSecretKey"...
75,958
def test_taylor_4(): """test_taylor_4() Tests for the accuracy of the Taylor formula approximation at point x[50] by calling sin(x) and taylor; fourth order derivative approximation """ a=-5 b=5 numberOfPoints=101 x=np.linspace(a,b,numberOfPoints) f=my_functions.sin(x) i=50 out_X...
75,959
def massProperties(vertices, faces=None, factor=1.): """Compute the mass, center of mass, and inertia tensor of a polygon or polyhedron Args: vertices (list): List of (x, y) or (x, y, z) coordinates in 2D or 3D, respectively faces (list): List of vertex indices for 3D polyhedra, or None for 2D....
75,960
def parse_method(uri: str, method: str, paths: dict, operation: Operation) -> None: """ :param uri: api route path :param method: get post put delete patch :param paths: openapi doc paths :param operation: `models.path.py` Operation """ if method == HTTPMethod.GET: if not paths.get(u...
75,961
def isDKA(filename): """ Checks whether a file is ASCII DKA k value format. AAA Geographical latitude: 43.250 N Geographical longitude: 76.920 E K-index values for 2010 (K9-limit = 300 nT) """ ok = False try: ...
75,962
def getBuggyMethodsFromFile( project_root: str, file: PatchedFile, is_target_file: bool ) -> List[Tuple[str, Set[int], ast.FunctionDef]]: """ Get a set of modified methods from a unidiff PatchedFile object :param project_root: The root directory of a Git repository containing the modified file :para...
75,963
def success(task): """ An event to record the total CPU time of a toil job. """ pipeline_args = task.get_pipeline_args() stats_db = pipeline_args.stats_db if task.zone is not None: cmd = ['toil', 'stats', '--raw', task.job_store] try: os.remove(os.path.abspath(task.jo...
75,964
def delate_materialslot_duplicate(arg_object:bpy.types.Object) -> bool: """指定オブジェクトのマテリアルスロットをソートする Args: arg_object (bpy.types.Object): 指定オブジェクト Returns: bool: 実行正否 """ # オブジェクトがメッシュであるか確認する if arg_object.type != 'MESH': # 指定オブジェクトがメッシュでない場合は処理しない return None ...
75,965
def from_DataFrame(df,df_func=None,index_func=None,force_sharex=None): """ Create a sharex Pdata.Pdata object from pandas DataFrame Parameters: ----------- df_func: function that applies on DataFrame before feeding data into Pdata. index_func: index function that will be applied before using th...
75,966
def run_dials_refine(experiments, reflections, params): """Functional interface to tasks performed by the program dials.refine. This runs refinement according to the PHIL parameters in params, using taking the initial experimental geometry from experiments, and the observed reflection centroids from re...
75,967
def clean_input(text): """ 텍스트 정제 함수 :param text: 사용자가 입력한 텍스트 :return: ASCII 이외의 문자를 제거한 정제된 텍스트 """ # 간단하게 시작하기 위해서 ASCII 문자만 사용합니다 return str(text.encode().decode("ascii", errors="ignore"))
75,968
async def update_voice_state(client: "Client", guild_id: int, channel_id: Optional[int]) -> None: """Update the voice state. Args: client: discord.py client. guild_id: Guild id to target channel_id: Channel id to connect to. If `None`, disconnect from the current channel. ...
75,969
def nearest_prime(lhs, ctx): """Element ∆p (num) -> nearest prime to a (str) -> python code from expression """ ts = vy_type(lhs) if ts == NUMBER_TYPE: if lhs < 2: return 2 elif is_prime(lhs, ctx): return lhs return { (NUMBER_TYPE): lambda: mi...
75,970
def testDisconnectBugSevere(serialno=None,Protocol=pmapi.USB_protocol()): """This will force the disconnect bug to occur in a short period of time. This one doesn't necessarily need to pass, but an ideal fix would allow it to do so.""" Mon = HVPM.Monsoon() Mon.setup_usb(serialno,Protocol) Engine = s...
75,971
def make_node2ancestors_recursively(node, node2ancestors): """ key=node, value=keyの全祖先のノードのセット となる辞書を作る。 Args: node: 全祖先を知りたいノード node2ancestors: key=ノード, value=keyの全祖先のセット Return: nodeにターゲットが存在しない:要素がnodeのみのセット nodeがnode2ancestors.keys()に存在する:node2ancestors[node] ...
75,972
def run(cmdfile,subsetfile=None, lookupfile=None): """ Generate TestCases from cmdfile according to the pattern in patternfile""" #Define the test case pattern pattern="""class %s(basecase.%sCase): def setUp(self): self.obsmode="%s" self.spectrum="%s" self.subset=%s self....
75,973
def build(func, target=None, target_host=None, params=None): """Helper function that builds a Relay function to run on TVM graph runtime. Parameters ---------- func: relay.Function The function to build. target : str, :any:`tvm.target.Target`, or dict of str(i.e. device/context nam...
75,974
def handle_response(resp, headers): """ return TRUE = HIT, FALSE = MISS """ val = resp.getvalue() head_val = headers.getvalue() index = head_val.find("X-CACHED-MIDDLEWARE: ") if index == -1: return False response = head_val[index + len(HEADER_STRING)] return response == "H"
75,975
def from_settings(request): """ Set context variables based on settings variables """ return { 'ENVIRONMENT_NAME': settings.ENVIRONMENT_NAME, 'ENVIRONMENT_COLOR': settings.ENVIRONMENT_COLOR, }
75,976
def load_adapters_internal(force_reload=False): """Load adapter related configurations into memory. If force_reload, reload all configurations even it is loaded already. """ global OSES if force_reload or OSES is None: OSES = _get_oses_from_configuration() global OS_INSTALLERS if fo...
75,977
async def test_remove_entry(hass, config_entry, smartthings_mock): """Test that the installed app and app are removed up.""" # Act await smartthings.async_remove_entry(hass, config_entry) # Assert assert smartthings_mock.delete_installed_app.call_count == 1 assert smartthings_mock.delete_app.cal...
75,978
def count_words(text: str) -> Dict[str, int]: """This is a function to count word frequencies or to count how many times each unique word occurs in the text. Args: text (str): A long string Returns: Dict[str, int]: A dictionary with sorted word frequencies """ freq = {} ...
75,979
def output_xml(data, code, headers=None): """Makes a Flask response with a XML encoded body""" resp = make_response(dumps({'response': data}), code) resp.headers.extend(headers or {}) return resp
75,980
def to_dict(conf): """Converts a Config object to a dictionary. Args: conf (Config): A Config object Returns: dict: A multi-level dictionary containing a representation ogf the configuration. """ return conf._xpipe_to_dict()
75,981
def _recode_default(x, default, out_type): """Get right default for recoding""" if default is None and ( out_type is None or isinstance(_get_first(x), out_type) ): return x return default
75,982
def edge_uniform_weight(edge, goal, slicevars): """ Return a uniform view of the edge's log-probability. :param edge: an edge :param goal: the goal node (gets a special treatment because there are no slice variables for it) :param slicevars: a SliceVariable object :returns: 1/beta.pdf(u_s; a, b)...
75,983
def add_query_params(url, params): """ Inject additional query parameters into an existing URL. If parameters already exist with the same name, they will be overwritten. Parameters with empty values are ignored. Return the modified URL as a string. """ def encode(s): return force_byt...
75,984
def np_seq_similarity(seq1, seq2, substMat, normed, asDistance): """Computes sequence similarity based on the substitution matrix.""" if seq1.shape[0] != seq2.shape[0]: raise IndexError("Sequences must be the same length (%d != %d)." % (seq1.shape[0], seq2.shape[0])) """Similarity between seq1 and ...
75,985
def loadkeys(filename): """ " load twitter api keys/tokens from CSV file with form consumer_key, consumer_secret, access_token, access_token_secret """ with open(filename) as f: items = f.readline().strip().split(", ") return items
75,986
def add_ra_dec_from_object_name(directory=None, new_file_ext=None, object_list=None, object_list_dir=None): """ Add RA/Dec to FITS file that has object name but no pointing. Parameters ---------- dir : str, optional Directory containing the files to be patche...
75,987
def query_db(query, args=(), one=False): """Query the database of the current application. Return the first row of the result if the optional argument 'one' is true, or the whole query result if not specified. """ cur = get_db().execute(query, args) rv = cur.fetchall() cur.close() retu...
75,988
def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."): """Flatten a nested dict into a single level dict.""" def _flatten_dict(d, parent_key="", delimiter="."): for k, v in d.items(): key = str(parent_key) + delimiter + str(k) if parent_key else k if v ...
75,989
def test_spf(): """Sorted/Unsorted distance matrix descriptor""" from pyvibdmc import DistIt transformer = DistIt(zs=[8, 1, 1] * 3, method='spf', eq_xyz=cds[0], full_mat=False, sorted_atoms=[[0], [1, 2], [3],...
75,990
def log(message: str) -> None: """Log a message to the log file if it is open. Args: message (str): The message to log. """ if LOG_FILE: print(message, file=LOG_FILE)
75,991
def sample_pixels(slide_path, sample_fraction=None, magnification=None, tissue_seg_mag=1.25, min_coverage=0.1, background=False, sample_approximate_total=None, tile_grouping=256): """Generates a sampling of pixels from a whole-slide image. Useful for generating statistics or...
75,992
def email_exception(exception): """ This is called by the main Flask errorhandler() decorator in api.py when we have an unhandled exception at any point of responding to a request. This prevents user-facing failures from being silently swallowed. """ # first, log it e_logger = get_logger(log_name=...
75,993
def import_yaml_folder(directory: str = '/') -> dict: """ Iterates through directory and looks for yaml files, if one is found, it is imported and stored in a dictionary with its root filename (without its extension) as the key """ yaml_objects = {} for entry in os.scandir(directory):...
75,994
def main(): """Main function.""" args = get_args() # Read the whole output file with open(args.heinz) as r: graph_dot = r.readlines() # Remove the redundant lines while not graph_dot[0].startswith('graph G {'): graph_dot.pop(0) src = Source(''.join(graph_dot)) data_pdf ...
75,995
def set_edge_weights( changes_file: typing.TextIO, edge_weights: Dict[str, Dict[str, int]] ) -> Iterator[Tuple[IncludeChange, int, str, str, Optional[int]]]: """Set edge weights in the include changes output""" change_type_value: str for change_type_value, line, filename, header, *_ in csv.reader(chan...
75,996
def valid_hex(value): """Check if the string is a valid hex number representation.""" try: int(value, 16) except Exception: return False return True
75,997
def _get_webauthn_user_public_key_credential_descriptors(user, *, rp_id): """ Returns a webauthn.WebAuthnUser instance corresponding to the given user model, with properties suitable for usage within the webauthn API. """ return [ PublicKeyCredentialDescriptor( id=base64url_t...
75,998
def bert_encoder(s, no_wordpiece=0): """ Compute semantic vector with BERT Parameters ---------- s: string to encode no_wordpiece: 1 if you do not use sub-word tokenization, otherwise 0 Returns ------- np array in shape of (768,) """ if no_wordpiece: words = s.split(...
75,999