content
stringlengths
22
815k
id
int64
0
4.91M
def db_listen(q): """ Open a db connection and add notifications to *q*. """ cnn = psycopg2.connect(dsn) cnn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT) cur = cnn.cursor() cur.execute("LISTEN \"SIMPLE_NOTIFY_CHANNEL\";") while 1: trampoline(cnn, read=True) cnn.poll() ...
1,900
def detail_url(reteta_id): """"Return reteta detail URL""" return reverse('reteta:reteta-detail', args=[reteta_id])
1,901
def load_metadata_txt(file_path): """ Load distortion coefficients from a text file. Parameters ---------- file_path : str Path to a file. Returns ------- tuple of floats and list Tuple of (xcenter, ycenter, list_fact). """ if ("\\" in file_path): raise ...
1,902
def _output_gradient(f, loss_function, dataset, labels, out0, batch_indices, chunk): """ internal function """ x = _getitems(dataset, batch_indices) y = _getitems(labels, batch_indices) if out0 is not None: out0 = out0[batch_indices] out = [] grad = 0 loss_value = 0 for...
1,903
def test75(): """ Check that a None in a list raises a gripe """ assert isinstance(p, Pod) copy: Pod = p.dup() copy.spec.containers.append(None) try: o = copy.object_at_path(["spec", "containers", 2]) assert False, "should have gotten a RuntimeError" except RuntimeError: ...
1,904
def test_xml_xhtml(): """XHTML responses are handled by the XML formatter.""" file = XML_FILES_PATH / 'xhtml' / 'xhtml_raw.xml' xml_data = file.read_text(encoding=UTF8) # Python < 3.8 was sorting attributes (https://bugs.python.org/issue34160) # so we have 2 different output expected given the Pyth...
1,905
def ensure_hash_valid(h): """This does not guarantee only hashes get through, it's best-effort.""" passes = True if not isinstance(h, str): passes = False elif [x for x in h if x not in '0123456789abcdef-u']: passes = False if not passes: raise ValueError('Invalid hash: %s' % repr(h))
1,906
def __material_desc_dict(m, d): """ Unpack positions 18-34 into material specific dict. """ return dict(zip(MD_FIELDS[m], {"BK": __material_bk, "CF": __material_cf, "MP": __material_mp, "MU": __material_mu, "CR": __material_cr, "VM": __material_vm, ...
1,907
def test_get_valid_filter(mockclient_cl1): """Each comliance level has a set of allowed filters. Test 's' which is not allowed with cl0 but ok for cl1 """ r = mockclient_cl1.get(TEST_URL + "?p=1") assert r.status_code == 200
1,908
def writePendingTaskToDatabase(task): """pendingTransfers tracks files prepped for transfer, by dataset: { "dataset": { "files": { "filename1___extension": { "name": "filename1", "md": {}, "md_name": "name_of_metadat...
1,909
def toint(x): """Try to convert x to an integer number without raising an exception.""" try: return int(x) except: return x
1,910
def obtain_time_image(x, y, centroid_x, centroid_y, psi, time_gradient, time_intercept): """Create a pulse time image for a toymodel shower. Assumes the time development occurs only along the longitudinal (major) axis of the shower, and scales linearly with distance along the axis. Parameters -----...
1,911
def remove_comment(to_remove, infile): """Removes trailing block comments from the end of a string. Parameters: to_remove: The string to remove the comment from. infile: The file being read from. Returns: The paramter string with the block comment removed (if comment was ...
1,912
def generate_notification_header(obj): """ Generates notification header information based upon the object -- this is used to preface the notification's context. Could possibly be used for "Favorites" descriptions as well. :param obj: The top-level object instantiated class. :type obj: class w...
1,913
def promptyn(msg, default=None): """ Display a blocking prompt until the user confirms """ while True: yes = "Y" if default else "y" if default or default is None: no = "n" else: no = "N" confirm = raw_input("%s [%s/%s]" % (msg, yes, no)) confirm =...
1,914
def FdGars_main(support: list, features: tf.SparseTensor, label: tf.Tensor, masks: list, args: argparse.ArgumentParser().parse_args()) -> None: """ Main function to train, val and test the model :param support: a list of the sparse adjacency matrices :par...
1,915
def plan_launch_spec(state): """ Read current job params, and prescribe the next training job to launch """ last_run_spec = state['run_spec'] last_warmup_rate = last_run_spec['warmup_learning_rate'] add_batch_norm = last_run_spec['add_batch_norm'] learning_rate = last_run_spec['learning_rate']...
1,916
def test_infinite_fifo_queue(): """ Validate basic properties and push/pop to the infinite FIFO queue. """ queue: Queue[int] = InfiniteFifoQueue() assert queue.capacity == np.inf assert queue.size == 0 assert queue.empty assert not queue.full # Add some elements: queue.push(1) ...
1,917
def ssgenTxOut0(): """ ssgenTxOut0 is the 0th position output in a valid SSGen tx used to test out the IsSSGen function """ # fmt: off return msgtx.TxOut( value=0x00000000, # 0 version=0x0000, pkScript=ByteArray( [ 0x6a, # OP...
1,918
def sexag_to_dec(sexag_unit): """ Converts Latitude and Longitude Coordinates from the Sexagesimal Notation to the Decimal/Degree Notation""" add_to_degree = (sexag_unit[1] + (sexag_unit[2]/60))/60 return sexag_unit[0]+add_to_degree
1,919
def is_immutable_type(value: Any) -> bool: """ Get a boolean value whether specified value is immutable type or not. Notes ----- apysc's value types, such as the `Int`, are checked as immutable since these js types are immutable. Parameters ---------- value : Any ...
1,920
def add_column_node_type(df: pd.DataFrame) -> pd.DataFrame: """Add column `node_type` indicating whether a post is a parent or a leaf node Args: df: The posts DataFrame with the columns `id_post` and `id_parent_post`. Returns: df: A copy of df, extended by `node_type`. """ if "node...
1,921
def compute_occurrences(ibs, config=None): """ Clusters ungrouped images into imagesets representing occurrences CommandLine: python -m ibeis.control.IBEISControl --test-compute_occurrences Example: >>> # ENABLE_DOCTEST >>> from ibeis.control.IBEISControl import * # NOQA ...
1,922
def read_motifs(fmotif): """ create a random pool of motifs to choose from for the monte-carlo simulations """ motif_pool = [] for line in open(fmotif): if not line.strip(): continue if line[0] == "#": continue motif, count = line.rstrip().split() motif_pool.extend(mo...
1,923
def createCone( axis=1, basePos=-1, tipPos=1, radius=1, colour=(0.6,0.6,0.6), moiScale = 1, withMesh = True, **kwargs ): """ Create a rigid body for a cone with the specified attributes (axis is 0:x, 1:y, 2:z). Other rigid body parameters can be specified with keyword arguments, look at App.Proxys.RigidBody...
1,924
def test_ap_wpa2_tdls(dev, apdev): """WPA2-PSK AP and two stations using TDLS""" hapd = start_ap_wpa2_psk(apdev[0]) wlantest_setup(hapd) connect_2sta_wpa2_psk(dev, hapd) setup_tdls(dev[0], dev[1], hapd) teardown_tdls(dev[0], dev[1], hapd) setup_tdls(dev[1], dev[0], hapd) #teardown_tdls(d...
1,925
async def test_setup_via_discovery_cannot_connect(hass): """Test setting up via discovery and we fail to connect to the discovered device.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) await hass.async_block_till_done() assert...
1,926
def test_ap_wpa2_ptk_rekey(dev, apdev): """WPA2-PSK AP and PTK rekey enforced by station""" ssid = "test-wpa2-psk" passphrase = 'qwertyuiop' params = hostapd.wpa2_params(ssid=ssid, passphrase=passphrase) hapd = hostapd.add_ap(apdev[0], params) dev[0].connect(ssid, psk=passphrase, wpa_ptk_rekey="...
1,927
def createInputFiles(): """Create input files from the command line: from stdin, from --inputfiles, and also create an empty scratch file Return them in a dictionary with standard names as keys: names = ("$file1", "$file2", etc. ) Also give them names name = <stdin>, filename from the command line, or "...
1,928
def ef(candles: np.ndarray, lp_per: int = 10, hp_per: int = 30, f_type: str = "Ehlers", normalize: bool = False, source_type: str = "close", sequential: bool = False) -> Union[ float, np.ndarray]: # added to definition : use_comp: bool = False, comp_intensity: float = 90.0, """ https://www.tradingview.com...
1,929
def stl_plot( ts: "TSDataset", period: int, segments: Optional[List[str]] = None, columns_num: int = 2, figsize: Tuple[int, int] = (10, 10), plot_kwargs: Optional[Dict[str, Any]] = None, stl_kwargs: Optional[Dict[str, Any]] = None, ): """Plot STL decomposition for segments. Paramete...
1,930
def parse_displays(config: Dict) -> Dict[str, QueryDisplay]: """Parse display options from configuration.""" display_configs = config.get("displays") if not display_configs: return {} displays = {} for name, display_config in display_configs.items(): displays[name] = QueryDisplay( ...
1,931
async def update_result(user: dict, form: dict) -> str: """Extract form data and update one result and corresponding start event.""" informasjon = await create_finish_time_events(user, "finish_bib", form) # type: ignore return informasjon
1,932
def rasterize_polygons_within_box( polygons: List[np.ndarray], box: np.ndarray, mask_size: int ) -> torch.Tensor: """ Rasterize the polygons into a mask image and crop the mask content in the given box. The cropped mask is resized to (mask_size, mask_size). This function is used when generating...
1,933
def has_ao_num(trexio_file) -> bool: """Check that ao_num variable exists in the TREXIO file. Parameter is a ~TREXIO File~ object that has been created by a call to ~open~ function. Returns: True if the variable exists, False otherwise Raises: - Exception from trexio.Error class if ...
1,934
def teapot(size=1.0): """ Z-axis aligned Utah teapot Parameters ---------- size : float Relative size of the teapot. """ vertices, indices = data.get("teapot.obj") xmin = vertices["position"][:,0].min() xmax = vertices["position"][:,0].max() ymin = vertices["position"]...
1,935
def f30(x, rotations=None, shifts=None, shuffles=None): """ Composition Function 10 (N=3) Args: x (array): Input vector of dimension 2, 10, 20, 30, 50 or 100. rotations (matrix): Optional rotation matrices (NxDxD). If None (default), the official matrices from the benchmark suit...
1,936
def loadNode( collada, node, localscope ): """Generic scene node loading from a xml `node` and a `collada` object. Knowing the supported nodes, create the appropiate class for the given node and return it. """ if node.tag == tag('node'): return Node.load(collada, node, localscope) elif node.ta...
1,937
def create_xla_tff_computation(xla_computation, type_spec): """Creates an XLA TFF computation. Args: xla_computation: An instance of `xla_client.XlaComputation`. type_spec: The TFF type of the computation to be constructed. Returns: An instance of `pb.Computation`. """ py_typecheck.check_type(xl...
1,938
def render_contact_form(context): """ Renders the contact form which must be in the template context. The most common use case for this template tag is to call it in the template rendered by :class:`~envelope.views.ContactView`. The template tag will then render a sub-template ``envelope/contact_fo...
1,939
def get_basic_project(reviews: int = 0) -> List[Dict]: """Get basic project config with reviews.""" reviews = max(reviews, MIN_REVIEW) reviews = min(reviews, MAX_REVIEW) middle_stages, entry_point = _get_middle_stages(reviews, OUTPUT_NAME) input_stage = { "brickName": "labelset-input", ...
1,940
def choose_quality(link, name=None, selected_link=None): """ choose quality for scraping Keyword Arguments: link -- Jenitem link with sublinks name -- Name to display in dialog (default None) """ import re if name is None: name = xbmc.getInfoLabel('listitem.label') if link.s...
1,941
def picp_loss(target, predictions, total = True): """ Calculate 1 - PICP (see eval_metrics.picp for more details) Parameters ---------- target : torch.Tensor The true values of the target variable predictions : list - predictions[0] = y_pred_upper, predicted upper limit of the t...
1,942
def find_files_to_upload(upload_dir): """ Find the files which are named correctly and have a .asc file """ files = [] for name in os.listdir(upload_dir): asc_file = os.path.join(upload_dir, "{}.asc".format(name)) if valid_format(name) and os.path.isfile(asc_file): files....
1,943
def index_wrap(data, index): """ Description: Select an index from an array data :param data: array data :param index: index (e.g. 1,2,3, account_data,..) :return: Data inside the position index """ return data[index]
1,944
def image_api_request(identifier, **kwargs): """ TODO: A IIIF Image API request; redirect to Wikimedia image URI """
1,945
def import_operand_definition( defdict, yaml, key, base_module, regs, force=False ): """ :param defdict: :param yaml: :param key: :param base_module: :param regs: """ try: entry = defdict[key] except KeyError: raise MicroprobeArchitectureDefinitionError( ...
1,946
def mzml_to_pandas_df(filename): """ Reads mzML file and returns a pandas.DataFrame. """ cols = ["retentionTime", "m/z array", "intensity array"] slices = [] file = mzml.MzML(filename) while True: try: data = file.next() data["retentionTime"] = data["scanList"...
1,947
def metadata_volumes(response: Response, request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST), sourcetype: str=Query(None, title=opasConfig.TITLE_SOURCETYPE, description=opasConfig.DESCRIPTION_PARAM_SOURCETYPE), ...
1,948
def do_step_right(pos: int, step: int, width: int) -> int: """Takes current position and do 3 steps to the right. Be aware of overflow as the board limit on the right is reached.""" new_pos = (pos + step) % width return new_pos
1,949
def unzipConfigFile(): """ Unzip configuration export using ARCHIVE_SECRET generated above. Parameters: None - Local directory is scanned to find downloaded configuration archive Returns: None - Files are unzipped in local directory to a "configfiles" directory """ with console.status(...
1,950
def _initialise_template(workspace: Workspace, path: Path, name: str, type: str = None, template: str = None): """Initialise the project directory.""" if template: workspace.templates.create( template, path=path, name=name ) else: if not type: raise WorkspaceC...
1,951
def log_agm(x, prec): """ Fixed-point computation of -log(x) = log(1/x), suitable for large precision. It is required that 0 < x < 1. The algorithm used is the Sasaki-Kanada formula -log(x) = pi/agm(theta2(x)^2,theta3(x)^2). [1] For faster convergence in the theta functions, x should b...
1,952
def score_model(model): """ Fits a model using the training set, predicts using the test set, and then calculates and reports goodness of fit metrics and alpha. """ model.fit(Xtrain, ytrain) yhat = model.predict(Xtest) r2 = r2_score(ytest, yhat) me = mse(ytest, yhat) ae = mae(ytest, ...
1,953
def addDataset( parent, dataset ): """ Convert HDF5 dataset into text :param parent: xml element corresponding to the dataset :param dataset: HDF5 dataset to be converted """ if str(dataset.dtype).startswith("|S"): parent.text = dataset[()].decode("utf8") else: parent.text ...
1,954
def simplify_name(name): """Converts the `name` to lower-case ASCII for fuzzy comparisons.""" return unicodedata.normalize('NFKD', name.lower()).encode('ascii', 'ignore')
1,955
async def parse_regex(opsdroid, skills, message): """Parse a message against all regex skills.""" matched_skills = [] for skill in skills: for matcher in skill.matchers: if "regex" in matcher: opts = matcher["regex"] matched_regex = await match_regex(messa...
1,956
def interpolate_minusones(y): """ Replace -1 in the array by the interpolation between their neighbor non zeros points y is a [t] x [n] array """ x = np.arange(y.shape[0]) ynew = np.zeros(y.shape) for ni in range(y.shape[1]): idx = np.where(y[:,ni] != -1)[0] if len(idx)>1: ...
1,957
def write_read(writer, reader, input_mesh, atol): """Write and read a file, and make sure the data is the same as before. """ with tempfile.TemporaryDirectory() as temp_dir: filepath = os.path.join(temp_dir, "test.dat") writer(filepath, input_mesh) mesh = reader(filepath) # Make...
1,958
def logged_batches(specs: Iterable[ht.JobSpec], limit: int) -> Iterable[Iterable[ht.JobSpec]]: """Accepts an iterable of specs and a 'chunk limit'; returns an iterable of iterable of JobSpec, each of which is guaranteed to contain at most 'chunk limit' items. The subsequences don't pull cont...
1,959
def precision(y, yhat, positive=True): """Returns the precision (higher is better). :param y: true function values :param yhat: predicted function values :param positive: the positive label :returns: number of true positive predictions / number of positive predictions """ table = continge...
1,960
def add_posibility_for_red_cross(svg): """add a symbol which represents a red cross in a white circle Arguments: svg {Svg} -- root element """ symbol = Svg(etree.SubElement(svg.root, 'symbol', {'id': 'red_cross', ...
1,961
def main(): """ Main entry point for script. """ if len(argv) > 1 and argv[1].lstrip("-").startswith("c"): print(_get_script(), end="") return if not _is_clean(): print("Uncommitted changes in working directory. Stopping.") exit(1) if len(argv) > 1 and argv[1].l...
1,962
def circular_abstractions(graph, settings): """doc goes here""" for pattern, count in abstractions.circular_abstractions(graph, settings): print "<LIBRARY CIRCLE:> chain:", pattern, count
1,963
def exceptions2exit(exception_list): """ Decorator to convert given exceptions to exit messages This avoids displaying nasty stack traces to end-users :param exception_list: list of exceptions to convert """ def exceptions2exit_decorator(func): @functools.wraps(func) def func_w...
1,964
def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" ...
1,965
def dasopw(fname): """ Open a DAS file for writing. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasopw_c.html :param fname: Name of a DAS file to be opened. :type fname: str :return: Handle assigned to the opened DAS file. """ fname = stypes.stringToCharP(fname) ha...
1,966
def is_ncname(value): """ BNode identifiers must be valid NCNames. From the `W3C RDF Syntax doc <http://www.w3.org/TR/REC-rdf-syntax/#section-blank-nodeid-event>`_ "The value is a function of the value of the ``identifier`` accessor. The string value begins with "_:" and the entire value MUST matc...
1,967
def test_metric_type_completeness(): """ Test that the value map is complete above 243, our arbitrary cutoff from Apr. 14th. """ vals = metric_types_map.values() complete_min = 243 complete_max = max(vals) complete_range = range(complete_min, complete_max + 1) # All values in the compl...
1,968
def health_func() -> Dict[str, str]: """Give the user the API health.""" return "ok"
1,969
def queue_worker(decoy: Decoy) -> QueueWorker: """Get a mock QueueWorker.""" return decoy.mock(cls=QueueWorker)
1,970
def temp_hdf_handler(): """ Generate temporary empty hdf file and return its handler. Delete file after test is done. Returns ------- """ import tempfile import os import time path = tempfile.mkdtemp() fp = os.path.join(path,f'{time.time()}.hdf5') with Hdf5io(fp,lockfile_pat...
1,971
def imports_of_package( package, module_dotpath_filt=None, imported_module_dotpath_filt=None, depth=None ): """Generates (module_dotpath, imported_module_dotpaths) pairs from a package, recursively. :param package: Module, file, folder, or dotpath of package to root the generation from :param module_do...
1,972
def astra_fp_3d(volume, proj_geom): """ :param proj_geom: :param volume: :return:3D sinogram """ detector_size = volume.shape[1] slices_number = volume.shape[0] rec_size = detector_size vol_geom = build_volume_geometry_3d(rec_size, slices_number) sinogram_id = astra.data3d.crea...
1,973
def handle_article_file(file_path, storage_config): """ Processed a file by extracting a ticker(s) and then moving it to an appropriate dir """ base_name = os.path.basename(file_path) with open(file_path, 'rw') as f: j = json.loads(f.read()) if "an error has occured" in j['title'].lower(): ...
1,974
def get_wf_neb_from_images( parent, images, user_incar_settings, additional_spec=None, user_kpoints_settings=None, additional_cust_args=None, ): """ Get a CI-NEB workflow from given images. Workflow: NEB_1 -- NEB_2 - ... - NEB_n Args: parent (Structure): parent structure...
1,975
def categorize_folder_items(folder_items): """ Categorize submission items into three lists: CDM, PII, UNKNOWN :param folder_items: list of filenames in a submission folder (name of folder excluded) :return: a tuple with three separate lists - (cdm files, pii files, unknown files) """ found_cdm...
1,976
def _broadcast_all(indexArrays, cshape): """returns a list of views of 'indexArrays' broadcast to shape 'cshape'""" result = [] for i in indexArrays: if isinstance(i, NDArray) and i._strides is not None: result.append(_broadcast(i, cshape)) else: result.append(i) ...
1,977
def _none_tozero_array(inarray, refarray): """Repair an array which is None with one which is not by just buiding zeros Attributes inarray: numpy array refarray: numpy array """ if inarray is None: if _check_ifarrays([refarray]): inarray = np.zeros_like(refarray)...
1,978
def dpuGetExceptionMode(): """ Get the exception handling mode for runtime N2Cube Returns: Current exception handing mode for N2Cube APIs. Available values include: - N2CUBE_EXCEPTION_MODE_PRINT_AND_EXIT - N2CUBE_EXCEPTION_MODE_RET_ERR_CODE """ return pyc_l...
1,979
def clean_links(links, category): """ clean up query fields for display as category buttons to browse by :param links: list of query outputs :param category: category of search from route :return: list of cleansed links """ cleansedlinks = [] for item in links: # remove blanks ...
1,980
def doAllSol(inst,sol): """writes out a csv file for all attributes of a given instrument sol and insturment Returns: El,Stereo,SeqID,Sclk,Frame,Mission, Sol,RMC,OOV,Inst,LocType,DataProduct,QUAT, ObsType,Eas,Az,Elev,Method,Nor,Cpnt""" print "Entering doAllSol.BulkInstLoc.InstLocUber.py...
1,981
def set_log_level(log_level: str = "None") -> None: """Convenience function to set up logging. Args: log_level (str): Can be one of None, Critical, Error, Warn, Info, Debug. """ configure_logging(log_level)
1,982
def as_bool(value: Any, schema: Optional[BooleanType] = None) -> bool: """Parses value as boolean""" schema = schema or BooleanType() value = value.decode() if isinstance(value, bytes) else value if value: value = str(value).lower() value = BOOLEANS.get(value) validation.validate(sc...
1,983
def get_raw_feature( column: Text, value: slicer_lib.FeatureValueType, boundaries: Dict[Text, List[float]] ) -> Tuple[Text, slicer_lib.FeatureValueType]: """Get raw feature name and value. Args: column: Raw or transformed column name. value: Raw or transformed column value. boundaries: Dictiona...
1,984
def ndmi(nir: Union[xr.DataArray, np.ndarray, float, int], swir1: Union[xr.DataArray, np.ndarray, float, int]) -> \ Union[xr.DataArray, np.ndarray, float, int]: """ Normalized difference moisture index. Sentinel-2: B8A, B11 Parameters ---------- nir : xr.DataArray or np.ndarra...
1,985
def _log_failed_job(resource_group, job): """Logs information about failed job :param str resource_group: resource group name :param models.Job job: failed job. """ logger.warning('The job "%s" in resource group "%s" failed.', job.name, resource_group) info = job.execution_info # type: models....
1,986
def coerce_kw_type(kw, key, type_, flexi_bool=True): """If 'key' is present in dict 'kw', coerce its value to type 'type\_' if necessary. If 'flexi_bool' is True, the string '0' is considered false when coercing to boolean. """ if key in kw and type(kw[key]) is not type_ and kw[key] is not None: ...
1,987
def _collect_data_and_enum_definitions(parsed_models: dict) -> dict[str, dict]: """ Collect all data and enum definitions that are referenced as interface messages or as a nested type within an interface message. Args: parsed_models: A dict containing models parsed from an AaC yaml file. Retur...
1,988
def _list_goals(context, message): """Show all installed goals.""" context.log.error(message) # Execute as if the user had run "./pants goals". return Phase.execute(context, 'goals')
1,989
def values(df, varname): """Values and counts in index order. df: DataFrame varname: strign column name returns: Series that maps from value to frequency """ return df[varname].value_counts().sort_index()
1,990
def get_or_none(l, n): """Get value or return 'None'""" try: return l[n] except (TypeError, IndexError): return 'None'
1,991
def pfam_clan_to_pdb(clan): """get a list of associated PDB ids for given pfam clan access key. :param clan: pfam accession key of clan :type clan: str :return: List of associated PDB ids :rettype:list""" url='http://pfam.xfam.org/clan/'+clan+'/structures' pattern='/structure/[A-Z, 0-9]...
1,992
def fib(n): """Compute the nth Fibonacci number. >>> fib(8) 21 """ if n == 0: return 0 elif n == 1: return 1 else: return fib(n-2) + fib(n-1)
1,993
def go_prefix(prefix): """go_prefix sets the Go import name to be used for this workspace.""" _go_prefix_rule(name = "go_prefix", prefix = prefix, visibility = ["//visibility:public" ] )
1,994
def _is_cache_dir_appropriate(cache_dir, cache_file): """ Determine if a directory is acceptable for building. A directory is suitable if any of the following are true: - it doesn't exist - it is empty - it contains an existing build cache """ if os.path.exists(cache_dir): ...
1,995
def run_cmd(cmd, **kwargs): """Run a command using parameters kwargs.""" flags = [k for k, v in kwargs.items() if v is None] kwargs = {k: v for k, v in kwargs.items() if v is not None} run_cmd_str(dict_to_cmd(cmd, flags, **kwargs))
1,996
def executeCodeIn(code, namespace): """Execute the final translated Python code in the given namespace.""" exec(code, namespace)
1,997
def score_tours_absolute(problems: List[N_TSP], tours: List[Union[int, NDArray]]) -> NDArray: """Calculate tour lengths for a batch of tours. Args: problems (List[N_TSP]): list of TSPs tours (List[Union[int, NDArray]]): list of tours (in either index or segment format) Returns: NDA...
1,998
def has(pred: Pred, seq: Seq) -> bool: """ Return True if sequence has at least one item that satisfy the predicate. """ for x in seq: if pred(x): return True return False
1,999