content
stringlengths
22
815k
id
int64
0
4.91M
def create_qme_trial(nc: int, q: int, trials: int, well_formed: bool): """ well_formed: whether the trial should contain well_formed (a, B) Create `trials` trials for `nc` classes. Saves to folder trials/qme/k=nc. """ np.random.seed(7) # reproducability os.makedirs("trials", exist_ok=True) ...
48,700
def profile_send_transfer_ownership_request( context: Context, supplier_alias: str, company_alias: str, new_owner_alias: str ): """ Due to bug ED-2268 the first time you visit SUD pages by going directly to SUD "Find a Buyer" page, then you're redirected to SUD "About" page To circumvent this behavi...
48,701
def solve(A, b): """solve a sparse system Ax = b Args: A (torch.sparse.Tensor[b, m, m]): the sparse matrix defining the system. b (torch.Tensor[b, m, n]): the target matrix b Returns: x (torch.Tensor[b, m, n]): the initially unknown matrix x Note: 'A' should be 'dense'...
48,702
def paths(alembic_files): """ 获取文件路径交集 :rtype: list """ #get texture sets def _get_set(path): # 获取文件路径集合 _list = [] def _get_path(_path, _list): _path_new = os.path.dirname(_path) if _path_new != _path: _list.append(_path_new) ...
48,703
def test_ap_ft_invalid_resp(dev, apdev): """WPA2-PSK-FT AP and invalid response IEs""" ssid = "test-ft" passphrase="12345678" params = ft_params1(ssid=ssid, passphrase=passphrase) hapd0 = hostapd.add_ap(apdev[0], params) dev[0].connect(ssid, psk=passphrase, key_mgmt="FT-PSK", proto="WPA2", ...
48,704
def smiles_to_fp(smiles): """ Convert smiles to Daylight FP and MACCSkeys. Parameters ---------- smiles : str, smiles representation of a molecule Returns ------- fp : np.ndarray zero and one representation of the fingerprints """ try: mol = Chem.MolFromSmiles(smiles) ...
48,705
def save_environment(filename): """Dump current environment into a CSV file given in `filename`""" with open(filename, 'w') as csvfile: writer = csv.writer(csvfile) for row in environment: writer.writerow(map(int, row))
48,706
def _networkinfo(interface): """Given an interface name, returns dict containing network and broadcast address as IPv4Interface objects If an interface has no IP, returns None """ ipcmds = "ip -o -4 address show dev {}".format(interface).split() out = check_output(ipcmds).decode('utf-8') nw...
48,707
def handle_view_errors(func): """ view error handler wrapper # TODO - raise user related errors here """ @functools.wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except ValueError as e: message: str = str(e) ...
48,708
def eztrim( clip: vs.VideoNode, /, trims: Union[List[Trim], Trim], audio_file: str, outfile: Optional[str] = None, *, ffmpeg_path: Optional[str] = None, quiet: bool = False, timecodes_file: Optional[str] = None, debug: bool = False, ) -> Union[Dict, str]: """ Simple trimm...
48,709
def score_decorator(f): """Decorator for sklearn's _score function. Special `hack` for sklearn.model_selection._validation._score in order to score pipelines that drop samples during transforming. """ def wrapper(*args, **kwargs): args = list(args) # Convert to list for item assignment ...
48,710
def monkey_patch(state_path: Optional[str]) -> None: """ Apply all monkey patches to the specification. """ from . import dao_fork, frontier, homestead frontier.monkey_patch(state_path) homestead.monkey_patch(state_path) dao_fork.monkey_patch(state_path)
48,711
def trait(name, notify=True, optional=False): """ Create a new expression for observing a trait with the exact name given. Events emitted (if any) will be instances of :class:`~traits.observation.events.TraitChangeEvent`. Parameters ---------- name : str Name of the trait to match....
48,712
def get_splits(space, data, props, max_specs=None, seed=None, fp_type="morgan"): """ Get representations and values of the data given a certain set of Morgan hyperparameters. Args: space (dict): hyperopt` space of hyperpara...
48,713
def download(url, *paths): """Download a file if it isn't already present""" chunkSize = 4096 h = hashlib.sha256() if path.isfile(path.isfile(wspath(*paths))): logging.info( '"{}" already exists. Will not download.'.format(wspath(*paths))) return (False, calculateSha256(*pa...
48,714
def amortized_loan(principal, apr, periods, m=12): """ """ return principal / pvifa(apr, periods, m)
48,715
def size(): """ :requires: sympy """ from sympy import Symbol from sympy import integrate, exp, pi x = Symbol('x') y = Symbol('y') mu = Symbol('mu') sigma = Symbol('sigma') tmpx = (x - mu) tmpy = (y - mu) integrand = (1/(2*pi*sigma**2)) * exp(-((tmpx**2 + tmpy**2) / (2*...
48,716
def _icc_to_dict(field_data): """ Get de55 fields from message :param field_data: the field containing de55 :return: dictionary of de55 key values key is tag+tagid """ TWO_BYTE_TAG_PREFIXES = [b'\x9f', b'\x5f'] field_pointer = 0 return_values = {"ICC_DATA": binascii.b2a_he...
48,717
def horizontal_legend( fig: Figure, handles: Optional[Iterable[Artist]] = None, labels: Optional[Iterable[str]] = None, *, ncol: int = 1, **kwargs, ) -> Legend: """ Place a legend on the figure, with the items arranged to read right to left rather than top to bottom. :param fig: The figure to plot the...
48,718
def _create_lock_inventory(session, rp_uuid, inventories): """Return a function that will lock inventory for this rp.""" def _lock_inventory(): rp_url = '/resource_providers/%s' % rp_uuid inv_url = rp_url + '/' + 'inventories' resp = session.get(rp_url) if resp: data ...
48,719
def train_algorithm(use_case_id: int, use_case_step: int, user_emotion: str, user_emotion_reason: str) -> None: """ To train the algorithm, first we check if there are at least 20 data points for every ERG This means there we need a lot of starting data to start this process It just doesn't make sense t...
48,720
def strip(string, p=" \t\n\r"): """ strip(string, p=" \t\n\r") """ return string.strip(p)
48,721
def deepvariant_header(contigs, sample_names, add_info_candidates=False, include_med_dp=True): """Returns a VcfHeader used for writing VCF output. This function fills out the FILTER, INFO, FORMAT, and extra header information created by the Dee...
48,722
def correlation_matrix_plot( df, function=pearsonr, significance_level=0.05, cbar_levels=8, figsize=(6, 6) ): """Plot corrmat considering p-vals.""" corr, pvals = correlation_matrix(df, function=function) # create triangular mask for heatmap mask = np.zeros_like(corr) mask[np.triu_indices_from(...
48,723
def _unvec(vecA, m=None): """inverse of _vec() operator""" N = vecA.shape[0] if m is None: m = np.sqrt(vecA.shape[1] + 0.25).astype(np.int64) return vecA.reshape((N, m, -1), order='F')
48,724
def test_qs_application( qapp: QuteStyleApplication, ) -> None: """Test qs app.""" assert qapp.APP_DATA.app_name == "Test-App" assert qapp.APP_DATA.app_version == "2.3.4" assert not qapp.STARTUP_THREADS
48,725
def one_hot_encode(sequences): """One hot encoding of a list of DNA sequences Args: sequences (list):: python list of strings of equal length Returns: numpy.ndarray: 3-dimension numpy array with shape (len(sequences), len(list_item), 4) """...
48,726
def make_fire(player): """ creates a fire reducing chance of nighttime attacks """ labor = random.randint(5, 10) print("you gather wood and make a fire\nyou feel warm, and the night recedes\n") print("-{} exhaustion\n".format(labor), "yellow") player.exhaustion -= labor if random.randint(1, 4)...
48,727
def binary_cross_entropy(labels, logits, linear_input=True, eps=1.e-5, name='binary_cross_entropy_loss'): """ Same as cross_entropy_loss for the binary classification problem. the model should have a one dimensional output, the targets should be given in form of a matrix of dimensions batch_size x 1 with va...
48,728
def get_number_from_user(): """ None -> (int) Get a symbol by index from the user's input. """ movers = ApiWrapper.get_movers() while True: print("To choose a company, enter a responding integer from the list below") print_movers(movers) y = input("Enter the number of compan...
48,729
def check_service_replication( instance_config, all_tasks, smartstack_replication_checker, ): """Checks a service's replication levels based on how the service's replication should be monitored. (smartstack or mesos) :param instance_config: an instance of MarathonServiceConfig :param smarts...
48,730
def handle_templates(url, domain, _method, **kwargs): """ Handle Templates :param url: Incoming URL dictionary :type url: dict :param domain: Incoming domain :type domain: str :param _method: Incoming request method (but not used here) :type _method: str :param kwargs: kwargs :re...
48,731
def filter_sv_vcf(vcf_file, flank=10, filter_name='DB', filter_query=False, filter_ori=False, filter_count=2): """ Parse vcf files and filter on database. Args: vcf_file (str): Path to vcf file """ # Open vcf file try: vcf = py_vcf.Reader(open(vcf_file, 'r')) except IOError:...
48,732
async def clean_day(message): """ """ global average_typing_speed if message.author != bot.user: msg = message.content if any(name in msg for name in names) \ and "should I clean today" in msg \ and "?" in msg: day_tasks = [ "Di...
48,733
def read_refseqscan_results(fn): """Read RefSeqScan output file""" ret = dict() for line in open(fn): line = line.strip() if line == '' or line.startswith('#'): continue cols = line.split() ret[cols[0]] = cols[2] return ret
48,734
def discretize_categories(iterable): """ :param iterable: :return: """ uniques = sorted(set(iterable)) discretize = False for v in uniques: if isinstance(v, str): discretize = True if discretize: # Discretize and return an array str_to_int_map = {} ...
48,735
def multhist(hists, asone=1): """Takes a set of histograms and combines them. If asone is true, then returns one histogram of key->[val1, val2, ...]. Otherwise, returns one histogram per input""" ret = {} num = len(hists) for i, h in enumerate(hists): for k in sorted(h): if k...
48,736
def parse_ldb(fout_name, fin_name=CFG.chainstate_path, decode=True): """ Parsed data from the chainstate LevelDB and stores it in a output file. :param fout_name: Name of the file to output the data. :type fout_name: str :param fin_name: Name of the LevelDB folder (CFG.chainstate_path by default) ...
48,737
def test_generate_telemetry(run_generate, summary_store: SummaryStore): """ Telemetry data polygons can be synthesized from the path/row values """ run_generate("ls8_satellite_telemetry_data") _expect_values( summary_store.get("ls8_satellite_telemetry_data"), dataset_count=1199, ...
48,738
def to_dict(obj, table=None, scrub=None, fields=None): """ Takes a single or list of sqlalchemy objects and serializes to JSON-compatible base python objects. If scrub is set to True, then this function will also remove all keys that match the specified list """ data = None serialize_obj = ...
48,739
def CWLoss(output, target, confidence=0): """ CW loss (Marging loss). """ num_classes = output.shape[-1] target = target.data target_onehot = torch.zeros(target.size() + (num_classes,)) target_onehot = target_onehot.cuda() target_onehot.scatter_(1, target.unsqueeze(1), 1.) target_var...
48,740
def get_square(array, size, y, x, position=False, force=False, verbose=True): """ Return an square subframe from a 2d array or image. Parameters ---------- array : 2d array_like Input frame. size : int Size of the subframe. y : int Y coordinate of the center of the s...
48,741
def iou_with_anchors(anchors_min, anchors_max, box_min, box_max): """Compute jaccard score between a box and the anchors. """ len_anchors = anchors_max - anchors_min int_xmin = np.maximum(anchors_min, box_min) int_xmax = np.minimum(anchors_max, box_max) inter_len = np.maximum(int_xmax - int_xmi...
48,742
def load_from_np(filename, arr_idx_der): """ arr_idx_der 1 for rho and 2 for p """ # load npy data of 3D tube arr = np.load(filename) arr_t = arr[:, 0] arr_der = arr[:, arr_idx_der] return arr_t, arr_der
48,743
def rxzero_vel_amp_eval(parm, t_idx): """ siglognormal velocity amplitude evaluation """ if len(parm) == 6: D, t0, mu, sigma, theta_s, theta_e = parm elif len(parm) == 4: D, t0, mu, sigma = parm else: print 'Invalid length of parm...' return None #argument for...
48,744
def get_image_from_request(request, type): """ Based on the content type, get the image data from the request. """ logger.info(prepend_ip("get_image_from_request method=%s content_type=%s" %(request.method, request.content_type), request)) logger.debug("first 32 bytes of body: %s" %request.body[:32]) if...
48,745
def read_json(json_file): """ Read input JSON file and return the dict. """ json_data = None with open(json_file, 'rt') as json_fh: json_data = json.load(json_fh) return json_data
48,746
def mixnet_xl(pretrained=False, num_classes=1000, in_chans=3, **kwargs): """Creates a MixNet Extra-Large model. Not a paper spec, experimental def by RW w/ depth scaling. """ default_cfg = default_cfgs['mixnet_xl'] #kwargs['drop_connect_rate'] = 0.2 model = _gen_mixnet_m( channel_multipl...
48,747
def accuracy(results): """ Evaluate the accuracy of results, considering victories and defeats. Args: results: List of 2 elements representing the number of victories and defeats Returns: results accuracy """ return results[1] / (results[0] + results[1]) * 100
48,748
def sub_sellos_agregar(): """ Agregar nuevo registro a 'sub_sellos' """ form = SQLFORM(db.sub_sellos, submit_button='Aceptar') if form.accepts(request.vars, session): response.flash = 'Registro ingresado' return dict(form=form)
48,749
async def ensure_valid_path(current_path: str) -> bool: """ ensures the path is configured to allow auto refresh """ paths_to_check = settings.NO_AUTO_REFRESH for path in paths_to_check: if path in current_path: return False return True
48,750
def lookup_series(name=None, tvdb_id=None, only_cached=False, session=None, language=None): """ Look up information on a series. Will be returned from cache if available, and looked up online and cached if not. Either `name` or `tvdb_id` parameter are needed to specify the series. :param unicode name: ...
48,751
def secure_boot_settings(): """1.4 Secure Boot Settings""" if os.path.isfile('/boot/grub/menu.lst'): exec_shell([ 'chown root:root /boot/grub/menu.lst', 'chmod og-rwx /boot/grub/menu.lst' ]) PropertyFile('/etc/sysconfig/init', '=').override({ 'SINGLE': '/sbi...
48,752
def visual_summary(type_, df, col): """Summarize the Data using Visual Method. This function accepts the type of visualization, the data frame and the column to be summarized. It displays the chart based on the given parameters. Keyword arguments: type_ -- visualization method to be used ...
48,753
def part_1_original_approach(lines: List[str]) -> int: """ This was my original approach. I missed a few critical details that really bit me in the ass. 1. Operator precedence for modulo. """ ans = 0 seq = [[int(c) for c in x] for x in lines] for _ in range(100): ns = [[(a + 1)...
48,754
def pacman_packages_to_update(): """ Return the packages to update from the pacman's database. """ pacman_proc = subprocess.Popen(["/bin/pacman -Qu"], stdout=subprocess.PIPE, shell=True) (pacman_out, pacman_err) = pacman_proc.communicate() if pacman_proc.returncode == 0: pkgs_to_update = pac...
48,755
def get_distances(username,location,dist): """ The purpose of this function is the calculation of distances between user and created rooms """ distances=[] keys = ['_id','dist'] base=list(nego.find({},{'location':0})) ## Retrieves every user in the base except location for d in base: ...
48,756
def AcProgEgrep(context, grep, selection=None): """Corresponds to AC_PROG_EGREP_ autoconf macro :Parameters: context SCons configuration context. grep Path to ``grep`` program as found by `AcProgGrep`. selection If ``None`` (default), the program will...
48,757
def test_hub_height(hub_height): """ Test WindRose serial vs parallel """ wspd_bins = (0, 30, 1) wdir_bins = (0, 360, 5) with WindResource(WIND_H5) as f: wspd = f[f'windspeed_{hub_height}m'] wdir = f[f'winddirection_{hub_height}m'] test = JointPD.wind_rose(WIND_H5, hub_heigh...
48,758
def is_number(s): """Is string a number.""" try: float(s) return True except ValueError: return False
48,759
def save_params(params, fname): """ Pickle uses different protocols to convert your data to a binary stream. - In python 2 there are 3 different protocols (0, 1, 2) and the default is 0. - In python 3 there are 5 different protocols (0, 1, 2, 3, 4) and the default is 3. You must specify in python 3 ...
48,760
def install_thread_excepthook(): # Workaround for sys.excepthook thread bug """See https://bugs.python.org/issue1230540 for details.""" init_original = threading.Thread.__init__ def init(self, *args, **kwargs): """Docstring.""" init_original(self, *args, **kwargs) run_original = se...
48,761
def calc_motif_dist(motifList): """Given a list of motifs, returns a dictionary of the distances for each motif pair, e.g. {Motif1:Motif2:(dist, offset, sense/antisense)} """ ret = {} for m1 in motifList: for m2 in motifList: if m1.id != m2.id: #check if the score...
48,762
def step(name=None): """ Decorates functions that will register a step. """ def decorator(func): add_step(get_name(name, func), func) return func return decorator
48,763
def prepare_subimg(image5d, size, offset): """Extracts a subimage from a larger image. Args: image5d: Image array as a 5D array (t, z, y, x, c), or 4D if no separate channel dimension exists as with most one channel images. size: Size of the region of interest as ...
48,764
def filter_plants_by_region_id(region_id, year, host='switch-db2.erg.berkeley.edu', area=0.5): """ Filters generation plant data by NERC Region, according to the provided id. Generation plants w/o Region get assigned to the NERC Region with which more than a certain percentage of its County area interse...
48,765
def _get_image_blob(roidb, scale_ind): """Builds an input blob from the images in the roidb at the specified scales. """ num_images = len(roidb) processed_ims = [] # processed_ims_depth = [] # processed_ims_normal = [] im_scales = [] for i in xrange(num_images): # rgba ...
48,766
def adjust_learning_rate(learning_rate, optimizer, epoch, lr_steps): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr_new = learning_rate * (0.1 ** (sum(epoch >= np.array(lr_steps)))) for param_group in optimizer.param_groups: param_group['lr'] = lr_new
48,767
def logger(failure_list): """Log items in a list of errors to a logfile. """ logfile = 'logfile' while os.path.exists('%s.txt' % logfile): logfile = logfile.split('-') if len(logfile) == 1: logfile.append('2') else: logfile[1] = str(int(logfile[1]) + 1) ...
48,768
def translate_month(month): """ Translates the month string into an integer value Args: month (unicode): month string parsed from the website listings. Returns: int: month index starting from 1 Examples: >>> translate_month('jan') 1 """ for key, values ...
48,769
def gencpppxd(desc, exception_type='+'): """Generates a cpp_*.pxd Cython header file for exposing C/C++ data from to other Cython wrappers based off of a dictionary description. Parameters ---------- desc : dict Class description dictonary. exception_type : str, optional Cython...
48,770
def read_files(filepath, **kwargs): """Reads a ``.dbf``/``.shp`` pair, squashing geometries into a 'geometry' column. Parameters ---------- filepath : str The file path. **kwargs : dict Optional keyword arguments for ``dbf2df()``. Returns ------- df : pandas.Dat...
48,771
def no_results_to_show(): """Produce an error message when there are no results to show.""" return format_html('<p class="expenses-empty">{}</p>', _("No results to show."))
48,772
def extrude_surface_to_beam_vector(element:int, vector:point_3d) -> int: """Extrude a surface to a beam. Args: element (int): element ID vector (point_3d): vector e.g. point_3d(0,0,1200) Returns: int: element ID """
48,773
def create_crd_old(): """ Create IBM Spectrum Scale CSI Operator CRD (Custom Resource Defination) Object Args: None Returns: None Raises: Raises an ValueError exception but it is expected. hence we pass. """ # input to crd_metadata crd_lab...
48,774
def test_fetch_nonexisting_config_val(): """Tests fetching non-existing value in the conf.""" msaf.configparser.fetch_val_for_key("caca", delete_key=False)
48,775
def getExecDirectory(_file_=None): """ Get the directory of the root execution file Can help: http://stackoverflow.com/questions/50499/how-do-i-get-the-path-and-name-of-the-file-that-is-currently-executing For eclipse user with unittest or debugger, the function search for the correct folder in the stac...
48,776
def enhance_shadows(Shw, method, **kwargs): """ Given a specific method, employ shadow transform Parameters ---------- Shw : np.array, size=(m,n), dtype={float,integer} array with intensities of shading and shadowing method : {‘mean’,’kuwahara’,’median’,’otsu’,'anistropic'} method n...
48,777
def _to_real_set( number_or_sequence: Optional[ScalarOrSequence] ) -> Set[chex.Scalar]: """Converts the optional number or sequence to a set.""" if number_or_sequence is None: return set() elif isinstance(number_or_sequence, (float, int)): return {number_or_sequence} # pytype: disable=bad-return-type...
48,778
def alt_or_ref(record, samples: list): """ takes in a single record in a vcf file and returns the sample names divided into two lists: ones that have the reference snp state and ones that have the alternative snp state Parameters ---------- record the record supplied by the vcf reader ...
48,779
def legend_mice(ax, mouse_names, symbol=''): """ Add legend of all markers labeled with unique mouse names @Params ax - plot axis mouse_names - list of mouse names to include in legend symbol - if multiple marker types (e.g. '*' and 'o') are labeled with the same mouse name, the mar...
48,780
def plot_loss(ctx, tests, rulers=[], sfx="", **kwargs): """Loss plot (1 row per test, val on left, train on right).""" vh = len(tests) fig, axs = plt.subplots(vh, 2, figsize=(16, 4 * vh)) for base, row in zip(tests, axs.reshape(vh, 2)): ctx.plot_loss( base, row[0], baselines=["adam"]...
48,781
def mpi_rank(): """ Returns the rank of the calling process. """ comm = mpi4py.MPI.COMM_WORLD rank = comm.Get_rank() return rank
48,782
def create_environment(dirname): """ Prepare the execution environment """ logo_file = os.path.join(dirname, "output", "logo.pdf") if not os.path.exists("files"): os.makedirs("files") if not os.path.exists(os.path.join(dirname, "output", "nologo")): os.makedirs(os.path.join(dirn...
48,783
def db(app): """ Setup our database, this only gets executed once per session. :param app: Pytest fixture :return: SQLAlchemy database session """ _db.drop_all() _db.create_all() # Create a single user because a lot of tests do not mutate this user. # It will result in faster tests...
48,784
def is_const_component(record_component): """Determines whether a group or dataset in the HDF5 file is constant. Parameters ---------- record_component : h5py.Group or h5py.Dataset Returns ------- bool True if constant, False otherwise References ---------- .. https://...
48,785
def centernet_resnet101b_voc(pretrained_backbone=False, classes=20, **kwargs): """ CenterNet model on the base of ResNet-101b for VOC Detection from 'Objects as Points,' https://arxiv.org/abs/1904.07850. Parameters: ---------- pretrained_backbone : bool, default False Whether to load th...
48,786
def test_render_dataframe( rich_notebook_output: RichOutput, mock_tempfile_file: Generator[Mock, None, None], remove_link_ids: Callable[[str], str], tempfile_path: Path, ) -> None: """It renders a DataFrame.""" code_cell = { "cell_type": "code", "execution_count": 2, "id"...
48,787
def req(): """ REST Controller """ load("req_req") default_type = 3 request.vars["default_type"] = 3 if "skill_id" in request.get_vars: # Look up the Request from the Skill component # (since that is what is available to us within the dataTables row) table = db.req_req_skil...
48,788
def isodate(dt): """Formats a datetime to ISO format.""" tz = pytz.timezone('Europe/Zagreb') return dt.astimezone(tz).isoformat()
48,789
def execute_sequentially(commands): """ Helper function that runs a sequence of provided shell commands, prints their associated names simultaneously, and returns an error if any command failed. Args: commands (OrderedDict): Essentially a sequence of shell commands to execute. The v...
48,790
def run_main(): # pragma: no cover """entry point for launching app""" RunTestsCLI.run()
48,791
def _ncells_after_subdiv(ms_inf, divisor): """Calculates total number of vtu cells in partition after subdivision :param ms_inf: Mesh/solninformation. ('ele_type', [npts, nele, ndims]) :type ms_inf: tuple: (str, list) :rtype: integer """ # Catch all for cases where cell subdivision is not perf...
48,792
def test_handle_symmetric_padding(symmetric_padding_parameters): """ Test that data of various lengths can be padded correctly using different padding schemes. """ engine = crypto.CryptographyEngine() result = engine._handle_symmetric_padding( symmetric_padding_parameters.get('algorithm...
48,793
def match_santa_pairs(participants: list): """ This function returns a list of tuples of (Santa, Target) pairings """ shuffle(participants) return list(make_circular_pairs(participants))
48,794
def conv_relu_forward(x, w, b, conv_param): """ A convenience layer that performs a convolution followed by a ReLU. Inputs: - x: Input to the convolutional layer - w, b, conv_param: Weights and parameters for the convolutional layer Returns a tuple of: - out: Output from the ReLU - cache: Object to give to t...
48,795
def top_rank(df, target, n=None, ascending=False, method='spearman'): """ Calculate first / last N correlation with target This method is measuring single-feature relevance importance and works well for independent features But suffers in the presence of codependent features. pearson : standard corr...
48,796
def sample_points_on_sphere(center, distance_from_center, hemisphere=False): """just use the polar coordinates to do this, this can be sped up do that """ EPS = 1e-6 thetas = np.linspace(0+EPS, 2*np.pi, 64) phis = np.linspace(0+EPS, np.pi/2, 64) if hemisphere else np.linspace(0+EPS, np.pi, 64) p...
48,797
def notify_helpdesk(**request_info): """Populate and send an email to the helpdesk to open a ticket""" request_info.update(dict(config.items('email_defaults'))) request_info.update(dict(config.items('helpdesk'))) subject = 'MOC {}'.format(request_info['csr_type']) if 'project' not in request_info: ...
48,798
def apply_along_axis( func1d: Callable, axis: int, arr: numpy.ma.core.MaskedArray, *args: Literal["v", "t"], ): """ usage.scipy: 9 """ ...
48,799