content
stringlengths
22
815k
id
int64
0
4.91M
def compare_diam(filename, param_list=None): """Change distal dendrite's diameter""" diam_list = param_list if not diam_list: diam_list = [0.5, 1, 1.5, 2] print("diam_list:{}".format(diam_list)) load_file(filename) for diam in diam_list: h("""ldend.diam = {}""".format(diam)) ...
79,400
def get_archive_posts(): """Get post links from codingdose archive.""" base_url = 'https://codingdose.info/archives/' paging_url = base_url + 'page/' ordered_list = [] for page in range(1, get_num_pages()): url = base_url if page < 2 else paging_url + str(page) page = requests.get(ur...
79,401
def normalize(X): """Normalize the dataset""" scaler = MinMaxScaler() scaler.fit(X) return scaler.transform(X)
79,402
def test_get_inflation_rate(test_http_client): """Test get inflation rate.""" resp = test_http_client.get_inflation_rate() assert_valid_response(resp)
79,403
def project_3d_to_2d(points3d, intrinsics): """Projects 3d points, (in the Google format) to pixel location using the intrinsic matrix. The intrinsic matrix must be scaled if the image is scaled. Args: points3d ([list]): List of 3D points in camera frame. intrinsics ([np.array]): Intrin...
79,404
def compute_images2labels(images: List[str], labels: List[str]) -> Dict: """Maps all image paths to a list of labels. Args: images (List[str]): The list of image paths. labels (List[str]): The list of labels. Returns: Dict: The mapping between the image paths and the labels. ""...
79,405
def createsuperusers(): """ Creates all superusers defined in settings.INITIAL_SUPERUSERS. These superusers do not have any circles. They are plain superusers. However you may want to signup yourself and make this new user a super user then. """ from django.contrib.auth import models as auth_mod...
79,406
def similarString(inString, inList): """ check if there is an object that resembles the given string in the list :param inString: string to check for :type inString: string :param inList: list of strings to choose from :type inList: list :return: the string that resembles the input the m...
79,407
def __validate_enabled_entity(request: Request, db_issue: Optional[Issue], entity, entity_id): """ Get entity-id from path and query it in the database. Check if it belongs to the queried issue and if it is disabled. :param request: :param db_issue: :param entity: :param entity_id: :return:...
79,408
def get_custom_report_table(pdb_ids, columns, log=sys.stdout, prefix="dimStructure", check_for_missing=True): """Given a list of PDB IDs and a list of attribute identifiers, returns a Python list of lists for the IDs and attributes.""" assert (len(columns) > 0) if (len(pdb_ids) == 0) : return [] url_base ...
79,409
def _has_constant_term(p, x): """ Check if ``p`` has a constant term in ``x`` Examples ======== >>> from sympy.polys.domains import QQ >>> from sympy.polys.rings import ring >>> from sympy.polys.ring_series import _has_constant_term >>> R, x = ring('x', QQ) >>> p = x**2 ...
79,410
def fattoriale_gen(): """Sucessione dei fattoriali dei numeri interi a partire da 0 Returns ------- fat_gen : generator Generatore dei fattoriali dei numeri interi a partire da 0. """ # TODO implementare questa funzione # ============== YOUR CODE HERE ============== raise NotIm...
79,411
def values_to_percent_growth(values): """ Turn a series of values into a series giving the growth from one period to the next :param values: a list of floats :return: another list, of length one less than values >>> rate = 0.05 >>> n_periods = 5 >>> initial_investment = 100 >>> values =...
79,412
def handle_testing_state(state, session, guest, round_num): """TODO: Fix round_num""" if state not in {State.TESTING, State.WAITING}: raise ValueError("Unexpected to handle state {}".format(state)) if round_num is None: round_num = 0 round_num = int(round_num) if state == State.TES...
79,413
def test_scoreboard_limit_user(): """cli.darshan_scoreboard --limit-user """ argv = ['--json', '--limit-user', INDEXDB_USER, INDEXDB] print("Executing: %s" % " ".join(argv)) output_str = tokiotest.run_bin(tokio.cli.darshan_scoreboard, argv) decoded_result = json.loads(output_str) print("Resu...
79,414
def test_get_one_project(build_worktree, args): """ Test Get One Project """ build_worktree.create_project("hello") world = build_worktree.create_project("world") args.projects = ["world"] assert qibuild.parsers.get_one_build_project(build_worktree, args) == world with qisys.sh.change_cwd(world....
79,415
def get_listing_by_url(conn: "SQLite connection", url: Dict[str, str]): """Collect records by URL Args: conn (sqlite connection): connection to zillow db url (Dict[str,str]): dictionary with key='url' and value=url string """ c = conn.cursor() c.execute( """ SELE...
79,416
def _all(command): # pylint: disable=unused-argument """Runs isort, autoflake, black, pylint, mypy and pytest Arguments: command {[type]} -- [description] """ # If we get to this point all tests listed in 'pre' have passed # unless we have run the task with the --warn flag if not comma...
79,417
def AbsolutePathToModule(file_path: str) -> str: """Determine module name from an absolute path.""" match = re.match(r'.+\.runfiles/phd/(.+)', file_path) if match: # Strip everything up to the root of the project from the path. module = match.group(1) # Strip the .py suffix. module = module[:-len(...
79,418
def sum_counts(fname, R1=False): """Collect the sum of all reads for all samples from a summary count file (e.g. from collect_counts)""" count = 0 with open(fname, 'r') as infh: for line in infh: l = line.split() if R1: if l[2] == "R1": cou...
79,419
def publish(target, test, list_, verbose, build_dir, skip_build): """ Publish the package to PyPI or another target. """ if list_ and target: sys.exit('error: conflicting options') package = project.load_or_exit(expect=PackageModel) if list_: publishers = list(get_publishers(package)) for sco...
79,420
def test_construct_simulation_config(): """ Test that simulation configurations are properly constructed from YAML and JSON """ yaml_str = """ seed: 20203 hours_per_timestep: 8 start_date: "2000-00-00" end_date: "2030-00-00" town: name: "Pizzavill...
79,421
def vappressure(temp): """Approximate vapour pressure over ice. Approximate the vapour pressure over ice at the given temperature. :arg float temp: Temperature in K. :returns: Vapour pressure in Pa. :Examples: >>> vappressure(270.) 470.061877574 """ tau = temp/_TT...
79,422
def parse_tags(tag_list): """ >>> 'tag2' in parse_tags(['tag1=value1', 'tag2=value2']) True """ tags = {} for t in tag_list: k, v = t.split('=') tags[k] = v return tags
79,423
def api_key_is_valid(app, flask_request): """ check the validity of API key Args: app: the flask app flask_request: the flask request Returns: 200 HTTP code if it's valid otherwise 401 error """ if app.config["OWASP_NETTACKER_CONFIG"]["api_access_key"] != get_value(fla...
79,424
def write_review(review, out): """Writes out the fields of a single review in tag/value format.""" out.write('# Review\n\n') write_value('Reviewer', review.reviewer, out) write_value('ReviewDate', review.review_date_iso_format, out) if review.has_comment: write_text_value('ReviewComment', re...
79,425
def resnetv1(num_classes=[1000]): """Encoder for instance discrimination and MoCo""" return resnet50(num_classes=num_classes)
79,426
def radial_distrubtion_pair(p1, p2, bins=100, range=None, weighted=False, dim=None): """ Compute a pair radial distribution function. Returns (counts, bin_edges) Arguments: p1[T,N1,ndim] particle group 1 positions p1[T,N2,ndim] particle group 2 positions bins nu...
79,427
async def create_source_event_stream( schema: GraphQLSchema, document: DocumentNode, root_value: Any = None, context_value: Any = None, variable_values: Dict[str, Any] = None, operation_name: str = None, field_resolver: GraphQLFieldResolver = None, ) -> Union[AsyncIterable[Any], ExecutionRes...
79,428
def call_list_parsers_history(args, log_type): """Calls list parsers history endpoint and pretty prints parser history.""" # Make the request parser_history = make_request(args, get_list_parsers_history_url(args, log_type)) if 'cbnParsers' not in parser_history: print(json.du...
79,429
def relative(src, dest): """ Return a relative path from src to dest. >>> relative("/usr/bin", "/tmp/foo/bar") ../../tmp/foo/bar >>> relative("/usr/bin", "/usr/lib") ../lib >>> relative("/tmp", "/tmp/foo/bar") foo/bar """ import os.path if hasattr(os.path, "relpath"): ...
79,430
def unread_count_for(user): """Returns the number of unread messages for the specified user.""" return InboxMessage.objects.filter(to=user, read=False).count()
79,431
def is_available(): # type: () -> bool """Returns whether visualization is available or not. .. note:: :mod:`~optuna.visualization` module depends on plotly version 4.0.0 or higher. If a supported version of plotly isn't installed in your environment, this function will return :obj...
79,432
def coerce_bool(value): """Coerce a string to a bool, or to None""" clean_value = str(value).strip().lower() if clean_value in ["yes", "1", "true", "t"]: return True elif clean_value in ["no", "n0", "0", "false", "f"]: return False elif clean_value in ["", "na", "n/a", "none"]: ...
79,433
def setup_oath(token_path, client_path): """ Path containing token.pkl and client_secret.json respectively. """ # Set up credentials scopes = ['https://www.googleapis.com/auth/calendar'] # Token generated after first time code is run. if os.path.exists(token_path): with open(token_p...
79,434
def gen_points_GMM(optNK, optCP, optPT, time, numClusters): """Generates points from a scikit-learn GMM object for a fit NK, CP and PT""" GMM = GaussianMixture(n_components=optNK.size, covariance_type="full") precisions = covFactor_to_precisions(optPT) means = tl.cp_to_tensor((None, np.asarray(optCP, dt...
79,435
def expand_mask_targets(masks, mask_class_labels, resolution, num_classes): """Expand masks from shape (#masks, resolution ** 2) to (#masks, #classes * resolution ** 2) to encode class specific mask targets. """ assert masks.shape[0] == mask_class_labels.shape[0] # Target values of -1 are "don't...
79,436
def supervised_loss(R_tgt_src_pred, t_tgt_src_pred, batch, config, alpha=10.0): """This function computes the L1 loss between the predicted and groundtruth translation in addition to the rotation loss (R_pred.T * R) - I. Args: R_tgt_src_pred (torch.tensor): (b,3,3) predicted rotation t_t...
79,437
def read_file_line_by_line(file_name, code='utf-8'): """ async generator to read file in with special delimeter :param file_name: the way to the file :param code: encoding of file (utf-8) :return: generator with all parts of file """ with open(file_name, 'r', encoding=code) as f: whi...
79,438
def smooth_data(indices_, tag_counts_, sigma=20, width=120, size=None): """ #sigma = 20 #width = 120 #epsilon = 0 #some minimum peak height #size, epsilon = data_size, minimum_peak_size """ if size is None: size = max(indices_) lo, hi, normal = normal_function(sigma, width) ...
79,439
def count_consonants(string): """ Function which returns the count of all consonants in the string \"string\" """ consonants = "bcdfghjklmnpqrstvwxz" counter = 0 if string: for ch in string.lower(): if ch in consonants: counter += 1 return counter
79,440
def in6_isaddrTeredo(x): """ Return True if provided address is a Teredo, meaning it is under the /32 conf.teredoPrefix prefix value (by default, 2001::). Otherwise, False is returned. Address must be passed in printable format. """ our = inet_pton(socket.AF_INET6, x)[0:4] teredoPrefix =...
79,441
def get_resized_raster_8chan_image(image_id, band_rgb_th, band_mul_th): """ RGB + multispectral (total: 8 channels) """ im = [] fn = train_image_id_to_path(image_id) with rasterio.open(fn, 'r') as f: values = f.read().astype(np.float32) for chan_i in range(3): min_va...
79,442
def calculateDailyResult_init(): """主函数,供其他python程序进行模块化程序初始化调用""" reload(ADRB) # 创建回测引擎 engine = BacktestingEngine() # 设置引擎的回测模式为K线 engine.setBacktestingMode(engine.BAR_MODE) # 设置产品相关参数 engine.setSlippage(0) # 股指1跳 engine.setRate(0) # 万0.3 engine.setSize(...
79,443
def bonds_getting_formed_or_broken(rsmi, psmi, n_atoms): """ Based on the reaction and product structure, the bonds that are fomed/broken are singled out for contraintment the difference in the afjacency matric tells whether bond has been formed (+1) or bond is broken (-1) """ bond_pairs_ch...
79,444
def test_cube_metadata_extracted_from_info_json(): """Metadata - ['base_uri', 'creator', 'description', 'from_dict', 'issued', 'keywords', 'landing_page', 'license', 'public_contact_point', 'publisher', 'summary', 'themes', 'title', 'uri_safe_identifier', 'validate']""" data = pd.read_csv( get...
79,445
def write_msp(all_preds_in, peprec_in, output_filename='MS2PIP_Predictions', write_mode='wt+', unlog=True, return_stringbuffer=False): """ Write MS2PIP predictions to MSP spectral library file. """ def write(msp_output): if use_tqdm & len(spec_ids) > 100000: spec_ids_iterator = tqdm(spec_ids) else: ...
79,446
async def votes_by_comment( req: Request, res: Response, comment_ID: int, limit: Optional[int] = 20, offset: Optional[int] = 0, sort: Optional[str] = "id:asc", ) -> Optional[List[Dict[str, Any]]]: """Get all votes of comment or some of them using 'offset' and 'limit' Args: use...
79,447
def create_dir(directory: str) -> None: """ Creates a directory path if it does not exists. :param directory: str - full path to the directory to create :return: None """ try: os.makedirs(directory) except FileExistsError: pass
79,448
def test_atomic_conv_initialize(): """Quick test of AtomicConv.""" acm = atomic_conv.AtomicConvModel( n_tasks=1, batch_size=1, layer_sizes=[ 1, ], frag1_num_atoms=5, frag2_num_atoms=5, complex_num_atoms=10) assert acm.complex_num_atoms == 10 assert len(acm.at...
79,449
def retrieve_context_path_routing_constraint_requested_capacity_bandwidth_profile_committed_burst_size_committed_burst_size(uuid): # noqa: E501 """Retrieve committed-burst-size Retrieve operation of resource: committed-burst-size # noqa: E501 :param uuid: ID of uuid :type uuid: str :rtype: Capac...
79,450
def _create_file(my_data, sheet_name): """Create .xlsx file in memory.""" df = pd.DataFrame(my_data[1:], columns=my_data[0], index=None) file = BytesIO() with pd.ExcelWriter(file, date_format='YYYY-MM-DD', mode='w', engine='xlsxwriter') as writer: df.to_excel(writer, sheet_name=sheet_name, na_rep='', index=False)...
79,451
def status(): """ Shows if mlcomp server is already running """ lines = os.popen("ps ef | grep mlcomp").readlines() pids = {} for line in lines: if "mlcomp/configs/supervisord.conf" in line: pids["server"] = line elif "mlcomp-server start-site" in line: pi...
79,452
def get_symbol(parent_node): """Fetches the node tag value for 'printSymbol'""" def traverse(node): while node != Node.TEXT_NODE: if len(node.childNodes) != 0: traverse(node.childNodes[0]) else: return get_name(parent_node) return node.data...
79,453
def compute_point_area(surf, cell_area=None, area_as='one_third'): """Compute point area from its adjacent cells. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. cell_area : str, 1D ndarray or None, optional Array with cell areas. If str, it must be in the cell...
79,454
def writeEnvVars(var1, value1, var2, value2): """ Write environment variables to build shell script or batch file. """ global system_family # Generate shell script on Unix-likes / Mac OS X. if re.match('\*nix|darwin', system_family): f = open('build.sh', 'w') f.write('#!/bin/sh\nexport {0}="{1}"'.format(var1...
79,455
async def get_html(url, link, sem, dict_xpath): """ Функция устанавливает Semaphore, получает response и передает html код функции parser """ headers = {'User-Agent': ua.random} async with sem: try: async with aiohttp.ClientSession() as session: async with session.get...
79,456
def rename_temp_file(video): """ Renames TEMP_FILE to replace video :param video: File to replace """ os.remove(video) os.rename(TEMP_FILE, video)
79,457
def getLogoutlink(): """Return the HTML required to clear and expire the current OAuth2 token.""" from urllib import quote_plus u = '' host = request.headers['Host'] if session and 'u' in session: u = session['u'] elif request.args and 'u' in request.args: u = request.args.get('u') if u: u = q...
79,458
def run_pyscf(molecule, run_scf=True, run_mp2=False, run_cisd=False, run_ccsd=False, run_fci=False, verbose=False): """ This function runs a pyscf calculation. Args: molecule: An instance of the MolecularData or Pys...
79,459
def evaluate(label, model, history, exp_dir='exp'): """Evaluate a labeled model on all test sets and save it.""" print('Evaluating', label) losses = [] accs = [] for name, data in zip(['val', 'test'] + web_genres, [val, test] + web_tests): loss = model.evaluate(*data, verbose=2) loss...
79,460
def soft_contingency_table(resp1, resp2): """Compute the soft contingency table for two responsibility matrices Args: resp1 (numpy array): N x K_1 responsibility matrix - each row is a probability vector for one of the N items belonging to each of K_1 modes resp1 (numpy array): ...
79,461
def is_opt(typ) -> bool: """ Test if the type is `typing.Optional`. >>> is_opt(Optional[int]) True >>> is_opt(Optional) True >>> is_opt(None.__class__) False """ args = type_args(typ) if args: return typing_inspect.is_optional_type(typ) and len(args) == 2 and not is_...
79,462
def filter_remove_large_objs( zarr_grp_name: str, parsed_raw_data_fpath: str, processing_parameters: dict, dark_img: np.ndarray)-> Tuple[Tuple[np.ndarray,np.ndarray],dict]: """Function used to mask large objects (ex. lipofuscin) present in the image Args: zarr_grp_name ...
79,463
def on_builder_inited(app): """ Hooks into Sphinx's ``builder-inited`` event. """ app.cache_db_path = ":memory:" if app.config["uqbar_book_use_cache"]: logger.info(bold("[uqbar-book]"), nonl=True) logger.info(" initializing cache db") app.connection = create_cache_db(app.cach...
79,464
def on_blue(string, *funcs, **additional): """Text background color - blue. (see _combine()).""" return bg_blue(string, *funcs, **additional)
79,465
def allowed_request_lot_filters(lot_filters): """Create a set of (name, value) pairs for all form filters.""" filters = set() def recursive_search(filters): more_filters = set() for f in filters: more_filters.add((f['name'], f['value'])) children = f.get('children')...
79,466
def render_error_response( description: str, status_code: int = status.HTTP_400_BAD_REQUEST, content_type: str = "application/json", ) -> Response: """ Renders an error response in Django. Currently supports HTML or JSON responses. """ resp_data = { "data": {"error": description...
79,467
def predict(self, df=None, *args, **kwargs): """ Predict using the prophet model. Parameters ---------- df: pd.DataFrame with dates for predictions (column ds), and capacity (column cap) if logistic growth. If not provided, predictions are made on the history. """ if not...
79,468
def decode_token(token): """ Decode token but don;t check the signature :param token: :return decoded token: """ return jwt.decode(token, verify=False, algorithms=[__algorithm__])
79,469
def test_ps_s3_notification_push_http_on_master(): """ test pushing http s3 notification on master """ if skip_push_tests: return SkipTest("PubSub push tests don't run in teuthology") hostname = get_ip() zones, _ = init_env(require_ps=False) realm = get_realm() zonegroup = realm.master_...
79,470
def canbus_kvaser_persist_data(queue): """Read data from queue and persist""" total_events = 0 while True: data = queue.get() total_events += 1 r.rpush("extract_queue", data) if total_events % 100 == 0: log.info(f"Processed {total_events} events since starting")
79,471
def FindPosition(point, points): """Determines the position of point in the vector points""" if point < points[0]: return -1 for i in range(len(points) - 1): if point < points[i + 1]: return i return len(points)
79,472
def PARTE_ELSE(): """ PARTE_ELSE : else COMANDO | e """ global current_token, tabela, pilha_tipos if current_token['token'] == 'else': getSimbol() if not COMANDO(): return False else: return True # vazio return True
79,473
def _check_if_StrNotBlank(string): """ check if a sting is blank/empty Parameters ---------- Returns ------- : boolean True if string is not blank/empty False if string is blank/empty """ return bool(string and string.str...
79,474
def footprint_mean(flash_id_key='flash_id', area_key='area'): """ Takes x, y, z flash locations and gets Extent density unique pixels, average all flashes """ while True: events, flash, x,y,z = (yield) # print 'Doing extent density', x_i = np.floor( (x-x0)/dx ).astype('int3...
79,475
def createRectangle(image=None,topLeftPoint=None,bottomRightPoint=None,color=(255,255,255),lineThickness=3,fill=False,fillColor=None): """ Creates a rectangle on an image Arguments: image = 3D Numpy array; image on which the rectangle has to be created topLeftPoint = (x,y); top left poi...
79,476
def confirmedPattern(passW,pat): """ Checks if the password has the right pattern """ if(len(passW)<pat.min_length or len(passW)>pat.max_length): return False if(isStatusChecked(pat.numbers,hasNumber(passW))==False): return False if(isStatusChecked(pat.capital,hasCapitalLetters(p...
79,477
def normal2SD(x,y,z): """Converts a normal vector to a plane (given as x,y,z) to a strike and dip of the plane using the Right-Hand-Rule. Input: x: The x-component of the normal vector y: The y-component of the normal vector z: The z-component of the normal vector Output: ...
79,478
def parse_date_string(s): """Attempt to parse the expression as a simple date string.""" # https://en.wikipedia.org/wiki/ISO_8601 y = r'(\d\d\d\d)' m = r'(\d\d)' d = m # wk = r'W' + d # wd = r'(\d)' # yd = r'(\d\d\d)' # def groups(*strings, sep='-'): # it = (f'({x})' for x i...
79,479
def print_envspec(S): """ Print the environment spectrum S in the output. Only at most a hundred values are printed. If the spectrum has l values and l>100, only every ceil(l/100)th value is printed. """ l = len(S) step = int(np.ceil(l/100)) envspeclist = sorted(S.to_ndarray(), reverse=T...
79,480
def run_query(**kwargs): """ Takes query name, syntax, and iteration count and calls the execute_query function for each iteration. Reports total, iteration, and exec timings, memory usage, and failure status. Kwargs: query(dict)::: name(str): Name of query ...
79,481
def summarize_target_per_regulator(genes, motif_peaks, motif_information, num_workers=None, debug=False, by_chromosome=True, silent=False): """ Process a large dataframe of motif hits into a dataframe with the best hit for each regulator-target pair :param genes: pd.DataFr...
79,482
def append_result(results, result_hash, item): """Append to results, creating an index if needed.""" if result_hash not in results: results[result_hash] = [item] else: results[result_hash].append(item) return results
79,483
def rotateToHome(x, y): """Rotate to the home coordinate frame. Home coordinate frame starts at (0,0) at the start of the runway and ends at (0, 2982 at the end of the runway). Thus, the x-value in the home coordinate frame corresponds to crosstrack error and the y-value corresponds...
79,484
def utc_time(ms): """return UTC format time""" return dt.datetime(1970, 1, 1) + dt.timedelta(milliseconds=ms*100)
79,485
def cli_args(args: Sequence[str]) -> ToxIniFmtNamespace: """Load the tools options. :param args: CLI arguments :return: the parsed options """ parser = ArgumentParser() parser.add_argument( "-s", "--stdout", action="store_true", help="print the formatted text to ...
79,486
def load_requirements(): """Loads requirements yaml from s3 and updates requirements in requirements table along with various other configs""" s3_response = client_s3.get_object(Bucket=requirements_bucket, Key=os.getenv('REQUIREMENTS_FILE_PATH')) requirements_file = yaml.safe_load(s3_response['Body'...
79,487
def add_rebuild(subparsers): """Rebuild Pipeline subcommands.""" rebuild_parser = subparsers.add_parser( 'rebuild', help=runner.rebuild_pipelines.__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) rebuild_parser.set_defaults(func=runner.rebuild_pipelines) rebuild_parser.add_argumen...
79,488
def hidden_frame(func, posargs, kwargs): """this is just an extra method for new thread so """ """we have the same # of extra frames (1) as the main thread""" func(*posargs, **kwargs)
79,489
def FindFirstVolumeMountPoint(volume_name): """Find the first volume mount point which the system recognises. If none is found, raise x_kernel32. Otherwise return the search handle and the volume mount point name. """ volume_mount_point_name = ctypes.create_unicode_buffer(" " * VOLUME_NAME_LENG...
79,490
def uniq(seq): """ the 'set()' way ( use dict when there's no set ) """ return list(set(seq))
79,491
def set_trace(): """Wrapper function to keep the same import x; x.set_trace() interface. We catch all the possible exceptions from pdb and cleanup. """ debugger = Rpdb() try: debugger.set_trace(sys._getframe().f_back) finally: debugger.shutdown()
79,492
def compute_angles(v1: ndarray, v2: ndarray, axis: int = -1) -> ndarray: """ Computes angle cosines between sets of vectors. Parameters ---------- v1 v2 Sets of vectors. axis Dimension to sum over. Returns ------- A numpy array with angle cosines. """ re...
79,493
def decorator(d): """Make function d a decorator: d wraps function fn.""" def _d(fn): return update_wrapper(d(fn), fn) update_wrapper(_d, d) return _d
79,494
def plot_surface(trimesh): """ Plots a surface over a matplotlib Triangulation. Assumes that the height of the surface has been stored in an attribute 'z' on the trimesh object. """ fig,ax = plt.subplots() ax = fig.gca(projection='3d') polycollection = ax.plot_trisurf(trimesh, trimesh....
79,495
def write_to_csv(data, file): """ Data: dictionary """ with open(file, 'wb') as f: w = csv.writer(f) w.writerow(data.keys()) w.writerows(zip(*data.values()))
79,496
def get_prioritized_county_list(): """the scraper prioritizes its work such that counties with less recorded information are addressed before counties with more information. This is accomplished by dividing the counties into quartiles based on an estimate of the amount of information collected for each ...
79,497
def gen_rand_ddf( batch_size: int, image_size: Tuple[int, ...], field_strength: Union[Tuple, List, int, float], low_res_size: Union[Tuple, List], seed: Optional[int] = None, ) -> tf.Tensor: """ Function that generates a random 3D DDF for a batch of data. :param batch_size: total number ...
79,498
def sanitize_codes(codes): """ Sanitize codes by splitting and removing unnecessarsy characters Params: codes (list): target codes Returns: the sanitized codes """ codes = codes.split(';') codes = [sanitize_code(code) for code in codes] return codes
79,499