content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from time import time def vectorize_timing(n_targets): """ Calculate the rise time of ``n_targets`` targets, return the run time in seconds. """ vega_coord = SkyCoord(279.23473479*u.degree, 38.78368896*u.degree) vega = FixedTarget(name="Vega", coord=vega_coord) target_list = n_targets*[veg...
287f723d66efedc9eaa874e3b1db9d6724598c10
5,348
import json def get_game(name, all=False): """ Get the game information for a particular game. For response object structure, see: https://dev.twitch.tv/docs/v5/reference/search/#search-games May throw exceptions on network/Twitch error. """ search_opts = { 'query': name, 'type': 'suggest', 'live': 'fa...
0946516ca7062087d0dc01daa89b328a26367145
5,349
def compute_correlation_prob_class_target(candidates_per_query_target): """This function computes the overall correlation between the probability of being in the positive class and the value of the target column """ probs_per_query_target = [] gains_per_query_target = [] for key in candidates_per_query_tar...
e0412cfa3940149d88c75f680aab55dece9b36a2
5,350
def get(sql: str): """ execute select SQL and return unique result. select count(1) form meters or select lass(ts) from meters where tag = 'xxx' :return: only value """ result = _query(sql) try: value = result.next() except StopIteration: return None ...
10b03b64c0a18b4cd5a3c83e6d101d05566b251c
5,351
def is_fully_defined(x): """Returns True iff `x` is fully defined in every dimension. For more details, see `help(tf.TensorShape.is_fully_defined)`. Args: x: object representing a shape; convertible to `tf.TensorShape`. Returns: is_fully_defined: `bool` indicating that the shape is fully known. """...
d3d419864fb9d6168adce54afae84f089c9a680c
5,353
def make_shell_context(): """ Creates a python REPL with several default imports in the context of the current_app :return: """ return dict(current_app=current_app)
8db290ccfa51681ac63e8e5d88b29c4e82176f36
5,354
def recommend_hybrid_user( df, model, interactions, user_id, user_dict, item_dict, topn, new_only=True, threshold=3, show=True): """Function to produce user recommendations. Hybrid version of recommend_known_user Args: mo...
f6f1bb5486dcd3a7848ca006998587a8efce4939
5,355
def i(mu_i, mu_ij, N) : """Calcule le tableau I[i, j]""" return [[I_ij(i, j, mu_i, mu_ij, N) for j in range(0, N)] for i in range(0, N)]
518609bbe91088d94267515ccd07b3fa16525d4f
5,356
import dateutil def format_datetime(this, date, date_format=None): """Convert datetime to a required format.""" date = dateutil.parser.isoparse(date) if date_format is None: date_format = "%d-%m-%Y" return date.strftime(date_format)
0311eb918540dbb0c5751244b89de220073b9dcd
5,357
import numpy def _estimate_melting_levels(latitudes_deg, valid_time_unix_sec): """Estimates melting level at each point. This estimate is based on linear regression with respect to latitude. There is one set of regression coefficients for each month. :param latitudes_deg: numpy array of latitudes (...
d72ac1cf0c23eadb49fc15e55c2a71e273120500
5,358
def edit_municipality(self, request, form): """ Edit a municipality. """ layout = EditMunicipalityLayout(self, request) if form.submitted(request): form.update_model(self) request.message(_("Municipality modified."), 'success') return redirect(layout.success_url) if not form.e...
4d233f97cbc7672b38348eb982cecc68f88ade17
5,359
import copy def operate_monitor(params): """ different apps has different required params""" ret_obj = copy.deepcopy(RET_OBJ) group_id = params.get("group_id", type=int, default=None) app_name = params.get("app_name") operate = "update" if key_exist(group_id, app_name) else "insert" valid_ke...
8d78d61dc44acf2fdcc85a8e3cd4d6fd68c47bf6
5,361
def construct_rgba_vector(img, n_alpha=0): """ Construct RGBA vector to be used to color faces of pcolormesh This funciton was taken from Flamingo. ---------- Args: img [Mandatory (np.ndarray)]: NxMx3 RGB image matrix n_alpha [Mandatory (float)]: Number of border pixels ...
028275930ad4d2a3b98ce32e48021da8ff1e6c43
5,362
def nice(val): """Make sure this value is nice""" if pd.isna(val): return None return val
a2d0c3c64c7c2e01d66d171902e85a3d0056cc73
5,363
import logging import requests import json def retrieve_tree(issue_id): """Retrieve a tree of issues from Redmine, starting at `issue_id`.""" logging.info(f" Retrieving issue #{issue_id} ...") params = { 'issue_id': issue_id } response = requests.get(ISSUES_ENDPOINT, params=params, header...
928d2f3d68e5b9033a062d5e24d3f34f74781357
5,364
from typing import Sequence from typing import Dict def cmdline_args(argv: Sequence[str], options: Sequence[Option], *, process: callable = None, error: callable = None, results: dict = None) -> (Dict, Sequence[str]): """ Take an array of command line args, process them :param argv: argum...
c9c78d5a6b5fb6147a8b392647ec9a7e4abc2800
5,365
def trailing_zeroes(value): # type: (int) -> int """Count the number of trailing zeros in a given 8-bit integer""" return CTZ_TABLE[value]
a98968aa38c886de9aa38bae71e52d0e012c432c
5,366
def _calc_WaterCirculation(heat_load, CT_design, WBT, DBT, fixedCWT_ctrl, pump_ctrl, ignore_CT_eff, max_CT_eff=0.85): """Calculates the water circulation loop. Used by simulate_CT(). Parameters: Returns: All (time x CT) arrays as HWT Hot water temp [pint, C] CWT ...
46d4d7e8fb1c718821b9f64fe86fa268e05c459a
5,367
def read_dataset_from_csv(data_type, path): """Read dataset from csv Args: data_type (str): train/valid/test Returns: pd: data """ data = pd.read_csv(tf.io.gfile.glob(path + data_type + "*")[0]) return data
3b5fb8318d6b7297166b381d199fe206f4240d84
5,369
def search_ignore_case(s, *keywords): """Convenience function to search a string for keywords. Case insensitive version. """ acora = AcoraBuilder(keywords, ignore_case=True).build() return acora.findall(s)
bf093c3864353278a9ff91267b0806bc1e2362a3
5,370
from typing import Union from typing import List import pathlib def _prepare_directory(data_dir: Union[str, PathLike], ignore_bad: bool = True, confirm_uids: bool = True) -> List[str]: """ Reorganizes PPMI `data_dir` to a structure compatible with ``heudiconv`` ...
2220dec499f875501ab7fd80e4bdcf25c61c641d
5,372
import re def find_log_for(tool_code, form_id, log_f): """Returns an array of lines from log for given tool code (P1,N3,...) and form_id. The form_id is taken from runner - thus we search for formula number ``form_id+1`` """ log = open(log_f,'r') current_f = -1 formula = re.compile('.*...
c28659ce832dcc8ad372188a556699f20c9116db
5,373
def create_patric_boolean_dict(genome_dict,all_ECs): """ Create new dict of dicts to store genome names :param genome_dict: dict of key=genome_id, value=dict of genome's name, id, ec_numbers :param all_ECs: set of all ECs found across all genomes """ ## new format: key=genome, value={EC:0 or 1}...
7ab3554bbf705ee8ce99d1d99ff453b06e3d2b53
5,376
def append_ast_if_req(field): """ Adds a new filter to template tags that for use in templates. Used by writing {{ field | append_ast_if_req }} @register registers the filter into the django template library so it can be used in template. :param Form.field field: a field of a form that you woul...
76e36ead3387729b0536bf84f288c400f376a041
5,377
def getPileupMixingModules(process): """ Method returns two lists: 1) list of mixing modules ("MixingModule") 2) list of data mixing modules ("DataMixingModules") The first gets added only pileup files of type "mc", the second pileup files of type "data". """ mixModules, dataMixModules = [], [] ...
4ee3cc5f7b11e4ad6a846f14dc99e4f82bd04905
5,378
from typing import Hashable from typing import Type from typing import Any from typing import ForwardRef import typing def GetFirstTypeArgImpl_(type_: Hashable, parentClass: Type[Any]) -> Type[Any]: """ Returns the actual type, even if type_ is a string. """ if isinstance(type_, type): return type_ ...
f6fd63c4080af886de24465d866f87e716b49992
5,379
from typing import Callable from typing import Any from typing import Sequence def tree_map_zipped(fn: Callable[..., Any], nests: Sequence[Any]): """Map a function over a list of identical nested structures. Args: fn: the function to map; must have arity equal to `len(list_of_nests)`. nests: a list of id...
8117efd93402fb7ab5e34b4015950c77a24dc038
5,380
def square_area(side): """Returns the area of a square""" # You have to code here # REMEMBER: Tests first!!! return pow(side,2)
e3cc1a0d404c62a9b1d50de63ea924087c77066a
5,381
def match_collision_name_to_mesh_name(properties): """ This function matches the selected collison to the selected mesh. :param object properties: The property group that contains variables that maintain the addon's correct state. :return str: The changed collision name. """ collisions = get_fr...
3658435cdaa21408664a511e3555f3976c1b3614
5,382
def _handle_event_colors(color_dict, unique_events, event_id): """Create event-integer-to-color mapping, assigning defaults as needed.""" default_colors = dict(zip(sorted(unique_events), cycle(_get_color_list()))) # warn if not enough colors if color_dict is None: if len(unique_events) > len(_ge...
31ae730af0a184b5de469687b74334960c2939ef
5,383
import logging import warnings def redirect_logs_and_warnings_to_lists( used_logs: list[logging.LogRecord], used_warnings: list ) -> RedirectedLogsAndWarnings: """For example if using many processes with multiprocessing, it may be beneficial to log from one place. It's possible to log to variables (logs a...
31cda3f036c8438371811b6421a8af2b0f6ac215
5,384
def get_file_picker_settings(): """Return all the data FileUploader needs to start the Google Drive Picker.""" google_settings = frappe.get_single("Google Settings") if not (google_settings.enable and google_settings.google_drive_picker_enabled): return {} return { "enabled": True, "appId": google_settings.a...
3b1840e22512e1f9112f9fa4dfb6697299aa248a
5,385
def match_subset(pattern: oechem.OEMol, target:oechem.OEMol): """Check if target is a subset of pattern.""" # Atoms are equal if they have same atomic number (so explicit Hydrogens are needed as well for a match) atomexpr = oechem.OEExprOpts_AtomicNumber # single or double bonds are considered identica...
99d8d5d73f465f929b6710ec53b5e01f92c1e229
5,387
def get_quad_strike_vector(q): """ Compute the unit vector pointing in the direction of strike for a quadrilateral in ECEF coordinates. Top edge assumed to be horizontal. Args: q (list): A quadrilateral; list of four points. Returns: Vector: The unit vector pointing in strike direc...
169b8043a5a385843b92225cba8677ef39bb43a5
5,388
def CP_to_TT( cp_cores, max_rank, eps=1e-8, final_round=None, rsvd_kwargs=None, verbose=False, ): """ Approximate a CP tensor by a TT tensor. All cores of the TT are rounded to have a TT-rank of most `max_rank`, and singular values of at most `eps` times the largest singular val...
54c30dec3f18271050150dfcc443fcbfe74c4df5
5,389
def _create_key_list(entries): """ Checks if entries are from FieldInfo objects and extracts keys :param entries: to create key list from :return: the list of keys """ if len(entries) == 0: return [] if all(isinstance(entry, FieldInfo) for entry in entries): return [entry.ke...
bb87bbfbfc1856d4041c12d8babaaa8d8ce42249
5,390
def compose_rule_hierarchies(rule_hierarchy1, lhs_instances1, rhs_instances1, rule_hierarchy2, lhs_instances2, rhs_instances2): """Compose two rule hierarchies.""" if len(rule_hierarchy1["rules"]) == 0: return rule_hierarchy2, lhs_instances2, rhs_instances2 if len(rule_h...
0cfab451af31bfc7b41d610381efb47e8c5c0fb5
5,391
def expand_tile(value, size): """Add a new axis of given size.""" value = tf.convert_to_tensor(value=value, name='value') ndims = value.shape.ndims return tf.tile(tf.expand_dims(value, axis=0), [size] + [1]*ndims)
50adf652fff47418d1f8f1250a2a6d01f712da76
5,392
import logging import requests import time import json import pytz def fetch_exchange(zone_key1='DK-DK1', zone_key2='DK-DK2', session=None, target_datetime=None, logger=logging.getLogger(__name__)): """ Fetches 5-minute frequency exchange data for Danish bidding zones from api.energidat...
93488b4bc24a6a899232a5a1fd0e694d0747ad12
5,393
def snitch(func): """ This method is used to add test function to TestCase classes. snitch method gets test function and returns a copy of this function with 'test_' prefix at the beginning (to identify this function as an executable test). It provides a way to implement a st...
b8b54d55269951cb3db4c1f45c375ac36cbd3bdf
5,394
def average_h5(path, path_dc): """Return averaged data from HDF5 DC measurements. Subtracts dark current from the signal measurements. Args: - path, path_dc: paths to signal and dark measurement files. Returns: - 2D array containing averaged and DC-subtracted measurement. """ with h5....
8daaa7efcdbaf7137d320407b64a96b73f847289
5,395
def edit_distance(hypothesis, truth, normalize=True, name="edit_distance"): """Computes the Levenshtein distance between sequences. This operation takes variable-length sequences (`hypothesis` and `truth`), each provided as a `SparseTensor`, and computes the Levenshtein distance. You can normalize the edit dis...
9dfcebb6f49de41c5d5d6bfcc849873f14e2b3f9
5,396
def kl_bernoulli(p: np.ndarray, q: np.ndarray) -> np.ndarray: """ Compute KL-divergence between 2 probabilities `p` and `q`. `len(p)` divergences are calculated simultaneously. Parameters ---------- p Probability. q Probability. Returns ------- Array with the KL...
91567169da22ae42bd90c15292f1699f53a184ab
5,398
def _incremental_mean_and_var(X, last_mean, last_variance, last_sample_count): """Calculate mean update and a Youngs and Cramer variance update. last_mean and last_variance are statistics computed at the last step by the function. Both must be initialized to 0.0. In case no scaling is required last_var...
8fac3715bed8431f0910bbf7a37d3924afece9c0
5,399
def avg_pds_from_events( times, gti, segment_size, dt, norm="frac", use_common_mean=True, silent=False, fluxes=None, errors=None, ): """Calculate the average periodogram from a list of event times or a light curve. If the input is a light curve, the time array needs to be un...
904f43b36380e07e115d23c6677b61bca155d898
5,400
import random def check_random_state(seed): """ Turn seed into a random.Random instance If seed is None, return the Random singleton used by random. If seed is an int, return a new Random instance seeded with seed. If seed is already a Random instance, return it. Otherwise raise ValueError. ...
347481de01f4a3bba59bc9a2c484c10d4857e1e2
5,401
def chunk(seq, size, groupByList=True): """Returns list of lists/tuples broken up by size input""" func = tuple if groupByList: func = list return [func(seq[i:i + size]) for i in range(0, len(seq), size)]
e7cece99822a01476b46351cebc1345793485cbd
5,402
def registerNamespace(namespace, prefix): """ Register a namespace in libxmp.exempi @namespace : the namespace to register @prefix : the prefix to use with this namespace """ try: registered_prefix = libxmp.exempi.namespace_prefix(namespace) # The namespace already exists, return actual prefix. return r...
6e7dbed515651f252222a283dc1cda08941fa4c5
5,403
def definition(): """ Lists the parent-child relationships through the curriculum structure. """ sql = """ --Course to session SELECT c.course_id as parent_id, CASE WHEN cc.course_id IS NULL THEN 0 ELSE 1 END as linked, cs.course_session_id as child_id, 'course' as parent, cs.description + ' ' + ...
e8dc6a720dcd5f62854ce95e708a88b43859e2cc
5,404
def create_user(strategy, details, backend, user=None, *args, **kwargs): """Aggressively attempt to register and sign in new user""" if user: return None request = strategy.request settings = request.settings email = details.get("email") username = kwargs.get("clean_username") if ...
afdff23d6ca578ef652872ba11bcfe57264b0a9b
5,405
def prendreTresorPlateau(plateau,lig,col,numTresor): """ prend le tresor numTresor qui se trouve sur la carte en lin,col du plateau retourne True si l'opération s'est bien passée (le trésor était vraiment sur la carte paramètres: plateau: le plateau considéré lig: la ligne où se trou...
5fa94fb875e34068f4e391c66952fe4cc4248ddf
5,406
def task_get_all(context, filters=None, marker=None, limit=None, sort_key='created_at', sort_dir='desc', admin_as_user=False): """ Get all tasks that match zero or more filters. :param filters: dict of filter keys and values. :param marker: task id after which to start page :param ...
4d03e8f7ae15411c2cb597aeb06e25cd40c4f033
5,409
def updateAppMonConf(AppID, requestModel): """Update an Application Monitoring Configuration for a given application Args: AppID (str): This is the application ID of the Web App you are interested in. requestModel: This is the data you wish to update and you need to put it in this f...
0b61eae04b79702b2722d0c0bc5dafe48dcdf21f
5,410
def plot_morphology(morphology, order=MORPHOLOGY_ORDER, colors=MORPHOLOGY_COLORS, metastases=None, metastasis_color=METASTASIS_COLOR, ax=None, bg_color='#f6f6f6', **kwargs): ""...
62048ced8ede14e9aa505c6e45dd5b196d12297d
5,411
import requests def post(name,url,message,params=None): """Wrap a post in some basic error reporting""" start = dt.now() s = requests.session() if params is None: response = s.post(url,json=message) else: response = s.post(url,json=message,params=params) end = dt.now() if n...
9180424171cdf4cb7bf16a938d7207a99af0987f
5,413
def get_lin_reg_results(est, true, zero_tol=0): """ Parameters ---------- est: an Estimator A covariance estimator. true: array-like, shape (n_features, n_features) zero_tol: float Output ------ out: dict with keys 'utri' and 'graph' """ est_coef = get_coef(est)[...
0f963c135d0bd74a70714ef47ed6f2b0191df846
5,414
import requests import logging def download_file(requested_url: str) -> str: """Download a file from github repository""" url = f"https://github.com/{requested_url.replace('blob', 'raw')}" resp = requests.get(url) logging.info(F"Requested URL: {requested_url}") if resp.status_code != 200: ...
f96d68843f6291aa3497a6e7a5b1e30e2ea4005e
5,415
import warnings def readBody(response): """ Get the body of an L{IResponse} and return it as a byte string. This is a helper function for clients that don't want to incrementally receive the body of an HTTP response. @param response: The HTTP response for which the body will be read. @type r...
bbc693fca1536a3699b0e088941d9577de94d8dd
5,416
def is_valid_mac(address): """Verify the format of a MAC address.""" class mac_dialect(netaddr.mac_eui48): word_fmt = '%.02x' word_sep = ':' try: na = netaddr.EUI(address, dialect=mac_dialect) except Exception: return False return str(na) == address.lower()
f8bb59a986773307f803dd52154ec03eaddb8597
5,417
def build_state_abstraction(similar_states, mdp, tol=0.1): """ """ bools = similar_states + np.eye(similar_states.shape[0]) < tol # approximate abstraction if bools.sum() == 0: raise ValueError('No abstraction') mapping, parts = partitions(bools) idx = list(set(np.array([p[0] for p i...
d4d9354507172ee92ea11c915de0376f0c873878
5,418
def diagram(source, rstrip=True): """High level API to generate ASCII diagram. This function is equivalent to: .. code-block:: python Diagram(source).renders() :param source: The ADia source code. :type source: str or file-like :param rstrip: If ``True``, the trailing wihtespaces at t...
2a386b49052a7f4dd31eb4f40dec15d774d86b94
5,419
def eng_to_kong(eng_word: str)-> list[str]: """ Translate given English word into Korean into matching pronounciation, matching the English Loanword Orthography. For example, "hello" will be translated into 헐로. # Panics When given a english word that it cannot translate, `eng_to_kong` will rai...
0b0d55fdacdea1493d73de85c21dc9c086352b99
5,420
def socfaker_dns_answers(): """ A list of DNS answers during a DNS request Returns: list: A random list (count) of random DNS answers during a DNS request """ if validate_request(request): return jsonify(str(socfaker.dns.answers))
c1f641e1a0e977363067937487a6455800e6a25c
5,422
def bilin(x, y, data, datax, datay): # --DC """ x, y ARE COORDS OF INTEREST data IS 2x2 ARRAY CONTAINING NEARBY DATA datax, datay CONTAINS x & y COORDS OF NEARBY DATA""" lavg = ( (y - datay[0]) * data[1,0] + (datay[1] - y) * data[0,0] ) / (datay[1] - datay[0]) ravg = ( (y - datay[0]) * data[1,1] + ...
59a740f65c7187a08cdc09cef8aa100b01c652cf
5,424
import array def slice_data(xdata, ydata, x_range): """ crops or slices the data in xdata,ydata in the range x_range on the x axis """ data = zip(xdata, ydata) sliced_data = [d for d in data if d[0] >= x_range[0] and d[0] <= x_range[1]] return array(zip(*sliced_data))
faf90781e2f073e74a7b11cd80d7c127c0db1bb3
5,425
def best_low_rank(A, rank): """ Finding the best low rank approximation by SVD """ u, s, vh = np.linalg.svd(A) s = np.sqrt(s[:rank]) return u[:, range(rank)] @ np.diag(s), np.diag(s) @ vh[range(rank)]
5df8197fc0113bfa74a36803445a6a300766880f
5,426
def get_bangumi(uid: int, type_: str = "bangumi", limit: int = 114514, callback=None, verify: utils.Verify = None): """ 自动循环获取追番/追剧列表 :param callback: 回调函数 :param uid: :param type_: :param limit: :param verify: :return: """ if verify is None: verify = utils.Verify() ...
b5a2a553a3bf13ded7eb30c53ce536b4a2b9e043
5,427
def local_cases_range(start_date='2020-06-01',end_date='2020-07-01',areaname='Hartlepool'): """calculate new cases in a time range""" try: q=DailyCases.objects.filter(areaname=areaname,specimenDate=start_date)[0] start_total=q.totalLabConfirmedCases q=DailyCases.objects.filter(areaname=areaname,specimenDate=e...
747f03f2ef9925f7dc252798bb7f3844cd31d2c0
5,428
def ecal_phisym_flattables(process, produce_by_run : bool=False): """ Add the NanoAOD flat table producers. This functions adjust also the output columns. Should be called once nMisCalib has been set in the EcalPhiSymRecHitProducer """ process.load('Calibration.EcalCalibAlgos.EcalPhiSymFlatTabl...
f6f48ab2e5b1df6a3e58c5e3130be56861eb1384
5,429
def nx_add_prefix(graph, prefix): """ Rename graph to obtain disjoint node labels """ assert isinstance(graph, nx.DiGraph) if prefix is None: return graph def label(x): if isinstance(x, str): name = prefix + x else: name = prefix + repr(x) ...
c8f05052c613adc17423637186867b70db31e70d
5,430
def infected_asymptomatic_20x80(): """ Real Name: b'Infected asymptomatic 20x80' Original Eqn: b'Infected asymptomatic 20+Infected asymptomatic 80' Units: b'person' Limits: (None, None) Type: component b'' """ return infected_asymptomatic_20() + infected_asymptomatic_80()
fd9cba446672bf8ebcc5fe2fc7f2f961129bdb71
5,431
def biosample_table_data(): """Return a dictionary containing the expected values of the BioSample Table""" columns = [ "id", "BioSample_id", "BioSampleAccession", "BioSampleAccessionSecondary", "BioSampleBioProjectAccession", "BioSampleSRAAccession", "Bi...
65e5d5bb5416a8f113100562fba8f2e6fd66796a
5,433
def grid_adapter3D( out_dim=(100.0, 100.0), in_dim=(50.0, 50.0), z_dim=-10.0, out_res=(10.0, 10.0, 10.0), in_res=(5.0, 5.0, 5.0), out_pos=(0.0, 0.0), in_pos=(25.0, 25.0), z_pos=0.0, in_mat=0, out_mat=0, fill=False, ): """ Generate a grid adapter. 3D adapter from ...
9c14a4f9b27ec14cdc550f81fd861207a5674616
5,434
from typing import Sequence from typing import Tuple from typing import Mapping from typing import Any from functools import reduce from typing import cast def concat_dtypes(ds: Sequence[np.dtype]) -> np.dtype: """Concat structured datatypes.""" def _concat( acc: Tuple[Mapping[Any, Any], int], a: ...
bef7d8ebe30f41297adbf8f1d8de9b93f646c8f4
5,435
def mutation(param_space, config, mutation_rate, list=False): """ Mutates given configuration. :param param_space: space.Space(), will give us information about parameters :param configs: list of configurations. :param mutation_rate: integer for how many parameters to mutate :param list: boolean...
38427cfee226589d72117f102d2befdbe8ebbcc0
5,436
from typing import Union from typing import Callable from typing import Optional from typing import Tuple def uncertainty_batch_sampling(classifier: Union[BaseLearner, BaseCommittee], X: Union[np.ndarray, sp.csr_matrix], n_instances: int = 20, ...
eb95ad79f4326d89c94a42aa727e2e3c338e021e
5,437
import re def only_digits(raw, force_int=False): """Strips all not digit characters from string. Args: raw (str or unicode): source string. Kwargs: force_int (boolean): not to seek for dot, seek only for int value. Returns: int or float: in dependence of "raw" argument conte...
413763588b067f335f7401fb914f1d6f3f8972fa
5,438
def namedtuple(typename, field_names, verbose=False): """Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', 'x y') >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args o...
ce2e4b2f6fe0243a8ac5c418d10c6352c95ea302
5,439
from typing import Optional from typing import Sequence def get_users(compartment_id: Optional[str] = None, external_identifier: Optional[str] = None, filters: Optional[Sequence[pulumi.InputType['GetUsersFilterArgs']]] = None, identity_provider_id: Optional[str] = None, ...
4d404eb1069c829bb757f3870efc548583998434
5,440
def se_resnet20(num_classes: int = 10, in_channels: int = 3 ) -> ResNet: """ SEResNet by Hu+18 """ return resnet(num_classes, 20, in_channels, block=partial(SEBasicBlock, reduction=16))
da1d1327d5e5d1b55d3b4cc9d42dbf381ece029f
5,441
def parallel_threaded(function): """ A decorator for running a function within a parallel thread """ def decorator(*args, **kwargs): t = ParallelThread(target=function, args=args, kwargs=kwargs) t.daemon = True t.start() return t return decorator
9f4936b0ab7de3d550b404043d6b0e37dbb3a066
5,442
def Upsample(x, size): """ Wrapper Around the Upsample Call """ return nn.functional.interpolate(x, size=size, mode="bilinear", align_corners=True)
dfaabb3999047589b2d755a2cc631b1389d172b1
5,443
def get_user_playlists(spotipy_obj, username): """Gets and returns all Spotify playlists owned by the username specified. Parameters: spotipy_obj: Spotipy object username: Spotify username Returns: List of dictionaries, each dictionary a Spotify playlist object. """ # Gra...
90c06e0ddd91a7a84f4d905dd9334f9b4c27f890
5,444
def create(dataset, target, features=None, l2_penalty=1e-2, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level = _DEFAULT_SOLVER_OPTIONS['lbfgs_memory_level'...
3988ac27163873a8feff9fd34a5e8fe87e923487
5,447
def argument(*name_or_flags, **kwargs): """Convenience function to properly format arguments to pass to the subcommand decorator. """ args = list() for arg in name_or_flags: args.append(arg) return args, kwargs
0cae66e8b23211affc97fd8857f17b48a73cf286
5,448
def get_logger(): """ Provides the stem logger. :returns: **logging.Logger** for stem """ return LOGGER
8189cae16a244f0237f641e613783a484be5cf38
5,449
def get_graphql_type_for_model(model): """ Return the GraphQL type class for the given model. """ app_name, model_name = model._meta.label.split('.') # Object types for Django's auth models are in the users app if app_name == 'auth': app_name = 'users' class_name = f'{app_name}.graph...
d9f2b4093c290260db864cedd6b06958651bf713
5,450
from pathlib import Path def load_image_files(container_path, dimension=(64, 64)): """ Load image files with categories as subfolder names which performs like scikit-learn sample dataset """ image_dir = Path(container_path) folders = [directory for directory in image_dir.iterdir() if dir...
1c92309c7f8f0b99db841fed21901d37e143f41c
5,451
from datetime import datetime import calendar def create_calendar(year=None, month=None): """ Create an inline keyboard with the provided year and month :param int year: Year to use in the calendar, if None the current year is used. :param int month: Month to use in the calendar, if None the c...
232dd093b08c53f099b942d4497aef920002f5d4
5,452
def format_allowed_section(allowed): """Format each section of the allowed list""" if allowed.count(":") == 0: protocol = allowed ports = [] elif allowed.count(":") == 1: protocol, ports = allowed.split(":") else: return [] if ports.count(","): ports = ports.s...
0c07feec16562826a1f38a11b1d57782adf09b4d
5,453
def get_airmass(when, ra, dec): """Return the airmass of (ra,dec) at the specified observing time. Uses :func:`cos_zenith_to_airmass`. Parameters ---------- when : astropy.time.Time Observation time, which specifies the local zenith. ra : astropy.units.Quantity Target RA angle(...
2d2b25963cc5814c8189b117734963feda762d88
5,455
def get_metadata(class_): """Returns a list of MetaDataTuple structures. """ return list(get_metadata_iterator(class_))
95bc083464431cd8bc3c273989680732f711c5c1
5,456
def get_register(regname): """ Get register value. Exception will be raised if expression cannot be parse. This function won't catch on purpose. @param regname: expected register @return register value """ t = gdb.lookup_type("unsigned long") reg = gdb.parse_and_eval(regname) return ...
43d077b59dc0b1cb8a6233538a2a1291216c1ec4
5,457
import re def create_queries(project_id, ticket_number, pids_project_id, pids_dataset_id, pids_table): """ Creates sandbox and truncate queries to run for EHR deactivated retraction :param project_id: bq name of project :param ticket_number: Jira ticket number to identify and title...
2940468b76ccd4d16dfb1bbddf440be635eaaf8d
5,458
def load_and_estimate(file, arguments, denoise=medfilt, data=None): """Loads mean+std images and evaluates noise. Required for parallelization.""" # Pipeline for µCT data if data is not None: # Evaluate noise on data noises = np.zeros(len(metrics)) for m in range(len(metrics)): ...
63b53eb5441dd9a2e9f4b558005b640109fea220
5,459
import torch def calc_self_attn( bert_model: BertModel, protein: dict, device="cuda:0", **kwargs ): """Calculate self-attention matrices given Bert model for one protein. Args: bert_model: a BertModel instance protein: a dict object from LM-GVP formatted data (json record). de...
4d076cc232207c9c446c4f9f52f1156af2afabf2
5,460
def compute_median_survival_time(times, surv_function): """ Computes a median survival time estimate by looking for where the survival function crosses 1/2. Parameters ---------- times : 1D numpy array Sorted list of unique times (in ascending order). surv_function : 1D numpy array...
22103bc705acb791c0937a403aa9c34e9145e1c2
5,461
def TDMAsolver_no_vec(coeffs): """ TDMA solver, a b c d can be NumPy array type or Python list type. refer to http://en.wikipedia.org/wiki/Tridiagonal_matrix_algorithm and to http://www.cfd-online.com/Wiki/Tridiagonal_matrix_algorithm_-_TDMA_(Thomas_algorithm) """ a = coeffs[1:, 0] b = coef...
cdec1baa7ce0fe2baef71631b0ba678a0f7559dc
5,462
def aggregate_ant(data, sub_num, response_type="full"): """ Aggregate data from the ANT task. Calculates various summary statistics for the ANT task for a given subject. Parameters ---------- data : dataframe Pandas dataframe containing a single subjects trial data for the task. su...
be01651d450560a5c36bc6240025fe59352d6347
5,463
def parse_search_after(params): """Validate search_after and return it as a list of [score, ID].""" search_pair = params.get("search_after") sort = params.get("sort") if not search_pair or not sort: return if '_' not in search_pair or len(search_pair.split("_")) != 2: return _sco...
f44228d4f5b47129218d122adcb29e41a81c5a1f
5,464