content
stringlengths
22
815k
id
int64
0
4.91M
def scale_loss(loss, optimizer, model=None, delay_unscale=False): """ On context manager entrance, creates ``scaled_loss = (loss.float())*current loss scale``. ``scaled_loss`` is yielded so that the user can call ``scaled_loss.backward()``:: with amp.sca...
10,500
def get_top_words(keywords): """ Orders the topics from most common to least common for displaying. """ keywords = itertools.chain.from_iterable(map(str.split, keywords)) top_words = list(Counter(keywords)) return top_words
10,501
def is_mac(): """ Check if mac os >>> print(is_mac()) True or False Returns ------- bool: bool True or False. """ if sys.platform == 'darwin': return True return False
10,502
def login(i): """ Input: { (sudo) - if 'yes', add sudo } Output: { return - return code = 0, if successful > 0, if error (error) - error text if return > 0 } """ import os ...
10,503
def main(): """Execute setup and start the application.""" loop = asyncio.get_event_loop() score = pull_from_disk('score') banned = pull_from_disk('banned') asyncio.ensure_future(run_client(loop, **kwargs)) asyncio.ensure_future(save_to_disk('score', score)) asyncio.ensure_future(save_to_dis...
10,504
def now_playing(ctx): """ Show now playing metadata. """ client = ctx.obj['client'] client.now_playing()
10,505
def streamline_to_data(x_val, y_val, x0, y0): """ save streamline to bokeh.models.ColumnDataSource :param x_val: streamline data x :param y_val: streamline data y :param x0: initial value x of streamline :param y0: initial value y of streamline :return: """ source_initialvalue.data =...
10,506
def test_global_parser(): """ Check that the global_parser does what's expected """ global_test_str = ('global color=green dashlist=8 3 width=1 ' 'font="helvetica 10 normal roman" select=1 ' 'highlite=1 dash=0 fixed=0 edit=1 move=1 ' '...
10,507
def obj_prop(*args, **kwargs): """ Build an object property wrapper. If no arguments (or a single ``None`` argument) are suppled, return a dummy property. If one argument is supplied, return :class:`AttrObjectProperty` for a property with a given name. Otherwise, return :class:`MethodObjectProp...
10,508
def CreateDataObject(**kwargs): """ Creates a new Data Object by issuing an identifier if it is not provided. :param kwargs: :return: """ # TODO Safely create body = kwargs['body']['data_object'] doc = create(body, 'data_objects') return({"data_object_id": doc['id']}, 200)
10,509
def insertion_sort(A): """Sort list of comparable elements into nondecreasing order.""" for k in range(1, len(A)): # from 1 to n-1 cur = A[k] j = k # find correct index j for current while j > 0 and A[j-1] > cur: # element A[j-1] must be after...
10,510
def generate_sample_files_at(folder_path: PosixPath): """Generaetes sample files at a given folder path.""" for sample_file in constants.SAMPLE_FILES: sample_file_path = folder_path / sample_file with open(sample_file_path, "w") as f: f.write("") # Make empty folder to go with ...
10,511
def _check_name(name: str, invars: Iterable[str]) -> str: """Check if count is valid""" if name is None: name = _n_name(invars) if name != "n": logger.warning( "Storing counts in `%s`, as `n` already present in input. " 'Use `name="new_name" to pick a...
10,512
def test_count_animal_parametrise(spark, animal, expected_count): """ You can easily test different parameters for the same test by adding parametrisation. Here we are generalising the test_count_animal from test_basic by adding an argument for animal and expected_count. Be ...
10,513
def test_depth(run_line, go_ep1_id): """ Confirms setting depth to 1 on a --recursive ls of EP1:/ finds godata but not file1.txt """ load_response_set("cli.transfer_activate_success") load_response_set("cli.ls_results") result = run_line(f"globus ls -r --recursive-depth-limit 1 {go_ep1_id}:/...
10,514
def apply_random_filters(batches, filterbank, max_freq, max_db, min_std=5, max_std=7): """ Applies random filter responses to logarithmic-magnitude mel spectrograms. The filter response is a Gaussian of a standard deviation between `min_std` and `max_std` semitones, a mean betwe...
10,515
def get_documents(corpus_tag): """ Returns a list of documents with a particular corpus tag """ values = db.select(""" SELECT doc_id FROM document_tag WHERE tag=%(tag)s ORDER BY doc_id """, tag=corpus_tag) return [x.doc_id for x in values]
10,516
def version_patch(monkeypatch): """Monkeypatch version to stable value to compare with static test assets.""" monkeypatch.setattr(erd, "__version__", "TEST")
10,517
def draw_with_indeces(settings): """ Drawing function that displays the input smiles string with all atom indeces """ m = Chem.MolFromSmiles(settings['SMILESSTRING']) dm = Draw.PrepareMolForDrawing(m) d2d = Draw.MolDraw2DSVG(350,350) opts = d2d.drawOptions() for i in range(m.GetN...
10,518
def test_options_with_api_client(): """Checks that client can receive token, timeout values, and enable_compression """ client = lokalise.Client( "123abc", connect_timeout=5, read_timeout=3, enable_compression=True) opts = options(client) assert opts["headers"]["X-A...
10,519
def get_main_page_info(): """获取首页统计信息 :return info: Dict 统计信息 """ from app.extensions.celerybackend import models from app.extensions.logger.models import Log from app.modules.auth.models import User from app.utils import local task_cnt = models.Tasks.objec...
10,520
def get_tablenames(cur): """ Conveinience: """ cur.execute("SELECT name FROM sqlite_master WHERE type='table'") tablename_list_ = cur.fetchall() tablename_list = [str(tablename[0]) for tablename in tablename_list_ ] return tablename_list
10,521
def reverse_geocode(userCoords): """ Returns the city, state (or equivalent administrative region), and country that the specified point is in userCoords is a tuple: (latitude, longitude) """ lat, lng = userCoords latlng = "{0},{1}".format(lat, lng) data = urllib.parse.urlencode(...
10,522
def match_red_baselines(model, model_antpos, data, data_antpos, tol=1.0, verbose=True): """ Match unique model baseline keys to unique data baseline keys based on positional redundancy. Ideally, both model and data contain only unique baselines, in which case there is a one-to-one mapping. If model con...
10,523
def _choose_random_genes(individual): """ Selects two separate genes from individual. Args: individual (np.array): Genotype of individual. Returns: gene1, gene2 (tuple): Genes separated by at least another gene. """ gene1, gene2 = np.sort(np.random.choice(len(individual), size=...
10,524
def incomplete_sample_detection(device_name): """Introspect whether a device has 'incomplete sample detection', described here: www.ni.com/documentation/en/ni-daqmx/latest/devconsid/incompletesampledetection/ The result is determined empirically by outputting a pulse on one counter and measuring i...
10,525
def diag_numba(A, b): """ Fill matrix A with a diagonal represented by vector b. Parameters ---------- A : array Base matrix. b : array Diagonal vector to fill with. Returns ------- array Matrix A with diagonal filled. """ for i in range(b.shape[0]): ...
10,526
def get_symminfo(newsymms: dict) -> str: """ Adds text about the symmetry generators used in order to add symmetry generated atoms. """ line = 'Symmetry transformations used to generate equivalent atoms:\n' nitems = len(newsymms) n = 0 for key, value in newsymms.items(): sep = ';' ...
10,527
def get_random_sequences( self, n=10, length=200, chroms=None, max_n=0.1, outtype="list" # noqa ): """ Return random genomic sequences. Parameters ---------- n : int , optional Number of sequences to return. length : int , optional Length of sequences to return. chrom...
10,528
def get_sampleentropy(data): """Sample entropy, using antropy.sample_entropy, in the ML and AP directions. """ x, y = np.array(data[4]), np.array(data[5]) sample_entropy_ML = ant.sample_entropy(x) sample_entropy_AP = ant.sample_entropy(y) return sample_entropy_ML, sample_entropy_AP
10,529
def export_pdf(imgname, autotm, default_dpi, outfile, tformat, tleft, ttop, twidth, theight): """Trim the image and creates a PDF with the same size.""" if outfile == '': outfile = '%s.pdf' % (imgname) outtrim = '%s-trim.' % (outfile) outtrim = outtrim + tformat pdf = Canvas(outfile, pageCom...
10,530
def test_kernels_feedback_matrix(with_tf_random_seed, kernel_setup): """Test the feedback_matrices correspond to the state transitions for each kernel.""" time_points, kernel_factory, _ = kernel_setup tf_time_points = tf.constant(time_points) tf_time_deltas = to_delta_time(tf_time_points) kernel =...
10,531
def from_json(filename, columns=None, process_func=None): """Read data from a json file Args: filename: path to a json file columns (list, optional): list of columns to keep. All columns are kept by default process_func (function, optional): A callable object that you can pass to proces...
10,532
def save_books(books, file_path): """ Дописываем в таблицу все книги из списка :param books: list - список книг (классов Book) :param file_path: string - путь к таблице """ with open(file_path, 'a', encoding='utf-8') as file: if os.path.getsize(file_path) == 0: file.write('Na...
10,533
def send_admin_email(db_obj, support_case): """ Send announcement for each member of 'admin' groups When the support case is being created """ msg = Message('Autopsy Web app: a support case has been created') msg.sender = app.config['MAIL_USERNAME'] email_dl = db_obj.session.query( ...
10,534
def render_content(tab): """ This function displays tabs based on user selection of tab """ if tab == 'tab-2': return filter_based_recommendation.TAB2_LAYOUT return choice_based_recommendation.CHOICE_BASED_RECOMMENDATION_LAYOUT
10,535
def course(name, reviews = False): """ Get a course. Parameters ---------- name: string The name of the course. reviews: bool, optional Whether to also return reviews for the course, specifically reviews for professors that taught the course and have the course listed as...
10,536
def track_job(job, total, details = "", update_interval=1): """ Tracks map_async job. Parameters ---------- job : AsyncResult object total : total number of jobs update_interval : interval of tracking """ # if not isinstance(job, mp.pool.AsyncResult): # ra...
10,537
def task(weight=1): """ Used as a convenience decorator to be able to declare tasks for a TaskSet inline in the class. Example:: class ForumPage(TaskSet): @task(100) def read_thread(self): pass @task(7) def create_thr...
10,538
def unprotect_host(hostname): """ Cause an host to able to be acted on by the retirement queue Args: hostname - The hostname to remove from protection """ reporting_conn = get_mysqlops_connections() cursor = reporting_conn.cursor() sql = ("DELETE FROM mysqlops.retirement_protection " ...
10,539
def generate_age(issue_time): """Generate a age parameter for MAC authentication draft 00.""" td = datetime.datetime.now() - issue_time age = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 return unicode_type(age)
10,540
def out_atok_dic(out_dir, entries, dic_type): """ ATOK用の辞書を作成する。 ファイルのencodingはutf-16, 改行コードはCR/LF, タブ区切り。 :param out_dir: 出力先ディレクトリ :param entries: 出力するエントリ :param dic_type: 辞書の種別 """ file_path = os.path.join(out_dir, 'atok_dic_{}.txt'.format(dic_type.value)) with open(file_path, '...
10,541
def measures_hrna_basepairs(name, s, path_to_3D_data, thr_idx): """ Open a rna_only/ file, and run measures_hrna_basepairs_chain() on every chain """ setproctitle(f"RNANet statistics.py Worker {thr_idx+1} measures_hrna_basepairs({name})") l = [] chain = next(s[0].get_chains()) ...
10,542
def _bqm_from_1sat(constraint): """create a bqm for a constraint with only one variable bqm will have exactly classical gap 2. """ configurations = constraint.configurations num_configurations = len(configurations) bqm = dimod.BinaryQuadraticModel.empty(dimod.SPIN) if num_configurations =...
10,543
def read_workdir(conffile): """read working dir from a config file in the users larch dir compare save_workdir(conffile) which will save this value can be used to ensure that application startup starts in last working directory """ try: w_file = os.path.join(user_larchdir, conffile) ...
10,544
def _ssh(server): """ SSH into a Server """ remote_user = server.remote_user private_key = server.private_key if not private_key or not remote_user: if remote_user: return {"result": "Critical. Missing Private Key", "status": 3, } ...
10,545
def _create_group_codes_and_info( states: pd.DataFrame, assort_bys: Dict[str, List[str]], contact_models: Dict[str, Dict[str, Any]], ) -> Tuple[pd.DataFrame, Dict[str, Dict[str, Any]]]: """Create group codes and additional information. Args: states (pd.DataFrame): The states. assort...
10,546
def print_version(ctx, param, value): """Print suricataindex version to stdout.""" if value_check(value, ctx): return click.echo(str(__version__)) ctx.exit()
10,547
def json_reader(input_data): """A generator that converts an iterable of newline-delimited JSON objects ('input_data' could be a 'list' for testing purposes) into an iterable of Python dict objects. If the line cannot be parsed as JSON, the exception thrown by the json.loads() is yielded back, instead o...
10,548
def test_pip_std_install(tmpdir): """ Test Pip Standard Install """ python_dir = tmpdir.join("lib", "python2.7", "site-packages", "qibuild") python_dir.ensure("__init__.py", file=True) cmake_dir = tmpdir.join("share", "cmake") cmake_dir.ensure("qibuild", "qibuild-config.cmake", file=True) res = ...
10,549
def quiver_plotter(X, Y, Z, plot_range=None, mes_unit='', title='', x_label=r'$x$', y_label=r'$y$', show_plot=True, dark=False): """ Generates a plot of some vector fields. Parameters ---------- X : numpy.ndarray Matrix with values for the first axis on all the rows. Y : numpy.n...
10,550
def get_attr(item, name, default=None): """ similar to getattr and get but will test for class or dict :param item: :param name: :param default: :return: """ try: val = item[name] except (KeyError, TypeError): try: val = getattr(item, name) except...
10,551
def float2(val, min_repeat=6): """Increase number of decimal places of a repeating decimal. e.g. 34.111111 -> 34.1111111111111111""" repeat = 0 lc = "" for i in range(len(val)): c = val[i] if c == lc: repeat += 1 if repeat == min_repeat: return float(val[:i+1] + c * 10) else...
10,552
def load_array_meta(loader, filename, index): """ Load the meta-data data associated with an array from the specified index within a file. """ return loader(filename, index)
10,553
def viterbi_value(theta: np.ndarray, operator: str = 'hardmax') \ -> float: """ Viterbi operator. :param theta: _numpy.ndarray, shape = (T, S, S), Holds the potentials of the linear chain CRF :param operator: str in {'hardmax', 'softmax', 'sparsemax'}, Smoothed max-operator ...
10,554
def pack32(n): """Convert a Python int to a packed signed long (4 bytes).""" return pack('<i', n)
10,555
def run_rollout( policy, env, horizon, use_goals=False, render=False, video_writer=None, video_skip=5, terminate_on_success=False, ): """ Runs a rollout in an environment with the current network parameters. Args: policy (Rollout...
10,556
def create_test_client( route_handlers: Union[ Union[Type[Controller], BaseRouteHandler, Router, AnyCallable], List[Union[Type[Controller], BaseRouteHandler, Router, AnyCallable]], ], after_request: Optional[AfterRequestHandler] = None, allowed_hosts: Optional[List[str]] = None, back...
10,557
def queue_tabnav(context): """Returns tuple of tab navigation for the queue pages. Each tuple contains three elements: (tab_code, page_url, tab_text) """ counts = context['queue_counts'] request = context['request'] listed = not context.get('unlisted') if listed: tabnav = [('nomina...
10,558
def _plot_feature_correlations(ax, correlation_matrix, cmap="coolwarm", annot=True, fmt=".2f", linewidths=.05): """ Creates a heatmap plot of the feature correlations Args: :ax: the axes object to add the plot to :correlation_matrix: the feature correlations :cmap: the color map ...
10,559
def _fix_mark_history(user): """ Goes through a users complete mark history and resets all expiration dates. The reasons for doing it this way is that the mark rules now insist on marks building on previous expiration dates if such exists. Instead of having the entire mark database be a linked list...
10,560
def create_asset(show_name, asset_name, asset_type, hero, target_date): """Create asset entity within a show""" db = con.server.hydra db.assets.insert( { "name": asset_name, "show": show_name, "type": asset_type, "hero": hero, "target_date"...
10,561
def test_par_04(floatprecision='double'): """Test setters""" assert floatprecision in ['double', 'float'] const = N.array([1.5, 2.6, 3.7], dtype=floatprecision[0]) var = R.parameter(floatprecision)('testpar', const.size) taintflag = R.taintflag('tflag') var.subscribe(taintflag) taintflag.set...
10,562
def graphviz_visualization(activities_count, dfg, image_format="png", measure="frequency", max_no_of_edges_in_diagram=100000, start_activities=None, end_activities=None, soj_time=None, font_size="12", bgcolor="transparent", stat_locale: ...
10,563
def sig_io_func(p, ca, sv): # The method input gives control over how the Nafion conductivity is # calculated. Options are 'lam' for laminar in which an interpolation is # done using data from [1], 'bulk' for treating the thin Nafion shells the # as a bulk-like material using NR results from [5], ...
10,564
def srwl_opt_setup_cyl_fiber(_foc_plane, _delta_ext, _delta_core, _atten_len_ext, _atten_len_core, _diam_ext, _diam_core, _xc, _yc): """ Setup Transmission type Optical Element which simulates Cylindrical Fiber :param _foc_plane: plane of focusing: 1- horizontal (i.e. fiber is parallel to vertical axis), 2-...
10,565
def __create_menu_elements() -> Enum: """Create Menu Elements. :return: Menu elements as an enum in the format KEY_WORD -> Vales(char, KeyWord) """ menu_keys = ["MAIN_MENU", "PROFILE", "CLEAN_TIME", "READINGS", "PRAYERS", "DAILY_REFLECTION", "JUST_FOR_TODAY", "LORDS_PRAYER", "SERENITY_...
10,566
def solve(coordinates): """ 알고리즘 풀이 함수 : 두 점의 최단거리를 구해주는 함수 :param coordinates: 좌표들 :return: 두 점의 최단거리 """ n = len(coordinates) x_coordinates = [coordinate[0] for coordinate in coordinates] y_coordinates = [coordinate[1] for coordinate in coordinates] middle_point = (sum_of_list(x_co...
10,567
def get_cache_key(account, container=None, obj=None): """ Get the keys for both memcache and env['swift.infocache'] (cache_key) where info about accounts, containers, and objects is cached :param account: The name of the account :param container: The name of the container (or None if account) :...
10,568
def manipComponentPivot(*args, **kwargs): """ Dynamic library stub function Derived from mel command `maya.cmds.manipComponentPivot` """ pass
10,569
def dir_plus_file(fname): """Splits pathnames into the dirname plus the filename.""" return os.path.split(fname)
10,570
def test_flatten_list() -> None: """Flatten a list.""" nested_list: List[List[int]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] assert [num for elem in nested_list for num in elem] == [1, 2, 3, 4, 5, 6, 7, 8, 9]
10,571
def arctan(x): """Returns arctan(x)""" if type(x) in (float,_numpy._numpy.float64): x = _numpy._numpy.array([x]) a = abs(x) r = arctan_1px( a - 1. ) f = arctan_series( a ) eps = _numpy._numpy.finfo(1.).eps g = arctan_series( 1. / maximum( 0.125, a ) ) g = 0.5 * _numpy._numpy.pi - g j...
10,572
def uniform_dist(low, high): """Return a random variable uniformly distributed between `low` and `high`. """ return sp_uniform(low, high - low)
10,573
def flatten(dictionary, parent_key=False, separator='_'): """ Turn a nested dictionary into a flattened dictionary :param dictionary: The dictionary to flatten :param parent_key: The string to prepend to dictionary's keys :param separator: The string used to separate flattened keys :return: A fl...
10,574
def format_sec_to_hms(sec): """Format seconds to hours, minutes, seconds. Args: sec: float or int Number of seconds in a period of time Returns: str Period of time represented as a string on the form ``0d\:00h\:00m``. """ rem_int, s_int = divmod(int(sec), 60) h_int, m_int,...
10,575
def one_hot_encode(data): """turns data into onehot encoding Args: data (np.array): (n_samples,) Returns: np.array: shape (n_samples, n_classes) """ n_classes = np.unique(data).shape[0] onehot = np.zeros((data.shape[0], n_classes)) for i, val in enumerate(data.astyp...
10,576
def null_write_block(fo, block_bytes): """Write block in "null" codec.""" write_long(fo, len(block_bytes)) fo.write(block_bytes)
10,577
def is_number(input_str): """Check if input_str is a string number Args: input_str (str): input string Returns: bool: True if input_str can be parse to a number (float) """ try: float(input_str) return True except ValueError: return False
10,578
def test_swapping(exopy_qtbot, task_workbench, dialog_sleep): """Test moving a view between containers. """ task = RootTask() view = RootTaskView(task=task, core=task_workbench.get_plugin('enaml.workbench.core')) subtask = ComplexTask(name='Test') subview = view.view_fo...
10,579
def run_command( info, host, port, reload, debugger, eager_loading, with_threads, extra_files ): """Run a local development server. This server is for development purposes only. It does not provide the stability, security, or performance of production WSGI servers. The reloader and debugger ar...
10,580
def impute_between(coordinate_a, coordinate_b, freq): """ Args: coordinate_a: coordinate_b: freq: Returns: """ metrics = discrete_velocity(coordinate_a, coordinate_b) b, d, sec = metrics['binning'], metrics['displacement'], metrics['time_delta'] if b...
10,581
def seq(fr,to,by): """An analogous function to 'seq' in R Parameters: 1. fr: from 2. to: to 3. by: by (interval) """ if fr<to: return range(fr,to+abs(by),abs(by)) elif fr>to: if by>0: aseq = range(fr,to-by,-1*by) else: aseq = range(fr,...
10,582
def _get_config_from_context(ctx): """ :param ctx: :return: :rtype: semi.config.configuration.Configuration """ return ctx.obj["config"]
10,583
def _invert_options(matrix=None, sparse=None): """Returns |invert_options| (with default values) for a given |NumPy| matrix. See :func:`sparse_options` for documentation of all possible options for sparse matrices. Parameters ---------- matrix The matrix for which to return the options...
10,584
def directory_is_empty(path: AnyStr) -> bool: """ :param path: a directory path :return: True if directory is empty, False otherwise """ return not any(os.scandir(path))
10,585
def get_Carrot_scramble(n=70): """ Gets a Carrot-notation scramble of length `n` for a Megaminx. Defaults to csTimer's default length of 70. """ return _UTIL_SCRAMBLER.call("util_scramble.getMegaminxCarrotScramble", n).replace('\n','').replace(' ',' ').replace(' ',' ')
10,586
def convex_env_train(Xs, Ys): """ Identify the convex envelope on the set of models from the train set. """ # Sort the list in either ascending or descending order of the # items values in Xs key_X_pairs = sorted(Xs.items(), key=lambda x: x[1], reverse=False) # this...
10,587
def main(): """ Main function Main function that distributes the files that will be parsed and writes the result into database """ # Get list of names of the files that will be parsed file_list=[] # Open the file and read file names f = open( config.files["HYDRAFILES"], "r" ) for x in f: file_list.append...
10,588
def handle_control_command(sniffer, arg, typ, payload): """Handle command from control channel""" if arg == CTRL_ARG_DEVICE: if payload == b' ': scan_for_devices(sniffer) else: follow_device(sniffer, payload) elif arg == CTRL_ARG_KEY: set_passkey_or_...
10,589
def randthresh(Y,K,p=np.inf,stop=False,verbose=False,varwind=False,knownull=True): """ Wrapper for random threshold functions (without connexity constraints) In: Y (n,) Observations K <int> Some positive integer (lower bound on the number of null hypotheses) p ...
10,590
def referrednested(func, recurse=True): #XXX: return dict of {__name__: obj} ? """get functions defined inside of func (e.g. inner functions in a closure) NOTE: results may differ if the function has been executed or not. If len(nestedcode(func)) > len(referrednested(func)), try calling func(). If poss...
10,591
def format_organizations_output(response: Dict[str, Any], page_number: int, limit: int) -> Tuple[list, int]: """ Formatting list organizations command outputs. Args: response (Dict[str,Any): The response from the API call. limit (int): Maximum number of results to return. page_number...
10,592
def which_db_version(cursor): """ Return version of DB schema as string. Return '5', if iOS 5. Return '6', if iOS 6 or iOS 7. """ query = "select count(*) from sqlite_master where name = 'handle'" cursor.execute(query) count = cursor.fetchone()[0] if count == 1: db_version ...
10,593
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the LiteJet switch platform.""" litejet_ = hass.data['litejet_system'] devices = [] for i in litejet_.button_switches(): name = litejet_.get_switch_name(i) if not litejet.is_ignored(hass, name): d...
10,594
async def get_number_of_images_from_category(category : str): """ TODO docstring Get number of images in category """ categories_query = CATEGORIES_DB.search(where('category') == category) if not categories_query: return {"number_of_images": 0} return {"number_of_imag...
10,595
def gaussian_total_correlation(cov): """Computes the total correlation of a Gaussian with covariance matrix cov. We use that the total correlation is the KL divergence between the Gaussian and the product of its marginals. By design, the means of these two Gaussians are zero and the covariance matrix of...
10,596
def S3list(s3bucket, fdate, instrm, network='OKLMA'): """ get list of files in a s3 bucket for a specific fdate and instrument (prefix) fdate: e.g. '2017-05-17' instrm: e.g. 'GLM' """ prefix = {'GLM': 'fieldcampaign/goesrplt/GLM/data/L2/' + fdate + '/OR_GLM-L2-LCFA_G16', 'LIS': 'fi...
10,597
def formatted_karma(user, activity): """ Performs a karma check for the user and returns a String that's already formatted exactly like the usual response of the bot. :param user: The user the karma check will be performed for. :return: A conveniently formatted karma check response. """ resp...
10,598
def setsysvolacl(samdb, netlogon, sysvol, uid, gid, domainsid, dnsdomain, domaindn, lp, use_ntvfs): """Set the ACL for the sysvol share and the subfolders :param samdb: An LDB object on the SAM db :param netlogon: Physical path for the netlogon folder :param sysvol: Physical path for the sysvol...
10,599