content
stringlengths
22
815k
id
int64
0
4.91M
def get_buckets(rdd, buckets): """Extracted from pyspark.rdd.RDD.histogram function """ if buckets < 1: raise ValueError("number of buckets must be >= 1") # filter out non-comparable elements def comparable(x): if x is None: return False if type(x) is float and i...
5,310,700
def dollo_parsimony(phylo_tree, traitLossSpecies): """ simple dollo parsimony implementation Given a set of species that don't have a trait (in our hash), we do a bottom up pass through the tree. If two sister species have lost the trait, then the ancestor of both also lost it. Otherwise, the ancestor has the trait....
5,310,701
def localtime(t=None): """ localtime([seconds]) -> (tm_year,tm_mon,tm_day,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst) Convert seconds since the Epoch to a time tuple expressing local time. When 'seconds' is not passed in, convert the current time instead. Modified to accept timestamps before t...
5,310,702
def test_list_unsigned_int_max_length_2_nistxml_sv_iv_list_unsigned_int_max_length_3_2(mode, save_output, output_format): """ Type list/unsignedInt is restricted by facet maxLength with value 7. """ assert_bindings( schema="nistData/list/unsignedInt/Schema+Instance/NISTSchema-SV-IV-list-unsigned...
5,310,703
def _to_bytes(str_bytes): """Takes UTF-8 string or bytes and safely spits out bytes""" try: bytes = str_bytes.encode('utf8') except AttributeError: return str_bytes return bytes
5,310,704
def tile_num(fname): """ extract tile number from file name. """ l = os.path.splitext(fname)[0].split('_') # fname -> list i = l.index('tile') # i is the index in the list return int(l[i+1])
5,310,705
def extract_hidden_image(merged_image_path, mesg_image_path, secret_key): """ Unmerge an image. INPUT: The path to the input image. OUTPUT: The extracted hidden image. """ merged_img = Image.open(merged_image_path) message_image = Image.open(mesg_image_path) # Create the new image and l...
5,310,706
def get_earliest_tables_last_updated_date(database_name: str, tables: Tuple[Tuple[str, str]]): """ Return the earliest of the last updated dates for a list of tables in UTC. """ with connections[database_name].cursor() as cursor: cursor.execute( """ SELECT MIN(modified_da...
5,310,707
def check_nested_model(required_attribute_type: str) -> bool: """ Takes the properties of a required attribute on a model and searches as to whether or not this attribute requires a model of its own Parameters ---------- required_attribute_type : str The type of the required attribute ...
5,310,708
def save_image(image_numpy, image_path, aspect_ratio=1.0): """Save a numpy image to the disk Parameters: image_numpy (numpy array) -- input numpy array image_path (str) -- the path of the image """ image_pil = Image.fromarray(image_numpy) h, w, _ = image_numpy.shape i...
5,310,709
def precision_and_recall(actual, predictions): """ Given predictions (an N-length numpy vector) and actual labels (an N-length numpy vector), compute the precision and recall: https://en.wikipedia.org/wiki/Precision_and_recall Hint: implement and use the confusion_matrix function! Args: ...
5,310,710
def _insert_special_message(body): """Troll mode on special day for new pull request.""" tt = datetime.utcnow() # UTC because we're astronomers! dt = timedelta(hours=12) # This roughly covers both hemispheres tt_min = tt - dt tt_max = tt + dt # See if it is special day somewhere on Earth ...
5,310,711
def determine_host(environ): """ Extract the current HTTP host from the environment. Return that plus the server_host from config. This is used to help calculate what space we are in when HTTP requests are made. """ server_host = environ['tiddlyweb.config']['server_host'] port = int(serv...
5,310,712
def _createUtilityMenuItems(node): """ Create node item marking menu items specific to utility nodes """ pass
5,310,713
def gen_rand_sys(size): """ generate a grid with input size """ # Initialize grid with size grid = np.zeros(shape=(size, size), dtype=int, order='F') # Randomize grid randomize_sys(grid) # return the generated table return grid
5,310,714
def __get_size__(filename): """ Parses the filename to get the size of a file e.g. 128M+12, 110M-10 """ match = FILE_REGEX.search(filename) if match: size_str = match.group('size') si_unit = match.group('size_si') shift = __get_shift__(match) mul = 1 if si...
5,310,715
def _assign_X(k, number_of_months, BT, PX1, PX2, PX3, X): """ Assign X values using backtracking. :param k: number of months to backtrack :param number_of_months: ? :param BT: backtracking array ...
5,310,716
def dbinfo(db, *patterns, **kw): """Gets types and lengths of keys matching given patterns. If any pattern is a list, then assumes it's a list of keys. Else, assumes it's a string and expands out using db.keys(). If no patterns are given, then processes all keys. The lengths are defined by redis ty...
5,310,717
def store_d_html_text_single(data, prefix='./webpage/'): """ Get the dynamical html text for given urls and store them. Input: data - list of [id, url] """ service_args=[] service_args.append('--load-images=no') ##关闭图片加载 service_args.append('--disk-cache=yes') ##开启缓存 driver = webdriver...
5,310,718
def fe7_runesword(unit: ActiveUnit, arena: ActiveArena, combat: CombatData): """ Replaces the unit's Mag modifier with its initial value. """ skill: Skill = Skill.objects.get(id=711) skill_data: SkillData = SkillData.objects.get(arena=arena, unit=unit, skill=skill) unit.mod_mag = skill_data.data...
5,310,719
def clean(ctx): """ Clean DB""" ctx.run('''docker run --rm --net={net} -v logs:/tmp/{app}/\ -e CLEAN_DB=True \ {img}:latest \ sh -c "python service/main.py"'''.format(app=APP_NAME, net=NETWORK, img=APP_IMG))
5,310,720
def main(connection, info, args) : """Registers the sender with sonicbot""" if connection.users["users"][info["sender"]]["userlevel"] == 1 : salt = connection.gensalt() connection.users["users"][info["sender"]] = {"salt":salt,"password":hashlib.sha512(args[1]+salt).hexdigest(), "hostname":[conne...
5,310,721
def load_data(filename: str) -> pd.DataFrame: """ Load city daily temperature dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (Temp) """ df = pd.read_csv(filename, parse_dates...
5,310,722
def document_entity_generator(*ehrpreper_files): """Generator of DocumentEntity""" return ( document for ehrpreper_file in ehrpreper_files for model in load(ehrpreper_file) for document in model.documents )
5,310,723
def showApp(firstArg=None,dataframe=None,filenames=[]): """ The main function to start the data frame GUI. """ app = MyWxApp(False) frame = MainFrame() # Optional first argument if firstArg is not None: if isinstance(firstArg,list): filenames=firstArg elif isinsta...
5,310,724
def readCSV(filepath): """ Method that reads a list of values from a CSV file Parameters: filepath (str): The path of the CSV file Returns: values (list): The list of values """ values = [] with open(IP_LIST, "rt", encoding="ascii") as f: reader = cs...
5,310,725
def smooth_voxels(voxels, padding_vox=10, sigma=2): """ TODO: smoothing params and padding should be in um padding_vox: zero padding to apply to kernals to ensure that smoothing doesn't go over edges voxels: binary voxel mask sigma: std dev for gaussian """ # pad voxels voxels_padded = ...
5,310,726
def test_1d_rtree(): """Testing the rtree ctypes wrapper""" tree = rtree.RTreeCreateTree(-1, 0, 1) for i in range(10): rect = rtree.RTreeAllocRect(tree) rtree.RTreeSetRect1D(rect, tree, float(i - 2), float(i + 2)) rtree.RTreeInsertRect(rect, i + 1, tree) rect = rtree.RTreeAll...
5,310,727
def calc_gamma(data: np.ndarray) -> Tuple[str, int]: """Return a tuple consisting of binary form/string and decimal of gamma value.""" n = np.array([len(data)] * len(data[0]), dtype=int) ones = np.count_nonzero(data, axis=0) zeros = n - ones gamma_bin = ''.join(map(str, (ones > zeros).astype(int))) ...
5,310,728
def test_stream_contains_unsupported_properties_by_bulk(stream_config, stream_api_v2): """ Stream `Account` contains compound field such as BillingAddress, which is not supported by BULK API (csv), in that case REST API stream will be used for it. """ stream_name = "Account" stream = generate_st...
5,310,729
def read_messages(message_file): """ (file open for reading) -> list of str Read and return the contents of the file as a list of messages, in the order in which they appear in the file. Strip the newline from each line. """ # Store the message_file into the lst as a list of messages...
5,310,730
def find_outliers(data, threshold=3.5): """ Function to remove outlier data, based on the median absolute deviation from the median. Note that the function supports asymmetric distributions and is based on code from the included reference Parameters ---------- data: Pandas Series-li...
5,310,731
def main(): """ main method """ cursor = connections['default'].cursor() if sql: cursor.execute(sql) if txt: f = open (txt,"r") text = f.read() cursor.execute(text) f.close() for obj in dictfetchall(cursor): #for obj in cursor.fetchall(): ...
5,310,732
def result_message(iden, result=None): """Return a success result message.""" return { 'id': iden, 'type': TYPE_RESULT, 'success': True, 'result': result, }
5,310,733
def _smesolve_single_trajectory(data, L, dt, tlist, N_store, N_substeps, rho_t, A_ops, e_ops, m_ops, rhs, d1, d2, d2_len, dW_factors, homogeneous, distribution, args, store_measurement=False, ...
5,310,734
def check_user_dir(g): """ Check directories exist for saving apps/configs etc. Create if not. """ dirs = [os.path.expanduser('~/.hdriver')] if 'app_directory' in g.cpars: dirs.append(os.path.expanduser(g.cpars['app_directory'])) if 'log_file_directory' in g.cpars: dirs.append(os...
5,310,735
def setup_authorized_keys(ssh_fingerprint, script_path, pubkey): """Sets up an authorized_keys file to redirect SSH commands""" authorized_keys = join(environ['HOME'], '.ssh', 'authorized_keys') if not exists(dirname(authorized_keys)): makedirs(dirname(authorized_keys)) # Restrict features and ...
5,310,736
def reconstruction_error(S1, S2): """Do Procrustes alignment and compute reconstruction error.""" S1_hat = compute_similarity_transform_batch(S1, S2) return S1_hat
5,310,737
def main(): """ Purpose: Read an .avro File """ logging.info("Starting Process") cli_args = get_cli_arguments() logging.info("Process Complete")
5,310,738
def encode_bboxes(boxes): """[This function processes rectangles from Azure API and converts it to cv2.polylines format] Args: boxes ([list]): [list of x, y coordinates of rectangles] Returns: [list]: [np.array of formatted for use with cv2.polylines function call] """ polygon...
5,310,739
def mask2coco(npmasks, img_id, coco_dict): """ Convert ndarray masks to COCO json file """ images = { "license": 1, "coco_url": "", "date_captured": "", "flickr_rul": "", "id": img_id, "height": npmasks[0].shape[0], "width": npmasks[0].shape[1], ...
5,310,740
def createTokenFromCredentials(body): """ Given a request body with a username and a password, generates a JWT access token or returns an error response. """ valid = False try: user: User = User.objects(username=body["username"]).get() valid = user.validatePassword(body["password...
5,310,741
def map_model_to_images(folder_model, path_datatests, batch_size=1, gps=0.1, crop_value=25, gpu_per=1.0): """ Apply one trained model to all the specified images """ # Load config with open(os.path.join(folder_model, 'config_network.json'), 'r') as fd: config_network = json.loads(fd.read())...
5,310,742
def makeFile(f, d): """ makeHHPFile(f, d): f = file path to make d = data to be added Purpose - Makes Contents.hhc, Index.hhk and Bootstrap.hhp file """ copyanything(f, 'build\\' + f) p = 'build\\' + f fptr = open(p, 'r') data = fptr.read() fptr.close() data = data + '\n' + d fptr = open(p, 'w') fptr...
5,310,743
def upload_forecast_batch(conn, json_io_dict_batch, forecast_filename_batch, project_name, model_abbr, timezero_date_batch, overwrite=False): """ Uploads a batch (list) of JSON dictionaries to the model corresponding to the args. This only iterates through timezeros, not models or ...
5,310,744
def count_team_forecasts_draw(team_id): """ count the number of draw forecasts for a team """ request = """ SELECT COUNT(*) FROM season_forecast, season_fixture WHERE season_forecast.fixture_id = season_fixture.id AND ( (season_fixture.team_a_id = '%(team_id)s' AND season_forecast.s...
5,310,745
def get_args(): """Add custom knn arguments.""" parser = extraction_argument_parser() parser.add_argument("-k", "--knearest", type=int, default=5, help="When using a knn classifier, this is the number " "of neighbors to check. " "Defaul...
5,310,746
def start_xql_query_polling_command(client: Client, args: dict) -> Union[CommandResults, list]: """Execute an XQL query as a scheduled command. Args: client (Client): The XDR Client. args (dict): The arguments to pass to the API call. Returns: CommandResults: The command results. ...
5,310,747
def forward_0018(apps, schema): """ Given the BadLine objects in the DB, create BadLineRange objects, collapsing runs of errors into single objects. This *loses information* - we don't store the actual bad line for every original BadLine object, only the first in each run. """ BadLine =...
5,310,748
def preprocess(path): """Transform the 3D image to 2D slices, do normalization and save.""" all_folders = os.listdir(path) flair = [] dwi = [] seg = [] cnt = 0 for folder in all_folders: folder_individual = path + '/' + folder + '/' all_data_individual = os.listdir(f...
5,310,749
def change_main_address_column(df: gpd.geodataframe.GeoDataFrame) -> gpd.geodataframe.GeoDataFrame: """ Changing the main address column for building gdf :param df: modified gdf (address column changed) """ # Dropping cadaste address from df df.drop(c.adr_main, inplace=True, axis=1) # Renaming...
5,310,750
def send_message(bot, message): """Отправляет в Telegram сообщение.""" try: bot.send_message( chat_id=CHAT_ID, text=message ) except telegram.error.TelegramError as error: raise SendMessageError(ERROR_SENDING_MESSAGE.format(error)) else: logging.in...
5,310,751
def _RunInApp(function, args, kwargs): """Executes a set of Python unit tests, ensuring app.really_start. Most users should call basetest.main() instead of _RunInApp. _RunInApp calculates argv to be the command-line arguments of this program (without the flags), sets the default of FLAGS.alsologtostderr to Tr...
5,310,752
def _ToGypPath(path): """Converts a path to the format used by gyp.""" if os.sep == '\\' and os.altsep == '/': return path.replace('\\', '/') return path
5,310,753
def hello_world1(): """ Flask endpoint :return: TXT """ return "Hello World From App 1!"
5,310,754
def vpt2(prog, output_str): """ Reads VPT2 information from the output string. :param prog: electronic structure program to use as a backend :type prog: str :param output_str: string of the program's output file :type output_str: str """ return pm.call_module_function( ...
5,310,755
def learning_rate_schedule(current_epoch, base_learning_rate, lr_boundaries, lr_multiplier): """Handles linear scaling rule, gradual warmup, and LR decay. The learning rate starts at 0, then it increases linearly per epoch. After 5 e...
5,310,756
def cradmin_titletext_for_role(context, role): """ Template tag implementation of :meth:`django_cradmin.crinstance.BaseCrAdminInstance.get_titletext_for_role`. """ request = context['request'] cradmin_instance = request.cradmin_instance return cradmin_instance.get_titletext_for_role(role)
5,310,757
def to_unicode_for_identify(hash): """convert hash to unicode for identify method""" if isinstance(hash, unicode): return hash elif isinstance(hash, bytes): # try as utf-8, but if it fails, use foolproof latin-1, # since we don't really care about non-ascii chars # when runni...
5,310,758
def url_to_path(url: URL) -> Path: """Convert a file:// URL into a UNIX path.""" return Path(url.path)
5,310,759
def ver_notas(request): """Ver notas de investigaciones o documentos""" form_elegir = BuscadorInvestigacionesForm(request.user) form_crear = NotaForm() context = { 'form_elegir':form_elegir, 'form_crear': form_crear, "title":'Notas de investigaciones', ...
5,310,760
def training_config(estimator, inputs=None, job_name=None, mini_batch_size=None): """Export Airflow training config from an estimator Args: estimator (sagemaker.estimator.EstimatorBase): The estimator to export training config from. Can be a BYO estimator, Framework estimator or...
5,310,761
def stft(sig, fs=16000, win_type="hann", win_len=0.025, win_hop=0.01): """ Compute the short time Fourrier transform of an audio signal x. Args: x (array) : audio signal in the time domain win (int) : window to be used for the STFT hop (int) : hop-size Returns: X ...
5,310,762
def parse_problem_statement(problem_code: str): """ This function takes a Leet Code problem code as input and scrapes the problem statement from the site and returns the parsed problem statement as a text file. PARAMETERS: ----------- problem_code: string LeetCode problem co...
5,310,763
def get_raising_file_and_line(tb=None): """Return the file and line number of the statement that raised the tb Returns: (filename, lineno) tuple """ if not tb: tb = sys.exc_info()[2] filename, lineno, _context, _line = traceback.extract_tb(tb)[-1] return filename, lineno
5,310,764
def get_name(): """ should return the name of the tool as listed on http://qcomp.org/competition/2020/""" return "PET"
5,310,765
def gabby_gums_dark_green() -> Colour: """A convenience function that returns a :class:`Colour` with a value of 0x508787 (R80, G135, B135).""" # discord.Color.from_rgb(80, 135, 135)) return Colour(0x508787)
5,310,766
def compute_average_oxidation_state(site): """ Calculates the average oxidation state of a site Args: site: Site to compute average oxidation state Returns: Average oxidation state of site. """ try: avg_oxi = sum([sp.oxi_state * occu f...
5,310,767
def est_dans_collection(collection, numero): """ Teste si le puzzle dont le :numero: est fourni en paramètre fait partie de la collection dont le nom est donné dans le paramètre :collection: :param collection: Nom de la collection considérée :param numero: Numéro du puzzle recherché dans la c...
5,310,768
def lookup_zones(output_file=None,opts=None): """ This data source provides a list of available zones in the current region. > This content is derived from https://github.com/terraform-providers/terraform-provider-ucloud/blob/master/website/docs/d/zones.html.markdown. """ __args__ = dict() ...
5,310,769
def PyDict_Next(space, w_dict, ppos, pkey, pvalue): """Iterate over all key-value pairs in the dictionary p. The Py_ssize_t referred to by ppos must be initialized to 0 prior to the first call to this function to start the iteration; the function returns true for each pair in the dictionary, and false ...
5,310,770
def load_point_cloud(filename, min_norm_normal=1e-5, dtype=torch.float64): """ Load a point cloud with normals, filtering out points whose normal has a magnitude below the given threshold. :param filename: Path to a PLY file :param min_norm_normal: The minimum norm of a normal below which we discard a p...
5,310,771
def cos(x, offset=0, period=1, minn=0, maxx=1): """A cosine curve scaled to fit in a 0-1 range and 0-1 domain by default. offset: how much to slide the curve across the domain (should be 0-1) period: the length of one wave minn, maxx: the output range """ value = math.cos((x/period - offset) *...
5,310,772
def get_terms(num_distinct_documents=500, remove_stopwords=False, stopwords=[',', '.', '-', '\xa0', '“', '”', '"', '\n', '—', ':', '?', 'I', '(', ')']): """ Creates TermGenerator, and parses the documents for a specific set of documents. :param num_distinct_documents: (int) Passe...
5,310,773
def iswritable(pathname): """Is file or folder writable?""" from os import access,W_OK return access(pathname,W_OK)
5,310,774
def get_args(): """Get arguments from CLI""" parser = argparse.ArgumentParser( description="""Given a LASTZ input directory, find matches, add flank, and return a FASTA file of sequences""") parser.add_argument( "conf", action=FullPaths, type=is_file, ...
5,310,775
def cli(argv: List[str], renderer: Renderer, commands: Dict[str, Command]): """ Command Line Interface Handles the incoming console input. :param argv: Raw list of arguments. :param renderer: The renderer service to print messages. :param commands: The list of available commands. :return: ...
5,310,776
def calc_crossproduct_flow(vU,vV,btU_in,btV_in,elev,bt_depth,mtime): """ Calculates the discharge(flow) by finding the cross product of the water and bottom track velocities. **elev and bt_depth are positive** Inputs: vU = U velocity, 2D numpy array, shape [ne,nb] {m/s} vV = V ve...
5,310,777
def reverse_mutation(perm, *args): """ Performs a reverse mutation on a permutation """ n = len(perm) - 1 i = np.random.choice(n, 1)[0] perm[i:i+2] = perm[i:i+2][::-1] return perm
5,310,778
def Send(filename, data): """Sends python data to a shell file. Args: filename: The shell file to send to. data: The python data to send. """ with open(filename, 'wb') as f: pickle.dump(data, f)
5,310,779
def extraire_reunions(fichier, afficher): """ Retourne des structures contenant la liste des réunions/organisateurs et des participants Vérifie au passage la présence de valeurs inhabituelles dans les champs """ organisateurs = {} participants = {} lecteur = csv.reader(fichier) lignes = lis...
5,310,780
def MTL_loss(device, batch_size, ndata=0, contrastive_loss=False): """Returns the learned uncertainty loss function.""" # task_rot = LearnedLoss('CrossEntropy') task_contrastive = LearnedLoss('Contrastive', batch_size=batch_size) task_recons = LearnedLoss('L1') task_NCE = LearnedLoss('NCE', nda...
5,310,781
def non_commutative_sympify(string: str): """Evaluates sympy string in non-commutative fashion. This function was taken from stack overflow answer by @ely https://stackoverflow.com/a/32169940 """ parsed_expr = parse_expr(string, evaluate=False) new_locals = { sym.name: Symbol(sym.name,...
5,310,782
def parse_last_name(name_string): """ isolates last name in a name string extracted from a record args: name_string: str, entire name returns: last_name: str, with removed diactritics and in uppper case; may include value of subfield $b """ try: last_na...
5,310,783
def debug_test(project_dir, board_manager_script, verbose_level): """ Run tests without compilation, flushing and target resetting for debugging purposes. """ _log_app_envvar(verbose_level) from vznncv.mbed.greentea._test_runner import debug_test ret_code = debug_test( project_dir=projec...
5,310,784
def generate_neighbours(pattern: str, mismatches: int) -> set: """ Generate neighbours for the given pattern (genome string) :param pattern: genome pattern :param mismatches: number of mismatches to generate neighbours :return: a set of patterns in the neighbourhood, including the 'pattern' itself ...
5,310,785
def head_pose_preprocess(imgs): """ Preprocesses the image(s) and face detections for the head pose estimator. Parameters ---------- imgs: NumPy array The image(s) to format with values in the range [-1, 1]. Returns ------- input_hp: NumPy array Formatted image(s). ...
5,310,786
def dataset_input_put(id, dataset): # noqa: E501 """Submits data to the framework # noqa: E501 :param id: ID of the data source :type id: str :param dataset: Dataset submitted to the framework :type dataset: dict | bytes :rtype: None """ if connexion.request.is_json: try...
5,310,787
def _regularize_20m_dataset(temp_dir): """ ratings.csv Each line of this file after the header row represents one rating of one movie by one user, and has the following format: userId,movieId,rating,timestamp - The lines within this file are ordered first by userId, then, within user, by movie...
5,310,788
def two_sum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): mid = target - nums[i] for j in range(i + 1, len(nums)): if nums[j] == mid: return [i, j]
5,310,789
def filter_useful_paths_into_a_dataframe(path_list): """ Classifies the file types of the paths we actually care about then finegles them into a DataFrame. """ print("Gathering metadata.") paths_we_actually_care_about = [path for path in path_list if filetype_of(path) != "unsorted"] subjects =...
5,310,790
def do_cv(opts): """ """ df = pandas.read_csv(opts["-c"], index_col=None, header=None) y, X = df[0], df[1] X_tfidf, X_vocab = sentiment.make_tfidf_matrix(X, toarray=opts["-d"]) X_tfidf = sklearn.preprocessing.scale(X_tfidf.toarray()) clf = sentiment.make_clf(opts["-C"], opts["<param>"]) ...
5,310,791
def pivottab(d, rowkey, columnkey, reducefn, duplicates=False): """ A simple pivot table generator based on 2 key indexes and a reduce function Parameters ---------- d: dict like structure data container (SimpleTable or DictDataFrame) rowkey : str Values to group by in the rows ...
5,310,792
def paseto_required(): """ """ def wrapper(func): @wraps(func) def decorated_view(*args, **kwargs): if not hasattr(current_app, "paseto_verifier"): raise ConfigError("paseto_verifier is not set in the current_app.") if not current_paseto.is_verified: ...
5,310,793
def mean_of_list(list_in): """Returns the mean of a list Parameters ---------- list_in : list data for analysis Returns ------- mean : float result of calculation """ mean = sum(list_in) / len(list_in) return(mean)
5,310,794
def delazi(lat1, lon1, lat2, lon2): """delazi(double lat1, double lon1, double lat2, double lon2)""" return _Math.delazi(lat1, lon1, lat2, lon2)
5,310,795
def create_datastore_client(): """Creates a Client, to connect to the Datastore DB.""" os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = config.GCP_CREDENTIALS client = datastore.Client(project=config.GCP_PROJECT) print("Connected to cloud Datastore database, GCP project", config.GCP_PROJECT) return cl...
5,310,796
def preliminary_register_user(): """Администратор может добавить предопределенного пользователя (студента или преподавателя) """ answer = blank_resp() try: if current_user.status != 'admin': raise Exception('Only admins can do preliminary registration') form = PreliminaryRe...
5,310,797
def read_markers_gmt(filepath): """ Read a marker file from a gmt. """ from collections import OrderedDict ct_dict = OrderedDict() with open(filepath) as file_gmt: for line in file_gmt: values = line.strip().split('\t') ct_dict[values[0]] = values[2:] return c...
5,310,798
def num_decimal_part(value: float) -> float: """Return the decimal part of a floating point number. Parameters ---------- >>> num_decimal_part(-2.1) -0.1 >>> num_decimal_part(2.1) 0.1 """ return value - num_truncate(value)
5,310,799