content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import sys from bs4 import BeautifulSoup import traceback import os def download_images(content, dump_path): """ download images from content :param content: html content :param dump_path: path to dump updated html :return: """ echo.push_subroutine(sys._getframe().f_code.co_name) echo.clog(f'Start Parsing I...
c48af729f1ffd37887a2a8c990aa4fdff21ff049
38,400
from typing import Optional def original_text_sector( run: Optional[Run] = None, clustered: bool = True, ): """the text sector for each company from the original clustering. If the companies were not included in that the text sector clustering, this will be `None` for each company.""" run = ru...
8a92cc66954d90651bb2562afc84e42131a599d1
38,401
from typing import Union from typing import Dict from typing import List def flatten_errors(error_message: Union[Dict, List, str]) -> str: """Flatten Cerberus' error messages.""" def flatten_dict(error_dict: Dict) -> str: """Return a string version of the dict.""" return ", ".join([f"{key}: {f...
ab6f359cc214a5a1929254e6066fdc6740938f09
38,402
import os import pickle def get_best_estimators(classification): """ Loads the estimators that are pickled in `grid` folder Note that if you want to use different or more estimators, you can fine tune the parameters in `grid_search.py` script and run it again ( may take hours ) """ grid_di...
ac35183c83ce90c0f13c5237634735f08a5d644f
38,403
def get_byuserid(u_id, categories): """Render all gifts created by a user of id u_id. Arguments: u_id (int): the id of the desired user. categories (object): generally passed through the @include_categories decorator, contains all categories in the data...
615d12e32fc30ab18ea9b1010516ec94e8b17815
38,404
def index(request): """ This view redirects user to home if logged in else it redirects user to login page. """ if request.user.is_authenticated: return HttpResponseRedirect('home') return HttpResponseRedirect('login')
f89da15db58f1ae6e4d206086cac36dd3396acb4
38,405
def _classname(class_): """Returns the full name for a class. Has option for overriding some class names to hide internal details. The overrides are stored in the `_class_aliases` dictionaries. """ rawname = "{}.{}".format(class_.__module__, class_.__name__) if rawname in _class_aliases: ...
ca1e7f66646e5e9dfa3b8ddb4749ebf45dc0f17a
38,406
def fracsimplify(numerator, denominator): """ Simplify a fraction. :type numerator: integer :param numerator: The numerator of the fraction to simplify :type denominator: integer :param denominator: The denominator of the fraction to simplify :return: The simplified fraction ...
9f1decc8d9021ea988f6eb28342da8ecc2ceb607
38,407
def polar_adjust_scale(lon, lat, s=1): """Rescale lon, lat by contracting or expanding from the north pole. This is necessary to compensate for the not quite complete coverage of the projection For the test PufferSphere, s=0.833 is a good compensation s sets the scaling factor. """ r = (np.pi/2...
2c294430bc62dfd06ebfcc1d5b5d81d12d08dd8e
38,408
def process_jobs_output(final_df): """ preprocess the dataframe before creating pdf :param final_df: final dataframe :type final_df: pandas.DataFrame :return: processed dataframe """ output_df = final_df.copy() output_df['job_title'] = np.where(output_df['job_title'].str.len() > 30, o...
d833af76ebe05a856c567e47ef7411e116d2cae1
38,409
def save_parts(fig, fpath, grouped_axes=None, dpi=None): """ FIXME: this works in mpl 2.0.0, but not 2.0.2 Args: fig (?): fpath (str): file path string dpi (None): (default = None) Returns: list: subpaths CommandLine: python -m wbia.plottool.draw_func2 sav...
d2499560f32cee3ee0583a50b183ef14343eaeb4
38,410
def _vector2xy(v, pole): """Return stereographic coordinates (X, Y) of 3D unit vectors. (X, Y) is both zero for vectors with z equal to the projection pole. Parameters ---------- v : Vector3d If it's not a unit vector, it will be made into one. pole : int -1 or 1, where -1 (1) ...
c1df4ddd024ffa4d4ba457ece365f015eadfa3f8
38,411
def find_unique_addresses(address_request_json): """ Finds unique addresses in a provided address request json returned from the ReCollect service :param address_request_json: json object returned from ReCollect address request service :return: list of unique addresses """ logger.deb...
f8bb59fce5ba38c64a9040b5ee3f12dff09ec8e5
38,412
def defer_group_class(node: c.SchemaNode, kw: dict) -> t.Type[IGroupModel]: """Colander helper deferred to assign the current group model. :param node: Colander SchemaNode :param kw: Keyword arguments. :return: IGroupModel """ request = kw.get("request") assert request, "To use this widget ...
59c5da9d2f9c0f79125cd1fa26d242f0dc897a63
38,413
async def search_roles_count(conn, search_query): """Get a count of all search fields for roles in one query.""" resource = ( await roles_search_name(search_query) .union(roles_search_description(search_query)) .distinct() .count() .run(conn) ) return resource
ba43e3c38f28bb9bc10ac757e6b5d2c0cabbfbdb
38,414
import math import pathlib import os def train(args, base_model=None, loaders=None, loaders_len=None, is_fold=-1, is_train=True): """ :param args: :return: """ if loaders is None: loaders, loaders_len = load_data(args) print(loaders_len) postfix = '' if is_fold == -1 else '-kf{}...
9758099d3c1624a7c2cb90a5c63cc9707745526a
38,415
def get_db_engine() -> Engine: """ Opens a new database connection if there is none yet for the current application context. """ if not hasattr(g, "dbengine"): engine = create_engine(application.config["SQLALCHEMY_DATABASE_URI"], echo=ENV_LOG_FLAG) engine.connect() g.dbengine...
844bce3fc30bc4a3c77a27934107d20d597ae793
38,416
def get_subset(container, subset_bounds): """Returns a subset of the given list with respect to the list of bounds""" subset = [] for bound in subset_bounds: subset += container[bound[0]: bound[1]] return subset
4932ecba987c4936f9f467f270c6c07fd8681840
38,417
def _encode_decimal128(name, value, dummy0, dummy1): """Encode bson.decimal128.Decimal128.""" return b"\x13" + name + value.bid
f0d72f1fdef51559eb66dd2ac65ba6a43a91bf85
38,418
def buildstamp(p5_connection=None): """ Syntax: srvinfo buildstamp Description: Returns the build time-stamp of the P5 release Return Values: -On Success: The build time-stamp """ method_name = "buildstamp" return exec_nsdchat([module_name, method_name], p5_connection)
8d8c7a8ee6821fea618af2caafc765c0efca1a5d
38,419
def changeoOb(attrname, G, A, i): """change statistic for binary exogenous attribute oOb (outcome attribute related to binary attribute on same node) [*] """ return 0 if G.binattr[attrname][i] == NA_VALUE else G.binattr[attrname][i]
6b97269fe2f1490bff632868c10e03160caaf421
38,420
def is_cli_command(ctx: Context) -> bool: """ Check if command is run from CLI Args: ctx: Click context object Returns: True if run as CLI command, False otherwise """ return ctx.parent.info_name == "model-navigator"
c6121dd742e2c2a3a0c3b4b5863d73d8d0fde658
38,421
import os def IsPlatformSupported(opts): """Checks that this platform and build system are supported. Args: opts: The options parsed from the command line. Returns: True if the platform and build system are supported. """ # Haven't tested the script out on any other platforms yet. supported = ['...
ae115798b435e4be35ecada9528f688020aeb082
38,422
import random def is_prime_mr(n): """ Miller-Rabin primality test. A return value of False means n is certainly not prime. A return value of True means n is very likely a prime. Source: http://rosettacode.org/wiki/Miller-Rabin_primality_test#Python >>> is_prime_mr(2) True >>> is_pri...
48a9ea5f8708b56199cdf36dc0affe5d84c113a9
38,423
import subprocess def call(command, **kwargs): """ 参考subprocess.call Args: command: shell命令 kwargs: 其他参数 """ if "print_command" in kwargs: print_command = kwargs["print_command"] del kwargs["print_command"] else: print_command = IS_PRINT_COMMAND de...
e5f1cb1fe894a0fffbc50a562f2844ef9112a821
38,424
def lat_lon2point(df): """Create shapely point object of latitude and longitude.""" return Point(df['Wikipedia', 'longitude'], df['Wikipedia', 'latitude'])
f430d9532c52eb11ec05f6a2cbddd2d5600c9413
38,425
from typing import OrderedDict def _get_exp_uri(): """Return expected basic result for OpenUri action.""" return OrderedDict( ( ("@type", "OpenUri"), ("name", "Open URL"), ( "targets", [OrderedDict((("os", "default"), ("uri", "http://...
a3e527a52769083fd7adb8cf04a27ebcfc272922
38,426
def save_json(node): """Load tvm object as json string. Parameters ---------- node : Node A TVM Node object to be saved. Returns ------- json_str : str Saved json string. """ return _api_internal._save_json(node)
0c9a2b18d18bf2357a2a539f2941972dd4e810ce
38,427
import re import string def normalize_text(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r"\b(a|an|the)\b", " ", text) def white_space_fix(text): return " ".join(text.split()) def remove_punc(text): exclude = set(string.punc...
d619ed0c963997e90dc57a8fad951a4555b5c304
38,428
def computeBits(image, start, end, newName): """ Compute the bits of an image :param start: start bit :type start: int :param end: end bit :type end: int :param newName: new name for the band :type newName: str :return: A function which single argument is the image and returns a single ...
5a741e4cc8f14fa914b914bb9a237ee2768b1d76
38,429
import getpass def get_html_connector_kwargs_options_from_args(args): """Take a parsed ArgumentParser and return a dict of argument.""" if not args.password: args.password = getpass.getpass( "Please enter the password for {} with login {}:\n".format(args.url, args.login) ) retu...
d96f070363c6db33632974028b6363cbad739537
38,430
def benchmark(problems, algorithms, stop_criterion, runs=10, seeds=None): """A function to perform multiple algorithms on multiple soltions. Note that the problems, algorithms and the stop criterion all need to have the method reset method properly implemented for this function to work properly. The lo...
5ed084bf1e3fb2ba55a579e1ed5a3314721d1559
38,431
def list_huisnummers_adapter(obj, request): """ Adapter for rendering a list of :class:`crabpy.gateway.crab.Huisnummer` to json. """ return { 'id': obj.id, 'status': { 'id': obj.status.id, 'naam': obj.status.naam, 'definitie': obj.status.definitie ...
bcc48d753e5c51581b34d7f5f695ae1f1ae744c1
38,432
def fetch_production(zone_key, session=None, target_datetime=None, logger=None): """ Requests the last known production mix (in MW) of a given country Arguments: zone_key (optional) -- used in case a parser is able to fetch multiple countries session (optional) -- request session passed in orde...
e23234553a0da497415488e3c15e2e62b00cc779
38,433
def generate_vocab_from_token_count(token_count, max_vocab_size=1000000, min_count=0, unk_tk=UNK_TK, start_tk=START_TK, decode_tk=DECODE_TK,...
11b7fb52db85302353ffb5128ee04a2cd6958d1e
38,434
from typing import Optional from typing import Dict def timesketch_list_saved_searches( data: Optional[Text] = '') -> Dict[str, api_search.Search]: """List up all available saved searches. Args: data (str): Not used. Returns: A dict with a list of available saved searches. """ connect() stat...
c575d1c6ef6b66a371c1b3370b9f954fb2688bb5
38,435
import os import sys def codePath(): """Returns path to the program sources""" if not frozen: return os.path.dirname(__file__) return ( os.environ.get('RESOURCEPATH') # pylint: disable=protected-access if frozen == "macosx_app" else sys._MEIPASS)
a959751dcd873debf67d96ae41004406cee2fb99
38,436
def get_coords(gals): """ Takes list of galaxies and looks up their coordinates by name. If no name found: warn, skip, remove galaxy from list Returns: gals: list of galaxies minus those that weren't found start_coord: list of coordinates corresponding to center of g...
904405f70611b4fcc38f2f963f36b9d63dd98e6f
38,437
def yesnoquery(message): """ Displays `message` and waits for user Y/N input. Returns Boolean where true means Y. """ useryn = None while useryn is None: if not isinstance(message, str): raise ValueError("Must pass a valid string to query") useryn =...
87ec3cb01e4a2e52ce1cd900e5446cbab9a05373
38,438
def material(): """ Factory associated with PowerLaw3D. """ return PowerLaw3D()
5340bdd546d9c804a12ac0a9bbf446a4859ce2bb
38,439
def formatExtendedTraceback(exc): """Format a traceback for the given exception as a string. The traceback will include the source line of each frame, as usual, but also the values of local variables in the frames. """ return ''.join(listExtendedTraceback(exc)).rstrip('\n')
567274bd8cfef86e8070c659d470edbc5e793ade
38,440
def _normalize_ad_ts_sid(df, ndays=0, nhours=8, target_tz='utc'): """规范`asof_date`、`timestamp`、`sid` 操作: 股票代码 -> sid(int64) date(date) -> asof_date(timestamp) date(date) + ndays -> timestamp(timestamp) 确保timestamp >= asof_date """ if AD_FIELD_NAME in df.columns: ...
19fa72d33128ba4684c388db6fb1e63062c85c26
38,441
def convertHDF5Mesh(h5Mesh, group='mesh', indices='cell_indices', pos='coordinates', cells='topology', marker='values', marker_default=0, dimension=3, verbose=True, useFenicsIndices=False): """ Converts instance of a hdf5 mesh to a :gimliapi:`GIMLI::Me...
1c901cf43ae8dc507c1d857c4be9553b411c2f62
38,442
def lnLikelihoodGaussian(parameters, values, errors, weights=None): """ Calculates the total log-likelihood of an ensemble of values, with uncertainties, for a Gaussian distribution. INPUTS parameters : model parameters (see below) values : data values errors : data unc...
17d1cdf00a841fae15f9f77616bc4b6c5fdb39ce
38,443
def g(r, r_i, r_c, a, gamma): """ Non-orthogonalized radial functions """ def g_(r, r_i, r_c, a): return (r-r_i)**(2)*(r_c-r)**(a+2)*np.exp(-gamma*(r/r_c)**(1/4)) # return (r-r_i)**(5)*(r_c-r)**(a+2) r_grid = np.arange(r_i, r_c, (r_c-r_i)/1e3) N = np.sqrt(np.sum(g_(r_grid,r_i,r_...
fbfcf68470f0b8198f4697bf1079bd4009c3259d
38,444
def formatProccessingTime(ss, verbose: int = 1, estimate: bool = True, keep_seconds=False): """ Format processing time to string Args: ss: Time in seconds or a string """ if isinstance(ss, (str, bytes)): res = ss else: if ss < 0: res = '-1' elif ss < 60: ...
a2bea60365530169013322f8a767c9da3cc44c31
38,445
def lorenz(xyz, t, sigma, beta, rho): """The most famous of the strange attractors.""" x, y, z = xyz dx = sigma * (y - x) # dt dy = x * (rho - z) - y # dt dz = x * y - beta * z # dt return dx, dy, dz
4241c36b8d4b924289edaa522a49855949208327
38,446
def seq_to_array(seq, k=1, overlap=True): """Converts a DNA sequence into a Numpy vector. If :math:`k>1`, then it creates a vector of the :math:`k`-mers. Args: seq (~skbio.sequence.DNA or str): The sequence to convert. k (int, optional): The :math:`k` value to use. Defaults to 1. ov...
8a236536f85c49c8da217e8fd6b50f5f6051e64c
38,447
import copy def add_classes_to_geojson(geojson, class_map): """Add missing class_names and class_ids from label GeoJSON.""" geojson = copy.deepcopy(geojson) features = geojson['features'] for feature in features: properties = feature.get('properties', {}) if 'class_id' not in properti...
9aadf15fbe64995e7e52b2f6182e76ab722f06b5
38,448
import math def calNewGeoLocationNE(initialPOINT, yNORTH, xEAST): """ This function is used to calculate new GEO Point which is 'y' meters north and 'x' meters east of a Reference point. Knowing the lat/long of reference point and y and x distance , it returns a POINT class object with new location lat/long value...
3116856f253984dc89a6fb10889a1ac24d955072
38,449
def solve_RMits(data, xs, flx, k, slvr_opts, filename=None): """Solve the Ronen Method by non-linear iterations based on CMFD and diffusion.""" # unpack data Db = xs[-1] # retrieve Db which does not change with CMFD ss = xs[1] # check for scattering anisotropy in input xs data lin_anis = False...
e471e9f695de1df6c7d0e6cac9df511af0918150
38,450
def add_quantiles_functions_to_pymc_class(pymc_class): """ add quantiles methods to a pymc class Input: pymc_class <class> """ #turn pymc node into the final wfpt_node def compute_quantiles_stats(self, quantiles=(0.1, 0.3, 0.5, 0.7, 0.9)): """ compute quantiles statistic...
cc6b7234f7e606e9ae9661b8b64008cc5b271412
38,451
from typing import Set from typing import Tuple def cfpq_matrix( graph: MultiDiGraph, cfg: CFG, start_nodes: Set[int] = None, final_nodes: Set[int] = None, start_var: Variable = Variable("S"), ) -> Set[Tuple[int, int]]: """ Context-Free Path Querying based on Matrix Multiplication Par...
647d7110c2bed1403e36cc0208f62849e809cbbb
38,452
from pathlib import Path import errno import argparse def is_file_ro(filename: Path) -> Path: """Verifies file exists and can be open for read-only Args: filename (Path): path/filename to check """ try: with open(filename) as f: f.read() f.close() r...
48082137363ac60b8c6666b0236d5f4314daf47d
38,453
import os def project_create(): """View for an AJAX endpoint that creates a new project""" project = Project(name=request.form["name"]) errors = [] current_user.add_project(project, role=ProjectsUsers.ROLE_ADMIN) project.path = os.path.join(app.config["UPLOAD_DIR"], str(project.id)) project.sa...
9289cfa0294100b9d16ed349484513efe2622bff
38,454
from typing import Optional def filter_reg(reg: IRParam) -> Optional[Register]: """Filters a possible register object. returns None if not a register.""" if isinstance(reg, Dereference) and isinstance(reg.to, Register): return reg.to if isinstance(reg, Register): return reg return None
f39e10d08ba5265496663dd64e849562f9918a09
38,455
def get_init_data(file_name): """ Args: file_name: Returns: camera starting position, imu starting position """ init_file = INIT_PATH + file_name + '.json' init_data = read_json_file(init_file) return init_data['cam_start'], init_data['imu_start']
52e2d7afd3b0667a122c857205db86a29ad048b6
38,456
import re def get_aspect_ratio (video_source_filename): """This returns the aspect ratio of the original video. This is usualy 1.78:1(16/9) or 1.33:1(4/3). This function is very lenient. It basically guesses 16/9 whenever it cannot figure out the aspect ratio. """ cmd = "mplayer '%s' -vo png -...
a71b642f64464f0675a9d3c20b610ccfb55df426
38,457
from typing import Dict from typing import Any from typing import Callable def ot3_remote_everything_commit_id( ot3_default: Dict[str, Any], robot_set_source_type_params: Callable ) -> RuntimeComposeFileModel: """Get OT3 configured for local source and local robot source.""" return robot_set_source_type_p...
9b4511e83d31b2e58c046447ed87569e9721ffba
38,458
from typing import Union import random def pick_typo(next_letter: str) -> Union[str, None]: """Picks a typo according to the next letter to type. This function uses `is_typo()` to determine wether or not there will be a typo. Plausible typos are defined in the `PLAUSIBLE_TYPOS` global variable. ...
a0f310f04d57e97d85afbdcaa6074a71eed324ff
38,459
def _get_tag_by_name(tag_name: str, auth_id: int, db: Session): """ Returns tag data by passing the tag name Args: tag_name (str): Tag Name auth_id (int): User Id db (Session): sqlAlchemy connection object Returns: sql_object : Tag data """ return db.query(TagDB).fi...
47ea0ec8572fdeec0005ffb0e8d132855db09336
38,460
def sshconnect_ex1(ssh: SSH): """ SSH example using :class:`ssh2.SSHConnect` with SSH configuration file (:code:`~/.ssh/config`). """ return ssh.execute("ls -l")
4ee656143e5d8fde85dd4bff264775a09c7f0f56
38,461
def list_org_inner_pub_repos(org_id, username, start=None, limit=None): """ List org inner pub repos, which can be access by all org members. """ try: shared_repos = seafserv_threaded_rpc.list_org_inner_pub_repos(org_id) except SearpcError: shared_repos = [] for repo in shared_r...
df00f7dd9a7c7b05246ad6663eae4697aede4b53
38,462
import sqlite3 def select_special_student(sql_special): """ 特殊sql语句的查询 并将其结果封装为Student类型的列表 :param sql_special: 特殊的sql条件 :return: list(Student) """ if sql_special is None: return None connection = sqlite3.connect(r'sqlite/student_system.db') cursor = connection.cursor() # ...
bacec7fe8628c78d3911bdf20a18c5f2bd7759ef
38,463
def gauss(x, a, b, c): """ generate a Gaussian function Parameters ---------- x : array like x coordinates. a : float amplitude (centeral height). b : float center. c : float sigma. Returns ------- y y = Gaussian(x | a, b, c). ""...
99d14f51d17488dcb216c92754c97303c2b64295
38,464
import re def replace_urls(text, filler='<url>'): """Replaces URLs in text with `f' {filler}'`. Potentially induces duplicate whitespaces. Includes punctuation in websites (which is not really a problem, because URLs on Twitter are rendered as https://t.co/randomnum). The regex doesn't account...
0556120c0b8ab8a888acad550cb4cad24c5961ae
38,465
from typing import Dict from datetime import datetime import urllib import hmac import hashlib import base64 def create_signature_v2( api_key, method, host, path, secret_key, get_params=None ) -> Dict[str, str]: """ 创建签名 :param get_params: dict 使用GET方法时附带的额外参数(urlparams) :retur...
6ff58204372f07085fae99fcce418638b1e8b30c
38,466
def solution(X, A): """Find the earliest time that a frog can jump to position X. In order to reach X, a leaf must be present at every position from 1 to X. Args: X (int): The position that the frog must reach. A (list): A list of integers from 1 to X, where A[k] represents a leaf ...
d1fec5a3ec4c6dc06cd0feab295c90cb4c920ced
38,467
import os import distutils def is_charmcraft_running_in_managed_mode(): """Check if charmcraft is running in a managed environment.""" managed_flag = os.getenv("CHARMCRAFT_MANAGED_MODE", "n") return distutils.util.strtobool(managed_flag) == 1
1be4df2434d904122bd5b49e15101a48adc984a1
38,468
import math def moments_get_orientation(m): """Returns the orientation in radians from moments. Theta is the angle of the principal axis nearest to the X axis and is in the range -pi/4 <= theta <= pi/4. [1] 1. Simon Xinmeng Liao. Image analysis by moments. (1993). """ theta = 0.5 * math.atan...
0b75e86e324dccd5fe2c4332dfeb15d63a417b9b
38,469
def load_sklearn_bc_dataset(): """ Helper to load sklearn dataset into a pandas dataframe Returns: pd.DataFrame: X and y combined """ dataset = load_breast_cancer() df = pd.DataFrame(data=pd.np.c_[dataset['data'], dataset['target']], columns=(dataset['feature_names...
39ac7c63099971fce732f18d6051c0ac3f250a36
38,470
def get_select_form_layout(id, options, label, description): """Creates a select (dropdown) form with provides details Parameters ----------- id: str id of the form options: list options to show label: str label of the select dropdown bar description: str lon...
d019943048679ec0dfb15150d5df26ddd1c2ff21
38,471
def visualise_sampling_grid(X_sampled, gridsize=3): """Show how herding algorithm samples the datapoints Using X_sampled, which is the original design matrix with rows permuted such that X_sampled[i] is the i'th row chosen by the sampling algorithm. This enables calculating X_sampled by arbitrary algor...
efed02bf1f58b1d01d5fe087eb3f1838b606952b
38,472
def serialize_ip_block(block): """ Serialize an IP block to protobuf string. Args: block (ipaddress.ip_network): object to serialize Returns: serialized (bytes): serialized object """ proto = IPBlock( version=_ip_version_int_to_proto(block.version), net_address=b...
9344c35f51d6ecaa7803f9198b8e0451bb78caaf
38,473
def copy_and_add_dataset_source(entity, dataset_label, dataset_type, original_source_location, move=False): """Copies the dataset to the entity location and then adds as Dataset. If the original_source_location is a file object, then it just read()s from the handle and writes to destination. If...
7dfd7b23903e0ae5363047bb7f91f9d055d7c5d8
38,474
def DeWeWriteCAN(nBoardNo, CanFrameList): """Dewe write CAN""" if f_dewe_write_can is not None: n_real_frame_count = c_int() n_frame_count = len(CanFrameList) p_can_frames = (BOARD_CAN_FRAME * n_frame_count)() i = 0 for CanFrame in CanFrameList: p_can_frames[...
bb3eb6ddc28cd43ed9c9a70457626e92496d6a77
38,475
def get_article_case(article, word): """Determines the correct article casing based on the word casing""" return article.capitalize() if word[0].istitle() else article
603810cb60c3719c102afe024cdc0ce474d37bfa
38,476
def calc_DM(seg): """ Computes NON-SIGNED Distance Map of input ground truth image or volume using scipy function. In case seg is 3D volume, it separately computes 2D DM fo each single slice. Args: seg: 2D or 3D binary array to compute the distance map Returns: res: distance map ...
f707db2ca620a62f994f04360c96450fa855d0e3
38,477
def get_valid0(cfg: Config): """ Simple network with all inputs and all outputs used. Configuration: 0 1 / | 2 \ / \ | -1 -2 -3 """ # Create a dummy genome genome = Genome( key=0, num_outputs=cfg.genome.num_outputs, ...
c52c72285ee8b364ecafed330d9348de79a38198
38,478
from typing import List def get_dependents_auto(tensor: tf.Tensor, candidates: List[tf.Tensor]) -> List[tf.Tensor]: """Return the nodes in `candidates` that `tensor` depends on. Args: tensor (): candidates (): """ try: dependent_ops = all_parents(tensor.op) except RuntimeE...
2b1a5143a3c2faf54a7e5bb42093e7fde41d512c
38,479
def gram_matrix(input_tensor): """ Computes the outer-product of the input tensor x. Input: - x: input tensor of shape [H,W,C]. We reshape it to [C (H, W)] Returns: Tensor of shape [C,C] corresponding to the Gram matrix Your code goes here """ channels = int(input_tensor.shape[...
e7db0bcae972331146958b02eac3e0e23fae87cc
38,480
def false_positive_rate(context, positive_class, penalty_loss=defaults.DEFAULT_PENALTY_LOSS, constraint_loss=defaults.DEFAULT_CONSTRAINT_LOSS): """Creates an `Expression` for a multiclass false positive rate. The result of this function repres...
ece9d7d9f40d6b52af1efc1f168186698c3ec94f
38,481
def register_root_routes(app: Flask, static_digest: FlaskStaticDigest): """Register the root routes blueprint.""" def set_static_digest() -> None: g.static_digest = static_digest ROOT_BLP.before_request(set_static_digest) if app.config.get("DEBUG", False): # add cache busting for debu...
168e164f66b42a2e89d4e6f429cd6fc9856f51b0
38,482
def start_proc(proc, body): """Start individual process as specified in startClusterReq command. proc - the process object in the message body - the whole message """ f = proc['file'] (key_based, user, pwd, key_file) = get_cred(f['hostName'], body) with produce_ABClusterHost(f['hostName'], ...
a03662fa2938195fda81232ef1f4cf46c63dd7ab
38,483
from typing import List import re from pathlib import Path def check_missing_pictures(document: Document, args: Args) -> List[Issue]: """Check that all pictures files linked in the document exist.""" issues = [] markdown_picture_re = re.compile(r"\s*\!\[.*\]\((.*)\)") for number, line in enumerate(do...
92d45dc4895dfcb143ec44a7eda3a8189b1f3155
38,484
def _load_mesh(path: str): """Loads mesh data from numpy file. Args: path (str): Path to data file Returns: data (np.ndarray): Scaled data (NHWC) """ with open(path, "rb") as f: mesh = np.einsum("abcde->deabc", sio.loadmat(f)["im"]) flattened_mesh = mesh.reshape((-1,) +...
ae46ff174a4efaf8e3accc601ba1ee6d5bfbb989
38,485
def configure(filename="tuf.interposition.json", parent_repository_directory=None, parent_ssl_certificates_directory=None): """The optional parent_repository_directory parameter is used to specify the containing parent directory of the "repository_directory" specified in a configurati...
3aca6e4b3fb6bdbd8e909b4b686c7871bf7a9115
38,486
import xdg def get_script_folder_name(): """Returns the folder where Enso commands are found. This function is responsible for ensuring that this folder exists: it must not return a path that is not present! It is expected to place this folder in some platform-specific logical location.""" return x...
78ff0b66e4198c15f8f0aa9cfa9428415f57db9f
38,487
def CDLHOMINGPIGEON(equity, start=None, end=None): """Homing Pigeon :return: """ opn = np.array(equity.hp.loc[start:end, 'open'], dtype='f8') high = np.array(equity.hp.loc[start:end, 'high'], dtype='f8') low = np.array(equity.hp.loc[start:end, 'low'], dtype='f8') close = np.array(equity.hp....
26a95084abe3cc418a35db13fd191d8fd544cd04
38,488
import collections def deep_convert_to_plain_dict(an_odict): """ Recursively convert `an_odict` and any of its dictionary subelements from `collections.OrderedDict`:py:class: to plain `dict`:py:class: .. note:: This is naive, in that it will not properly handle dictionaries with recursive obj...
0a463981909153d4beee64fbbf5fad489adf78ac
38,489
def mie(r, eps, sig, m=12, n=6): """Mie pair potential. """ prefactor = (m / (m - n)) * (m / n)**(n / (m - n)) return prefactor * eps * ((sig / r) ** m - (sig / r) ** n)
97e96c73c55c9db61f9efe404b26b368090df0bc
38,490
def dpn_conv1x1(in_channels, out_channels, stride=1): """ 1x1 version of the DPN specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. stride : int or tuple...
65e2d408a330050fb45d0b63cced003b443c18e0
38,491
def _conv2d_legalize(attrs, inputs, arg_types): """Legalizes Conv2D op. Parameters ---------- attrs : tvm.ir.Attrs Attributes of current convolution inputs : list of tvm.relay.Expr The args of the Relay expr to be legalized types : list of types List of input and output ...
912b8f144a0c00ba5fa4985fbfadcc8d13d334a9
38,492
def smooth_good_regions_repeatedly(blob_id, repeated_smoothings=5, spine_order=SPINE_ORDER, spine_window=SPINE_WINDOW, time_order=TIME_ORDER, time_window=TIME_WINDOW, ...
ed16652137854607b3afa224975c3b80c9965fcc
38,493
def mean_filter(dem, kernel_radius): """Applies mean filter (low pass filter) on DEM. Kernel radius is in pixels. Kernel size is 2 * kernel_radius + 1. It uses matrix shifting (roll) instead of convolutional approach (works faster). It returns mean filtered dem as numpy.ndarray (2D numpy array).""" radi...
1bbac4841ab35a38045083cdabd70a5371e97f87
38,494
def _members_geom_lists(relation_val, footprints): """ Add relation members' geoms to lists. Parameters ---------- relation_val : dict members and tags of the relation footprints : dict dictionary of all footprints (including open and closed ways) Returns ------- tu...
a0ccf10ef75c381b5839cf8e17ba304a7488ecda
38,495
import numpy as np def hits_numpy(G,normalized=True): """Return HITS hubs and authorities values for nodes. The HITS algorithm computes two numbers for a node. Authorities estimates the node value based on the incoming links. Hubs estimates the node value based on outgoing links. Parameters ...
b202749cad4550f094f7a5908c4d0e835920acd1
38,496
def InputFunc(): """ InputFunc [This Function is used to take declare input.] Returns: [int]: [windowSize] [int]: [dataBits] [int]: [Timeout] """ dataStr = '1010010011' dataStr = " ".join(dataStr) windowSize = 4 # Makes the input string to a list dataBits = [...
ec9426e20774d093459e752c128a103886b7b514
38,497
def httpResponse(graph, uri): """HTTP response: FAIR metadata in RDF and JSON-LD formats""" accept_header = request.headers.get('Accept') fmt = 'turtle' # default RDF serialization mime_types = { 'text/turtle': 'turtle', 'application/rdf+xml': 'xml', 'application/ld+json': 'json...
b3f9d07d3c7a610a3b09a601e4a988e95488e4c5
38,498
def reaction( func=None, # type: Optional[Callable[[_BO, Action, Phase], None]] priority=None, # type: Optional[int] ): # type: (...) -> Union[CustomReaction, ReactionDecorator] """ Decorates an object's method into a custom reaction. Reaction methods are called automatically when an action pr...
1dab9c52aa3d381e7ad418851b5d75aa5c96af8e
38,499