content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import click def d_reduce_options(f): """Create common options for dimensionality reduction""" f = click.option('--axes', nargs=2, type=click.Tuple([int, int]), help='Plot the projection along which projection axes.', default=[0, 1])(f) f = click.option('--dimensi...
97577d5d52b777ea33d4d47a80cbacc0f394ad00
43,525
def normalize(D, value=1): """normalize. Normalize the coefficients to a maximum magnitude. Parameters ---------- D : dict or subclass of dict. value : float (optional, defaults to 1). Every coefficient value will be normalized such that the coefficient with the maximum magnitu...
d8dcce6a35254790e82f948608a3f848f1a80286
43,527
def precond_is_classifier(iterable=None, program=None): """Ensure that a program can do classification.""" if program.__class__.__name__ in ['SGDClassifier', 'LogisticRegression']: return True else: return False
3b10e252780b10971924c8f0f15db2130e599873
43,528
def comment_lines_ocaml(text, start='(* ', end=' *)'): """ Build an OCaml comment line from input text. Parameters ---------- text : str Text to comment out. start : str Character to open the multi-line comment. end : str Character to close the multi-line comment. ...
13cd5de355bfbb8b9861016c1d95541d6aa0dbe2
43,530
def test_cached_properties_are_cached( PropertyRegistry, # noqa: N803 CachedPropertyRegistry, PropertyParamRegistry, CachedPropertyParamRegistry, ): """Cached properties are truly cached.""" # Register registry member @PropertyRegistry.registry() @CachedPropertyRegistry.registry() @...
1b10b2c5c738e3ec3edb9841d474e6688ec6e7c4
43,531
def calculate_delta_time_series(times, valid_dt): """ calculate_delta_time_series This function calculates the differences between all the elements of a timeseries and compares the differences with a valid time difference. True is returned if all the differences are valid; i.e. equal to the val...
c1f42e185b6b2bb9c71942222998e46758db7ff1
43,532
from typing import Dict from typing import Callable def dict_subset(adict: Dict, predicate: Callable): """Return a dict that is a subset of ``adict`` using a filter function. The signature of the filter is: ``predicate(key, val) -> bool`` """ return {k: v for k, v in adict.items() if predicate(k, v)}
2ee1b2b2a20665222440cc43fdbb99a5151386cb
43,534
from typing import Union import imaplib def delete_mails_by_recipient( mailbox: Union[imaplib.IMAP4_SSL, imaplib.IMAP4], recipient_mail: str, expunge=False, sanity_check=100, ) -> int: """ Delete all mail to recipient_mail in IMAP mailbox """ assert recipient_mail status, count = ...
c8ea6f72e5654cfc882026b2da8f70be14175965
43,535
from typing import List def asciiRowToStrings(filename: str) -> List[str]: """Extract and returns a list of strings from the first row of the file. Args: filename Returns: list of string """ f = open(filename, "r") line = f.readline() f.close() if "," in line: ...
8e9c5d181e542fd2c80186394ea98c50ad1fbd44
43,536
import math def frac_bin(f, n=32): """ return the first n bits of fractional part of float f """ f -= math.floor(f) # get only the fractional part f *= 2**n # shift left f = int(f) # truncate the rest of the fractional content return f
fd644c38e620300ed0674aa986883dfa46463014
43,537
def calculate_boundbox(list_coordinates): """ coordinates are inverted x: colums y :rows list_coordinates: list of the form [ [x2,y1], [x2,y2], . . . ] returns top left point (x,y) and width (w) and heigth (h) of rectangle """ x = int(min(list_coordinates[:,0])) y = int(min(list...
bbabdd81e88dd4304293712aff389bfd568f4772
43,538
def default(): """default.""" return "healthcheck"
5162236a517c63a3bfa58ec1bdedf348871e7bf0
43,539
def log(x): """ Simulation to math.log with base e No doctests needed """ n = 1e10 return n * ((x ** (1/n)) - 1)
59d2b41645bd81f113f22c863bc7eda584e4a74e
43,542
def multiply(c, d): """ Multiply two numbers Here is an example reference: astropy_ """ return c * d
e14d202edbcba0fb1fe2af88612c551f4205eb22
43,544
def gen_rotation_list(num): """ Returns a generator of all digit rotations of num (excluding itself). """ return (int(str(num)[a:] + str(num)[:a]) for a in range(1, len(str(num))))
a92f588d02693eced6db207c2703d5c1f1a524e7
43,545
from itertools import islice, tee def pairwise(iterable, offset=1): """ Return successive pairs from iterable. """ a, b = tee(iterable) return zip(a, islice(b, offset, None))
3395e82e658f89e6505ab9d57da19dd9f53aefab
43,547
def top_class_auc(df): """Out of all the predictive scores across all models, CHOOSE the best model prediction score for each treatment dose""" df_max_class = df.groupby(['class']).agg(['max']) df_max_class.columns = df_max_class.columns.droplevel(1) df_max_class.rename_axis(None, axis=0, inplace = True...
0a4d79523caacc3372cef5d0ed8346caccd184ab
43,548
def int_type(value): """Integer value routing.""" print(value + 1) return "correct"
b17b6568b17316a85fbff846e81223e41d737556
43,549
import argparse import ast def add_com_train_args( parser: argparse.ArgumentParser, ) -> argparse.ArgumentParser: """Add arguments specific to COM training. Args: parser (argparse.ArgumentParser): Command line argument parser. Returns: argparse.ArgumentParser: Parser with added argum...
1dbd1a82603fe62cf74de6123223f3311417afb8
43,550
import os import json def load_images_data(image_json_file): """ 从 """ if os.path.exists(image_json_file): with open(image_json_file, 'r') as f: image_dict = json.loads(''.join(f.readlines())) return image_dict else: return False
a7ac163aa3fce212ae5d91842fe7e0b375688a6e
43,552
def _get_time_signature(e): """ Get the time signature and return Returns ------- tuple (mumber, number) OR None the tuple is (beats, beat_type). `beats` is the numerator, `beat_type` is the denominator of the key signature fraction. """ if e.find('time/beats') is not None ...
bf1ba2b885ed55c7793fa3a355eadbad1d287987
43,553
def is_observed_custom_module(module): """ Check if a module is marked as observed custom module or not """ return hasattr(module, '_is_observed_custom_module') and \ module._is_observed_custom_module
b5455ba014d397849bbae637e9367dda1d53c94a
43,555
def _temp_pad(F, x, padding=1, zeros=True): """ Pads a 3D input along temporal axis by repeating edges or zeros Args: x: dim 5 b,t,c,w,h padding: the number of dim to add on each side zeros: pad with zeros? Returns: padded x """ first = x.slice_axis(axis=1, begin=0, end...
192c11c9aa694755f309237294ad55397fb24a34
43,557
def infinite(smaj, smin, bpa): """ If the beam is not correctly fitted by AWimager, one or more parameters will be recorded as infinite. :param smaj: Semi-major axis (arbitrary units) :param smin: Semi-minor axis :param bpa: Postion angle """ return smaj == float('inf') or smin == float...
87a67ed9b880287def798fdfddd5c42c483e3b7d
43,559
def secondsToTime(seconds): """Convert seconds to time""" minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) weeks, days = divmod(days, 7) return "%d Weeks %d Days %d Hours %d Minutes %d Seconds" % (weeks, days, hours, minutes, seconds)
d71caafa633d17a7bcdf9e3709ff52a9a490b16f
43,560
from typing import OrderedDict def compare_headers(hdr2width_old, hdr2width_new, colwidthmax): """Compare headers.""" in_old_but_not_new = set(hdr2width_old.keys()).difference( set(hdr2width_new.keys())) in_new_but_not_old = set(hdr2width_new.keys()).difference( ...
d88ae809b815c43df25d8139893b270aae67f086
43,561
def clip_paths(paths, bounds): """Return the paths that overlap the bounds.""" return [path for path in paths if path.bounds().overlap(bounds)]
c19d099673e1270fe10a9daf1b60e1da240e9660
43,562
def remove_unrelated_domains(subdomains, domains): """ This function removes from the entire set hostnames found, the ones who do not end with the target provided domain name. So if in the list of domains we have example.com and our target/scope is example.it, then example.com will be removed becaus...
3e9029958687e82247ffe2797fb971de15e628fd
43,563
import os def get_local_versioning(directory): """Get versioning.py from local repository clone""" filename = os.path.join(directory, 'versioning', 'versioning.py') if os.path.isfile(filename): return open(filename).read() else: return None
24c77c2f07cddf18485d1ef36abd7b0c808cebc7
43,564
def zerocase(case): """Check if the binary string is all zeroes""" if int(case, 2) == 0: return True else: return False
4227ff69e8ccd4250f519de4d09d498dfc13289e
43,566
def scalar( relation ): """ Returns the Python value in the first column of the first row. """ for t in relation: return t[0]
bff8dd8b6cf38d5f697a89a64f7c3c6eef7b0ce1
43,567
def parts_to_uri(base_uri, uri_parts): """ Converts uri parts to valid uri. Example: /memebers, ['profile', 'view'] => /memembers/profile/view """ uri = "/".join(map(lambda x: str(x).rstrip('/'), [base_uri] + uri_parts)) return uri
7fd45dba18152aed9dd18d6b2757c4f449d10930
43,569
def create_ids(data): """Generate IDs for the species in the dataset, by combining: - original species name - trait - reference - latitude - longitude""" ids = {} for row in data: species = row[0] reference = row[2] trait = row[3] lat = row[7] lo...
3488e65358278c1cb97162bf9f8a4a8b06e54223
43,571
def find_outliers(serie, cutoff_margin): """ Find outliers on a serie based on percentiles. Parameters ---------- :serie: array_like Input array or object that can be converted to an array. :cutoff_margin: represents the edges to be cut Returns ------- :otl...
09915e27e8a67f3512676628988513739987d2a7
43,573
from functools import reduce def mac_aton(s): """Convert a Mac address to an integer.""" try: mac = list(map(lambda x: int(x, 16), s.split(':'))) mac = reduce(lambda a,b: a+b, [mac[i] << (5-i)*8 for i in range(6)]) except (ValueError, IndexError): raise ValueError('illegal Mac: {0}...
dd29c6e99998bfd0676ae9e7200f02500c2eed0d
43,575
import argparse def make_parser(): """ Create a parser to parse arguments """ p = argparse.ArgumentParser(description="") p.add_argument("--log_name", "-n", help="Name of log to create. If multiple logs, log number will be appended to this name.") p.add_argument("--log_level", "-l", help="") p.ad...
3de179c77f9329b17c03ad17b86bf443fc13a43e
43,577
from typing import Optional from pathlib import Path def get_resource(filename: str, path: Optional[str] = None) -> str: """A utility method to get the absolute path to a resource in the test suite. Args: filename: the name of the file to get. path: an optional path relative to the root of th...
d2341484fb46dc4da2d00b9b62092d0f5b52339e
43,579
def functional_distribution(word): """ Given a word, return a map from cryptic functions to relative probabilities. Currently a stub. """ return {'syn': .4, 'null': .2, 'sub': .3, 'ana': .3}
591f13d731a4a77e936a2906ab74bde110c07e11
43,580
import re def columnMatcher(patterns, cols, needed=None, verbose=False): """Infer BQ expressions to extract required columns """ def matchHelper(var, matches, cols, verbose): for m in matches: try: r, v = m except ValueError: # shortcut, single item match ...
cc626703906c0b16fa24f34da10694517f5d1be0
43,581
def pre_check_state(s,N,args): """ imposes that that a bit with 1 must be preceded and followed by 0, i.e. a particle on a given site must have empty neighboring sites. # Works only for lattices of up to N=32 sites (otherwise, change mask) # """ mask = (0xffffffff >> (32 - N)) # works for la...
999ec694bdb5adcc851d1c6a426b0103493991bd
43,582
def check_input(prompt, assertion=None, default=None): """Get input from cmdline, ensuring that it passes the given assertion. assertion: a function that if given a value will return None if the check should pass, otherwise returning a helpful error message as a string.""" if default is not None: ...
9cb72146a931974c186a8473a9f0b75e2f2515d6
43,583
import os import time def convert_time(epoch_time, time_format="%s", delta=1): """ Converts GMT epoch time to the specified time format. Also rounds off to the nearest minute, hour, day when valid delta value is passed :param epoch_time: epoch time to be converted :param time_format: expected outp...
4ff577732d9205dd9228d84fd57242ea19fd0f94
43,584
def single_value_columns(df): """Return a list of the columns in `df` that have only one value.""" return { col: df[col].iloc[0] for col in df if df[col].nunique() == 1 }
e0cbdf42dec1600edcd78d3f74d302bcba9fd93b
43,585
def quantile_bin_column(self, column_name, num_bins=None, bin_column_name=None): """ Classify column into groups with the same frequency. Group rows of data based on the value in a single column and add a label to identify grouping. Equal depth binning attempts to label rows such that each bin con...
99dcef7869efa3e6439d380dda9b19fcb2b0ff99
43,586
def close_connection(connection) -> bool: """Function to close Database connection. Args: connection (mysql.connector.connection_cext): The argument received is a MySQL connection. Returns: bool: The original return was False when database connection was closed. But, I ...
b01fbf53c03b74fc60e65b91aaf681747254ebb5
43,587
import math def project_gdf(gdf, to_crs=None, to_latlong=False): """ Project a GeoDataFrame from its current CRS to another. If to_crs is None, project to the UTM CRS for the UTM zone in which the GeoDataFrame's centroid lies. Otherwise project to the CRS defined by to_crs. The simple UTM zone cal...
d25ee19f834bb7befbee05a344c4581f872eb8dd
43,588
import numpy import pandas def scan_preprocessing_loess_impute(df): """ LOESS imputer. Value imputer for LOESS procedure. Parameters ---------- df : dataframe Dataframe with potentially missing responses. Returns ------- df : dataframe Dataframe with no missing r...
3f7cca5eb44d282cc8ce8dee7dc702cd5a66c059
43,589
def list_experiment_names(exp_file_path): """Retrieve experiment names from the given file.""" def helper(): with open(exp_file_path, "r") as ef: for line in ef: exp_name = line.rstrip("\n") yield exp_name return [x for x in helper()]
143d958629c85926018f225d1b61427f7eceb30f
43,591
def legend_positions(df, y, scaling): """ Calculate position of labels to the right in plot... """ positions = {} for column in y: positions[column] = df[column].values[-1] - 0.005 def push(dpush): """ ...by puting them to the last y value and pushing until no o...
97ec60cc944b972159fd2dbd08305a6bbc0a01ce
43,595
from datetime import datetime def sTimeUnitString( ismilli=False, abbr=True ): """OpendTect-like time stamp Parameters: * ismilli (bool, optional): Include millisecond (default is False) * abbr (bool, optional): Abbreviated (default is True) Returns: * str: Time stamp string formatted like done by...
2ba388ee895501490caecf37243f08bc8f4d2f24
43,596
def calc_Gunning_fog(n_psyl, n_words, n_sent): """Метрика Gunning fog для английского языка""" n = 0.4 * ((float(n_words)/ n_sent) + 100 * (float(n_psyl) / n_words)) return n
a10b21c4bc4c59e54b7f37a7f48b7d114b948eae
43,600
def _uniform_probability(action_spec): """Helper function for returning probabilities of equivalent distributions.""" # Equivalent of what a tfp.distribution.Categorical would return. if action_spec.dtype.is_integer: return 1. / (action_spec.maximum - action_spec.minimum + 1) # Equivalent of what a tfp.dist...
f5f0d68e710661bd9f6806b60ae9d695a1e78ccb
43,601
from typing import Mapping from typing import Any from typing import List import re def get_int_regex_matches(pattern: str, state: Mapping[str, Any]) -> List[int]: """Matches a pattern with an integer capture group against state keys.""" matches = [re.match(pattern, key) for key in state] return sorted(set(int(...
2df629de28ecf4a48d628dd179966b538e5f2db7
43,602
def longest_line_length(file_name): """ This function takes a string file_name and returns the length of the longest line in the file. """ with open(file_name) as file: lines = file.readlines() length = 0 for line in lines: if len(line) > length: l...
ead6e352b5886191318df7308efff7099e874a68
43,604
from typing import Tuple from typing import List from typing import Set def _get_repeating_chars_count(box_id: str) -> Tuple[int, int]: """Returns a tuple (twice_repeated, thrice_repeated) twice_repeated, thrice_repeated - 1 - atleast 1 character is repeated twice exactly - 0 No character i...
af4ac5f5b972e69d591691cf3176cf48661a30c2
43,605
import torch def binary_accuracy(y_pred, y_true): """Function to calculate binary accuracy per batch""" y_pred_max = torch.argmax(y_pred, dim=-1) correct_pred = (y_pred_max == y_true).float() acc = correct_pred.sum() / len(correct_pred) return acc
7fdd406e2871c33ffdf9324c1073e4a362572483
43,608
def star(table): """ Return the list of all columns in a table. This is used much like the ``*`` notation in SQL:: ``select(*star(employee), where=employee.department == 'Finance')`` returns all of the columns from the *employee* table for the Finance department. :type table: :class:`hustle....
2935ddc7cccbdca173d90574e3370f45a49a1841
43,609
def valide(seq): """ Vérifie la validité d'une séquence ADN. """ return len(seq)==(seq.count('A') + seq.count('C') + seq.count('G') + seq.count('T'))
14a3f70324dd8d3d94ae11187ef95eff49ca663c
43,610
import numpy def transformData(data): """ this function will add 3 sin(dec), 4 cos(dec), 5 tan(dec), 6 sin(RA), 7 cos(RA), 8 tan(RA), 9 dec*RA, 10 sin(dec*RA), 11 cos(dec*RA), 12 tan(dec*RA), 13 dec/RA, 14 sin(dec/RA), 15 cos(dec...
7fc728050d8341185341ce77fbdfda659f5a452f
43,611
def get_refresh_rate(): """ What should be the refresh rate (in seconds) Output: --> integer, nb of seconds between refresh """ refresh_rate = input("Enter the refresh rate (in seconds): ") print("") print("****************************************************************") try:...
a27725199a2bb8cd32e44843e8afba92fc8e60ad
43,612
def _safe_lin_pred(X, coef): """Compute the linear predictor taking care if intercept is present.""" if coef.size == X.shape[1] + 1: return X @ coef[1:] + coef[0] else: return X @ coef
f74eba444cf03681ec41ea2314c0457b321a4344
43,614
from typing import List from pathlib import Path def open_article(filename: str) -> List[str]: """Loads plain text article into memory. Args: filename (str): article filename Returns: str: raw article text """ input_path = Path("local", filename) with open(input_path, "r") as...
b064286cb097dd16fb9900278bdfd16e31d14b3b
43,615
def has_data_been_validated(flags): """Return True (or a boolean series) if flags has been validated""" return flags > 1
987f0c7dcd7d23d67075863642b2a7cbe314d6ac
43,616
import requests def get_job_id( domain, org_key, headers, hostname="*", process="*", window="10h", start="0", end="0", ): """ Function takes in the domain, org_key, headers, hostname, and timeframe to generate the initial query an retrieve the job id of that query returns j...
e004ec3b9be5cfb45b8b7cce5c6ed38e68f77928
43,618
def _match_specie_group(file_metadata): """ Classifies the virus taxonomy group from NCBI based structure to broadly used Baltimore Classification Based on https://en.wikipedia.org/wiki/Virus#Classification Baltimore Classification: I: dsDNA viruses (e.g. Adenoviruses, Herpesviruses, Poxvi...
36273c7678321acbea64dbd710fb2fbd40729a0a
43,619
def tolist_if_not(arr): """ Convert `arr` to list if it is not already. >>> import numpy as np >>> tolist_if_not([0]) [0] >>> tolist_if_not(np.arange(1)) [0] """ try: tolist = arr.tolist except AttributeError: return arr return tolist()
6aeccb2011dd4660953ffe20417f7528ae5d7137
43,620
def _safe_hasattr(obj, attr): """Workaround unreliable hasattr() availability on sqlalchemy objects""" try: object.__getattribute__(obj, attr) return True except AttributeError: return False
d726f83115431b39aebfde341cc1ea055117c8c0
43,621
def user_input_coords(string): """Converts user coordinate input from string to list""" while True: # makes sure the input has only two integer coordinates inp = input(string) if len([i for i in inp.split() if i.isdigit()]) == 2 and len(inp.split()) == 2: return list(map(int, inp.sp...
c4f4e617777c7076e14fcba3fd84251b8f46edf9
43,622
def softmax_bias(p, slope, bias): """ Symmetric softmax with bias. Only works for binary. Works elementwise. Cannot use too small or large bias (roughly < 1e-3 or > 1 - 1e-3) :param p: between 0 and 1. :param slope: arbitary real value. 1 gives identity mapping, 0 always 0.5. :param bias: betwee...
fe13cacabe721710c4108bc1322b90d2e971ca21
43,623
def default_str_tester(s: str) -> bool: """ Default test whether s URL, file name or just data. This is pretty simple - if it has a c/r, a quote :param s: string to test :return: True if this is a vanilla string, otherwise try to treat it as a file name """ return not s.strip() or any(c in s fo...
2234f3a34d3f24d104cb97193a300489d595b62d
43,625
def index_to_angle(i): """ Takes an index into a LIDAR scan array and returns the associated angle, in degrees. """ return -135.0 + (i / 1081.0) * 0.25
63f99389ef532a662d5ea3a3a173a1ba8dd9df09
43,626
import socket def getInterfaceAddress(peer_ip_address): """tries to find the ip address of the interface that connects to a given host""" s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((peer_ip_address, 53)) # 53=dns ip=s.getsockname()[0] s.close() return ip
6a98ea178b14ff13c777072a62c04d4f92a7c58e
43,627
def count_tracks_in_album_from(df, decade_year): """returns count of tracks on albums published over given decade and dataframe; dataframe has to have `release_year` and `track_id` columns.""" years = [decade_year + y for y in range(10)] mask = df["release_year"].isin(years) return df.loc[mask, ...
7d1fc82146003e246a7981332e6a2bd7bba5d1fb
43,628
def remove_implications(ast): """ @brief Removes implications in an AST. @param ast The ast @return another AST """ if len(ast) == 3: op, oper1, oper2 = ast oper1 = remove_implications(oper1) oper2 = remove_implications(oper2) if op == '-...
4d9c4b46a102a613a805608df58163194a320ce1
43,629
import binascii def hex_to_bytes(value: str) -> list: """ Parameters ---------- value : str hex encoded string Returns : list ------- bytes array of hex value """ return list(binascii.unhexlify(value))
d2ad089185accf72451a89bcd30cd0ddf90f5a49
43,633
def F_hydro(R): """ fraction of all free-free emissions due to hydrogen. R is the ratio of the number of heliums to the number of hydrogens, which is approximately 0.08 """ result = 1 - R return result
20083d14be33bcf2b0ee01eb2208bac073b8ec5b
43,636
def apply_filters(genes, records, db_info, filters): """Apply predefined and additional filters. Args: genes: list of Gene objects records: list of records as Variant objects db_info: database configuration as Config object filters: list of filters as Filter objects """ ...
be6cb19865b711cec56dd2f74563bf6ea8fe5a8e
43,637
def ParseIssueNumber(issueCode): """Notes: Issue code comes in a five digit number. The first three numbers are the issue number padded in zeroes The fouth number is for varient covers starting at 1 The fith number seems to always be 1 """ if len(issueCode) == 5: issueNumber = issueCode[...
a8e7643a3008ef0062c17ed64c864b104e54909c
43,640
import torch def _read_response_manual_input(self, additional_text): """ read response provided by user as manual input via prompt :param additional_text (str): additional text to display in prompt when sourcing user input; to be used in case a datapoint is to be re-sampled """ # read candida...
9d8cb3587a9044ec4529940c027d8466ec210cc1
43,641
def get_ranking07(): """ Return the ranking with ID 07. """ return [ ("a2", 0.644440), ("a1", 0.623018), ("a3", 0.593228), ("a6", 0.591963), ("a4", 0.543750), ("a5", 0.540097), ]
a11103990ae212edb8008369d4bbcfff2e0fbf2a
43,642
def dual(x, y): """ dual """ ret = 3 * x * x * x * y * y * y return ret
62203bfee0eb98b1b219ae45a2b1424e02f5440a
43,643
def findMaxAverage(self, nums, k): # ! 超时 """ :type nums: List[int] :type k: int :rtype: float """ maxSum = -10001 curSum = 0 for i in range(len(nums) - k + 1): curSum = sum(nums[i:i + k]) maxSum = max(maxSum, curSum) return float(maxSum / k)
0a63b4e54a3252b6f1f5c96c1b6e18705bd2b919
43,644
from typing import List def get_grid() -> List[List[int]]: """ Retuns the Grid that the SudokuBoard is based off of """ return [ [0, 1, 6, 5, 0, 8, 4, 0, 2], [5, 2, 0, 0, 0, 4, 0, 0, 0], [0, 0, 7, 6, 0, 0, 0, 3, 1], [0, 6, 3, 0, 1, 0, 0, 8, 0], [9, 0, 4, 8, 6, 3, 0, 0, 5], [0, 5, 0...
3c92e60683c3986d60b8261b3980ccd72cccf091
43,645
def calculate_profit_pod(location, destination): """ calculate net profit by good (for one pod) between location planet and destination planet return a list of list, with a 2 decimals float format """ _profit = [] for key in destination.price_slip.keys(): if location.price_slip[key] != 0 an...
f9298ba58ea19d4f2a20f9ff770d8ec01405023b
43,646
def iterit(*args, **kwargs): """ This takes some input (int, string, list, iterable, whatever) and makes sure it is an iterable, making it a single item list if not. Importantly, it does rational things with strings. You can pass it more than one item. Cast is optional. def foo(offsets=10): ...
696bf6f99c79924d25a649b73ee35e624d52e53d
43,647
import struct def readShort(f): """Read unsigned 2 byte value from a file f.""" (retVal,) = struct.unpack("H", f.read(2)) return retVal
ce730430018b9589670e411c4186139fc2f0345d
43,648
from typing import Union from typing import List from typing import Dict from typing import OrderedDict def sort_callbacks_by_order( callbacks: Union[List, Dict, OrderedDict] ) -> OrderedDict: """Creates an sequence of callbacks and sort them. Args: callbacks: either list of callbacks or ordered ...
bba43ab6292e1132f8447e79403d9d730831e3de
43,649
def _make_env_vars(runlevel): """ makes standard env vars to pass to the scripts when they are run. the script must be expecting them have a "--env=XXX=xxx" entry for each """ env_vars = dict() env_vars['NEST_RUNLEVEL'] = runlevel.get_runlevel_name() return env_vars
384db73cd53d24878fb6fe0b07bb1507a8086127
43,651
def sign(value): """ Returns an integer that indicates the sign of a number. Parameters: value (int): The number to get the sign of Returns: -1 if the number is negative, 0 if the number is 0, or 1 if the number is positive. """ if value < 0: return -1 elif...
71997a571fcdbadf45fa1dd3b8d2b6c54eafdd61
43,652
import socket import struct def build_ip_header(src_ip, dst_ip): """Builds a valid IP header and returns it Parameters: - src_ip: A string with a valid IP address which will be used as SRC IP - dst_ip: A string with a valid IP address where the packets will be sen...
8f949e70ef55e18c7d2adaa812a8ed45fc86f358
43,653
def get_default_freesolv_task_names(): """Get that default freesolv task names and return measured expt""" return ['expt']
17da2d1af123c71e6a2de9799b25110b54b0a022
43,654
def repr_object(o): """ Represent an object for testing purposes. Parameters ---------- o Object to represent. Returns ------- result : str The representation. """ if isinstance(o, (str, bytes, int, float, type)) or o is None: return repr(o) return "...
7ae24f46d626b7673af6389574b55583ec70971e
43,655
import shlex def _lexcmds(cmds): """spit pipeline specification into arguments""" if isinstance(cmds, str): return shlex.split(cmds) else: return [shlex.split(cmd) if isinstance(cmd, str) else cmd for cmd in cmds]
44102762f46e097caae8b9a1ef5f788897d8c9aa
43,657
def ifb(bites): """ ifb is a wrapper for int.from_bytes """ return int.from_bytes(bites, byteorder="big")
ae02449bd48ebe69e6fcbc2714da90dc15a24d40
43,659
def build_container_sas_uri(storage_acc_url: str, container: str, sas: str) -> str: """ Create a container SAS URL in the format of: {account-url}/{container}?{SAS} Note that this method is not responsible for the generation of the SAS token. :param storage_acc_url: Base URL to the storage account ...
8ab30acf0b792324c5e170c8b3eadd657494b5c6
43,662
def _to_signed32(n): """Converts an integer to signed 32-bit format.""" n = n & 0xffffffff return (n ^ 0x80000000) - 0x80000000
b5562063cc0467222f3d972eca9305dddbe4e05e
43,664
def generate_method_bindings(obj): """Function to create the function calls, which contain calls to the godot apis""" result = "\n##################################Generated method bindings#########################################\n" result += f"cdef godot_method_bind *bind_{obj['name']}\n" for method i...
62e1c319021bdd549d78f4b96afbdb3aef5e68b7
43,665
def test(when): # this is another custom comment """ this is a test docstring for test """ tester1 = {"test1": 1, "test2": 2} tester2 = { "test1": 1, "test2": 2, } return tester1
df3a90e4e43a95ebdc3b58fb1aec5869b95b706c
43,666
def define_chains(pdb_id, sabdab_chains_df): """ """ entry = sabdab_chains_df[sabdab_chains_df["pdb"] == pdb_id].values[0] Hchain = entry[1] Lchain = entry[2] # check if antigen has more than one chain if len(entry[3]) > 1: antigen_chain = entry[3].split(" | ") else: ...
d643822dc71b7549151971d150eb9a91dab49a2c
43,667
from typing import Tuple import gc import torch def find_tensor_by_shape(target_shape: Tuple, only_param: bool = True) -> bool: """Find a tensor from the heap Args: target_shape (tuple): Tensor shape to locate. only_param (bool): Only match Parameter type (e.g. for wei...
606e0223ea4014d8b1f7d5c6bba16ec64a1fc1ea
43,668