content
stringlengths
22
815k
id
int64
0
4.91M
def get_key_list_images(path): """ Returns the list of the keys representing the images in the hdf/mrcs/st file. It will be converted in list of integer :param path: :return: """ print("Try to list images on", path) import os filename_ext = os.path.basename(path).split(".")[-1] resul...
5,289,400
def teardown() -> None: """ The function would be called when the test ended. """ for checkout_file_path in _CHECKOUT_FILE_PATHS: os.system(f'git checkout {checkout_file_path}')
5,289,401
def get_object_info(obj, cache=None): """ This function is intended to behave just like get_doc_info, only you call it with objects other than Couch docs (such as objects that use the Django ORM). """ class_name = obj.__class__.__name__ cache_key = '%s-%s' % (class_name, obj.pk) if cache...
5,289,402
def wave_bases(mother, k, scale, param=-1): """Computes the wavelet function as a function of Fourier frequency used for the CWT in Fourier space (Torrence and Compo, 1998) Arguments --------- mother: str equal to 'MORLET' or 'DOG' to choose the wavelet type k: vector of the Fourier...
5,289,403
def encrypt_binary(keyfile, read_file, write_file): """ファイルの暗号化処理""" # 鍵ファイルから公開鍵を読み込む public_key = read_key(keyfile) # 平文ファイルを読み込む f = open(read_file, "rb") plain_bytes = [] while True: d = f.read(16) if len(d) == 0: break plain_bytes.append(d) f.cl...
5,289,404
def load_strings(): """Inject 'strings' into the jinja2 environment so it is available everywhere """ with open(os.path.join(APP_ROOT_FOLDER, 'strings.json')) as fp: strings = json.load(fp) return dict(strings=strings)
5,289,405
def test_multiplex_fq_files_missing_sample_sheet_error(configuration): """ Test that specifying multiplexed sample files and a non-existent sample sheet gives the expected error code. :param configuration_module: temporary configuration and \ configuration file :type configuration_module: tuple...
5,289,406
def load_spec(filename): """Load a PIL style input specification.""" f = open(filename, "r") # Create new specification object ... spec = PIL_class.Spec() # ... and populate it with the contents of the file. for line in f: # Strip comments and whitespace line = re.sub(r"#.*\n", "", line) line...
5,289,407
def subgraph_from_edges(G, edge_list, ref_back=True): """ Creates a networkx graph that is a subgraph of G defined by the list of edges in edge_list. Requires G to be a networkx MultiGraph or MultiDiGraph edge_list is a list of edges in either (u,v) or (u,v,d) form where u and v are nodes compr...
5,289,408
def _nptype_to_taco_type(ty: np.dtype) -> DType: """Returns the TACO type for the given numpy type.""" nptype_to_dtype = { np.int8: Type.INT8, np.int16: Type.INT16, np.int32: Type.INT32, np.int64: Type.INT64, np.float32: Type.FLOAT32, np.float64: Type.FLOAT64 } return DType(n...
5,289,409
def search_images(request): """Function for Image searching/sourcing""" if 'image' in request.GET and request.GET['image']: search_term = request.GET.get('image') searched_images =Image.search_by_name(search_term) message = f'{search_term}' return render(request, 'search.html',...
5,289,410
def readRem(byteStream): """The rem - remark/comment type tokens""" commentLength = struct.unpack('bb', byteStream.read(2))[1] bytesRead = 2 comment = struct.unpack('%ds' % commentLength, byteStream.read(commentLength))[0].rstrip("\x00") bytesRead += commentLength return bytesRead, comment
5,289,411
def linKK(f, Z, c=0.85, max_M=50, fit_type="real", add_cap=False): """A method for implementing the Lin-KK test for validating linearity [1] Parameters ---------- f: np.ndarray measured frequencies Z: np.ndarray of complex numbers measured impedances c: np.float ...
5,289,412
def ERR_USERSDISABLED(sender, receipient, message): """ Error Code 446 """ return "ERROR from <" + sender + ">: " + message
5,289,413
def get_route_name(route): """Returns route name.""" # split once, take last peice name = route.split("/", 1)[-1] return name
5,289,414
def teardown(): """ Tearing down the environment """ global RBD_SECRET_OBJ, CEPHFS_SECRET_OBJ log.info("Deleting PVC") assert pvc.delete_pvcs(PVC_OBJS) log.info("Deleting CEPH BLOCK POOL") assert helpers.delete_cephblockpool() log.info("Deleting RBD Secret") RBD_SECRET_OBJ.delete...
5,289,415
def ifft_inplace(signal, scale = None): """ Inverse In-place Fast Fourier Transform: 1D Parameters ---------- signal: af.Array A 1 dimensional signal or a batch of 1 dimensional signals. scale: optional: scalar. default: None. - Specifies the scaling factor. - I...
5,289,416
def test_create_enrollments_blocked_country(user_client, user): """ Create enrollment view should redirect with a user message in a cookie if the attempted enrollment is blocked """ run = CourseRunFactory.create() BlockedCountryFactory.create(course=run.course, country=user.legal_address.country) ...
5,289,417
def get_response_ids_submitdates(resp_meta, debug=False): """ Return a dict mapping response ids to submitdates. response ids are of type int, submitdates of type str. :param resp_meta: dict mapping response ids to a dict with meta information, cf. :func:`ge...
5,289,418
def singlecore(known_face_encodings, names, face_query): """ single core is impl to compare faces on one core """ tolerance, similarity_metric = configs.face_similarity_threshold, configs.metric if similarity_metric == 'euclidean': name= singlecore_euclidean(known_face_encodings, names, face...
5,289,419
def _pickled_setitem_ ( self , key , value ) : """ Add object (pickle if needed) to dbase >>> db['A/B/C'] = obj """ ## if self.writeback: self.cache [ key ] = value ## not TObject? pickle it and convert to Ostap.BLOB if not isinstance ( value , ROOT.TObject ) : ## (1) pick...
5,289,420
def poisciPristanisce(pristanisce): """Vrne podatke o pristanišču na podlagi njegovega imena.""" cur.execute(""" SELECT id, pristanisce FROM Pristanisce WHERE pristanisce LIKE ?""", (pristanisce,)) return cur.fetchone()
5,289,421
def test_str_wrong_parameters(process_test_df): """Test that invalid argument for Pandas string method raises an error.""" with pytest.raises(TypeError): process_test_df.process_text( column_name="text", string_function="split", pattern="_" )
5,289,422
def launch(): """Launch the RAPyDo-based HTTP API server""" args = [ 'run', '--host', '0.0.0.0', '--port', os.environ.get(PORT), '--reload', '--no-debugger', '--eager-loading', '--with-threads' ] if starting_up(): log.exit("Please wait few...
5,289,423
def showfreq(signal,fs,fc=0,db=False): """ return f,fft """ if fc==0: kc = int(len(signal)/2) else: kc = int(len(signal)/fs*fc) signal_fft = np.abs(scipy.fftpack.fft(signal)) f = np.linspace(0,fs/2,num=int(len(signal_fft)/2)) out_f = f[:kc] out_fft = signal_fft[0:i...
5,289,424
def test_merge_conda_pip_include2(random_folder: Path) -> None: """ Tests the logic to exclude PIP include statements from Conda environments, on the root level environment file. """ if paths.is_himl_used_from_git_repo(): root_yaml = paths.git_repo_root_folder() / paths.ENVIRONMENT_YAML_FILE_NAM...
5,289,425
def make_input_split(filename, offset, length): """ Build a fake (i.e., not tied to a real file) :class:`~pydoop.pipes.InputSplit`\ . This is used for testing. :type filename: string :param filename: file name :type offset: int :param offset: byte offset of the split with respect to the beginning of ...
5,289,426
def get_info(devices: Sequence[custom_types.Device]) -> List[Dict[str, Any]]: """Returns persistent info and firmware version for each device.""" info = [] for device in devices: props = {} for device_prop in _DEVICE_PROPS: try: props[device_prop] = device.get_property(device_prop, raise_err...
5,289,427
def get_policy_profile_by_uuid(db_session, profile_id): """ Retrieve policy profile by its UUID. :param db_session: database session :param profile_id: string representing the UUID of the policy profile :returns: policy profile object """ with db_session.begin(subtransactions=True): ...
5,289,428
def recall_score(y_true: np.ndarray, y_pred: np.ndarray, *, labels: Optional[np.ndarray] = None, pos_label: Union[str, int] = 1, average: Optional[Literal['micro', 'macro', 'samples', 'weighted', 'binary']] = 'binary', sample_...
5,289,429
def evaluateIndcostt(individual, verbose=False): """ This function should take an individual,possibly an instance of Candidate class, and return a tuple where each element of the tuple is an objective. An example objective would be (error,circuitLen) where: error = |1 - < createdState | wantedStat...
5,289,430
def test_run_linked_script(): """Test running a code snippet calling other ones""" ...
5,289,431
def weibull_cdf(): """ Generates a figure and table for the Weibull CDF data in the paper. """ exact = 2.4, 1.6, 0.8 t = np.array([ 1.202, 1.397, 1.537, 1.57, 1.768, 1.856, 1.87, 1.889, 1.918, 2.098, 2.212, 2.349, 2.453, 2.557, 2.596, 2.602, 2.678, 2.706, 3.089, 3.441 ]) F =...
5,289,432
def test_config_view_show_remote(svc_client_with_repo, it_remote_repo_url): """Check config show view.""" svc_client, headers, project_id, _ = svc_client_with_repo params = dict(git_url=it_remote_repo_url) response = svc_client.get("/config.show", query_string=params, headers=headers) assert {"re...
5,289,433
def runFunction(func, pargs=None, kwargs=None, msg=DEFAULT_MSG): """ Runs the function, catching errors, and writing a message. :param Function func: :param list pargs: postional arguments :param dict kwargs: keyword arguments """ if pargs is None: pargs = [] if kwargs is None: kwargs = {}...
5,289,434
def random_simplicial_complex(level=1, p=0.5): """ Return a random simplicial complex. :param level: measure of complexity: the larger this is, the more vertices and therefore the larger the possible dimension of the complex. :type level: positive integer; optional, default 1 :param p: ...
5,289,435
def from_url(url, **kwargs): """ Returns an active Redis client generated from the given database URL. Will attempt to extract the database id from the path url fragment, if none is provided. """ from aioredis.client import Redis return Redis.from_url(url, **kwargs)
5,289,436
def rollback_loaded_discussions( request_client: RequestClient, response_dict: Dict[str, List[Dict]] ): """ Delete already loaded discussions via the Schoology API. **** Used during testing of the load functionality **** Parameters ---------- request_client : RequestClient A Request...
5,289,437
def get_remote_version(url: str) -> str: """Gets the remote file and returns it as a long string.""" response = requests.get(url) if response: #print("Getting remote version") s = response.text return s else: return "Url Not Found."
5,289,438
def mesh_renderer(vertices, triangles, normals, diffuse_colors, camera_position, camera_lookat, camera_up, light_positions, light_intensities, image_width, ...
5,289,439
def _is_optional(anno: Any) -> bool: """Is the supplied annotation an instance of the 'virtual' Optional type? Optional isn't really a type. It's an alias to Union[T, NoneType] """ return ( is_union(anno) and NoneType in anno.__args__ )
5,289,440
def single_number_hashtable(nums: list[int]) -> int: """Returns the only element in `nums` that appears exactly once Complexity: n = len(nums) Time: O(n) Space: O(n) Args: nums: array of integers s.t. every element appears twice, except for one Returns: the only elemen...
5,289,441
def mse_from_logits_bm(output_logits, target_logits): """Computes MSE between predictions associated with logits. Args: output_logits: A tensor of logits from the primary model. target_logits: A tensor of logits from the secondary model. Returns: The mean MSE """ alphas = t...
5,289,442
def test_glue_bokeh_no_display(mock_ipython): """Test gluing a Bokeh figure without displaying it. The main difference from a displayed figure is the mime_prefix in the metadata. """ p = figure() p.circle(range(1, 10), range(1, 10)) myst_nb_bokeh.glue_bokeh("a", p) obtained = mock_ipython.p...
5,289,443
def get_data(input_path): """ Reading passage retrieval results into a dataframe. Parameters ---------- input_path : str Path to file containing passage retrieval results. Returns ------- data : DataFrame DataFrame containing passage retrieval results. ...
5,289,444
def metadata(datasets): """ Extract datasette metadata from a CLDF dataset. """ def iter_table_config(cldf): for table in cldf.tables: try: name = cldf.get_tabletype(table) except (KeyError, ValueError): name = None name = name ...
5,289,445
def display_player_stats(player: dict) -> None: """Display the player statistics in order given. Key/Value pairs.""" for stat in player: print(f'{stat.capitalize()}:\t{player[stat]}')
5,289,446
def chunk_bboxes(shape, chunks, overlap): """Calculates the bounding box coordinates for each overlapped chunk Parameters ---------- shape : tuple overall shape chunks : tuple tuple containing the shape of each chunk overlap : int int indicating number of voxels to overl...
5,289,447
def DCT1e(x): """ This can act as a forward or backward transform. We use it simply as a transform. This is a very similar definition to wikipedia but with scaling 2. https://www.researchgate.net/publication/3343693_Convolution_Using_Discrete_Sine_and_Cosine_Transforms DCT1 of the input signal x...
5,289,448
def get_igrf(lons,lats,alts,ephtimes): """ Highly visible getter method for acquiring Earth's magnetic field values for the provided ndarray of longitudes/latitudes/altitudes/times. Uses the IGRF model """ from davitpy.models import igrf from davitpy import utils itype = 1 #Geodetic co...
5,289,449
def draw_border (im, v=max_image_value, width=2): """ Draw a border around an image. Arguments: im image to which the border is to be added (modified) v value to which the border is to be set (default: 255) width width of the border in pixels (default: 2) """ ny, nx, nc = size...
5,289,450
def test_make_classification_informative_features(setup): """Test the construction of informative features in make_classification Also tests `n_clusters_per_class`, `n_classes`, `hypercube` and fully-specified `weights`. """ # Create very separate clusters; check that vertices are unique and # ...
5,289,451
def dcg_score_at_k(ground_truth, predictions, k=5, pos_label=1): """ Function to evaluate the Discounted Cumulative Gain @ k for a given ground truth vector and a list of predictions (between 0 and 1). Args: ground_truth : np.array consisting of multi-hot encoding of label ...
5,289,452
def write_reg_grid(time,lon,lat,u,v,atts,ofn): """ Write GNOME compatible netCDF file (netCDF3) from regular grid data subset(time,lon,lat,u,v,atts,dfn) Arguments: *time*: 1-D time vector *lon* : 1-D in decimal degrees -180:180 *lat* : 1-D in decimal degrees -90:90...
5,289,453
def index(): """Show all the posts, most recent first.""" posts = HubPost.query\ .join(HubPost.post_content)\ .join(HubPost.effectivity)\ .join(HubPost.author)\ .filter(text("sat_post_effectivity.post_status = 'Active'")) return render_template("blog/index.html", posts=posts)
5,289,454
def which_executable(environment_variable, executable_name): """ Determine the path of an executable. An environment variable can be used to override the location instead of relying on searching the PATH. :param str environment_variable: The name of the environment variable :param str executab...
5,289,455
def parse_card(card: str) -> tuple: """Separates the card into value and suit. Args: card (str): String representing a poker card, in the format ValueSuit, like '9D' (9 of Diamonds). Returns: tuple: Returns a tuple of the card, like (Value, Suit). Ex: '9D' -> ('9', 'D'). """ if le...
5,289,456
def parseargs(): """ Parse the command line arguments :return: An args map with the parsed arguments """ parser = argparse.ArgumentParser(description="Download all image cube files for a given sky location") parser.add_argument("opal_username", help="Your user name on the...
5,289,457
def reduce_mem_usage( df: pd.DataFrame, ) -> pd.DataFrame: """Function to automatically check if columns of a pandas DataFrame can be reduced to a smaller data type. Source: https://www.mikulskibartosz.name/how-to-reduce-memory-usage-in-pandas/ :param df: DataFrame to reduce memory usage on :ty...
5,289,458
def DEFINE_constant_string(name, default, help): """A helper for defining constant strings.""" CONFIG.AddOption(type_info.String(name=name, default=default or "", description=help), constant=True)
5,289,459
def plot_po(one_survey): """Plot a diagram of PO (Porakonekairaus) with matplotlib. Parameters ---------- one_survey : hole object Returns ------- figure : matplotlib figure """ df = pd.DataFrame(one_survey.survey.data) if "Soil type" in df.columns: # pylint: disable=unsupport...
5,289,460
def check_cycles(skel_img, label="default"): """ Check for cycles in a skeleton image Inputs: skel_img = Skeletonized image label = optional label parameter, modifies the variable name of observations recorded Returns: cycle_img = Image with cycles identified :param skel_img:...
5,289,461
def test_no_inverse(): """CTD:affects_activity_of has an exact map and no inverse. It shouldn't crash.""" expected = {"CTD:affects_activity_of": {"identifier": "biolink:affects_activity_of", "label": "affects activity of", "inverted": False}} param = {'version': '2.2.3'} ...
5,289,462
def http_get_with_headers(url, h=False): """ executes regular HTTP GET request to url returns response body and headers """ global hd if h: hd = h resp = requests.get(url, headers=hd, allow_redirects=False) return (resp.content, resp.headers)
5,289,463
def analysis_create(): """ Renders analysis creation page """ return flask.render_template('analysis_creation.tpl')
5,289,464
def create_test_engine(): """ Returns an SQLAlchemy Engine, configured for testing. :return: an SQLAlchemy Engine, configured for testing. """ engine = use_database_file(":memory:") return engine
5,289,465
def _reformat_policy(policy): """ Policies returned from boto3 are massive, ugly, and difficult to read. This method flattens and reformats the policy. :param policy: Result from invoking describe_load_balancer_policies(...) :return: Returns a tuple containing policy_name and the reformatted policy...
5,289,466
def test_parent_skip_branch(session, dag_maker): """ A simple DAG with a BranchPythonOperator that does not follow op2. NotPreviouslySkippedDep is not met. """ start_date = pendulum.datetime(2020, 1, 1) with dag_maker( "test_parent_skip_branch_dag", schedule_interval=None, st...
5,289,467
def get_log_lvl(lvl): """ get logging level via string """ lvl = lvl.lower() if lvl == 'debug': return logging.DEBUG if lvl == 'info': return logging.INFO if lvl == 'warn': return logging.WARN if lvl == 'error': return logging.ERROR
5,289,468
def get_line(file_path, line_rule): """ 搜索指定文件的指定行到指定行的内容 :param file_path: 指定文件 :param line_rule: 指定行规则 :return: """ s_line = int(line_rule.split(',')[0]) e_line = int(line_rule.split(',')[1]) result = [] # with open(file_path) as file: file = codecs.open(file_path, "r", e...
5,289,469
def strip_all_unbalanced_parens(s): """ Return a string where unbalanced parenthesis are replaced with a space. Strips (), <>, [] and {}. """ c = strip_unbalanced_parens(s, '()') c = strip_unbalanced_parens(c, '<>') c = strip_unbalanced_parens(c, '[]') c = strip_unbalanced_parens(c, '{}'...
5,289,470
def test_module(client: Client, first_fetch_time: Optional[int]) -> str: """ Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. :type client: ``Client`` :param client: Darktrace Client :type first_fetch_time: ``Optional[int]`...
5,289,471
def import_odk(datafile, flavour="odk-tt036", extradata=None, usercsv=None, mapping=make_mapping()): """Import ODK data. Arguments datafile A filepath to the JSON exported from ODK Aggregate flavour The ODK form with version flavour A st...
5,289,472
def collect_localdisk(approot, destroot): """Get host local disk information.""" src = '%s/localdisk_svc' % approot dest = '%s%s' % (destroot, src) try: shutil.copytree(src, dest) except (shutil.Error, OSError): _LOGGER.exception('fail to copy %s => %s', src, dest) # FIXME vgdi...
5,289,473
def plot_metrics(losses, accs, path, model, dataset, num_classes): """Plot and Save Figure on Loss and Accuracy""" (train_losses, val_losses) = losses (train_top1_acc, train_top5_acc, val_top1_acc, val_top5_acc) = accs # Plot on Loss # plt.figure(1) plt.plot(train_losses, label='Train Loss', al...
5,289,474
def get_data_streams(stream_list): """ Auxiliary function to translate a list of identifier strings specified in LoggerStream.available into the corresponding DataStream classes to be used in the file logger. Args: stream_list: List of strings indicating the requested DataStreams for the file l...
5,289,475
def create_species(category_id, name): """ Create a new species for a specified category :param category_id: Category ID :param name: Species name :returns: An instance of the Species class for the created record :raises ValueError: If the species is a duplicate or has an invalid name """ ...
5,289,476
def wait_for_new_checkpoint(checkpoint_dir, last_checkpoint=None, seconds_to_sleep=1, timeout=None): """Waits until a new checkpoint file is found. Args: checkpoint_dir: The directory in which checkpoints are saved. last_ch...
5,289,477
def checksum1(data, stringlength): """ Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1 ...
5,289,478
def padding_function(context, length, chars=None): """ The str:padding function creates a padding string of a certain length. The second argument gives a string to be used to create the padding. This string is repeated as many times as is necessary to create a string of the length specified by the ...
5,289,479
def existence_validator(path): """Validate whether the `path` exists. Args: path (str): path to be checked. Raises: FileNotFoundError: if `path` does not exist. """ abspath = os.path.abspath(path) if not os.path.exists(abspath): msg = f"No such file or directory: {abspa...
5,289,480
def tycho_fits_to_healpix(): """Convert files in $TYCHO_DIR/fits to files in $TYCHO_DIR/healpix. Returns ------- Nothing But the archived Tycho FITS files in $TYCHO_DIR/fits are rearranged by HEALPixel in the directory $TYCHO_DIR/healpix. The HEALPixel sense is nested with nside...
5,289,481
def add_gc_siepic(circuit, gc=siepic.GratingCoupler): """Add input and output gratings. Args: circuit: needs to have `o1` and `o2` pins. gc: grating coupler. """ gci = gco = gc gci["n1"].connect(gco["n1"]) gci["n2"].rename("o1") gco["n1"].rename("o2") return gci.circuit...
5,289,482
def allZero(buffer): """ Tries to determine if a buffer is empty. @type buffer: str @param buffer: Buffer to test if it is empty. @rtype: bool @return: C{True} if the given buffer is empty, i.e. full of zeros, C{False} if it doesn't. """ allZero = True for byte ...
5,289,483
def _recursive_walk(path): """ Perform os.walk() on a given path and construct the full path for each recursively found file and directory. :param path: Path of the directory to walk through :return: Tuple of all recursively found file names and directory names :rtype: tuple """ f, d = ...
5,289,484
def trim_session(pvs): """Remove duplicate page views (matching title and project). For a given session, this retains only the first view of a given page title on a given project. Parameters: pvs: list of page view objects for a given reader's session Returns: Nothing. The page views ar...
5,289,485
def s_and(a: Floatable, b: Floatable) -> float: """ Lukasiewicz's «strong and» operator. This operator (&&) is defined by: a && b := max {0, a + b - 1} Args: a (LogicValue) b (LogicValue) Returns: LogicValue: a && b """ a = float(a) b = float(b) return max(0, a...
5,289,486
def downgrade(): """Downgrade database.""" ctx = op.get_context() insp = Inspector.from_engine(ctx.connection.engine) op.drop_table('oauthclient_remotetoken') for fk in insp.get_foreign_keys('oauthclient_useridentity'): if fk['referred_table'] == 'accounts_user': op.drop_constr...
5,289,487
def setup_08_import_septa_data(): """ Import SEPTA's regional rail, 15-minute bus network, and heavy/light rail stations and merge them all into one layer named 'pois_for_septa_tod_analysis' """ db = pg_db_connection() data_folder = GDRIVE_DATA / "inputs/SEPTA request" # Import shapefiles ...
5,289,488
def convert_table(text): """ Convert a table in text from rst to markdown.""" lines = text.split("\n") new_lines = [] for line in lines: if _re_ignore_line_table.search(line) is not None: continue if _re_ignore_line_table1.search(line) is not None: continue ...
5,289,489
def negotiate_version(version, supported_versions=None): """ >>> negotiate_version(Version('0.9.0')) Version('1.0.0') >>> negotiate_version(Version('2.0.0')) Version('1.3.0') >>> negotiate_version(Version('1.1.1')) Version('1.1.1') >>> negotiate_version(Version('1.1.0')) Version('1.1...
5,289,490
def map_from_arrays(col1, col2): """Creates a new map from two arrays. :param col1: name of column containing a set of keys. All elements should not be null :param col2: name of column containing a set of values :rtype: Column >>> from pysparkling import Context, Row >>> from pysparkling.sql.s...
5,289,491
def injection_distutils(folder: str) -> dict: """This is a bit of "dark magic", please don't do it at home. It is injecting code in the distutils.core.setup and replacing the setup function by the inner function __fake_distutils_setup. This method is a contextmanager, after leaving the context it will r...
5,289,492
def user_loader(session_token): """Populate user object, check expiry""" if "expires" not in session: return None expires = datetime.utcfromtimestamp(session['expires']) expires_seconds = (expires - datetime.utcnow()).total_seconds() if expires_seconds < 0: return None user = U...
5,289,493
async def complete_conversations(request: HistoryQuery = HistoryQuery(), collection: str = Depends(Authentication.authenticate_and_get_collection)): """Fetches the number of successful conversations of the bot, which had no fallback.""" conversation_count, message = HistoryProce...
5,289,494
def get_all_labels(): """ Returns, List of labels that are in the complete state """ dbs = get_dbs(os.getcwd()) all_labels = list() for db in dbs: all_labels.extend(db.query(resultsdb.models.TuningRun.name) .filter_by(state='COMPLETE') .distinct() ...
5,289,495
def update_loss_accuracy_display_dash(value): """ Function that just calls the update_loss_accuracy_display function. This function is decorated by the Dash Application decorator. Such an arrangement is used as unit testing decorated functions is complex. """ display_loss, display_acc = updat...
5,289,496
def acad_to_academy(text): """ A function to change `Acad` to `Academy`. Smartly. Tries to ignore instances of `Acad` followed by `emy` or `emies`. Usage: from core.utils import acad_to_academy replace_str = 'Harmony Science Acad (Waco)' print acad_to_academy(replace_str) # 'Harmony S...
5,289,497
def load_database(path): """Return database metadata object for the database stored in ``path``. This is the default way of loading a database for read-only purposes in estimagic. Args: path (str or pathlib.Path): location of the database file. If the file does not exist, it will be cr...
5,289,498
def test_nofc(): """Test loading and parsing invalid json file: no forecast data.""" file = open('tests/json/buienradar_nofc.json', 'r') data = file.read() file.close() result = parse_data(data, None, usexml=False) # test calling results in the loop close cleanly print(result) assert (...
5,289,499