content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def R1g(): """ """ A = Ugde(b,t1)*Uedg(b,t1+t2)*Ugde(a,t1+t2+t3) return evaluate_cumulant(A, positive_times=(t1, t2, t3), leading_index=a, arrays=["gg"])
9e56df51ab2ff7bdbaf1304b2e8b3a0c471e250b
46,900
import numpy def calc_raster_sum(raster_path): """Return the sum of the values in raster_path.""" nodata = pygeoprocessing.get_raster_info(raster_path)['nodata'][0] raster_sum = 0.0 for _, raster_array in pygeoprocessing.iterblocks((raster_path, 1)): raster_sum += numpy.sum( raster...
29bcc0ad6645907851f658bb7209391d11e5339f
46,901
def schema_maker(db, meta): """ create a Schema class with db bind :param db: :param meta: dict key value in class Meta :return: """ # meta["db"] = db meta = make_meta(meta) return NewSchemaMeta("BaseSchema", (BaseSchema,), dict(Meta=meta, db=db))
6ed34911c2396d0f1fec98bb6a7f1d8697fe512d
46,902
def kpc_comoving_per_arcmin(z, cosmo=None): """ Separation in transverse comoving kpc corresponding to an arcminute at redshift `z`. Parameters ---------- z : array_like Input redshifts. Returns ------- d : astropy.units.Quantity The distance in comoving kpc corresponding t...
639e84cee46811f1cfcd02656cde482601ac66ee
46,903
import logging def standard_run(args): """ High-level function to run a standard analysis Args: :args: (obj) Instance of form 'StdRunArgs' Returns: :results: (dict) Results from static analysis """ # ===== Logging ===== hlogger.init(log_filename="log.txt", level=args) ...
d82e780349f2d24844d75da8ce71008f5af16217
46,904
import os def get_plot_savepath(file_name, extension=".pdf"): """Get savepath for some result of the evaluation named `file_name`.""" savedir = get_plot_savedir() return os.path.join(savedir, f"{file_name}{extension}")
8848bd46665b04fcaef0db036a59b5c33bb31a90
46,905
import glob import os import json def find(parameter, value, identifier_pattern): """ Finds all locally registered peripherals that match parameter=value :param parameter: name of the parameter to search for :param value: value of that parameter :param identifier_pattern: regex expression to limit th...
9b201ba4b3bbbbf2de059d72e3c46447c545c779
46,906
import logging def debug_logger(output_filename="debug.log"): """Logger for printing time-stamped messages, DEBUG and higher, to file.""" debugfile_logger = logging.getLogger("debugfile_logger") debugfile_logger.setLevel(logging.DEBUG) debugfile_logger_handler = logging.FileHandler(output_filename, mo...
5d96b71a23c63d50dad00c353dcf2bb191fc43a6
46,907
def unbox_interval(typ, obj, c): """ Convert a Interval object to a native interval structure. """ lo_obj = c.pyapi.object_getattr_string(obj, "lo") hi_obj = c.pyapi.object_getattr_string(obj, "hi") data_obj = c.pyapi.object_getattr_string(obj, "_arr") interval = cgutils.create_struct_proxy(...
cd24282f73353095d0bb72e4b654e6563ffc5728
46,908
import time def findBranchByScanBusCk(mirror, ScanBus, Ck): """Return mirror bus object if possible""" tic = time.time() # required to use find functions during mirror creation before searchDict made if not mirror.branchDict: for branch in mirror.Branch: if branch.ScanBus == ScanB...
ec1ef604061b09359dcb25916987484dbe6f26c1
46,909
def serialize_index_binary(index): """ convert an index to a numpy uint8 array """ writer = VectorIOWriter() write_index_binary(index, writer) return vector_to_array(writer.data)
3f4bf9f5cf44cb7b69b2d060721182bcad93c00e
46,910
def aggregate_all_tables(table_list, max_number=1000): """ Examples -------- >>> table = Table({'a': [1, 2], 'b': [5, 6]}) >>> newt = aggregate_all_tables([table])[0] >>> len(newt) 2 >>> np.all(newt['a'] == table['a']) True >>> np.all(newt['b'] == table['b']) True """ ...
8e01c374e673040acff0f788f3cc7d370848038e
46,911
def pop(snippet, N): """ >>> pop('abc') ['abc'] >>> pop('abc+def') ['abc', 'def'] >>> pop('abc$def+ghi') ['abc+def', 'ghi'] """ def replace(s): for s1, s2 in reversed(list(zip(SEPARATORS[N+1:], SEPARATORS[N:]))): s = s.replace(s1, s2) return s return [...
5b800664eda7bc811fa7a070a625ede50abb0020
46,912
def validate_metadata(metadata, parameters): """validate metatdata. Ensure metadata references parameter workload_context, and that it is a string. Return error message string or None if no errors. """ for value in metadata.values(): if isinstance(value, dict): if "get_param"...
177a1133bacd9e7560be9604cd03542eaf5944ff
46,913
def id2name(query, tchs, gi): """ convert id number to name """ if query.isdigit() is True: if gi is True: if query in tchs['gi2taxid.tch']: taxid = tchs['gi2taxid.tch'][query] else: query = 'n/a' else: taxid = query ...
b59a50002f989cf98ca3bd83d4494325c6a84cfb
46,914
import json def open_json_catalog(): """Loads local CMIP6 JSON intake catalog""" data = json.load(open("cmip_catalog.json")) return data
ce47d3de71a2227d4ea3cc49c3332959a4c0a279
46,915
import torch def quaternions_to_so3_matrix(q): """Normalises q and maps to group matrix.""" q = q / q.norm(p=2, dim=-1, keepdim=True) r, i, j, k = q[..., 0], q[..., 1], q[..., 2], q[..., 3] return torch.stack( [ r * r - i * i - j * j + k * k, 2 * (r * i + j * k), ...
7b48bc7176a462497e64671fe8a204a9942c301c
46,916
import functools def _recursive_guard(fillvalue='...'): """ Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs Decorates a function such that if it calls itself with the same first argument, it returns `fillvalue` instead of recursing. Largely copied from reprlib.recursi...
5ae23b61aadea4192c5b77624ad6a85cce0577b1
46,917
def canConnectPins(src, dst): """**Very important fundamental function, it checks if connection between two pins is possible** :param src: Source pin to connect :type src: :py:class:`PyFlow.Core.PinBase.PinBase` :param dst: Destination pin to connect :type dst: :py:class:`PyFlow.Core.PinBase.PinBas...
55152859dc0eaae0ee296a0c74029138761dc04f
46,918
def is_document_public(document: dict) -> bool: """ checks whether document `visibility` and `revisionState` match requirements to be considered ready for publication. :param document: couchdb document :returns: whether visibility and revision state qualify for publication """ if document.get("...
ccef67cab34eb6833a526de03b6a6872d4b31a1a
46,919
from sys import path def read_pom_input(): """ Description: Opens forcing files reading the paths specified in the pom_input namelist. :return: data arrays for wind stress, surface salinity, solar radiation, inorganic suspended matter, salinity and temperature vertical profiles, general cir...
fb708cbed1595815e5194fb03ca61affb5818f5d
46,920
def raises(exception_type): """Make a matcher that checks that a callable raises an exception. This is a convenience function, exactly equivalent to:: return Raises(MatchesExceptionType(exception_type)) See `Raises` and `MatchesExceptionType` for more information. """ return Raises(Matche...
fe37de39a9cdc6bf3972fe3384d857735a493cd4
46,921
def relu(Z): """ RELU activation function Arguments: Z -- numpy array Returns: A -- output of rulu(Z) cache -- Z, useful for back propagation """ A = np.maximum(0, Z) return A
1c1d7523c5af9b61ef6f733dda21a91452f9eb14
46,922
import os def get_cache_path(split): """Gets cache file name.""" cache_path = os.path.join(os.path.dirname(__file__), "../../../data/mini-imagenet/mini-imagenet-cache-" + split + ".pkl") return cache_path
ee822a1a1940e61189513dd100693c60ec6f2e4b
46,923
def flux(component): """Determine flux in every channel Parameters ---------- component: `scarlet.Component` or array Component to analyze or its hyperspectral model """ if hasattr(component, "get_model"): model = component.get_model() else: model = component re...
b95b0aa926ee2cc2c78e90c425b47f04bc0a4d4c
46,924
def get_current_vistrail(): """get_current_vistrail(): Returns the currently selected vistrail. """ return get_current_controller().vistrail
8fa39968ad1dc78bc72de49b804463c82f1747e9
46,925
from typing import Dict from typing import Type from typing import Any def wrap_components( container: ServiceContainer, ) -> Dict[str, Type]: """ Wrap component rendering with a partial to gain access to container """ # Get all the components, from the container components: Dict[str, Any] =...
b071f3bcb61b617bb38b6ad0941ae9b48884b3ac
46,926
def curl(url): """ Test URL, return http code """ try: return urllib2.urlopen(url, timeout=30).getcode() except urllib2.HTTPError as e: return e.fp.getcode() except Exception: logger.exception("unknown error") return 0
928ca0e15a38794a029301c44bfdae83aea43ef3
46,927
import _ast def BinOpMap(operator): """Maps operator strings for binary operations to their _ast node.""" op_dict = { '+': _ast.Add, '-': _ast.Sub, '*': _ast.Mult, '**': _ast.Pow, '/': _ast.Div, '//': _ast.FloorDiv, '%': _ast.Mod, '<<': _ast.LShift, '>>': _ast...
0b332b1043b31b123daf8812e6f2ecb4e3974f19
46,928
from datetime import datetime def get_cgi_dates(form): """ Figure out which dates are requested via the form, we shall attempt to account for invalid dates provided! """ y1 = int(form.get("year1")) m1 = int(form.get("month1")) d1 = int(form.get("day1")) y2 = int(form.get("year2")) m2 = int...
f1971aac5798f46c03a93c1afb86606fd9495234
46,929
def is_current_game_state(handler_input, state): """Check the current game state""" return handler_input.attributes_manager.session_attributes['game_state'] == state
a06e661408ca560d53ed15679af07dbb535744f0
46,930
import logging import click def verbosity_option(**kwargs): """Adds a -v/--verbose option to a click command. Parameters ---------- **kwargs All kwargs are passed to click.option. Returns ------- ``callable`` A decorator to be used for adding this option. """ def...
9c0b6bc24a5ba7af935237ec82f946be1aa85d07
46,931
def get_garmin_client(): """ General access point for getting an authenticated Garmin Connect session. Returns ------- session : Garmin Connected Garmin Connect API object """ # 1. If an email / password is stored, attempt to login with the credentials while True: try: ...
fc4c83eb2cefd956059c60b53273207d4659dd13
46,932
def logout(): """退出登录""" logout_user() return redirect(url_for('backend.login'))
6a7274de86edcc34dceba1ebe42c59a75bfcc12a
46,933
def patient_details(id): """Display the full patient details form for an existing user.""" check_patient_permission(id) patient = Patient.query.get(id) form = ( get_unsaved_form(request, patient, 'patient_details', PatientForm) or PatientForm(obj=patient) ) if request.method == ...
16d455a837d05840f4e042dc5be348bfaba6a229
46,934
def version(): """Return current package version.""" with open("demo/version/A-major", "rt") as f: major = f.read().replace("\n", "") with open("demo/version/B-minor", "rt") as f: minor = f.read().replace("\n", "") with open("demo/version/C-patch", "rt") as f: patch = f.read().re...
f6180cd34edd57b523470d203505172eea28b51e
46,935
def schedule_binarize_pack(outs): """Schedule for binarize_pack Parameters ---------- outs: Array of Tensor The computation graph description of binarize_pack in the format of an array of tensors. Returns ------- sch: Schedule The computation schedule for the op...
975f18d5ce25db140774ff7b9d4f1d54524db72f
46,936
import io def stream_result_fixed(input_query: InputFixedQuery, authorization: str = Header(None), processor: Processor = Depends(get_processor)): """ Create result set of data with temporality type fixed, and stream result as response. """ log.info(...
b45343f9811232d1d30b5ee171e9aae5d8d7f12f
46,937
import regex def html_to_text(html_text): """Strip html_text tags from string and return a plain plain_text version.""" strip_tags = regex.compile(r"<.*?>") eol_tags = regex.compile(r"</p>") return strip_tags.sub("", eol_tags.sub("\n", html_text))
e85ce9f7a5119145ed8209fe4fc0be6b0019f221
46,938
import PureNcclCommunicator def create_multi_node_optimizer(actual_optimizer, communicator, double_buffering=False): """Create a multi node optimizer from a Chainer optimizer. Args: actual_optimizer: Chainer optimizer (e.g., ``chainer.optimizers.Adam``). ...
24f242859747f35ff7f3e052f5074115f1fc24ab
46,939
def extract_title_from_text(text: str) -> str: """Extract and return the title line from a text written in Markdown. Returns the first line of the original text, minus any header markup ('#') at the start of the line. """ firstline = text.split('\n', 1)[0] return firstline.lstrip('# ')
c51c7dd517b7d50a50df472d055618a092bb3518
46,940
def _all_pairs(i, contextsize, arrlen): """ i: index in the array contextsize: size of the context around i arrlen: length of the array Returns iterator for index-tuples near i in a list of size s with context size @contextsize. Context of k around i-th index means all substrings/subarrays...
7234e7b092e60c74d4f1c0af44a469c25cc34dc9
46,941
def swatch_masks(width, height, swatches_h, swatches_v, samples): """ Returns swatch masks for given image width and height and swatches count. Parameters ---------- width : int Image width. height : height Image height. swatches_h : int Horizontal swatches count. ...
19838ccffd49973ff646e0cb460a9da5c38ec44f
46,942
import itertools import numpy def generate_features(landmark_coords): """Generate features from landmarks.""" key_points = [18, 22, 23, 27, 37, 40, 43, 46, 28, 32, 34, 36, 5, 9, 13, 49, 55, 52, 58, 61, 63, 65, 67] combinations = itertools.combinations(key_points, 4) point1 = [] p...
4971cdf20548e9adc41fd3c22dd8e86ef63dded3
46,943
def create_path_complete_condition(transmit_node_pairs): """ This factory allows us to specify that there are valid directed paths between pairs of nodes. This returns a function that takes an graph argument (G) and verifies that for the list of node pairs the graph meets those dependency conditions. ...
fd8b9e081d9b7da93f56dc58fd1055d8e11f3822
46,944
def percentformat(x, pos): """ Generic percent formatter, just adds a percent sign """ if (x==0): return "0%" if (x<0.1): return ('%4.3f' % (x)) + "%" if (x<1): return ('%3.2f' % (x)) + "%" if (x<5): return ('%2.1f' % (x)) + "%" return ('%1.0f' % x) + "%"
382f9760e26a31c6ddcdf8a58600fa5010dcba1e
46,945
def is_hexagonal(hexag: int): """any tn in triangle sequence is t = ½n(n+1): Solving with quadratic formula reveals n is only an integer if (1+8t) ** 0.5 is an integer and odd""" if int((1+8*hexag)**0.5) == (1+8*hexag)**0.5 and ((1+8*hexag)**0.5)%4 == 3: return True return False
521ca4e7f87c54651ff3f4a59266fdd4cc2d869e
46,946
def get_fashion_mnist_labels(labels): """返回Fashion-MNIST数据集的文本标签。 Defined in :numref:`sec_fashion_mnist`""" text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot'] return [text_labels[int(i)] for i in labels]
a477522b679eb129cae7800c57a2a4fda6246284
46,947
def bufferParser(readbuffer, burst=16): """ Parse concatenated frames from a burst """ out = b'' offset = 1 while len(readbuffer) > 0: length = readbuffer[2] if readbuffer[4] == offset: out += readbuffer[5:3+length] offset += 1 readbuffer = readbuffe...
a3a7eb312f9e9c0e9a2183960074ebd1e9925025
46,948
import json def aaa_load_profile(): """ this function load the account which will be used as cookie """ account = Account(ES) return Response(json.dumps(account.load_account_profile(request.args.get("email"))))
3651278b1d4ff37896a4ca153933133974db76aa
46,949
def _pairwise_non_aligned_corr(g1: BaseEstimator, g2: BaseEstimator, attr: str, # either metastable_states or absorption_probabilities key: str): """Utility function to handle the case of subsampled data.""" o1, o2 = ...
59c637d6aa8d23b5ad720d433437bfe7b4f4b2ec
46,950
import os def get_fmri(fmri_dir, ROI): """This function loads fMRI data into a numpy array for to a given ROI. Parameters ---------- fmri_dir : str path to fMRI data. ROI : str name of ROI. Returns ------- np.array matrix of dimensions #train_vids x #repetitio...
24136f99e5392e8d4e512be21aea79e1fb1325ad
46,951
def iterative_topological_sort(graph, start): """doesn't return some nodes""" seen = set() stack = [] # path variable is gone, stack and order are new order = [] # order will be in reverse order at first queue = [start] while queue: node = queue.pop() if node not in seen: ...
a0654b1b1ce93818f01a5e6347243fabd1c0d23c
46,952
def calculate_density_values(centers_of_intervals, mean, deviation) : """ Обчислюємо значення функції щільності """ density_values = np.zeros(centers_of_intervals.size) t_values = __calculate_t_values_for_density(centers_of_intervals, mean, deviation) phi_values = __calculate_phi_values_for_density(t_values) ...
e5a8d962cd91180a9b43a343f8800319422d6325
46,953
def _helper(length_diff, linked_list): """Helper function for longer linked list.""" length_diff = abs(length_diff) return linked_list[length_diff:]
67c208d2eab4f1be4e3e7a77008b1c3169fcee73
46,954
def getFuncDict(): """Directs key word to given function""" FuncDict = {"Aff": affHeatMap, "Valency": ValencyPlot, "Mix": MixPlot} return FuncDict
65847aca065ca7afad770fc022240ed447ee35a6
46,955
def run(cutouts, hostname="localhost", port=DEFAULT_PORT): """Start a local web app on the given port that lets you explore this cutout.""" def handler(*args): return ViewerServerHandler(cutouts, *args) myServer = HTTPServer((hostname, port), handler) print("Viewer server listening to http://{}:{}".format(...
b5b7d858b0e6c0625de8bee0c58aaa66d69257ae
46,956
def account(account): """Changing scope of the account fixture to be called after mailhog_delete_all fixture""" return account
7e5b4386b5aae8b5f35b6593e328401959c84ee5
46,957
import subprocess def getRefSeq( gene ): """Module RefSeq. Getting gene description thanks to lynx (must be installed) """ URL = "http://www.ncbi.nlm.nih.gov/IEB/Research/Acembly/av.cgi?db=human&c=Gene&a=fiche&l=" + gene #Url usage p = subprocess.Popen(['/usr/bin/lynx', '-dump', URL ], stdout=subprocess.PIPE, ...
82ffe4e6ab5f75b3944b67c3e19b03e1f69c4a0a
46,958
def writeResponse(func): """Prints response objects returned by functions. Args: func: Function whose output will be printed to screen. Returns: What the function given returns. """ def inner(*args, **kwargs): response = func(*args, **kwargs) if(verbose): print response.data return response re...
b2e0e91e59def4aba3d69bb2a5953a746b7b98e9
46,959
def get_polygon(aoiSquare): """ Translation from PAIRS aoiSquare to Shapely polygon. :aoiSquare: PAIRS aoiSquare :returns: Shapely polygon """ return box(aoiSquare[1], aoiSquare[0], aoiSquare[3], aoiSquare[2])
e46166d5cad2c293b3a1ca406b7fd91a33f7ebef
46,960
import re def collectComponents(board, components=None): """ Collect components template from the board. Include only footprints in components if specified """ d = CommentedMap() footprints = [f for f in board.GetFootprints() if components is None or len(components) == 0 or any([re.mat...
baabd95ef9d79614b43a9a367dac65371eb7635d
46,961
def nucleation_3D(writer, args, R=20): """ raise NotImplementedError("Needs some work") params = { "A": 3.4, "B": 13.5, "k2": 1.0, "k-2": 0.1, "k5": 0.9, "D_G": 1.0, "D_X": 1.0, "D_Y": 1.95, "density_G": 1.0, "density_X": 0.0002...
aaacb57cead9745f789fa8c0573d7338636f0922
46,962
def rsub(self, other): """Compute the element-wise subtraction. Parameters ---------- other : Union[dragon.Tensor, number] The value to be subtracted. Returns ------- dragon.Tensor The output tensor. See Also -------- `dragon.math.sub(...)`_ """ return...
3e4f075b978ba4a710070ecb5b62497f2f8ab634
46,963
def train_calculator(request: TrainCalculatorRequest) -> TrainCalculatorResponse: """Calculate CO2 emissions for a train trip""" response = build_response(request) return response
7ef5e9a26084160b2eae89d56aba2d8398ed5ef8
46,964
def socfaker_file_signature_status(): """ The signature status of a file Returns: str: A randomly selected signature status of Verified, Unknown, or Counterfit """ if validate_request(request): return { 'value': socfaker.file.signature_status }
12f26f9b80945843e687d0cf2ec51e275e0012e0
46,965
def lif_asc_aibs_converter(config, tau_syn=[5.5, 8.5, 2.8, 5.8]): """ :param config: :return: """ coeffs = config['coeffs'] params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03, 'g': coeffs['G'] / config['R_input'] * 1.0e09, ...
d6c283a3d6c0723f78e343c6bf020c508e7963b9
46,966
def get_routing_best_routes( device: object, address: str, protocol: str, active_tag: str = "*", ) -> list: """Return a list of best routes Args: device (object): Device object address (str): Address to check protocol (str): Protocol to check active_tag (str, opt...
e4e1b7be65e45fffa28c3372d8e1832de99b7286
46,967
def _proper_delay(q, c): """Analytically derived state-space when p = q - 1. We use this because it is numerically stable for high q and doesn't have a passthrough. """ j = np.arange(q, dtype=np.float64) u = (q + j) * (q - j) / (c * (j + 1)) A = np.zeros((q, q)) B = np.zeros((q, 1)) ...
c883808179d8b1a297fe8178416c65197d077706
46,968
def _CommonChecks(input_api, output_api): """Checks common to both upload and commit.""" result = [] result.extend(_CheckColorFormat(input_api, output_api)) result.extend(_CheckColorReferences(input_api, output_api)) result.extend(_CheckDuplicateColors(input_api, output_api)) # Add more checks here return...
00f371e2c56cbe67d8f331daae8e7195e9b38fe5
46,969
def login_required(f): """ Decorate routes to require login. """ @wraps(f) def decorated_function(*args, **kwargs): if session.get("user_id") is None: return redirect("/login") return f(*args, **kwargs) return decorated_function
e015e8f97c342e18ea3c8a86dd19fbbd720c0935
46,970
import sys def sensor_qry_single_row_v2(SYSTEM,querySingle, sensor_raw_table): #{{{APIINFO """ { "API_application":"提供查詢postgresql單一感測器感測資料服務(最新一筆或第一筆),不經過mysql直接抓取postgresql", "API_path_parameters":{ "SYSTEM":"合法的系統名稱", "querySingle":"First(取得第一筆資料)/Last(取得最後一筆資料)"...
b66d0e824cdc7266fa1298cc9a04c8d764487de8
46,971
def differential_replication(fitness, individuals): """ Individuals are selected into the next generation by a probability proportional to their fitness. Selected individuals are differentially replicated. """ return new_population
1aa711c4aa9bebd4eb24421eb12161b03c5dbd03
46,972
import copy def presco(te: np.ndarray, data: np.ndarray, tesla: float, none: bool = False, debug: bool = False) -> (np.ndarray, np.ndarray, np.ndarray, np.ndarray, float): """ [params sse] = presco(te, data) [params sse] = presco(imDataParams) Phase regularized estimation using smoothing a...
a99a4cdd7c39dd37ce5f3209df68b43c01149262
46,973
import json def voter_guides_followed_by_organization_retrieve_for_api(voter_device_id, # voterGuidesFollowedByOrganizationRetrieve voter_linked_organization_we_vote_id, filter_by_this_google_civic_e...
56cb380f3a1b9f4606b3ac10bef735e50c9fdd95
46,974
def show_questionnaire(request, runinfo, errors={}): """ Return the QuestionSet template Also add the javascript dependency code. """ request.runinfo = runinfo if request.GET.get('show_all') == '1': # for debugging purposes. questions = runinfo.questionset.questionnaire.questions() ...
f2eeba154114871c75592705b23ce5fa644b1cb7
46,975
def ib_model(img_in, noise, num_actions, scope, reuse=False, decoder="DECONV"): """As described in https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf""" img_size = img_in.shape[1] with tf.variable_scope(scope, reuse=reuse): out = img_in # coordinate = np....
21991b13c5fcfa701699565177d158214c26d586
46,976
from typing import List from typing import Callable from typing import Any def pad_sequence_to_length( sequence: List, desired_length: int, default_value: Callable[[], Any] = lambda: 0, padding_on_right: bool = True, ) -> List: """ Take a list of objects and pads it to the desired length, retu...
c8277e5a20ef83e3742e07b2fec068a1f945465b
46,977
def output_path(request): """ Returns the desired name for the folder that will store the results of the tests. If no name is provided, it will default to naming the folder after the timestamp at the moment this test session started. Datetime as string in the format YYYY-MM-DDTHH_MM_SS_F This fixture i...
39af5379fc016c835856692f5164d4b8a5286a7e
46,978
def compute_interestingness_conjunct(trace, ltl_name, ltl_props, vocab): """ Computes the interestingness for a conjunct LTL over trace :param trace: execution trace in the form of a list of states over time :param ltl_name: the ltl formula name (global, eventual, etc.) for which interestingness metric ...
d45ab83559ff16846e7988f138281098b68cbd03
46,979
import requests def vts_proxy_world_topo_thunderforest( layer: str, z: int, x: int, y: int ) -> FlaskResponse: """ Tunneling map requests to the Thunderforest servers in order to hide the API key. Other tile layer URLs: https://manage.thunderforest.com/dashboard Args: layer (str): Til...
b95b86e82b1b6d579ddf98260a9368d4f779f6b8
46,980
def download_key(): """Download security key **Example request** .. sourcecode:: http POST /downloadKey HTTP/1.1 { "token": "<token>", } **Example response** .. sourcecode:: http HTTP/1.1 200 OK Content-Encoding: gzip Content-Type: a...
64e4f6d1d8cef693a46a4d873b858e183434652e
46,981
def getAll(namespaces=None): """ Gets all the controls found in the control set with the given namespace. Args: namespaces (Iterable): Names of namespace to append as prefix to the control set name. Returns: (list): All controls sorted. """ if namespaces: sets = [pm.PyN...
2ae58a79aef207bdbcee98b4288a4e33cd80bd67
46,982
import os def get_module_files(src_directory, blacklist): """given a package directory return a list of all available python module's files in the package and its subpackages :type src_directory: str :param src_directory: path of the directory corresponding to the package :type blacklist: ...
6585f9c023bc708b7564b69131a5ee56624e605c
46,983
def create_grouped_word_list(words, group_span_indices, join_string): """Group together words with join_string string and return updated token list.""" adjusted_words = [] curr_group = [] group_idx = 0 curr_group_start_idx, curr_group_end_idx = group_span_indices[group_idx] for i, token in enume...
efd8c4a2e02b9704e6a3f8647ccb0d31be18551c
46,984
def get_next_object(table, remote_id, provider_id): """Check if object already exists in NEXT and return it.""" query_filter = {"remote_id": remote_id} if table == "user_mapping": query_filter["provider_id"] = provider_id conn = connect_to_db() result = r.table(table).filter(query_filter).co...
2673e72853dcdac12b5d57fc7db897688d8c4360
46,985
def clean_data(df): """ Input: df: Dataframe containing messages and respective categories. [dataframe] Output: df: Dataframe containing cleaned messages and categories. [dataframe] Description: Cleans dataframe with removing unneccesary columns, duplicates and text artifacts. """ ...
c4ea937cedf55fe446e5246f28aa1816b1f976c5
46,986
def connects_to_emergency_number(number, region_code): """Returns whether the number might be used to connect to an emergency service in the given region. This function takes into account cases where the number might contain formatting, or might have additional digits appended (when it is okay to d...
a7794cbb91f987f0d460ad490dc5a41947027003
46,987
def split_on(delimiter, text): """Split text based on a delimiter.""" return filter(None, map(strip, text.split(delimiter)))
9d29330171d650ade4ff052f63eb41f01009047e
46,988
import threading def notify(recipient_email: str, notification_type: NotificationType, payload=None): """Sends a notification to the specified user.""" notification_group = type_to_group[notification_type] channel = db.session.query( # pylint: disable=unsubscriptable-object Account.notific...
a020fe40ca3b9cf6fd53154a056d602a7b3ab8ee
46,989
import time def format_time_input(time_in, return_seconds=False, return_milliseconds=False): """Format timestamp as seconds/milliseconds for use in REST requests. :param time_in: timestamp -- int/float :param return_seconds: return time in seconds -- bool :param return_milliseco...
bbe4861b66220851251400396c86d53348d46797
46,990
def fetch_consumption( zone_key=ZONE_KEY, session=None, target_datetime=None, logger=None ) -> dict: """Fetch Chhattisgarh consumption""" if target_datetime: raise NotImplementedError("This parser is not yet able to parse past dates") zonekey.assert_zone_key(zone_key, ZONE_KEY) html = web....
ba5218facb2ca0119db47ae0a07436b1a894eb17
46,991
def extract_stops(route_data): """ Extracts a dataframe of stops info Returns the main stops dataframe, and a list of inbound and outbound stops in the order they are intended to be on the route """ stops = pd.DataFrame(route_data['stop']) directions = pd.DataFrame(route_data['direction'])...
6fb0eaf3d3b834e23219a13df39fe341a01bc8c8
46,992
def uu_get_industry(): """ 查询股票所属行业 :param :security:标的代码,类型为字符串,形式如"000001.XSHE";或为包含标的代码字符串的列表,形如["000001.XSHE", "000002.XSHE"] date:查询的日期。类型为字符串,形如"2018-06-01"或"2018-06-01 09:00:00";或为datetime.datetime对象和datetime.date。注意传入对象的时分秒将被忽略。 :rtype :dict :return: """ return get_indust...
8737896ecfaa22778cd91a5801a1d32605dd468d
46,993
def computePhasesCOMValues(cs,DEFAULT_HEIGHT, overwrite = False): """ Generate c, dc and ddc initial and final values for the contactSequence if not provided or if overwrite = True With null dc and ddc and c position in the center of the support polygone for each phase :param cs: the contact sequence ...
ee12496e4586cad39b763a6851e2d7deb98f6ac5
46,994
def Z_theta(theta:float, unit='deg'): """ PTM of rotation of theta degrees along the X axis """ if unit=='deg': theta = np.deg2rad(theta) Z = np.array([[1, 0, 0, 0], [0, np.cos(theta), -np.sin(theta), 0], [0, np.sin(theta), np.cos(theta), 0], ...
3a275d0eadcd9304f8e48680bf82fd1da43ba7e0
46,995
def str_2_vec(str): """ Convert vector of integers to string. :param str: string :return: [int, int, int, ...] """ return [ord(i) for i in str]
555204ff45e6b55c78bf0a6aef7af2d913f2aa3d
46,996
def db_connection(host, user, dbname, charset = "utf8mb4"): """ Connect to a MySQL Database Server """ key = pwdutil.get_key() encoded = pwdutil.get_pwd() password = pwdutil.decode(key,encoded) connection = pymysql.connect(host = host , user = user ...
0a49688e6896b93124a17385f74cdc3aa0d2b2be
46,997
import itertools from distutils import sysconfig import os import sys def locate_libpython_2(python_version: str): """Get path to the python library associated with the current python interpreter.""" # https://stackoverflow.com/questions/47423246/get-pythons-lib-path # determine direct path to libpyt...
3fef805f119f212f13b79b334673b3a32f3a16cb
46,998
def getAttributes(obj): """Get non hidden and built-in type object attributes that can be persisted""" d={} allowed = [str,int,float,list,tuple,bool] for key in obj.__dict__: if key.startswith('_'): continue item = obj.__dict__[key] if type(item) in allowed: ...
ea60687e48734f9bd53b96109b101b8a2267e8d1
46,999