content
stringlengths
22
815k
id
int64
0
4.91M
def _write_header(buf: Union[memoryview, bytearray], dtype: np.dtype, shape: tuple): """ Write the header data into the shared memory :param buf: Shared memory buffer :type buf: bytes :param dtype: Data format :type dtype: np.dtype :param shape: Array dim...
5,315,500
def _padright(width, s): """Flush left. >>> _padright(6, u'\u044f\u0439\u0446\u0430') == u'\u044f\u0439\u0446\u0430 ' True """ fmt = u"{0:<%ds}" % width return fmt.format(s)
5,315,501
def single(mjd, hist=[], **kwargs): """cadence requirements for single-epoch Request: single epoch mjd: float or int should be ok hist: list, list of previous MJDs """ # return len(hist) == 0 sn = kwargs.get("sn", 0) return sn <= 1600
5,315,502
def accuracies(diffs, FN, FP, TN, TP): """INPUT: - np.array (diffs), label - fault probability - int (FN, FP, TN, TP) foor keeping track of false positives, false negatives, true positives and true negatives""" for value in diffs: if value < 0: if value < -0.5: FP+=1 ...
5,315,503
def group_te_ti_b_values( parameters: np.ndarray, data: Optional[torch.Tensor] = None ) -> Tuple[np.ndarray, Optional[np.ndarray]]: """Group DWI gradient direction by b-values and TI and TE parameters if applicable. This function is necessary for the S^2 fourier transforms. Args: parameters: un...
5,315,504
def test_trim_words(): """Test if _trim() produces correct list.""" easy_list = gi_wst.trim(3, 5, LIST_EXAMPLE) assert "a" not in easy_list assert "Supercalifragilisticexpialidocious" not in easy_list assert list(easy_list).sort() == LIST_EXAMPLE_EASY.sort() master_list = gi_wst.trim(11, 12, LIS...
5,315,505
def compress(s): """param s: string to compress count the runs in s switching from counting runs of zeros to counting runs of ones return compressed string""" #the largest number of bits the compress algorithm can use #to encode a 64-bit string or image is 320 bits #I tested the penguin and ...
5,315,506
def data_scaling(Y): """Scaling of the data to have pourcent of baseline change columnwise Parameters ---------- Y: array of shape(n_time_points, n_voxels) the input data Returns ------- Y: array of shape(n_time_points, n_voxels), the data after mean-scaling, de-meaning a...
5,315,507
def _process_normalizations(model_dict, dimensions, labels): """Process the normalizations of intercepts and factor loadings. Args: model_dict (dict): The model specification. See: :ref:`model_specs` dimensions (dict): Dimensional information like n_states, n_periods, n_controls, n_...
5,315,508
def add_text(dct, f, val): """ add_text offers a basic idea of how to add values to dict before sending to solr. TEXT strings may need scrubbing but you just add non-TEXT values. """ if is_text(val): dct[f] = val else: dct[f] = val
5,315,509
def versioned_static(path): """ Wrapper for Django's static file finder to append a cache-busting query parameter that updates on each Wagtail version """ return versioned_static_func(path)
5,315,510
def calculate_estimated_energy_consumption(motor_torques, motor_velocities, sim_time_step, num_action_repeat): """Calculates energy consumption based on the args listed. Args: motor_torques: Torques of all the motors motor_velocities: Velocities of all the motors....
5,315,511
def affine_to_shift(affine_matrix, volshape, shift_center=True, indexing='ij'): """ transform an affine matrix to a dense location shift tensor in tensorflow Algorithm: - get grid and shift grid to be centered at the center of the image (optionally) - apply affine matrix to each index...
5,315,512
def get_item_details(args, doc=None, for_validate=False, overwrite_warehouse=True): """ args = { "item_code": "", "warehouse": None, "customer": "", "conversion_rate": 1.0, "selling_price_list": None, "price_list_currency": None, "plc_conversion_rate": 1.0, "doctype": "", "name": "", "s...
5,315,513
def _get_store(cls: Type[BaseStore]) -> BaseStore: """Get store object from cls :param cls: store class :return: store object """ if jinad_args.no_store: return cls() else: try: return cls.load() except Exception: return cls()
5,315,514
def list_call_get_all_results_generator(list_func_ref, yield_mode, *list_func_args, **list_func_kwargs): """ Calls a list operation and automatically fetches more data from the service (automatically following pagination tokens) until the no more records are available. Apart from the formally listed paramet...
5,315,515
async def connections_send_message(request: web.BaseRequest): """ Request handler for sending a basic message to a connection. Args: request: aiohttp request object """ context = request.app["request_context"] connection_id = request.match_info["conn_id"] outbound_handler = request...
5,315,516
def load_json(path: str): """Load json file from given path and return data""" with open(path) as f: data = json.load(f) return data
5,315,517
def process(): """ The main function which responds to the html form submission. The Flask server has it under the /process address. """ # 1. Obtain inputs from the webpage code = request.form.get('Python_Code', '', type=str) graph = request.form.get('Figure_Parameters', '', type=str) ...
5,315,518
def check_admin_access(func): """Wrap a handler with admin checking. This decorator must be below post(..) and get(..) when used. """ @functools.wraps(func) def wrapper(self): """Wrapper.""" if not auth.is_current_user_admin(): raise helpers.AccessDeniedException('Admin access is required.') ...
5,315,519
def genericSearch(problem, fringe, heuristic=None): """ A generic search algorithm to solve the Pacman Search :param problem: The problem :param fringe: The fringe, either of type: - Stash, for DFS. A Last-In-First-Out type of stash. - Queue, for BFS. A First-In-First-Out type of stash. ...
5,315,520
def _check_option_defaults(options): """Set the defaults for options if they are not set. This prevents users from calling the method and its subordinates with missing options. """ for opt_name in _DEFAULT_OPTIONS: if not opt_name in options: options[opt_name] = _DEFAULT_OPTION...
5,315,521
def post_processing( predicted: xr.Dataset, ) -> xr.DataArray: """ filter prediction results with post processing filters. :param predicted: The prediction results """ dc = Datacube(app='whatever') #grab predictions and proba for post process filtering predict=predicted.Predicti...
5,315,522
def controleer_versie(): """Controleer of we wel met de juiste python werken""" if not sys.version_info >= (3,0): print("Je hebt minstens python 3 nodig voor dit script") exit()
5,315,523
def lifeMouseHandler(x, y): """ This function is called with each mouse click. Its inputs are the pixel location of the next mouse click: (x,y) It computes the column and row (within the board) where the click occurred with getPos, and changes the color of the clicked squar...
5,315,524
def test_pu_creation(): """ Test all the PUs are created correctly as specified in the config. # TODO Currently we're only checking the string representation of PU object matches, but we can do more thorough testing in the future. Returns ------- None """ Component.reset_ids() with...
5,315,525
def average_filter(values, n=3): """ Calculate the sliding window average for the give time series. Mathematically, res[i] = sum_{j=i-t+1}^{i} values[j] / t, where t = min(n, i+1) :param values: list. a list of float numbers :param n: int, default 3. window size. :return res: lis...
5,315,526
def _get_int_val(val, parser): """Get a possibly `None` single element list as an `int` by using the given parser on the element of the list. """ if val is None: return 0 return parser.parse(val[0])
5,315,527
def first_setup(db: bot.GameDB) -> None: """Perform initialization of game.""" pname = input(f"Initializing dbfile {bot.datapath(conf.get('dbfile'))}. Give an account name that you would like to have admin access [{conf.get('owner')}]: ") if pname == "": pname = conf.get("owner") pclass = input...
5,315,528
def read_csv_folder_into_tidy_df(csv_glob, drop_columns=[' '], sample_id_categories=None, regex_exp="[a-z]\dg\d\d?"): """ Input ----- Takes glob (str) to csv folder as input. Optional sample_id_categories (e.g. list). Function -------- Combines into tidy dataframe. Returns ------- ...
5,315,529
def read_gps(gps_filename): """ read gps data and output arrays of coordinates, one with speeds, one with altitudes :param gps_filename: the gps filename :return: 2 lists of points, one containing speed, the other altitude """ speed_data = [] # list for storing gps coordinates with speed ...
5,315,530
def gram_schmidt(vs, normalised=True): """Gram-Schmidt Orthonormalisation / Orthogonisation. Given a set of vectors, returns an orthogonal set of vectors spanning the same subspace. Set `normalised` to False to return a non-normalised set of vectors.""" us = [] for v in np.array(vs): u =...
5,315,531
def gcd(a, b): """Compute greatest common divisor of a and b. This function is used in some of the functions in PyComb module. """ r = a % b while r != 0: a = b b = r r = a % b return b
5,315,532
def circle_line_intersect(circle, a, b): """a and b are endpoints""" assert isinstance(a, Point) and isinstance(b, Point) c, r = circle ab = b - a p = a + ab * (c - a).dot(ab) / ab.dist2() s = Point.cross(b-a, c-a) h2 = r*r - s * s / ab.dist2() if h2 < 0: return () ...
5,315,533
def rekognition_json_to_df(path, filter_poseNAs=False): """Convert AWS Rekognition output json into Pandas DataFrame. Works for json responses written by AWS Rekognition GetFaceSearch function (or as run in VidFaceSearch.py) Arguments: path -- (string) path/file filter_poseNAs -- (bool)...
5,315,534
def write_data(x, y, filename): """Writes the data to the file with given filename. """ assert(x.shape[0] == y.shape[0]) assert(len(x.shape) == 1 and len(y.shape) == 1) f = open(filename, 'w') for n in xrange(x.shape[0]): print >>f, "%0.6f\t%0.6f" % (x[n], y[n]) f.close()
5,315,535
def horizontal_flip(img, boxes, labels): """ Function to horizontally flip the image The gt boxes will be need to be modified accordingly Args: img: the original PIL Image boxes: gt boxes tensor (num_boxes, 4) labels: gt labels tensor (num_boxes,) Returns: img: the ...
5,315,536
def is_micropython_usb_device(port): """Checks a USB device to see if it looks like a MicroPython device. """ if type(port).__name__ == 'Device': # Assume its a pyudev.device.Device if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or 'SUBSYSTEM' not in port or port['SUBSYSTEM'...
5,315,537
def newcomers_and_returners(returners_df, newcomers_df, team=""): """filter newcomers and returners by team""" if team != "": team = f" for {team}" logging.info("Newcomer & Returner applicants %s", team) _, ax2 = plt.subplots() team_returners_and_newcomers = [len(returners_df), len(newcomers...
5,315,538
def main(): """Test this plot""" import cea.config import cea.plots.cache config = cea.config.Configuration() cache = cea.plots.cache.PlotCache(config.project) cache = cea.plots.cache.NullPlotCache() LoadDurationCurvePlot(config.project, {'network-type': config.plots.network_type, ...
5,315,539
def gauss_paramters(): """ Generate a random set of Gaussian parameters. Parameters ---------- None Returns ------- comps: int Number of components amp: float Amplitude of the core component x: array x positions of components y: array y posit...
5,315,540
def test_decrypt_message_failure_wrong_receiver(local_settings): """Attempt to decrypt a message that was not intended for us. Args: local_settings ([type]): passed automatically via above fixture """ test_file_path = ( files("DecryptFunction").parent / "tests" / "assets...
5,315,541
def ignore_previously_commented(reviews, username=None, email=None): """Ignore reviews where I'm the last commenter.""" filtered_reviews = [] for review in reviews: if _name(review['comments'][-1]['reviewer']) not in (username, email): filtered_reviews.append(review) return filtered_...
5,315,542
def clean(self): """Routine to return DMSP IVM data cleaned to the specified level 'Clean' enforces that both RPA and DM flags are <= 1 'Dusty' <= 2 'Dirty' <= 3 'None' None Routine is called by pysat, and not by the end user directly. Parameters ----------- inst : (pysat....
5,315,543
def get_n_p(A_A, n_p_in='指定しない'): """付録 C 仮想居住人数 Args: A_A(float): 床面積 n_p_in(str): 居住人数の入力(「1人」「2人」「3人」「4人以上」「指定しない」) Returns: float: 仮想居住人数 """ if n_p_in is not None and n_p_in != '指定しない': return { '1人': 1.0, '2人': 2.0, '3人': 3.0, '4人以上':...
5,315,544
def parse_ma_file(seq_obj, in_file): """ read seqs.ma file and create dict with sequence object """ name = "" index = 1 total = defaultdict(int) ratio = list() with open(in_file) as handle_in: line = handle_in.readline().strip() cols = line.split("\t") samples...
5,315,545
def make_mmvt_boundary_definitions(cv, milestone): """ Take a Collective_variable object and a particular milestone and return an OpenMM Force() object that the plugin can use to monitor crossings. Parameters ---------- cv : Collective_variable() A Collective_variable object whi...
5,315,546
def mask(inputs, queries=None, keys=None, type=None): """Masks paddings on keys or queries to inputs inputs: 3d tensor. (N, T_q, T_k) queries: 3d tensor. (N, T_q, d) keys: 3d tensor. (N, T_k, d) e.g., >> queries = tf.constant([[[1.], [2.], [0.]]],...
5,315,547
def is_leaf_module(module): """Utility function to determine if the given module is a leaf module - that is, does not have children modules :return: True if the module is a leaf, False otherwise """ module_list = list(module.modules()) return bool(len(module_list) == 1)
5,315,548
def get_dir_url(user_path): """ Gets the URL for a directory """ return os.path.join(DIR_URL_ROOT, user_path.lstrip('/'))
5,315,549
def _gettempdir_inner(): """Function to calculate the directory to use.""" global tempdir if tempdir is not None: return tempdir try: pwd = os.getcwd() except (AttributeError, os.error): pwd = os.curdir attempdirs = ['/tmp', '/var/tmp', '/usr/tmp', pwd] if os.name == ...
5,315,550
def test_update_individual_no_args(): """Tests the CLI that updates a individual""" # GIVEN a CLI object runner = CliRunner() # WHEN updating a individual without any args result = runner.invoke(ind_cmd) # THEN assert it fails since its missing mandatory arguments assert result.exit_code ...
5,315,551
async def modification_options(call: types.CallbackQuery): """ This handler will provide the user some options to choose from if they are not happy with the file list. Options include: 1. change around the order of the files 2. delete a file from the list 3. insert a new file to some position i...
5,315,552
def edit_subgroup_purchases(request, delivery, subgroup): """Allows to change the purchases of user's subgroup. Subgroup staff only.""" delivery = get_delivery(delivery) user = request.user subgroup = get_subgroup(subgroup) if user not in subgroup.staff.all() and user not in delivery.network.staff....
5,315,553
def get_biggest_pv_to_exchange_ratio(dataset): """Return the largest ration of production volume to exchange amount. Considers only reference product exchanges with the ``allocatable product`` classification. In theory, this ratio should always be the same in a multioutput dataset. However, this is quite ...
5,315,554
def sequence_processing_pipeline(qclient, job_id, parameters, out_dir): """Sequence Processing Pipeline command Parameters ---------- qclient : tgp.qiita_client.QiitaClient The Qiita server client job_id : str The job id parameters : dict The parameter values for this jo...
5,315,555
def Reorder(x, params, output=None, **kwargs): """Reorder a tuple into another tuple. For example, we can re-order (x, y) into (y, x) or even (y, (x, y), y). The output argument specifies how to re-order, using integers that refer to indices in the input tuple. For example, if input = (x, y, z) then ...
5,315,556
def _is_fix_comment(line, isstrict): """ Check if line is a comment line in fixed format Fortran source. References ---------- :f2008:`3.3.3` """ if line: if line[0] in '*cC!': return True if not isstrict: i = line.find('!') if i!=-1: ...
5,315,557
def _fix_rows(rows: Set["ElementList"], elements: "ElementList") -> None: """ Sometimes an element may span over multiple rows. For example: --------- | A | B | ----| | | C | | --------- In this, case, when extract_table scans for element in line with A it will pick up A and B. W...
5,315,558
def _profile_and_exit(session, model, optimizer, handle): """ Profile the run metadata at the first iteration and exit the program. """ from tensorflow.python.client import timeline run_metadata = tf.RunMetadata() for i in range(5): session.run([optimizer], feed_dict={model.h...
5,315,559
def parseConfigFile(configFilePath): """ :param configFilePath: :return: a hash map of the parameters defined in the given file. Each entry is organized as <parameter name, parameter value> """ # parse valid lines lines = [] with open(configFilePath) as f: for line in f: ...
5,315,560
def setup_passwordless_ssh(remote_host): """Execute a script for setting up a passwordless login to the target host""" execute("ssh-keyput root@%s" % remote_host)
5,315,561
def powerset(iterable): """ powerset([1,2,3]) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)] Args: iterable : iterable (e.g. list, tuple,...) - set to generate possible subsets of Returns: list - list of possible subsets """ xs = list(iterable) # note w...
5,315,562
def create_invoice(sender, invoice, issuer_details, **kwargs): """ Creates an invoice when customer is "billed". :param sender: Invoice model :param invoice: Invoice instance :param issuer_details: details about issuer """ if not invoice.items: return price = sum([item.price for...
5,315,563
def test_update_signature_on_invalid_arguments( token_network: Contract, token_network_test_utils: Contract, create_channel: Callable, channel_deposit: Callable, get_accounts: Callable, create_balance_proof: Callable, create_balance_proof_countersignature: Callable, create_close_signatur...
5,315,564
def request_artifact_published(etos, artifact_id): """Request an artifact published event from graphql. :param etos: ETOS library instance. :type etos: :obj:`etos_lib.etos.Etos` :param artifact_id: ID of artifact created the artifact published links to. :type artifact_id: str :return: Response ...
5,315,565
def get_stats(selected_sensors=None): """ return a dictionary of { sensorname: {stats} } NOTE: runs immediately not - used when we _need_ a result """ Config.logger.debug("Get Stats: {}".format(selected_sensors)) if is_str(selected_sensors): selected_sensors = (selected_sensors, ) da...
5,315,566
def show_img_and_mask(imgs,polygon_list): """ This function show the images and annotated masks for the training dataset. Input: - list of nd array images - list of polygon mask vertex coordinates Output: - Inline plot with images and masks """ mask = [] for ...
5,315,567
def count_abs_peak(arr1d, threshold): """ calculates the number of scenes which are underflooded depending on the peak count function which calculates how often the signal drops beneath a certain threshold ---------- arr1d: numpy.array 1D array representing the time serie...
5,315,568
def torch_to_numpy(data: Dataset) -> List[np.ndarray]: """Convert data from torch dataset to list of numpy arrays [input, target].""" # Create empty numpy arrays. images_shape = (len(data), *data[0][0].shape) images = np.zeros(images_shape) labels = np.zeros(len(data)) # Fill arrays with sampl...
5,315,569
def planck_taper(tlist, t1, t2): """tlist: array of times t1. for t<=t1 then return 0 t2. for t>=t2 then return 1 else return 1./(np.exp((t2-t1)/(t-t1)+(t2-t1)/(t-t2))+1)""" tout = [] for t in tlist: if t<=t1: tout.append(0.) elif t>=t2: tout.append(1.) ...
5,315,570
def has_annotations(doc): """ Check if document has any mutation mention saved. """ for part in doc.values(): if len(part['annotations']) > 0: return True return False
5,315,571
def xmon_to_arc(xmon: XmonDevice) -> Architecture: """Generates a :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` object for a Cirq :py:class:`XmonDevice` . :param xmon: The device to convert :return: The corresponding :math:`\\mathrm{t|ket}\\rangle` :py:class:`Architecture` """ node...
5,315,572
async def test_can_set_level(opp): """Test logger propagation.""" assert await async_setup_component( opp, "logger", { "logger": { "logs": { CONFIGED_NS: "warning", f"{CONFIGED_NS}.info": "info", f"{...
5,315,573
def LoadAcqSA(): """Acquisition Loading per Sum Assured""" param1 = SpecLookup("LoadAcqSAParam1", Product()) param2 = SpecLookup("LoadAcqSAParam2", Product()) return param1 + param2 * min(PolicyTerm / 10, 1)
5,315,574
def DEFAULT_APPLICANT_SCRUBBER(raw): """Remove all personal data.""" return {k: v for k, v in raw.items() if k in ("id", "href", "created_at")}
5,315,575
def _has_fileno(f): # type: (Any) -> bool """ test that a file-like object is really a filehandle Only filehandles can be given to apt_pkg.TagFile. """ try: f.fileno() return True except (AttributeError, io.UnsupportedOperation): return False
5,315,576
def _sign_rsa(hash_algorithm_name: str, sig_base_str: str, rsa_private_key: str): """ Calculate the signature for an RSA-based signature method. The ``alg`` is used to calculate the digest over the signature base string. For the "RSA_SHA1" signature method, the alg mu...
5,315,577
def partition(my_list: list, part: int) -> list: """ Function which performs Partition """ begin = 0 end = len(my_list) - 1 while begin < end: check_lower = my_list[begin] < part check_higher = my_list[end] >= part if not check_lower and not check_higher: # Swap ...
5,315,578
def GenerateHoverDatabase(): """Generates a hover aerodynamics database in the DVL format. A hover aerodynamic database models all the aerodynamic surfaces as independent airfoils and accounts for the effect of the propwash on these surfaces. The database is output in the DVL format which includes the follo...
5,315,579
def silhouette_k(data, n_clusters): """Generates a silhouette plot for n_clusters """ fig, ax1 = plt.subplots(1) ax1.set_xlim([-.1, 1]) ax1.set_ylim([0, data.shape[0] + (n_clusters + 1) * 10]) clusterer = KMeans(n_clusters=n_clusters) cluster_labels = clusterer.fit_predict(data) silhouet...
5,315,580
def _get_value(point: Tuple[int, int, int], volume_data: torch.Tensor) -> float: """ Gets the value at a given coordinate point in the scalar field. Args: point: data of shape (3) corresponding to an xyz coordinate. volume_data: a Tensor of size (D, H, W) corresponding to a 3D s...
5,315,581
def assert_request_user_has_resource_db_permission(request, resource_db, permission_type): """ Check that currently logged-in user has specified permission on the provied resource. If user doesn't have a required permission, AccessDeniedError is thrown. """ has_permission = request_user_has_resourc...
5,315,582
def handle_error(error): """ Handle generic SocketIOEventError. """ if isinstance(error, SocketIOEventError): LOGGER.warning(f"Error encountered during {request.event}: {error!r}") emit(error.event, error.response) else: error_id = uuid4() LOGGER.exception( f"An ...
5,315,583
def compare_cli(filename, param_list=None): """Change internal chloride concentration (for constant/static) runs""" cli_list = param_list if not cli_list: cli_list = [2.5, 5, 7.5, 10, 12.5, 15, 20, 25, 30] print("cli_list:{}".format(cli_list)) load_file(filename) for cli in cli_list: ...
5,315,584
def wait_for_ipc(ipc_path: pathlib.Path, timeout: int=30) -> None: """ Waits up to ``timeout`` seconds for the IPC socket file to appear at path ``ipc_path``, or raises a :exc:`TimeoutError` otherwise. """ start_at = time.monotonic() while time.monotonic() - start_at < timeout: if ipc_pa...
5,315,585
def forced_checkout_with_real_obstructions_and_unversioned_files(sbox): """co with real obstructions and unversioned files""" # Make a local tree that partially obstructs the paths coming from the # repos, make the obstructing files different from the standard greek # tree, and finally add some files that don'...
5,315,586
def test_merge_primary_command(create_project, run): """Test that a simple primary command is attached to the default doc.""" with create_project( ''' def roar(): """usage: roar""" print('ROAR!') def rawr(): """usage: roar rawr""" print('R...
5,315,587
def generate(request, name): """ Generate initialcons for a given name as a .png. Accepts custom size and font as query parameters. """ if name == '': name = '?' name = name.encode('utf-8').upper() # Custom size size = request.GET.get('size', False) if size and size.isdigit(...
5,315,588
def update_file(info, dist_dir, username, password): """Updates the file by re-uploading it. Only way I could figure to remove the 'Featured' label, ugh. Unfortunately, it also updates the upload date, oh well. Args: info: dictionary filled with project_name, fname, summary, and labels dist_dir: the d...
5,315,589
def run_learning_tests_from_yaml( yaml_files: List[str], *, max_num_repeats: int = 2, smoke_test: bool = False, ) -> Dict[str, Any]: """Runs the given experiments in yaml_files and returns results dict. Args: yaml_files (List[str]): List of yaml file names. max_n...
5,315,590
def printFaceBox(frame, scale, bb, color): """ 打印脸上的方框 args: frame: opencv 格式图像 scale: 同 resize:scale bb: 头像定位对象, 通过 faceapi.allFaceBoundingBoxes 可以得到 """ # center = bb.center() # height, width = getSize(frame) # centerI = 0.7 * center.x * center.y / \ # (sca...
5,315,591
def make_interpolant(a, b, func, order, error, basis="chebyshev", adapt_type="Remez", dtype='64', accurate=True, optimizations=[]): """ Takes an interval from a to b, a function, an interpolant order, and a maximum allowed error and returns an Approximator class representing a...
5,315,592
def dumpkvs(): """ Write all of the diagnostics from the current iteration level: int. (see logger.py docs) If the global logger level is higher than the level argument here, don't print to stdout. """ Logger.CURRENT.dumpkvs()
5,315,593
def set_seed(seed=0): """ set seed for torch. @param seed: int, default 0 """ random.seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) # if you are using multi-GPU. t...
5,315,594
def handle_UnknownLanguageError(exc, *args): """Handles error raised when an unknown language is requested """ _ = gettext_lang.lang lang = exc.args[0] all_langs = exc.args[1] message = _( " AvantPy exception: UnknownLanguageError\n\n" " The following unknown language was ...
5,315,595
def get_title(bot, trigger): """ Get the title of the page referred to by a chat message URL """ DOMAIN_REMAPS = [("mobile.twitter.com", "twitter.com")] url = trigger.group(1) for substr, repl in DOMAIN_REMAPS: url = url.replace(substr, repl) host = urlparse(url).hostname if any(badhost...
5,315,596
def test_on_dataframe(df, excluded_features=None, clustering_features=None, integer_features=None): """Prints comparison of distributions: original one and toymc. :type excluded_features: features we absolutely don't take into account :type clustering_features: list | None, very close to integer ones, usua...
5,315,597
def assumption_html(): """Produces an HTML list of all assumption descriptions.""" # full_descriptions = [a.description.format(a.value) for a in ASSUMPTIONS_TO_DISPLAY] items = _list_items(map(_prettyprint, ASSUMPTIONS_TO_DISPLAY)) return ASSUMPTION_TEXT.format("\n".join(items))
5,315,598
def edit_page_element(project, pagenumber, pchange, location, tag_name, brief, hide_if_empty, attribs): """Given an element at project, pagenumber, location sets the element values, returns page change uuid """ proj, page = get_proj_page(project, pagenumber, pchange) part = page.location_item(locatio...
5,315,599