content
stringlengths
22
815k
id
int64
0
4.91M
def plot_2d(x_data, x_name='x_data', y_data=None, y_name='y_data', yerr=None, groups=None, identifiers=None, graph_type='scatter', line_width_=None, fit=None): """ Min part for plottings a 2d graph. If specified, args groups and identifiers specify the order of groups and exper...
5,297,700
def visit(name, visitor=None): """Utility function to rewrite rows in csv files. :param name: Name of the csv file to operate on. :param visitor: A callable that takes a row as input and returns a (modified) row or\ None to filter out the row. """ if visitor is None: visitor = lambda r:...
5,297,701
def setup(KateBot): """Adds the cog to the bot""" KateBot.add_cog(Misc(KateBot))
5,297,702
def test_LoxApp_init(): """Test class initialisation""" api = LoxAPI() assert api._host == "" assert api._port == 80 assert api._user is None assert api._password is None assert api.json is None assert api.version == "" assert api._https_status is None assert api._tls_check_hostn...
5,297,703
def test_list_nodes_full(): """Test the list_nodes_full function by using a mock""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: with pytest.raises(SaltCloudSystemExit): hetzner.list_nodes_full("action") mock = MagicMock...
5,297,704
def serialize_some_embed( instance: some.graph.SomeEmbed, ordered: bool = False ) -> typing.MutableMapping[str, typing.Any]: """ serializes an instance of SomeEmbed to a JSONable representation. :param instance: the instance of SomeEmbed to be serialized :param ordered: If set, ...
5,297,705
def convert_format_nifti_mask(nifti_path:str, destination:str): """Convert 8Bits UINT nifti mask to 32Bits UINT nifti mask Args: nifti_path ([str]): [path of the nifti file] destination ([str]): [path of destination's directory] """ img = sitk.ReadImage(nifti_path) img = sitk.Cast(...
5,297,706
def get_current_user(*args): """Return the current user configured in middleware.""" if hasattr(LOGSFORHUMAN_THREAD, 'request'): return getattr(LOGSFORHUMAN_THREAD.request, 'user', None)
5,297,707
def get_pair_single(name): """ Given a fastq file name, determines if it's paired-end or single-end and returns the type + name. :param name: The name to check. :return: The combined file type ('single', 'forward', or 'reverse') and the name minus the direction-identifying part of the file name. ...
5,297,708
def test_schemas_are_valid_spec_not_file(tmpdir): """ GIVEN spec is actually a folder WHEN schemas_are_valid is called with the spec filename THEN CacheError is raised. """ path_tmpdir = pathlib.Path(tmpdir) spec_filename = "spec.json" spec_file = path_tmpdir / spec_filename spec_fil...
5,297,709
def parse_lst(lst_path): """Extract audio names of nnenglish.""" audio_names = [] with open(lst_path) as fd: for line in fd: audio_path, lang = tuple(line.strip().split()) if lang != "nnenglish": continue audio_name = Path(audio_path).with_suffix(...
5,297,710
def add_angle(r): """ Add angle for each r value to make up a coordinate of a polar coordinate. """ coords = [] for ri in r: theta = random.random() * 360 coords.append((ri, theta)) if len(coords) == 1: return coords[0] else: return coords
5,297,711
def Article_Add(request): """ 新增文章 :param request: :return: """ seo_list = get_object_or_404(Seo, name='文章') if request.method == 'GET': category = Category_Article.objects.all() return render(request,'pc/articlesadd.html',{"category":category,'seo_list':seo_list}) if re...
5,297,712
def compute_cv_fold_stats(data_df, cv_splits): """ Computes CV fold size and class proportions for a given CV splitting. :param data_df: a DataFrame :param cv_splits: a given cv splitting as e.g. returned by cv_independent_associations() :return: a DataFrame that lists count and fraction of pos...
5,297,713
def lag_port_stats( data # type: "XDR Data" ): """LAG Port Statistics Counter - Type: Counter, Enterprise: 0, Format: 7""" sample_data = {} # Cache sample_data["dot3adAggPortActorSystemID"] = data.unpack_string() sample_data["dot3adAggPortPartnerOperSystemID"] = data.unpack_string() sample_data["dot3adAggPortAtt...
5,297,714
def main(): """ NAME core_depthplot.py DESCRIPTION plots various measurements versus core_depth or age. plots data flagged as 'FS-SS-C' as discrete samples. SYNTAX core_depthplot.py [command line optins] OPTIONS -h prints help message and quits -f FILE: sp...
5,297,715
def fit(comb): """returns true if combination can be chosen and false otherwise""" if len(comb)>5|len(comb)<1: return False desk=list(filter(lambda x: x>4,comb)) if len(desk)<1: return True desk.sort() handOut = 5 - (len(comb)- len(desk)) deskLast=desk[-1] if handOut>=des...
5,297,716
async def wait_for_reply(predicate: TYPE_CALLABLE_PREDICATE = None, timeout=30, default=None, raise_on_timeout=False) -> ReplyResult: """ waits for a message matching `predicate` to be received, when its received, it returns a ReplyResult instance with the response. if no message matching `predicate` is re...
5,297,717
def query(session, qid, args={}): """Query AP system page by qid and args :param session: requests session object, the session must login first. :type session: class requests.sessions.Session :param qid: query id of ap system page :type qid: str :param args: arguments of query post :type ar...
5,297,718
def get_airflow_operation_client(): """ Get a client to operate airflow dags and tasks. """ global _default_airflow_operation_client ensure_project_registered() if _default_airflow_operation_client: return _default_airflow_operation_client else: return AirflowOperation(_default_proje...
5,297,719
def FILTER(*args) -> Function: """ Returns a filtered version of the source range, returning only rows or columns which meet the specified conditions. Learn more: https//support.google.com/docs/answer/3093197 """ return Function("FILTER", args)
5,297,720
def get_args(): """ Command line arguments """ parser = ArgumentParser(description="Inspect sets of rts contained in hdfs store file(s) as pandas DataFrames.") parser.add_argument("files", help="XML file with RTS", nargs="+", type=str) parser.add_argument("--key", help="DataFrame key in store", default=...
5,297,721
def load_status_info(sfile, fudge=None): """ Parse the output of pb_run_status.py, either from a file or more likely from a BASH <() construct - we don't care. It's quasi-YAML format but I'll not use the YAML parser. Also I want to preserve the order. """ res = OrderedDict() if s...
5,297,722
def calculateSimilarity(img1, img2, similarityType="l2"): """ This method calculates the similarity of two images given the type of similarity function (such as l2 distance). :param img1: np.array :param img2: np.array :param similarityType: str default: "l2" :return: float - distance between th...
5,297,723
def main(args=None): """ The main method for parsing command-line arguments and running the application. :param args: the commandline arguments, uses sys.argv if not supplied :type args: list """ parser = argparse.ArgumentParser( prog="simple_redis_helper-listen", description="L...
5,297,724
def _is_false(x): """Evaluates false for bool(False) and str("false")/str("False"). The function is vectorized over numpy arrays or pandas Series. Everything that is NA as defined in `is_na()` evaluates to False. but also works for single values.""" x = np.array(x).astype(object) return _is_f...
5,297,725
def dockercomposeup(ctx): """Runs docker-compose up -d """ _run('docker-compose up -d')
5,297,726
def badDebts(_trader: str = None, _start: int = None, _end: int = None) -> []: """ Get bad debts """ with utils.dbInterface() as client: db = client['perp'] criteria = {} if _trader: criteria['trader'] = _trader if _start or _end: criteria['timestamp'] = {} i...
5,297,727
def create_run_group(prj): """ Create a new 'run_group' in the database. This creates a new transaction in the database and creates a new run_group within this transaction. Afterwards we return both the transaction as well as the run_group itself. The user is responsible for committing it when the ...
5,297,728
def get_tags_from_message(message): """ Given a message string, extracts hashtags and returns a comma-separated list :param message: a Hipchat message body """ tags = {word.strip('#') for word in message.split() if word.startswith('#')} return ','.join(tags)
5,297,729
def get_canny_edge_detected(image=None): """the function receives an [image] as an argument The list of things that function performs 1. checks if image is not None 2. turns the color image to Gray Scale 3. blurs the image to reduce the noise 4. detects edges using canny edge detection """ ...
5,297,730
def test_nwspgr(dimensions: int, level: int, nested: bool) -> None: """Compare with output from the Matlab function nwspgr by Florian Heiss and Viktor Winschel. The weights differ by floating point error because different sorting algorithms are used by Matlab and NumPy. """ if shutil.which('matlab') is ...
5,297,731
def sha512_gen(): """ SHA-512 takes a message of arbitrary length as input and generates a hash value that is 512-bit in size. """ user_message = input("Enter message to encrypt: ") message = user_message.encode() message_hash = hashlib.sha512(message).digest() print("\nHash(byte format...
5,297,732
def normdat(base_path, outpath, version, num2show=None): """ normdat is a function that convert this dataset to standard ezxr format output Args: :param base_path: path to the dataset :param outpath: path of the output files :param version: a version of dataset, including ('gs', 'ho...
5,297,733
def tf_read_img(tf, filename): """Loads a image file as float32 HxWx3 array; tested to work on png and jpg images.""" string = tf.read_file(filename) image = tf.image.decode_image(string, channels=3) image = tf.cast(image, tf.float32) image /= 255 return image
5,297,734
def remove_outliers(X): """Function to replace "bad" measurements to zero. Inputs: H: Measurement applied field [float, SI units] Hr: Reversal field [float, SI units] M: Measured magnetization [float, SI units] Fk: Index of measured FORC (int) Fj: Index of given measurement within ...
5,297,735
def writeFile(fileName, data): """Write the information to a file""" print("###Writing file") with open("./"+fileName, 'w') as outfile: json.dump(data, outfile, indent=0, sort_keys=True)
5,297,736
def mumps_eigsh(matrix, k, sigma, **kwargs): """Call sla.eigsh with mumps support. Please see scipy.sparse.linalg.eigsh for documentation. """ class LuInv(sla.LinearOperator): def __init__(self, matrix): instance = kwant.linalg.mumps.MUMPSContext() instance.analyze(matr...
5,297,737
def collect_server_info(host, port): """ Collect general information of server. """ info = {} with pymongo.MongoClient(host, port, connect=True, serverSelectionTimeoutMS=3000) as mc: info['version'] = mc.server_info()['version'] return info
5,297,738
def mean(array): """Return the mean value of the valid elements of an array. Parameters ---------- array : `numpy.ndarray` array of values Returns ------- `float` mean value """ non_nan = e.isfinite(array) return array[non_nan].mean()
5,297,739
def _get_boot_list_for_boot_device(node, device, controller_version): """Get the boot list for a given boot device. The DCIM_BootConfigSetting resource represents each boot list (eg. IPL/BIOS, BCV, UEFI, vFlash Partition, One Time Boot). The DCIM_BootSourceSetting resource represents each of the boot l...
5,297,740
def land_sic_overlap_timeseries(instrument, title="Land-Sea Ice Border Variations"): """ Time Series that shows the percentage variations of the land mask border given the expansion of sea ice in VIRS. """ files = data.file_names(instrument_id=data.INSTRUMENT...
5,297,741
def putseconds(secs): """ Create a datestring for format 'dd HH:MM:SS' """ days = int(secs / SECSPERDAY) secs = int(secs - days * SECSPERDAY) hours = int(secs / SECSPERHOUR) secs = int(secs - hours * SECSPERHOUR) minutes = int(secs / SECSPERMINUTE) secs = int(secs - minutes * SECSPERMINU...
5,297,742
def get_dataloaders(datasets, batch_size, data_type, preprocessor=None, name=None, label_transformer=None, **kwargs): """ Prepare, define and retrieve appropiate data loaders for the dataset partitions. Args: datasets: dict, {key:partition, val:dict of X, y lists} batch_size: int, batch size data_type: st...
5,297,743
def get_sequence_from_PDB(PDBFile): """Extracts the sequence from each PDB""" with open(PDBFile, 'r') as pdb_file: for record in SeqIO.parse(pdb_file, 'pdb-atom'): print('>' + record.id) print(record.seq)
5,297,744
def Gillespie_FRM4X(generics_func, func_param): """ FUNCTION: Gillespie_FRM4X(a{}, b str) a: dictionary containing function's generic values b: XML string file name - Function generic's handler for "Gillespie_FRM4X". """ # Python's variable...
5,297,745
def make_gunicorn_config( _gunicorn_config_path='', ): """makes gunicorn.conf file for launching in docker Notes: https://sebest.github.io/post/protips-using-gunicorn-inside-a-docker-image/ renders gunicorn.config (python) file in running dir looks for GUNICORN_{option} in envir...
5,297,746
def test_1_subject(sess,MR_image,CT_GT,MR_patch_sz,CT_patch_sz,step): """ receives an MR image and returns an estimated CT image of the same size """ matFA=MR_image matSeg=CT_GT dFA=MR_patch_sz dSeg=CT_patch_sz eps=1e-5 [row,col,leng]=matFA.shape margin1=int((dFA[0]-dSeg[0])/2) margin2=int((dFA[1]-dSeg[...
5,297,747
def la_uploader(mock_put): """Generate LAUploader for testing.""" response = Response() response.status_code = 200 mock_put.return_value = response la_uploader = LAUploader(workspace="1234", workspace_secret="password", debug=True) return la_uploader
5,297,748
def jpeg_cmyk_to_rgb(image_bytes, quality=100): """Converts JPEG CMYK image (bytes) to RGB JPEG (bytes).""" runner = _get_runner() image = runner.run(tf.image.decode_jpeg, image_bytes) fn = lambda img: tf.image.encode_jpeg(img, format="rgb", quality=quality) return runner.run(fn, image)
5,297,749
def indices_for_pixel(pix_x, pix_y, x, y): """ Return the indices of the sources for which the coordinates lie in the x, y pixel """ (indxs,) = np.where( np.logical_and.reduce([pix_x > x, pix_x <= x + 1, pix_y > y, pix_y <= y + 1]) ) return indxs
5,297,750
def is_valid_config_entry(opp, logger, origin, destination, region): """Return whether the config entry data is valid.""" origin = resolve_location(opp, logger, origin) destination = resolve_location(opp, logger, destination) try: WazeRouteCalculator(origin, destination, region).calc_all_routes_...
5,297,751
def set_value(value, *keys): """Update lcr-modules configuration using simpler syntax. This function will automatically create dictionaries if accessing a key that doesn't exist and notify the user. Parameters ---------- value : anything The value to be set at the location specified by...
5,297,752
def test_failure(database): """ Tests that SF 133 amount sum for line 2490 does not match Appropriation unobligated_balance_cpe for the specified fiscal year and period """ tas = 'fail_tas' sf = SF133(line=2490, tas=tas, period=1, fiscal_year=2016, amount=1, agency_identifier='sys', ...
5,297,753
def Debug(message, *args, **kwargs): """Emits a debugging message using the logging module.""" logger.debug(message, *args, **kwargs)
5,297,754
def __compare_decode_dir(base_decode_dir: Path, new_decode_dir: Path): """对解码文件夹进行对比. Args: base_decode_dir: 基础解码文件夹. new_decode_dir: 新的解码文件夹. """ subset_to_base_cer = __get_subset_to_cer(base_decode_dir) subset_to_new_cer = __get_subset_to_cer(new_decode_dir) msg = '两个解码文件夹内的子...
5,297,755
def is_numpy_array(obj: Any) -> bool: # type: ignore """ Checks if the given object is a numpy array Args: obj (Any): The object to check Returns: bool: True if the object is a numpy array otherwise False """ try: import numpy as np # noqa except Excep...
5,297,756
def create_rest_blueprint(app) -> Blueprint: """Create the blueprint for the REST endpoints using the current app extensions.""" # note: using flask.current_app isn't directly possible, because Invenio-MaDMP is # registered as an extension in the API app, not the "normal" app # (which is the...
5,297,757
def construct_storage_path() -> Path: """Construct a Path to draw the standard "storage" flowchart shape.""" # NOTE: After a MOVETO, we need to put the pen down for CLOSEPOLY to # complete a filled shape. _path_data = [ # main shape (Path.MOVETO, [-1.000, -0.800]), # start at bottom lef...
5,297,758
def create_pb_from_mathtext(text, align='center', weight='heavy', color='b', style='normal'): """ Create a Gdk.Pixbuf from a mathtext string """ global pbmt_cache global dpi if not text in pbmt_cache: parts, fontsize = _handle_customs(text) pbs = [] width = 0 ...
5,297,759
def compare_rrs_types(exp_val, got_val, skip_rrsigs): """sets of RR types in both sections must match""" def rr_ordering_key(rrset): if rrset.covers: return rrset.covers, 1 # RRSIGs go to the end of RRtype list else: return rrset.rdtype, 0 def key_to_text(rrtype, rr...
5,297,760
def __do_config_section(parser): """Populate the config section""" # Purge section before adding. parser.remove_section(dtfglobals.CONFIG_SECTION_CONFIG) parser.add_section(dtfglobals.CONFIG_SECTION_CONFIG) # Color is enabled by default parser.set(dtfglobals.CONFIG_SECTION_CONFIG, 'use_color...
5,297,761
def act_gsymbol_reference(context, nodes): """Repetition operators (`*`, `+`, `?`) will create additional productions in the grammar with name generated from original symbol name and suffixes: - `_0` - for `*` - `_1` - for `+` - `_opt` - for `?` Zero or more produces `one or more` productions a...
5,297,762
def is_higher_permission(level1, level2): """ Return True if the level1 is higher than level2 """ return (is_publish_permission(level1) and not is_publish_permission(level2) or (is_edit_permission(level1) and not is_publish_permission(level2) and not is_...
5,297,763
def vectorize_array(y, steps=1, return_type='df'): """ Take in an array like sequence of values. Vectorize the array and add steps from further in the series to each item. The values in the input array must be of shape [n, 1]. Rows with nan values in the result array will be dropped. If return_...
5,297,764
def extract_hist(*input_data, bias): """ Split the SSPFM curve into on and off signal. Function was rewritten to work with m_apply, and to take account a bug into Cypher machine, leading to pulse not all being the same size. Parameters ---------- input_data : array-like data which n...
5,297,765
def test_cray_ars_uploads(cli_runner, rest_mock): """ Test cray ars artifacts uploads command """ runner, cli, _ = cli_runner result = runner.invoke(cli, ['ars', 'uploads']) assert result.exit_code == 0 outputs = [ "ars uploads [OPTIONS] COMMAND [ARGS]...", "create", "delete...
5,297,766
def do_upper_envelope_step( policy: List[np.ndarray], value: List[np.ndarray], *, expected_value: np.ndarray, params: pd.DataFrame, options: Dict[str, int], compute_utility: Callable, ) -> Tuple[np.ndarray, np.ndarray]: """Runs the Upper Envelope algorithm and drops sub-optimal points. ...
5,297,767
def KMLs_to_geosjon(kml_paths, ofname): """ backward coimpatibility due to typo bug """ KMLs_to_geojson(kml_paths, ofname)
5,297,768
def normalize_yaml(path): """Normalize a YAML file, and return whether the file changed.""" data = read_yaml(path) changed = write_yaml(data, path) return changed
5,297,769
def download(dbx, folder, subfolder, name): """Download a file. Return the bytes of the file, or None if it doesn't exist. """ path = '/%s/%s/%s' % (folder, subfolder.replace(os.path.sep, '/'), name) while '//' in path: path = path.replace('//', '/') try: md, res = dbx.files_down...
5,297,770
def test_render_response_content_example_1st_from_media_type(testrenderer): """Path response's example from first media type is rendered.""" markup = textify( testrenderer.render_response_content( { "text/plain": {"example": 'foo = "bar"\nbaz = 42'}, "applica...
5,297,771
def rotateQuaternionByRPYInUnrotatedFrame(roll, pitch, yaw, in_quat): """ Apply RPY rotation in the reference frame of the quaternion. Input: geometry_msgs.msg.Quaternion Output: geometry_msgs.msg.Quaternion rotated by roll, pitch, yaw in its frame """ q_in = [in_quat.x, in_quat.y, in_quat.z, i...
5,297,772
def log_mat(U): """Matrix logarithm, only use for normal matrices, i.e., square matrices U with U * U^T = U^T * UU""" vals, vecs = la.eig(U) vals = np.log(vals) return np.real(np.einsum('...ij,...j,...kj', vecs, vals, vecs))
5,297,773
def png(x, filename, density=150, debug=False, do_in_background=False, tiny=False, pdflatex=True, engine='pdflatex'): """ Create a png image representation of ``x`` and save to the given filename. INPUT: - ``x`` -- object to be displayed - ``filename`` -- file in which to save the i...
5,297,774
def date_str_to_datetime(date_str: Optional[str]) -> timezone.datetime: """ Converts a date string to a datetime object. :param date_str: Date string (iso8601) :return: A datetime object. """ if date_str is None: return None return parse_datetime(date_str)
5,297,775
def test_pw_failed_scf_not_converged(fixture_database, fixture_computer_localhost, generate_calc_job_node, generate_parser, generate_inputs_default, data_regression): """Test the parsing of an scf calculation that ran nominally but did not reach convergence.""" name = 'failed_scf_not_converged' entr...
5,297,776
def video_demo(): """Detect videos.""" cap = cv2.VideoCapture(FLAGS.input_path) # Define the codec and create VideoWriter object # fourcc = cv2.cv.CV_FOURCC(*'XVID') # fourcc = cv2.cv.CV_FOURCC(*'MJPG') # in_file_name = os.path.split(FLAGS.input_path)[1] # out_file_name = os.path.join(FLAGS.out_dir, 'ou...
5,297,777
def add_field(radar_dest, radar_orig): """ adds the fields from orig radar into dest radar. If they are not in the same grid, interpolates them to dest grid Parameters ---------- radar_dest : radar object the destination radar radar_orig : radar object the radar object conta...
5,297,778
def result_folder(*relative_path): """Return the full path to the result/ folder containing experimental result files""" C = _get_config() path = C["experiment"]["expr_results_path"] if relative_path: path = os.path.join(path, *relative_path) return path
5,297,779
def _convert_str_to_html(string): """Helper function to insert <br> at line endings etc.""" if not string: return "" lines = string.splitlines() for index, line in enumerate(lines): for char in line: if char == '\t': lines[index] = line.replace(char, "&nbsp;&nbsp;&nbs...
5,297,780
def open_event_loop(as_current: bool = True) -> Iterator[asyncio.AbstractEventLoop]: """Open a new event loop and cleanly stop it Args: as_current: whether to make this loop the current loop in this thread """ loop = asyncio.new_event_loop() try: if as_current: asyncio.s...
5,297,781
def build_icd(cp, instruction): """ Build the integer representation of the input channels to dequeue. :param cp: CoreParameters instance for the target architecture :param instruction: Instruction instance :return: integer representation of icd """ # OR in the literal array of bits. i...
5,297,782
def broadcast(tensor, src_rank: int = 0, group_name: str = "default"): """Broadcast the tensor from a source process to all others. Args: tensor: the tensor to be broadcasted (src) or received (destination). src_rank (int): the rank of the source process. group_name (str): the collectiv...
5,297,783
def processDirectory(inDir, doBgd, doFgd): """Create a layered PDF file from the rasters in `inDir` Temp files are stored in `jbigDir` """ if inDir.endswith("/"): print("%s->%s" % (inDir, inDir[:-1])) inDir = inDir[:-1] base = os.path.basename(inDir) base, _ = os.path.splite...
5,297,784
def _parseLinks(response, rel): """ Parses an HTTP response's ``Link`` headers of a given relation, according to the Corelight API specification. response (requests.Response): The response to parse the ``Link`` headers out of. rel (str): The link relation type to parse; all other relations are...
5,297,785
def compute_crop_box(bound_box: dict): """Computes the coordinates to crop an image based on the provided bound_box and the SCALE variable. The input only describes a box around the mask (or area where the mask would be), and the width and height could could be different. The output box will be a square...
5,297,786
def find_min_max(data): """Solution to exercise C-4.9. Write a short recursive Python function that finds the minimum and maximum values in a sequence without using any loops. """ n = len(data) min_val = data[0] max_val = data[0] def recurse_minmax(idx): nonlocal min_val, max_v...
5,297,787
async def test_play_media_didl_metadata( hass: HomeAssistant, dmr_device_mock: Mock, mock_entity_id: str ) -> None: """Test play_media passes available DIDL-Lite metadata to the DMR.""" @dataclass class DidlPlayMedia(PlayMedia): """Playable media with DIDL metadata.""" didl_metadata: d...
5,297,788
def generate_T3_uvh5(name, pt_dec, tstart, ntint, nfint, filelist, params=T3PARAMS, start_offset=None, end_offset=None): """Generates a measurement set from the T3 correlations. Parameters ---------- name : str The name of the measurement set. pt_dec : quantity The pointing declinat...
5,297,789
def upload_file(file:Path, metadata:Metadata, repo): """Upload a file to an index server, given the index server details. """ data = build_post_data('file_upload', metadata) data['protocol_version'] = '1' if file.suffix == '.whl': data['filetype'] = 'bdist_wheel' py2_support = not (m...
5,297,790
def mask_with_tokens(t, token_ids): """ 用记号遮掩 """ init_no_mask = torch.full_like(t, False, dtype=torch.bool) mask = reduce(lambda acc, el: acc | (t == el), token_ids, init_no_mask) # print("mask",mask) return mask
5,297,791
def isStandard(descriptorType): """ >>> isStandard(0x0a) True >>> isStandard(0x22) False >>> isStandard(0x61) False >>> isStandard(0x1a) True """ # See USB Common Class Specification s. 3.11 for this field's structure # Bit 7: reserved # Bits 6..5: descriptor type ...
5,297,792
def test_set_value_for_non_existing_key(): """Passed key has non entry in the config. A new entry with the passed key-value pair should get created. """ config: Config = Config() config.set(route="database.connection.user", value="Testuser") assert config.defaults["database"]["connection"]["user"]...
5,297,793
def split_test(df, test_method='fo', test_size=.2): """ method of splitting data into training data and test data Parameters ---------- df : pd.DataFrame raw data waiting for test set splitting test_method : str, way to split test set 'fo': split by ratio ...
5,297,794
async def status(ctx): """Displays remaining time before ping and timer settings.""" raw_time = timer.get_time() time_secs = raw_time % 60 time_mins = int((raw_time - time_secs) / 60) if time_secs < 10: time_secs = '0' + str(time_secs) time_desc = f'Time Remaining: `{time_mins}:{time_sec...
5,297,795
def test_estimparam(path): """Run basic Parameter estimation example """ for filePath in glob.glob('estimparam_out.*'): os.remove(filePath) subprocess.call([path,"--parameter","ra","--chosenscen","3","--noob","50"])
5,297,796
def CompileAssetCatalog(output, platform, product_type, min_deployment_target, inputs, compress_pngs): """Compile the .xcassets bundles to an asset catalog using actool. Args: output: absolute path to the containing bundle platform: the targetted platform product_type: the bundle type min_deplo...
5,297,797
def store_bot_config(host, content): """Stores a new version of bot_config.py. Returns the ndb.Key of the new stored entity. """ if not _validate_python(content): raise ValueError('Invalid python') # The memcache entry will be cleared out automatically after 60s. Try a best # effort. signature = _get...
5,297,798
def equals(val1, val2): """ Returns True if the two strings are equal, False otherwise. The time taken is independent of the number of characters that match. For the sake of simplicity, this function executes in constant time only when the two strings have the same length. It short-circuits when t...
5,297,799