content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Optional from typing import Type def boolean_op_wrapper( _cls=None, *, and_: Optional[Type[BinaryOp]] = _And, or_: Optional[Type[BinaryOp]] = _Or, not_: Optional[Type[UnaryOp]] = _Not, ): """ Provide the atom class with __and__, __or__ and __not__ dunder methods. :p...
dc1fe474ab41982db9ac6118a8c5e4c856e74c5e
39,600
import tempfile import time import os import subprocess import sys def _evaluate_model_single_file(target_folder, test_file): """ Evaluate a model for a single recording. Parameters ---------- target_folder : string Folder where the model is test_file : string The test file (....
24a624feb74279a328ad596ed4a689aa39b2a89d
39,601
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Modem Caller ID from a config entry.""" device = entry.data[CONF_DEVICE] api = PhoneModem(device) try: await api.initialize(device) except EXCEPTIONS as ex: raise ConfigEntryNotReady(f"Unable to o...
ce5ad077056fea1f7ecaf492811d343548f48b1b
39,602
import array def _expect_array(obj): """Return an ndarray, or raise TypeError.""" if obj in (0, "0"): return array([ZERO]) if obj in (1, "1"): return array([ONE]) if obj in ("x", "X"): return array([LOGICAL]) if obj == "?": return array([ILLOGICAL]) if isinstanc...
caedb628f0812937199f63eaf67871b4e30d0bbb
39,603
from typing import Callable def internal_rescue( container: KindN[_RescuableKind, _FirstType, _SecondType, _ThirdType], function: Callable[ [_SecondType], KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType], ], ) -> KindN[_RescuableKind, _FirstType, _UpdatedType, _ThirdType]: "...
162b11fd5ba310dd7a993d2cae3c8a71aa369387
39,604
import attr def _library_rule_attrs(): """Returns an attribute dictionary for `swift_library`-like rules. The returned dictionary contains the same attributes that are defined by the `swift_library` rule (including the private `_toolchain` attribute that specifies the toolchain dependency). Users who...
bd6a00829a1debba5de2d19a7467eb003362563d
39,605
def connection_stats(): """ Get packet statistics. """ return qmilib.wds_get_packet_statistics()
07af477de5be24c5637f5479a793a1b256c3419b
39,606
def date_after(d): """ Input: an integer d Quickly find out the actual calendar date of some day in the EPIC dataset. Output: the date, d days after 2015-06-13 00:00:00.000 """ t_i = Time("2015-06-13", format='iso', scale='utc') # make a time object t_new_MJD = t_i.mjd + d #...
f2b5fb9a575c3d5311767e526e37c8be67be6542
39,607
import os import logging def load_partial_vars(exe, init_model, main_program): """tbd""" assert os.path.exists(init_model), "[%s] cann't be found." % init_model def existed_params(var): """tbd""" if not isinstance(var, fluid.framework.Parameter): logging.info("%s not existed",...
c8402568266600e22c7a26d4628e1c82388c5a58
39,608
import re def __remove_punctuation(string): """ Remove all the punctuation symbols and characters in a string. :param string: the string where the punctation characters must be removed. :return: a string without punctuation. """ return re.sub("[!@#£$.()/-]", "", string)
bb2015dc040fedb3656099b57b103f7fb9c416b9
39,609
def pad_chunk_columns(chunk): """Given a set of items to be inserted, make sure they all have the same columns by padding columns with None if they are missing.""" columns = set() for record in chunk: columns.update(record.keys()) for record in chunk: for column in columns: ...
2e5d91ad03ad613b55bcaea97fd8c0785eec977f
39,610
def username_check(username: str) -> str: """ Run a loop to check and determine if a username is valid. :param username: The username to check. """ running = True while running: flag1 = True flag2 = True if username_exists(username): print_error(f"'{username...
b717e0c2fcf90fd49aff6abe3fc203710627e260
39,611
def get_next_match( map ): """ This changes the inverse table by removing hits""" todelete = [] retval = None for px,s in map.iteritems(): if len(s) > 1: retval = s.pop(),s.pop() if retval[0][0] == retval[1][0]: s.add( retval[1] ) #print retval, s retval = None co...
a1154773fb466f976c8145787200c6489f800f5f
39,612
import math def coefficient(multiset): """ multinomial coefficient of the multiset """ S = multiset.size_as_nat() return math.factorial(S) / facto(multiset)
7cf88891adaa9b5844ae4f1b5605ebae1e1a5ffc
39,613
def join_contains(): """**Flask POST rule.** Spatial join on two spatial files drived by contains relationship. --- post: summary: Spatial join on two spatial files drived by contains relationship. description: Create a new spatial file on the condition that the geometry of the **other*...
edbd199403a07d33dd26fca12f477dfe3f47bf10
39,614
import os import pickle def read_pickle(text_folder_path, file_name): """ Read a pickled file from a directory. Parameters: text_folder_path (string): path to the directory where the file is located file_name (string): name of file to read. Returns: read_text (string): text read from the...
046dba6305a7b786715d3af89fbda597851ce684
39,615
def parse_request_table(path: str) -> pd.DataFrame: """Return a dict of userid mapped to keywords. Capitalised columns are in the original file. Derived columns are all lower case. """ df = pd.read_excel(path).dropna() df["username"] = df["Link"].str.split("/").str[-1] return df
d8d041d3a60045125b13c909134f2ad61280ff7a
39,616
import joblib def load_model(model_path): """ Loads the model from the path specified. """ return joblib.load(model_path)
116546721d1de9f6a59dfbf8a1246b966dfb8074
39,617
import re def parse_system(system): """ Parse a system string into a pair of projectiles and a beam energy. """ match = re.fullmatch('([A-Z]?[a-z])([A-Z]?[a-z])([0-9]+)', system) return match.group(1, 2), int(match.group(3))
b0b578e48fbd366cd11cc385fa4c9b7a9b9a1b20
39,618
def is_negligible(in_text): """" Checks if text or tail of XML element is either empty string or None""" if in_text is None: return True elif type(in_text) is str: if in_text.strip(chr(160) + ' \t\n\r') == '': return True else: return False else: r...
3e9e5276e0b58518d942fc3e2a16f64223eb4e0d
39,619
from typing import Union def get_MD5(file: Union[BufferedReader, str]) -> str: """ Creates a MD5 hash of a file """ buffered_file: BufferedReader = None if isinstance(file, str): buffered_file = open(file, 'rb') else: buffered_file = file chunk_size = 8192 h = md5() ...
8da321f3cda89d282751637f16f3ab7139d19ce8
39,620
def jsd_distance_0(x_list, data_list): """ :param x: a list or an np.ndarray data: a list or an np.ndarray :return: jsd_list measure distance between numbers """ jsd_list = [] x_list = single_point_list_2_list(x_list) data_list = pa...
0ba7f1f1c46613ed2506133b401fdec0c5f29ae1
39,621
import numpy import math def quaternion_from_matrix(matrix, isprecise=False): """Return quaternion from rotation matrix. If isprecise is True, the input matrix is assumed to be a precise rotation matrix and a faster algorithm is used. """ M = numpy.array(matrix, dtype=numpy.float64, copy=False)[...
56e4c97d1808d79947f26703ae7f6141a3e78490
39,622
def apply_backoff(strategy = None, max_tries = None, max_delay = None, catch_exceptions = None, on_failure = None, on_success = None): """Decorator that applies a backoff strategy to a decorated function/method. :param st...
fe34a6cb760a3e630ca5a2db21bf5ecba99e9882
39,623
def make_a_tweet(Hash, Message, Reduced): """ Generate a valid tweet using the info passed in. """ tweet = Hash + ': ' + Message if Reduced: tweet += '…' return tweet
1d0c3246874f8a6c9b3cb1b1f7cf27040ff1bd1b
39,624
def ldns_pkt_edns_udp_size(*args): """LDNS buffer.""" return _ldns.ldns_pkt_edns_udp_size(*args)
83140c4dad1764a45385aa0850db23037ee6d0f5
39,625
from typing import Mapping def split_some_by_age( files_data: Mapping[str, np.ndarray], metadata ) -> Clients_X_y: """ Split the datum points (X,y) into three sets based on the age of the patients. Like `split_by_age`, except the first two sets are mixed. In effect, yes, this implies that ...
14d1eb283d968ab6b956ffa370d44b35a512d037
39,626
import sys import inspect def _get_size(obj, seen=None): """ Recursively find the actual size of an object, in bytes. Taken as-is (with tweaked function name) from https://github.com/bosswissam/pysize. """ size = sys.getsizeof(obj) if seen is None: seen = set() obj_id = id(obj) ...
8921489a54059c065c3a71682a9955ade7d17358
39,627
import os def search_with_id(student_id): """ Obtain the username for a user with a given Student ID number (if server is tied into WPI network). :param student_id: Student ID number to use in the search :return: The user's network username """ try: username = os.popen('id +' + str(st...
f7792ba2a2c891c22b07988846dd6bd8016676c7
39,628
async def fetch_confirmed_proposals(request, next_id): """Get confirmed proposals for a user, by their next_id.""" log_request(request) head_block = await get_request_block(request) start, limit = get_request_paging_info(request) conn = await create_connection() proposals = await proposals_query...
6df321ab59783c37c868ec8d8b73f5997e1c7334
39,629
def get_first_transcript_name(fasta_file): """Return the first FASTA sequence from the given FASTA file. Keyword arguments: fasta_file -- FASTA format file of the transcriptome """ with open_pysam_file(fname=fasta_file, ftype='fasta') as f: transcript_name = f.references[0] return tran...
547bb3490c996229b6bae71215d5c72621143934
39,630
def export_account_json(request): """Export an account as JSON""" subdomains = [] for subdomain in Subdomain.objects.filter(user=request.user): subdomains.append({'name': subdomain.name, 'ip': subdomain.ip, 'ipv6': subdomain.ipv6, 'updated': subdomain.updated}) return ...
71bf569e97ecf58c92fa9dc5b14278905f18b99e
39,631
def calc_lat(hours_daylight, delta): """ Latitude is estimated from equation (1.6.11) in: Duffie, John A., and William A. Beckman. Solar engineering of thermal processes. New York: Wiley, 1991. :param hours_daylight: daylight hours as calculated by calculate_hours_daylight or calculate_hours_daylig...
cf5182f8a368fac80c456e3f207458e52e7c9698
39,632
def remainder(numbers): """Function for finding the remainder of 2 numbers divided. Parameters ---------- numbers : list List of numbers that the user inputs. Returns ------- result : int Integer that is the remainder of the numbers divided. """ ret...
4c17d717ef52a7958af235e06feff802ed9c3802
39,633
import os def get_logical_test_file_paths(test_file, output_dir): """ Given the full path to logical test file, return all the paths to the expected output and gold result files. This depends on the logical tests main directory having 2 levels of subdirectories eg tdvt/logicaltests/setup/calcs ...
1408c50af3a8290aef3173c8cb7a3ae5724ae19a
39,634
def branin(x): """ A standard 2-dimensional global optimization test function with a long, shallow valley. f(x) = (x2 - 4 * 5.1 (x1 / pi)^2 + 5 x1 / pi - 6)^2 + 10 (1 - (8 pi)^-1 ) cos (x1) + 10 (The general form doesn't specify coefficients.) There is a global minimum at [[-pi, 12.275], [pi, 2.275], [9.4247...
4d1490406311fae82c2f565ecb1ccc9161335f2f
39,635
def connect_to_cloud( account: str, password: str, appkey=DEFAULT_APPKEY, appid=DEFAULT_APP_ID, appname: str = None, hmackey=DEFAULT_HMACKEY, iotkey=DEFAULT_IOTKEY, api_url=DEFAULT_API_SERVER_URL, proxied=DEFAULT_PROXIED, sign_key=DEFAULT_SIGNKEY, ) -> MideaCloud: """Connects...
6a2e66b426e072f24318948b54094cf0995bc6ae
39,636
def get_cfg_value(config, section, option): """Get configuration value.""" try: value = config[section][option] except KeyError: if (section, option) in MULTI_OPTIONS: return [] else: return '' if (section, option) in MULTI_OPTIONS: value = split_m...
330c284cf5c31819c1ae975c48b4b0ec743a543c
39,637
import requests def getItemSpecs(session_id, guid): """Get specs of a certain item :param session_id: token for current user session :param guid: unique id of an item :return: :class:'Response <Response>' object :rtype: requests.Response """ url = base_url + "/items/{guid}?includeEmp...
f94c125fb2074fb5704eea41319edfc68e090be6
39,638
def _calculate_noise_by_substitution(below_thresh_positions: pd.DataFrame, sample_id: str) -> pd.DataFrame: """ Use the below_threhold_positions data frame to calculate noise of each substitution type :param below_thresh_positions: pd.DataFrame :param sample_id: str - sample ID for first column :re...
393403b49de7cb0ce6fc5d1fdf0ae60afcb1a85a
39,639
def get_sorted_fields(doctype, custom_fields): """sort on basis of insert_after""" fields_dict = frappe.get_meta(doctype).get("fields") standard_fields_count = frappe.db.sql("""select count(name) from `tabDocField` where parent=%s""", doctype)[0][0] newlist = [] pending = [d.fieldname for d in fields_dict] m...
c4448af0f1ee3d7838e462777372b97a0d6e84fc
39,640
import os import re def mk_gparams_register_modules_internal(component_src_dirs, path): """ Generate a ``gparams_register_modules.cpp`` file in the directory ``path``. Returns the path to the generated file. This file implements the procedure ``` void gparams_register_mod...
fe0a93a334db59783c04a526200c0278cbd13568
39,641
def staffing_agency_employee_factory(db): """ Fixture to get the factory used to create staffing agency employees. """ return StaffingAgencyEmployeeFactory
8060bde2937485db2e88f808747cedfcc03fb2bf
39,642
def parse_dburi(url:str, uppercase:bool=False) -> dict: """Parse a given URL or URI string and return the component parts relevant for database connectivity. These come in the general UNIX form: engine://[user:pass@]host[:port]/database[?options] """ uri = URI(url) parts = { 'engine': str(uri.scheme),...
e4dc8aa8bd6fb8827decdfa24fee5d4235c0e3b8
39,643
import posixpath def relativize(home_domain, web_root_path, html_file_path, link_attr_value): """ :param home_domain: Domain that originally hosted the file :param web_root_path: Path of the web root on the local filesystem :param html_file_path: Path of html file containing the links we are working on :param li...
750ccf7f3413a596067c591a6b502fa4cfb0efff
39,644
def train_classifier(input_raster, input_training_sample_json, classifier_parameters, segmented_raster=None, segment_attributes="COLOR;MEAN", *, gis=None, future=False, ...
100a0f73a1cd49376a8e9f2bd575af7356231277
39,645
def _get_wanted_channels(wanted_sig_names, record_sig_names, pad=False): """ Given some wanted signal names, and the signal names contained in a record, return the indices of the record channels that intersect. Parameters ---------- wanted_sig_names : list List of desired signal name st...
00812318105f92cc0552fcf58cbe4b0ec53547a2
39,646
import os def get_image_filename(file_name, list_of_image_files): """Compare an ALTO XML file name with a list of image file names and try to find a pair :param file_name: absolute path to an ALTO XML file :param list_of_image_files: list of image file names :type file_name: str :type list_of_ima...
b54fa348183289f0b65a0385a46a92f9e647975c
39,647
def make_cmsweb_prod_request(query_url, data=None, timeout=90, keep_open=True): """ Make a request to https://cmsweb-prod.cern.ch """ return make_request('https://cmsweb-prod.cern.ch:8443', query_url, data, timeout, keep_open)
cda459d3f2b3d9e21b063a0ae0676786fda47802
39,648
def logpdf_multivariate_normal(x:np.ndarray, mean:np.ndarray, cov:np.ndarray): """ Calculate \log p(x|w) = \sum_{j=1}^M \log(\frac{\sqrt{s_j}}{2\pi} 1/cosh(\sqrt{s_j}/2(x_j - b_j))) Input: + x: n*M + mean: M + cov :M * M Output: + n*M """ return(multivariate_normal.logpdf(x, ...
f6133a9ff674aaf33a42ea4e7a05160b425d46ae
39,649
def get_thumbnail_options(file_, thumb_options=None): """ Get all options of thumbnail, including default ones. """ options = thumb_options.copy() if thumb_options else {} if settings.THUMBNAIL_PRESERVE_FORMAT: options.setdefault('format', sorl_backend._get_format(file_)) for key, valu...
551c0e800fec9edee982f1fb69b9f73bc5667e0d
39,650
def subset_sum(numbers: list, target: int, partial=[], results=[]) -> list: """ Determine all combinations of list items that add up to the target :param numbers: A list of values :type numbers: list :param target: The total that the values need to add up to :type target: int :param partial...
120a9604db4f503fe001732ca52059e86ff50a7e
39,651
import os def aug_image(filename: str, df: pd.DataFrame, config, folder: str, augmentations: int, img_ext: str = 'jpg') -> (list, list): """ This function will: 1. load the image based on the filename from the given folder 2. load all given bounding boxes to that image from the given DataFrame ...
02e5af4851c768b7057a6b593fd9f417ad2a30bf
39,652
import functools import logging def oneTimeJob(func): """ Decorator that causes the given scheduled function to run only once. As a bonus, it also logs the subsequent job to be ran. NOTE: This decorator suppresses any returned results by the given function. :param func: function, the function to...
14729dce9b47d957d9da825eabbd07262e2a4a25
39,653
import argparse def get_args(): """get command-line arguments""" parser = argparse.ArgumentParser( description='Argparse Python script', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( 'positional', metavar='DIR', nargs='+', help='DIR') parser.add...
7b0fb5f786705e11915c441af463377fb9ed1789
39,654
def getTimezone(profile): """ Returns the pytz timezone for a given profile. Arguments: profile -- contains information related to the user (e.g., email address) """ try: return timezone(profile['timezone']) except: return None
f9abd83fc3065d9859d20b101e5eaedd0678d6f9
39,655
def ret_int(potential): """Utility function to check the input is an int, including negative.""" try: return int(potential) except: return None
682ab4987e94d7d758be5957b610dc1ee72156a1
39,656
def card_component( title, context, highlight_start, highlight_end, score, url, key=None): """Create a new instance of "my_component". Parameters ---------- title: ... context: ... highlight_start: ... highlight_end: ... score: ... url: ... key: str or None A...
46a2180f1f95fca7f0d507ee13775b3692b4e5c6
39,657
def read_file(file_name): """Read contents of file.""" with open(file_name, encoding='utf8') as file: return file.read().rstrip().lstrip()
cb8e85c076baa97d8f1a5361abe6ab4ee5b9f00c
39,658
def mean_squared(array): """Returns the mean squared value of an array """ # We need to handle both real and complex cases sqr = jnp.conj(array) * array mean_sqr = jnp.mean(sqr) # Make sure that we are down to float data type return jnp.abs(mean_sqr)
0a8eb7b6610a232222b58c59a4d59bbc1f48a10d
39,659
def create_plankton_dataset(start: int, end: int) -> dict: """Function to create dataset for plankton experiment. Uses data from experiments C1 to C4 from [1]. A series of ten chemostat experiments was performed, constituting a total of 1,948 measurement days (corresponding to 5.3 years of measurement) an...
e6e5f679a9bfd56fbe84be5379041a0a389e743f
39,660
def series_quatrot_inverse(x, y, z, q0, q1, q2, q3, rot_name=""): """Given pandas series x-z and quaternion q0-q4, compute reversed rotated vector x_r, y_r, z_r. Arguments: x,y,z -- vector to be rotated q0-q4 -- quaternion entries. The vector is being rotated with the inverse of that quaternion Ke...
326977d1e0612ab04f4278c72cfa11b5dc8dddd3
39,661
def frexp102str(x): """ Convert to mantesa exponent form in txt """ m, exp = frexp10(x) txt = r"%.2f$\times 10^{%d}$" % (m, exp) return txt
d62d0017061c79337a017c4e3da852d1032fd53d
39,662
def post_theme(config, storage_url, parameters, files): """ POST the theme zip file to the provided storage url :param config: context config :param storage_url: the storage url provided by import job response :param parameters: the parameters provided by the import job response :param files: th...
e3f691d0129a7f48765163c990a8089889eddce1
39,663
import pickle def get_data(sequence_length): """ Get all the notes and chords from the midi files in the ./midi_songs directory """ vocab = set() sequence_in = list() sequence_out = list() all_notes = list() for file1 in data_dir.glob("simpl*.txt"): notes = None with open(fil...
840752bce1c8e5274652f85d92f3b034d52f9cfc
39,664
def pipeline_lightcurve(d, l1=0, m1=0, segments=[], scan=-1): """ Makes lightcurve at given (l1, m1) l1, m1 define phase center. if not set, then image max is used. """ if scan == -1: scan = d['scan'] if segments == []: segments = range(d['nsegments']) d = set_pipeline(d['filename'], scan, fil...
eb2a757da802a2af2b4fcde6bbfd44d2ad50fe78
39,665
import numpy def registry_sources(sntype, subclassName=None): """ get a list of sources in the SNCosmo registry that are of the supernova type sntype, and also of the same subclass if subclassName is not None Parameters ---------- sntype: string, mandatory string used to denote a part...
c1ceaab0f597c2779053f695ee00d6c80bcd691e
39,666
import numpy as np from scipy.linalg import pinv def transform_mne_ica2data(sources, ica, idx_zero=None, idx_keep=None): """ performs back-transformation from ICA to Data space using rescaling as used as in MNE-Python sources: shape [n_chan, n_samples] ica: ICA object from MNE-Python ...
83de6a08e03a98894958ba381541706d54c327f1
39,667
def get_fans_or_followers_ids(user_id, crawl_type): """ Get followers or fans :param user_id: user id :param crawl_type: 1 stands for fans,2 stands for follows :return: lists of fans or followers """ # todo check fans and followers the special users,such as writers # todo deal with cond...
09bed6c1fad8c74f3d31c973c081218b0c282a62
39,668
def RGB2HEX(color): """In: RGB color array Out: HEX string""" return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))
7283f0a8a72d83496c93084ab5c514a0184682c7
39,669
def updateBenchmarkInfo(AllInfo, CurInfo, nRepeat, **kwargs): """ Aggregate information about different experiments into one dict. """ for method in CurInfo: tvec = np.asarray([ CurInfo[method][r]['telapsed'] for r in range(nRepeat)]) key = 't_' + method loc = np.flatnonz...
f2a7d1a9f228e2491919abedbc50d4849dcc8701
39,670
from typing import Tuple async def infer_type_tail(engine, tup): """Infer the return type of tail.""" tup_t = await tup['type'] if not isinstance(tup_t, Tuple): raise MyiaTypeError('tail of non-tuple') if not len(tup_t.elements) >= 1: raise MyiaTypeError('tail on empty tuple') retu...
831731b8e8c08dfbe3d62b4a2a01803756cd40e3
39,671
def search() -> dict: """ Parses the user's search. Can be POST or GET method. """ form = forms.SearchForm() if form.validate_on_submit(): query = form.query.data elif flask.request.args.get("query", None) is not None: query = flask.request.args["query"] else: return {} r...
385e8b95bce91f720381c99dffa1368d2033207b
39,672
def getMetrics(predictions, ground): """Given predicted labels and the respective ground truth labels, display some metrics Input: shape [# of samples, NUM_CLASSES] predictions : Model output. Every row has 4 decimal values, with the highest belonging to the predicted class ground : Ground truth...
81e6684606e27397bb3f45e7e0092e09dabb9725
39,673
def tgos(location, **kwargs): """TGOS Provider :param location: Your search location you want geocoded. :param language: (default=taiwan) Use the following: > taiwan > english > chinese :param method: (default=geocode) Use the following: > geocode API Reference ...
a8b3edfcebc47dccb49c09d36c09a566e07aa551
39,674
def read(source_file, *args, **kwargs): """ Read an input file of various formats. Arguments: source_file: The first argument is a structure file of some format. The remaining args and kwargs are passed to the methods called to read the structure. If the structure name con...
e7ed71d5c065ef13fd09153311291982a03ac537
39,675
def snap_flow_mapper(product_set, snap_function, config, mount=None, rebuild=False): """Run a single set of products through the workflow. Inputs ------ product_set : list of N-tuple Something like... [(s1), (s1_2)...] [(s1, s2), (s1_2, s2_2)...] [(s1_old, s1...
b248c07022c30d116a96555ea5897d17f7157097
39,676
import six def _parse_selection(*selection): """ Parser for *selection* strings used in :py:func:`join_root_selection` and :py:func:`join_numexpr_selection`. """ _selection = [] for s in flatten(selection): if isinstance(s, (int, float)): # special case: skip ones ...
689fa575a0d57ca443c1d84c3b45db76da742cc4
39,677
def prompt_download(): """ Ask the user if they want to download the object """ while True: result = raw_input('Download? [y/n]') if result == 'y' or result == 'Y': return True elif result == 'n' or result == 'N': return False else: pri...
71265c22763b0c6efdf8f4c28a87433691bb73a9
39,678
import torch def blk_chol_mtimes(A, B, x, lower = True, transpose = False): """ Evaluate Cx = b, where C is assumed to be a block-bi-diagonal matrix ( where only the first (lower or upper) off-diagonal block is nonzero. Inputs: A - [T x n x n] tensor, where each A[i,:,:] is the ith block dia...
35584bbe7a1486f06980fb65aab4e3cd3cc7269c
39,679
def signed_area(contour): """Return the signed area of a contour. Parameters ---------- contour: sequence of x,y coordinates, required Returns ------- area: :class:`float` Signed area of the given closed contour. Positive if the contour coordinates are in counter-clockwise...
79a60d064fad70afb8902d6d66b980d778215de3
39,680
def payload_too_large(error) -> BaseErrorType: """Payload is too large.""" return BaseRequestException(413, error, request.path), 413
d792e25188f8d8dfd203a21b83ccbbce1a8857bb
39,681
def get_mean_centroids_coords_distances(df): """ Creates a features array. For each address (each row), calculate the \ mean distances between the corresponding centroid coords and the coords \ suggested from different services. Args: df (pandas.DataFrame): Contains data points for which th...
a5fa41fc08e2bad81f2ec9d6e1836a111ad5c91e
39,682
def rmsd(native, p, loops_as_strings, ca_only = False, all_atom=False): """ Prints + Returns RMSD for Full Protein, as well as any loops in loops_as_strings. """ rms = "" if ca_only: rms = CA_rmsd(native, p) print("C-Alpha:") print("%.3f RMSD"%rms) elif all_atom: ...
8627a5406a9271cf21692fa0b5126d7ff460a74d
39,683
import logging import time def _optimize_commodity( physical_network, k, extended_nodes, extended_arcs, current_t, inventory_shape, inf_capacity=9000000, ): """ Returns: cost: Total cost of the optimization for this commodity transport_movements: Arc flows moving f...
35631bb9ba26d5e4447f26bff13c73aa9eb4323c
39,684
def unlinked_objects(self: JSONClassObject) -> dict[str, list[JSONClassObject]]: """Unlinked objects of this jsonclass object. """ return self._unlinked_objects
72a54356829c24d797054aedf3b54210bbb5bcc4
39,685
def ChooseFunction(title): """ Ask the user to select a function Arguments: @param title: title of the dialog box @return: -1 - user refused to select a function otherwise returns the selected function start address """ f = idaapi.choose_func(title, idaapi.BADADDR) return...
301372b59463aa11c8f7944a05ac8352a9be82a8
39,686
def collect_nodes(trees): """ Collect node information(token, left child, right child, label) of trees by starting from lower part of trees and moving to the top Param: ------ trees: list of tree Return: ------ list of tuple, (token, left child token, right child token, label) ...
351b9e976379b4d81c88ff6d6735758ba80995d0
39,687
def conv2d( inputs, filters, training, batchnorm=constants.BN, activation=tf.nn.relu, padding=constants.SAME, data_format='channels_last', kernel_size=3, strides=1, kernel_initializer=None, name=None): """Buils a 2d convolutional layer with batch normalization. Args: ...
964694fc374be8777795119e16de33bd7e1faa2f
39,688
def natr( client, symbol, timeframe="6m", highcol="high", lowcol="low", closecol="close", period=14, ): """This will return a dataframe of normalized average true range for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (str...
88bef923fdf638c2d064c29df48e47c2356db12e
39,689
async def validation_handler(request, exc): """Handle Pydantic validation errors raised by FastAPI.""" error = exc.errors()[0] return JSONResponse( {"output": error["msg"], "level": "error", "keywords": error["loc"]}, status_code=422, )
431ded5caf61adeca61bbb9d4dfbefe3e8c98ac2
39,690
import argparse import os def common_args(*, under_test=False, include_x_modules=False): """Construct default ArgumentParser parent. Args: under_test (Boolean): When true, create an argument parser subclass that raises an exception instead of calling exit. include_x_modules (Boole...
cfd0dd82d9d1431a2c3d35ad57b207ba77ee9bdb
39,691
def tex_cii(tcii, tau_cii, tbg): """ """ return tstar/np.log(1. + tstar*(1. - np.exp(-tau_cii))/(tcii + J(tbg)))
71874e69a740e4b0e3b9ca76b7f560969cab49c4
39,692
import subprocess def call(args, **kwargs): """Execute the command and return its output or raise a ReplayGainError on failure. """ try: return command_output(args, **kwargs) except subprocess.CalledProcessError as e: raise ReplayGainError( "{} exited with status {}".fo...
46be43876d79bed3fd3b4e38db9a2b28b399bee0
39,693
def debug(func): """Decorator for logging debug messages. """ def wrapped(*args, **kws): logger.debug(u'{}: args={}, kws={}'.format( func_name(func), UNICODE_TYPE(args), UNICODE_TYPE(kws) )) f_result = func(*args, **kws) logger.debug(u'{}: ...
3c0282b5c2c6ec3e31a2d0ef32dd0b0516578a9b
39,694
def initDriver(browser): """ Funcion para crear una instancia de un navegador web para realizar las pruebas automaticas usando Selenium :param browser: navegador a usar firefox o chrome (firefox no sirve la captura de logs) :type browser: String :return: driver Selenium """ if browser =...
e24ebac9b76833ffa67acf22991e425e7dce846b
39,695
def search(request): """Handling search request """ if 'q' in request.GET: q = request.GET['q'] # results = SearchItem.objects.all() results = search_request(q) return render(request, 'search/result.html', {'results': results, 'query': q})
4caf6933aeeeca350cb5bc9e181293752b7c47ed
39,696
def nufft1d1(x,c,isign,eps,ms,f,debug=0,spread_debug=0,spread_sort=2,fftw=0,modeord=0,chkbnds=1,upsampfac=2.0): """1D type-1 (aka adjoint) complex nonuniform fast Fourier transform :: nj-1 f(k1) = SUM c[j] exp(+/-i k1 x(j)) for -ms/2 <= k1 <= (ms-1)/2 j=0 Args: x (float[nj]...
8aa893124e86e167c003496571c3e7cdb8482090
39,697
from typing import Any def valid_topic(value: Any) -> str: """Validate that this is a valid topic name/filter.""" value = cv.string(value) try: raw_value = value.encode("utf-8") except UnicodeError as err: raise vol.Invalid("MQTT topic name/filter must be valid UTF-8 string.") from err...
2258474263b6754fe4866e97944051a7dbdb1720
39,698
import typing from typing import Dict from typing import Optional import urllib import re def parse_agent_uri(uri: str) -> typing.Tuple[str, Dict[str, Optional[str]]]: """ Parse an agent uri and return the settings :attr uri: The uri to parse :return: (scheme, config) """ parts = urllib.parse...
15e6615ac7f2b652b9d9a411c8221bbe2c3a0fe4
39,699