content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from datetime import datetime from typing import Optional from re import L def day_label(dt: datetime, *, now: Optional[datetime] = None) -> str: """Returns nice date label (today, Monday, 11.12.2013).""" if now is None: now = datetime.now if now.date() == dt.date(): return L(32327, 'Today...
900b7c2e787beea3877c4f5a5384d4776ce500e5
67,700
def combine_codon_labels(c1, c2): """ Combines codon labels, assuming bases mixed randomly Ex: AAA + CCC + GGG + TTT -> NNN = (AAA, AAC, ....) Ex: ABC + CCC --> MBC """ letters = [] for b1, b2 in zip(c1, c2): b1 = b1.upper() b2 = b2.upper() _ = DEGENERATE_NUCLEOTIDE_C...
6b9731e0fda82f6c46fe4edb9a00b1a6e6ff1bf0
67,701
import time import json def result_running_callback(request, context): # pylint: disable=unused-argument """ Callback function returning 'running' JSON. """ job_result_running = { 'status': 'running', } time.sleep(1) return json.dumps(job_result_running)
cb38b44b86cdcc96706dbf40a764d8d2059de449
67,702
def polylinear_gradient(colors, n): """Returns a list of colors forming linear gradients between all sequential pairs of colors. `n` specifies the total number of desired output colors. Code from http://bsou.io/posts/color-gradients-with-python """ # The number of colors per individual linear g...
305949f20f96899c003c61d77d58668332b57d23
67,703
import os import aiohttp import json from dateutil import tz from datetime import datetime def station(bot, mask, target, args): """ Show departures for station: 151213 (Leipziger Platz, Erfurt). The service URL is consumed by Erfurt Mobil (Android/iOS). A list of all known stations in the VMT area c...
246cafe19ff9fef7d902192c75b26ea801bf6dba
67,704
def applyXformToBounds(curXform, curBounds): """ Utility function to calculate the effect of an Xform (list of 16 values) to a bounds (list of 6 values) """ newBounds = None # loop through the 8 corners of the bounding box for ix, iy, iz in ( (0,2,4), (1,2,4), (0,3,4), (1,3,4), (0,2,5), (1,2,5),...
228520db56b75a2e831d7443e20bce461a121dcc
67,705
def _convert_to_binary_classification_predictions(predictions): """Converts a `Tensor` into a set of binary classification predictions. This function checks that the given `Tensor` is floating-point, and that it is trivially convertible to rank-1, i.e. has only one "nontrivial" dimension (e.g. the shapes [1000...
bd72f62ce793f398306161868c467fb8ae953fb5
67,706
import pandas as pd import os def pottery(path): """Chemical Composition of Pottery The data give the chemical composition of ancient pottery found at four sites in Great Britain. They appear in Hand, et al. (1994), and are used to illustrate MANOVA in the SAS Manual. (Suggested by Michael Friendly.) A da...
99d8c909bf55b3342d1984f2ed4246355b24bdcd
67,707
from typing import Union def value_counts_v2(s: Union[pd.Series, pd.DataFrame]) -> pd.DataFrame: """ Returns that normalised and unnormalised columns in value_counts() Useful when you want to know absoluoute number any percentage """ if isinstance(s, pd.Series): s = s.to_frame() df =...
3bb053499c42b0b70c6b11b52dadcc2725a36204
67,708
from datetime import datetime def months2days(nmon=288, baseyear=1992, basemon=1): """ This routine converts the mid-month time to days from January 1st of a particular year. Parameters ---------- nmon : dtype=integer number of months baseyear : dtype=integer year of time of...
d456eaec22c5d58a71a62e46631b7024cee3384a
67,709
import os import zipfile import xml.etree.ElementTree as ET def get_files_list(folderlist): """Gets a list of files from the arg folder and check for errors. Args: folderlist: the list of folder where the Lattes CV files are found. The Lattes CV files are downloaded as .zip files containin...
d8191746b2545111617b086f5f06a1fd2d4d2572
67,710
def run_defense_method(graph, method, k=3, seed=None): """ Runs a specified defense on an undirected graph, returning a list of nodes to defend. :param graph: an undirected NetworkX graph :param method: a string representing one of the attack methods :param k: number of nodes or edges to attack ...
186852827d5a8392986ccff3409d02bdc09e5311
67,711
def delta_S_2(psi_time, points, X, Y, ret_max=True): """ Short summary. Parameters ---------- psi_time : numpy.ndarray Description of parameter `psi_time`. points : list of two tuples Description of parameter `points`. X : numpy.ndarray Description of parameter `X`. ...
aed396051397436c950c90aa08696101f9c8d2ba
67,712
def fake_biblist(nb_codes): """ Generate a list of fake bibcodes :param nb_codes: number of bibcodes to generate :return: list of bibcodes """ bibcodes = [] for i in range(nb_codes): bibcodes.append(fake_bibcode()) return bibcodes
586ff939c50d07491dd0cc7466ff77cfaba1b2a6
67,713
def scalar_summary(tags, values, collections=None, name=None): # pylint: disable=line-too-long """Outputs a `Summary` protocol buffer with scalar values. This ops is deprecated. Please switch to tf.summary.scalar. For an explanation of why this op was deprecated, and information on how to migrate, look ['h...
cb169a9af97074d30ce096ed087c5398945b5421
67,714
def compute_convergence_data(f, u, t_final, dts, scheme, num_steps, error_idx=None, fixed_coefficients_twice=False, **kwargs): """ Compute the numerical errors obtained by the LMM `scheme` which uses `num_steps` previous step/derivative values for th...
cc904eb9ecd33266816b813b43ebd952cc40e9cb
67,715
def closeMap(): """ 类型:z_关闭地图 说明: close map 参数: test: 模版参数 desc: 描述方法操作功能,更具体的展示在测试报告 返回: False True """ r_v = AT.RunCommand(command="adb shell am force-stop com.baidu.naviauto",timeout="100") AT.sleep(sleepTime="200") ...
1650ab56bbfc89bf7327b6500e3bdaf0ac64e3a4
67,716
def filter_counts_by_interactions(counts: pd.DataFrame, interactions: pd.DataFrame, suffixes: tuple = ('_1', '_2'), counts_data: str = 'ensembl') -> pd.DataFrame: """ Removes counts if is not defined in interactions components """ genes = interactions['{}{}'.format(coun...
a57c8f482001186c6d269ddfcd80261644510158
67,717
def load_sentiment_data(): """ Load the data set :return: data_set """ data_set = list() download_data_if_not_yet() words_ids = dict(get_word_dict()) for sample_file in sort_files(): words_list = list() category = 0 if 'neg' in sample_file else 1 for word ...
43b7b829d6f87cccb45f3f2df24b075d27761b76
67,718
def ready_branched_dummy_context(branched_dummy_context, dummy_dataframe): """Get dummy ready by placing a dummy dataframe at every input edge node.""" print("ready branched") for dataset in branched_dummy_context.pipeline.inputs(): d = getattr(branched_dummy_context.catalog.datasets, dataset) ...
3cc4eef20f282f9128affc0638a4c8ad0ce14730
67,719
def get_ellipse_focus_add_by_standard_equation(a11, a12, a22, a1, a2, a0): """ a11 = 1/a^2 a22 = 1/b^2 a12 = a1 = a2 = 0 a0 = -1 """ if a11 < a22: a11_1 = 1 / a11 c = sqrt(a11_1 - 1 / a22) return [[c, 0], [-c, 0], 2 * sqrt(a11_1)] a22_1 = 1 / a22 c = sqrt(a22_...
85bce9536519787570bbc65c2854fd098954fadd
67,720
import requests from bs4 import BeautifulSoup def pullWksaCountryPages(): """Scrapes the WKSA schools website for the list of countries WKSA has locations in.""" KSW_SCHOOLS_PAGE = 'http://www.kuksoolwon.com/site/schools' r = requests.get(KSW_SCHOOLS_PAGE) schools_page = BeautifulSoup(r.text, 'lxml') ...
ee242319a7ad990827e61a99be6093959ebe2097
67,721
import struct def get_system_bits(): """Return 32 for 32-bit systems and 64 for 64-bit""" return struct.calcsize("P") * 8
252d5acab4dec512df238031f89c072129485959
67,722
def validateSubSequence(array, sequence): """ ### Description validateSubSequence -> validates if a sequence of elements is a subsequence of a list. ### Parameters - array: the list where it will validate the subsequence. - sequence: the potential subsequence of elements ...
ae780814e6f0ce59b21acb46cd272443bd2a5f92
67,723
import asdf def read_table(filename, data_key=None, find_table=None, **kwargs): """ Read a `~astropy.table.Table` object from an ASDF file This requires `asdf <https://pypi.org/project/asdf/>`_ to be installed. By default, this function will look for a Table object with the key of ``data`` in the...
a9457b17653213412389f453a23237e48c204f75
67,724
def _cleanse_dict(original): """Strip all admin_password, new_pass, rescue_pass keys from a dict.""" return dict((k, v) for k, v in original.items() if "_pass" not in k)
2691cc31f127548f5dc0693a0f117dad0b6139dd
67,725
def FPs(names, fpsort, ctx=None): """Return an array of floating-point constants. >>> x, y, z = FPs('x y z', FPSort(8, 24)) >>> x.sort() FPSort(8, 24) >>> x.sbits() 24 >>> x.ebits() 8 >>> fpMul(RNE(), fpAdd(RNE(), x, y), z) fpMul(RNE(), fpAdd(RNE(), x, y), z) """ ctx = _...
660674f5ef4a07dfa057ae30a3d618ca01bae49e
67,726
def calc_mode(sample_list): """ Calculate mode from continuous samples. Parameters ---------- sample_list : list or numpy array Returns ------- mode : float """ hist_freqs = np.histogram(sample_list, bins="auto")[0] hist_edges = np.histogram(sample_list, bins="auto")[1] ...
c7c6d6274aa9680912e0793288a4c3c9d67ae6ce
67,727
import collections def pretty_recursive(value, htchar="\t", lfchar="\n", indent=0): """ Recursive pretty printing of dict, list and tuples - full creadit to: http://stackoverflow.com/questions/3229419/pretty-printing-nested-dictionaries-in-python """ nlch = lfchar + htchar * (indent + 1) if...
2538337ed0711bcf60040dc0f4112ea01184fabb
67,728
from datetime import datetime def process_weighted_time_avg(procstatus, dscfg, radar_list=None): """ computes the temporal mean of a field weighted by the reflectivity Parameters ---------- procstatus : int Processing status: 0 initializing, 1 processing volume, 2 post-processing ...
ec2edc41fedcde3755996c71821a379ec23c5468
67,729
import os def create_app( name="doku", config=None, minimal=False, test=False, additional_config=None ) -> Flask: """ App Factory - create_app This is the doku Flask app factory :param name: Name of the application. Defaults to ``doku`` :param config: Pythonic path (``path.to.module``) for t...
0372de865c0d1275f87f7ef6482f76e22e23a8d9
67,730
import urllib def _get_authorize_url(client_id, response_type, state=None): """ 認可のためのURLを取得 :param client_id: ClientID :param response_type: code or token :param state: CSRFトークン :return: 認可するためのURL :rtype: str """ payload = {'client_id': client_id, 'response_type': res...
99086aec415174b48b850acdfd16b79f91086955
67,731
def format_knot_hash(value, format_spec): """ >>> format_knot_hash([64, 7, 255], '02x') '4007ff' >>> format_knot_hash(bytearray.fromhex('A0C20170'), '08b') '10100000110000100000000101110000' """ return "".join(format(h, format_spec) for h in value)
2a12f299807bcc6606a00092faecf1b34ec32170
67,732
def mazziotti_opdm_purification(opdm, trace_target): """ Mazziotti purification of the 1-RDM in Phys. Rev. E. 65 026704 i) set all negative eigenvalues to zero ii) correct the trace by decreasing the HOMO iii) set all eigenvalues >1 to 1 iv) correct the trace by increasing the LUMO :param ...
a170c58fbbe0bfa459a4cb0c6278662092429b85
67,733
from typing import Tuple import torch def get_mean_std(loader: DataLoader) -> Tuple: """Calculates mean and standard deviation of a dataset taken from the given DataLoader.""" cnt = 0 ds_mean = torch.empty(3) ds_std = torch.empty(3) for data in loader: b, c, h, w = data.shape n...
b6123a6fbf4d86a3139715e92e7251ef2ae43ede
67,734
def profiler(fname,scans=None, data_type=None, datetime_format=None, num_info_lines=5, check_na=['SPD','DIR'],na_values=999999, height_name='HT', read_scan_properties=False, verbose=False): """Wind Profiler radar with RASS ...
d291cb5839bbb9006aff048c87247a3aa0b7665e
67,735
def angle(v1, v2=None): """Compute angle between 2D vectors v1 and v2. If v2 is not specified it will default to e1 (the unit vector in the x-direction) The angle is measured as a number in [0, 2pi] from v2 to v1. """ # Prepare two numeric vectors if v2 is None: v2 = [1.0, 0.0] # ...
84e8105323809d55eb40af9cff102ebbe45a57bc
67,736
import os def delete_orphaned_document_files(): """ Deletes orphaned files of deleted documents. """ deleted = [] _, files = storage.listdir(os.path.join("documents", "document")) for filename in files: if Document.objects.filter(doc_file__contains=filename).count() == 0: ...
a4ecf0e176d223149138cd8d0cbe47919a6a2681
67,737
def read_gtf(f, full=True, as_df=False, nrows=None, duplicate_attr=False): """Read files in the Gene Transfer Format. Parameters ---------- f : str Path to GTF file. as_df : bool, default False Whether to return as pandas DataFrame instead of PyRanges. nrows : int, default ...
c596e402b0f387aae60265f8beca3f0ce136c138
67,738
from typing import Tuple def predict(model, data, tokenizer, label_map, batch_size=1): """ Predicts the data labels. Args: model (obj:`paddle.nn.Layer`): A model to classify texts. data (obj:`List(Example)`): The processed data whose each element is a Example (numedtuple) object. ...
5c2475b79ec104331d4654171d76ac8f9fd8b6cf
67,739
from typing import Optional import logging async def create_model(item: Optional[param] = None): """ the user submit a json object that contain all the details needed to create and train a model :param item: :return: """ if item is None: return {"name cannot be empty"} else: ...
e985b7747d562b3fe16f98762f68e545588283f8
67,740
def unmarshal_object(swagger_spec, object_spec, object_value): """Unmarshal a jsonschema type of 'object' into a python dict. :type swagger_spec: :class:`bravado_core.spec.Spec` :type object_spec: dict :type object_value: dict :rtype: dict :raises: SwaggerMappingError """ deref = swagge...
a16c70649a70ed7b89a357503f06e312ae0f46d8
67,741
def upvote_question(current_user, question_id): """Endpoint to upvote a question""" error = "" status = 200 response = {} question = db.get_single_question(question_id) if not question: error = "That question does not exist!" status = 404 elif db.upvote_question(current_use...
c294e2e81c7d3623bf984c35179514489a27bc42
67,742
import logging def create_logger(args): """ 将日志输出到日志文件和控制台 """ logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(levelname)s - %(message)s') # 创建一个handler,用于写入日志文件 file_handler = logging.FileHandler( fil...
fec4665020ee2d5e8d1103ba4d2ebb7bf26679fa
67,743
from typing import Union import torch def update_lr( scheduler: Union[lr_scheduler.StepLR, lr_scheduler.LambdaLR, lr_scheduler.ReduceLROnPlateau, lr_scheduler.CosineAnnealingLR, lr_scheduler.CyclicLR], optimizer: optimizer.Optimizer, metric: torch.Tensor = None ) -> float: """Update learning rate ...
b11c6a5a49758554a7e1062d7f65da1543896678
67,744
import os def modelIterator(initial=0, final=1000, data_dir=cn.BIOMODELS_DIR, zip_filename=cn.BIOMODELS_ZIP_FILENAME): """ Iterates across all models in a data directory. :param int initial: initial file to process :param int final: final file to process :param str data_dir: absolute path of the ...
b5e8e04089fcd9c1f651c3667bbf73a67a13a6ca
67,745
def load_clean_captions(filename, dataset): """为图像标题首尾分别加上'startseq ' 和 ' endseq', 作为自动标题生成的起始和终止 Args: filename: 文本文件,每一行由图像名,和图像标题构成, 图像的标题已经进行了清洗 dataset: 图像名list Returns: dict, key为图像名, value为添加了'startseq'和'endseq'的标题list """ # load document doc = load_doc(filename...
5477c5e0ce972d42a1bb79d0c4b44b58b66db832
67,746
def get_python_packages_info(path, python_version="3"): """Get details about all python packages in an image filesystem. :param path: path were the docker image filesystem is expanded. :type path: string :param python_version: version of python to use. can be "2" or "3". default to "3". :type p...
515ff6c517e11d08f11e18b59ddfd921695e144e
67,747
def compute_intersection_length(A, B): """Compute the intersection length of two tuples. Args: A: a (speaker, start, end) tuple of type (string, float, float) B: a (speaker, start, end) tuple of type (string, float, float) Returns: a float number of the intersection between `A` and...
6cf038e1febbc1a7aa19eb104f5628ff2f935174
67,748
import random def Move(src, label, pad_color, max_move_ratio=0.2): """ item = { "img_name":save_name, "keypoints":save_keypoints, relative position "center":save_center, "other_centers":other_centers, "other_keypoints":other_keypoints, ...
5517b76215ed836d02f496e969fe072c8831e125
67,749
import subprocess def cygwinSafePath(path): """If the system is Cygwin, converts the given Cygwin path to a Windows path; this does nothing if not Cygwin""" if isCygwin(): cmdLine = ['cygpath', '-w', path] printCmdLine(cmdLine) return subprocess.check_output(cmdLine).strip() else: return path
5aab8d9591c5e46963244b5d57711501de95d760
67,750
import copy def pcc_slower1(circ, supp, verbose=False): """ Args: circ(list(list(tuple))): Circuit supp(list): List of integers Returns: list(list(tuple)): Past causal cone of supp """ circ_rev= circ[::-1] circ_reduced = [] supp_temp = copy.deepcopy(supp) for u...
4f02c0db839456dc91b508b89b4d343d7c02beb0
67,751
import os def read_dem(bounds, res): """ Function to read in a DEM from SRTM amd interplolate it onto a dolphyn mesh. This function uses the python package 'elevation' (http://elevation.bopen.eu/en/stable/) and the gdal libraries. I will assume you want the 30m resolution SRTM model. :param boun...
236db47674d96a5e9729f6c7f650276624e37882
67,752
import socket def bindsocket(port, host=''): """ Creates a socket assigned to the IP address (host, port). Parameters ---------- port : int port assigned to the socket. host : str, optional host assigned to the socket. The default is ''. Returns ------- tcpsock : ...
48be29952a3d35af0ec0886e3ca332f9280384f1
67,753
def _absolute_clustering(data, group_pop_var, total_pop_var, alpha=0.6, beta=0.5, metric='euclidean'): """ Calculation of Absolute Clustering index Parameters ---------- ...
4e80f6397f2b2f2c44039c6d517b0675c9ced3ed
67,754
def toText(p, alreadyLabeled=None): """Render a pattern as human-readable text. :type p: titus.P :param p: the pattern :type alreadyLabeled: set of strings or ``None`` :param alreadyLabeled: used to avoid recursion in recursive types :rtype: string :return: text representation of the patter...
602cd3caee485f235f4d6b1f4d774c81b34a0249
67,755
import re def _yesno(message, default='no', suffix=' '): """Modified from github.com/tylerdave/prompter to reduce depenencies. All credit to the creator.""" if default == 'yes': yesno_prompt = '[Y/n]' elif default == 'no': yesno_prompt = '[y/N]' else: raise ValueError("defa...
f66bdf51fd79deb9ccba52f426a691361c9c6993
67,756
def get_intersection(y_true, y_pred): """ aka TP, assuming binary images that were removed the background """ return K.sum(K.sum(K.squeeze(y_true * y_pred, axis=3), axis=2), axis=1)
d965c17d5f321fd4913997170d362d05863192ff
67,757
def MAD_outliers(data: pd.Series) -> pd.Series: """Detect outliers use MAD based method and return a binary index Detect outliers we can use robust method based on median absolute deviation ( Page 19, Data Cleaning, 2019 ): >> ... the median and the median absolute deviation (MAD) that can replace mean an...
bf22e1d3884811f7f974df53b0ffffd053728e65
67,758
def create_java_app_env(deployment_config): """ Returns the environment variables Java application servers uses. Args: deployment_config: A DeploymentConfig object. Returns: A dictionary containing the environment variables """ env_vars = {'APPSCALE_HOME': APPSCALE_HOME} gcs_config = {'scheme': 'h...
fc4ab2bd4c714cfdf17a9144d82afd09eda9b4ae
67,759
from datetime import datetime def date(): """ Return formatted date Parameters ---------- None Returns -------- None """ today = datetime.today() month = today.strftime("%B") day = today.day year = today.year date = f"{month} {day}, {year}" return date
c28eb0b89d524d9856cb18a53004a34278011e90
67,760
def _BroadcastMul(vec, mat): """Multiply after broadcasting vec to match dimensions of mat. Args: vec: A 1-D tensor of dimension [D0] mat: A 2-D tensor of dimension [D0, D1] Returns: A tensor of dimension [D0, D1], the result of vec * mat """ # Reshape vec to [D0, 1] vec = array_ops.expand_dim...
fedf209bdfc23838bc70a38aa1dce49816a1bad6
67,761
def broadcast_global_variables(root_rank): """Used to broadcast global variables""" variables = backend._get_variables(backend.get_graph()) candidate_vars = [] for v in variables: if getattr(v, "_keras_initialized", False): candidate_vars.append(v) op_list = [] if candidate_v...
7ea68f3f973325c33440de3d6c3507d5a88a805b
67,762
import json import logging def output(post, quiet=False, use_test_node=False, diagnostic=False, urls_only=False) -> int: """Prints out the post and extracts the custom_json""" data = json.loads(post.get("json")) if diagnostic: logging.info( ...
31f3e977d47d44ed6b9ec45d171cbe9cfecb7ed9
67,763
def rainbow_nums(freq, i): """create rgb values for part of a rainbow""" rgb = [] for channel in range(3): rgb.append(max(0, min(5, int(6 * (sin(2 * pi * (freq * i + 0.333 * channel)) / 2 + 0.5))))) return rgb
d163296b1dbf53218a730082379159de94f8853b
67,764
def local_ordering(circuit, weighted=True, verbose=False): """Permute qubit labels so that two-qubit gates are as local as possible. Parameters: circuit (qiskit.QuantumCircuit): An input quantum circuit. weighted (bool): Using weighting method. verbose (bool): Print values and plot ...
bf6d0404edc11d2321b9ede1822116972a2d46af
67,765
def _job_substring_match(search_string, job_name): """Return a bool on whether a string exists in a provided job name or use from environment if available (case insensitive).""" job_name = job_name or get_value('JOB_NAME') if not job_name: return False return search_string in job_name.lower()
8d056fcff3408736d5d13401cfb7f77380ca3594
67,766
def raw(func, **func_args): """Decorator for eager functions checking input array and stripping away the weld_type. Stripping the weld_type is required to keep the same code in Series.apply and because Numpy functions don't (all) have kwargs. Passing weld_type to NumPy functions is unexpected and r...
92b10d3ea54f3c0f8c0e4204c37371fca66be09e
67,767
def nanmean(x): """Average value of the array a, ignoring 'Not a Number' elements""" if not hasattr(x,"__len__"): return x x = asanyarray(x) valid = ~isnan(x) return sum(x[valid])/sum(valid)
2272021953e665278899ba00b8967e4dc30cc3dd
67,768
import os def get_filepath(date, data_source='data'): """Renvoie le filepath d'un fichier donné Args: date (string): string contenant la date sous le format {jour}{Mois abbrégé} -> exemple : 7Nov Returns: string """ return os.path.join(data_source, f'data...
27456a7a49c56d11d76ce63c5e043fcc94cdac27
67,769
from datetime import datetime import six def obj2str(i, force_detailed=False): """Returns a human-readable ascii string representation of a model instance, even in some edge cases. """ if not isinstance(i, models.Model): if isinstance(i, (int, IncompleteDate)): return str(i) # Au...
72a16f25e27528f8bab638c5317570a877d52569
67,770
import urllib def facebook_authorize(request): """ Obtain authorization for Graph API access. If code exists in request.GET, then we should be good to move on to Step 3 and exchange the code for an access token. Otherwise, send the user to Facebook to grant access to our app. """ site = S...
27aaa3009c20a970fe70763d98639cfa6f894947
67,771
def is_video(video): """ Checks that `file` is a video file. `video` is cv.VideoCapture object. """ return video.get(cv.CAP_PROP_FRAME_HEIGHT) != 0
366a52d6bc40286efa2483dd36ac9098ef0197a1
67,772
from torchvision.models.resnet import resnet152 def resnet152(pretrained=False, fixed_feature=True): """ "ResNet-152 model from torchvision's resnet model. :param pretrained: if true, return a model pretrained on ImageNet :param fixed_feature: if true and pretrained is true, model features are fixed whil...
e172a833e3d38b9692a3a55bd4961a5444c54187
67,773
def draw_text(img, y, x, text, color=(0, 255, 0), size=25): """ Draw text on an image. This uses by default DejaVuSans as its font, which is included in this library. dtype support:: * ``uint8``: yes; fully tested * ``uint16``: no * ``uint32``: no * ``uint64``: no ...
d27b5146fc70621b65b3f214599dc7b86c7d1f29
67,774
import six def _UnitsByMagnitude(units, type_abbr): """Returns a list of the units in scales sorted by magnitude.""" scale_items = sorted(six.iteritems(units), key=lambda value: (value[1], value[0])) return [key + type_abbr for key, _ in scale_items if key]
972a17b51901a133444ddb77989c4ebc372fc35e
67,775
def index(): """View root page function that returns index page and the various news sources""" title = 'Home- Welcome to the best News source page' # Getting the news sources news_sources = get_sources('sources') return render_template('index.html', title=title, news_sources=news_sources)
ee31a6f0a70cff1d057389a9c402e5d6498e23d0
67,776
def download_link(youtube_url: str, directory_path: str, audio_format: str = "wav") -> str: """ Downloads a track from the given youtube_url into the given directory_path :param youtube_url - the URL to a youtube video containing the audio file to download :param directory_path - the path to a local direct...
bc0cdec17bc5cee9d436dba790fda937832afd1e
67,777
def calc_I_MacDonald2014(TEMP): """ Temp. (C) to Macdonald2014 parameterised [iodide] in nmol/dm^-3 (nM) """ # Parameterisation is Arrhenius expression # y= 1.46E6 * exp(-9134.0/TEMP(K)) * 1E9 # NOTE: temp. is converted from degC to DegK return (1.46E6 * np.exp((-9134.0 / (TEMP+273.15))))*1E...
be929814a5f9b23c5789a9decbbe080dc215e0f8
67,778
def get_payload(job): """Construct payload for SqoopJob -> Genie 2.""" return Genie2Adapter.construct_base_payload(job)
d0af452837af02a82a2a4b5f95935b5d1106da5a
67,779
def replace_toffoli_with_alt(qasm): """ Replace all Toffoli gates (including parallelized ones) by their alternative representation. See src.grover.search_utilies.alternative_toffoli for more details. Args: qasm: The full qasm program that contains Toffoli gates to replace Returns: The sam...
2afda126a975c11f13e8f1fd71b73c2621dad032
67,780
def make_rpc_name(name: str) -> str: """ Convert python compatible name to Transmission RPC name. """ return name.replace("_", "-")
057f1446f230dac93a09661e4eeb27edb09fda62
67,781
async def document_convert_to_base64(encoding, the_file): """this function convert a pdf file to base64 format""" with open(the_file, 'rb') as open_file: byte_content = open_file.read() base64_bytes = b64encode(byte_content) base64_string = base64_bytes.decode(encoding) return base64_stri...
50b697c346ba46468543cdc317d6a643a3c26fed
67,782
def get_model_layers(model): """Returns all layers of a model.""" ret = [] def collect_layers(container): for layer in container.layers: assert layer not in ret ret.append(layer) if kchecks.is_network(layer): collect_layers(layer) collect_laye...
e3675dcaa3f7cb73543e6187f6cf06da68943b8c
67,783
def splitList(listToSplit, num_sublists=1): """ Function that splits a list into a given number of sublists Reference: https://stackoverflow.com/questions/752308/split-list-into-smaller-lists-split-in-half """ length = len(listToSplit) return [ listToSplit[i*length // num_sublists: (i+1)*length ...
1a22fcb061a6fce6a2971e277ecc94251e0a2011
67,784
def create_reader(reader_name, input_shape, is_multi_task, task_map_id, *gens): """ build reader for multi_task_learning """ placeholder = Placeholder(input_shape) pyreader, model_inputs = placeholder.build(capacity=16, reader_name=reader_name) joint_generator = create_joint_generator(input_shap...
04fb537882957e5d40a9460709acddd82751f54f
67,785
import subprocess from distutils import spawn import tempfile import time from pdf2image import convert_from_path from PIL import Image import logging as logger def to_text(path, language='fra'): """Wraps Tesseract 4 OCR with custom language model. Parameters ---------- path : str path of ele...
287bde030530c6f2bbca82b3d6320594c052b926
67,786
from dvc.fs.memory import MemoryFileSystem def _get_staging(odb: "ObjectDB") -> "ReferenceObjectDB": """Return an ODB that can be used for staging objects. Staging will be a reference ODB stored in the the global memfs. """ fs = MemoryFileSystem() fs_path = _make_staging_url(fs, odb, odb.fs_pat...
aafff52be65ede1dc011ecc2061d2cd5055a659e
67,787
def _block_array_reduction_wrapper(func): """Wraps a reduction (eg sum, norm) to allow for joint operation on `DeviceArray` and `BlockArray`""" @wraps(func) def wrapper(inp, *args, axis=None, **kwargs): all_args = (inp,) + args + tuple(kwargs.items()) if any([isinstance(_, BlockArray) ...
8353aff2a764c080f1709bcbc205579f238f5c6f
67,788
import functools import traceback def check_workchain_step(func): """ Decorator for workchain steps that logs (and re-raises) errors occuring within that step. """ @functools.wraps(func) def inner(self, *args, **kwargs): try: return func(self, *args, **kwargs) except Ex...
d6e5834b233075fbb1097a84f7e3010c3f292194
67,789
from app import main, admin def create_app(config_name): """ 创建flask的应用对象 :param config_name: str 配置模式的模式的名字 ("develop", "product") :return: """ app = Flask(__name__) # 根据配置模式的名字获取配置参数的类 config_class = config_map.get(config_name) app.config.from_object(config_class) # 使用app...
ee4c817b4c02e4dc4ae10ea5b95a81fdf94a687d
67,790
import json def kibana_api_request(url, method='GET', filename=None): """Kibana API request.""" data = {} if filename: curl_url = "curl -X%s %s -T %s" % (method, url, filename) else: curl_url = "curl -X%s %s" % (method, url) print_color_text(curl_url, MAGENTA) opener = urlli...
e44df7402f90ca9fe661d1f4597c3173e6eb083a
67,791
import inspect def worker_factory(service_cls, **injections): """ Return an instance of ``service_cls`` with its injected dependencies replaced with Mock objects, or as given in ``injections``. **Usage** The following example service proxies calls to a "math" service via and ``rpc_proxy`` inject...
ca0082472c866b512be45553ac2f9866dd6f3c1c
67,792
from typing import Optional from typing import Dict from typing import Any def values_to_numpy(data: Optional[Dict[Any, Any]]) -> Optional[Dict[Any, Any]]: """Replaces all tensorflow-tensor values with their numpy versions. Args: data: Any dictionary for which values should be converted. Returns...
b2546f78517b04711a9301feaf65d2ccc055302b
67,793
def naive_r(augend, addend): """A recursive definition of addition. (http://en.wikipedia.org/wiki/Addition#Natural_numbers) """ if addend == 0: return augend return inc(naive_r(augend, dec(addend)))
ea801ec069a0c4a86d9b18837bb3dc369edbff0a
67,794
import scipy def lqr(A, B, Q, R): """Solve the infinite-horizon, discrete-time LQR controller x[k+1] = A x[k] + B u[k] u[k] = -K*x[k] cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k] # Arguments: A, B: Linear system matrices Q, R: State and input penalty matrices, both positiv...
d300ba4bbdb612ff4410fc1f320ad9825f9aa9d3
67,795
import scipy def get_gray_imgs_fn(file_name, path): """ Input an image path and name, return an image array; if RGB images, then mode = 'RGB'.""" # return scipy.misc.imread(path + file_name).astype(np.float) return scipy.misc.imread(path + file_name, mode='L')
d2dc0c8b8b098fc5b7cd8cfb2ebdf11f511a81d6
67,796
def file_url(repo_name, rev, path): """ Forges Github URL to a blob in a repo (through branch or commit rev). :param str repo_name: Github repository name such as 'Author/Repo' :param str rev: branch, commit or tag :param str path: the path to the file :return: URL :rtype: str """ r...
f9d85c3ffed30c3e6edc0d61b5fbffc9100e33ce
67,797
from typing import Callable from typing import Tuple def cross_validate(estimator: BaseEstimator, X: np.ndarray, y: np.ndarray, scoring: Callable[[np.ndarray, np.ndarray, ...], float], cv: int = 5) -> Tuple[float, float]: """ Evaluate metric by cross-validation for given estimator Para...
3ed043290a8839fa31ff0d684a6b05f27c61863d
67,798
import sys def read_all_files(filename_dict, readin_dict , verbose=False,logfile=None, record_contributor=True): """ INPUT: filename_dict is dictionary of files names, sorted by file type readin_dict is a list of corrections and column renames, etc. by filename OUTPUT: All files merged into a Pandas Da...
cc08fb1f7806581137b78cb47a75304c0a2b0fc3
67,799