content
stringlengths
22
815k
id
int64
0
4.91M
def hdfs_open(server, username, path, **args): """Read a file. Returns a filelike object (specifically, an httplib response object). """ datanode_url = datanode_url(server, username, path, **args) response = _datanode_request(server, username, 'GET', datanode_url) if response.status == httplib...
30,300
def get_serv_loader(desc_file=SERVICES_FILE): """Get a ServiceLoader with service descriptions in the given file. Uses a "singleton" when the file is `SERVICES_FILE`. """ global _serv_loader if desc_file == SERVICES_FILE: if _serv_loader is None: with open(desc_file, "r") as fp:...
30,301
def check_reverse_lookup(): """ Check if host fqdn resolves to current host ip """ try: host_name = socket.gethostname().lower() host_ip = socket.gethostbyname(host_name) host_fqdn = socket.getfqdn().lower() fqdn_ip = socket.gethostbyname(host_fqdn) return host_ip == fqdn_ip except socket....
30,302
def render_pages(site_data: SiteData) -> dict[Path, str]: """Create page content.""" homepage = (site_data.homepage, rendering.render_homepage(site_data)) record_pages = [ (page, rendering.render_record_page(site_data, uri)) for uri, page in site_data.record_pages.items() ] toc_pages...
30,303
def download_file(clean_url, download_folder, downloaded_file_name, depth=0, error_output=True): """ Downloads a specific file. :param clean_url: Decoded URL to the file. :param download_folder: Folder to place the downloaded file in. :param downloaded_file_name: File name to save the download to. ...
30,304
def compact_map_save(hpmap, outname, exclude=lambda x:x>0): """ Save maps in a pixel, signal format Parameters ---------- hpmap: healpix map Healpix map outname: str Output name exclude: function Function to mask pixels to be excluded, must have hpmap as argument ...
30,305
def _clean_bar_plot_data(df_in: pd.DataFrame, sweep_vars: Sequence[Text] = None) -> pd.DataFrame: """Clean the summary data for bar plot comparison of agents.""" df = df_in.copy() df['env'] = pd.Categorical( df.bsuite_env, categories=_ORDERED_EXPERIMENTS, ordered=True) df['type'] ...
30,306
def reset_db(ml_dag_repository: MLDagRepository) -> None: """ Resets DB before each test to initial testing state """ ml_dag_repository.metadata.drop_all() ml_dag_repository.metadata.create_all()
30,307
def file_resources(): """File Resources.""" return { 'mock_file': CustomFileResource(service=FileService()), 'mock_file_action': CustomFileActionResource(service=FileService()), }
30,308
def p_node_test(p): """NodeTest : NameTest | NODETYPE '(' ')' | NODETYPE '(' Literal ')' """ if len(p) == 2: p[0] = p[1] elif len(p) == 4: p[0] = ast.NodeType(p[1]) else: p[0] = ast.NodeType(p[1], p[3])
30,309
def test_get_resampled_multiscene( sMf, tmp_path, fake_multiscene_empty, fake_multiscene2): """Test getting a resampled multiscene from files.""" from sattools.scutil import get_resampled_multiscene sMf.return_value = fake_multiscene_empty def load(ds_all, unload=None): for (sc, ref_sc)...
30,310
def prepare_data(features=None): """Prepare data for analysis Args: features (list of str): list with features Returns: X_train (np.matrix): train X X_test (np.matrix): test X y_train (np.matrix): train y y_test (np.matrix): test y """ # Read data xls =...
30,311
def choose_my_art_date(my_location, google_maps_key, mapping = False, search_range = 500, min_rating = 4.3): """ Function to select an artsy date and dinner; randomly selects local arts event from NY ArtBeat API found at https://www.nyartbeat.com/resources/doc/api, and uses the arts event data to determine...
30,312
def flatten_repo_tree(d, parent_key=''): """Flatten a dict to so that keys become nodes in a path.""" items = [] for k, v in d.items(): new_key = os.path.join(parent_key, k) try: repo = Repo(**v) except (ValidationError, TypeError): repo = None if re...
30,313
def hash_text(message: str, hash_alg: str = 'keccak256') -> str: """get the hash of text data :param message: str :param hash_alg: str, `keccak256` or `sha256`, the default value is `keccak256` :return: hex str, digest message with `keccak256` or `sha256` """ if hash_alg == 'keccak256': ...
30,314
def get_grains_connected_to_face(mesh, face_set, node_id_grain_lut): """ This function find the grain connected to the face set given as argument. Three nodes on a grain boundary can all be intersected by one grain in which case the grain face is on the boundary or by two grains. It is therefore su...
30,315
def get_git_projects(git_worktree, args, default_all=False, use_build_deps=False, groups=None): """ Get a list of git projects to use """ git_parser = GitProjectParser(git_worktree) groups = vars(args).get("groups") if groups: use_bu...
30,316
def RmZ( ps: Table, r_band: Literal["9601", "9602"] = "9602", z_band: Literal["9801", "9901"] = "9901", **kw ) -> units.mag: """R-Z color. Parameters ---------- ps : astropy.table.Table need arguments for r(z)_band functions r_band: {'9601', '9602'} R band to use ...
30,317
def get_table_names(connection: psycop.extensions.connection) -> List[str]: """ Report the name of the tables. E.g., tables=['entities', 'events', 'stories', 'taxonomy'] """ query = """ SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' ...
30,318
def mrpxmrp(sigmaset1, sigmaset2): """in work; returns transformation [FN] = [FB(s2)][BN(s1)] """ q1 = np.array(sigmaset1) q2 = np.array(sigmaset2) sig1_norm = norm(sigmaset1) sig2_norm = norm(sigmaset2) scalar1 = 1 - sig1_norm**2 scalar2 = 1 - sig2_norm**2 scalar3 = 2. denom = 1...
30,319
def continuous_partition_data(data, bins='auto', n_bins=10): """Convenience method for building a partition object on continuous data Args: data (list-like): The data from which to construct the estimate. bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-space...
30,320
def create_pulsed_programming_accuracy_plot_2(pulsed_programmings, directory_name): """ This function creates a plot showing the impact of the tolerance on the accuracy of the pulsed programming. Parameters ---------- pulsed_programmings : list of list of PulsedProgramming.PulsedProgramming di...
30,321
def readInput(infile,genefile, segfile): """ Reads input files. Extended description of function. Parameters: infile (str): File containing list of genes to be analyzed genefile (str): File containing gene range definitions segfile (str): File containing cell line intervals and...
30,322
def list_rulesets(command): """ tests if the list rulesets command is running properly """ namespace = app.main(command) assert namespace.command == 'lr' or namespace.command == "listrulesets"
30,323
def library_name(name, suffix=SHLIB_SUFFIX, is_windows=is_windows): """ Convert a file basename `name` to a library name (no "lib" and ".so" etc.) >>> library_name("libpython3.7m.so") # doctest: +SKIP 'python3.7m' >>> library_name("libpython3.7m.so", suffix=".so", is_windows=False...
30,324
def main(): """Entry point.""" parser = argparse.ArgumentParser(description='People protected by coastal habitat analysis') parser.add_argument( '--population', type=str, required=True, help='path to the population raster') parser.add_argument( '--reefs', type=str, required=True,...
30,325
def gen_v2v_spmv_schedule(adj, spmv_pairs, nft, eft, eid, out): """Generate v2v spmv schedule. Parameters ---------- adj : tuple (sparse matrix, utils.Index) spmv_pairs : list of pair nft : var.Var input node features eft : var.Var input edge features eid : var.Var ...
30,326
def grid_search_dict(org_params: Dict[str, Any]) -> Iterator[Tuple[str, Dict[str, Any]]]: """ Iterate list in dict to do grid search. Examples -------- >>> test_dict = dict(a=[1,2], b = [1,2,3], c = 4) >>> list(grid_search_dict(test_dict)) [('a:1-b:1', {'c': 4, 'a': 1, 'b': 1}), ('a:1-b...
30,327
def add_light(light_type: str = 'POINT') -> str: """ Add a light of the given type to the scene, return the name key of the newly added light :param light_type: :return: The named key used to index the object """ if utils.is_new_api(): bpy.ops.object.light_add(type=light_type) el...
30,328
def test_twosinesum(): """checks that the S function is commensurate with direct calculation for t = 1, n = 2, T = 2pi""" apt = abs(S(1, 2, 2 * pi) - (4 / pi) * (sin(1) + sin(3) / 3)) < 1E-3 msg = "Sums do not match." assert apt, msg
30,329
def set_constants(ze=40, p=0.4, kc_min=0.01, kc_max=1.0, snow_alpha=0.2, snow_beta=11.0, ke_max=1.0, a_min=0.45, a_max=0.90): """ :param ze: :param p: the fraction of TAW that a crop can extract from the root zone without suffering wat...
30,330
def project_poses(poses, P): """Compute projected poses x = Pp.""" assert poses.ndim == 2 and poses.shape[-1] == 3, \ 'Invalid pose dim at ext_proj {}'.format(poses.shape) assert P.shape == (3, 4), 'Invalid projection shape {}'.format(P.shape) p = np.concatenate([poses, np.ones((len(poses)...
30,331
def print_latest_failures(server, job_names): """Get a list of all tests that failed on the most recent build of the given jobs.""" build_urls = {} test_failures = {} for job_name in job_names: job = server.get_job(job_name) for build in recent_builds(job, num=1): build_urls...
30,332
def argmin(x): """ Returns the index of the smallest element of the iterable `x`. If two or more elements equal the minimum value, the index of the first such element is returned. >>> argmin([1, 3, 2, 0]) 3 >>> argmin(abs(x) for x in range(-3, 4)) 3 """ argmin_ = None min_...
30,333
def detect_scenes(files: Collection[str], pipeline: PipelineContext, progress=ProgressMonitor.NULL): """Detect scenes for the given files.""" files = tuple(files) remaining_video_paths = tuple(missing_scenes(files, pipeline)) # Ensure dependencies are satisfied if not frame_features_exist(remainin...
30,334
def find_spot(entry, list): """ return index of entry in list """ for s, spot in enumerate(list): if entry==spot: return s else: raise ValueError("could not find entry: "+ str(entry)+ " in list: "+ str(list))
30,335
def add_texts_lower_right(image: numpy.array, texts: List[str]): """add texts into lower right corner of cv2 object Args: image (numpy.array): cv2 image object texts (List[str]): texts """ W, H = image.shape[1], image.shape[0] str_len = max([len(text) for text in texts]) pos = (W - (18 ...
30,336
def parse_file(path, game=None, path_relative_to_game=True, verbose=False): """ Parse a single file and return a Tree. path, game: If game is None, path is a full path and the game is determined from that. Or game can be supplied, in which case path is a path relative to the game directory....
30,337
def test_reactivate_unituser_as_unitadmin(module_client): """Reactivate unituser as Unit Admin""" # Try to get token as user that is to be deactivated response = module_client.get( tests.DDSEndpoint.ENCRYPTED_TOKEN, auth=tests.UserAuth(tests.USER_CREDENTIALS[unituser["username"]]).as_tuple()...
30,338
def test_DateEncoder(): """Tests encoding.DateEncoder""" # Dummy data df = pd.DataFrame() df['a'] = ['1999/09', '2001/01', '2040/12', '1987/05'] df['y'] = np.random.randn(4) # Transform date_cols = { 'a': ('%Y/%m', ['year', 'month']) } de = DateEncoder(date_cols) dfo = ...
30,339
def svn_repos_fs_commit_txn(*args): """svn_repos_fs_commit_txn(svn_repos_t * repos, svn_fs_txn_t * txn, apr_pool_t pool) -> svn_error_t""" return _repos.svn_repos_fs_commit_txn(*args)
30,340
async def run_command( cmd: list, cwd: str = None, log_path=None, environ=None) -> str: """ Run a command. If 'log_path' is provided, stdout and stderr will be written to this location regardless of the end result. :raises subprocess.CalledProcessError: If the command returned an error ...
30,341
def iter_dir(temp_dir, blast_db, query_name, iteration): """ Get the work directory for the current iteration. We need to call this function in child processes so it cannot be in an object. """ name = '{}_{}_{:02d}'.format( basename(blast_db), basename(query_name), iteration) retur...
30,342
def assert_allclose( actual: numpy.ndarray, desired: numpy.ndarray, atol: float, err_msg: Literal["OneClassSVM"], ): """ usage.sklearn: 1 """ ...
30,343
def zoomSurface(src, zoomx, zoomy, smooth): """Zooms a surface with different x & y scaling factors. This function renders to a new surface, with optional anti-aliasing. If a zoom factor is negative, the image will be flipped along that axis. If the surface is not 8-bit or 32-bit RGBA/ABGR, it will be ...
30,344
def array(*cols: Column) -> Column: """ Return column of arrays """ return (struct(*cols).apply(list)).alias(f"[{', '.join([Column.getName(c) for c in cols])}]")
30,345
def addtodo(request): """ :param request: HttpRequest object :return: None. Redirects to Webpage. if pk is not available defaults to id=0. """ pk = request.POST.get("id_todo", 0) if pk: todoobj = Todo.objects.get(pk=pk) newtodoform = NewTodoForm(request.POST, instance=todoob...
30,346
def prepare_inputs(boxes, digits_occurrence): """ :param boxes: 2D list of 81 gray OpenCV images (2D numpy arrays) :param digits_occurrence: 2D numpy array that contains True or False values that represent occurrence of digits :return: if no digit was found returns None; otherwise returns 4D numpy array wit...
30,347
def evaluate_constants(const_arrays, expr): # pragma: no cover """Convert constant arguments to cupy arrays, and perform any possible constant contractions. """ return expr(*[to_cupy(x) for x in const_arrays], backend='cupy', evaluate_constants=True)
30,348
def setup_family(dompc, family, create_liege=True, create_vassals=True, character=None, srank=None, region=None, liege=None, num_vassals=2): """ Creates a ruler object and either retrieves a house organization or creates it. Then we also create similar ruler objec...
30,349
def info_cmd(ctx): """ Display information in the blockchain. """ pass
30,350
async def async_setup_platform(hass, config, async_add_entites, discovery_info=None): """Set up Buspro switch devices.""" # noinspection PyUnresolvedReferences from pybuspro.devices import Switch hdl = hass.data[DATA_BUSPRO].hdl devices = [] for address, device_config in config[CONF_DEVICES].i...
30,351
def normalize_line(line: dict, lang: str): """Apply normalization to a line of OCR. The normalization rules that are applied depend on the language in which the text is written. This normalization is necessary because Olive, unlike e.g. Mets, does not encode explicitly the presence/absence of whitespac...
30,352
def dump(self, option): """Dump information. Parameters ---------- Returns ------- """ pass return
30,353
def new(template,directory,url_template): """ Generates the necessary files for a new PreTeXt project. Supports `pretext new book` (default) and `pretext new article`, or generating from URL with `pretext new --url-template [URL]`. """ directory_fullpath = os.path.abspath(directory) if utils...
30,354
def attribute_summary(attribute_value, item_type, limit=None): """Summarizes the information in fields attributes where content is written as an array of arrays like tag_cloud, items, etc. """ if attribute_value is None: return None items = ["%s (%s)" % (item, instances) for ...
30,355
def create_rgb_vrt(outname, infiles, overviews, overview_resampling): """ Creation of the color composite VRT file. Parameters ---------- outname: str Full path to the output VRT file. infiles: list[str] A list of paths pointing to the linear scaled measurement backscatter files...
30,356
def add_profile(db, profile, xon, xoff, size, dynamic_th, pool): """Add or modify a buffer profile""" config_db = db.cfgdb ctx = click.get_current_context() profile_entry = config_db.get_entry('BUFFER_PROFILE', profile) if profile_entry: ctx.fail("Profile {} already exist".format(profile)) ...
30,357
def markdown_inside_fence(contents, fence="yaml"): """ This generator iterates through the entire `contents` of a Markdown file line-by-line. It yields each line along with its index that is only within a YAML block. It ignores lines that are not part of YAML block. # Parameters contents:...
30,358
def generate_groups(message: message.Message, fields: Iterable[str], max_repeated_group: int, **kwargs) -> Iterator[str]: """Yields possible group keys given the message and field. This function will generate group keys based on the fields provided in `fields`. Each field in `fields` may be r...
30,359
def test_bfs_returns_false(): """Test that the breadth first search method returns false.""" from CTCI_4_1 import is_route_bfs graph = {'a': ['b', 'c'], 'b': ['c'], 'c': ['a', 'b'], 'd': ['a']} node1 = 'a' node2 = 'd' assert is_route_bfs(graph, node1, nod...
30,360
def root(): """Base view.""" new_list = json.dumps(str(utc_value)) return new_list
30,361
def plc_read_db(plc_client, db_no, entry_offset, entry_len): """ Read specified amount of bytes at offset from a DB on a PLC """ try: db_var = plc_client.db_read(db_no, entry_offset, entry_len) except Exception as err: print "[-] DB read error:", err sys.exit(1) db_val =...
30,362
def test_cli_parse_args_empty(mocker, change_curdir_fixtures): """When no arg is given we should find the closest tackle file.""" mock = mocker.patch("tackle.main.update_source", autospec=True, return_value={}) main([]) assert mock.called assert isinstance(mock.call_args[0][0], Context) context...
30,363
def reload_subs(verbose=True): """ Reloads ibeis and submodules """ import_subs() rrr(verbose=verbose) getattr(constants, 'rrr', lambda verbose: None)(verbose=verbose) getattr(main_module, 'rrr', lambda verbose: None)(verbose=verbose) getattr(params, 'rrr', lambda verbose: None)(verbose=verbose)...
30,364
def validate_overlap_for(doc, doctype, fieldname, value=None): """Checks overlap for specified field. :param fieldname: Checks Overlap for this field """ existing = get_overlap_for(doc, doctype, fieldname, value) if existing: frappe.throw(_("This {0} conflicts with {1} for {2} {3}").format(doc.doctype, existin...
30,365
def __fail(copied_files): """ Prints a fail message and calls cleanup. :param copied_files: :return: """ print('An error has occurred.') print('Cleaning up copied files...') __cleanup(copied_files)
30,366
def getPath(path=__file__): """ Get standard path from path. It supports ~ as home directory. :param path: it can be to a folder or file. Default is __file__ or module's path. If file exists it selects its folder. :return: dirname (path to a folder) .. note:: It is the same as os.p...
30,367
def rank_adjust(t, c=None): """ Currently limited to only Mean Order Number Room to expand to: Modal Order Number, and Median Order Number Uses mean order statistic to conduct rank adjustment For further reading see: http://reliawiki.org/index.php/Parameter_Estimation Above reference...
30,368
def print_AF(newAttacksFrom, fileformat): """ Invoked when the user uses stdout as a wanted output. This method prints the AF resulting from the reductions asked on the terminal. dict*str --> None """ assert type(newAttacksFrom) is dict, "The first argument ofthis method must be a dictionar...
30,369
def login_captcha(username, password, sid): """ bilibili login with captcha. depend on captcha recognize service, please do not use this as first choice. Args: username: plain text username for bilibili. password: plain text password for bilibili. sid: session id Returns: ...
30,370
def ml_transitions(game, attach=True, verbose=False): """ dataframe to directional line movement arrays """ transition_classes = [] prev = [None, None] for i, row in game.iterrows(): cur = list(row[["a_ml", "h_ml"]]) transition_class = analyze.classify_transition(prev, cur) ...
30,371
def initialize_leftcorners(grammar, trace=None): """ Calculate the left-corner tables from the grammar. The tables are stored in grammar['leftcorner'] and grammar['lcword']. It requires that grammar['topdown'], grammar['sequences'] and grammar['emptycats'] are already calculated. """ ...
30,372
def plugin_uninstall(plugin, flags=None, kvflags=None): """ Uninstall a Helm plugin. Return True if succeed, else the error message. plugin (string) The plugin to uninstall. flags (list) Flags in argument of the command without values. ex: ['help', '--help'] kvflags (d...
30,373
def test_consistency_GPUA_parallel(): """ Verify that the random numbers generated by GPUA_mrg_uniform, in parallel, are the same as the reference (Java) implementation by L'Ecuyer et al. """ from theano.sandbox.gpuarray.tests.test_basic_ops import \ mode_with_gpu as mode from thean...
30,374
def geom_to_tuple(geom): """ Takes a lat/long point (or geom) from KCMO style csvs. Returns (lat, long) tuple """ geom = geom[6:] geom = geom.replace(" ", ", ") return eval(geom)
30,375
def b_s_Poole(s, V_max, z, halo_type, bias_type): """ This function expresses Equation (2) of Poole et al (2014) and fetches the parameters needed to compute it. Args: s (numpy.ndarray) : scale values V_max (float) : halo maximum circular velocity z (float) : redshift of in...
30,376
def find_places_location(): """Finds the location of the largest places.sqlite file""" location = "" filesize = 0 for user in listdir('/Users'): profile_dir = '/Users/' + user + '/Library/Application Support/Firefox/Profiles/' if path.exists(profile_dir): for profile in listdir(profile_dir): places_locat...
30,377
def argumentParser(listOfArguments): """Parses arguments""" argumentParserFilter = {} for argument in listOfArguments: if argument in sys.argv: argumentParserFilter[listOfArguments[argument]] = True else: argumentParserFilter[listOfArguments[argument]] = False r...
30,378
def _install_one( repo_url, branch, destination, commit='', patches=None, exclude_modules=None, include_modules=None, base=False, work_directory='' ): """ Install a third party odoo add-on :param string repo_url: url of the repo that contains the patch. :param string branch: name of the branch to c...
30,379
def test_create_board_for_other_organization(api_client_factory, board_data): """Recourse that is out of control (i.e. organization) should not be found and raised exception 400.""" api_client = api_client_factory() response = api_client.post(reverse("api:board-list"), board_data) assert ( res...
30,380
def rasterize_polygon(poly_as_array, shape, geo_ref): """ Return a boolean numpy mask with 1 for cells within polygon. Args: poly_as_array: A polygon as returned by ogrpoly2array (list of numpy arrays / rings) shape: Shape (nrows, ncols) of output array geo_ref: GDAL style georeference ...
30,381
def _model_columns(ins): """ Get columns info :type ins: sqlalchemy.orm.mapper.Mapper :rtype: list[SaColumnDoc] """ columns = [] for c in ins.column_attrs: # Skip protected if c.key.startswith('_'): continue # Type column_type = c.columns[0].type # ...
30,382
def get_reg_part(reg_doc): """ Depending on source, the CFR part number exists in different places. Fetch it, wherever it is. """ potential_parts = [] potential_parts.extend( # FR notice node.attrib['PART'] for node in reg_doc.xpath('//REGTEXT')) potential_parts.extend( ...
30,383
def load(vocab_name, corpus_reader, sconn): """ Given a solr connection, load terms from a Getty vocab """ idx = 0 bulk_size = 1000 docs = [] for term in corpus_reader.terms(): idx += 1 term_text = term.findtext('Term_Text'), docs.appe...
30,384
def lazy_validate(request_body_schema, resource_to_validate): """A non-decorator way to validate a request, to be used inline. :param request_body_schema: a schema to validate the resource reference :param resource_to_validate: dictionary to validate :raises keystone.exception.ValidationError: if `reso...
30,385
def load_configuration(module: str, configs_path=None) -> dict: """ Load the configuration and return the dict of the configuration loaded :param module: The module name to load the configuration. :type module: str :param configs_path: path where to check configs. Default `configs/modules/` :ty...
30,386
def startup(update: Update) -> None: """Send a message when the bot is started to the users listed in the user_ids.""" query = 'whoami' response = ps_command(query)[0].split('\n')[0] response = f"{response} -> Online" for user in chat_ids: update.bot.sendMessage(text=response, chat_id=us...
30,387
def main(): """ Übergibt dem Controller die TermeApp Klasse. :rtype: object """ controller = control.TermeApp() """Start ist im StartScreen / Hauptmenue.""" controller.run()
30,388
async def process_resource_event( lifecycle: lifecycles.LifeCycleFn, registry: registries.OperatorRegistry, memories: containers.ResourceMemories, resource: resources.Resource, event: bodies.Event, replenished: asyncio.Event, event_queue: posting.K8sEventQueue, ) ...
30,389
def load_sprites(obj_list:list, paths:list): """Load the sprites for each of the items in parallel""" #Run functions concurrently for i, obj in enumerate(obj_list): #Add image sprites to each class concurrently asyncio.run(add_to_sprite(obj, paths[i]))
30,390
def loadFileOBJ(model, fileName): """Loads an obj file with associated mtl file to produce Buffer object as part of a Shape. Arguments: *model* Model object to add to. *fileName* Path and name of obj file relative to top directory. """ model.coordinateSystem = "Y-up" model.parent = None ...
30,391
def direct(input_writer, script_str, run_dir, prog, geo, charge, mult, method, basis, **kwargs): """ Generates an input file for an electronic structure job and runs it directly. :param input_writer: elstruct writer module function for desired job :type input_writer: elstruct fun...
30,392
def get_ids(records, key): """Utility method to extract list of Ids from Bulk API insert/query result. Args: records (:obj:`list`): List of records from a Bulk API insert or SOQL query. key (:obj:`str`): Key to extract - 'Id' for queries or 'id' for inserted data. Returns: (:obj:`l...
30,393
def read(*parts): """ Build an absolute path from *parts* and return the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), "rb", "utf-8") as f: return f.read()
30,394
def auto_help(func): """Automatically registers a help command for this group.""" if not isinstance(func, commands.Group): raise TypeError('Auto help can only be applied to groups.') cmd = commands.Command(_call_help, name='help', hidden=True) func.add_command(cmd) return func
30,395
def unique_justseen(iterable, key=None): """ List unique elements, preserving order. Remember only the element just seen. >>> [x for x in unique_justseen('AAAABBBCCDAABBB')] ['A', 'B', 'C', 'D', 'A', 'B'] >>> [x for x in unique_justseen('ABBCcAD', str.lower)] ['A', 'B', 'C', 'A', 'D'] """ ...
30,396
def unique_rows(arr, thresh=0.0, metric='euclidean'): """Returns subset of rows that are unique, in terms of Euclidean distance http://stackoverflow.com/questions/16970982/find-unique-rows-in-numpy-array """ distances = squareform(pdist(arr, metric=metric)) idxset = {tuple(np.nonzero(v)[0]) for v in...
30,397
def backdoors_listing(request,option=None): """ Generate the Backdoor listing page. :param request: Django request. :type request: :class:`django.http.HttpRequest` :param option: Action to take. :type option: str of either 'jtlist', 'jtdelete', 'csv', or 'inline'. :returns: :class:`django.h...
30,398
def writeConfigs(pathfile: str, options: dict[str, dict[str, object]]) -> ConfigParser: """ docstring """ config = ConfigParser() # config.read(pathfile) for section in options: if not config.has_section(section): config.add_section(section) for option, value in opt...
30,399