content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
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 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
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 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
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
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
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
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
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
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
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
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
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
def isready() -> bool: """Is the embedded R ready for use.""" INITIALIZED = RPY_R_Status.INITIALIZED return bool( rpy2_embeddedR_isinitialized == INITIALIZED.value )
ce9bc69c897004f135297331c33101e30e71dca7
3,649,600
from typing import Optional from typing import Dict from typing import Any from typing import Tuple import types def create_compressed_model(model: tf.keras.Model, config: NNCFConfig, compression_state: Optional[Dict[str, Any]] = None) \ -> Tuple[Compres...
42ffc9c9426ce8b95db05e042fa2d51098fc544f
3,649,602
def load_misc_config(): """Load misc configuration. Returns: Misc object for misc config. """ return Misc(config.load_config('misc.yaml'))
b1eb2e8cc3e836b846d292c03bd28c4449d80805
3,649,603
def filter_activations_remove_neurons(X, neurons_to_remove): """ Filter activations so that they do not contain specific neurons. .. note:: The returned value is a view, so modifying it will modify the original matrix. Parameters ---------- X : numpy.ndarray Numpy Matri...
711a858f8d28e5d0909991d85538a24bf063c523
3,649,604
def adaptive_threshold(im, block_size, constant, mode=cv2.THRESH_BINARY): """ Performs an adaptive threshold on an image Uses cv2.ADAPTIVE_THRESH_GAUSSIAN_C: threshold value is the weighted sum of neighbourhood values where weights are a gaussian window. Uses cv2.THRESH_BINARY: ...
c237a0bb05dc8a43495f60ef9d8157c4b9c4bf1f
3,649,605
def get_loss(stochastic, variance_regularizer): """Get appropriate loss function for training. Parameters ---------- stochastic : bool determines if policy to be learned is deterministic or stochastic variance_regularizer : float regularization hyperparameter to penalize high varianc...
e78d47c31a7762bcb091ea1a314348c27f2174b7
3,649,606
import copy def simul_growth_ho_amir(nbstart, run_time, params, name): """Simulate the Ho and Amir model (Front. in Microbiol. 2015) with inter-initiation per origin adder and timer from initiation to division Parameters ---------- nbstart : int number of cells to simulate run_ti...
fa4d35cfd26dbcb08217b3ffee6cf4e3e7431a08
3,649,607
def variable_id(variable): """Return variable identification for .dot file""" if isinstance(variable, FileAccess): return "a_{}".format(variable.id) act_id = variable.activation_id act_id = "global" if act_id == -1 else act_id return "v_{}_{}".format(act_id, variable.id)
b68fd9d6b08a537768dc82b7925f0cb6f383428e
3,649,608
def node_set_power_state(request, node_id, state, soft=False): """Set power state for a given node. :param request: HTTP request. :param node_id: The UUID or name of the node. :param state: the power state to set ['on', 'off', 'reboot']. :param soft: flag for graceful power 'off' or reboot :ret...
e94a13f4a797d31bd0eae24803a782b049ea44dc
3,649,609
import sympy def __sympyToC_Grad(exprs: list, doOpts: bool = False) -> str: """ creates C code from a list of sympy functions (somewhat optimized). source: https://stackoverflow.com/questions/22665990/optimize-code-generated-by-sympy and modified """ tmpsyms = sympy.numbered_symbols("tmp") if do...
33a95d99b19458ac7b8dd8d8e4272485b0f5f206
3,649,610
def index(): """User friendly index page at the root of the server guides the user to the reportss """ return render_template('index.html')
0e810716e0bbfae98736bc13f458636eb33dc87d
3,649,612
def read_lookup(infile): """ ----------------------------------------------------------------------------- Read data from a lookup database. Inputs: infile [string] Input file containing the lookup data base. Outputs: [tuple] each element of the tuple is a numpy array. The elements in ...
a86a2e8da2580e66656f8328488941c402383c60
3,649,613
import json def event_detail(request, id): """ Return a JSON dict mapping for event given id """ event = get_object_or_404(Event, pk=id) event_dict = { "success": 1, "result": [{ "id": event.id, "title": event.title, "description": event.description,...
4b4083a81d5de90e9156f05d9f7b0375981a42d0
3,649,615
import logging def prepare_state(qubits: list[cirq.Qid], x: int) -> list[cirq.Gate]: """Prepare qubits into an initial state. Args: qubits: The qubits to prepare. x: The initial state of the qubits. Must be non-negative. Returns: A list of gates to prepare the qubits. Raises...
f11a4ddd83a6e2d1d7348c8ef3b5693a26e3e26d
3,649,616
def manage(id): """Manage room request.""" room_request = RoomRequest.query.get(id) if room_request is None: return abort(404) return render_template('room_request/manage.html', room_request=room_request)
5a565342adbe53a647cb622e4688d1c26d88078d
3,649,617
def ger(self, y): """Computer an outer product between two vectors""" assert self.dim() == 1 and y.dim() == 1, "Outer product must be on 1D tensors" return self.view((-1, 1)).matmul(y.view((1, -1)))
003dda3dd678fdcf35f63f80c064586320c97d23
3,649,618
def load_data(database_filepath): """ Input: 1. database_filepath: the path of cleaned datasets Output: 1. X: all messages 2. y: category columns generated by cleaning process 3. category_names: category columns' names Process: 1. Read-in the datafrmae 2. ...
15ec78cfac2dfde9294061432514001b21967b93
3,649,619