content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_all_elems_from_json(search_json: dict, search_key: str) -> list: """Returns values by key in all nested dicts. Args: search_json: Dictionary in which one needs to find all values by specific key. search_key: Key for search. Returns: List of values stored in nested structure...
6ab45e33962ccb5996b50d13e57626365c4ed78b
32,256
def prFinalNodeName(q): """In : q (state : string) Out: dot string (string) Return dot string for generating final state (double circle) """ return dot_san_str(q) + '[shape=circle, peripheries=2];'
8a4e5649ebeb0c68f2e1741fefd935c9a5f919bf
32,258
import typing from datetime import datetime def decodeExifDateTime(value: str) -> typing.Optional[datetime.datetime]: """ utility fct to encode/decode """ try: # return path.encode(sys.stdout.encoding, 'ignore').decode(sys.stdout.encoding) d = datetime.datetime.strptime(value, '%Y:%m:%...
a1ce11305e8e486ad643530930368c47f1c073ef
32,259
def parse(file: str) -> Env: """Parse an RLE file and create a user environment Parameters ---------- file: str Path to the RLE file. Returns ------- user_env: `dict` [str, `Any`] User environment returned from ``user_env()``. It has these attributes: ``width`` ...
cf0a884169b22f4781450c78a35b33ef43049d65
32,260
import six def logger_has_handlers(logger): """ Check if given logger has at least 1 handler associated, return a boolean value. Since Python 2 doesn't provide Logger.hasHandlers(), we have to perform the lookup by ourself. """ if six.PY3: return logger.hasHandlers() else: c =...
dc0093dd25a41c997ca92759ccb9fa17ad265bdd
32,261
import json def query_parameters(prefix, arpnum, t_recs, keywords, redis=True): """Query keyword sequence from a header file. Alternative design: replace prefix and arpnum with filepath. """ KEYWORDS = ['T_REC', 'AREA', 'USFLUXL', 'MEANGBL', 'R_VALUE'] if redis: id = f'{prefix}{arpnum:06...
84c0a43d6d045e3255478175697cbb0bfaac5da8
32,262
def x0_rand(mu3,xb,num_min): """ Randomly initialise the 5 protocol parameters using the specified bounds. Parameters and bounds should be specified in the order {Px,pk1,pk2,mu1,mu2}. Parameters ---------- mu3 : float Intensity of pulse 3 (vacuum). xb : float, array-like Upp...
fcf32cd7367e7b78e48829f72523f50855ba563e
32,264
def render_smiles_list(smiles_list): """ Format and return a SMILES string(s). """ # The string that will be returned to the template result = r'<h3>Solvent SMILES:</h3>' + '\n' result += r'<p>' if len(smiles_list) == 1: result += smiles_list[0] else: result += 'This is a...
f6207bb63452d1037c321874b8ed5248e89dc83e
32,265
def get_config_id(kwargs=None, call=None): """ Returns a config_id for a given linode. .. versionadded:: 2015.8.0 name The name of the Linode for which to get the config_id. Can be used instead of ``linode_id``. linode_id The ID of the Linode for which to get the config_id...
b66eda936157d0c6794289ed90acd681a5d31c02
32,266
def bunq_oauth_reauthorize(): """ Endpoint to reauthorize OAuth with bunq """ cookie = request.cookies.get('session') if cookie is None or cookie != util.get_session_cookie(): return render_template("message.html", msgtype="danger", msg=\ "Invalid request: session cookie not set or not v...
57708acb8e4c726640360bfb1263ede323571c15
32,267
from typing import List from typing import Tuple def extract_mealentries(meals: List[Meal]) -> List[Tuple]: """ Extract meal entries records from a sequence of myfitnesspal meals. Args: - meals (List[Meal]): A list with meal objects to extract data from Returns: - List[Tuple]: A list wit...
c7c043cee0b4af1253902080af67919cc9238d75
32,269
import math def get_45point_spiralling_sphere_with_normal_zaxis_dist( num_of_spirals = 4, num_of_vertices = 45): """ A sphere of spiralling points. Each point is equally spaced on the x,y,z axes. The equal spacing is calculated by dividing the straight-line spiral distance by 45. Adapted from Leonsim's co...
59173bdd28b513d0f039215ea7d713cd80d81b4e
32,270
import re import json def parse_results(line): """Parses and logs event information from logcat.""" header = re.search(r'cr_PasswordChangeTest: (\[[\w|:| |#]+\])', line).group(1) print(header) credentials_count = re.search(r'Number of stored credentials: (\d+).', line) if not credentials_count: # Event...
24cc928d945d2d4f16f394be68a8bb217c21b342
32,273
def bqwrapper(datai): """ Wraps the kdtree ball query for concurrent tree search. """ return kdtbq(datai, r=bw[0])
203e77e37ddb53b76366b0d376c37b63536da923
32,274
import re def crawl_user_movies(): """ @功能: 补充用户观看过的电影信息 @参数: 无 @返回: 电影信息 """ user_df = pd.read_csv('douban_users.csv') user_df = user_df.iloc[:, [1, 2, 3]] user_movies = list(user_df['movie_id'].unique()) movies = [] # 储存电影 count = 1 # 日志参数 for i in user_movies: ...
882fe56fc2fc5e22b6ad0ce518b7adaabd724cd2
32,275
import logging def filter_by_shape(data: pd.DataFrame, geofence: Polygon) -> pd.DataFrame: """Remove trips outside of geofence. Filter by pickup and dropoff locations""" logging.info('Filtering by bbox') (min_lon, min_lat, max_lon, max_lat) = geofence.bounds data = data[ (data.pickup_longitu...
fa98c85ea286921e9a986820a7a17e03e94181dc
32,276
from ..core import cache as cache def upload_collection(flask_app, filenames, runs, dataset_id, collection_id, descriptions=None, cache=None): """ Create new Predictors from TSV files Args: filenames list of (str): List of paths to TSVs runs list of (int): List of run ids...
d6d16206716dae0e7e945d1cff95317454031e3e
32,277
def get_filtered_metadata_list(metadata_list, strand): """ Given a lis of exon junctions, remove the ones that redundantly cover a junction Parameters ---------- metadata_list: List(Output_metadata), strand: strand of the gene Returns ------- filtered_meetadata_list: List of metadata o...
dab3da34f435d7401dd5e76be2c9c032aea875c1
32,278
import functools import traceback def handle_exceptions(database, params, constraints, start_params, general_options): """Handle exceptions in the criterion function. This decorator catches any exceptions raised inside the criterion function. If the exception is a :class:`KeyboardInterrupt` or a :class:`...
725cfc7d3c338e2a4dbd143fc558307cbb49e1cc
32,279
def vector2angles(gaze_vector: np.ndarray): """ Transforms a gaze vector into the angles yaw and elevation/pitch. :param gaze_vector: 3D unit gaze vector :return: 2D gaze angles """ gaze_angles = np.empty((1, 2), dtype=np.float32) gaze_angles[0, 0] = np.arctan(-gaze_vector[0]/-gaze_vector[2]...
b0db8e1f6cb9865e9563af5385f760699069013e
32,280
def setup_train_test_idx(X, last_train_time_step, last_time_step, aggregated_timestamp_column='time_step'): """ The aggregated_time_step_column needs to be a column with integer values, such as year, month or day """ split_timesteps = {} split_timesteps['train'] = list(range(last_train_time_step + 1)) ...
256fbe66c0b27b651c8190101e5068f7e0542498
32,281
def get_targets_as_list(key_list): """Get everything as list :param key_list: Target key list :type key_list: `list` :return: Values list :rtype: `list` """ session = get_scoped_session() values = [] for key in key_list: values.append(get_all_targets(session, key)) retur...
bcd2ed48d685353a59c4545d1277589fa388b4a0
32,282
import re def load_jmfd(jmfd_path): """Loads j-MFD as Pandas DataFrame. Args: jmfd_path (str): Path of J-MFD. Raises: JMFDFormatError: J-MFD format error. Returns: pandas.DataFrame: Pandas DataFrame of loaded j-MFD with word, existence of stem, foundation ...
675370c9ce0ed37667ec347dc4a0af57ea5b20b3
32,283
def objectId(value): """objectId校验""" if value and not ObjectId.is_valid(value): raise ValueError('This is not valid objectId') return value
2e33950649fe95460e82102c1d6209a9173fa5fd
32,285
def add_lists(list1, list2): """ Add corresponding values of two lists together. The lists should have the same number of elements. Parameters ---------- list1: list the first list to add list2: list the second list to add Return ---------- output: list ...
e4efbc079a981caa4bcbff4452c8845a7e534195
32,286
def get_struc_first_offset(*args): """ get_struc_first_offset(sptr) -> ea_t Get offset of first member. @param sptr (C++: const struc_t *) @return: BADADDR if memqty == 0 """ return _ida_struct.get_struc_first_offset(*args)
f589dec791c3a81664b81573ea52f02d1c9a6b15
32,287
def export_gps_route( trip_id, trip_date, vehicle_id, gtfs_error, offset_seconds, gps_data ): """ Writes the given entry to the "tracked_routes" table. This table is used to cache the results of finding and filtering only the valid routes as represented in the GPS da...
fe1a4f4fb2c89c6634353748d5cdd49d82110e64
32,288
def optimize_solution(solution): """ Eliminate moves which have a full rotation (N % 4 = 0) since full rotations don't have any effects in the cube also if two consecutive moves are made in the same direction this moves are mixed in one move """ i = 0 while i < len(soluti...
4be6bf0e4200dbb629c37a9bdae8338ee32c262b
32,289
from typing import Iterable import resource from typing import Optional def secretsmanager_resource( client: Client, policies: Iterable[Policy] = None, ): """ Create Secrets Manager resource. Parameters: • client: Secrets Manager client object • policies: security policies to apply to all...
ee2d880944065331aba0751bdfba2f82c3d7e2ac
32,290
def lgbm_hyperband_classifier(numeric_features, categoric_features, learning_rate=0.08): """ Simple classification pipeline using hyperband to optimize lightgbm hyper-parameters Parameters ---------- `numeric_features` : The list of numeric features `categoric_features` : The list of categoric ...
7c48373d1f40d7248a9d0f6a37c95281027aa1bd
32,291
def GL(mu, wid, x, m = 0.5): """ Function to generate a 1D Gaussian-Lorentzian peak. The peak is centered at pos, is wid wide (FWHM) and with blending parameter m. Parameters ---------- mu: float Peak center wid: float FWHM of Gaussian peak. FWHM is related to ...
d458eae3ad1ea31dcab021c798e9d7d02fa390ae
32,292
def jp_(var,mask): """Value at j+1/2, no gradient across boundary""" return div0((var*mask + np.roll(var*mask,-1,axis=0)),(mask+np.roll(mask,-1,axis=0)))
cc2aaf2e17bd0cbe3a211b26bc9d976298307f0d
32,293
import re def _solrize_date(date, date_type=''): """ Takes a date string like 2018/01/01 and returns an integer suitable for querying the date field in a solr document. """ solr_date = "*" if date: date = date.strip() start_year, end_year = fulltext_range() if date_typ...
f309f784d79b46ed704ee1e631d7b4bdda7057f6
32,294
def read_file(filename): """ read filename and return its content """ in_fp = open(filename) content = in_fp.read() in_fp.close() return content
c707a412b6099591daec3e70e9e2305fee6511f9
32,295
def delete_job(job_id): """Delete my job by Id Upon success, marks job as &#x27;aborted&#x27; if it must be suspended, and returns the deleted job with the appropriate status # noqa: E501 :param job_id: Id of the job that needs to be deleted :type job_id: str :rtype: Job """ job = q.fetch...
e8f02faa2a9336c93725739443b9007242b50b5c
32,297
def service(appctx): """Service with files instance.""" return RecordService(ServiceWithFilesConfig)
4902f8eae2c2c4200543a9c594f2abbc5163ec70
32,298
import json import re def get_sci_edus(filepath): """ load each sciedu """ with open(filepath, 'r') as fb: train = json.loads(fb.read().encode('utf-8'))['root'] EDUs = [] sentenceNo = 1 sentenceID = 1 for edu_dict in train: if edu_dict['id'] == 0: continue ...
0b8fd37dd8884e9e3f38f4bb671dff2df978f5b2
32,299
def vec_moderates(vec, minv, maxv, inclusive=1): """return a integer array where values inside bounds are 1, else 0 if inclusive, values will also be set if they equal a bound return error code, new list success: 0, list error : 1, None""" if not vec: return 1, None i...
65696ba3d4cb8c43e231a4aae1c8cef83351fb07
32,300
def SideInfo(version_index, channel_mode, raw_data=None): """SideInfo(version_index, channel_mode, raw_data) -> object Return an object representing MPEG layer 3 side info, based on the given parameters. The class of the object varies based on the MPEG version and channel mode (only applicable fields are present, and...
af554b0b6ebc4c33846881b27c02fb648d82b5ca
32,301
def datetimeConvertor(date, month, year, time, timezone): """ Converts raw date/time data into an object of datetime class. """ Date = date + "/" + monthnumberSwap(month) + "/" + year Time = time + " " + timezone return dt.datetime.strptime(Date + " " + Time, "%d/%m/%Y %H:%M:%S %z")
a83e873ee9b9aa1737fffc61c80aa9204305d3fb
32,302
import pathlib def dump_gone(aspect_store: dict, indent=False) -> bool: """Not too dry ...""" return _dump(aspect_store, pathlib.Path('gone.json'), indent)
14df4567d0ffc80f9764afa50c725bc1d178e031
32,303
def loss_fn(params, model, data): """ Description: This is MSE loss function, again pay close attention to function signature as this is the function which is going to be differentiated, so params must be in its inputs. we do not need to vectorize this function as it is written with batching co...
cddd29becee4ce047b086130c7ce8cea114cb914
32,304
import copy def lufact(A): """ lufact(A) Compute the LU factorization of square matrix A, returning the factors. """ n = A.shape[0] L = eye(n) # puts ones on diagonal U = copy(A) # Gaussian elimination for j in range(n-1): for i in range(j+1,n): L[i,j] = U[i,j] / U[j,j] # row multiplier U[i,...
e04c20ede47019789e00dc375b84efa931fe2e1f
32,305
def get_city(msg): """ 提取消息中的地名 """ # 对消息进行分词和词性标注 words = posseg.lcut(msg) # 遍历 posseg.lcut 返回的列表 for word in words: # 每个元素是一个 pair 对象,包含 word 和 flag 两个属性,分别表示词和词性 if word.flag == 'ns': # ns 词性表示地名 return word.word return None
017f910090291fdc77cc22ce4bc3fc3699c2981b
32,306
def get_cycle_time(string): """ Extract the cycle time text from the given string. None if not found. """ return _search_in_pattern(string, CYCLE_TIME_PATTERN, 1)
6d41a9f4b04f90b4a5a8d7892398bc080d41e519
32,309
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms( config_entry, PLATFORMS ) hass.data[DOMAIN].pop(config_entry.entry_id, None) if not hass.data[DOMAIN]: has...
6e4bf924e6e04d03cc30de3a6d4b2f713dd05b32
32,310
from typing import Union def get_scale_factor(unit: Union[str, float]) -> float: """ Get how many pts are in a unit. :param unit: A unit accepted by fpdf.FPDF :return: The number of points in that unit :raises FPDFException """ if isinstance(unit, (int, float)): return float(unit) ...
c95429436b96f883e5fcfe3b1680a9f35c5f27e3
32,312
def r2_score(y_true,y_pred): """Calculate the coefficient of determination.""" assert len(y_true)==len(y_pred) rss = sum_square_residuals(y_true,y_pred) tss = total_sum_squares(y_true) return 1 - rss/tss
7d2eba54db3d5682ec0ed22b5c09a65cf1e34e27
32,313
def give_name(fname): """ return name.csv """ if fname[:len( AUX_FILE) ] != AUX_FILE: # hide file # renaming with correct extension if fname[ -4: ]!= '.csv': if fname.find('.') > -1: fname = fname[: fname.find('.')]+'.csv' else: fname += '.csv'...
55f6241b7a57d7611fe2db1731d909bb5b4186ac
32,314
def categorize(document): """Categorize a document. Categorizes a document into the following categories [business, entertainment, politics, sport, tech]. Takes a string object as input and returns a string object. """ doc = clean(document) vector = doc2vec_model.infer_vector(doc.split(' '...
a085e08e7e8b7ff31e68a536e973b5131540e481
32,315
def delete_intent(token, aiid, intent_name): """Delete an Intent""" return fetch_api( '/intent/{aiid}?intent_name={intent_name}', token=token, aiid=aiid, intent_name=intent_name, method='delete' )
198ed90b176c2f08c3c681dfbb5deea52cfbcfa4
32,316
def report_all(df_select): """ report all values to a defined template """ if len(df_select) == 0: report_all = 'No similar events were reported on in online media' else: report_all = """ Similar events were reported on in online media. Below we provide a tabulated s...
d0e5f06416a467d7578f4748725301638b33d1bb
32,317
import urllib def get_filename_from_headers(response): """Extract filename from content-disposition headers if available.""" content_disposition = response.headers.get("content-disposition", None) if not content_disposition: return None entries = content_disposition.split(";") name_entry...
d4c54c3d19d72f2813e2d1d4afde567d0db0e1af
32,318
def names(as_object=False, p5_connection=None): """ Syntax: ArchiveIndex names Description: Returns the list of names of archive indexes. Return Values: -On Success: a list of names. If no archive indexes are configured, the command returns the string "<empty>" """ met...
1b1d00d70730b79ccab25e5ca101f752ad49cc1c
32,319
def regionvit_base_w14_224(pretrained=False, progress=True, **kwargs): """ Constructs the RegionViT-Base-w14-224 model. .. note:: RegionViT-Base-w14-224 model from `"RegionViT: Regional-to-Local Attention for Vision Transformers" <https://arxiv.org/pdf/2106.02689.pdf>`_. The required input ...
63983c4fe9cb5ed74e43e1c40b501f50fbaead56
32,320
import collections def create_executor_list(suites): """ Looks up what other resmoke suites run the tests specified in the suites parameter. Returns a dict keyed by suite name / executor, value is tests to run under that executor. """ memberships = collections.defaultdict(list) test_membe...
c9150b14ba086d9284acb2abdcd4592e7803a432
32,321
def calculate_great_circle(args): """one step of the great circle calculation""" lon1,lat1,lon2,lat2 = args radius = 3956.0 x = np.pi/180.0 a,b = (90.0-lat1)*(x),(90.0-lat2)*(x) theta = (lon2-lon1)*(x) c = np.arccos((np.cos(a)*np.cos(b)) + (np.sin(a)*np.sin(b)*np.co...
f0832b984382b2cd2879c40ab1249d68aacddd69
32,322
def divide(x,y): """div x from y""" return x/y
74adba33dfd3db2102f80a757024696308928e38
32,323
def execute(compile_state: CompileState, string: StringResource) -> NullResource: """ Executes the string at runtime and returns Null""" compile_state.ir.append(CommandNode(string.static_value)) return NullResource()
4785d9a527982eb723d120f47af2915b6b830795
32,324
import torch def fakeLabels(lth): """ lth (int): no of labels required """ label=torch.tensor([]) for i in range(lth): arr=np.zeros(c_dims) arr[0]=1 np.random.shuffle(arr) label=torch.cat((label,torch.tensor(arr).float().unsqueeze(0)),dim=0) return label
a2ffb4a7ff3b71bc789181130bc6042ff184ac9c
32,325
def load_canadian_senators(**kwargs): """ A history of Canadian senators in office.:: Size: (933,10) Example: Name Abbott, John Joseph Caldwell Political Affiliation at Appointment Liberal-Conservative Pro...
42ae6a455d3bed11275d211646ee6acd2da505b6
32,326
def _get_md5(filename): """Return the MD5 checksum of the passed file""" data = open(filename, "rb").read() r = md5(data) return r.hexdigest()
c86943841a1f8f8e296d82818c668c197f824373
32,327
def implements(numpy_func_string, func_type): """Register an __array_function__/__array_ufunc__ implementation for Quantity objects. """ def decorator(func): if func_type == "function": HANDLED_FUNCTIONS[numpy_func_string] = func elif func_type == "ufunc": HANDL...
ec0d843798c4c047d98cd9a76bcd862c3d5339e8
32,328
def r2(data1, data2): """Return the r-squared difference between data1 and data2. Parameters ---------- data1 : 1D array data2 : 1D array Returns ------- output: scalar (float) difference in the input data """ ss_res = 0.0 ss_tot = 0.0 mean = sum(data1) / l...
d42c06a5ad4448e74fcb1f61fa1eed1478f58048
32,329
from typing import IO def fio_color_hist_fio(image_fio): """Generate a fileIO with the color histogram of an image fileIO :param image_fio: input image in fileIO format :type image_fio: fileIO :return: color histogram of the input image in fileIO format :rtype: fileIO """ image_fio.seek(0...
13c10cce5dc9bfa17d19a4b2f486fb7b34bcb176
32,330
def lattice2d_fixed_env(): """Lattice2DEnv with a fixed sequence""" seq = 'HHHH' return Lattice2DEnv(seq)
664b6b411a47018c460b09909ccb29c033bae2e5
32,332
import time import logging def expected_full( clr, view_df=None, smooth_cis=False, aggregate_smoothed=False, smooth_sigma=0.1, aggregate_trans=False, expected_column_name="expected", ignore_diags=2, clr_weight_name='weight', chunksize=10_...
5f387c71f059cd942ff1ff4b6cdb6a59e91ef85b
32,333
def nmgy2abmag(flux, flux_ivar=None): """ Conversion from nanomaggies to AB mag as used in the DECALS survey flux_ivar= Inverse variance oF DECAM_FLUX (1/nanomaggies^2) """ lenf = len(flux) if lenf > 1: ii = np.where(flux>0) mag = 99.99 + np.zeros_like(flux) mag[ii] = 22....
5f65a06049955b4ddfe235d6fc12ae5726089b0f
32,334
def rnn_decoder(dec_input, init_state, cell, infer, dnn_hidden_units, num_feat): """Decoder for RNN cell. Given list of LSTM hidden units and list of LSTM dropout output keep probabilities. Args: dec_input: List of tf.float64 current batch size by number of features matrix tensors input to the decod...
215691ac8b3191da46d01a17fd37e2be08174640
32,335
import torch def l1_loss(pre, gt): """ L1 loss """ return torch.nn.functional.l1_loss(pre, gt)
c552224b3a48f9cde201db9d0b2ee08cd6335861
32,336
def run_tnscope(align_bams, items, ref_file, assoc_files, region=None, out_file=None): """Call variants with Sentieon's TNscope somatic caller. """ if out_file is None: out_file = "%s-variants.vcf.gz" % utils.splitext_plus(align_bams[0])[0] if not utils.file_exists(out_file)...
a7e82dc94a9166bde47ad43dab2c778b2f7945d6
32,337
def get_product(product_id): """ Read a single Product This endpoint will return a product based on it's id """ app.logger.info("Request for product with id: %s", product_id) product = Product.find(product_id) if not product: raise NotFound("product with id '{}' was not found.".forma...
e9ee42be5f586aa0bbe08dfa5edefbd3b0bbc5d7
32,338
import re import string def aips_bintable_fortran_fields_to_dtype_conversion(aips_type): """Given AIPS fortran format of binary table (BT) fields, returns corresponding numpy dtype format and shape. Examples: 4J => array of 4 32bit integers, E(4,32) => two dimensional array with 4 columns and 32 rows....
772bd75ff2af92cede5e5dac555662c9d97c544a
32,339
def account_list(): """获取账户列表""" rps = {} rps["status"] = True account_list = query_account_list(db) if account_list: rps["data"] = account_list else: rps["status"] = False rps["data"] = "账户列表为空" return jsonify(rps)
3ab704e96cbf2c6548bf39f51a7f8c6f77352b6c
32,340
def sample_points_in_range(min_range, max_range, origin, directions, n_points): """Sample uniformly depth planes in a depth range set to [min_range, max_range] Arguments --------- min_range: int, The minimum depth range max_range: int, The maximum depth range origin: tensor(shape=(4, 1),...
6cc33a77e58a573315caf51b907cd881029e7ea1
32,341
from typing import Counter def normalize(vectorOrCounter): """ normalize a vector or counter by dividing each value by the sum of all values """ normalizedCounter = Counter() if type(vectorOrCounter) == type(normalizedCounter): counter = vectorOrCounter total = float(counter.totalC...
8d4cb0f8be4e7c6eeaba6b49d5a84b024f2c91b9
32,342
def IsStringInt(string_to_check): """Checks whether or not the given string can be converted to an int.""" try: int(string_to_check) return True except ValueError: return False
75d83ce78fca205457d4e4325bca80306f248e08
32,343
import torch import math def build_ewc_posterior(data_handlers, mnet, device, config, shared, logger, writer, num_trained, task_id=None): """Build a normal posterior after having trained using EWC. The posterior is constructed as described in function :func:`test`. Args: ...
dd04d235a36516ea600eec154f5a8952ee6ea889
32,345
def get_roc_curve(y_gold_standard,y_predicted): """ Computes the Receiver Operating Characteristic. Keyword arguments: y_gold_standard -- Expected labels. y_predicted -- Predicted labels """ return roc_curve(y_gold_standard, y_predicted)
b522ee6566004ec97781585be0ed8946e8f2889e
32,346
def get_image_unixtime2(ibs, gid_list): """ alias for get_image_unixtime_asfloat """ return ibs.get_image_unixtime_asfloat(gid_list)
2c5fb29359d7a1128fab693d8321d48c8dda782b
32,347
def create_sql_query(mogrify, data_set_id, user_query): """ Creates a sql query and a funtion which transforms the output into a list of dictionaries with correct field names. >>> from tests.support.test_helpers import mock_mogrify >>> query, fn = create_sql_query(mock_mogrify, 'some-collection', Q...
ac56dd8b89da7554111f4e285eb9511fbdef5ced
32,348
def patch_hass(): """ Patch the Hass API and returns a tuple of: - The patched functions (as Dict) - A callback to un-patch all functions """ class MockInfo: """Holds information about a function that will be mocked""" def __init__(self, object_to_patch, function_name, autospec=F...
400bb38ca7f00da3b1a28bc1ab5c2408be2931c9
32,349
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns: ----...
009f637b7ff1d92514711ca5566f2c2c7ee307b0
32,350
def parallax_angle(sc, **kw) -> DEG: """Compute parallax angle from skycoord. Parameters ---------- sc: SkyCoord ** warning: check if skycoord frame centered on Earth Returns ------- p: deg parallax angle """ return np.arctan(1 * AU / sc.spherical.distance)
0d84a98cae93828d1166008fe3d654668a4a178e
32,351
def formatting_dates(dates_list): """ Formatting of both the start and end dates of a historical period. dates = [period_start_date, period_end_date]""" new_dates = dates_list # Change all "BCE" into "BC": for index1 in range(len(new_dates)): if " BCE" not in new_dates[index1]: ...
174617ad0a97c895187f8c1abe7e6eb53f59da6f
32,352
from datetime import datetime def exp_days_f(cppm_class, current_user): """ User's password expiration and check force change password function. 1. Calculates days to expiry password for particular user 2. Checks change password force checkbox. Returns: exp_days: Number of days unt...
e0f014fe4813dd70fd733aa2ed2fa4f06105c2f0
32,353
def isinteger(x): """ determine if a string can be converted to an integer """ try: a = int(x) except ValueError: return False except TypeError: return False else: return True
b39530a79c39f0937a42335587f30bed26c6ce0a
32,354
import hashlib def _get_hash(x): """Generate a hash from a string, or dictionary.""" if isinstance(x, dict): x = tuple(sorted(pair for pair in x.items())) return hashlib.md5(bytes(repr(x), "utf-8")).hexdigest()
c47f96c1e7bfc5fd9e7952b471516fbf40470799
32,357
def wrap_arr(arr, wrapLow=-90.0, wrapHigh=90.0): """Wrap the values in an array (e.g., angles).""" rng = wrapHigh - wrapLow arr = ((arr-wrapLow) % rng) + wrapLow return arr
e07e8916ec060aa327c9c112a2e5232b9155186b
32,358
def task_fail_slack_alert(context): """ Callback task that can be used in DAG to alert of failure task completion Args: context (dict): Context variable passed in from Airflow Returns: None: Calls the SlackWebhookOperator execute method internally """ if ENV != "data": re...
392d5f3b1df21d8dbe239e700b7ea0bd1d44c49f
32,359
def largest_negative_number(seq_seq): """ Returns the largest NEGATIVE number in the given sequence of sequences of numbers. Returns None if there are no negative numbers in the sequence of sequences. For example, if the given argument is: [(30, -5, 8, -20), (100, -2.6, 88, -40, -...
b7326b3101d29fcc0b8f5921eede18a748af71b7
32,360
def align_quaternion_frames(target_skeleton, frames): """align quaternions for blending src: http://physicsforgames.blogspot.de/2010/02/quaternions.html """ ref_frame = None new_frames = [] for frame in frames: if ref_frame is None: ref_frame = frame else: ...
7c8d6f4bacfb3581dc023504b94d2fba66c5e875
32,361
import math def do_round(precision=0, method='common'): """ Round the number to a given precision. The first parameter specifies the precision (default is ``0``), the second the rounding method: - ``'common'`` rounds either up or down - ``'ceil'`` always rounds up - ``'floor'`` always rou...
3e2b4c6c842ca5c3f60951559a815f27cc8edd19
32,362
import torch def scale_invariant_signal_distortion_ratio(preds: Tensor, target: Tensor, zero_mean: bool = False) -> Tensor: """Calculates Scale-invariant signal-to-distortion ratio (SI-SDR) metric. The SI-SDR value is in general considered an overall measure of how good a source sound. Args: pred...
2ec9e4d3cbd0046940974f8d7bae32e230da63ed
32,363
import json from datetime import datetime def is_token_valid(): """Check whether the stored token is still valid. :returns: A bool. """ try: with open('/tmp/tngcli.txt', 'r') as file: for line in file: payload = json.loads(line) except: return Fal...
2574245a38a02bdba7b2fee8f5dff807b128316f
32,364
def DB_getQanswer(question): """ Calls the function in the database that gets the question answer to the input question. """ return DB.get_question_answer(question)
8afb32f1e8b39d3ff89b3c9fe02a314099a416ef
32,365
def _state_senate_slide_preview(slug): """ Preview a state slide outside of the stack. """ context = make_context() resp = _state_senate_slide(slug) if resp.status_code == 200: context['body'] = resp.data return render_template('slide_preview.html', **context) else: ...
c9139df85745feca150fd22591e85165969952de
32,366
def tensor_network_tt_einsum(inputs, states, output_size, rank_vals, bias, bias_start=0.0): # print("Using Einsum Tensor-Train decomposition.") """tensor train decomposition for the full tenosr """ num_orders = len(rank_vals)+1#alpha_1 to alpha_{K-1} num_lags = len(states) batch_size = tf.shape(in...
b9cabf2e76e3b18d73d53968b4578bedc3d7bb7e
32,367
from .observable.case import case_ from typing import Callable from typing import Mapping from typing import Optional from typing import Union def case( mapper: Callable[[], _TKey], sources: Mapping[_TKey, Observable[_T]], default_source: Optional[Union[Observable[_T], "Future[_T]"]] = None, ) -> Observab...
3ecc790a3e6e7e30e4f0a34e06dbfc9e2875388c
32,368
from typing import Tuple import json def group_to_stats(request, project_id) -> Tuple: """ Combining the same actions for grouping data for chart """ filters = json.loads(request.query_params.get('filters', '{}')) # date time, issue type, method group_by = request.query_params.get('groupBy', 'hou...
7a27fa180fd0e1bf059d11bd7995cdea0a85c6cf
32,369