content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import re def tokenize(text): """ The function to tokenize and lemmatize the text. Inputs: text: the text which needs to be tokenized Outputs: tokens: tokens which can be used in machine learning """ stop_words = stopwords.words("...
b41e66c4a065d898b2c3cf05fa261f6100d0f413
3,649,500
def remove_task(name: str): """ Delete a task based on information "name": - **name**: each tasks must have a name """ name_idx = _db_has_name(name) if name_idx == None: raise HTTPException(status_code = 400, detail = {"message" : "name doesn't exists"}) else: del db["tasks...
4190e3e6a0ac55defe5ba6dcac3036f7c7df290b
3,649,501
def set_dj_definition(cls, type_map: dict = None) -> None: """Set the definition property of a class by inspecting its attributes. Params: cls: The class whose definition attribute should be set type_map: Optional additional type mappings """ # A mapping between python types and DataJoi...
9335e1b4413ce03f98ca885bcf4a888af9d014a1
3,649,502
def mmap_zeros(shape, dtype): """ Create an empty shared memory array. """ new = anonymousmemmap(shape, dtype) new[:] = 0.0 return new
5f78b5e227ab7f5115bc04af2e3f7ea62a769cd8
3,649,503
from typing import Iterable def edge_disjoint_paths(g: Graph, source: Node, sink: Node) -> Iterable: """ Given directed graph G, and two nodes s and t, find k paths from s to t such that no two paths share an edge. Menger’s Theorem: Given a directed graph G with nodes s,t the maximum number o...
d638923e9091eefcee0c0e2623adba095e33cc0c
3,649,504
def listToMLlibVectorUDF(col): """ Map struct column from list to MLlib vector """ return Column(default().listToMLlibVectorUDF(col._jc))
9b785839234bc2dfcb44c193cc12930e4f26f1a8
3,649,505
def change_file_paths_to_showcase(df, showcase_dir="/showcase_data/raw_data"): """Changes file paths to use showcase directory""" output = df.copy() if "file_path" in df.columns: output.loc[:, "file_path"] = df.file_path.apply( lambda x: add_path(x, showcase_dir) ) if "file_p...
6789ff426794b620eebb1d80ae96b1a18c9a2dc8
3,649,506
def match_conftest_error(line): """ Extract `ConftestImportFailure` error message from a string. :param line: A string to pattern match against. :returns: A dictionary where the key `file_path` holds the file path and the key `error` the error description. If not matched, the dictionary is ...
90b10831b672bb053cc46e5adbefaea5597607e3
3,649,507
import string def modifyModlist( old_entry,new_entry,ignore_attr_types=None,ignore_oldexistent=0 ): """ Build differential modify list for calling LDAPObject.modify()/modify_s() old_entry Dictionary holding the old entry new_entry Dictionary holding what the new entry should be ignore_attr_ty...
f28814b4659ccc8e9e27eec0dee5da8700a732ac
3,649,508
def regnety_3200m(**kwargs): """ Constructs a RegNet-Y model under 3200M FLOPs. """ model = RegNet(regnetY_3200M_config, **kwargs) return model
6799f96df72769e6f8bd0819e47353e141acefd0
3,649,509
import operator import numpy def _get_exposure(fname, stop=None): """ :param fname: path of the XML file containing the exposure :param stop: node at which to stop parsing (or None) :returns: a pair (Exposure instance, list of asset nodes) """ [exposure] = nrml.read(fna...
d782826c427fb30e5561908f4342b2f6983ab46b
3,649,510
def dcos_api_session(dcos_api_session_factory): """ Overrides the dcos_api_session fixture to use exhibitor settings currently used in the cluster """ args = dcos_api_session_factory.get_args_from_env() exhibitor_admin_password = None expanded_config = get_expanded_config() if expanded_conf...
ab677802d1228b3af4bfc8ecc2cbf6040edbc6b0
3,649,511
def BarycentricInterpolation(bins, pnts): """ barycentricinterpolation for given points, return the barycentric coordinates for points within the grids INPUT bins - grids for discretization, m-length array where bins[i] indicates the mesh along dimension i pnts - an a...
aa12be78a581cae154887da4546b0a9e94297e00
3,649,512
from pathlib import Path import shutil def submit_rgi_job(sample_instance: AnalysisSample) -> RGIResult: """ Given an input AnalysisSample instance, runs RGI and stores result in the database :param sample_instance: Instance of AnalysisSample object :return: Populated RGIResult object generated by the...
3610f59fe62c01c211fcbf93658bc0c70eb25b12
3,649,513
def forwardslash2shift(args=None): """ Make forward slash shift when pressed with another key """ run_mapper(premade.ForwardSlash2Shift) return 0
cb9cbbe3272fbfd2cdf16fc4d5fce90b378b4b32
3,649,514
def plotly_figure(figure, id: str): """ :param figure: plotly graph object or px figure :param id: unique id string of format 'id_xxx' with x representin a number :return: html style string containing a plotly figure """ json_figure = figure.to_json() html = """ <div id="""+id+"""></...
949415c70d467c48ee3aa1f028c9e3539099febf
3,649,515
def _add_resources_to_vault_obj(obj, data, columns): """Add associated resources to column and data tuples """ i = 0 for s in obj.resources: if obj.resources[i].id: name = 'resource_id_' + str(i + 1) data += (obj.resources[i].id,) columns = columns + (name,) ...
3a6dd7541ac853a7c62b638abf4d0eeb21bb6cb2
3,649,516
def classify_helmet_belt_worn(x): """ This function returns a strinig representation of the int value of the field which specifies whether the person was wearing a setabelt or a helmet. This specification is from the Road Crash Statistics Victoria , 2013 Edition document. :param x: int value represe...
cba05be8d03c933e767a75400032d07e296e0ec3
3,649,517
def history_kernels ( estimated_stimulus_kernel, estimated_response_kernel, ci_kernels, ax=None, presentation="left/right", ground_truth=None ): """plot history kernels :Parameters: *estimated_stimulus_kernel* stimulus kernel estimated from the data *estimated_response_kernel* ...
c25751759079dbf11b7b63e9ed66b73d3552c040
3,649,518
def init_application(): """Main entry point for initializing the Deckhand API service. Create routes for the v1.0 API and sets up logging. """ config_files = _get_config_files() paste_file = config_files[-1] CONF([], project='deckhand', default_config_files=config_files) setup_logging(CONF...
3bc5b9d8f0378c4e19ce61f9ab4ef66a9a6733d6
3,649,519
def specs_url(self): """ The Swagger specifications absolute url (ie. `swagger.json`) :rtype: str """ return url_for(self.endpoint('specs'), _external=False)
1620c8eb4d0b8e61c9a67aadca677b2acae5074f
3,649,520
import sqlite3 def construct_db(db: str) -> sqlite3: """Build empty database 'db'.""" conn = sqlite3.connect(db) c = conn.cursor() c.executescript(''' CREATE TABLE files ( ID INTEGER PRIMARY KEY, Name TEXT, Path TEXT, FullPath TEXT, isDir INTEGER, S...
22759b9b8e68e7c39f8fdd6fc33124c0ecea3a24
3,649,521
def class_javadoc(ns, stmt): """ Generate javadoc for class (string without '/**' and '*/' but with * on new line) """ description = '' desc_stmt = search_one(stmt, 'description') if desc_stmt is not None: description += ''.join([str(desc_stmt.arg).replace('\n', '\n * ')]) description += ''....
9bfc093362bdb573ba8b41ca17b037b57da3891e
3,649,522
def r_precision(r): """Score is precision after all relevant documents have been retrieved Relevance is binary (nonzero is relevant). Args: r: Relevance scores (list or numpy) in rank order (first element is the first item) Returns: R Precision """ r = np.asarray(r) ...
998ff6750ce51455fa09ae5970a94934a4c3f383
3,649,523
import sklearn.metrics import sklearn.utils.multiclass from rasa.test import get_evaluation_metrics from typing import List from typing import Optional from typing import Dict import os def evaluate_response_selections( response_selection_results: List[ResponseSelectionEvaluationResult], output_directory: Opt...
cf108c5db93785a2ee8ab963cd6dc318c6a871fe
3,649,524
from typing import Callable from typing import Coroutine from typing import Any def _async_climate_updater( lookin_protocol: LookInHttpProtocol, uuid: str, ) -> Callable[[], Coroutine[None, Any, Remote]]: """Create a function to capture the cell variable.""" async def _async_update() -> Climate: ...
b4160385fe7f304096de6bb9196822d3230c342f
3,649,525
def load_natural_movies(cpd=1.00): """load natural movies dataset Parameters ---------- - cpd: float of cycles per degree, should be 1.00 or 1.33 """ if cpd not in {1.00, 1.33}: raise Exception('cpd must be in {1.00, 1.33}') if cpd == 1.00: cpd = '1.00' elif cpd == 1.33:...
bff8dd14cc2afac89aceb9407651f5cb91509a9a
3,649,526
import collections def sort_dataset_by_len(dataset): """ returns a dict mapping length -> list of items of that length an OrderedDict is used to that the mapping is sorted from smallest to largest """ sorted_dataset = collections.OrderedDict() lengths = sorted(list(set(len(x[1]) for x in datas...
1e67da963c6d968fba39730cc33e100242fcafca
3,649,527
def rule_VisibleTo_if_in_same_visible_container(x, actor, world) : """Anything in the same visible container to the actor is visible if the visible container is lit. We treat doors specially: if x is in the get_room_doors of the visible container, then the door is visible, too.""" actor_vis_cont = ...
8e4465d7684c95a9890e4271b2dbb75b665d2efd
3,649,528
import copy import random def select_random_user_goals(user_goals_no_req_slots, user_goals_with_req_slots, cardinality_no_req, cardinality_req): """ Helper method to randomly select user goals """ random_user_goals = {} random_user_goals['all'] = [] # select randomly user goals without reque...
ff51361d45cdbd62cc9ee9e8263d47870435b326
3,649,529
import copy def dict_items_recursive_apply(config_dict, apply_method, **apply_method_parameters): """Recursive apply method to dict elements >>> dict_items_recursive_apply( ... {"foo": {"bar":"baz"}, "qux": ["a","b"]}, ... lambda k,v,x: v.upper()+x, **{"x":"!"} ... ) == {'foo': {'bar': 'B...
760e3de8e414dcd5300aa79cc703b0941a5852fd
3,649,530
def d_B_nu_d_T_d_nu_dimensionless(x): """ Calculates d^2(B_nu) / d (T) / d (nu), as a function of dimensionless units, x = (h nu / k_B T) Parameters ---------- x : float Returns ------- d_B_nu_d_T_d_nu_dimensionless : float Not normalized to anything meaningful """ return - np.exp(x)*x**3 * (np.exp(x)*...
eb1e42d48e15cbc5ea17877868cca27422d89346
3,649,531
def node_to_get_batch_value(shape_node: Node): """ The function returns a node that produces the batch value which is usually the element of the shape with index 0 :param shape_node: the node of 1D output shape to get batch from :return: the node producing batch value """ return node_to_get_shap...
126570b69895cd34bb6821f179076d6d005c36db
3,649,532
def re2_full_match(input, pattern): # pylint: disable=redefined-builtin """Extract regex groups Args: input: A `tf.string` tensor pattern: A pattern string. """ return core_ops.io_re2_full_match(input, pattern)
d9ca2606eae8faf21bf2cf7ec1730c69f609d4c5
3,649,533
import os import socket import requests def user_agent(): """ Return a User-Agent that identifies this client. Example: python-requests/2.9.1 edx-rest-api-client/1.7.2 ecommerce The last item in the list will be the application name, taken from the OS environment variable EDX_REST_API_CL...
b0e65ba2ddb3af1f0fc5b0ae1a561b330426d9de
3,649,534
import click def optional_tools_or_packages_arg(multiple=False): """ Decorate click method as optionally taking in the path to a tool or directory of tools or a Conda package. If no such argument is given the current working directory will be treated as a directory of tools. """ name = "paths" if ...
4a34da51b4a644df70c5ce3ea8afb8b86ae2281d
3,649,535
import numpy def linear_interpolate_cdf(base_cdf): """Linear interpolate regions of straight lines in the CDF. Parameters: base_cdf (list): n elements of non-decreasing order. Returns: list of length base_cdf where consecutive elements of straight lines are linearly interpolated ...
8f119d1698a44e90253920decf1b3253db9171be
3,649,536
def hash_str(string: str) -> int: """ Create the hash for a string (poorly). """ hashed = 0 results = map(ord, string) for result in results: hashed += result return hashed
b80c177974437966361e4117ba235c1563fee5c4
3,649,537
import plotly.graph_objects as go import plotly.io as pio def graph(g: nx.Graph, s: Optional[list] = None, plot_size: Tuple = (500, 500)): # pragma: no cover """Creates a plot of the input graph. This function can plot the input graph only, or the graph with a specified subgraph highlighted. Graphs are ...
9830ef44f3a85234002c11d0da1913a89c332491
3,649,538
def intersect(p1x, p1y, p2x, p2y, x0, y0): """Intersect segment defined by p1 and p2 with ray coming out of x0,y0 ray can be horizontal y=y0 x=x0+dx , want dx>0. Args: p1x (float): x coordinate of point 1 of segment p1y (float): y coordinate of point 1 of segment p2x (float): x coo...
b58ae51cf179183689a7ed4b0854eefaeb28b895
3,649,539
from scipy import linalg def impulse_matrix(params, dt, reduced=False): """Calculate the matrix exponential for integration of MAT model""" a1, a2, b, w, R, tm, t1, t2, tv, tref = params if not reduced: A = - np.matrix([[1 / tm, -1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], ...
4305d588680dd5de91765e79b170d26e43f82a01
3,649,540
def get_vimg(request): """ 获取验证码 :param request: :return: """ text, image = vcode.gen_captcha_text_and_image() v_key = request.GET.get('vk') ex_key = request.GET.get('ex') if ex_key: try: redis_conn.delete(ex_key) except Exception as e: logger.error(e) redis_conn.set(v_key, text, 60*3) return...
f3398236cb4d69f21a04519de472d85dca885a2c
3,649,541
def generate_fcm_token(): """Generate an FCM token nLAUJTr5RIJ:MNmSQ8O52FoJSvfWEPF4KvWopcNScNFRPHHbXdepwzuXJJMfadpEfb2JlHoqEhWanFz7-N0sfPg-pW4gNubNdxyikiI0lrvGeWGTp86fn9-NA3sZ-Eizv9QE7YKHCOIa70fR38N1ZYsb """ return '{}:{}-{}-{}-{}-{}'.format(random_all(11), random_a...
e535584bf630e1353a8f7458ff45cf2f0c1433fb
3,649,542
from typing import Optional import grp def _create_group(username: str, gid: Optional[int] = None, system: bool = False) -> Result[Group]: """ Create a new group. """ try: get_group(username) except KeyError: pass else: raise ValueError("Username {!r} is already in use"...
117e25e91c9f3e37bc58a005d3e036dc8cc9f4d3
3,649,543
def evaluate(data_loader): """Evaluate given the data loader Parameters ---------- data_loader : DataLoader Returns ------- avg_loss : float Average loss real_translation_out : list of list of str The translation output """ translation_out = [] all_inst_ids ...
f7697e9f22e5bda3af6b0892b3cc5c3b047771f0
3,649,544
def adding_equation(thetas, eta0, eta1, eta2, eta3, kappa3 = 0.0, polarized=False, tau1=0.0, tau2=0.0): """ Return the reflectance of a 4 layers material (3 interfaces) with all inter-reflections, using adding equation """ zeros = [np.zeros_like(thetas),np.zeros_like(thetas)] if polarized else np.zeros_...
1e1f7e56096d712f04354cca52987b2010fd322f
3,649,545
import logging def text_expand(context): """ Give context, pick out the bible indexes, turn them into normalized scripture, and put the scripture back into the context """ output = [] end = 0 for m in candidate_filter(context): output.append(m.group('out')) try: buc...
146cd85a1007215cc8bed53341418a7b3c23b532
3,649,546
from typing import Iterable from datetime import datetime def json_custom_parser(obj): """ A custom json parser to handle json.dumps calls properly for Decimal and Datetime data types. """ if not isinstance(obj, string_types) and isinstance(obj, Iterable): return list(obj) elif isinsta...
dbee1501376d2b1fc235b5351236e857fc9c5750
3,649,547
def like(): """ Function to automatically like a picture :return: 0 or 1 where 1 = one picture liked :rtype: int """ like_icons = driver.find_elements_by_xpath("//*[contains(@aria-label, 'Like')]") unlike_icons = driver.find_elements_by_xpath("//*[contains(@aria-label, 'Unlike')]") for icon...
5db4a43c4b29a3cb49d62bddf755a9e374f0ac4e
3,649,548
import os def entity_tsv(args): """ Get list of entities in TSV format. Download files for which the encoding is undetected (e.g. ZIP archives). """ r = fapi.get_entities_tsv(args.project, args.workspace, args.entity_type, args.attrs, args.model) fapi._check_response_code...
14f966144e21d91801f9e4b5966e0499699da83e
3,649,549
def compare_files(file_name1, file_name2): """ Compare two files, line by line, for equality. Arguments: file_name1 (str or unicode): file name. file_name2 (str or unicode): file name. Returns: bool: True if files are equal, False otherwise. """ with open(file_name1) as f...
3f77cf177ba60ddd121b95648379fff845d9877b
3,649,550
def like(request, pk): """Add a user to those who liked the post. Only authenticated users are able to like a post. """ if request.method == 'POST': # query the post in question try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: return Respons...
d3ef1d9728592872a73b900c60e4021078d2ef2e
3,649,551
import os import sys import subprocess def calc_power_VARIANT(input_data, working_dir, t_pt=0): """Calculate the power distributions from VARIANT Parameters ---------- data : dict DASSH input data dictionary working_dir : str Path to current working directory Returns ----...
acd58904ae1f67ef1f27de5e5399d21175c0ef9e
3,649,552
def from_float32(buffer): """Interprets an arbitrary string or NumPy array as Vax single-precision floating-point binary values, and returns the equivalent array in IEEE values.""" # Convert the buffer to 2-byte elements if isinstance(buffer, (str, np.str_, bytes, bytearray)): pairs = np.fr...
2ab310b2d5cc6fcd7f9f094d97de319a1643dc7e
3,649,553
def get_file_stats(file_name, entity_type='file', lineno=None, cursorpos=None, plugin=None, language=None, local_file=None): """Returns a hash of information about the entity.""" language = standardize_language(language, plugin) stats = { 'language': language, 'dependenci...
b1ccf3d0eb2af676fce690e5f81182d89d50596b
3,649,554
def setup(app: sphinx.application.Sphinx) -> dict[str, object]: """Called by Sphinx to set up the extension.""" app.add_config_value("gaphor_models", {}, "env", [dict]) app.add_directive("diagram", DiagramDirective) app.connect("config-inited", config_inited) return { "version": "0.1", ...
992d7436d31cd18b7cd50b02b013d9c56179eacb
3,649,555
from nipype.interfaces.afni import utils as afni_utils def create_vmhc(use_ants, flirt_only=False, name='vmhc_workflow', ants_threads=1): """ Compute the map of brain functional homotopy, the high degree of synchrony in spontaneous activity between geometrically corresponding interhemispheric (i.e., homotopi...
4c71974d962d86385de8de9d6752dc59b1e205d0
3,649,556
def get_chunk_index(connection, db, # pylint: disable=too-many-arguments tbl, chunk, ch_db='percona', ch_tbl='checksums'): """ Get index that was used to cut the chunk :param connection: MySQLDb connection :param db: database of the chunk :param tbl: table o...
6cf59174d766d68dc635e9c578c9d4d12dba55bf
3,649,557
import subprocess import json def _get_tree(code): """Return an AST tree of the JS passed in `code`.""" if not code: return # Acceptable unicode characters still need to be stripped. Just remove the # slash: a character is necessary to prevent bad identifier errors. code = JS_ESCAPE.sub(...
7705ca63765a4408651b310f604141fc1ebc1d6e
3,649,558
from typing import List def initial_assignment_alpha_MSS(agents: List[AdditiveAgent], items: List[str], alpha: float)->Allocation: """ Initial division for allocting agents according to their alpha-MMS. :param agents: valuations of agents, normalized such that MMS=1 for all agents, and valuation are...
5ac7fa947ee555dfd963c679696224e58e2c343a
3,649,559
import os def find_furious_yaml(config_file=__file__): """ Traverse directory trees to find a furious.yaml file Begins with the location of this file then checks the working directory if not found Args: config_file: location of this file, override for testing Returns: ...
b2b3354fc411123f9360d01d0123946c9cf9fe24
3,649,560
def comp_axes( self, axes_list, machine=None, axes_dict_in=None, is_periodicity_a=None, is_periodicity_t=None, per_a=None, is_antiper_a=None, per_t=None, is_antiper_t=None, ): """Compute simulation axes such as time / angle / phase axes, with or without periodicities and ...
d01cb4efb2b1676cc2548e3e57324733708e4764
3,649,561
def clean_vehicles(country): """Delete all vehicles from given country.""" with elastic() as client: search = Vehicle.search(using=client).filter("term", country=country) count = search.count() search.delete() return count
021189a68ec6035af2b5140f79a29ce71caa12fd
3,649,562
from typing import Union from pathlib import Path from typing import Any def render_template( env: NativeEnvironment, template: Union[Text, Path], context: Any, ) -> Any: """Utility function for rendering Jinja2 text or file templates. Args: env: The Jinja2 environment to use for renderin...
61585cf76896afd70be8b3a620cb4dbe8620c567
3,649,563
import os def _get_template_dirs(type="plugin"): """Return a list of directories where templates may be located. """ template_dirs = [ os.path.expanduser(os.path.join("~", ".rapport", "templates", type)), os.path.join("rapport", "templates", type) # Local dev tree ] return templat...
b0c6351d0e346310f5d36c6d010332cc1e1b54ea
3,649,564
def aspect_ToCString(*args): """ * Translates an ExtendedString to a CString depending of the local format. :param aString: :type aString: TCollection_ExtendedString & :rtype: char * """ return _Aspect.aspect_ToCString(*args)
e5f5b352b60610f3a18e0757a98b8e58f31c84ff
3,649,565
def suites_list(request): """List suites.""" return TemplateResponse( request, "manage/suite/suites.html", { "suites": model.Suite.objects.select_related().annotate( case_count=NotDeletedCount("cases", distinct=True)), } )
55e1cd86a0d82bc6fd2a6b75248a1a4b06264bb5
3,649,566
def push_gitlab_event_dict(): """ Cleared version of the push gitlab webhook content. """ return { "object_kind": "push", "event_name": "push", "before": "0e27f070efa4bef2a7c0168f07a0ac36ef90d8cb", "after": "cb2859505e101785097e082529dced35bbee0c8f", "ref": "refs/...
3a0134774f828e233c8b1e3fd2d6b94d6fae699f
3,649,567
def compute_rotation_effects(VD, settings, EW_small, GAMMA, len_mach, X, CHORD, XLE, XBAR, rhs, COSINP, SINALF, PITCH, ROLL, YAW, STB, RNMAX): """ This computes the effects of the freestream and aircraft rotation rate on CLE, the induced flow at the leading edge Assumptio...
6184f0732c4da4726a5f17e99bd7329bd55c4907
3,649,568
def introduction(course): """This method represents route to 'courses/<course>/intro.html' where the character introduction is rendered. This method handles both GET and POST requests. Args: course (string): Name of the course. Returns: render_template: Returns rendered 'courses/<cours...
7c569f98afbced4a0e1c45b0956d3ba15147384f
3,649,569
import pesummary.core.file.formats import pesummary.gw.file.formats import pkgutil import importlib def available_formats(): """Return the available formats for reading and writing Returns ------- tuple: tuple of sets. First set are the available formats for reading. Second set are the available ...
1419092210d0cf5dfa116d43c0354c309afc831e
3,649,570
import json def bbox_from_openpose(openpose_file, rescale=1.2, detection_thresh=0.2): """Get center and scale for bounding box from openpose detections.""" with open(openpose_file, 'r') as f: keypoints = json.load(f)['people'][0]['pose_keypoints_2d'] keypoints = np.reshape(np.array(keypoints), (-1...
c91397fbe42a15d8bce1f1018303e6ff7328c467
3,649,571
def calc_KPs(TempC, Sal, P=None): """ Calculate equilibrium constants for P species. KP1 = H3PO4 KP2 = H2PO4 KP3 = HPO4 Chapter 5, Section 7.2.5 of Dickson, Sabine and Christian (2007, http://cdiac.ornl.gov/oceans/Handbook_2007.html) **WITHOUT APPROX PH SCALE CONVERSION IN CONSTANT** ...
a850fb9a85946d4fc9607f8b6744291157b980d1
3,649,572
def evaluate_model_sector_prediction( model, test_data_x, test_data_y, test_data_industry, test_data_size, mode_classifier=True, max_seq_length=512, batch_size=8, ): """This is a function to predict the sector given the input text ids""" model = model.eval() pred_label_test ...
4b0d97c647f9e49600a149a0f5144744ea78f8bc
3,649,573
def is_no_op(module: Module) -> bool: """Return whether the module does no operation in graph. Args: module: module Returns: whether module is no operation """ no_op_modules = (Sequential, _Branch, Parallel, ReduceTuple, GraphModule) return isinstance(module, no_op_modules)
6b5a765be41353596a500e6827800868daa16386
3,649,574
import os def has_ext(path_name, *, multiple=None, if_all_ext=False): """ Determine if the given path name has an extension """ base = os.path.basename(path_name) count = base.count(EXT) if not if_all_ext and base[0] == EXT and count != 0: count -= 1 if multiple is None: ...
53fc639b44b2a1791220ec24f2b1fc6922152482
3,649,575
import os import multiprocessing def index_directory(directory, labels, formats, class_names=None, shuffle=True, seed=None, follow_links=False): """Make list of all files in the subdirs of `direct...
474886eecf2515e53d2120357a8c5405e89a45fb
3,649,576
def colors_from_cmap(length=50, cmap=None, start=None, stop=None): """Return color cycle from a given colormap. Parameters ---------- length : int The number of colors in the cycle. When `length` is large (> ~10), it is difficult to distinguish between successive lines because successiv...
e2c7c117ab3d463ee20548c15d3e7deee3a1879a
3,649,577
def mag_thresh(img, sobel_kernel=3, mag_thresh=(30, 100)): """ Return the magnitude of the gradient for a given sobel kernel size and threshold values """ # Apply the following steps to img # 1) Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) # 2) Take the gradient in x and y separately...
c079ca591c4e35e69821d871d7f451aaaf867ef9
3,649,578
def mean_absolute_percentage_error(predictions, targets): """Calculate mean absolute percentage error""" mask = (targets != 0.0) return (np.fabs(targets - predictions)/targets)[mask].mean()*100.0
1f37da29c47035a3656d3d07b34ec26f862a80ac
3,649,579
def make_net_xds_list(data_xds_list, coords_per_xds): """Construct a list of dicts of xarray.Datasets to house the net gains. Args: data_xds_list: A List of xarray.Dataset objects containing MS data. coords_per_xds: A List of Dicts containing dataset coords. Returns: net_gain_xds_l...
1546555e76d0f6bab4abc7985707f8be9fc19558
3,649,580
import collections def sort_dict(d, key=None, reverse=False): """ Sorts a dict by value. Args: d: Input dictionary key: Function which takes an tuple (key, object) and returns a value to compare and sort by. By default, the function compares the values of the dict ...
9ca904a5e0df3e3c50b29967adfe9061e778dfc9
3,649,581
import requests def check_builds(): """Base task""" response = requests.get( url=urljoin(Config.SISENSE_URL, "v2/builds"), headers=Config.SISENSE_HEADERS ) builds = pd.DataFrame(data=response.json()) failed_builds = builds.loc[(builds.status == "failed")] # for each failed cube: fo...
38820f314ff8a57cbf5b7242a52b557905b0f1eb
3,649,582
def comp_neworig(tileid,dirn='/global/cfs/cdirs/desi/survey/catalogs/testfiberassign/SV3rerun/orig/'): """ check that new matches the original """ ts = str(tileid).zfill(6) fa = fitsio.read('/global/cfs/cdirs/desi/target/fiberassign/tiles/trunk/'+ts[:3]+'/fiberassign-'+ts+'.fits.gz') fn = ...
e7d1d4202b024508712e14de86341d3597c85314
3,649,583
def _get_widget_handler(webmanager): """ Returns a handler to get the widgets :param WebManager webmanager: :return tornado.web.RequestHandler: """ class WidgetHandler(web.RequestHandler): """ Handler for all communications over WebSockets """ def get(self): ...
734b081e3b92180356e88ca21418785d45662b64
3,649,584
def get_model_field_type(model, field_label): """ Returns model's field type. """ return FIELD_TYPES_MAPPING.get(type(get_model_field(model, field_label)), 'STRING')
aeba374954b25f0383015f56be41cdc5f9917ae3
3,649,585
def Normalize_Column_Scores(df, columns, norm_type = 'divide_by_max'): """Normalizes scores for specified columns in a pandas dataframe Parameters ---------- df : a pandas DataFrame object that contains the specified columns columns: a list object that includes the columns to normalize ...
906fcf944b676e04120eb915e7ead24c97900f56
3,649,586
import json import os def custom_pdf_merge(doctype,docid,attach_to_og_doc=False,doc_to_merge={}): """ doc_to_merge = { "dt_to_merge": "", ##doctype on which merge is to be performed "dt_to_merge_id": "", ##docid on which merge is to be performed "attach_fieldname": "", ##fieldname of the attach field th...
070caf97c60139841bf0471f75442ea0a6397336
3,649,587
def find_most_common_word(sentence): """Return the most common word in the sentence.""" # Change to lowercase and strip out punctuation sentence = clean_sentence(sentence) list_of_words = sentence.split() word_to_count = dict() # Create a histogram of the occurrence of all words for w...
0c9e03fb4324999e73e2d036ab3dec53f1857fe8
3,649,588
def fast_rcnn_inference(boxes, scores, image_shapes, predictions, score_thresh, nms_thresh, topk_per_image): """ Call `fast_rcnn_inference_single_image` for all images. Args: boxes (list[Tensor]): A list of Tensors of predicted class-specific or class-agnostic boxes for each image. Elem...
24fec22cdd285d50b4512115b638f3b7499f47be
3,649,589
def GetVar(doc:NexDoc, varNumber, varType) -> NexVar: """Returns the reference to the specified variable.""" return NexRun("GetVar", locals())
355f51f3ffa9b0d5c5f835546ee38bc3e0784328
3,649,590
def putversenotes(): """Serves AJAX call for json data to save notes. See also [M:NOTESAVE.putVerseNotes][notesave.NOTESAVE.putVerseNotes]. Client code: [{noteverse.sendnotes}][noteversesendnotes] """ session.forget(response) Books = BOOKS() Note = NOTE(Books) NoteSave = NOTESAVE(Note)...
b1fece391a6e47c2f500a540d57e12c1c0c11279
3,649,591
def _valid_multiview_args(cfg_user, logger): """ Validates the "multiview" parameters of a json configuration file used for training. The function returns False if an error has occurred and True if all settings have passed the check. :param cfg_user: EasyDict, json configuration file imported as dicti...
1a60afbf956b5b7096ec21a52669b1aa85f54c7d
3,649,592
import os def generate_extension(project=None, outdir=None, *, _project_from_raw=info.Project.from_raw, _abspath=os.path.abspath, _projfiles=None, _gen=None, ): """Produce all needed files to build a...
966b1539c5b90a4ae53d13c8fdc71f88fb76ea99
3,649,593
def apply_gradient_descent(var_list, obj, learning_rate = 0.01): """ Sets up the gradient descent optimizer Args: var_list: List of variables to optimizer over. obj: Node of the objective to minimize Notes: learning_rate: What learning rate to run with. (Default = ``0.01...
97ed8db3e02412f2dfbe4e44b6835ed8fe754c57
3,649,594
from re import T from typing import Callable import inspect from typing import get_type_hints def make_cls_accept_cls_annotated_deps(cls: type[T]) -> type[T]: """ Make class `cls` accept class-annotated dependencies, performing following modifications: - Update `__init__` function to set any class-annotat...
529b73cd76adde9868bebec2a91b323c679fcdd0
3,649,595
def getReviewRedirect(entity, params): """Returns the redirect to review the specified entity. """ return '/%s/review/%s' % ( params['url_name'], entity.key().id_or_name())
959ff6d0297ec54248ee725e93a79702512d00d7
3,649,596
def leapfrog_step(state, target_log_prob_fn, kinetic_energy_fn, step_size, rng=None): """Single step of leapfrog. Notes ===== The canonical distribution is related to the energy of the system by p(p, \theta) = 1/Zexp(-H(\theta, p)/T) For now, we assume that the kinetic energy takes the...
78a98c9edaabefd0d6d13b8b83ee080b4a11e941
3,649,597
import requests def get_plugins_json(url: str = "https://repobee.org/plugins.json") -> dict: """Fetch and parse the plugins.json file. Args: url: URL to the plugins.json file. Returns: A dictionary with the contents of the plugins.json file. """ resp = requests.get(url) if res...
f6d795d88d124d8cb68e2dad4d8a354af88525c1
3,649,598
def add_available_prefixes(parent, prefix_list): """ Create fake Prefix objects for all unallocated space within a prefix. """ # Find all unallocated space available_prefixes = IPSet(parent) ^ IPSet([p.prefix for p in prefix_list]) available_prefixes = [Prefix(prefix=p) for p in available_prefi...
1df9f991f33e1a77b81b43de08c5f86f6acc7a20
3,649,599