content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def coords_to_id(traversed): """calculate the id in level-order from the coordinates Args: input: traversed tree as list of dict Returns: traversed tree (dict) with id as key """ traversed_id = {} #print('coords to id, traversed ', traversed) for node in traversed: ...
91f993f9693e01983de1f7fa124dcb5cb39a92f9
25,600
def dataframe_to_ipy_image(df, f=None, **kwargs): """Create IPython Image from PIL Image. Args: df - dataframe to render f - operation to perform on PIL Image (e.g. f=lambda img: img.rotate(-90, expand=True)) kwargs - arguments to IPython.display.Image, such as width and height for html display ...
44348ac041067620bfa37cdedb22f3544e6bc940
25,601
import os import yaml def get_yaml_file_info(file_name): """Loads a yaml file into a dictionary Args: file_name (str): The file to load Returns: Raises: ProgramError """ if not os.path.isfile(file_name): print("Cannot find file %s" % file_name) raise ProgramE...
516c1484515d26d97dca44d2e2d04eb6fb852026
25,602
def read_dmarkov(columns, rows, D, symbolization_type, division_order, suffix=["normal", "gaussian002"]): """ Reads the result files for the D-Markov algorithm. The function requires a configuration for the parameters of the D-Markov. The suffix parameter indicates if the non-modified files should be loaded...
c9fec2d46cbc8c3f4bcf7fc112779432dd6e9155
25,603
import torch def compute_output_shape(observation_space, layers): """Compute the size of the output after passing an observation from `observation_space` through the given `layers`.""" # [None] adds a batch dimension to the random observation torch_obs = torch.tensor(observation_space.sample()[None]) ...
865b9b90f39f5726feb16da70afc515071991fd7
25,604
def tenure_type(): """ RESTful CRUD controller """ return s3_rest_controller(#rheader = s3db.stdm_rheader, )
bfee3c2be579e1db6e8799b4a9d3156130b802a9
25,605
def _format_port(port): """ compute the right port type str Arguments ------- port: input/output port object Returns ------- list a list of ports with name and type """ all_ports = [] for key in port: one_port = {} one_port['name'] = key port...
2fa65686b6b764afc97a200a02baec65645c9879
25,606
import os def getTileName(minfo,ti,xIndex,yIndex,level = -1): """ creates the tile file name """ global LastRowIndx max = ti.countTilesX if (ti.countTilesY > max): max=ti.countTilesY countDigits= len(str(max)) parts=os.path.splitext(os.path.basename(minfo.filename)) if par...
e48dea5c57e018c1ab99a865a5ceacf6dbd91e29
25,607
import io def proc_cgroups(proc='self'): """Read a process' cgroups :returns: ``dict`` - Dictionary of all the process' subsystem and cgroups. """ assert isinstance(proc, int) or '/' not in proc cgroups = {} with io.open(_PROC_CGROUP.format(proc), 'r') as f: for cgroup_line i...
95cb24cbbb4167dd2fa26ce36d78e5f532f10c1a
25,608
import csv def load_csv_data( data_file_name, *, data_module=DATA_MODULE, descr_file_name=None, descr_module=DESCR_MODULE, ): """Loads `data_file_name` from `data_module with `importlib.resources`. Parameters ---------- data_file_name : str Name of csv file to be loaded fr...
3629dded45954c25e538c53b5c7bc5d0dfec0a39
25,609
def ptFromSudakov(sudakovValue): """Returns the pt value that solves the relation Sudakov = sudakovValue (for 0 < sudakovValue < 1) """ norm = (2*CA/pi) # r = Sudakov = exp(-alphas * norm * L^2) # --> log(r) = -alphas * norm * L^2 # --> L^2 = log(r)/(-alphas*norm) L2 = log(sudakovVal...
8ba504749f13ed1046799b5456d1f6f3c74bfc1e
25,610
def _set_lod_2(gml_bldg, length, width, height, bldg_center): """Adds a LOD 2 representation of the building based on building length, width and height alternative way to handle building position Parameters ---------- gml_bldg : bldg.Building() object A building object, where bldg is ...
309f66319c5cce07adbcb456548b3c29f707d96c
25,611
def load_data(filename: str): """ Load Agoda booking cancellation dataset Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector in either of the following formats: 1) Single dataframe with last column representing ...
808b0e1344352a6645ef090019ac5015172e096c
25,612
def send_mail(subject, message, from_email, recipient_list, html_message='', scheduled_time=None, headers=None, priority=PRIORITY.medium): """ Add a new message to the mail queue. This is a replacement for Django's ``send_mail`` core email method. """ subject = force_text(subject) ...
a97103e5e56463170122252073ebcc873306c708
25,613
def proxy_a_distance(source_X, target_X): """ Compute the Proxy-A-Distance of a source/target representation """ nb_source = np.shape(source_X)[0] nb_target = np.shape(target_X)[0] train_X = np.vstack((source_X, target_X)) train_Y = np.hstack((np.zeros(nb_source, dtype=int), np.ones(nb_targe...
fe0102cfd2a5a3cadb64a5ddfb7705e7b8440028
25,614
import json def load_metadata(stock_model_name="BlackScholes", time_id=None): """ load the metadata of a dataset specified by its name and id :return: dict (with hyperparams of the dataset) """ time_id = _get_time_id(stock_model_name=stock_model_name, time_id=time_id) path = '{}{}-{}/'.format(...
1171bf3a06327e907449872755315db8c34565c8
25,615
from typing import List import torch def evaluate(env: AlfEnvironment, algorithm: RLAlgorithm, num_episodes: int) -> List[alf.metrics.StepMetric]: """Perform one round of evaluation. Args: env: the environment algorithm: the training algorithm num_episodes: number of epis...
0218f1a38be8f897ac3b2a70036213877f5f7654
25,616
from pagure.hooks import BaseHook def get_plugin_names(blacklist=None, without_backref=False): """Return the list of plugins names. :arg blacklist: name or list of names to not return :type blacklist: string or list of strings :arg without_backref: whether or not to include hooks that have ba...
7f3b560334a5680fdcb4a47929613706bb699393
25,617
def is_autosync(*args): """ is_autosync(name, type) -> bool is_autosync(name, tif) -> bool Is the specified idb type automatically synchronized? @param name (C++: const char *) @param type (C++: const type_t *) """ return _ida_typeinf.is_autosync(*args)
0f7eacc9931897f5fc0f076d0e07e0f1e1e01bce
25,618
def scanboards(dirpath): """Scans the directory for board files and returns an array""" print("Scanning for JSON board data files...", end = "") files = [x for x in subfiles(dirpath) if x.endswith(".json") and not x.endswith("index.json")] print("Found {} in \"{}\"".format(len(files), dir...
9cfce78b06fef0b8f7ebaa3d1c5904dfd3e0ec56
25,619
def router_get_notification() -> dict: """Lista todas as configurações do BOT Telegram.""" logger.log('LOG ROTA', "Chamada rota /get_all.") return {"configuracoes": TelegramNotifier.make_current_cfg_dict()}
46faf67e02d537de49616085a1bcbb30f3087805
25,620
def script_filter_maximum_value(config): """ The scripting version of `filter_maximum_value`. This function applies the filter to the entire directory (or single file). It also adds the tags to the header file of each fits file indicating the number of pixels filtered for this filter. Parame...
8eccc2356c803d63c1ddfc7603e1dc784ccc49fe
25,621
import time def pretty_date(d): """ returns a html formatted pretty date """ special_suffixs = {1 : "st", 2 : "nd" , 3 : "rd", 21 : "st", 22 : "nd", 23 : "rd", 31 : "st"} suffix = "th" if d.tm_mday in special_suffixs: suffix = special_suffixs[d.tm_mday] suffix = "<sup>" + suffix + "</sup>" day = ti...
7d6675f115021ddd46b2a614e831c9fae8faf7ad
25,622
from datetime import datetime import dateutil def update(model, gcs_bucket, gcs_object): """Updates the given GCS object with new data from the given model. Uses last_modified to determine the date to get items from. Bases the identity of entities in the GCS object on their 'id' field -- existing ent...
66bde1371383f16c9449a3aec29e894e6a473d44
25,623
import logging def setup_logging( logger: logging.Logger = logging.getLogger(__name__), verbose: bool = False, debug: bool = False, ) -> logging.Logger: """Configure logging.""" if debug: logger.setLevel(logging.DEBUG) elif verbose: logger.setLevel(logging.INFO) else: ...
22024a54fdc6f7a1a542121f032baef33649fe02
25,624
import os def train_protocol(): """ train the model with model.fit() """ model = create_cnn_model(tf_print=True) model.compile(optimizer='adam', loss='mean_squared_error') x_all, y_all = load_data_batch(num_images_total=30000) model.fit(x=x_all, y=y_all, batch_size=128, epochs=50, verbose=1, ...
e9c999c8c5ac53b675a06da5898cccd33aac2bef
25,625
def member_requests_list(context, data_dict): """ Show request access check """ return _only_registered_user()
c3ffdf798aabc80b3bd91160e9a580ff38c9540d
25,626
def get_conductivity(sw_tdep,mesh,rvec,ham_r,ndegen,avec,fill,temp_max,temp_min,tstep,sw_tau,idelta=1e-3,tau0=100): """ this function calculates conductivity at tau==1 from Boltzmann equation in metal """ def calc_Kn(eig,veloc,temp,mu,tau): dfermi=0.25*(1.-np.tanh(0.5*(eig-mu)/temp)**2)/temp ...
0304781bac6160b353a90e5bce061faa89075bc0
25,627
from typing import List from typing import Union import time def time_match( data: List, times: Union[List[str], List[int], int, str], conv_codes: List[str], strptime_attr: str, name: str, ) -> np.ndarray: """ Match times by applying conversion codes to filtering list. Parameters ...
0480f5ca3e29ebcc4f44bef5a81db8fb36f78616
25,628
def find_best_input_size(sizes=[40]): """ Returns the average and variance of the models """ accuracies = [] accuracy = [] t = [] sigma = [] time = [] #sizes = np.arange(5, 80, 5) for size in sizes: #for size in [80]: accuracy = [] N = 20 for j in range(N): ...
3d22441d07b44779cde6c4347669a435568f0378
25,629
import torch def eval_acc(trainer, dataset="val"): """ """ trainer.model.eval() with torch.no_grad(): shot_count = 0 total_count = 0 for inputs,targets in trainer.val_dataset(): inputs = nested_to_cuda(inputs, trainer.device) targets = nested_to_cuda(tar...
452861ccb5805778d5dd0bc83226b73539b8aebb
25,630
import os import sys def which(program): """ Find a program in PATH and return path From: http://stackoverflow.com/q/377017/ """ def is_exe(fpath): found = os.path.isfile(fpath) and os.access(fpath, os.X_OK) if not found and sys.platform == 'win32': fpath = fpath + ".ex...
b58fe57517bf66301ff1de0e8f345674a5796d9d
25,631
def _floor(n, base=1): """Floor `n` to a multiple of `base`""" return n // base * base
49019e4aa925b4f77a7f13f9919d36948bd132cc
25,632
import os def record_pid(ptype: str, running: bool = True) -> int: """ 记录程序运行的PID """ pid = os.getpid() if running else -1 if ptype == 'bpid': i = dao.update_config([ConfigVO(const.Key.Run.BPID.value, pid)], True) elif ptype == 'fpid': i = dao.update_config([ConfigVO(const.Key....
0000a2688a58744f6fdbc8c531f298d8c2154645
25,633
def fixed_timezone(offset): # type: (int) -> _FixedTimezone """ Return a Timezone instance given its offset in seconds. """ if offset in _tz_cache: return _tz_cache[offset] tz = _FixedTimezone(offset) _tz_cache[offset] = tz return tz
401303d1893bc2ab7bee19ba09161549a2cc7fb2
25,634
def getFactoriesInfo(): """ Returns a dictionary with information on how to create an object Sensor from its factory """ return {'Stitcher': { 'factory':'createStitcher' } }
75806002b1ada6bd1a87c9bde6b2e47f587d988d
25,635
from typing import Dict from typing import List from typing import Optional def pending_observations_as_array( pending_observations: Dict[str, List[ObservationFeatures]], outcome_names: List[str], param_names: List[str], ) -> Optional[List[np.ndarray]]: """Re-format pending observations. Args: ...
bc9bfff51b991b413b5861f55c8b0f55331ab763
25,636
import os def sauv_record_jeu(pseudo, collec, numero, score): """ Sauvegarde le nouveau record dans le fichier de record. :param pseudo: Pseudo du joueur ayant réalisé le nouveau record :param collec: Collection du puzzle sur lequel il y a eu un nouveau record :param numero: Numero du puzzle sur ...
4b1e4176898eadc4fff965d0f9d4c2da37a7859a
25,637
def inverted_conditional_planar(input_dim, context_dim, hidden_dims=None): """ A helper function to create a :class:`~pyro.distributions.transforms.ConditionalPlanar` object that takes care of constructing a dense network with the correct input/output dimensions. :param input_dim: Dimension of inpu...
8bf5ae5dd6d8743a3eb1506b26dec5cf51af2bde
25,638
def create_category_index(categories): """Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category...
226a39189d4203e2861bbba7334d5b8bbaa3b7df
25,639
import torch def n_step_returns(q_values, rewards, kls, discount=0.99): """ Calculates all n-step returns. Args: q_values (torch.Tensor): the Q-value estimates at each time step [time_steps+1, batch_size, 1] rewards (torch.Tensor): the rewards at each time step [time_steps, batch_size, 1]...
3bbd6026046328dc8ef63ab3e871f6c47636cb80
25,640
import os def user(*args: str) -> str: """ Creates an absolute path from the specified relative components within the user's Cauldron app data folder. :param args: Relative components of the path relative to the root package :return: The absolute path """ return clean(os....
6ab8750b5c29a1d23ed194adab569b4c7b7c87c3
25,641
import random def random_split_exact(iterable, split_fractions=None): """Randomly splits items into multiple sample lists according to the given split fractions. The number of items in each sample list will be given exactly by the specified fractions. Args: iterable: a finite iterable ...
2b7ae86e55b9be225e94cfc983295beeb3ed08cf
25,642
def calc_output_coords(source_dataset, config, model_profile): """Construct the coordinates for the dataset containing the extracted variable(s). The returned coordinates container has the following mapping of attributes to coordinate names: * :kbd:`time`: :kbd:`time` * :kbd:`depth`: :kbd:`depth` ...
22759d734f5356bc0597db5528eac864df23d39c
25,643
def computeMaskIntra(inputFilename, outputFilename, m=0.2, M=0.9, cc=1): """ Depreciated, see compute_mask_intra. """ print "here we are" return compute_mask_intra(inputFilename, outputFilename, m=m, M=M, cc=cc)
0eaf8b8845c12b1fc90cb032881dacf53a2c7d12
25,644
def read_space_delimited(filename, skiprows=None, class_labels=True): """Read an space-delimited file skiprows: list of rows to skip when reading the file. Note: we can't use automatic comment detection, as `#` characters are also used as data labels. class_labels: boolean if true, the last ...
be25b4f6c3c775f12fdfef7f334b4886c85a514e
25,645
def get_gas_price(endpoint=_default_endpoint, timeout=_default_timeout) -> int: """ Get network gas price Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- int Ne...
b7f18a5a5044d8aeee7a63b702b01944cbff597b
25,646
def function_3(): """This is a Function prototype in Python""" print("Printing Docs String") return 0
4268904e75772b9fef804931e3a3564fda333bc7
25,647
def client(): """ client fixture """ return testing.TestClient(app=service.microservice.start_service(), headers=CLIENT_HEADERS)
ea9997f9904057f0ffdc3175f081acb7e21e719d
25,648
def get_character_bullet(index: int) -> str: """Takes an index and converts it to a string containing a-z, ie. 0 -> 'a' 1 -> 'b' . . . 27 -> 'aa' 28 -> 'ab' """ result = chr(ord('a') + index % 26) # Should be 0-25 if index > 25: current = index // 26 whi...
357f68feb302f11a996b5446c642ad9ca1f0f8d3
25,649
import os def get_masks_path(base_dir, trial, prune_iter): """Builds the mask save path""" return os.path.join( base_dir, "trial_{:02d}".format(trial), "prune_iter_{:02d}".format(prune_iter), "masks", )
7da9d346aa42b5ea9d291b3422aa447cce02db53
25,650
def update_det_cov( res: OptResult, jacobian: JacobianValue): """Calculates the inv hessian of the deterministic variables Note that this modifies res. """ covars = res.hess_inv for v, grad in jacobian.items(): for det, jac in grad.items(): cov = propagate_uncert...
c505654be6f08dcf037337104b4077f6003db876
25,651
def simplex_init_modified(A, b, c): """ Attempt to find a basic feasible vector for the linear program max: c*x ST: Ax=b x>=0, where A is a (m,n) matrix. Input Parameters: A - (n,m) constraint matrix b - (m,1) vector appearing in the constr...
fd415eedaec1138812fb054656c45450a53535b8
25,652
import os def get_all_user_dir(): """get the root user dir. This is the dir where all users are stored Returns: str: path """ return os.path.join(get_base_dir(), ALL_USER_DIR_NAME)
225c30e1d956722c63facde6d876f757dc8c40d5
25,653
def LeakyRelu( alpha: float, do_stabilize: bool = False) -> InternalLayer: """Leaky ReLU nonlinearity, i.e. `alpha * min(x, 0) + max(x, 0)`. Args: alpha: slope for `x < 0`. do_stabilize: set to `True` for very deep networks. Returns: `(init_fn, apply_fn, kernel_fn)`. """ return ABRelu(al...
93a9f103c42979e5107291f818d387eb06feb41b
25,654
def load_interp2d(xz_data_path: str, y: list): """ Setup 2D interpolation Example: x1, y1, z1, x2, y2, z2\n 1, 3, 5, 1, 4, 6\n 2, 3, 6, 2, 4, 7\n 3, 3 7, 3, 4, 8\n xy_data_path will lead to a file such as: 1,5,6\n 2,6,7\n 3,7,8\n y will be: [3, 4] ...
0883c317c44a97a8e38c615285315adb22a091c5
25,655
def save_new_party(json_data): """saves a new party in the database Args: json_data (json) : party details Returns: json : api endpoint response """ # Deserialize the data input against the party schema # check if input values throw validation errors try: data = p...
e6a11646c1aa13bfceabb1c143308fc985b3f59d
25,656
import sys def _system_path_separator(): """ System dependent character for element separation in PATH variable :rtype: str """ if sys.platform == 'win32': return ';' else: return ':'
b89a77d5b444a1b806a75e9f024f2084e3cfc93f
25,657
def cost_function(theta, X, y, lamda=0.01, regularized=False): """ Compute cost and gradient for logistic regression with and without regularization. Computes the cost of using theta as the parameter for regularized logistic regression and the gradient of the cost w.r.t. to the parameters. using l...
e4002fc30455be730e6ba46db85588b113e24451
25,658
from pathlib import Path import torch def read_image_numpy(input_filename: Path) -> torch.Tensor: """ Read an Numpy file with Torch and return a torch.Tensor. :param input_filename: Source image file path. :return: torch.Tensor of shape (C, H, W). """ numpy_array = np.load(input_filename) ...
987185e7b207ecae1abcf01fd5ea939ace0fb869
25,659
import argparse def init_argparse(): """Parses the required arguments file name and source database type and returns a parser object""" parser = argparse.ArgumentParser( usage="%(prog)s --filename 'test.dtsx' --source 'postgres'", description="Creates a configuration file in the output directo...
1c57c6712819d147ef7917d1100c20353339f7b4
25,660
def solution(n: int = 4000000) -> int: """Returns the sum of all fibonacci sequence even elements that are lower or equals to n. >>> solution(10) 10 >>> solution(15) 10 >>> solution(2) 2 >>> solution(1) 0 >>> solution(34) 44 """ fib = [0, 1] i = 0 while ...
b2c3983b9888ae8a10b4ceca2faf5d943b17fbe3
25,661
def triu(m: ndarray, k: int = 0) -> ndarray: """ Upper triangle of an array. """ af_array = af.data.upper(m._af_array, is_unit_diag=False) return ndarray(af_array)
00b0b4a301b0b59214a53d8b741c7417bac95f3d
25,662
def generate_annotation(overlay_path,img_dim,ext): """ Generate custom annotation for one image from its DDSM overlay. Args: ---------- overlay_path: string Overlay file path img_dim: tuple (img_height,img_width) ext: string Image ...
e9d334c834063ee27b5b9a9d597f084bc735f794
25,663
from datetime import datetime def parse_episode_page(loc, contents): """Parse a page describing a single podcast episode. @param loc: The URL of this page. @type loc: basestring @param contents: The raw HTML contents of the episode page from which episode information should be parsed. @ty...
805e466c15741ee004059817efa70da66e470871
25,664
def _bitarray_to_message(barr): """Decodes a bitarray with length multiple of 5 to a byte message (removing the padded zeros if found).""" padding_len = len(barr) % 8 if padding_len > 0: return bitstring.Bits(bin=barr.bin[:-padding_len]).bytes else: return barr.bytes
79e601bc30519e42c8dbf2369deea5b36a5851ff
25,665
import os import subprocess import logging def join(kmerfile, codonfile, minhashfile, dtemp): """Externally join with built-in GNU Coreutils in the order label, kmers, codons ,minhash Args: kmerfile (str): Kmer csv file codonfile (str): Codon csv file minhashfile (str): Minhas...
d3a373573d87a0312ecb8291bb0c81479f6402b6
25,666
def align_address_to_page(address: int) -> int: """Align the address to a page.""" a = align_address(address) >> DEFAULT_PAGE_ALIGN_SHIFT return a << DEFAULT_PAGE_ALIGN_SHIFT
1211d3c1a3ae6b1bd183f3d1b1cfb1097fc7dc40
25,667
from typing import List from sys import path def virtual_entities(entity: AnyText, kind: int = Kind.HATCHES) -> EntityQuery: """Convert the text content of DXF entities TEXT and ATTRIB into virtual SPLINE and 3D POLYLINE entities or approximated LWPOLYLINE entities as outlines, or as HATCH entities as fil...
9d02dab1d2ed975d206888f403358db9e56936b1
25,668
def getNamespace(modelName): """Get the name space from rig root Args: modelName (str): Rig top node name Returns: str: Namespace """ if not modelName: return "" if len(modelName.split(":")) >= 2: nameSpace = ":".join(modelName.split(":")[:-1]) else: ...
abfb4c54f2dd1b54563f6c7c84e902ed4ee77b01
25,669
import re def compile_rules(environment): """Compiles all the rules from the environment into a list of rules.""" e = re.escape rules = [ ( len(environment.comment_start_string), TOKEN_COMMENT_BEGIN, e(environment.comment_start_string), ), ( ...
ca7971de422f66e9c9574c13306610e84a000271
25,670
import os def get_output(db, output_id): """ :param db: a :class:`openquake.server.dbapi.Db` instance :param output_id: ID of an Output object :returns: (ds_key, calc_id, dirname) """ out = db('SELECT output.*, ds_calc_dir FROM output, job ' 'WHERE oq_job_id=job.id AND output.id=?...
8ad5cd6b5ca0808038ee29345b8d3e53e80fb9de
25,671
def compute_window_based_feature(seq, sample_freq, func_handle, window_length, window_stride, verbose=False, **kwargs): ...
4ab084d3459c617640e404b5232db4557b22c8b8
25,672
def read_cif(filename): """ read the cif, mainly for pyxtal cif output Be cautious in using it to read other cif files Args: filename: path of the structure file Return: pyxtal structure """ species = [] coords = [] with open(filename, 'r') as f: lines = f....
d6d164a6425d088a17bb449b75e875047a5fbc29
25,673
import random def custom_data_splits(src_sents, trg_sents, val_samples=3000, seed=SEED): """ splits data based on custom number of validation/test samples :param src_sents: the source sentences :param trg_sents: the target sentences :param val_samples: number of validation/test samples :param ...
5a4754ce9fe400248a46f4868aeaa0b96ebd5760
25,674
def normalize(output): """将null或者empty转换为暂无输出""" if not output: return '暂无' else: return output
18af58c74325522a64dcfd98a75f55e677c01ca3
25,675
def sgd(args): """ Wrapper of torch.optim.SGD (PyTorch >= 1.0.0). Implements stochastic gradient descent (optionally with momentum). """ args.lr = 0.01 if args.lr == -1 else args.lr args.weight_decay = 0 if args.weight_decay == -1 else args.weight_decay args.momentum = 0 if args.momentum == -1 ...
17a852165766bcf02f92bac4c847684f2dcfb133
25,676
def normal_conjugates_known_scale_posterior(prior, scale, s, n): """Posterior Normal distribution with conjugate prior on the mean. This model assumes that `n` observations (with sum `s`) come from a Normal with unknown mean `loc` (described by the Normal `prior`) and known variance `scale**2`. The "known scal...
0bc94999ee10ce63ba0156510a9807523de6c085
25,677
def make_matrix(num_rows, num_cols, entry_fn): """retorna a matriz num_rows X num_cols cuja entrada (i,j)th é entry_fn(i, j)""" return [[entry_fn(i, j) # dado i, cria uma lista for j in range(num_cols)] # [entry_fn(i, 0), ... ] for i in range(num_rows)]
f706773245730eab3ce6cf41b0f6e81fbe3d52ab
25,678
def add_relationtoforeignsign(request): """Add a new relationtoforeignsign instance""" if request.method == "POST": form = RelationToForeignSignForm(request.POST) if form.is_valid(): sourceid = form.cleaned_data['sourceid'] loan = form.cleaned_data['loan'] ...
44e6a80ed4596b9dae48ce8f4ed37927feb1ec71
25,679
def check_url(url): """ Check if a URL exists without downloading the whole file. We only check the URL header. """ good_codes = [httplib.OK, httplib.FOUND, httplib.MOVED_PERMANENTLY] return get_server_status_code(url) in good_codes
f6dede6aaf41f404c182052cd4dc5708b9a0b879
25,680
def table(df, sortable=False, last_row_is_footer=False, col_format=None): """ generate an HTML table from a pandas data frame Args: df (df): pandas DataFrame col_format (dict): format the column name (key) using the format string (value) Return...
05c7250673160f74fab6ca9ad46b02c7e948c9c8
25,681
from datetime import datetime def ap_time_filter(value): """ Converts a datetime or string in hh:mm format into AP style. """ if isinstance(value, basestring): value = datetime.strptime(value, '%I:%M') value_tz = _set_timezone(value) value_year = value_tz.replace(year=2016) return ...
0539cd58bfa4b7ee647ac88a58bcac93108d4819
25,682
def make_signal(time, amplitude=1, phase=0, period=1): """ Make an arbitrary sinusoidal signal with given amplitude, phase and period over a specific time interval. Parameters ---------- time : np.ndarray Time series in number of days. amplitude : float, optional A specific ampl...
9f940922ae2a4bf1e3ff7d1c13351f4d07c40ca8
25,683
def train_data(X, y): """ :param X: numpy array for date(0-5), school_id :param y: output for the data provided :return: return the learned linear regression model """ regression = linear_model.LinearRegression() regression.fit(X, y) return regression
abaa0ba6f02ed111b6ec9b0945e9e26c643836be
25,684
import re def clean_text(s, stemmer, lemmatiser): """ Takes a string as input and cleans it by removing non-ascii characters, lowercasing it, removing stopwords and lemmatising/stemming it - Input: * s (string) * stemmer (object that stems a string) * lemmatiser (object that le...
0bcb14378c6b72e24526c7eff9f1daf2b6871152
25,685
def make_rst_sample_table(data): """Format sample table""" if data is None: return "" else: tab_tt = tt.Texttable() tab_tt.set_precision(2) tab_tt.add_rows(data) return tab_tt.draw()
160b28355f1bea80878417f2a92e5dc31dde66cd
25,686
def is_thunk(space, w_obj): """Check if an object is a thunk that has not been computed yet.""" while 1: w_alias = w_obj.w_thunkalias if w_alias is None: return space.w_False if w_alias is w_NOT_COMPUTED_THUNK: return space.w_True w_obj = w_alias
1918a7d79d02a2a20e6f7ead8b7a2dc6cfe05a85
25,687
def plot_roc_curve( fpr, tpr, roc_auc=None, ax=None, figsize=None, style="seaborn-ticks", **kwargs, ): """Plots a receiver operating characteristic (ROC) curve. Args: fpr: an array of false postive rates tpr: an array of true postive rates roc_auc (None): the...
d4d6f9d33857598a16b04097de035a5a7a3f354b
25,688
def my_place_or_yours(our_address: Address, partner_address: Address) -> Address: """Convention to compare two addresses. Compares lexicographical order and returns the preceding address """ if our_address == partner_address: raise ValueError("Addresses to compare must differ") sorted_addresses...
991b2d44042520eea28817f33cbb9421d7b99a78
25,689
def get_dataset_json(met, version): """Generated HySDS dataset JSON from met JSON.""" return { "version": version, "label": met['data_product_name'], "starttime": met['sensingStart'], }
d84f3652866c83e8c1618a9f87bc3bf6b5c6a0cf
25,690
def hlmoft_SEOB_dict(P,Lmax=2): """ Generate the TD h_lm -2-spin-weighted spherical harmonic modes of a GW with parameters P. Returns a dictionary of modes. Just for SEOBNRv2 SEOBNRv1, and EOBNRv2. Uses aligned-spin trick to get (2,2) and (2,-2) modes. A hack. Works for any aligned-spin time-do...
b963958e3defbed0e61cb0691fcef329ceadf313
25,691
def encode(value): """ pyg_mongo.encoder is similar to pyg_base.encoder with the only exception being that bson.objectid.ObjectId used by mongodb to generate the document _id, are not encoded Parameters ---------- value : value/document to be encoded Returns ------- encoded value/docum...
fa7dec607dca66736e3b9203bf97289a0ffdd733
25,692
def locate_line_segments(isolated_edges): """ Extracts line segments from observed lane edges using Hough Line Transformations :param isolated_edges: Lane edges returned from isolated_lane_edges() :return: Line segments extracted by HoughLinesP() """ rho = 1 theta = np.pi / 180 threshold...
3b26da0535b327dfac4b268552209c75481bb4d2
25,693
def proj(A, B): """Returns the projection of A onto the hyper-plane defined by B""" return A - (A * B).sum() * B / (B ** 2).sum()
982cdfb1564166dce14432bf24404f066e2acee3
25,694
def v6_multimax(iterable): """Return a list of all maximum values. Bonus 2: Make the function works with lazy iterables. Our current solutions fail this requirement because they loop through our iterable twice and generators can only be looped over one time only. We could keep track of the maximu...
5539adb0dcb6c9db4f8f2f68487fc13c6aa8d067
25,695
import traceback def format_traceback_string(exception): """Format exception traceback as a single string. Args: exception: Exception object. Returns: Full exception traceback as a string. """ return '\n'.join( traceback.TracebackException.from_exception(exception).format...
debdf53966b26b6562671bf48d283a3bf10d85d5
25,696
def get_stored_file(file_id): """Get the "stored file" or the summary about the file.""" return JsonResponse(StoredFile.objects(id=ObjectId(file_id)).first())
860f6f5dd24e5ebaf59fff1f4c82f4b5c7ce6da5
25,697
def _compute_array_job_index(): # type () -> int """ Computes the absolute index of the current array job. This is determined by summing the compute-environment-specific environment variable and the offset (if one's set). The offset will be set and used when the user request that the job runs in a n...
5c9b451af75f894ad49dc8aa95b7c1a80e6e9c96
25,698
def make_transpose(transpose_name, input_name, input_type, perm): """Makes a transpose node. Args: transpose_name: name of the transpose op. input_name: name of the op to be the tranpose op's input. input_type: type of the input node. perm: permutation array, e.g. [0, 2, 3, 1] for NCHW ...
21e05caed8a439f748f3fa939b5bff9864c2525d
25,699