content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def file_to_subtitles(filename): """ Converts a srt file into subtitles. The returned list is of the form ``[((ta,tb),'some text'),...]`` and can be fed to SubtitlesClip. Only works for '.srt' format for the moment. """ with open(filename,'r') as f: lines = f.readlines() ...
007c4360c0b8168c8a1ff4f609a02316f7374690
45,900
def all_layers(): """Sample layer elevation grid where some layers are completely pinched out (no botm elevation specified) and others partially pinched out (botms specified locally). Returns ------- """ nlay, nrow, ncol = 9, 10, 10 all_layers = np.zeros((nlay + 1, nrow, ncol), dtype=f...
fc9f43cf0f7a44512b3c21e3c0ac86a0ff881dd9
45,901
import imp import sys def _run_module_code(code, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, alter_sys=False): """Helper for run_module""" # Set up the top level namespace dictionary if alter_sys: # Modify sys.argv[0] and sys.module[mo...
7b434487e6e2a196b06f392f58c2650741f300d2
45,902
def calculate_border(grid_dims, width, height): """Calculate each line in all borders. Args: grid_dims: tuple of the number of tiles in grid. In format `(row, column)` width: float width in pixels height: float height in pixels Returns: list: containing dictionaries keys `(...
b4ec0e063034547783e871abf1a46d943648df67
45,903
import pandas def df_fe2num_frames(fn_instance): """ create a df in which each row contains the number of frames that a FE is a part of :param instance of nltk.corpus.reader.framenet.FramenetCorpusReader fn_instance: instace of fn version :rtype: pandas.core.frame.DataFrame :return: df with for...
69393f8097a0a705a193a3015bcb725dda6dbb8d
45,904
def check_y_pos(act: Act, acts: list) -> bool: """Checks if the y position of Activities overlaps any other given Activities. Args: act: Activity of which to check the overlap. acts: List of Activities to check against. Returns: True if Activity does not...
c63e9335a4357b5a4f091f2ad5b2758fd846f2ac
45,905
from datetime import datetime def aggregate_data_for_timespan(data): """ Calculate aggregate values for all data in a given timespan :param data: dict of result data from query_data_for_timespan() :type data: dict """ res = {} res['reports'] = {'run_count': 0, 'run_t...
73ac51fedb0d9831cc158ef0412c98a055751fd1
45,906
def dijkstra_heap(siten): """ 1-indexed 疎グラフの時に有効 O(E log(V)) :return: """ dist = [INF] * (n + 1) dist[siten] = 0 que = [] heappush(que, (dist[siten], siten)) while len(que): d, v = heappop(que) if d > dist[v]: continue for e in G[v]: ...
a7c5d770a7df6ca888e4df42146f327c95eca612
45,907
def _parse_face(face_row): """Parses a line in a PLY file which encodes a face of the mesh.""" face = [int(index) for index in face_row.strip().split()] # Assert that number of vertices in a face is 3, i.e. it is a triangle if len(face) != 4 or face[0] != 3: raise ValueError( 'Only supports face repre...
c0cf7472705544c3089a6c1c82190bcb8bd5f463
45,908
import sys import six import logging import subprocess import os def execute(command, env=None, split_lines=False, ignore_errors=False, extra_ignore_errors=(), translate_newlines=True, with_errors=True, none_on_ignored_error=False, ...
930a2c48b5c7d799956645afcb0b59085079d572
45,909
def include_keys(include, d): """ Pick out the `include` keys from a dict Args: include: list or set of keys to be included d: raw dict that might have irrelevant keys """ assert is_sequence(include) return {k: v for k, v in d.items() if k in set(include)}
83dde8334819fd1be825707172219eb8505956f1
45,910
import torch def spherical_interpolate(p1, p2, n_steps=8): """Spherical interpolation between two vectors.""" assert p1.dim() == p2.dim() == 1, "Only 1d vectors are currently supported." def _spherical_interpolate_pytorch(): ratios = torch.linspace(0, 1, steps=n_steps) vectors = [slerp(ra...
c30aca403ee6f4a96311c6b95a8fe81a515b3ff9
45,911
def override_serializer(format_output, dimension, base_serializer_class): """ Override Serializer switch output format and dimension data """ if format_output == 'geojson': if dimension == '3': class GeneratedGeo3DSerializer(BaseGeoJSONSerializer, ...
f02c3d6144cb152c40040a37a73f649c011c8ea4
45,912
import argparse def _parse_args(argv=None): """Parse command line args.""" default_config_file = default_config_file_path() parser = argparse.ArgumentParser( description=("Updates the AWS ParallelCluster configuration file."), epilog='For command specific flags, please run: "pcluster-conf...
33ec3aa6057536769ed933995cf240dcb5972728
45,913
def _get_config(): """Return a config dictionary.""" return { DYSON_DOMAIN: { CONF_USERNAME: "email", CONF_PASSWORD: "password", CONF_LANGUAGE: "GB", CONF_DEVICES: [ {"device_id": "XX-XXXXX-XX", "device_ip": "192.168.0.1"}, ...
b69094088f1dda94540e8e5f6f89a108ceb93396
45,914
def test_parallel_pathos_pp_task ( ) : """Test parallel processnig with parallel_pathos (task interface) """ logger = getLogger ("ostap.test_parallel_pathos_pp_task") if not WorkManager : logger.error ("Failure to import WorkManager") return logger.info ('Test job submission w...
8b027b496f52e26a8ee64d6c56882acda4cc4f13
45,915
def create_r2_script_content(sample_file_path, decoded_strings, stack_strings): """ Create r2script contents for r2 session annotations. :param sample_file_path: input file path :param decoded_strings: list of decoded strings ([DecodedString]) :param stack_strings: list of stack strings ([StackStrin...
edb91bc3489560cb5b3a9445ae35ffc5bb7d0dad
45,916
import pandas def ReadData(filename='PEP_2012_PEPANNRES_with_ann.csv'): """Reads filename and returns populations in thousands filename: string returns: pandas Series of populations in thousands """ df = pandas.read_csv(filename, header=None, skiprows=2, encoding='iso-88...
931256a3a22f64ee698bb4116728494473230bb4
45,917
import json def get_new_username(): """提示用户输入用户名""" username = input('请输入用户名:\n') filename = 'username.json' with open(filename, 'w') as f: json.dump(username, f) return username
3b6023dd950e689995af472005809d6ca97033c1
45,918
def bezier3_split_batch(batch): """Split N bezier3 curves in 2xN bezier3 curves at t=0.5""" return np.moveaxis(np.dot(BEZIER3_SPLIT, batch), 0, -2).reshape((-1, 4, 2))
daaae323b8e91ea40d1425b8a088f8f6eed616cf
45,919
def create_indices(ordering_1: SortedList, ordering_2: SortedList): """ Creates indices np.array which represents how agents from ordering_1 have to be rearranged in order to fit agents from ordering_2. If such relation is not possible, return False. :param ordering_1: first agents ordering :param ...
f58d59b997449a248673671375377fb623bdcd38
45,920
def extend_conv_spec(convolutions): """ 添加默认配置(残差) Extends convolutional spec that is a list of tuples of 2 or 3 parameters (kernel size, dim size and optionally how many layers behind to look for residual) to default the residual propagation param if it is not specified """ extended = [] ...
4e6639342b19db18939991c7bc681d7e23a855f4
45,921
def bin_spectra(filename, start=None, end=None, save=True, dec=3, function=None): """ Sums spectra from raw file and outputs to excel file :param filename: raw or mzML filename :param start: start scan (None will default to 1) :param end: end scan (None will default to the last scan) :param sav...
ef0a25d4b55dcef198b5e7a2a7d87411f2a144b1
45,922
def internal_manifest_from_external( manifest: ImportManifest, content_records: list ) -> InternalImportManifest: """ Construct an internal manifest from an external one plus the db records for the content :param manifest: ImportManifest object :param content_records: list of ImageImportContent rec...
ba20c97a80879d038f596603ebe8853e34634b87
45,923
def hello(): """Return a friendly HTTP greeting.""" if request.method == 'POST': return "Yes {}".format(request.form.get("myname")) return "<form id='myform' method='POST'><input name='myname'/></form>"
e05a9d20ac8626a70af8aa8cd377e79f4209099e
45,924
def prepare(topic_model, docs, **kargs): """Transforms the GraphLab TopicModel and related corpus data into the data structures needed for the visualization. Parameters ---------- topic_model : graphlab.toolkits.topic_model.topic_model.TopicModel An already trained GraphLab topic model. ...
ff18e1784d13a5e089a74f6ccab400ae7303c7d6
45,925
def fit_gaussians(data, height, width, savedir='./', overplot=False, savename='./Data-With-Gaussians.csv'): """ Fits gaussians to the data peaks. Parameters ---------- data: string or Pandas DataFrame This should be a string that points to the csv DataFrame file or...
de223ce309bf40dd13bff4e6166da777255a5e1f
45,926
import argparse def parseargs() -> argparse.ArgumentParser: """ Parse arguments """ parser = worker.parseargs('Manage origins') parser.add_argument("--list", action="store_true", help="List origins") parser.add_argument("--add", action="store_true", help="List origins") parser.add_argument("--dele...
d1e28959e98e7d42039f317aba009714aa140a6b
45,927
import json import re import requests def aci_app_proxy(): """ this function is a workaround to current ACI app api restriction that only allows for post/get requests and static one-level urls. Instead of doing get/post/delete to dynamic url as provided by this app, the request will be p...
32fcb0c8cce1142b522e42ad7517c5378eb9aef4
45,928
def f(x): """return x*x""" return x * x
f6f06aa4c83d4dfbdfe6d0d8cec93f4a0fef3d4d
45,929
def divideURL(url, queryDelim="&"): """Divides a URL into a dict with the following keys, whose values are an empty str if optional and not set: - scheme (str) - authority (dict. Keys: username, password, host, port) - path (str) - query (dict. Keys are query keys = list of their values) - ...
d8bca62a0c99fa1a1c93b07eb8e9a92d8e9c0ac8
45,930
import torch def permutation_kronecker(perm1: FixedPermutation, perm2: FixedPermutation) -> FixedPermutation: """Combine two permutations of size n1 and n2 into their Kronecker product of size n1 * n2. """ n1, n2 = perm1.permutation.shape[-1], perm2.permutation.shape[-1] x = torch.arange(n2 * n1, devi...
09538e042794f2c2ebba1743c13e3de04d0144f3
45,931
import pdb def get_palate_line_segments(speaker_tensor, name, mt_hull, plot_bool): """ data: unordered x,y coordinates from tongue coils T1/TT, T2/TB, T3/TD and data from T1/TT in the case of 'faet0', 'mjjn0', 'fsew0' are used to create a convex hull estimate as to where the palate is in order to...
d1bf5d4c8e87fa805b8d9e758940e00567a45193
45,932
import copy def third_round_phase(tableau, phase_stabilizer, phase_destabilizer): """Adds a diagonal matrix to the Z destabilizer matrix such that Zd + D = M*M' for some invertible M""" num_qubits = int(len(tableau[0, :]) / 2) x_destab = tableau[0:num_qubits, 0:num_qubits] z_destab = tableau[0:num_qub...
8fcc4842abd9046e353d489d0591fb55f867ff69
45,933
def conv_en2ko(string): """ conv_en2ko(string) Convert English characters to Korean characters. :return: String (Korean) """ char_groups = split_en(string) converted_string = '' for char_group in char_groups: top_idx = 0 mid_idx = 0 bot_idx = 0 for char_...
ffc3236a7a2c2773d5ed5e318461ac87d296e534
45,934
def _check_to_numpy(plugin, tensor): """Check the tensor and return a numpy.ndarray.""" np_value = tensor.asnumpy() if plugin == 'scalar': if np_value.size == 1: return np_value raise ValueError('The tensor holds more than one value, but the scalar plugin expects on value.') ...
919ff69a7eebf2d32d72f343ff51c9e41c915c5b
45,935
import json def get_f1_score(labels, pre_file, gold_file): """ Get F1 scores for each label. Args: labels: list of labels. pre_file: prediction file. gold_file: ground truth file. Returns: average F1 score on all labels. """ pre_lines = [json.loads(line.strip(...
cd473db2abd4c504293557e2c2be84f603083910
45,936
def calendar_date(year, doy): """ Calendar date from day of year @param year : int @param doy : int day of year @return: tuple of ints (year, month, day) """ if doy < 32: month = 1 day = doy elif doy < 60 + leap_year(year): month = 2 day = doy - 31 else: if leap_year(yea...
5c88ed2003d520cd83aba0e822f9ba9ffc9d12ff
45,937
def get_vulnerabilities(): """Return a paginated list of available vulnerabilities For vulnerability details see :http:get:`/api/1.0/vulnerabilities/(int:vuln_id)` **Example request**: .. sourcecode:: http GET /api/1.0/vulnerabilities HTTP/1.1 Host: cp.cert.europa.eu Accep...
edf3ea064aa51257ca04423316357c423dc414d3
45,938
import sys def alpha_075(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: eries:index为成分股代码,values为1或-1,当满足条件时为1,否则为-1 公式: (rank(correlation(vwap, volume, 4.24304)) < rank(correlation(rank(low), rank(adv50), 12.4413)))...
24f939c2e74ff1583645deebdb4ac4b7d0527ae7
45,939
def change_referential( self, rotation_speed, is_waveform, atol=1e-9, axes_list_change=list(), arg_list=list(), freqs_new=np.array([]), I1=np.array([]), Irf_un=np.array([]), sym_t_new=dict(), ta_in=tuple(), ta_out=tuple(), atol_freq=1e-6, ): """Change referential ...
801493ecb2e1ed9c497b6f54bbd661fa18143f65
45,940
def get_model(tree_type='lgb', objective='regression', n_tree=100, max_depth=5, random_state=1, max_bins=255, learning_rate=0.3): """ Return the ensemble object from the specified framework and objective. """ if tree_type == 'cb': class_fn = CatBoostRegressor if objective == 'regr...
4643440fad70c7e42b823d14456abb799dade9d3
45,941
import secrets import traceback def alert_gwg_owners(team, subject=None, body=None): """Direct messages the owners of the GWG challenge that there isn't a form available for todays game and that their players are angry!!! """ owners = secrets.get_team_contacts(team) if not subject: subjec...
b6fa01ef7516fd80ee46d7eceaed8be0af13d314
45,942
import logging import os import sys def setup_logger(name, level=logging.INFO): """Function setup as many loggers as you want""" if not os.path.exists('log'): os.makedirs('log') # pragma: no cover formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') handler = logging.Stream...
a67eac96359d2f86ecbca7e7c52c113f142ac112
45,943
def make_client(args, password='BadKangaroo'): """Make an app3 client that talks to an olinapp3 server.""" if 'local' in args: client = App3Client('localhost:8080', password) else: client = App3Client('olinapp3.appspot.com', password) return client
957ecda68dc0e8203f561e07b88c11d28ab54802
45,944
import json def app(args): # pragma: no cover """ Dumps Concepticon's contents for English, German, Chinese, and French. Notes ----- Data are by default dumped into a structured JSON file in html/data.js. Examples -------- $ concepticon html """ data = defaultdict(list) ...
3d3ee3e0fede9f5d77bd322797795ddadfd36274
45,945
import os def GetConfigFilePaths(): """Returns a list of the path(s) to the boto config file(s) to be loaded.""" potential_config_paths = BotoConfigLocations # When Boto's pyami.config.Config class is initialized, it attempts to read # this file, transform it into valid Boto config syntax, and load credentia...
e9d47769ea6201eb16eb0ff24263bd1682804151
45,946
def separate_qtranslate_content(text): """Parse the content of a wordpress post or page and separate the various language specific contents when they are delimited with qtranslate tags: <!--:LL-->blabla<!--:-->""" # TODO: uniformize qtranslate tags <!--/en--> => <!--:--> qt_start = "<!--:" qt_en...
a96dbbdec9fd45b3439ba9336bbd3b8a838da0fb
45,947
def get_current_user_info(token): """Returns information about the authenticated user.""" return _fetch_api(token, GITHUB_API_ROOT + '/user', bust_cache=True)
726971e21fd1428ebd543b30bdb9b3cd921e984e
45,948
import os import time def generate_loop_matrix_element(process_definition, reuse, output_path=None, cmd = FakeInterface(), proc_name=None, loop_filter=None): """ Generate a loop matrix element from the process definition, and returns it along with the timing information dictionary. ...
1ec35978bc111fc4ef02e3884cb9525296869448
45,949
def remove_no_include(wikicode: mwparserfromhell.wikicode.Wikicode) -> mwparserfromhell.wikicode.Wikicode: """Removes the noinclude tags""" for tag in wikicode.filter_tags(): if tag.tag.matches('noinclude'): try: wikicode.remove(tag) except ValueError: ...
d7c59ce6275a5b287f3f4b8828e890acddb6da1f
45,950
from typing import Dict from typing import Any from typing import cast from typing import Union from functools import reduce def parse_query_params(connection: HTTPConnection) -> Dict[str, Any]: """ Parses and normalize a given connection's query parameters into a regular dictionary """ qs = cast(Unio...
86f834b58030d065b1364d408c75df7b8d721e2a
45,951
def _get_state(self): """Get dictionary of dataclass fiels.""" return _dc.asdict(self)
f4c26ea75ba19988d649b62a12fbde29d7c7361e
45,952
def twilightFunc(xdata, *args, amCut=1.0): """ xdata: numpy array with columns 'alt', 'az', 'sunAlt' all in radians. az should be relative to the sun (i.e., sun is at az zero. based on what I've seen, here's my guess for how to fit the twilight: args[0] = ratio of (zenith twilight flux at sunAlt = ...
6a0b8f738cc6e21f0da0c88b40e2d6af4788518b
45,953
def matrix_constant_mult(m, c): """ Multiply components of matrix m by constant c """ return [mult(row_m, c) for row_m in m]
e6beb4400e1d99edb1193a3fe53fc17891182e51
45,954
def rasterize_geom(geom, affine, shape): """ Rasterize geometry to a matching affine and shape. """ geoms = [(geom, 1)] rv_array = features.rasterize( geoms, out_shape=shape, transform=affine, fill=0, dtype='uint8' ) return rv_array.astype(bool)
3032955cda29ff1801abbe5ff28be951460334c3
45,955
def top_usernames_used(): """ Get top usernames used according to module Returns: JSON/Dict of top usernames used """ module_name = get_value_from_request("module_name") module_query = [ group_by_ip_dest_and_username, { "$skip": fix_skip( get_...
8405def2c6875e282094d4270bf4c7503f6ffcc1
45,956
def robust_match_fundamental(p1, p2, matches, config): """Filter matches by estimating the Fundamental matrix via RANSAC.""" if len(matches) < 8: return np.array([]) p1 = p1[matches[:, 0]][:, :2].copy() p2 = p2[matches[:, 1]][:, :2].copy() FM_RANSAC = cv2.FM_RANSAC if context.OPENCV3 else ...
2f1a267b2b845415d18b8944ccc23c8286533e28
45,957
from numpy import array,arange def beam_position(images): """Returns first moment of beam position (X1,Y1) in units of pixels relative to the center pixel in images. The mask is assumed to be 7x7.""" height,width = images[0].shape N_bkg = background_mask().sum() X0 = int((width-1)/2) Y0 = int(...
469784d8091563acc1039408e7770530a412ca5d
45,958
import tqdm def median_freq_balancing(dataloader, num_classes): """Computes class weights using median frequency balancing as described in https://arxiv.org/abs/1411.4734: w_class = median_freq / freq_class, where freq_class is the number of pixels of a given class divided by the total number of pixel...
c2a5a6625d78893cb1357aa0e364936f4c77c791
45,959
def filter(params: LDS, x_hist: chex.Array, jump_size: chex.Array, dt: chex.Array): """ Compute the online version of the Kalman-Filter, i.e, the one-step-ahead prediction for the hidden state or the time update step Parameters ---------- x_hist: array(times...
097f34894c7b35f86893556940e26482b4baf868
45,960
def poly_trace(m, a): """Compute the coefficients of the trace polynomial of (a*x) mod m.""" out = [0, a] for i in range(FIELD_BITS - 1): out = poly_sqr(out) while len(out) < 2: out += [0] out[1] = a poly_divmod(m, out) return out
37f9410a25baefe2cdc45c2b0854e126170509b9
45,961
def totalStatistics(totalData, saveLoc): """Plots the error in a combined box plot Input arguments: totalData = error data which is to be analysed saveLoc = where to save the image """ mean = np.zeros([10,36]) std = np.zeros([10,36]) index = 0 for _, dataSet in enumerate(totalDat...
08dfa2aa4aab4070176ce3c02b9e76fe5b7f07f9
45,962
def convert_examples_to_features(examples, tokenizer, max_seq_length, is_training): """Loads a data file into a list of `InputBatch`s.""" # RACE is a multiple choice task. To perform this task using Bert, # we will use the formatting proposed in "Improving Language # Un...
83ed688237cfdea776ba6d1898345900eb04b876
45,963
def binRV(time, rv, err=None, stat='wmean', tstat='wmean', estat='addquad', binning_indices=False, n_consecutive=None, consecutive_step=None, seed=None): """ Bin a dataset of radial-velocity observations. Parameters ---------- time : array The array of times where the radial...
de3fd853de5709dafd065ab1de3cb85933ce47ec
45,964
def get_secret(secret_id): """ Get a Secret from Secrets Manager. """ return secrets_client.get_secret_value(SecretId=secret_id)["SecretString"]
80a18b37e7e8245e17c583728fd0df815e581db6
45,965
def generate_mutation_tracker(old_attributes, new_attributes): """ Given old attributes of an entity and the new attributes in a Properties object, this method creates a new dictionary based on the whole old attributes dictionary, with: - the attributes in old_attributes updated with the attributes in ...
f9a7545c9c55ef0afcfbc99df139a3679548c7e5
45,966
from typing import Tuple import transformers import torch def build_model(model_name: str) -> Tuple[transformers.FeatureExtractionMixin, torch.nn.Module]: """ Builds the model given its name Args: model_name (str): The name of the ViT Returns: Tuple[transformers.FeatureExtractionMixi...
f9d17b614c5b8c24e5cb7f99bea15d214fc162f4
45,967
def verify_chassis_pic_exists_under_mic(device, mic, fpc, invert=False, max_time=60, check_interval=10): """ Verif...
574d75a58fffa1517d7d6067b73e0906038292b9
45,968
def selection_sort(lst): """This function will do a sort on a string of input.""" for i in range(len(lst)): if len(lst) == 0: return False min_position = i for j in range(i+1, len(lst)): if lst[min_position] > lst[j]: min_position = j temp...
7e963a4b6a1e04c07ecf8af34ca9c425e831629b
45,969
def transform(transformation_matrix, points): """ Does homographic transformation to points using given transformation matrix. See http://www.corrmap.com/features/homography_transformation.php https://wp.optics.arizona.edu/visualopticslab/wp-content/uploads/sites/52/2016/08/Lectures6_7.pdf """...
69c72c1a1df893274236221e3bfcc25ff63fda91
45,970
from typing import Optional from typing import Tuple from typing import List from typing import Iterable import os import itertools def load_rollouts_from_dir( ex_dir: str, key: Optional[str] = "rollout", file_exts: Tuple[str] = ("pt", "pkl") ) -> Tuple[List[StepSequence], List[str]]: """ Crawl through th...
fe2b4f5134c171d233f406275d9af2575eb42fc3
45,971
def TextureAddMemoryHints(builder, memoryHints): """This method is deprecated. Please switch to AddMemoryHints.""" return AddMemoryHints(builder, memoryHints)
71903073b3be48ca64158d0f2aa1c0ffb55dd049
45,972
def S_outlier_filter(_data_list, _factor=4): """ Returns data samples where data samples significantly greater than median are discarded. """ n_data = [] ds = len(_data_list) p_d = S_translate_to_positive_axis_values(_data_list) m_d = mining.S_median_sample_values(p_d) b_v = m_d[1] ...
5804f72e901007f2dd8fbe90a5a01066c7d37995
45,973
def get_default_palette(): """ Return the default color palette, which slightly tweaks the Digital Standards for better flexibility on light/dark backgrounds. """ palette = {} # the standard set of colors palette["blue"] = "#2176d2" palette["green"] = "#58c04d" palette["yellow...
2eb1239ad9fde6185b47732f3f2540a19ae54770
45,974
import os import plistlib import xml def _read_plist_file(root, file_name): """ :param root: The root path of the plist file :param file_name: The name of the plist file :return: An empty dictionary if the plist file was invalid, otherwise, a dictionary with plist data """ file_path = os.path...
4b76541a154736edad237c16830c9ba264833be7
45,975
from pydft.poisson import _Bj_dag_operator, _O_operator, _Bj_operator, _generate_r, _find_dr def _Vdual(s,R,V = None): """Finds the dual of the potential matrix. Args: s (list of int): The number of samples points along each basis vector. R (numpy.ndarray): The basis vectors fo...
42add3b413672d9019c7b68bcf864d5b4bfa7fa8
45,976
def iv(): """ The initialization vector to use for encryption or decryption. It is ignored for MODE_ECB and MODE_CTR. """ return chr(0) * 16
f38999b898427f5c6df124acd727744652d5db75
45,977
def build_inputs(data_params, input_context=None): """Returns tf.data.Dataset for sentence_prediction task.""" return data_loader_factory.get_data_loader(data_params).load(input_context)
5f7fee282dbee8ba5abb8bcee1de209793e9c468
45,978
def support_index(): """ Renders a page with the details on how to get support for the Wikimetrics project. """ return render_template('support.html')
c5a79dc6079056fa6613e56b1f049b735baac754
45,979
import functools def peak_count_hist(dat, bins=20, lim=None, neighborhood_size=5, threshold=0, log=True, mean=True): """Make the histogram of the peak count of data. Arguments --------- dat : input data (numpy array, first dimension for the sample) bins : number of bins for the histogram (defaul...
e45b33a41975d4abe99829e6db9c09865552e762
45,980
def url(value, allow_empty = False, allow_special_ips = False, **kwargs): """Validate that ``value`` is a valid URL. .. note:: URL validation is...complicated. The methodology that we have adopted here is *generally* compliant with `RFC 1738 <https://tools.ietf.org/ht...
9f7f0d7f828a393a3e5254ba023de0a6eb9f0d14
45,981
def get_indent(text): """Get text indentation. Args: text: Text to analyze. Returns: Number of leftmost spaces. Notes: Input text must be tab expanded, otherwise indent will be incorrect. """ return len(text) - len(text.lstrip())
5d5d53417f35f84bf48aa66fa8f35cf1930e77b7
45,982
from typing import Any import ray def ray_get_if_needed(obj: Any) -> Any: """If obj is an ObjectRef, do ray.get, otherwise return obj""" if isinstance(obj, ray.ObjectRef): return ray.get(obj) return obj
8f96360a46cf4269218ff52ab686b47915b092d4
45,983
def get_mark(name, task): """Getting marks of students for certain student and task""" return int(input('Mark for {}, task {} > '.format(name, task)))
00d8a0bf1ab97f600a3e6d2c8f488563419a95e1
45,984
def svn_opt_args_to_target_array3(*args): """ svn_opt_args_to_target_array3(apr_array_header_t targets_p, apr_getopt_t os, apr_array_header_t known_targets, apr_pool_t pool) -> svn_error_t """ return apply(_core.svn_opt_args_to_target_array3, args)
4cc49952b047e03bfd381cc2e0a79f7aa193b31f
45,985
def is_unary(s: str) -> bool: """Checks if the given string is a unary operator. Parameters: s: string to check. Returns: ``True`` if the given string is a unary operator, ``False`` otherwise. """ return s == '~'
1e04439c9b94032fe1291bccd41c4a845c0c18c8
45,986
def prior_current_next(iterable, pad=None): """" s -> (pad, s0, s1), (s0,s1,s2), ..., (sN-1, sN, pad). Aka 'prior, current, and next' elements in an iteration all at once. Lets you visit each element in an iterable while also being presented with the prior and next element...
e3d74ff4661802e5fe6804df12085ec43fd47b72
45,987
import unittest def test_suite(): """Test suite including all test suites""" testSuite = unittest.TestSuite() testSuite.addTest(test_listtools("test_unique")) testSuite.addTest(test_listtools("test_sort")) return testSuite
e75092af531885eb550b7fcc4fb07b25562c3878
45,988
def create_db_session(*, engine: Engine) -> scoped_session: """Broadly speaking, the Session establishes all conversations with the database. It represents a “holding zone” for all the objects which you’ve loaded or associated with it during its lifespan. """ return scoped_session( sessio...
004c896a2b75740e74f391c536cae0c839295cde
45,989
def to_html_dicts(*, indent='', open_icon='<i class="fa fa-square-o"></i> ', done_icon='<i class="fa fa-check-square-o"></i> '): """ Takes our todo list, and returns two dictionaries of where the keys equal to the project name, and the value is a string of the todo items for ...
7303920a2bab850f47bb7a642fcb9f3f1e257eb2
45,990
def select_locale(): """ Selects the locale. Babel uses this to determine which language to go with. """ try: if opt['VERBOSE']: print(session['LANG']) return session['LANG'] except Exception, ex: return opt['LANG']
0547d690acefb7b401e8deb94619645c39031875
45,991
def _format_line(k, v): """ Format a readable line. """ return "0x%08x: %20s --> %s\n" % (v.start, str(k), str(v))
46f77e43a695933b89987e854cd6c6d91d05c1db
45,992
import pymf # noqa def pick_device_id() -> int: """Tries to use a library to list video devices""" try: except ImportError: return 0 device_list = pymf.get_MF_devices() if not device_list: raise RuntimeError('No video devices found...') elif len(device_list) == 1: ret...
1b04259f94da00ae9d80bf203264d87f953c70f5
45,993
from datetime import datetime def feature_extraction(activity, location, word2vec_file): """feature extraction function giving word embedding, demographics, case no., weather and social dist. levels""" # initiate placeholder and progress bar bar = st.progress(0) placeholder = st.empty() # get...
7ac749fb0335b14a58cc9b1e1ca38d4fda66be35
45,994
def axialslices_plotting(value): """creates graphical objects for similarities at level1/2 for plotting purposes""" layout_plot = go.Layout(width=600, height=500, autosize=True, margin=go.layout.Margin(l=5, r=5, b=5, t=5, pad=0), scene=dict( ...
0f3959c5a463485140f0b35bffd59505b1f6a600
45,995
def get_sample_sheet_text(p7_index_length, p5_index_length): """ Gets the sample sheet text that will demux cells into one set of files """ sample_sheet_template = """[DATA] Lane,Sample_ID,Sample_Name,index,index2 %s""" line = ',fake,fake,%s,%s' % ('N' * p7_index_length, 'N' * p5_index_length) ...
6b9c04b7d353bfdf2067213ce197152fdf92f90b
45,996
def truncate_money(money: Money) -> Money: """Truncates money amount to the number of decimals corresponding to the currency""" amount = truncate_to(money.amount, money.currency) return Money(amount, money.currency)
dcbb4b239e491d84796f781d52335a476bc2ebab
45,997
def elephantblog_patterns(list_kwargs={}, detail_kwargs={}): """ Returns an instance of ready-to-use URL patterns for the blog. In the future, we will have a few configuration parameters here: - A parameter to specify a custom mixin for all view classes (or for list / detail view classes?) -...
e989871b7696096bd80118619da5a129fb18040e
45,998
def vadd(v1, v2): """ Add two 3 dimensional vectors. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vadd_c.html :param v1: First vector to be added. :type v1: 3-Element Array of floats :param v2: Second vector to be added. :type v2: 3-Element Array of floats :return: v1+v2 :r...
e89cc6d3b147ccfbbb9b5851181f9d2cba6e1de2
45,999