content
stringlengths
22
815k
id
int64
0
4.91M
def run_otter(unparsed_args=None): """ Runs Otter's CLI by parsing the arguments in ``unparsed_args`` if provided or ``sys.argv`` if not Args: unparsed_args (``list[str]``, optional): unparsed arguments for running Otter; if not provided, ``sys.argv`` is used """ args = PARSER.p...
39,500
def batch_get_all_movies(): """Attempt to get all movies downloaded and serialized. Pickup where the last attempt left off.""" goal = len(movie_id_df.movie_id) pickup = check_row_files() for i in range(5000, goal, 5000): print(f"Batch serializing the next 5000 movies (to {i}).") batc...
39,501
def dataset_from_datasource(dsdict, *, datasource_name, dataset_name=None, **dsrc_args): """Transformer: Create a Dataset from a DataSource object This is just a thin wrapper around Dataset.from_datasource in order to conform to the transformer API Parameters ---------- dsdict: dict, ignored. ...
39,502
def annotate_note(annotator_host, note_json, output, tool_type): """Annotate a note with specified annotator""" with open(note_json, "r") as note_f: notes = json.load(note_f) all_annotations = [] for note in notes: note_name = note.pop("note_name") annotations = client.annotate_n...
39,503
def representative_sample(X, num_samples, save=False): """Sample vectors in X, prefering edge cases and vectors farthest from other vectors in sample set """ X = X.values if hasattr(X, 'values') else np.array(X) N, M = X.shape rownums = np.arange(N) np.random.shuffle(rownums) idx = AnnoyI...
39,504
def _heal(batch): """Heal whisper files. This method will backfill data present in files in the staging dir if not present in the local files for points between 'start' and 'stop' (unix timestamps). """ for metric in batch.metrics_fs: src = os.path.join(batch.staging_dir, metric) ...
39,505
def fix_saving_name(name): """Neutralizes backslashes in Arch-Vile frame names""" return name.rstrip('\0').replace('\\', '`')
39,506
def read_dataset_genomes(dataset): """Read genomes of the given dataset. Args: dataset: instance of datasets.GenomesDataset Returns: list of genome.Genome """ genomes = [] if dataset.is_multi_chr(): # The genomes in this dataset have more than one chromosome. l...
39,507
def train_with_msm( model: NeuroSignalEncoder, config: dict, train_loader: DataLoader, val_loader: Optional[DataLoader] = None): """ Trains the model with masked sequence modeling. 1. Generate a random mask for each sequence. 2. Train the model on the masked sequence. 3. Repeat. ...
39,508
def _parse_sum_ouput(exit_code): """Parse the SUM output log file. This method parses through the SUM log file in the default location to return the SUM update status. Sample return string: "Summary: The installation of the component failed. Status of updated components: Total: 5 Success: 4 F...
39,509
def compute_metrics(logits, labels, lengths): """Computes metrics and returns them.""" loss = cross_entropy_loss(logits, labels, lengths) # Computes sequence accuracy, which is the same as the accuracy during # inference, since teacher forcing is irrelevant when all output are correct. token_accuracy = jnp.ar...
39,510
def replace_prelu(input_graph_def: util.GraphDef) -> util.GraphDef: """ Replace all Prelu-activations in the graph with supported TF-operations. Args: input_graph_def: TF graph definition to examine Returns: Updated copy of the input graph with Prelu-nodes replaced by supported...
39,511
def test_suite(): """ Create a test suite for each test case in LogisticRegressionClassifierModelTest """ testCases = [ binary_classification_integer_target, binary_classification_string_target, multiclass_integer_target, ] # multiclass_string_target] for t in testCa...
39,512
def setup_wallet_passphrase(): """ Setup wallet passphrase (encrypted). """ if node_config['no-validator']: log(f"{Typgpy.WARNING}Node config specify no validator automation, skipping wallet setup...{Typgpy.ENDC}") return passphrase = get_wallet_passphrase() log(f"{Typgpy.HEADER}...
39,513
def tf_parse_filename_classes(filename, normalization='None', normalization_factor=1, augmentation=False): """Take batch of filenames and create point cloud and label""" idx_lookup = {'airplane': 0, 'bathtub': 1, 'bed': 2, 'bench': 3, 'bookshelf': 4, 'bottle': 5, 'bowl': 6, 'car': 7, 'chair':...
39,514
def test_dh24(): """Test that DH24 is handled properly.""" msg = ".A YCPC1 210726 PD DH240000 /PCIRRZZ 6.89" res = process_message_a(msg, utc(2021, 9, 20, 1, 1)) assert res[0].valid == utc(2021, 7, 27, 7)
39,515
def test_get_url(test_dict: FullTestDict): """ - GIVEN a list of words - WHEN a url is generated - THEN check the url is encoded """ word_list = convert_list_of_str_to_kaki(test_dict['input']) sections = test_dict['tangorin']['expected_sections'] for word in word_list: assert ta...
39,516
def next_traj_points(dimension: int, last_point): """ :param dimension: dimension of our fake latent trajectory :param last_point: the last point that was sent to the client as a numpy array :return: here we are sending 3 points at a time from a noisy Lorenz system """ #Euler step size step...
39,517
def has_internet(): """ Test if Internet is available. Failure of connecting to the site "http://www.sagemath.org" within a second is regarded as internet being not available. EXAMPLES:: sage: from sage.doctest.external import has_internet sage: has_internet() # random Tru...
39,518
def read_warfle_text(path: str) -> str: """Returns text from *.warfle files""" try: with open(path, "r") as text: return text.read() except Exception as e: raise Exception(e)
39,519
def test_deployment_defaults_with_schedule(mock_time): """Should get defaults for deployment of type git-quay""" # Given: Deployment dictionary deployment = _create_test_deployment({ 'schedule': '*:0/15', 'proxy': { 'hosts': { 'host1': { 'loca...
39,520
def from_mido(midi: MidiFile, duplicate_note_mode: str = "fifo") -> Music: """Return a mido MidiFile object as a Music object. Parameters ---------- midi : :class:`mido.MidiFile` Mido MidiFile object to convert. duplicate_note_mode : {'fifo', 'lifo', 'all'}, default: 'fifo' Policy f...
39,521
def iterable_validator(iterable_type, member_type): # type: (ISINSTANCE, ISINSTANCE) -> Callable[[object, Attribute, Iterable[Any]], None] """``attrs`` validator to perform deep type checking of iterables.""" def _validate_iterable(instance, attribute, value): # type: (object, Attribute, Iterable[A...
39,522
def sample_filtering(df, metadata, filter_by): """Filter samples based on selected features and values.""" # Get the variable a values specified for sample filtering filter_col = filter_by[0] filter_values = filter_by[1].split(sep=',') # Saving a new metadata file containing only the samples remai...
39,523
def blog_post_historia(request, slug,template="blog/blog_post_historia.html"): """Display a list of contenidos that are filtered by slug, """ templates = [] #listamos todos los pacientes.. pacientes = BlogPost.objects.published(for_user=request.user) paciente = get_object_or_404(pacientes,...
39,524
def _validate_scheduler_step_freq(scheduler_step_freq): """This validation check only happens if a scheduler is passed in.""" if scheduler_step_freq not in VALID_SCHEDULER_STEP: raise ValueError("Scheduler step freq must be in {}. Got {}".format( VALID_SCHEDULER_STEP, scheduler_step_freq))
39,525
def user_is_registered_or_more(user_id): """Check that user is registered, moderator, or admin.""" user = Users.query.filter_by(UserID=user_id).first() user_map = UsersAccessMapping.query.filter_by(UserID=user_id).first() if user is None: return False if user_map is None: return Fals...
39,526
def test_has_object_write_permission_owner(api_rf, km_user_accessor_factory): """ The user who created the accessor should have write permissions on it. """ accessor = km_user_accessor_factory() api_rf.user = accessor.km_user.user request = api_rf.get(accessor.get_absolute_url()) assert...
39,527
def _AnnotateAndPrint(text, url): """Add buildbot trappings to print <a href='url'>text</a> in the waterfall. Args: text: Anchor text for the link url: the URL to which to link """ print >> sys.stderr, '\n@@@STEP_LINK@%(text)s@%(url)s@@@' % { 'text': text, ...
39,528
def avi_common_argument_spec(): """ Returns common arguments for all Avi modules :return: dict """ return dict( controller=dict(default=os.environ.get('AVI_CONTROLLER', '')), username=dict(default=os.environ.get('AVI_USERNAME', '')), password=dict(default=os.environ.get('AVI_...
39,529
def run( cmds: Union[str, Sequence[Union[str, Sequence[str]]]], shell: Optional[Union[str, bool]] = None, mode: Type[Mode] = str, block: bool = True, **kwargs ) -> Processes: """ Runs several commands that pipe to each other in a python-aware way. Args: cmds: Any number of comma...
39,530
def _infer_labels(center_e): """Create labels based on center extrema.""" # Infer labels if center_e == 'trough': labels = ['Trough', 'Peak', 'Inflection'] keys = ['sample_trough', 'sample_next_peak', 'sample_end'] elif center_e == 'peak': labels = ['Peak', 'Trough', 'Inflection...
39,531
def MXXXtoMYYY(redshift = 0.3, MXXX = 6E14, CXXX = 3.0, wrt = "crit", new_wrt = "crit", XXX = 500.0, YYY = 500.0, cosmo = cosmo): """ It converts the (MXXX,CXXX) in...
39,532
def gldas_to_cycles( latitude, longitude, output_file, start_date="2000-01-01", end_date="2017-12-31", gldas_path="/raw-data/GLDAS", ): """Transform GLDAS to Cycles.""" j = Job("gldas_to_cycles") j.addProfile(Profile(Namespace.CONDOR, key="+SingularityImage", value=html.unescape("&qu...
39,533
def max_pool_2x2(x): """max_pool_2x2 downsamples a feature map by 2X.""" return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
39,534
def get_largest_files_new(directory: str, num: int) -> list: """ Return a sorted list containing up to num of the largest files from the directory. Preconditions: - num > 0 """ # ACCUMULATOR: Priority queue so far list_so_far = [] for root in os.walk(directory): path = root[0...
39,535
def parse_trace_file(trace_filename, syscalls, arg_inspection): """Parses one file produced by strace.""" uses_socketcall = ('i386' in trace_filename or ('x86' in trace_filename and '64' not in trace_filename)) with open(trace_filename) as trace_file: ...
39,536
def synch_labels(ctx, repo): """Synch all the repos' labels using the specified repo as the source of truth.""" ghm = GitHubMux(ctx.obj['organization'], ctx.obj['token'], ctx.obj['exclude']) ghm.synch_from_repo(repo)
39,537
def set_bit_value(val, offs, value): """Set bit at offset 'offs' to a specific value in 'val'.""" if value: return set_bit(val, offs) else: return clear_bit(val, offs)
39,538
def gradientFunction(theta, X, y): """ Compute cost and gradient for logistic regression with regularization computes the cost of using theta as the parameter for regularized logistic regression and the gradient of the cost w.r.t. to the parameters. """ # Initialize some useful values # n...
39,539
def splice(tree, rep, tag): """Splice in a tree into another tree. Walk ``tree``, replacing the first occurrence of a ``Name(id=tag)`` with the tree ``rep``. This is convenient for first building a skeleton with a marker such as ``q[name["_here_"]]``, and then splicing in ``rep`` later. See ``fora...
39,540
def test_folder_create_command(requests_mock, mocker): """ Tests the box-create-folder function and command. Configures requests_mock instance to generate the appropriate folders API response, loaded from a local JSON file. Checks the output of the command function with the expected output. Ver...
39,541
def get_devp2p_cmd_id(msg: bytes) -> int: """Return the cmd_id for the given devp2p msg. The cmd_id, also known as the payload type, is always the first entry of the RLP, interpreted as an integer. """ return rlp.decode(msg[:1], sedes=rlp.sedes.big_endian_int)
39,542
def test_subsorts_parser(): """Ensure basic subsorts parsing works.""" query_params = { "album.tracks._sorts_": "track_id,-name" } parser = ModelQueryParamParser(query_params) result = parser.parse_subfilters() assert len(result["album.tracks"].sorts) == 2 assert result["album.tracks...
39,543
def custom_cached(name, *old_method, **options): """ decorator to convert a method or function into a lazy one. note that this cache type supports expire time and will consider method inputs in caching. the result will be calculated once and then it will be cached. each result will be cached using ...
39,544
def _full_url(url): """ Assemble the full url for a url. """ url = url.strip() for x in ['http', 'https']: if url.startswith('%s://' % x): return url return 'http://%s' % url
39,545
def connect(): """ Ensure the connectivity. This repeats tries to connect util successful :return: """ connected = False while not connected: try: # Connect the socket to the port where the server is listening logging.info('Connecting management app on {}:{}'.form...
39,546
def replay(mapper: Optional[Mapper] = None, buffer_size: Optional[int] = None, window: Optional[typing.RelativeTime] = None, scheduler: Optional[typing.Scheduler] = None ) -> Callable[[Observable], Union[Observable, ConnectableObservable]]: """The `replay` operator. ...
39,547
def translate_fsim_to_xy_cz(gate: FSim) -> Iterator[Union[XY, CZ]]: """Convert the Cirq's FSim gate to a canonical gate""" q0, q1 = gate.qubits theta, phi = gate.params yield XY(theta / var.PI, q0, q1) yield CZ(q0, q1) ** (-phi / var.PI)
39,548
def read_from_mc(path: str, flush=False) -> object: """ Overview: read file from memcache, file must be saved by `torch.save()` Arguments: - path (:obj:`str`): file path in local system Returns: - (:obj`data`): deserialized data """ global mclient _ensure_memcached() ...
39,549
def write_wav(file, samples, nframes=-1, nchannels=2, sampwidth=2, framerate=44100, bufsize=2048): """ Writes the samples to a wav file. :param file: can be a filename, or a file object. :param samples: the samples :param nframes: the number of frames :param nchannels: the number of channels ...
39,550
async def check_login(self) -> dict: """Check loging and return user credentials.""" session = await get_session(self.request) loggedin = UserAdapter().isloggedin(session) if not loggedin: informasjon = "Logg inn for å se denne siden" return web.HTTPSeeOther(location=f"/login?informasjon...
39,551
def node_running_pods_enricher(event: NodeEvent): """ Enrich the finding with pods running on this node, along with the 'Ready' status of each pod. """ node = event.get_node() if not node: logging.error( f"NodeRunningPodsEnricher was called on event without node: {event}" ...
39,552
def get_knn_func_data_points( data_points: np.ndarray, pairwise_distances: np.ndarray = None, approx_nn: ApproxNN = None, metric: Callable = fastdist.euclidean, metric_name: str = "euclidean", ) -> KnnFunc: """ Gets a K-nearest neighbour callable for data points, used in `compute_gad`. ...
39,553
def generate_examples(trajectories, trajectory_to_training_examples_fn): """Generates an infinite stream of shuffled examples out of trajectories.""" examples = [ example # pylint: disable=g-complex-comprehension for trajectory_examples in map( trajectory_to_training_examples_fn, trajectories...
39,554
def get_database_nodecount(): """Description pending""" from aiida import orm query = orm.QueryBuilder() query.append(orm.Node) return query.count()
39,555
def print_recent_upload_results(gazelle_site, recent_uploads, searchstr): """Prints any recent uploads. Currently hard limited to 5. Realistically we are probably only interested in 1. These results can't be used for group selection because the log doesn't give us a group id""" if recent_uploads: ...
39,556
def shower_profile(xdat, alpha, beta, x0): """Function that represents the shower profile. Takes in the event and predicts total gamma energy using alpha and beta to fit. Described in source in README. shower_optimize() fits for alpha and beta. """ #measured_energy = event.measured_energy #...
39,557
def has_prefix(s, sub_index): """ This function can make sure that the current string(recorded in index) is in the dictionary. (or it will return False and stop finding. :param s: string, the user input word :param sub_index: list, current list (recorded in the index type) :return: (bool) If the...
39,558
def get_experiment_tag(name): """Interfaces to callables that add a tag to the matplotlib axis. This is a light-weight approach to a watermarking of a plot in a way that is common in particle physics experiments and groups. `name` can be an identifier for one of the styles provided here. Alternativ...
39,559
def compare_bfs(benchmark_callable, G, nx_values, start_vertex, return_sp_counter=False): """ Genereate both cugraph and reference bfs traversal. """ if isinstance(start_vertex, int): result = benchmark_callable(cugraph.bfs_edges, G, start_vertex, ...
39,560
def _add_layer1(query, original_data): """Add data from successful layer1 MIB query to original data provided. Args: query: MIB query object original_data: Two keyed dict of data Returns: new_data: Aggregated data """ # Process query result = query.layer1() new_dat...
39,561
def encodeUcs2(text): """ UCS2 text encoding algorithm Encodes the specified text string into UCS2-encoded bytes. @param text: the text string to encode @return: A bytearray containing the string encoded in UCS2 encoding @rtype: bytearray """ result = bytearray() for b in ...
39,562
def listS3Buckets(): """ lists s3 bucket names """ s3 = getClient() response = s3.list_buckets() if response: for bucket in response.get('Buckets', []): yield bucket['Name']
39,563
def w_kvtype(stype: str, ctx: dict) -> dict: """ Make definition from ktype or vtype option """ stypes = {'Boolean': 'boolean', 'Integer': 'integer', 'Number': 'number', 'String': 'string'} if stype in stypes: return {'type': stypes[stype]} if stype[0] in (OPTION_ID['enum'], OPTION_ID['p...
39,564
def test_update__endtoend__5(address_book, UpdateablePersonFactory, browser): """The keywords field can be updated.""" UpdateablePersonFactory(address_book, keywords=[KEYWORD, u'second kw']) browser.login('mgr') browser.keyword_search('second kw', apply='Update') browser.getControl('field').displayV...
39,565
def create_article_number_sequence( shop_id: ShopID, prefix: str, *, value: Optional[int] = None ) -> ArticleNumberSequence: """Create an article number sequence.""" sequence = DbArticleNumberSequence(shop_id, prefix, value=value) db.session.add(sequence) try: db.session.commit() excep...
39,566
def test_list_blocks_extra_5c(): """ Test case 05c: A list item with three levels and lazy continuation lines """ # Arrange source_markdown = """1. abc 1. abc 1. abc def""" expected_tokens = [ "[olist(1,1):.:1:3:]", "[para(1,4):]", "[text(1,4):abc:]", "...
39,567
def queryMultifield(queryWords, listOfFields, pathOfFolder, fVocabulary): """ Multifield query: """ fileList = defaultdict(dict) df = {} for i in range(len(queryWords)): word, key = queryWords[i], listOfFields[i] returnedList, mid= findFileNumber(0, len(offset), offset, sys.a...
39,568
def csv_to_im( image_in, csv_path, labelkey='label', key='dapi', name='', maxlabel=0, normalize=False, scale_uint16=False, replace_nan=False, channel=-1, outpath='', ): """Write segment backprojection.""" if isinstance(image_in, Image): labels = image_in ...
39,569
def get_defaults(vtkName, debug=False): """Get default values for VTK Set methods Example: -------- >>> print(get_defaults("vtkSphere")) >>> # {'SetCenter': (0.0, 0.0, 0.0), 'SetRadius': 0.5} """ import types import vtk t = getattr(vtk, vtkName)() ignores = [ 'Se...
39,570
def transform_side(side,theta): """Transform the coordinates of the side onto the perpendicular plane using Euler-Rodrigues formula Input: side coordinates, plane Output: new coordinates """ new_side = list() #calculating axis of rotation axis = side[len(side)-1][0]-side[0][0],0,0 #converting theta to radians...
39,571
async def clear_cache_by_model(model_name: str, *args, **kwargs): """ Deletes cache from Redis based on model name @param model_name: a name of a model @param args: optional args passed @param kwargs: kwargs passed to filter Redis key we want to delete from cache """ keys = await redis_conne...
39,572
def go(): """Regenerate all use case examples and figures (simple and advanced)""" for fname in glob.glob(os.path.dirname(__file__)+"/source/*.*"): os.remove(fname) generate_demos("demo_") generate_demos("advanced_")
39,573
def get_approved_listings(): """ Gets pending listings for a user :param user_id :return: """ user_id = request.args.get('user_id') approved_listings = [] if user_id: approved_listings = Listing.query.filter_by(approved=True, created_by=user_id) else: approved_listin...
39,574
def draw_structure(xyz=None, species=None, project_directory=None, method='show_sticks'): """ A helper function for drawing a molecular structure using either show_sticks or draw_3d. Args: xyz (str, optional): The xyz coordinates to plot in string format. species (ARCSpecies, optional): A s...
39,575
def edit_profile(request): """ 编辑公司信息 :param request: :return: """ user_id = request.session.get("user_id") email = request.session.get("email") # username = request.session.get("username") if request.session.get("is_superuser"): # 管理员获取全部公司信息 data = models.I...
39,576
def get_vault(vault_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetVaultResult: """ This data source provides details about a specific Vault resource in Oracle Cloud Infrastructure Kms service. Gets the specified vault's configuration information. A...
39,577
def build_docker_build_command(configuration): """ Translate a declarative docker `configuration` to a `docker build` command. Parameters ---------- configuration : dict configuration Returns ------- args : list sequence of command line arguments to build an image "...
39,578
def _make_dist_mat_sa_utils(): """Generate a sample distance matrix to test spatial_analysis_utils Returns: xarray.DataArray: a sample distance matrix to use for testing spatial_analysis_utils """ dist_mat = np.zeros((10, 10)) np.fill_diagonal(dist_mat, 0) # Create distanc...
39,579
def _workSE(args): """Worker function for batch source extraction.""" imageKey, imagePath, weightPath, weightType, psfPath, configs, \ checkImages, catPostfix, workDir, defaultsPath = args catalogName = "_".join((str(imageKey), catPostfix)) se = SourceExtractor(imagePath, catalogName, weigh...
39,580
def _add_app_entity(app_name, entity_type, entity_name): """ Add an IAM entity to the set managed by this charm instance. """ managed_entities = _get_managed_entities() app_entities = managed_entities.setdefault(app_name, { 'role': [], 'instance-profile': [], 'policy': [], ...
39,581
def pull_function_version(info, function_id, version_id, output_path): """Download a version of a given custom function""" api = ce_api.FunctionsApi(api_client(info)) # Infer the function uuid and name f_list = api_call(api.get_functions_api_v1_functions_get) f_uuid = find_closest_uuid(function_id,...
39,582
def split_match(date,time,station): """ Function to find and extract the measuremnt from Jack Walpoles splititng data for the same event. This matching is done by finding an entry with the same date stamp. Inital testing has shown this to be a unique identifier. station MUST be a string of a station cod...
39,583
def schoolf_eq(temps, B0, E, E_D, T_pk): """Schoolfield model, used for calculating trait values at a given temperature""" function = B0 * exp(-E * ((1/(K*temps)) - (1/(K*283.15)))) / (1 + (E/(E_D - E)) * exp((E_D / K) * (1 / T_pk - 1 / temps))) return numpy.array(map(log,function), dtype=numpy.float64)
39,584
def get_parser(): """ Builds the argument parser for the program. """ parser = argparse.ArgumentParser() parser.add_argument('-c', type=str, dest='clf_key', default='dt', choices=['dt', 'xts', 'rf'], help='A classifier to use.') parser.add_argument('-m', type=str, dest='mode', default='test', choices=['...
39,585
def plotM(r,v): """ 计算导弹爆炸伤害。 r(float):导弹爆炸半径。 v(float):导弹爆炸速度。 TODO:未完成:drf部分 https://wiki.eveuniversity.org/Missile_mechanics """ fig = plt.figure() ax = Axes3D(fig) x=np.linspace(0,optimal+falloff*2,100) a=np.linspace(0,0.5,100) z=np.ndarray((len(x),len(a)),dtype=np....
39,586
def analyze_pmi(url, username, password): """Analyze the PMI.""" jira = login(url, username, password) open_defects = get_open_defects(jira) pmi = calculate_pmi(open_defects) show_pmi(pmi, url)
39,587
def heat_type_of( obj: Union[str, Type[datatype], Any, Iterable[str, Type[datatype], Any]] ) -> Type[datatype]: """ Returns the corresponding HeAT data type of given object, i.e. scalar, array or iterable. Attempts to determine the canonical data type based on the following priority list: 1. dty...
39,588
def get_field_from_acc_out_ty( acc_out_ty_or_dict: Union[Tuple, Dict[str, Any]], field: str ): """ After tracing NamedTuple inputs are converted to standard tuples, so we cannot access them by name directly. Use this helper instead. """ if isinstance(acc_out_ty_or_dict, dict): acc_out_ty...
39,589
def stop_gracefully(db, no_exit=False): """ A mechanism to stop the python process that is reading/writing to brunodb and shutdown gracefully, i.e. close the database first. Better than a hard stop which might corrupt the database. Particularly for when running a load with block=False. :param db...
39,590
def bhc(data,alpha,beta=None): """ This function does a bayesian clustering. Alpha: Hyperparameter Beta: Hyperparameter If beta is not given, it uses the Multinomial-Dirichlet. Otherwise it uses Bernoulli-Beta. """ n_cluster = data.shape[0] nodekey = n_cluster list_cluster...
39,591
def get_sql_value(conn_id, sql): """ get_sql_value executes a sql query given proper connection parameters. The result of the sql query should be one and only one numeric value. """ hook = _get_hook(conn_id) result = hook.get_records(sql) if len(result) > 1: logging.info("Result: %s ...
39,592
def get_rendered_config(path: str) -> str: """Return a config as a string with placeholders replaced by values of the corresponding environment variables.""" with open(path) as f: txt = f.read() matches = pattern.findall(txt) for match in matches: txt = txt.replace("[" + match + "]",...
39,593
def units_to_msec(units, resolution): """Convert BLE specific units to milliseconds.""" time_ms = units * float(resolution) / 1000 return time_ms
39,594
def test_compare_none(): """ Check none comparison results. """ compare_none = VersionString.compare_none assert compare_none(None, None) == EQUAL # Version with less parts is higher, which means # None is higher than a non None "part" value. assert compare_none('A', None) == GREATER
39,595
def IR(numOfLayer, useIntraGCN, useInterGCN, useRandomMatrix, useAllOneMatrix, useCov, useCluster, class_num): """Constructs a ir-18/ir-50 model.""" model = Backbone(numOfLayer, useIntraGCN, useInterGCN, useRandomMatrix, useAllOneMatrix, useCov, useCluster, class_num) return model
39,596
def extractNextPageToken(resultString): """ Calling GASearchVariantsResponse.fromJsonString() can be slower than doing the variant search in the first place; instead we use a regexp to extract the next page token. """ m = re.search('(?<=nextPageToken": )(?:")?([0-9]*?:[0-9]*)|null', ...
39,597
def underscore(msg): """ return underlined msg """ return __apply_style(__format['underscore'],msg)
39,598
def stop(): """ Stops ser2sock """ for proc in psutil.process_iter(): if proc.name() == 'ser2sock': os.kill(proc.pid, signal.SIGKILL)
39,599