content
stringlengths
22
815k
id
int64
0
4.91M
def main(cfg): """Solve the CVRP problem.""" # Instantiate the data problem. data = create_data_model(cfg) print(data) if len(data['distance_matrix'])==0: result = { "solution":False, "error-message":"unable to calculate distance matrix" } return resul...
18,900
def abs2genomic(chromsizes, start_pos, end_pos): """ Convert absolute coordinates to genomic coordinates Parameters: ----------- chromsizes: [[chrom, size],...] A list of chromosome sizes associated with this tileset start_pos: int The absolute start coordinate end_pos: int ...
18,901
def generate_koopman_data(): """ Prepare Koopman data in .mat format for MATLAB Koopman code (generate_koopman_model.m) """ from scipy.io import savemat from sofacontrol.utils import load_data, qv2x from sofacontrol.measurement_models import linearModel pod_data_name = 'pod_snapshots' n...
18,902
def print_snapshot_stats(options, _fuse): """ @param options: Commandline options @type options: object @param _fuse: FUSE wrapper @type _fuse: dedupsqlfs.fuse.dedupfs.DedupFS """ _fuse.setReadonly(True) from dedupsqlfs.fuse.snapshot import Snapshot snap = Snapshot(_fuse.operatio...
18,903
def test_montage_readers( reader, file_content, expected_dig, ext, tmpdir ): """Test that we have an equivalent of read_montage for all file formats.""" fname = op.join(str(tmpdir), 'test.{ext}'.format(ext=ext)) with open(fname, 'w') as fid: fid.write(file_content) dig_montage = reader(fnam...
18,904
def print_message(msg): """Writes a message to screen. Input: string.""" print msg
18,905
def get_corners(p, fov): """Get corners relative to DSS coordinates. xy coords anti-clockwise""" c = np.array([[0, 0], fov[::-1]]) # lower left, upper right xy # corners = np.c_[c[0], c[:, 1], c[1], c[::-1, 0]].T # / clockwise yx corners = np.c_[c[0], c[::-1, 0], c[1], c[:, 1]].T # / clockwise xy ...
18,906
def mixnet_m( num_classes: int = 1000, multiplier: float = 1.0, divisor: int = 8, min_depth: int = None, dataset: str = "IMAGENET", ) -> Dict[str, Any]: """Build MixNet-M.""" if dataset == "IMAGENET": medium: Tuple[List[Any], ...] = ( [24, 24, 1, 1, 1, None, False], ...
18,907
def no_block(func): """Turns a blocking function into a non-blocking coroutine function.""" @functools.wraps(func) async def no_blocking_handler(*args, **kwargs): partial = functools.partial(func, *args, **kwargs) return await asyncio.get_event_loop().run_in_executor(None, partial) ret...
18,908
def wgan_g_loss(scores_fake): """ Input: - scores_fake: Tensor of shape (N,) containing scores for fake samples Output: - loss: Tensor of shape (,) giving WGAN generator loss """ return -scores_fake.mean()
18,909
def main(directory: str): """Export Hetionet in several BEL formats.""" click.echo(f'Using PyBEL v{pybel.get_version(with_git_hash=True)}') click.echo('Getting hetionet') graph = pybel.get_hetionet() click.echo('Grounding hetionet') graph = pybel.grounding.ground(graph) click.echo('Export...
18,910
def centroid_avg(stats): """ Read centroid X and Y 10x and return mean of centroids. stats : stats method of ophyd camera object to use, e.g. cam_8.stats4 Examples -------- centroid_avg(cam_8.stats4) centroidY = centroid_avg(cam_8.stats4)[1] """ centroidXArr = np.zeros...
18,911
def get_address_host_port(addr, strict=False): """ Get a (host, port) tuple out of the given address. For definition of strict check parse_address ValueError is raised if the address scheme doesn't allow extracting the requested information. >>> get_address_host_port('tcp://1.2.3.4:80') ('1...
18,912
def get_ua_list(): """ 获取ua列表 """ with open('zhihu_spider/misc/ua_list.txt', 'r') as f: return [x.replace('\n', '') for x in f.readlines()]
18,913
def measure_time(func): """add time measure decorator to the functions""" def func_wrapper(*args, **kwargs): start_time = time.time() a = func(*args, **kwargs) end_time = time.time() #print("time in seconds: " + str(end_time-start_time)) return end_time - start_time r...
18,914
def generate_dummy_targets(bounds, label, n_points, field_keys=[], seed=1): """ Generate dummy points with randomly generated positions. Points are generated on node 0 and distributed to other nodes if running in parallel. Parameters ---------- bounds : tuple of float Bounding box t...
18,915
def assert_allclose( actual: numpy.ndarray, desired: List[List[Union[float, int]]], err_msg: numpy.ndarray, ): """ usage.matplotlib: 1 """ ...
18,916
def save_map_data_in_nc_file(scn, chl_param, period): """ Save the mean values and number of data in a NetCdf file Use the satpy method by overwriting the chl_param and mask chl_param=mean chl data (note: it is log10 values) mask= number of data used for the calculation of means """ ...
18,917
def load_numbers_sorted(txt: str) -> List[int]: """ファイルから番号を読み込みソートしてリストを返す Args: txt (str): ファイルのパス Returns: List[int]: 番号のリスト """ numbers = [] with open(txt) as f: numbers = sorted(map(lambda e: int(e), f)) return numbers
18,918
def start_logger(log_directory_path): """To set up the log file folder and default configuration give a log directory path Args: log_directory_path (str): The directory path to create a folder containing the log files. Returns: logger (object): A logger object used for the MSOrgani...
18,919
def translate_pt(p, offset): """Translates point p=(x,y) by offset=(x,y)""" return (p[0] + offset[0], p[1] + offset[1])
18,920
def add_flag(*args, **kwargs): """ define a single flag. add_flag(flagname, default_value, help='', **kwargs) add_flag([(flagname, default_value, help), ...]) or define flags without help message add_flag(flagname, default_value, help='', **kwargs) add_flag('gpu', 1, help='CUDA_VISIBLE_...
18,921
def inference(hypes, images, train=True): """Build the MNIST model up to where it may be used for inference. Args: images: Images placeholder, from inputs(). train: whether the network is used for train of inference Returns: softmax_linear: Output tensor with the computed logits. """...
18,922
def test_address_list_one(): """Test making an address list with one address.""" email_renderer = EmailRenderer(SAMPLE_TO_ADDRESS, "") expected_address_1 = Address(username='smith', domain='example.com') assert email_renderer.address_list() == (expected_address_1, )
18,923
def truncate(sequence): """ Do nothing. Just a placeholder. """ string = str(sequence) return string.split()[0]
18,924
def reindex_record(pid_type, record_class, record_indexer_class): """Reindex records of given pid type.""" query = (x[0] for x in PersistentIdentifier.query.filter_by( object_type='rec', status=PIDStatus.REGISTERED ).filter( PersistentIdentifier.pid_type.in_((pid_type,)) ).values( ...
18,925
def unbind(port: int) -> dict: """Request browser port unbinding. Parameters ---------- port: int Port number to unbind. """ return {"method": "Tethering.unbind", "params": {"port": port}}
18,926
def get_files(dir="."): """ Gets all the files recursivly from a given base directory. Args: dir (str): The base directory path. Returns: list: A list that contains all files. """ folder_queue = [dir] files = set() while(folder_queue): next_folder = folder_...
18,927
def main(): """ run the tool""" tool = ProcessorTool() tool.run()
18,928
def test_theano_function_bad_kwarg(): """ Passing an unknown keyword argument to theano_function() should raise an exception. """ raises(Exception, lambda: theano_function_([x], [x + 1], foobar=3))
18,929
def xy_to_ellipse(x,Vx,y,Vy): """ Takes the Cartesian variables. This function returns the particle's position relative to an ellipse and parameters of the ellipse. Returns a,e,theta,theta_E """ # radius using x and y r = np.sqrt(x ** 2 + y ** 2) # speed of the particle V =...
18,930
def leak_dictionary_by_ignore_sha( policy_breaks: List[PolicyBreak], ) -> Dict[str, List[PolicyBreak]]: """ leak_dictionary_by_ignore_sha sorts matches and incidents by first appearance in file. sort incidents by first appearance on file, file wide matches have no index so give it -1 so the...
18,931
async def get_token(tkn: Token = Depends(from_authotization_header_nondyn)): """ Returns informations about the token currently being used. Requires a clearance level of 0 or more. """ assert_has_clearance(tkn.owner, "sni.read_own_token") return GetTokenOut.from_record(tkn)
18,932
def import_as_event_history(path): """ Import file as event history json format. Parameters ---------- path : str Absolute path to file. Returns ------- events : list List of historic events. """ # initialise output list events = [] # import through...
18,933
async def test_info_update(event_loop, aresponses): """Test getting Fumis WiRCU device information and states.""" aresponses.add( "api.fumis.si", "/v1/status", "GET", aresponses.Response( status=200, headers={"Content-Type": "application/json"}, ...
18,934
def reduce_dataset(d: pd.DataFrame, reduction_pars: dict): """ Reduces the data contained in a pandas DataFrame :param d: pandas DataFrame. Each column contains lists of numbers :param reduction_pars: dict containing 'type' and 'values'. 'type' describes the type of reduction performed on the lists ...
18,935
def update_office(office_id): """Given that i am an admin i should be able to edit a specific political office When i visit to .../api/v2/offices endpoint using PATCH method""" if is_admin() is not True: return is_admin() if not request.get_json(): return make_response(jsonify({'statu...
18,936
def load_project_resource(file_path: str): """ Tries to load a resource: 1. directly 2. from the egg zip file 3. from the egg directory This is necessary, because the files are bundled with the project. :return: the file as json """ ... if not os.path.isfile(file_pa...
18,937
def test_command_line_interface(): """Test the CLI.""" runner = CliRunner() result = runner.invoke(cli.main) assert result.exit_code == 0 assert 'WIP' in result.output help_result = runner.invoke(cli.main, ['--help']) assert help_result.exit_code == 0 assert '--help Show this message an...
18,938
def update_column(worksheet: gspread.Worksheet, column: str, data: t.List[str]): """ Update a column's data :param worksheet: the worksheet to update :param column: the column to update :param data: the data to replace the current cells with """ # Format the range and data r = f"{column}...
18,939
def start_command_handler(update, context): """Send a message when the command /start is issued.""" add_typing(update, context) quiz_question = QuizQuestion quiz_question.question = "What tastes better?" quiz_question.answers = ['water', 'ice', 'wine'] quiz_question.correct_answer_position = 2 ...
18,940
def phraser_on_header(row, phraser): """Applies phraser on cleaned header. To be used with methods such as: `apply(func, axis=1)` or `apply_by_multiprocessing(func, axis=1, **kwargs)`. Parameters ---------- row : row of pd.Dataframe phraser : Phraser instance, Returns ------- ...
18,941
def check_c_includes(filename, includes): """ Check whether file exist in include dirs """ from os.path import exists, isfile, join for directory in includes: path = join(directory, filename) if exists(path) and isfile(path): return path
18,942
def _delete(url, params): """RESTful API delete (delete entries in database) Parameters ---------- url: str Address for the conftrak server params: list Query string. Any pymongo supported mongo query Returns ------- bool True if delete successful Raises ...
18,943
def teardown(ctx): """Remove the VMs for current cluster.""" with _with_config(ctx) as tmpdirname: if click.confirm('Do you really want to tear down k93s cluster, set up ' 'with config {!s}'.format(ctx.obj['config'])): k93s.vms.teardown(tmpdirname, **ctx.obj)
18,944
def hard_nms(box_scores, iou_threshold, top_k=-1, candidate_size=200): """ Args: box_scores (N, 5): boxes in corner-form and probabilities. iou_threshold: intersection over union threshold. top_k: keep top_k results. If k <= 0, keep all the results. candidate_size: only consider...
18,945
def sma(data, span=100): """Computes and returns the simple moving average. Note: the moving average is computed on all columns. :Input: :data: pandas.DataFrame with stock prices in columns :span: int (defaul: 100), number of days/values over which the average is computed :Output: ...
18,946
def table_one(): """Table 1: Training results for different neuron numbers""" simulation_num = 1 print('\n** Running simulation {} **\n'.format(simulation_num)) table_header = ['hidden_neurons', 'learning_rate', 'max_epochs', 'activation', 'hits', 'mse'] args = INIT_ARGS.copy() ...
18,947
def parse_csd(dependencies): """Parse C-State Dependency""" return _CSD_factory(len(csd_data))(csd_data)
18,948
def field_path_get_type(root: HdlType, field_path: TypePath): """ Get a data type of element using field path """ t = root for p in field_path: if isinstance(p, int): t = t.element_t else: assert isinstance(p, str), p t = t.field_by_name[p].dtype ...
18,949
def reverse(rule): """ Given a rule X, generate its black/white reversal. """ # # https://www.conwaylife.com/wiki/Black/white_reversal # # "The black/white reversal of a pattern is the result of # toggling the state of each cell in the universe: bringing # dead cells to life, and killing li...
18,950
def hsic(k_x: torch.Tensor, k_y: torch.Tensor, centered: bool = False, unbiased: bool = True) -> torch.Tensor: """Compute Hilbert-Schmidt Independence Criteron (HSIC) :param k_x: n by n values of kernel applied to all pairs of x data :param k_y: n by n values of kernel on y data :param centered: whethe...
18,951
def write_msa_to_db(conn, cur, protein_id, msa): """ Writes a MSA to the database. Args: cur: Cursor object. protein_id: Protein id of the query. msa: MSA. Returns: Nothing. """ cur.execute('INSERT INTO alignments (id, msa) VALUES (?, ?)', (protein_id, msa)) ...
18,952
def task_group_task_ui_to_app(ui_dict): """Converts TaskGroupTask ui dict to App entity.""" return workflow_entity_factory.TaskGroupTaskFactory().create_empty( obj_id=ui_dict.get("obj_id"), title=ui_dict["title"], assignees=emails_to_app_people(ui_dict.get("assignees")), start_date=str_to_da...
18,953
def int_converter(value): """check for *int* value.""" int(value) return str(value)
18,954
def wraps(fun, namestr="{fun}", docstr="{doc}", **kwargs): """Decorator for a function wrapping another. Used when wrapping a function to ensure its name and docstring get copied over. Args: fun: function to be wrapped namestr: Name string to use for wrapped function. docstr: Docstri...
18,955
def test_plot_distributed_loads_fixed_left(): """Test the plotting function for distributed loads and fixed support on the left. Additionally, test plotting of continuity points. """ a = beam(L) a.add_support(0, "fixed") a.add_distributed_load(0, L / 2, "-q * x") a.add_distributed_load(L / 2...
18,956
def post_report(coverage): """Post coverage report to coveralls.io.""" response = requests.post(URL, files={'json_file': json.dumps(coverage)}) try: result = response.json() except ValueError: result = {'error': 'Failure to submit data. ' 'Response [%(status)s]: %(text)...
18,957
def parse_dialogs_per_response(lines,candid_dic,profile_size=None): """Parse dialogs provided in the personalized dialog tasks format. For each dialog, every line is parsed, and the data for the dialog is made by appending profile, user and bot responses so far, user utterance, bot answer index within candi...
18,958
def get_dist(): """ Measures the distance of the obstacle from the rover. Uses a time.sleep call to try to prevent issues with pin writing and reading. (See official gopigo library) Returns error strings in the cases of measurements of -1 and 0, as -1 indicates and error, and 0 seems to also i...
18,959
def wave_fingers(allegro_client, finger_indices=None, num_seconds=10): """ Wave one or more fingers in a sinusoidal pattern. :param allegro_client: The client. :param finger_indices: List of finger indices (between 0 and 3) :param num_seconds: Total time to spend do...
18,960
def map_filter(filter_function: Callable) -> Callable: """ returns a version of a function that automatically maps itself across all elements of a collection """ def mapped_filter(arrays, *args, **kwargs): return [filter_function(array, *args, **kwargs) for array in arrays] return mapp...
18,961
def compare_models( champion_model: lightgbm.Booster, challenger_model: lightgbm.Booster, valid_df: pd.DataFrame, comparison_metric: Literal["any", "all", "f1_score", "auc"] = "any" ) -> bool: """ A function to compare the performance of the Champion and Challenger models on ...
18,962
def check_additional_args(parsedArgs, op, continueWithWarning=False): """ Parse additional arguments (rotation, etc.) and validate :param additionalArgs: user input list of additional parameters e.g. [rotation, 60...] :param op: operation object (use software_loader.getOperation('operationname') :re...
18,963
def clean_text(text, language): """ text: a string returns: modified initial string (deletes/modifies punctuation and symbols.) """ replace_by_blank_symbols = re.compile('\#|\u00bb|\u00a0|\u00d7|\u00a3|\u00eb|\u00fb|\u00fb|\u00f4|\u00c7|\u00ab|\u00a0\ude4c|\udf99|\udfc1|\ude1b|\ude2...
18,964
def parameters(): """ Dictionary of parameters defining geophysical acquisition systems """ return { "AeroTEM (2007)": { "type": "time", "flag": "Zoff", "channel_start_index": 1, "channels": { "[1]": 58.1e-6, "[2]": ...
18,965
def generate_ngrams_and_hashit(tokens, n=3): """The function generates and hashes ngrams which gets from the tokens sequence. @param tokens - list of tokens @param n - count of elements in sequences """ return [binascii.crc32(bytearray(tokens[i:i + n])) for i in range(len(tokens) -...
18,966
def generate_fingerprints(args: Namespace, logger: Logger = None) -> List[List[float]]: """ Generate the fingerprints. :param logger: :param args: Arguments. :return: A list of lists of target fingerprints. """ # import pdb; pdb.set_trace() checkpoint_path = args.checkpoint_paths[0] ...
18,967
def _typecheck_input_batch_dot(x1_type, x2_type, prim_name=None): """ Check input tensor types to be valid and confirm they are the same type for batch dot ops. """ msg_prefix = f"For '{prim_name}', the" if prim_name else "The" const_utils.check_type_valid(x1_type, [mstype.float32], 'x1') const_...
18,968
def transform_xlogx(mat): """ Args: mat(np.array): A two-dimensional array Returns: np.array: Let UsV^† be the SVD of mat. Returns Uf(s)V^†, where f(x) = -2xlogx """ U, s, Vd = np.linalg.svd(mat, full_matrices=False) return (U * (-2.0*s * np.log(s))) @ Vd
18,969
def get_label_volumes(labelVolume, RefVolume, labelDictionary): """ Get label volumes using 1. reference volume and 2. labeldictionary :param labelVolume: :param RefVolume: :param labelDictionary: :return: """ import SimpleITK as sitk import os from collections import ( ...
18,970
def put_dummy_data(data_path): """Create a small dummy netCDF file to be cmorized.""" gen_cube = _create_sample_cube() t_path = os.path.join(data_path, "woa13_decav81B0_t00_01.nc") # correct var names gen_cube.var_name = "t_an" iris.save(gen_cube, t_path) s_path = os.path.join(data_path, "wo...
18,971
def get_clip_name_from_unix_time(source_guid, current_clip_start_time): """ """ # convert unix time to readable_datetime = datetime.fromtimestamp(int(current_clip_start_time)).strftime('%Y_%m_%d_%H_%M_%S') clipname = source_guid + "_" + readable_datetime return clipname, readable_datetime
18,972
def extract_pc_in_box3d(pc, box3d): """Extract point cloud in box3d. Args: pc (np.ndarray): [N, 3] Point cloud. box3d (np.ndarray): [8,3] 3d box. Returns: np.ndarray: Selected point cloud. np.ndarray: Indices of selected point cloud. """ box3d_roi_inds = in_hull(pc[...
18,973
def get_list_as_str(list_to_convert: typing.List[str]) -> str: """Convert list into comma separated string, with each element enclosed in single quotes""" return ", ".join(["'{}'".format(list_item) for list_item in list_to_convert])
18,974
def normalize_sides(sides): """ Description: Squares the sides of the rectangles and averages the points so that they fit together Input: - sides - Six vertex sets representing the sides of a drawing Returns: - norm_sides - Squared and fit sides list """ sides_list = [] # Average side vertices and make...
18,975
def GetFieldInfo(column: Schema.Column, force_nested_types: bool = False, nested_prefix: str = 'Nested_') -> FieldInfo: """Returns the corresponding information for provided column. Args: column: the column for which to generate the dataclass FieldInfo. force_n...
18,976
def get_session(): """ Get the current session. :return: the session :raises OutsideUnitOfWorkError: if this method is called from outside a UOW """ global Session if Session is None or not Session.registry.has(): raise OutsideUnitOfWorkError return Session()
18,977
def create_sgd_optimizers_fn(datasets, model, learning_rate, momentum=0.9, weight_decay=0, nesterov=False, scheduler_fn=None, per_step_scheduler_fn=None): """ Create a Stochastic gradient descent optimizer for each of the dataset with optional scheduler Args: datasets: a dictionary of d...
18,978
def equalize(img): """ Equalize the histogram of input PIL image. Args: img (PIL image): Image to be equalized Returns: img (PIL image), Equalized image. """ if not is_pil(img): raise TypeError('img should be PIL image. Got {}'.format(type(img))) return ImageOps....
18,979
def routemaster_serve_subprocess(unused_tcp_port): """ Fixture to spawn a routemaster server as a subprocess. Yields the process reference, and the port that it can be accessed on. """ @contextlib.contextmanager def _inner(*, wait_for_output=None): env = os.environ.copy() env.u...
18,980
def ratingRange(app): """ Get the rating range of an app. """ rating = 'Unknown' r = app['rating'] if r >= 0 and r <= 1: rating = '0-1' elif r > 1 and r <= 2: rating = '1-2' elif r > 2 and r <= 3: rating = '2-3' elif r > 3 and r <= 4: rating = '3-4' elif r > 4 and r <= 5: rating = '4-5' return rating
18,981
def immediate_sister(graph, node1, node2): """ is node2 an immediate sister of node1? """ return (node2 in sister_nodes(graph, node1) and is_following(graph, node1, node2))
18,982
def get_topic_link(text: str) -> str: """ Generate a topic link. A markdown link, text split with dash. Args: text {str} The text value to parse Returns: {str} The parsed text """ return f"{text.lower().replace(' ', '-')}"
18,983
def load_data(datapath): """Loads data from CSV data file. Args: datapath: Location of the training file Returns: summary dataframe containing RFM data for btyd models actuals_df containing additional data columns for calculating error """ # Does not used the summary_data_from_transaction_data fr...
18,984
def rms(a, axis=None): """ Calculates the RMS of an array. Args: a (ndarray). A sequence of numbers to apply the RMS to. axis (int). The axis along which to compute. If not given or None, the RMS for the whole array is computed. Returns: ndarray: The RMS of the arra...
18,985
def alpha_114(code, end_date=None, fq="pre"): """ 公式: ((RANK(DELAY(((HIGH - LOW) / (SUM(CLOSE, 5) / 5)), 2)) * RANK(RANK(VOLUME))) / (((HIGH - LOW) / (SUM(CLOSE, 5) / 5)) / (VWAP - CLOSE))) Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(e...
18,986
def event_message(iden, event): """Return an event message.""" return { 'id': iden, 'type': TYPE_EVENT, 'event': event.as_dict(), }
18,987
def logout(): """Logout.""" logout_user() flash(lazy_gettext("You are logged out."), "info") return redirect(url_for("public.home"))
18,988
async def test_discovery_single_instance(hass, discovery_flow_conf, source): """Test we not allow duplicates.""" flow = config_entries.HANDLERS["test"]() flow.hass = hass flow.context = {} MockConfigEntry(domain="test").add_to_hass(hass) result = await getattr(flow, f"async_step_{source}")({}) ...
18,989
def predicate_to_str(predicate: dict) -> str: """ 谓词转文本 :param predicate: 谓词数据 :return: 文本 """ result = "" if "block" in predicate: result += "检查方块\n\n" block = predicate["block"] if "nbt" in block: result += f"检查nbt:\n``` json\n{try_pretty_json_str(block[...
18,990
def _render_export(a): """Renders cpp stub from python code""" from liblolpig.export import scan_module_files from liblolpig import Renderer ctx = scan_module_files(a.input_filenames) r = Renderer(ctx) r.namespaces = a.namespaces r.is_gccxml = a.is_gccxml r.write_to_file(a.output_cpp, r...
18,991
def module_str_to_class(module_str): """Parse module class string to a class Args: module_str(str) Dictionary from parsed configuration file Returns: type: class """ if not validate_module_str(module_str): raise ValueError("Module string is in wrong format") module...
18,992
async def get_postcode(postcode_like: PostCodeLike) -> Optional[Postcode]: """ Gets the postcode object for a given postcode string. Acts as a middleware between us and the API, caching results. :param postcode_like: The either a string postcode or PostCode object. :return: The PostCode object else ...
18,993
def registerlib(path): """ Add KiKit's footprint library into the global footprint library table. If the library has already been registered, update the path. """ if path is None: path = getFpLibTablePath() with open(path, "r") as f: fpLibTable = parseSexprF(f) rest = f.r...
18,994
def oauth2callback(): """ The 'flow' has this one place to call back to. We'll enter here more than once as steps in the flow are completed, and need to keep track of how far we've gotten. The first time we'll do the first step, the second time we'll skip the first step and do the second, and so on. """ ...
18,995
def gen_cards(deck, bottom_up=True): """ Empties the deck! """ func = deck.pop if bottom_up else deck.popleft while True: try: yield func() except IndexError: return
18,996
def get_ebv(path, specs=range(10)): """Lookup the EBV value for all targets from the CFRAME fibermap. Return the median of all non-zero values. """ ebvs = [] for (CFRAME,), camera, spec in iterspecs(path, 'cframe', specs=specs, cameras='b'): ebvs.append(CFRAME['FIBERMAP'].read(columns=['EBV'...
18,997
def is_prime(i): """ """
18,998
def get_results_df( job_list: List[str], output_dir: str, input_dir: str = None, ) -> pd.DataFrame: """Get raw results in DataFrame.""" if input_dir is None: input_dir = os.path.join(SLURM_DIR, 'inputs') input_files = [ os.path.join(input_dir, f'{name}.json') for name i...
18,999