content
stringlengths
22
815k
id
int64
0
4.91M
def assert_stage_equal(d1, d2): """Keeps the params section in order, and then checks for equality.""" for d in [d1, d2]: assert recurse_not_a_node(d) for _, stage_d in d.get("stages", {}).items(): params = _merge_params(stage_d.get("params", [])) for k in params: ...
5,321,900
def test_handler(lambda_module, context, postconfirm_data): """ Test handler() """ output = copy.deepcopy(postconfirm_data["output"]) output["Time"] = stub.ANY # Prepare stub eventbridge = stub.Stubber(lambda_module.eventbridge) response = {} expected_params = {"Entries": [output]}...
5,321,901
def check_translation(s3key): """Check if the translation proccess is completed verifying that the translated data exists on an AWS S3 Bucket. If the translated data isn't in the AWS S3 Bucket it will call itself recursively until it's available. Arguments: s3key (str): the key of the data...
5,321,902
def streamline(ctx, a): """ Represents Streamline.vi. """ plotid = a.plotid() x = a.dbl_1d('x') # X loc of arrows y = a.dbl_1d('y') # Y loc of arrows u = a.dbl_2d('u') # Arrow X component v = a.dbl_2d('v') # Arrow Y component ...
5,321,903
def write_results_to_tensorboard( attack_results: AttackResults, writers: Union[tf1.summary.FileWriter, List[tf1.summary.FileWriter]], step: int, merge_classifiers: bool): """Write attack results to tensorboard. Args: attack_results: results from attack writers: a list of tensorboard writer...
5,321,904
def test_translate_init_files( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, test_app: Flask, runner: FlaskCliRunner, ) -> None: """Test management of files when running ``flask translate init``. :param tmp_path: Create and return temporary ``Path`` object. :param monkeypatch: Mock patch...
5,321,905
def check_reorgs_task(self) -> Optional[int]: """ :return: Number of oldest block with reorg detected. `None` if not reorg found """ with contextlib.suppress(LockError): with only_one_running_task(self): logger.info("Start checking of reorgs") reorg_service: ReorgService ...
5,321,906
def InputChecking(str_inputFileName_genotype, str_inputFileName_phenotype): """ To check the numbers of sample are consistent in genotype and phenotype data. Args: str_inputFileName_genotype (str): File name of input genotype data str_inputFileName_phenotype (str): File name of input pheno...
5,321,907
def main(): """ main entry point for module execution """ element_spec = dict( fabric=dict(required=True, type='str'), config=dict(required=False, type='list'), state=dict(type='str', default='merged', choices = ['merged', 'replaced', 'overridden', 'deleted', ...
5,321,908
def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the g...
5,321,909
def is_all_gathered(): """ Determines if all languages have had their download goals accomplished """ for lang in gathered: if len(gathered[lang]) < NUM_TO_GATHER: return False return True
5,321,910
def greedy_eval_Q(Q: QTable, this_environment, nevaluations: int = 1): """ Evaluate Q function greediely with epsilon=0 :returns average cumulative reward, the expected reward after resetting the environment, episode length """ cumuls = [] for _ in range(nevaluations): evaluation_state ...
5,321,911
def lowercase(obj): """ Make dictionary lowercase """ if isinstance(obj, dict): return {k.lower(): lowercase(v) for k, v in obj.items()} elif isinstance(obj, (list, set, tuple)): t = type(obj) return t(lowercase(o) for o in obj) elif isinstance(obj, str): return obj.lower...
5,321,912
def pie_chart_weights( weights: dict, title_opt: str, external_axes: Optional[List[plt.Axes]] ): """Show a pie chart of holdings Parameters ---------- weights: dict Weights to display, where keys are tickers, and values are either weights or values if -v specified title_opt: str ...
5,321,913
def bump_pipeline_version(lint_obj, new_version): """ Function to bump a pipeline version number. Called by the main script """ # Collect the old and new version numbers current_version = lint_obj.config.get('manifest.version', '').strip(' \'"') if new_version.startswith('v'): logging.warn("Str...
5,321,914
def link_translate(course, html): """ return html string with ~/ and ~~/ links translated into the appropriate course and site urls """ # for site course, url ends with / ; for others, it doesn't. if course.url[-1] == '/': course_url_with_slash = course.url else: course_url_with_...
5,321,915
def test_reversed_selection(): """Basic reversed order selection test.""" unsorted = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] assert selection(unsorted) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
5,321,916
def get_3ddata(nx, ny, nz, line, data): """ Read a line and convert it to 3D dose representation Parameters ---------- nx: integer nof X points ny: integer nof Y points nz: integer nof Z points line: string which contains all 3D dose data points data...
5,321,917
def test_is_benign_1(): """First criterias for benign: Benign (i) 1 Stand-alone (BA1) OR """ # GIVEN values that fulfill the (i) criteria for benign ba = True bs_terms = [] ## WHEN performing the evaluation res = is_benign(ba, bs_terms) ## THEN assert the criterias are fu...
5,321,918
def run(data_dir: str, genotype_matrix: str, phenotype_matrix: str, phenotype: str, encoding: str = None, maf_percentage: int = 0, save_dir: str = None, datasplit: str = 'nested-cv', n_outerfolds: int = 5, n_innerfolds: int = 5, test_set_size_percentage: int = 20, val_set_size_percentage: int = ...
5,321,919
def _workaround_for_datetime(obj): """Workaround for numpy#4983: buffer protocol doesn't support datetime64 or timedelta64. """ if _is_datetime_dtype(obj): obj = obj.view(np.int64) return obj
5,321,920
def getOptions(): """Function to pull arguments""" parser = argparse.ArgumentParser(description="Removes samples from the design file" \ "belonging to the user-specified group(s).") # Standar Input standar = parser.add_argument_group(title="Standard input", ...
5,321,921
def delete_user_password(session, password_name, user_id): # type: (Session, str, int) -> None """Delete the specified UserPassword. Args: session(grouper.models.base.session.Session): database session password_name: the name of the password to delete user_id: the user whose passwor...
5,321,922
def sql_dynamic_row_count_redshift(schemas: list) -> str: """Generates an SQL statement that counts the number of rows in every table in a specific schema(s) in a Redshift database""" sql_schemas = ', '.join(f"'{schema}'" for schema in schemas) return f""" WITH table_list AS ( SELECT schema...
5,321,923
def eow(date: datetime.date, offset: int = 0, weekday: str = "SUN") -> datetime.date: """ Returns the end of the week, i.e. the first date on or after the given date whose weekday is equal to the the :code:`weekday` argument, and offset by a given number of weeks. Weekday must be one of :code...
5,321,924
def set_proxy(url, port=80): """ Sets a proxy server to tunnel requests to the Riot API through Args: url (str): the URL of the proxy server, without port number or protocol port (int): the port number to conntect to (default 80) """ if url: cassiopeia.dto.requests.proxy = u...
5,321,925
def dequote(s): """ from: http://stackoverflow.com/questions/3085382/python-how-can-i-strip-first-and-last-double-quotes If a string has single or double quotes around it, remove them. Make sure the pair of quotes match. If a matching pair of quotes is not found, return the string unchanged. """...
5,321,926
def test_RR(contingency_table): """purpose: test risk ratio/enrichment""" contingency_table = Haldane_correction(contingency_table) observed = calculate_RR(contingency_table) assert observed == 5 / 9
5,321,927
def has_issue_tracker(function): """ Decorator that checks if the current pagure project has the issue tracker active If not active returns a 404 page """ @wraps(function) def check_issue_tracker(*args, **kwargs): repo = flask.g.repo if not flask.g.issues_enabled or not repo...
5,321,928
def find_deprecated_usages( schema: GraphQLSchema, ast: DocumentNode ) -> List[GraphQLError]: """Get a list of GraphQLError instances describing each deprecated use.""" type_info = TypeInfo(schema) visitor = FindDeprecatedUsages(type_info) visit(ast, TypeInfoVisitor(type_info, visitor)) return ...
5,321,929
def construct_embedding_mask(V): """ Construct a mask for a batch of embeddings given node sizes. Parameters ---------- V: (batch_size) actual number of nodes per set (tensor) Returns ------- mask: (batch_size) x (n_nodes) binary mask (tensor) """ batch_size = len(V) max_n_...
5,321,930
def test_config_present(): """ config_present method - add config """ config_data = [ "snmp-server community randomSNMPstringHERE group network-operator", "snmp-server community AnotherRandomSNMPSTring group network-admin", ] snmp_matches1 = [ "snmp-server community rand...
5,321,931
def test_procfilesreplicatejobs_t5(m_mkdir): """ Test a real application hook to see if this works. """ app = "gromacs" arg = "test" cwd = os.path.join(os.getcwd(), "tests/standards/jobs/replicate") initargs = ["-deffnm", "test"] rep = "rep4" fileitem = _procfilesreplicatejobs(app...
5,321,932
def url_form(url): """Takes the SLWA photo url and returns the photo url. Note this function is heavily influenced by the format of the catalogue and could be easily broken if the Library switches to a different url structure. """ if url[-4:] != '.png' and url[-4:] != '.jpg': url = url + '...
5,321,933
def timedelta_from_now(delta): """ Add a timedelta to now, plus a fudge factor of a few seconds. Most useful for chaining with Django's builtin filter "timeuntil", for producing a humanized timedelta. """ return datetime.datetime.utcnow() + delta + datetime.timedelta(seconds=5)
5,321,934
def parse_args(): """Command line argument parsing.""" global flag_subvol, flag_echo, flag_dryrun, flag_llvm_build global flag_echo try: optlist, args = getopt.getopt(sys.argv[1:], "deDs:b:") except getopt.GetoptError as err: # unrecognized option usage(str(err)) if args: usage("unknown ext...
5,321,935
def myglob(paths,include=('/**/*.ipynb',),exclude=None,exclude_default=\ ('/**/*_tested.ipynb','**/testnotebooks.ipynb',\ '**/*Template.ipynb')): """Find files that match some patterns, but exclude other patterns. For paths given by `paths`, find all file path names that match an...
5,321,936
def _filepaths(directory, full_paths=True): """Get the filenames in the directory. Args: directory: Directory with the files full_paths: Give full paths if True Returns: result: List of filenames """ # Initialize key variables if bool(full_paths) is True: resul...
5,321,937
def multivariate_gaussian(pos, mu, sigma): """ Calculate the multivariate Gaussian distribution on array pos. Source: https://scipython.com/blog/visualizing-the-bivariate-gaussian-distribution/ :param pos: numpy array, constructed by packing the meshed arrays of variables x1, x2, .. xk i...
5,321,938
def du(path): """disk usage in human readable format (e.g. '2,1GB')""" return subprocess.check_output(['du', '-sh', path]).split()[0].decode('utf-8')
5,321,939
def Rpivot(p, q, Mb): """ Given an augmented matrix Mb, Mb = M|b, this gives the output of the pivot entry [i, j] in or below row p, and in or to the right of column q. """ # n is the number of columns of M, which is one less than that of Mb. m = len(Mb) n = len(Mb[0]) - 1 # Ini...
5,321,940
def create3d_vector(name=None, source='default'): """%s :param name: The name of the created object :type name: `str`_ :param source: The object to inherit from. Can be a 3d_vector, or a string name of a 3d_vector. :type source: `str`_ or :class:`vcs.dv3d.Gf3Dvector` :returns: A 3d_ve...
5,321,941
def _GenerateJSONForTestResults(options, log_processor): """Generates or updates a JSON file from the gtest results XML and upload the file to the archive server. The archived JSON file will be placed at: www-dir/DEST_DIR/buildname/testname/results.json on the archive server. NOTE: This will be deprecated....
5,321,942
def unrank(n, rk): """Return the permutation of rank rk in Sn.""" P = [0] * n # Store (j+1)! for calculation. fac = 1 for j in xrange(n-1): fac *= (j+1) d = (rk % (fac * (j+2))) / fac rk -= d * fac P[n-j-2] = d for i in xrange(n-j-1,n): if P[i] ...
5,321,943
def _compute_influence_kernel(iter, dqd, iter_scale, radius,learning_rate): """Compute the neighborhood kernel for some iteration. Parameters ---------- iter : int The iteration for which to compute the kernel. dqd : array (nrows x ncolumns) This is one...
5,321,944
def get_as_dict(x: Union[Dict, Sentence]) -> Dict: """Return an object as a dictionary of its attributes.""" if isinstance(x, dict): return x else: try: return x._asdict() except AttributeError: return x.__dict__
5,321,945
def get_user_sector_name(db_id): """ Get the user defined sector for the given database id string. Raise an exception if not found. """ found, sector = user_sector_finder("id", int(db_id)) if found: return make_sector_description(sector[0], True) else: raise NotFoundExcepti...
5,321,946
def draw_things_into_one_plot(mother_folder, draw_type='AUPR', x_axis = 'iou_th', y_axis = 'min_th', save_name='agg_plot', fpr_threshold=FPR_THRESHOLD, dila=5): """ This function draws a number of plots into a single plot so that I do not have to put them one-by-one into a damn ppt ...
5,321,947
def delete_author_by_id( author_id: int = Path(..., title="The Id of the author to be deleted", ge=0), sql: Session = Depends(db_session), current_user: UsersBase = Depends(get_current_active_user) ): """delete a specific author""" if current_user.Status: ...
5,321,948
def assign_judges_to_track(track, judges): """ Assign judges to projects in a single, specified track with all the projects they will be looking at :param str track: name of the track we want judges for :param list judges: a list of the judges allocated for this track :return: a dictionary with the keys as ...
5,321,949
def build_week_stats(): """ A temporary helper to populate our weekly stats """ from perma.models import Link, LinkUser, Organization, Registrar, WeekStats from datetime import timedelta from django.utils import timezone # regenerate all weekly stats WeekStats.objects.all().delete()...
5,321,950
def get_current_user(current_user): """ User route to get current user Parameters ---------- Registered/Admin access Returns ------- User Data """ sql_query = "SELECT * FROM diyup.users WHERE email_address=%s" cur = mysql.connection.cursor() cur.execute(sql_query, (cur...
5,321,951
def incident_exists(name, message, status): """ Check if an incident with these attributes already exists """ incidents = cachet.Incidents(endpoint=ENDPOINT) all_incidents = json.loads(incidents.get()) for incident in all_incidents['data']: if name == incident['name'] and \ st...
5,321,952
def transmogrifier(bulk=5, once=False, sleep_time=60): """ Creates a Transmogrifier Worker that gets a list of new DIDs for a given hash, identifies the subscriptions matching the DIDs and submit a replication rule for each DID matching a subscription. :param thread: Thread number at startup. :...
5,321,953
def show_img_with_matplotlib(color_img, title, pos): """Shows an image using matplotlib capabilities""" img_RGB = color_img[:, :, ::-1] ax = plt.subplot(1, 4, pos) plt.imshow(img_RGB) plt.title(title) plt.axis('off')
5,321,954
def compute_down(expr): """ Compute the expression on the entire inputs inputs match up to leaves of the expression """ return expr
5,321,955
def test_selecting_no_points_with_drag(create_known_points_layer): """Select all points when drag box includes all of them.""" layer, n_points, known_non_point = create_known_points_layer layer.mode = 'select' # Simulate click event = ReadOnlyWrapper( Event(type='mouse_press', position=kno...
5,321,956
def clip_weight_norm(model, max_norm, norm_type=2, except_params=None): """Clips gradient norm of an iterable of parameters. The norm is computed over all gradients together, as if they were concatenated into a single vector. Gradients are modified in-place. Arguments: parameters (Iterable[Var...
5,321,957
def NEV_to_HLA(survey, NEV, cov=True): """ Transform from NEV to HLA coordinate system. Params: survey: (n,3) array of floats The [md, inc, azi] survey listing array. NEV: (d,3) or (3,3,d) array of floats The NEV coordinates or covariance matrices. cov: boolean ...
5,321,958
def create_read_model_cmd() -> list: """Create TaiSEIA device model request protocol data.""" return SAInfoRequestPacket.create( sa_info_type=SARegisterServiceIDEnum.READ_MODEL ).to_pdu()
5,321,959
def generate_mandatory_attributes(diagnostic_cubes, model_id_attr=None): """ Function to generate mandatory attributes for new diagnostics that are generated using several different model diagnostics as input to the calculation. If all input diagnostics have the same attribute use this, otherwise s...
5,321,960
def _convert_to_slices(indices, max_nslice_frac=0.1): """ Convert list of indices to a list of slices. Parameters ---------- indices : list A 1D list of integers for array indexing. max_nslice_frac : float A float from 0 -- 1. If the number of slices needed to represent ...
5,321,961
def log2(x, dtype=None): """ Base-2 logarithm of `x`. Note: Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and `extobj` are not supported. Args: x (Tensor): Input tensor. dtype (:class:`mindspore.dtype`, optional): Default: :class:`None`. Over...
5,321,962
async def init_app(): """ Инициализируем приложение :return: """ app = web.Application() try: app.db = await asyncpg.pool.create_pool(get_config()) except asyncpg.exceptions.InvalidCatalogNameError: raise Exception('DSN сконфигурирован неверно ' 'и...
5,321,963
def pad_array( x: np.ndarray, to_multiple: int = None, to_size: int = None, axis: int = 0 ): """Pads an array either to a multiple of `to_multiple` or to the exact length `to_size` along `axis`. Parameters ---------- x: np.ndarray The array to pad. to_multiple: int, optional ...
5,321,964
def fill_defaults(value, default): """ #TODO: no longer needed, remove. """ if value is None: value = default elif isinstance(value, int): value = tuple([value] * 3) elif isinstance(value, tuple): value = tuple(item if item else default[i] for i, item in enumerate(value)) ret...
5,321,965
def ihfft2(x, s=None, axes=(-2, -1), norm="backward", name=None): """ Compute the two dimensional inverse FFT of a real spectrum. This is really `ihfftn` with different defaults. For more details see `ihfftn`. Args: x(Tensor): Input tensor s(Sequence[int], optional): Shape of the r...
5,321,966
def pp_ajaximg(context, nodelist, *args, **kwargs): """ Modifies the request session data to prep it for AJAX requests to the Ajax image uploader. """ context.push() namespace = get_namespace(context) request = kwargs.get('request', None) obj = kwargs.get('object', None) if obj is not N...
5,321,967
def generate_commands(): """ Provide commands for working with generation name. """
5,321,968
def bgr2rgb(x, dim=-3): """Reverses the channel dimension. See :func:`channel_flip`""" return channel_flip(x, dim)
5,321,969
def test_manage_project_strings_translated_resource(client_superuser): """Test that adding new strings to a project enables translation of that project on all enabled locales. """ locales = [ LocaleFactory.create(code='kl', name='Klingon'), LocaleFactory.create(code='gs', name='Geonosian...
5,321,970
def get_all_predictions(): """ Function for getting the predictions of models on the mnist test dataset. :return: a dictionary with predictions of all models. """ all_results = {} model_paths = ["ffnn_models", "dropout_models"] sizes = [1000, 2500, 7000, 19000, 50000] pred, correct = Non...
5,321,971
def moving_avg(timeseries, days=7, dropna=False, win_type=None, params=None): """Takes a centred moving average of a time series over a window with user-defined width and shape. Note: when taking a N-day centred moving average, the first and last N//2 days won't return a value and are effectively lost, BUT they are...
5,321,972
def get_defined_lvls(inp_str): """ gets a list which specifies what levels have been defined """ levels_def_pattern = ('level' + one_or_more(SPACE) + capturing(one_or_more(NONSPACE))) defined_levels = all_captures(levels_def_pattern, inp_str) return defined_levels
5,321,973
def requests_per_process(process_count: int, conf) -> Tuple[int, int]: """Divides how many requests each forked process will make.""" return ( int(conf.concurrency / process_count), int(conf.requests / process_count), )
5,321,974
def load_into_bamfile(meshdata, subfiles, model): """Uses pycollada and panda3d to load meshdata and subfiles and write out to a bam file on disk""" if os.path.isfile(model.bam_file): print 'returning cached bam file' return model.bam_file mesh = load_mesh(meshdata, subfiles) model...
5,321,975
def gettree(number, count=3): """ Сформировать дерево каталогов """ result = [] newline = str(number) while len(newline) % count: newline = '0' + newline for i in range(0, len(newline)//count): result.append(newline[i*count:i*count+count]) return result
5,321,976
def test_single_nan(): """Test single 'nan' input for down sampling""" x = np.arange(20, dtype='int32') y = np.array([0.0, 1.0, 2.0, np.nan, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0], dtype=np.float) assert sys.getrefcou...
5,321,977
def activate(): """Activates face mouse control """ global click, is_active is_active = btn_activate.pressed click = btn_activate.pressed lbl_info.setText(f"Eye blinking status : {click}")
5,321,978
def to_unserialized_json(obj): """ Convert a wire encodeable object into structured Python objects that are JSON serializable. :param obj: An object that can be passed to ``wire_encode``. :return: Python object that can be JSON serialized. """ return _cached_dfs_serialize(obj)
5,321,979
def test_018_list_files_in_dir_modification_time(): """TC346 Test case for listing files in directory depending on modification time. **Test scenario** #. Create a tree with many sub directories and files. #. Modify a file and take timestamp of now (T1). #. List the parent directory of this tre...
5,321,980
def install_simulation( version, sim_dir, rel_name, run_dir, vel_mod_dir, srf_file, stoch_file, stat_file_path, vs30_file_path, vs30ref_file_path, check_vm, fault_yaml_path, root_yaml_path, v1d_full_path, cybershake_root, v1d_dir=platform_config[PLATFORM_C...
5,321,981
def get_negatives(all_contexts, vocab, counter, K): """返回负采样中的噪声词.""" # 索引为1、2、...(索引0是词表中排除的未知标记) sampling_weights = [ counter[vocab.to_tokens(i)]**0.75 for i in range(1, len(vocab)) ] all_negatives, generator = [], RandomGenerator(sampling_weights) for contexts in all_contexts: ...
5,321,982
def _get_msvc_vars(repository_ctx, paths): """Get the variables we need to populate the MSVC toolchains.""" msvc_vars = dict() vc_path = find_vc_path(repository_ctx) missing_tools = None if not vc_path: repository_ctx.template( "vc_installation_error.bat", paths["@baz...
5,321,983
def edmonds(V, E, root): """Recursive application of Edmonds' algorithm according to Wikipedia's description [0]. [0] https://en.wikipedia.org/wiki/Edmonds'_algorithm#Description :param V: set of vertices :type V: [int, ...] :param E: a set of edges :type E: [(int...
5,321,984
def run_multinest(loglikelihood, prior, dumper, nDims, nlive, root, ndump, eff, seed=-1): """Run MultiNest. See https://arxiv.org/abs/0809.3437 for more detail Parameters ---------- loglikelihood: :obj:`callable` probability function taking a single parameter: - ...
5,321,985
def tema(close, timeperiod=30): """Triple Exponential Moving Average 三重指数移动平均线 The triple exponential moving average was designed to smooth price fluctuations, thereby making it easier to identify trends without the lag associated with traditional moving averages (MA). It does this by taking multip...
5,321,986
def test_hash_table_hash_key_word(): """Test a hash table hashkey function.""" hash = HT() assert hash._hash_key('key') == 329 assert hash._hash_key('Key') == 297
5,321,987
def polling_iterator(lazy_iterator, max_memory): """Filter results of a lazy_iterator until either memory runs out or SIGINT. Patience is measured in nebulous "progress steps". """ assert isinstance(max_memory, float), max_memory assert 0 < max_memory and max_memory < 1, max_memory with In...
5,321,988
def load_single_model(save_path_stem, load_results_df=True): """load in the model, loss df, and model df found at the save_path_stem we also send the model to the appropriate device """ try: if load_results_df: results_df = pd.read_csv(save_path_stem + '_results_df.csv') els...
5,321,989
def mkheader(base_addr, infname, outfname): """Prepends the image with the MBN header. @arg base_addr: integer, specifies the image load address in RAM @arg infname: string, image filename @arg outfname: string, output image with header prepended @raises IOError: if reading/writing input/output fil...
5,321,990
def main(service: Service) -> None: """Runs an application.""" service.start()
5,321,991
def gray2jet(img): """[0,1] grayscale to [0.255] RGB""" jet = plt.get_cmap("jet") return np.uint8(255.0 * jet(img)[:, :, 0:3])
5,321,992
def main(infiles, outfile, key, queue, walltime, engine, num_runs, vmem, chunksize, log_level, log_dir, port, local): """ run over list of jsonl files convert each line to pandas df and dump it to HDF5 """ log.info("Putting ratescans from json files into hdf5 file") open_func = open if chu...
5,321,993
def is_context_spec(mapping): """Return True IFF `mapping` is a mapping name *or* a date based mapping specification. Date-based specifications can be interpreted by the CRDS server with respect to the operational context history to determine the default operational context which was in use at that dat...
5,321,994
def find_pair(cards): """ Find best pair of cards + three highest ranked cards Parameters ---------- cards : TYPE DESCRIPTION. Returns ------- prevCard : TYPE DESCRIPTION. """ PokerCard.cardsRank(cards) PairsList = [] try: prevCard = cards[...
5,321,995
def test_format_size(): """格式化 size""" assert '102B' == format_size(102) assert '1K' == format_size(1024) assert '1.98K' == format_size(2024) assert '1.86M' == format_size(1024 **2 + 900000) assert '1.84G' == format_size(1024 **3 + 900000000) assert '1.39T' == format_size(1024 **4 + 1024 **...
5,321,996
def test_vec_stringification(py_c_vec: PyCVec): """Test the various string methods.""" Vec, Angle, Matrix, parse_vec_str = py_c_vec # Add on the edge case where '.0' needs to be kept. for x, y, z in iter_vec(VALID_NUMS + [-210.048]): v: Py_Vec = Vec(x, y, z) assert str(v) == f'{x:g} {y:g...
5,321,997
def mergeSort(nums): """归并排序""" if len(nums) <= 1: return nums mid = len(nums)//2 #left left_nums = mergeSort(nums[:mid]) #right right_nums = mergeSort(nums[mid:]) print(left_nums) print(right_nums) left_pointer,right_pointer = 0,0 result = [] while left_pointer < len(left_nums) and r...
5,321,998
def fix_license(src_lfile, dst_lfile): """ Fix the license file, if there is one, so that it conforms to the SIP v5 syntax. src_lfile is the name of the license file. dst_lfile is the name of the fixed license file. """ f = open(src_lfile) f5 = open_for_writing(dst_lfile) for line in f: ...
5,321,999