content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import types def get_task_name(task): """Gets a tasks *string* name, whether it is a task object/function.""" task_name = "" if isinstance(task, (types.MethodType, types.FunctionType)): # If its a function look for the attributes that should have been # set using the task() decorator provi...
181682d930cf358f2532406f1558b007aa09a41f
16,037
def EventAddPublication(builder, publication): """This method is deprecated. Please switch to AddPublication.""" return AddPublication(builder, publication)
39cf5facf251370fd86a004477f848dafd41976c
16,038
def convModel(input1_shape, layers): """" convolutional model defined by layers. ith entry defines ith layer. If entry is a (x,y) it defines a conv layer with x kernels and y filters. If entry is x it defines a pool layer with size x""" model = Sequential() for (i, layer) in enumerate(layers): ...
d1a49a42ab0fc4eecd40783345f09121a773ae02
16,039
def cached_open_doc(db, doc_id, cache_expire=COUCH_CACHE_TIMEOUT, **params): """ Main wrapping function to open up a doc. Replace db.open_doc(doc_id) """ try: cached_doc = _get_cached_doc_only(doc_id) except ConnectionInterrupted: cached_doc = INTERRUPTED if cached_doc in (None, ...
82118a5c9c43aaf339e7ca3ab8af9680fbd362d1
16,040
import torch def dense2bpseq(sequence: torch.Tensor, label: torch.Tensor) -> str: """converts sequence and label tensors to `.bpseq`-style string""" seq_lab = dense2seqlab(sequence, label) return seqlab2bpseq
ec0a5d681fef518068042aa2830ee4d2ef3231c8
16,042
from datetime import datetime def _base_app(config): """ init a barebone flask app. if it is needed to create multiple flask apps, use this function to create a base app which can be further modified later """ app = Flask(__name__) app.config.from_object(config) config.init_app(app) ...
f5f40ed9ea740c5b9bc9ebb8490136179d06f777
16,043
def applyC(input_map,nbar,MAS_mat,pk_map,Y_lms,k_grids,r_grids,v_cell,shot_fac,include_pix=True): """Apply the fiducial covariance to a pixel map x, i.e. C[x] = S[x]+N[x]. We decompose P(k;x) = \sum_l P_l(k) L_l(k.x) where x is the position of the second galaxy and use spherical harmonic decompositions. P_...
91346d935217f540a91947b0a00e91e0125794ef
16,044
def invert_injective_mapping(dictionary): """ Inverts a dictionary with a one-to-one mapping from key to value, into a new dictionary with a one-to-one mapping from value to key. """ inverted_dict = {} for key, value in iteritems(dictionary): assert value not in inverted_dict, "Mapping i...
c8cba85f542c5129892eeba4168edf6d9715b54e
16,045
def biosql_dbseqrecord_to_seqrecord(dbseqrecord_, off=False): """Converts a DBSeqRecord object into a SeqRecord object. Motivation of this function was two-fold: first, it makes type testing simpler; and second, DBSeqRecord does not have a functional implementation of the translate method. :param DBSeq...
9129c5efd9025a04f0693fd2d35f420b28c2ea91
16,046
import re def parse_rpsbproc(handle): """Parse a results file generated by rpsblast->rpsbproc. This function takes a handle corresponding to a rpsbproc output file. local.rpsbproc returns a subprocess.CompletedProcess object, which contains the results as byte string in it's stdout attribute. """...
64be049b5cb96a3e59f421327d1715cee84e2300
16,048
from typing import get_type_hints def _invalidate(obj, depth=0): """ Recursively validate type anotated classes. """ annotations = get_type_hints(type(obj)) for k, v in annotations.items(): item = getattr(obj, k) res = not_type_check(item, v) if res: return f"{...
a1881d45414a4a034456e0078553e4aa7bf6471a
16,049
def convtranspose2d_output_shape(h_w, kernel_size=1, stride=1, pad=0, dilation=1, out_pad=0): """Calculates the output height and width of a feature map for a ConvTranspose2D operation.""" h_w, kernel_size, stride, pad, dilation, out_pad = num2tuple(h_w), num2tuple(kernel_size), num2tuple(stride), num2tuple(pad...
e1ded212929e7e24b138335ae3d9006b1dcfb759
16,051
def set_multizone_read_mode(session, read_mode, return_type=None, **kwargs): """ Modifies where data is read from in multizone environments. :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type read_mode: str :param read_mode: For mu...
0831bfd722514cab792eef38838e357209a0971f
16,052
import re def get_name_convert_func(): """ Get the function to convert Caffe2 layer names to PyTorch layer names. Returns: (func): function to convert parameter name from Caffe2 format to PyTorch format. """ pairs = [ # ------------------------------------------------------...
4e3cbe0885a0d23d5af151bc0cea7127156aa9c9
16,053
def generate_dict_entry(key, wordlist): """Generate one entry of the python dictionary""" entry = " '{}': {},\n".format(key, wordlist) return entry
57ab3c063df0bde1261602f0c6279c70900a7a88
16,054
def record_to_dict(record): """ Transform string into bovespa.Record :param record: (string) position string from bovespa. :return: parsed Record """ try: record = bovespa.Record(record) except: return None return { 'date': record.date, 'year': record.date.year, ...
3065d233a0186a72330165c9b082c819369ef449
16,055
def sample_product(user, **params): """Create and return a custom product""" defaults = { 'name': 'Ron Cacique', 'description': 'El ron cacique es...', 'price': 20, 'weight': '0.70', 'units': 'l', 'featured': True, } defaults.update(params) return Pro...
310b2ee775e5497597dd68cf6737623e40b78932
16,056
def _find_op_path_(block, outputs, inputs, no_grad_set): """ no_grad_set will also be changed """ input_names = set([inp.name for inp in inputs]) output_names = set([out.name for out in outputs]) relevant_op_flags = [True] * len(block.ops) # All the inputs of the block are used if inputs i...
05d1b18f883906cc41fa84f6f27f061b30ced4b8
16,057
def clean_gltf_materials(gltf): """ 未使用のglTFマテリアルを削除する :param gltf: glTFオブジェクト :return: 新しいマテリアルリスト """ return filter(lambda m: m['name'] in used_material_names(gltf), gltf['materials'])
7e429dceb84d48298897589172f976ea907ddcab
16,058
def create_root(request): """ Returns a new traversal tree root. """ r = Root() r.add('api', api.create_root(request)) r.add('a', Annotations(request)) r.add('t', TagStreamFactory()) r.add('u', UserStreamFactory()) return r
ebc64f7f49bf6b3405b9971aa0b30e72b3d13c5f
16,059
def sort_basis_functions(basis_functions): """Sorts a set of basis functions by their distance to the function with the smallest two-norm. Args: basis_functions: The set of basis functions to sort. Expected shape is (-1, basis_function_length). Returns: sorted_basis: The so...
18b11f80c7d08eb6435d823e557ec9ea4e028b92
16,060
def info_materials_groups_get(): """ info_materials_groups_get Get **array** of information for all materials, or if an array of `type_ids` is included, information on only those materials. :rtype: List[Group] """ session = info_map.Session() mat = aliased(info_map.Material) ...
49dcf0785be8d9a94b4bb730af6326d493e79000
16,062
def relu(x): """ Compute the relu of x Arguments: x -- A scalar or numpy array of any size. Return: s -- relu(x) """ s = np.maximum(0,x) return s
40b838889b62abca0a88788436b5d648261a3c67
16,064
def line(value): """ | Line which can be used to cross with functions like RSI or MACD. | Name: line\_\ **value**\ :param value: Value of the line :type value: float """ def return_function(data): column_name = f'line_{value}' if column_name not in data.columns: ...
07b4f9671ae06cf63c02062a9da4eb2a0b1a265a
16,066
import json import requests def goodsGetSku(spuId,regionId): """ :param spuId: :param regionId: :return: """ reqUrl = req_url('goods', "/goods/getGoodsList") if reqUrl: url = reqUrl else: return "服务host匹配失败" headers = { 'Content-Type': 'application/json', ...
23c3960384529c7a45e730a612cc7999fa316bd4
16,067
def get_scheduler(config, optimizer): """ :param config: 配置参数 :param optimizer: 优化器 :return: 学习率衰减策略 """ # 加载学习率衰减策略 if config.scheduler_name == 'StepLR': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=config.StepLR['decay_step'], ...
1e4be51c74ed6c35bde3343547c4a7a88736179a
16,069
def pipeline_dict() -> dict: """Pipeline config dict. You need to update the labels!""" pipeline_dictionary = { "name": "german_business_names", "features": { "word": {"embedding_dim": 16, "lowercase_tokens": True}, "char": { "embedding_dim": 16, ...
d9e15fb1a09678d65b30a49b7c7c811843420c57
16,070
def _is_hangul_syllable(i): """ Function for determining if a Unicode scalar value i is within the range of Hangul syllables. :param i: Unicode scalar value to lookup :return: Boolean: True if the lookup value is within the range of Hangul syllables, otherwise False. """ if i in range(0xAC00, 0...
793519ec33a8920ea13328b0e5a4f814c859b0d3
16,071
def shape14_4(tik_instance, input_x, res, input_shape, shape_info): """input_shape == ((32, 16, 14, 14, 16), 'float16', (1, 1), (1, 1))""" stride_w, stride_h, filter_w, filter_h, dilation_filter_w, dilation_filter_h = shape_info pad = [0, 0, 0, 0] l1_h = 14 l1_w = 14 c1_index = 0 jump_stride...
5606e2e6445ea5415960e1784009bcc75de29669
16,072
from typing import Dict from typing import Any from typing import Optional from typing import Iterator from typing import Union from typing import List def read_json( downloader: Download, datasetinfo: Dict, **kwargs: Any ) -> Optional[Iterator[Union[List, Dict]]]: """Read data from json source allowing for J...
77183992d42d9c3860965222c3feda23aca588dc
16,073
import json def json_dumps_safer(obj, **kwargs): """Convert obj to json, with some extra encodable types.""" return json.dumps(obj, cls=WandBJSONEncoder, **kwargs)
816e97051553f1adc4c39a7c5e4559fb3a354197
16,074
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
74707af8839b37de80d682d715ed8000375cdd7c
16,075
from uuid import uuid4 from redis import Redis from qiita_core.configuration_manager import ConfigurationManager from qiita_db.sql_connection import SQLConnectionHandler from moi.job import submit_nouser def test(runner): """Test the environment * Verify redis connectivity indepedent of moi * Verify data...
ea4f8f50e3d85c3df6f7c890b5b91140a63bac65
16,076
def validate_model(model): """ Validate a single data model parameter or a full data model block by recursively calling the 'validate' method on each node working from the leaf nodes up the tree. :param model: part of data model to validate :type model: :graphit:GraphAxis :return: ov...
009c629fe80af65f574c698567cb6b5213e9c888
16,078
def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None. """ filename = "{0}.html".format(url.split("/").pop().lower()) filepath = abspath(join(dirna...
60b7714a439d949f42b1b8de6064c8ba087ccfdc
16,079
def ensemble_tsfresh(forecast_in, forecast_out, season, perd): """ Create rolled time series for ts feature extraction """ def tsfresh_run(forecast, season, insample=True, forecast_out=None): df_roll_prep = forecast.reset_index() if insample: df_roll_prep = df_roll_prep.drop...
3bcef19cd495c043e51a591118c1ae8e043290b5
16,080
from affine import Affine def transform_from_latlon(lat, lon): """ Tranform from latitude and longitude NOTES: - credit - Shoyer https://gist.github.com/shoyer/0eb96fa8ab683ef078eb """ lat = np.asarray(lat) lon = np.asarray(lon) trans = Affine.translation(lon[0], lat[0]) scale = A...
1f6fccfddd23423c0a621efa74a62cdb61b53665
16,082
from typing import OrderedDict def xml_to_json(xml_text: str) -> OrderedDict: """Converts xml text to json. Args: xml_text (str): xml text to be parsed Returns: OrderedDict: an ordered dict representing the xml text as json """ return xmltodict.parse(xml_text)
243156c6f0b3b0f0bf92d8eeaa3ecf52f5846fc8
16,083
import requests def getWeather(city, apikey): """ 天気を取得する リクエストにAPIKeyと都市をパラメーターに入れる https://openweathermap.org/forecast5 """ payload = { 'APIKEY': APIKEY, 'q': CITY } r = requests.get( APIBASE, params=payload ) return r
41a61d1bd9d1bd5d835963c305d0692babd6b64a
16,085
def func1(xc): """Function which sets the data value""" s = .1 res = np.exp(-xc**2/(2*s**2)) return res
75ab06abf5b348746e322cf41660cfb908d69b62
16,086
def GetEnabledDiskTemplates(*args): """Wrapper for L{_QaConfig.GetEnabledDiskTemplates}. """ return GetConfig().GetEnabledDiskTemplates(*args)
c07707de13be5c055386659be620831b2f057d64
16,087
def is_pull_request_merged(pull_request): """Takes a github3.pulls.ShortPullRequest object""" return pull_request.merged_at is not None
0fecf82b96f7a46cfb4e9895897bd4998d6f225b
16,088
def arraytoptseries(arr, crs={'epsg': '4326'}): """Convert an array of shape (2, ...) or (3, ...) to a geopandas GeoSeries containing shapely Point objects. """ if arr.shape[0] == 2: result = geopandas.GeoSeries([Point(x[0], x[1]) for x in arr.reshape(2, -1).T...
b193f9bcb4144b81becca1acaa8285f8cafaaff2
16,089
async def get_kml_network_link(): """ Return KML network link file """ logger.info('/c-haines/network-link') headers = {"Content-Type": kml_media_type, "Content-Disposition": "inline;filename=c-haines-network-link.kml"} return Response(headers=headers, media_type=kml_media_type, content=...
699ac59529ce085264a79dfdd048c96b3771e0a8
16,090
def splitToPyNodeList(res): # type: (str) -> List[pymel.core.general.PyNode] """ converts a whitespace-separated string of names to a list of PyNode objects Parameters ---------- res : str Returns ------- List[pymel.core.general.PyNode] """ return toPyNodeList(res.split())
44e8780833ed2a5d7418c972afb9e184ca82670b
16,091
def get_jira_issue(commit_message): """retrieve the jira issue referenced in the commit message >>> get_jira_issue(b"BAH-123: ") {b'BAH-123'} >>> messages = ( ... b"this is jira issue named plainly BAH-123", ... b"BAH-123 plainly at the beginning", ... b"in parens (BAH-123)", ... b"(BAH...
b0bf47319c492ec297dd9898645a10ce8a53b43f
16,092
def get_mean_std(dataloader): """Compute mean and std on the fly. Args: dataloader (Dataloader): Dataloader class from torch.utils.data. Returns: ndarray: ndarray of mean and std. """ cnt = 0 mean = 0 std = 0 for l in dataloader: # Now in (batch,...
d943ae5244743749fa6a2186aacfbf0ea160d17b
16,094
import random import math def create_random_camera(bbox, frac_space_x, frac_space_y, frac_space_z): """ Creates a new camera, sets a random position for it, for a scene inside the bbox. Given the same random_seed the pose of the camera is deterministic. Input: bbox - same rep as output from get_scene...
8cfa86127d569493a2456e13ae5924da886640a9
16,096
def temp2(): """ This is weird, but correct """ if True: return (1, 2) else: if True: return (2, 3) return (4, 5)
c63f5566a6e52a3b5d175640fce830b7aad33ebe
16,097
from typing import Tuple def compute_blade_representation(bitmap: int, firstIdx: int) -> Tuple[int, ...]: """ Takes a bitmap representation and converts it to the tuple blade representation """ bmp = bitmap blade = [] n = firstIdx while bmp > 0: if bmp & 1: blade.ap...
3bf6672280629dee8361ee3c0dbf5920afa4edda
16,098
import time def get_ntp_time(ntp_server_url): """ 通过ntp server获取网络时间 :param ntp_server_url: 传入的服务器的地址 :return: time.strftime()格式化后的时间和日期 """ ntp_client = ntplib.NTPClient() ntp_stats = ntp_client.request(ntp_server_url) fmt_time = time.strftime('%X', time.localtime(ntp_stats.tx_time))...
17881970361994e329e1154478c8abb8171461f9
16,100
def read_data(path, names, verbose=False): """ Read time-series from MATLAB .mat file. Parameters ---------- path : str Path (relative or absolute) to the time series file. names : list Names of the requested time series incl. the time array itself verbose : bool, optional ...
978870d4517b5e5ab66186747c326794d6d43814
16,101
async def search(q: str, person_type: str = 'student') -> list: """ Search by query. :param q: `str` query to search for :param person_type: 'student', 'lecturer', 'group', 'auditorium' :return: list of results """ url = '/'.join((BASE_URL, SEARCH_INDPOINT)) params = {'term': q, ...
83913866f45a44202ccddbc9352fef9799caf751
16,102
def format_data_hex(data): """Convert the bytes array to an hex representation.""" # Bytes are separated by spaces. return ' '.join('%02X' % byte for byte in data)
27239052d9ca0b12c19977e79d512e0cab04182e
16,103
def disp(cog_x, cog_y, src_x, src_y): """ Compute the disp parameters Parameters ---------- cog_x: `numpy.ndarray` or float cog_y: `numpy.ndarray` or float src_x: `numpy.ndarray` or float src_y: `numpy.ndarray` or float Returns ------- (disp_dx, disp_dy, disp_norm, disp_ang...
e9d8166827e86a8e2180ba357a450aca817fdff4
16,106
def get_landmark_from_prob(prob, thres=0.5, mode="mean", binary_mask=False): """Compute landmark location from the model probablity maps Inputs: prob : [RO, E1], the model produced probablity map for a landmark thres : if np.max(prob)<thres, determine there is no landmark detected m...
fad614088e587e389f15b0700bf442a956d498b0
16,107
import socket def request( url, timeout: float, method="GET", data=None, response_encoding="utf-8", headers=None, ): """ Helper function to perform HTTP requests """ req = Request(url, data=data, method=method, headers=headers or {}) try: return urlopen(req, timeout...
80f130101290442d538fa3f416f5650800547c6b
16,108
from typing import Any from typing import Optional from typing import get_args from typing import get_origin def get_annotation_affiliation(annotation: Any, default: Any) -> Optional[Any]: """Helper for classifying affiliation of parameter :param annotation: annotation record :returns: classified value o...
db6efd7dfb0ed0272e7491547669de8f235b2b35
16,109
def sort_dict(original): """Recursively sorts dictionary keys and dictionary values in alphabetical order""" if isinstance(original, dict): res = ( dict() ) # Make a new "ordered" dictionary. No need for Collections in Python 3.7+ for k, v in sorted(original.items()): ...
8c194af76160b0e4d3bad135720e051a4d4622b0
16,111
import requests def playonyt(topic): """Will play video on following topic, takes about 10 to 15 seconds to load""" url = 'https://www.youtube.com/results?q=' + topic count = 0 cont = requests.get(url) data = str(cont.content) lst = data.split('"') for i in lst: count+=1 if...
49f4285dc0e0086d30776fc0668bac0e4c19dbc5
16,112
def train_classifier(classifier, features, labels): """This function must concern itself with training the classifier on the specified data.""" return classifier.fit(features, labels)
ef74548aeb6e245d8728caf3205163c249046aae
16,113
def work_on_disk(dev, root_mb, swap_mb, image_path): """Creates partitions and write an image to the root partition.""" root_part = "%s-part1" % dev swap_part = "%s-part2" % dev if not is_block_device(dev): LOG.warn(_("parent device '%s' not found"), dev) return make_partitions(dev,...
195ded6deae958b7efa41bcfdda1d3d68cabb23d
16,114
def get_annotation_names(viewer): """Detect the names of nodes and edges layers""" layer_nodes_name = None layer_edges_name = None for layer in viewer.layers: if isinstance(layer, napari.layers.points.points.Points): layer_nodes_name = layer.name elif isinstance(layer, napar...
20e64a6719b945eceda341d5a42da178818cb1a1
16,115
def remap(kx,ky,lx,ly,qomt,datai): """ remap the k-space variable back to shearing periodic frame to reflect the time dependent Eulerian wave number """ ndim = datai.ndim dim = np.array(datai.shape)# datai[nz,ny,nx] sh_data = np.empty([dim[0],dim[1],dim[2]]) tp_data = np.empty([dim[0],dim[2]]) sh...
6ea415df88c0db2ba26ef0fc8daa35b12a101ef8
16,116
def fips_disable(): """ Disables FIPS on RH/CentOS system. Note that you must reboot the system in order for FIPS to be disabled. This routine prepares the system to disable FIPS. CLI Example: .. code-block:: bash salt '*' ash.fips_disable """ installed_fips_pkgs = _get_install...
d31cc5ad6dd71ec0f3d238051a7b2a64b311c0fd
16,117
from datetime import datetime def buy_sell_fun_mp_org(datam, S1=1.0, S2=0.8): """ 斜率指标交易策略标准分策略 """ start_t = datetime.datetime.now() print("begin-buy_sell_fun_mp:", start_t) dataR = pd.DataFrame() for code in datam.index.levels[1]: # data = price.copy() # price = datam.que...
8d3b78b9d266c3c39b8491677caa0f4dfb9f839a
16,119
import collections import abc def marshall_namedtuple(obj): """ This method takes any atomic value, list, dictionary or namedtuple, and recursively it tries translating namedtuples into dictionaries """ recurse = lambda x: map(marshall_namedtuple, x) obj_is = partial(isinstance, obj) if ha...
87d24fe1b273bfcf481679a96710be757baf08a5
16,120
import torch def prep_image(img, inp_dim): """ Prepare image for inputting to the neural network. Returns a Variable """ # print("prepping images") img = cv2.resize(img, (inp_dim, inp_dim)) img = img[:,:,::-1].transpose((2,0,1)).copy() img = torch.from_numpy(img).float().div(255...
02ebc73a32a24d59c53da9bfb99485f3a4f6dee2
16,121
from typing import Dict from typing import List import math def best_broaders(supers_for_all_entities: Dict, per_candidate_links_and_supers: List[Dict], num_best: int = 5, super_counts_field: str = "broader_counts", doprint=False, ...
9aa9826c43e67a28eeca463b107296e093709246
16,122
def clump_list_sort(clump_list): """Returns a copy of clump_list, sorted by ascending minimum density. This eliminates overlap when passing to yt.visualization.plot_modification.ClumpContourCallback""" minDensity = [c['Density'].min() for c in clump_list] args = np.argsort(minDensity) list...
732e747e36c37f9d65ef44b6aa060d5c9d04e3d1
16,123
from typing import Dict from typing import Any from typing import Type import types from typing import Optional def _prepare_artifact( metadata_handler: metadata.Metadata, uri: Text, properties: Dict[Text, Any], custom_properties: Dict[Text, Any], reimport: bool, output_artifact_class: Type[types....
d30dcd579c73c71173f10207ab80d05c761c7185
16,124
import re def ParseCLILines(lines, skipStartLines=0, lastSkipLineRe=None, skipEndLines=0): """Delete first few and last few lines in an array""" if skipStartLines > 0: if lastSkipLineRe != None: # sanity check. Make sure last line to skip matches the given regexp if None == re....
dc445765f42df25b8d046e3f2303d85109a3d419
16,125
def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) ...
785985b79b9284ba8c6058c8e9c4018955407cf8
16,126
from datetime import datetime def get_df_from_sampled_trips(step_trip_list, show_service_data=False, earliest_datetime=None): """Get dataframe from sampled trip list. Parameters ---------- step_trip_list : list of lists List of trip lists occuring in the same step. show_service_data: bool...
36bba80f0c46862df0390cf4e4279eeb33002e86
16,128
def compute_v_y(transporter, particles): """ Compute values of V y on grid specified in bunch configuration :param transporter: transport function :param particles: BunchConfiguration object, specification of grid :return: matrix with columns: x, theta_x, y, theta_y, pt, V y """ return __com...
4a17e0c0e4612534483187b6779bcf5c179c0fcc
16,129
def run_fn(fn_args: TrainerFnArgs): """Train the model based on given args. Args: fn_args: Holds args used to train the model as name/value pairs. """ # get transform component output tf_transform_output = tft.TFTransformOutput(fn_args.transform_output) # read input data train_dataset...
15c8202ad6955052bbd1da2984aedb9887c390af
16,131
def log_likelihood(X, Y, Z, data, boolean=True, **kwargs): """ Log likelihood ratio test for conditional independence. Also commonly known as G-test, G-squared test or maximum likelihood statistical significance test. Tests the null hypothesis that X is independent of Y given Zs. Parameters --...
00493131d78506c5a6cbb9e04bda51b69f1a04ca
16,132
def conjugada_matriz_vec(mat:list): """ Funcion que realiza la conjugada de una matriz o vector complejo. :param mat: Lista que representa la matriz o vector complejo. :return: lista que representa la matriz o vector resultante. """ fila = len(mat) columnas = len(mat[0]) resul = [] f...
ad883dae9161f4e60f933caf93703544e16bfb4d
16,133
def features2matrix(feature_list): """ Args: feature_list (list of Feature): Returns: (np.ndarray, list of str): matrix and list of key of features """ matrix = np.array([feature.values for feature in feature_list], dtype=float) key_lst = [feature.key for feature in feature_li...
f60cdb904489cca3ab926dbc8d396804367e4a7a
16,134
import re def is_heading(line): """Determine whether a given line is a section header that describes subsequent lines of a report. """ has_cattle = re.search(r'steer?|hfrs?|calves|cows?|bulls?', line, re.IGNORECASE) has_price = re.search(r'\$[0-9]+\.[0-9]{2}', line) return bool(has_cattle) a...
ccbc80f7db61f7ba82aa88e54112d1995d457764
16,136
def get_channel_messages(channel_id): """ Holt fuer einen bestimmten Kanal die Nachrichten aus der Datenbank""" session = get_cassandra_session() future = session.execute_async("SELECT * FROM messages WHERE channel_id=%s", (channel_id,)) try: rows = future.result() except Exception: ...
7a3821dd8e93c4d49dfeecea200a881fdcb3f1a4
16,137
def train(traj, pol, targ_pol, qf, targ_qf, optim_pol, optim_qf, epoch, batch_size, # optimization hypers tau, gamma, # advantage estimation sampling, ): """ Train function for deep deterministic policy gradient Parameters ---------- tra...
14c09f3ce1f30366be3b8d0e0b965bdc1c677834
16,138
def merge_dicts(dict1, dict2): """ _merge_dicts Merges two dictionaries into one. INPUTS @dict1 [dict]: First dictionary to merge. @dict2 [dict]: Second dictionary to merge. RETURNS @merged [dict]: Merged dictionary """ merged = {**dict1, **dict2} return merged
67e96ba9c9831e6e2aa4bbd6cd8b8d1d5edb93c4
16,140
import pagure.api import pagure.lib.query def check_api_acls(acls, optional=False): """Checks if the user provided an API token with its request and if this token allows the user to access the endpoint desired. :arg acls: A list of access control :arg optional: Only check the API token is valid. Skip...
81d658036c5b31e3471e48ef44f4eb26e571c49a
16,141
def china_province_head_fifteen(): """ 各省前15数据 :return: """ return db_request_service.get_china_province_head_fifteen(ChinaTotal, ChinaProvince)
18dc3f22c05b3580bcd983361efc03bd3cdae43b
16,143
def pipeline(x_train, y_train, x_test, y_test, param_dict=None, problem='classification'): """Trains and evaluates a DNN classifier. Args: x_train: np.array or scipy.sparse.*matrix array of features of training data y_train: np.array 1-D arra...
f01e20851c91dd9f6b3db889fdf713edc1eb37b9
16,145
def model_selection(modelname, num_out_classes, dropout=None): """ :param modelname: :return: model, image size, pretraining<yes/no>, input_list """ if modelname == 'xception': return TransferModel(modelchoice='xception', num_out_classes=num_o...
67ba26ab4f7cbe8f4540eb10f2ef6e598b49ea2f
16,146
def Packet_computeBinaryPacketLength(startOfPossibleBinaryPacket): """Packet_computeBinaryPacketLength(char const * startOfPossibleBinaryPacket) -> size_t""" return _libvncxx.Packet_computeBinaryPacketLength(startOfPossibleBinaryPacket)
58139b8d874d9292e63b6eb6afdbd9c5c2fa6f9d
16,147
import itertools def gen_positions(n, n_boulders): """Generates state codes for boulders. Includes empty rows Parameters: n: number of rows/columns n_boulders: number of boulders per row return value: Possible boulder and alien states """ boulder_positions=[]; b_p=[] a...
0a20594f2e021bf8e190f6c7c726159fde0b8367
16,149
def analysis_linear_correlation(data1:np.array, data2:np.array, alpha:float = .05, return_corr:bool = True, verbose:bool = False)->bool: """ ## Linear correlation analysis to test i...
6eaf34a12281949236d28143399024ed30e834ad
16,150
def sha256(buffer=None): """Secure Hash Algorithm 2 (SHA-2) with 256 bits hash value.""" return Hash("sha256", buffer)
2e33c38c0f7b9dd019104a18e6842243773686ca
16,151
import math import torch def nmc_eig(model, design, observation_labels, target_labels=None, N=100, M=10, M_prime=None, independent_priors=False): """ Nested Monte Carlo estimate of the expected information gain (EIG). The estimate is, when there are not any random effects, .. math:: ...
8de69e87677a4a74fd04ce4cf302221121d00b2d
16,152
import scipy def _orient_eigs(eigvecs, phasing_track, corr_metric=None): """ Orient each eigenvector deterministically according to the orientation that correlates better with the phasing track. Parameters ---------- eigvecs : 2D array (n, k) `k` eigenvectors (as columns). phasing...
d6feebbd7b7748549ebc494bf8b00f0d9e313f7c
16,153
def test_CreativeProject_auto_multivariate_functional(max_iter, max_response, error_lim, model_type): """ test that auto method works for a particular multivariate (bivariate) function """ # define data covars = [(0.5, 0, 1), (0.5, 0, 1)] # covariates come as a list of tuples (one per covariate: (...
ee0cc1d34a1836c8ea9ec2b23de175f4b6d8ca75
16,154
def crossValidate(x, y, cv=5, K=None): """ :param y: N*L ranking vectors :return: """ results = {"perf": []} ## cross validation ## np.random.seed(1100) kf = KFold(n_splits=cv, shuffle=True, random_state=0) for train, test in kf.split(x): x_train = x[train, :] y_trai...
820f5b53a38d2a64a3a1ee740d0fded020000bb7
16,155
def make_word_groups(vocab_words): """ :param vocab_words: list of vocabulary words with a prefix. :return: str of prefix followed by vocabulary words with prefix applied, separated by ' :: '. This function takes a `vocab_words` list and returns a string with the prefix and the words...
f940c602939ca3a9bab013f5847918f7ba4536ae
16,156
def gpi_g10s40(rescale=False): """ Multiply by the 'rescale' factor to adjust hole sizes and centers in entrance pupil (PM) (Magnify the physical mask coordinates up to the primary mirror size) """ demag = gpi_mag_asdesigned() if rescale: demag = demag/rescale # rescale 1.1 gives a bigge...
4be151f7e99332be0f67d00619fe75def90c2b5d
16,157
import inspect def test_close_sections(): """Parse sections without blank lines in between.""" def f(x, y, z): """ Parameters ---------- x : X y : Y z : Z Raises ------ Error2 error. ...
793d92d989f3caa020c06ea798f7f34703abd747
16,158
def _int_converter(value): """Convert string value to int. We do not use the int converter default exception since we want to make sure the exact http response code. Raises: exception_handler.BadRequest if value can not be parsed to int. Examples: /<request_path>?count=10 parsed to {'count':...
6b5c99635211bf8ce2e3c2adc784f2a4e9ee355f
16,160
from typing import List def split_rule(rules, rule_name, symbols_to_extract: List[str], subrule_name: str): """ Let only options which are starting with symbols from symbols_to_extract. Put the rest to a subrule. """ r = rule_by_name(rules, rule_name) assert isinstance(r.body, Antlr4Selection...
aa4d2aac62c488e3cd8d002556edea3aaef7185b
16,161