content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_model_data(n_samples=None, ratio=None): """ Provides train and validation data to train the model. If n_samples and ratio are not None, it returns data according to the ratio between v1 and v2. V1 is data comming from the original distribution of SIRD parameters, and V2 is data comming from ...
540706ca37decbf718fcedeef30beb235e98ded8
3,641,445
def skip(): """ Decorator for marking test function that should not be executed.""" def wrapper(fn): fn.__status__ = "skip" return fn return wrapper
0b966c306515073bfb52427b78c65822ee09a060
3,641,446
def _GetThumbnailType(destination_id): """Returns the thumbnail type for the destination with the id.""" destination_type = _GetDestinationType(destination_id) if destination_type == _DestinationType.HOTSPOT: return _ThumbnailType.PRETTY_EARTH else: return _ThumbnailType.GEOMETRY_OUTLINE
3452044aae2f9660084be46d840747089f271b1b
3,641,448
async def postAsync(text: str, *, url: str = "auto", config: ConfigOptions = ConfigOptions(), timeout: float = 30.0, retries: int = 3): """Alias function for AsyncHaste().post(...)""" return await AsyncHaste().post(text, url=url, config=config, timeout=timeout, retries=retries)
bfa5460ac6f469c123eb1bef6e2430f2251809c9
3,641,449
from typing import OrderedDict def gpu_load_acquisition_csv(acquisition_path, **kwargs): """ Loads acquisition data Returns ------- GPU DataFrame """ chronometer = Chronometer.makeStarted() cols = [ 'loan_id', 'orig_channel', 'seller_name', 'orig_interest_rate', 'orig_upb', 'orig...
fdc2281a6bc31547f60c9c8d8585cdc1d101d88f
3,641,450
def get_flows_src_dst_address_pairs(device, flow_monitor): """ Gets flows under flow_monitor and returns source and destination address pairs Args: device ('obj'): Device to use flow_monitor ('str'): Flow monitor name Raises: N/A Returns: [(...
61ffbe3e0e81acf8c408df7b5ca0f8ff9519f87b
3,641,451
def imthresh(im, thresh): """ Sets pixels in image below threshold value to 0 Args: im (ndarray): image thresh (float): threshold Returns: ndarray: thresholded image """ thresh_im = im.copy() thresh_im[thresh_im < thresh] = 0 return thresh_im
180dc1eba6320c21273e50e4cf7b3f28c786b839
3,641,452
import _winreg def set_serv_parms(service, args): """ Set the service command line parameters in Registry """ uargs = [] for arg in args: uargs.append(unicoder(arg)) try: key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, _SERVICE_KEY + service) _winreg.SetValueEx(key, _SERV...
90eb2ac8ea6e9a11b7ff8c266017fe027503f159
3,641,453
def isRenderNode(): # type: () -> bool """ Returns ------- bool """ return flavor() == 'Render'
b0d5799f755c9c6a72f851ad325b4d8ddf3dec70
3,641,454
def test_clean_data_contains_instance_value(): """ Test values from instances remain when not in data. """ data = {'first_name': 'John'} fields = ['job_title', 'first_name'] class Job(object): job_title = 'swamper' first_name = '' class Swamper(BaseSwamper): def bui...
d2c310cfd760ddea7241ccb469ae7cffdaf373ea
3,641,455
def wrap_application(app: App, wsgi: WSGICallable) -> WSGICallable: """Wrap a given WSGI callable in all active middleware.""" for middleware_instance in reversed(ACTIVE_MIDDLEWARES): wsgi = middleware_instance(app, wsgi) return wsgi
09574d87e241c19cae30c2db29ee1ed4744a0c68
3,641,456
def cal_rpn(imgsize, featuresize, scale, gtboxes): """ Args: imgsize: [h, w] featuresize: the size of each output feature map, e.g. [19, 19] scale: the scale factor of the base anchor to the feature map, e.g. [32, 32] gtboxes: ground truth boxes in the image, shape of [N, 4]. ...
19178b125024d213808a497a005336678589588f
3,641,457
def run(args): """This function is called by a user to recover or reset their primary one-time-password secret. This is used, e.g. if a user has changed their phone, or if they think the secret has been compromised, or if they have lost the secret completely (in which case they will need...
c81e533c7dead3fcda028ef85e566d290a85ec74
3,641,458
import time def adjust_price(iteration, current_price, global_start, last_tx_time): """ Function that decides to lower or increase the price, according to the time of previous transaction and the progress in reaching TARGET in TARGET_TIME. Args: iteration (int) - Number of previous suc...
f27f13e7b4a753d6b912ed1d795383f0d206b2ef
3,641,459
import copy def read_csv_batch(file: str, offset, cnt, **read_csv_params): """ Args: file: offset: cnt: read_csv_params: Returns: """ read_csv_params = copy(read_csv_params) if read_csv_params is None: read_csv_params = {} try: usecols = ...
cc6699db5b9ecae9706d52768c8a1dcd084062ea
3,641,460
def fault_ack_faults_by_dn(cookie, in_dns): """ Auto-generated UCSC XML API Method. """ method = ExternalMethod("FaultAckFaultsByDn") method.cookie = cookie method.in_dns = in_dns xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
532e925b560d02a0ed47d61f9aa721f55fc6b650
3,641,461
from typing import List def provides(name=None, needs: List[str] = None): """A shortcut for defining a factory function that also needs dependencies itself.""" if not needs: needs = [] def decorator(f): decorated = _needs(*needs)(f) set(name or f.__name__, decorated) r...
e28e8d5690b7fa53907864c6d17e199a491ccada
3,641,462
def clip_xyxy_to_image(x1, y1, x2, y2, height, width): """Clip coordinates to an image with the given height and width.""" x1 = np.minimum(width - 1.0, np.maximum(0.0, x1)) y1 = np.minimum(height - 1.0, np.maximum(0.0, y1)) x2 = np.minimum(width - 1.0, np.maximum(0.0, x2)) y2 = np.minimum(height - 1...
cf0fe5269afe2a5cbe94efb3221184f706fcb59d
3,641,463
import re def build_url(urlo, base, end, url_whitespace, url_case): """ Build and return a valid url. Parameters ---------- urlo A ParseResult object returned by urlparse base base_url from config end end_url from config url_wh...
b6fa39062502a7d862b17cd079de3c4cfa3720c4
3,641,464
import re def remove_links(txt: str): """ Remove weblinks from the text """ pattern = r'[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)' txt = re.sub(pattern, " ", txt) txt = re.sub('http|https', " ", txt) return txt
4ccaae84d12ab47e70482d15100ba2e60ef476e8
3,641,466
def timefn(fn): """Times a function and stores the result in LOG variables""" @wraps(fn) def inside(*args, **kwargs): start = timer() result = fn(*args, **kwargs) end = timer() gv.TIME_LOG += f'Fn : {fn.__name__} - {end - start}\n' return result return inside
8dddcd54489d2fb754d9c4de7bc1b084a10840e2
3,641,467
def get_tweet_stream(output_file, twitter_credentials): """ This function is given and returns a "stream" to listen to tweets and store them in output_file To understand how this function works, check it against the code of twitter_streaming in part00_preclass :param output_file: the file where the ret...
71a336b71760ef74e14b6472cb8f2a8510d9acb3
3,641,468
def conv3d_3x3(filters, stride=1, padding=1, kernel_initializer=None, bias_initializer=None, name=None): """3D convolution with padding.""" return keras.Sequential([ layers.ZeroPadding3D(padding), layers.Conv3D(filters, ...
f8035b8be1bf82385c31aa0810e7addd8027b5cd
3,641,469
def get_available_quests(user, num_quests): """Get the quests the user could participate in.""" quests = [] for quest in Quest.objects.exclude(questmember__user=user).order_by('priority'): if quest.can_add_quest(user) and not quest.completed_quest(user): quests.append(quest) ...
d1bdbe96dbd0b7fd5295ec43153249e7b93c7339
3,641,470
def height(): """ Default window height """ return get_default_height()
fab02ec1881d1c2ccda9f59e6a72d2990d815973
3,641,471
def no_adjust_tp_func_nb(c: AdjustTPContext, *args) -> float: """Placeholder function that returns the initial take-profit value.""" return c.curr_stop
6896b72c20c79156c97ba09ba87a1947c7df04d6
3,641,472
def inverse_theoretical_laser_position(y, a, b, c): """ theoretical angular position of the wire in respect to the laser position """ return np.pi - a - np.arccos((b - y) / c)
0ba87442954fd3bc832edec9adc082e1d2448347
3,641,473
def ad_roc(y_true, y_score): """ Compute ROC-curve. """ fpr, tpr, thresholds = sklearn.metrics.roc_curve(y_true, y_score, pos_label=1, drop_intermediate=False) return fpr, tpr, thresholds
db161f7099aab4e1d266ab2b0c8aac0b96076a49
3,641,474
import torch def greedy_decoding(baseline_transformer, src_representations_batch, src_mask, trg_field_processor, max_target_tokens=100): """ Supports batch (decode multiple source sentences) greedy decoding. Decoding could be further optimized to cache old token activations because they can't look ahead ...
dbdf636979f28ea09b261fd3947068d6e4e359ad
3,641,476
def _parse_cell_type(cell_type_arg): """ Convert the cell type representation to the expected JVM CellType object.""" def to_jvm(ct): return _context_call('_parse_cell_type', ct) if isinstance(cell_type_arg, str): return to_jvm(cell_type_arg) elif isinstance(cell_type_arg, CellType): ...
1afa4b2ed28d08ebc3526b8462673e5aa7f8a47f
3,641,477
def Ht(mu, q=None, t=None, pi=None): """ Returns the symmetric Macdonald polynomial using the Haiman, Haglund, and Loehr formula. Note that if both `q` and `t` are specified, then they must have the same parent. REFERENCE: - J. Haglund, M. Haiman, N. Loehr. *A combinatorial formula ...
d3a46458215417db0789d3601163e105c9712c75
3,641,478
def is_generic_alias_of(to_check, type_def): """ :param to_check: the type that is supposed to be a generic alias of ``type_def`` if this function returns ``True``. :param type_def: the type that is supposed to be a generic version of ``to_check`` if this function returns \ ``True``. ...
d09b255e9ff44a65565196dd6643564aea181433
3,641,479
def train_PCA(X,n_dims,model='pca'): """ name: train_PCA Linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. It uses the LAPACK implementation of the full SVD or a randomized truncated SVD by the method of Halko et al. 2009, ...
1909d154d778864c2eba0819e43a2bbcb260edbf
3,641,480
def phedex_url(api=''): """Return Phedex URL for given API name""" return 'https://cmsweb.cern.ch/phedex/datasvc/json/prod/%s' % api
a642cd138d9be4945dcbd924c7b5c9892de36baa
3,641,482
import csv def extract_emails(fname, email='Email Address', outfile="emails_from_mailchimp.txt", nofile=False, nolog=False, sort=True): """ Extract e-mail addresses from a CSV-exported MailChimp list. :param fname: the input .csv file :param email: the header of ...
1b4e5f60eacd4843e1c9ba6a72c866c52b5bd8d9
3,641,483
def continuations(tree, *, syntax, expander, **kw): """[syntax, block] call/cc for Python. This allows saving the control state and then jumping back later (in principle, any time later). Some possible use cases: - Tree traversal (possibly a cartesian product of multiple trees, with the curr...
333494e07462ee554701616c5069fa61c5f46841
3,641,484
def DNA_dynamic_pressure(y, r, h, yunits='kT', dunits='m', opunits='kg/cm^2'): """Estimate peak pynamic overpressure at range r from a burst of yield y using the the Defense Nuclear Agency 1kT standard free airburst overpressure, assuming an ideal surface. Many real-world surfaces are not ideal (most, in the opinio...
ac56c9d72c516658384ac313c64ba7ed1235e0ea
3,641,486
def revcumsum(U): """ Reverse cumulative sum for faster performance. """ return U.flip(dims=[0]).cumsum(dim=0).flip(dims=[0])
da147820073f5be9d00b137e48a28d726516dcd0
3,641,487
def http_trace_parser_hook(request): """ Retrieves the propagation context out of the request. Uses the honeycomb header, with W3C header as fallback. """ honeycomb_header_value = honeycomb.http_trace_parser_hook(request) w3c_header_value = w3c.http_trace_parser_hook(request) if honeycomb_header...
7c97ed82f22357d3867e8a504a30f3a857837bcf
3,641,488
import torch def format_attn(attention_tuples: tuple): """ Input: N tuples (N = layer num) Each tuple item is Tensor of shape Batch x num heads x from x to Output: Tensor of shape layer x from x to (averaged over heads) """ # Combine tuples into large Tensor, then avg return tor...
8d25d081992099835a21cdbefb406f378350f983
3,641,489
def fit_gaussian2d(img, coords, boxsize, plot=False, fwhm_min=1.7, fwhm_max=30, pos_delta_max=1.7): """ Calculate the FWHM of an objected located at the pixel coordinates in the image. The FWHM will be estimated from a cutout with the specified boxsize. Parameters ------...
c3e69f93fdf84c7f895f9cb01adf3e6a0aa3001d
3,641,490
def _ensure_aware(series, tz_local): """Convert naive datetimes to timezone-aware, or return them as-is. Args: tz_local (str, pytz.timezone, dateutil.tz.tzfile): Time zone for time which timestamps will be converted to. If the series already has local timezone info, it is returned as-is. ""...
fbb99be365a47507ae676fc90601d13cfa46832b
3,641,491
def compute_epsilon(steps): """Computes epsilon value for given hyperparameters.""" if FLAGS.noise_multiplier == 0.0: return float('inf') orders = [1 + x / 10. for x in range(1, 100)] + list(range(12, 64)) sampling_probability = FLAGS.batch_size / NB_TRAIN rdp = compute_rdp(q=sampling_probability, ...
8c998fdcafaac3c99a87b4020ae6959e64170d36
3,641,493
def extract_tumblr_posts(client, nb_requests, search_query, before, delta_limit): """Extract Tumblr posts with a given emotion. Parameters: client: Authenticated Tumblr client with the pytumblr package. nb_requests: Number of API request. search_query: Emotion to search for. ...
bff51bcdc945244a47a88d32139749dddf25f0cf
3,641,494
def total_curtailment_expression_rule(mod, g, tmp): """ **Expression Name**: GenVar_Total_Curtailment_MW **Defined Over**: GEN_VAR_OPR_TMPS Available energy that was not delivered There's an adjustment for subhourly reserve provision: 1) if downward reserves are provided, they will be called up...
9a1466dbbbc945b30c1df04dc86a2134b3d0659a
3,641,495
def transpose(m): """Compute the inverse of `m` Args: m (Matrix3): Returns: Matrix3: the inverse """ return Matrix3(m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8])
843a4b9d52f7c15772957b7abe05ef8c32c8370b
3,641,496
def reverse_string(string): """Solution to exercise C-4.16. Write a short recursive Python function that takes a character string s and outputs its reverse. For example, the reverse of "pots&pans" would be "snap&stop". """ n = len(string) def recurse(idx): if idx == 0: ...
6d4472fb9c042939020e8b819b4c9b705afd1e60
3,641,497
def result_to_df(model, data, path: str = None, prediction: str = 'prediction', residual: str = 'residual') -> pd.DataFrame: """Create result data frame. Args: model (Union[NodeModel, StagewiseModel]): Model instance. data (MRData): Data object...
8b089569d628a0f89381240a133b21ae926da7f9
3,641,498
import re def auto(frmt, minV = None, maxV = None): """ Generating regular expressions for integer, real, date and time. :param format: format similar to C printf function (description below) :param min: optional minimum value :param max: optional maximum value :return: regular expression for...
a160b2c49baf875adb0a7949b8ea0e0e92dc936a
3,641,499
def tf_box_3d_diagonal_length(boxes_3d): """Returns the diagonal length of box_3d Args: boxes_3d: An tensor of shape (N x 7) of boxes in box_3d format. Returns: Diagonal of all boxes, a tensor of (N,) shape. """ lengths_sqr = tf.square(boxes_3d[:, 3]) width_sqr = tf.square(box...
acf1788f8e035a3adf96f3b303f6344bcee0a1f1
3,641,500
async def employment_plot(current_city:City): """ Visualize employment information for city - see industry breakdown and employment type ### Query Parameters - city ### Response JSON string to render with react-plotly.js """ city = validate_city(current_city) city_data = CityDa...
4db7f3f0973391c7294be486088a24c6ffa2770a
3,641,501
def get_freesurfer_matrix_ras2vox(): """ Get standard matrix to convert RAS coordinate to voxel index for Freesurfer conformed space volumes. Get matrix to convert RAS coordinate to voxel index for Freesurfer conformed space volumes. See the documentation for get_freesurfer_matrix_vox2ras for background in...
5d5ee8d7bec4f632e494f468f6ebc7ff20cdf85c
3,641,502
def parse_create_table(string): """Parse the create table sql query and return metadata Args: string(sql): SQL string from a SQL Statement Returns: table_data(dict): table_data dictionary for instantiating a table """ # Parse the base table definitions table_data = to_dict(get_...
e82875dfcc3cd052aeecac8c38277c26f0d15e8f
3,641,503
def retrieve_context_connection_connection_by_id(uuid): # noqa: E501 """Retrieve connection by ID Retrieve operation of resource: connection # noqa: E501 :param uuid: ID of uuid :type uuid: str :rtype: Connection """ return 'do some magic!'
4de55de3a799f7c41168fa9072b1a03345dd61de
3,641,504
def read_filenames(path): """ Read all file names from `path` and match them against FILENAME_REGEX. Arguments: - path: path to the directory containing CSV data files. Returns: - list of tuples of every filename and regex match to the CSV filename format in the specified dir...
970b00dc5947426960110fa646c9c1c91114ef9f
3,641,505
def _sp_sleep_for(t: int) -> str: """Return the subprocess cmd for sleeping for `t` seconds.""" return 'python -c "import time; time.sleep({})"'.format(t)
20ac8022a2438ceb62123f534ba5911b7c560502
3,641,506
import re def verify_show_environment(dut, verify_str_list): """ To get show environment. Author: Prudvi Mangadu (prudvi.mangadu@broadcom.com) """ command = "show environment" output = utils.remove_last_line_from_string(st.show(dut, command, skip_tmpl=True)) result = True for item in v...
9334045f2b4ff2e33085398b871ff7a905b995ee
3,641,507
def get_labelset_keys(): """get labelset keys Given DATA_CFG, return slideviewer labelsets Args: none Returns: list: a list of labelset names """ cfg = ConfigSet() label_config = cfg.get_value(path=const.DATA_CFG+'::LABEL_SETS') labelsets = [cfg.get_value(...
824d15b529bccb576c359fb50614ed1e33aa561c
3,641,508
from typing import List def create_instrument_level_pattern(instrument_symbols: List[str]) -> str: """Creates a regular expression pattern to target all the instrument symbols in a list. The function creates a regular expression pattern to target, within a specific DC message, the portion of the message ...
25e1e9cc52b009e8e4fa95f8502e5b10cad29209
3,641,509
def localtime(nist_lookup=0, localtime=DateTime.localtime,utctime=utctime): """ Returns the current local time as DateTime instance. Same notes as for utctime(). """ return localtime(utctime(nist_lookup).gmticks())
312bb973edd62b03d2d251e4d8e215cd00bd470d
3,641,510
from datetime import datetime def device_now(): """Return datetime object constructed from 'now' on device.""" cmd = "adb shell date '+%Y:%m:%d:%H:%M:%S'" lines = u.docmdlines(cmd) line = lines.pop(0) if line is None: u.error("unable to interpret output from '%s'" % cmd) d = line.split(":") try: ...
93e927194390e77fcc7b26cb22db2e5d1debd164
3,641,511
def copy_safe_request(request): """ Copy selected attributes from a request object into a new fake request object. This is needed in places where thread safe pickling of the useful request data is needed. """ meta = { k: request.META[k] for k in HTTP_REQUEST_META_SAFE_COPY if...
a0e2b670732a2d09ac51678059bac80d115b350b
3,641,512
import hashlib def sha256(firmware_filename, firmware_size=None): """Returns the sha256 hash of the firmware""" hasher = hashlib.sha256() # If firmware size is supplied, then we want a sha256 of the firmware with its header if firmware_size is not None: hasher.update(b"\x00" + firmware_size.to...
62fabc35796b9fe21ca2489b317550f93f6774ca
3,641,513
async def async_unload_entry(hass, entry): """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: hass.data[DOMAIN][entry.entry_id].stop() return unload_ok
38460ec92c350cdfcae0094039e834c3344369d8
3,641,514
def is_serial_increased(old, new): """ Return true if serial number was increased using RFC 1982 logic. """ old, new = (int(n) for n in [old, new]) diff = (new - old) % 2**32 return 0 < diff < (2**31 - 1)
44a33a1c7e8caebe3b74284002c7c4be6ac29b40
3,641,515
def svn_relpath_skip_ancestor(parent_relpath, child_relpath): """svn_relpath_skip_ancestor(char const * parent_relpath, char const * child_relpath) -> char const *""" return _core.svn_relpath_skip_ancestor(parent_relpath, child_relpath)
23ca0f2e91f0c69e7b410983603ef98e9dea4c13
3,641,516
def rnn_model(input_dim, units, activation, output_dim=29): """ Build a recurrent network for speech """ # Main acoustic input input_data = Input(name='the_input', shape=(None, input_dim)) # Add recurrent layer simp_rnn = GRU(units, activation=activation, return_sequences=True, implement...
2b0c4614e0e80888db89fcc8e43ef0a6614400cb
3,641,517
def _pad_statistic(arr, pad_width, stat_length, stat_op): """ pads the array with values calculated along the given axis, used in mode: "maximum", "minimum", "mean" """ ndim = arr.ndim shape = arr.shape if stat_length is None: stat_length = _make_stat_length(shape) else: ...
4976615e4d41f48d5063ed9af0719801dbe1f9db
3,641,518
def register_do(mysql, json): """ helper function that registers data objects into MySQL DB @param mysql: a mysql object for MySQL database @param json: metadata that contains information for data source and device """ cnx = mysql.connect() cursor = cnx.cursor() dataSource = json...
bfb8aa83e91955691d1b3a15c73c5e36d5e3b6b8
3,641,519
import decimal def split_amount(amount, splits, places=2): """Return list of ``splits`` amounts where sum of items equals ``amount``. >>> from decimal import Decimal >>> split_amount(Decimal('12'), 1) Decimal('12.00') >>> split_amount(Decimal('12'), 2) [Decimal('6.00'), Decimal('6.00')] ...
8c8a17ed9bbcab194550ea78a9b414f51ca5610d
3,641,520
from datetime import timedelta def shift_compare_date(df, date_field, smaller_eq_than_days=1, compare_with_next=False): """ ATENTION: This Dataframe need to be sorted!!! """ if compare_with_next: s = ( (df[date_field].shift(-1) - df[date_field] ) <= timedelta(days=smaller...
56d4466f61cb6329ec1e365ad74f349d6043dd0a
3,641,521
def format_alleles(variant): """Gets a string representation of the variant's alleles. Args: variant: nucleus.genomics.v1.Variant. Returns: A string ref_bases/alt1,alt2 etc. """ return '{}/{}'.format(variant.reference_bases, ','.join( variant.alternate_bases))
775fe3e112ff0b7e73780600e0621a8695fa5ad0
3,641,522
import numbers def _validate_inputs(input_list, input_names, method_name): """ This method will validate the inputs of other methods. input_list is a list of the inputs passed to a method. input_name is a list of the variable names associated with input_list method_name is the name of the m...
25a72bd99639b4aab23459635fce116e08299bdc
3,641,523
def server_base_url(environ): """ Using information in tiddlyweb.config, construct the base URL of the server, sans the trailing /. """ return '%s%s' % (server_host_url(environ), _server_prefix(environ))
3919c9223039929530d6543c13e39b880c657d4f
3,641,524
def calc_ctrlg_ratio(rpl: sc2reader.resources.Replay, pid: int) -> dict[str, float]: """Calculates the ratio between `ControlGroupEvents` and the union of the `CommandEvents`, `SelectionEvents` and `ControlGroupCommand` sets to quantify the players' level of awareness and use of this ...
74d79128bba3584a4966e0bb8f2ce0e4dfdf402e
3,641,525
import tqdm def draw_normal_surface(pcd, scale, estimation_params=None): """Draw and return a mesh of arrows of normal vectors for each point in the given cloud Parameters ---------- pcd : o3d.geometry.PointCloud Input point cloud scale : float Scale of the default arrow wh...
cb54f2a84febe82b03806b09af0a8c99fecc0669
3,641,528
def texture_from_clusters(clusters): """ Compute the GLCM texture properties from image clusters. :param clusters: clusters of pixels representing sections of the image :returns: DataFrame -- of texture features for every cluster. """ thetas = np.arange(0, np.pi, np.pi/8) props = ['contrast', ...
353aa3bbc1fec765fd01e201bd769e00bbf8a1fa
3,641,529
def parse_dict(input_data): """Return a rules dict of the format: { 'light red': [(1, 'bright white'), (2, 'muted yellow')], 'dark orange': [(3, bright white), (4, muted yellow)], 'faded blue': [(0, 'bags')] } """ bags = dict() for line in input_data.split('\n'): outer, ...
a1aad66a16e4754c35c9b3518d5641096e393530
3,641,530
def distance_without_normalise(bin_image): """ Takes a binary image and returns a distance transform version of it. """ res = np.zeros_like(bin_image) for j in range(1, bin_image.max() + 1): one_cell = np.zeros_like(bin_image) one_cell[bin_image == j] = 1 one_cell = distance_...
ed4cf85498a74e2f7d030daefceebf66e460e0fd
3,641,532
def list_inventory(): """ Returns all of the Inventory """ app.logger.info('Request for inventory list') inventory = [] category = request.args.get('category') name = request.args.get('name') condition = request.args.get('condition') count = request.args.get('count') available = request....
381de71a10d1626f44710643cd837523e9a930ed
3,641,533
def is_instance_method(obj): """Checks if an object is a bound method on an instance.""" if not isinstance(obj, MethodType): return False # Not a method elif obj.__self__ is None: return False # Method is not bound elif ( issubclass(obj.__self__.__class__, type) or hasa...
82050391193388cdb6d9466442774e6b0fa6878c
3,641,535
from typing import List from typing import Dict def _clean_empty_and_duplicate_authors_from_grobid_parse(authors: List[Dict]) -> List[Dict]: """ Within affiliation, `location` is a dict with fields <settlement>, <region>, <country>, <postCode>, etc. Too much hassle, so just take the first one that's not e...
5a02b877ee074270c544c7dbb06dd1ceab487e79
3,641,536
def get_distutils_display_options(): """ Returns a set of all the distutils display options in their long and short forms. These are the setup.py arguments such as --name or --version which print the project's metadata and then exit. Returns ------- opts : set The long and short form d...
86e87f22ea97db4a2642ef578999ad1f0cd67a66
3,641,537
def get_followers(api, user_id): """Returns list of followers""" followers = [] next_max_id = '' while next_max_id is not None: _ = api.getUserFollowers(user_id, maxid=next_max_id) followers.extend(api.LastJson.get('users', [])) next_max_id = api.LastJson.get('next_max_id', '') ...
debfb11fe0b8b22232b82e9a8ea360a4d2a8cdc1
3,641,538
def map(v, ds, de, ts, te): """\ Map the value v, in range [ds, de] to the corresponding value in range [ts, te] """ d1 = de - ds d2 = te - ts v2 = v - ds r = v2 / d1 return ts + d2 * r
2c2ba49b2acc283ca25b07c10b7ad717ad6a280d
3,641,539
def get_Q_body(hs_type, Theta_SW_hs): """温水暖房用熱源機の筐体放熱損失 (2) Args: hs_type(str): 温水暖房用熱源機の種類 Theta_SW_hs(ndarray): 温水暖房用熱源機の往き温水温度 Returns: ndarray: 温水暖房用熱源機の筐体放熱損失 """ if hs_type in ['石油従来型暖房機', '石油従来型温水暖房機', '石油従来型給湯温水暖房機', '不明']: # (2a) return [234 * 3600 * 10...
60e35a31d9c9b2f5d77d3d6f1518b7a20484fad2
3,641,540
def softmax(inputs): """ Calculate the softmax for the give inputs (array) :param inputs: :return: """ return np.exp(inputs) / float(sum(np.exp(inputs)))
eb8e215e24fbc30e08e986d9b9498973a866cb9b
3,641,541
def _get_turn_angle(start_angle, target_angle): """ Difference in angle in the range -180 to +180 (where negative is counter clockwise) Parameters ---------- start_angle, target_angle : float Returns ------- float difference in angle. """ return _map_to_pm180(target_ang...
7f41482ec69c4d3c4c4b3e1afb674ad46e7d607b
3,641,543
import ctypes def load(fname): """Load symbol from a JSON file. You can also use pickle to do the job if you only work on python. The advantage of load/save is the file is language agnostic. This means the file saved using save can be loaded by other language binding of mxnet. You also get the be...
bbeb4f5eb63a5ad656814d0ded27d7edbd9936d8
3,641,544
def filter_pairs(pairs): """returns pairs of with filter_pair()==True""" return [pair for pair in pairs if filter_pair(pair)]
ce65a6ec84ea8b637771d75a5334af7d90bafa15
3,641,545
def merge(list_geo, npts=5): """ merge a list of cad_geometries and update internal/external faces and connectivities Args: list_geo: a list of cad_geometries Returns: a cad_geometries """ geo_f = list_geo[0] for geo in list_geo[1:]: geo_f = geo_f.merge(geo, npts=np...
70db1b52be8ae70d21f689c8f12e051d9c41cd64
3,641,546
from typing import Union from typing import Sequence from typing import Dict import warnings from pathlib import Path import tqdm import logging def prepare_commonvoice( corpus_dir: Pathlike, output_dir: Pathlike, languages: Union[str, Sequence[str]] = "auto", splits: Union[str, Sequence[str]] = COMMO...
1f2be866e9003224588a6e2cd4a29500854e9fb9
3,641,548
def plot_array_trans(pdata,a,copy=False): """ Warning!!! ---------- Latest Information: 22/05/2012 this is deprecated and plot_array_transg is used instead. Purpose: -------- Transform array according to speficication in list a. return a copy if copy is True. Example: -------- ...
0b885fba59fa34f567df5f6891ecdbe46d8a8be9
3,641,549
def process_generate_api_token_data(post_data): """ This expects the post_data to contain an array called ``user_to_form``. Each item in this array is of the form: .. code-block:: python '<UserID>.<form_prefix>' (i.e. '1.form-0') Each form then may add two form data key-value pairs: ...
8da8c2566621bdc8710091daf604a292a30c602a
3,641,550
from bpy import context as C from bpy import data as D def add_vcolor(hemis, mesh=None, name='color'): """Seems like `hemis` is color you wish to apply to currently selected mesh.""" if mesh is None: mesh = C.scene.objects.active.data elif isinstance(mesh, str): mesh = D.meshes[mesh] ...
9199411ab0265c8e16e4a8bb2dfa45f9550d5d1a
3,641,551
import itertools import pandas as pd def gridSeach(model, parameters, features, response, train, test): """ This function performs a grid search over the parameter space. It is simplistic and only allows certain range of values. If there is a parameter in the models that needs to be a list it has to ...
69d406cb16312d2777e7aa0562f77c77b20c44f7
3,641,552
def cvt_lambdef(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base: """lambdef: 'lambda' [varargslist] ':' test""" assert ctx.is_REF, [node] name = xcast(ast_cooked.NameBindsNode, cvt(node.children[0], ctx.to_BINDING())) ctx_func = new_ctx_from(ctx) if len(node.children) == 4: parameters = xcas...
42ee22a02c2d003afc808bc3e28f18a57e3153fe
3,641,553
import re def ischapter_name(text_str): """判断是否是章节名""" if re.match(r'^第(.{1,9})([章节回卷集部篇])(\s*)(.*)', text_str): return True else: return False
c89a34408def2c2f9026045925212c2dde88a41d
3,641,554
def calc_mean_onbit_density(bitsets, number_of_bits): """Calculate the mean density of bits that are on in bitsets collection. Args: bitsets (list[pyroaring.BitMap]): List of fingerprints number_of_bits: Number of bits for all fingerprints Returns: float: Mean on bit density "...
4d68ff5c280708d930d8e1525753804f831fc9da
3,641,555
from typing import List from typing import Dict from typing import Any from typing import Optional def get_parameters(path: str) -> List[Dict[str, Any]]: """ Retrieve parameters from AWS SSM Parameter Store. Decrypts any encrypted parameters. Relies on the appropriate environment variables to authenticat...
0905e9e707dfa45b9dab8137676fac14e496e594
3,641,557