content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging import time from datetime import datetime import pytz def get_raw_temperature(request, pymortar_client, weather_mapping): """Returns temperatures for a given request or None. Guarantees that no Nan values in returned data exist.""" logging.info("received request: %s %s %s %s %s", request.bu...
fd7005911058d70481405e5c82b2bee6d18adff7
65,900
def abs_diff(a, b, base=0): """Absolute value of difference between scalars. abs_diff is symmetric, i.e. `a` and `b` are interchangeable. Args: a: First argument. An int. b: Seconds argument. An int. base: Dummy argument so that the argument signature matches other scalar d...
77d4d4231cd50a6e4cc527979fa806e139759d8f
65,901
def model_name(model): """Return model name given model class.""" # Django supports model._meta -> pylint: disable=W0212 return force_text(model._meta)
62a5e3a2ae757ebad6c8af911d492e44b1f359ec
65,902
def getTitles(db): """ Gets all the books titles in the whole database :param db: database object :return: sorted books titles """ data = [] for book in db.find('books'): data.append(book['Title']) return sorted(data)
f63d2138cef4d2ad51767ad62abacce5169bb3a2
65,903
def mse(x: np.ndarray, y: np.ndarray) -> float: """Mean squared error.""" return float(np.mean((x - y) ** 2))
b72f8717650953c1204319d15952a64c3a9c9b16
65,904
def plot_title(df, title, save_figure=False): """ Plots the skill frequencies of all skill categories for a given title. Params: df: (pandas df) the frequency df title: (str) one of the three job titles: 'data scientist', 'machine learning engineer', 'data engineer' ...
a8e69c6cbb6b7878adddcb843ce80091818392ae
65,905
def overlap(a: Pos, b: Pos, exact: bool = False) -> bool: """Calculate if two positions have overlap.""" if a == b: return True elif exact: return False s0, e0 = a s1, e1 = b if in_interval(s1, s0, e0): return True if in_interval(e1, s0, e0): return True i...
5860d7be034116a3c0017f4bb0221501f8948386
65,906
import string import random def random_string(string_length=10): """Generate a random string of fixed length """ letters = string.ascii_lowercase return "".join(random.choice(letters) for i in range(string_length))
b3b13b593f7818e85f836086b1ea6f445a414c38
65,907
import os def get_parallel_strategy(): """Get parallel strategy by train id.""" train_id = get_train_id(request) profiler_dir = os.path.realpath(os.path.join(settings.SUMMARY_BASE_DIR, train_id)) try: profiler_dir = validate_and_normalize_path(profiler_dir, 'profiler') except ValidationErr...
8ef9140ea65d68cb61210d26e2d78d17d2857019
65,908
from typing import Dict def get_dataset_labeling( dataframe: pd.DataFrame, tag_column: str ) -> Dict[str, int]: """Prepares a mapping using unique values from ``tag_column``. .. code-block:: javascript { "class_name_0": 0, "class_name_1": 1, ... "c...
6a968aa16a0cd3b50607d81162a354c8a3f0538e
65,909
def compute_misalignment_matrix_from_bam(bam_fp, bin_size=None, i_know_what_i_am_doing=False): """Create a matrix of binned mis-alignments :param bam_fp: input BAM :param bin_size: size of bin in mega bases :param i_know_what_i_am_doing: Set this to override the runtime warning of too many bins """ def bi...
f0e92ee274c5a8139ca7183fd8c9b8843725fd34
65,910
def calc_auc(scored_labels, true_label): """Calculates area under the (precision-recall) curve.""" tp = 0 total = 0 for ( _, l, ) in scored_labels: if l == true_label: tp += 1 else: total += tp return float(total) / (tp * (len(scored_labels...
f1e907548d3f5897197e97f7340cf3d7f6645e89
65,911
def give_coordinates(data): """ Get ground-truth coordinates (X,Y,Z, room label) where the measurement was taken, given the JSOn structure as an input. """ message = {} message['true_coordinate_x'] = data['raw_measurement'][1]['receiver_location']['coordinate_x'] message['true_coordinate_y'] = data['raw_m...
d412afbe08d4b1660ab9a12d1e567e4c4e4258fc
65,912
def activate_int8_int8_matrix_multiplications(spec, selector=None): """ Utility function that takes in either a full precision (float) spec or an nbit quantized spec to selectively enable int8 activation + weight quantization of matrix multiplication operations where the second matrix represents a const...
af94b9e737ea222e85f3c12de698e74fbcd4d420
65,913
def filter_comment_lines(line): """Filter variable comment lines.""" if line.startswith(b"#"): return True
6f0441adb79ddf7aebb6466cb6dfdb74c74e1d24
65,914
def update_shipping_profile(profile_id, shipping_profile_id, shipping_form_data): """ Update a customer shipping profile and return the CIMResponse. Arguments: profile_id -- unique gateway-assigned profile identifier shipping_profile_id -- uni...
0d4f180760d0d2628f330128691ad98e3c81d85e
65,915
def orders_by_dow(data_frame): """ Gives orders_count by day of week. :param data_frame: DataFrame containing orders data. :return: DataFrame of order_ids count by day of week. """ grouped = data_frame.groupby(['order_dow'], as_index=False) # count by column: 'order_id' count = grouped.agg(...
bfca97ced614fb8c309f8edc482fc2136914759b
65,916
def is_user_logged(app): """Check for auth_tkt cookies beeing set to see if user is logged in.""" cookies = app.cookies if 'auth_tkt' in cookies and cookies['auth_tkt']: return True return False
67e670fd70787b35bc9b8d9a724512bfc4e7bac8
65,917
from pathlib import Path import numpy as np import nibabel as nb def _fix_topup_fieldcoeff(in_coeff, fmap_ref, refpe_reversed=False, out_file=None): """Read in a coefficients file generated by TOPUP and fix x-form headers.""" if out_file is None: out_file = Path("coefficients.nii.gz").absolute() ...
3a62133034d9e23b4593c5f10f8d048a32a63b8d
65,918
def create_get_service_interface_point_list_by_id(): # noqa: E501 """Create get-service-interface-point-list by ID Create operation of resource: get-service-interface-point-list # noqa: E501 :rtype: GetServiceInterfacePointListRPCOutputSchema """ return 'do some magic!'
2f54434f1ecfe77d50034e50b2c4333f24371a08
65,919
def map_reduce_partitions_nb(a, map_func_nb, map_args, reduce_func_nb, reduce_args): """Map using `map_func_nb` and reduce using `reduce_func_nb` each partition of signals in `a`. `map_func_nb` and `reduce_func_nb` are same as for `map_reduce_between_nb`.""" out = np.full(a.shape[1], np.nan, dtype=np.float...
c424f7fd7b22280fd4ba5df86a2f16a1c55948be
65,920
def lookup(name_in_data, language, metalookup=True, openrefine=False): """ Parameters ---------- name_in_data : str Search string. Returns ------- list = [WDdf, how_matched] WDdf is a dataframe with SPARQL-request how_matched shows how the string was matched ...
866180191de041936f3bf9bae4efb7629eaff62a
65,921
import torch def generate_predictions(model, test_dict): """ Function that is used to obtain the test predictions and metrics """ test_data = test_dict.map( lambda batch: batch_tokenize_preprocess( batch, tokenizer, max_input_length, max_output_length ), batched=Tr...
34074065595bf07db3c0d965235a2a8ef1036f25
65,922
from typing import Dict from typing import Optional def issm_likelihood_computations( precomputed: Dict, issm_params: Dict, r_min: int, r_max: int, skip_c_d: bool = False, profiler: Optional[SimpleProfiler] = None, ) -> Dict: """ Given `precomputed` from `issm_likelihood_precomputation...
5f56b547826abbd096f9d4925aab002586f9621f
65,923
def convert_nodata_to_nans(xarr): """ Args: xarr: Returns: """ nodata_attr = [k for k in xarr.attrs.keys() if k.lower().startswith('nodata')][0] nodata = xarr.attrs[nodata_attr] if nodata: if str(xarr.dtype).startswith('int') or str(xarr.dtype).startswith('uint'): ...
f052c4b34141b0823631a61c1f35f163f84d6ddc
65,924
def Main(operation, args): """ :param operation: :param args: :return: """ # 'init' has to be invokded first after deploying the contract to store the necessary and important info in the blockchain if operation == 'init': return init() if operation == 'name': return name(...
1d69d5b0f05774d9ea1540b55ceff5a0020a8b66
65,925
def test_cache_memoize(cache): """ Test that cache.memoize() caches the return value of a function using a key based on function arguments used. """ marker = 1 @cache.memoize() def func(a, b, c, d): return ((a, b, c, d), marker) args, markx = func(1, 2, 3, 4) assert args ==...
5b93bcab00b334b1c38114f8b700b6ef0d9c3178
65,926
def get_settings_text(poll): """Compile the options text for this poll.""" text = [] locale = poll.user.locale text.append( i18n.t( "settings.poll_type", locale=locale, poll_type=translate_poll_type(poll.poll_type, locale), ) ) text.append(i18...
34ad92078b0d440d5706ce0f8486a0770900dc10
65,927
def static(): """ Returns the live STATIC_ROOT directory. """ return python("from django.conf import settings;" "print(settings.STATIC_ROOT)", show=False).split("\n")[-1]
d6fbb06ed26240881d80189d4f758e3f64902011
65,928
import json def parse_osm_streets(fpath): """ Parses the API response from *fpath* and converts it to a dataframe. Args: fpath (str): File path to read Returns: pandas.DataFrame: Contains all streets as well as their geometries """ # Helper function def convert_to_wkt_geo...
429df1f5015dd2b1c1f0c87a9fe01394b44fa688
65,929
def setpgid(space, pid, pgrp): """ setpgid(pid, pgrp) Call the system call setpgid(). """ try: os.setpgid(pid, pgrp) except OSError, e: raise wrap_oserror(space, e) return space.w_None
c4bdfa143b90a57cf941fe0cc5ef442912708a01
65,930
def obey_reporting_preference(function): """ Do not execute this method if report_errors is disabled, even if someone tells you to! """ def inner(self, *args, **kwargs): if not self.reporting_enabled: return None else: return function(self, *args, **kwargs) ...
c0b38babc999b7bf1ace6821d6079f1afb53e540
65,931
def get_number_of_pages(url): """Function that will scrape for the number of pages with listed apartments available. This number will then be used to generate urls that will be scraped for individual apartments. Args: url (str): Url to first page of listings. Returns: int: The ...
a4ac15e798304d6dd0dd92a30d864426186f6cec
65,932
def paths_edges(random_graph): """Fixture for generating path census data frames for edges and node/global counts based `random_graph` fixture. """ _, P = random_graph E = P.census("edges") return E, P
238dfdc767dccd3b048ca7a2781cc692d289554e
65,933
def interpolate_epsilon(teff, dnu, dnu_threshold=30, epsilon_offset=0.601, epsilon_slope=0.632): """ Calculate the asymptotic phase term. This function computes the value of epsilon for either a main-sequence, subgiant star or a red giant star by exploiting empirical relations linking epsilon with...
d8df11b9be137a650adf4ce65ba337b4356d346c
65,934
def make_celery(app): """ Configure celery for app :param app: flask application instance """ # Create and configure celery celery = Celery(app.import_name) celery.config_from_object('config.CeleryConfig') # Celery task using app context BaseTask = celery.Task class ContextTask...
68e8834d431b734f0d0386ff9cfa7af93f7968a7
65,935
import warnings def cycle_matrix(signals, ampl_bins=10, mean_bins=10, rainflow_func=rainflow_windap): """Markow load cycle matrix Calculate the Markow load cycle matrix Parameters ---------- Signals : array-like or list of tuples - if array-like, the raw signal\n - if list of tup...
bef538efa77a5a704effc07ed32e27e90d9f80c7
65,936
def compare(isamAppliance1, isamAppliance2): """ Compare kerberos configuration realms between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) return tools.json_compare(ret_obj1, ret_obj2, deleted_keys=[])
09e5322ef408ac1d86857a4f3bcc4d48ca0fcef7
65,937
def logout_view(request): """ 注销 :param request: :return: """ logout(request) return redirect('system:login')
d6174cefbfab31d31e72387f6c2577e0399dd93f
65,938
def logout(): """ Logout Route The route to log a user out of the portal Args: None Returns: redirect to the public index page """ logout_user() return redirect(url_for('main.public'))
b75f6cabd8766602d868e09cfff98d1491ea04ce
65,939
def get_nx_graph(sdp_lines, remove_singletons = False): """ Return a networkx graph representation of the conll input. @param remove_singletons: Indicates whether to remove nodes which aren't connected to any other node. """ graph = nx.MultiDiGraph() words, pred...
c3ed5c1765eec6b9e829f3eda3bd27f3f3a1bf79
65,940
def is_in_manifest(dynamodb_client, table_name, run_id): """Check if run_id is stored in DynamoDB table. Return True if run_id is stored or False otherwise. Arguments: dynamodb_client - boto3 DynamoDB client (not service) table_name - string representing existing table name run_id - string repr...
5709dd0ffac71bac29d8b585f43f4ea4d4c190c5
65,941
def audio_slip(signal, delay, overlap=0.5): """ # Audio Slip Args: signal (numpy.ndarray): audio signal. delay (int): value of delay size. overlap (float, optional): overlap rate. Defaults to 0.5. Returns: tuple: list of energy and list of zero crossing rate list. """ ...
35da37bd968052e1cfb33d35e81c23fe25dfc59f
65,942
import json import logging import sys import traceback async def _create_user(): """ Method Name : create_user Parameters : {"userName": Name,"password": password,"firstName":Name,"lastName":Name,"emailId": Mail} This function will create the details of the user in access the software by lo...
9404e5260587b093bb4883e9318a917c0bdf1f6c
65,943
import json def break_bot(): """[Slash command for break punch]""" # break payload blocks = json.loads(""" [ { "type": "header", "text": { "type": "plain_text", "text": "Select your status below:", "emoji": true } }, { "type": "divider" }, { "type": "actions", ...
4664ea206b425a74b2add71b870a9ed904a284dc
65,944
import tqdm def count_destiantions_from_hex( feed: gk.Feed, hex_resolution: int = 8, include_sum: bool = True ) -> pd.DataFrame: """Calculates available directions aggregated to hex. Args: feed (gk.Feed): gtfs feed hex_resolution (int, optional): Defaults to 8. Returns: ...
b41284f9a7b1c8da1f39c9da24af584a9cabdf16
65,945
def extract_gloss(phrase, log=None): """Extract IGT from example.""" if not phrase.find('words'): if log: log.warn("No words in phrase '{}'".format(phrase.attrib.get('guid', '???'))) return {} morph_glosses = list(map(_parse_morph, _find_morphemes(phrase))) gloss = {k: [] f...
fde649961bfdddf961ad8e647af1366c02134685
65,946
def forward_sample(bn, n=1000): """ Approximate marginal probabilities from forward sampling algorithm on a BayesNet object. This algorithm works by repeatedly sampling from the BN and taking the ratio of observations as their marginal probabilities. One sample is done by first sampling from any prior random ...
cd00006c9149b5db504d567f40a931ae49167dfc
65,947
import re def mqtt_wildcard(topic, wildcard): """Returns True if topic matches the wildcard string. """ regex = wildcard.replace('.', r'\.').replace('#', '.*').replace('+', '[^/]*') if re.fullmatch(regex, topic): return True return False
fd7a3a5e8af1e6172decd62f2ba8294dfe07124c
65,948
import _struct def parse_atp_packet(pkt): """Parse a raw ATP packet. pkt -- raw packet data to be parsed. Returns: (kind, flags, seqno, tid, udata, pdata) """ if len(pkt) < ATP_HEADER_LEN + 1: raise ValueError("Invalid packet data: Truncated header") (ddp_tag, kfl, seq, ti...
a14c71006df869ebdc9cc8c5dc475f544385facc
65,949
def make_connection_url(config): """ Returns an SqlAlchemy connection URL based upon values in config dict. Args: config: dict-like object with keys: type, username, password, host, and database. Returns: str URL which SqlAlchemy can use to connect to a database. """...
d7dbd16184efe17355230b59e1157c7dfe164351
65,950
def make_df_from_csv(fname): """Make df""" df = pd.read_csv(fname) df.index = pd.to_datetime(df['DateTime']) df.drop(columns=['DateTime'], inplace=True) return df
8084bd47938d42abbf7a34b016180f0b35deda02
65,951
from datetime import datetime from typing import List def get_obsnums(h5file: h5py.File, start_date: datetime.datetime = None, end_date: datetime.datetime = None, rcu_modes: List[int] = None, station_name: str = None, subband: int = None,...
124ba13a82baf01f502b3fca46e19b66fa46713d
65,952
def build_table_row(obj,admin_class): """生成一条记录的html element""" ele = "" for column_name in admin_class.list_display: column_obj = admin_class.model._meta.get_field(column_name) if column_obj.choices: #get_xxx_display column_data = getattr(obj,'get_%s_display'% column_name)() ...
1aaa614cd3a118b3d5d5a55d311f9cf55e222706
65,953
import re import string def sanitize_name(name): """ Sanitizes the given name such that it conforms to unix policy. Args: name: the name to sanitize. Returns: The sanitized form of name. """ if len(name) == 0: raise Exception("Can not sanitize an empty field.") ...
5b85146c529e37924dd045cc52014cd2c05b9aaa
65,954
import optparse import os import logging import re import sys def ParseOpts(): """Parses the command line arguments and returns a dictionary of flags.""" parser = optparse.OptionParser() default_credentials_file = os.path.join(os.environ['HOME'], '.tracker2gcal-auth.in...
17056064ba571403cc876f7210728357e1d7916c
65,955
from re import T import functools def deco_factory_retry(retry_exceptions=None, max_retries: int = 3, enable_default=False, default=None, exception_predicate: T.Callable[[Exception], bool] = None, exception_queue: T.QueueType = None) -> T.Decorator:...
5bd03aef00de70438915745204d0d61800953204
65,956
import pickle def run_ns( dd_s: DynamicDress, base_path: str, rho_6T_min, rho_6T_max, dM_chirp_abs, gamma_s, rho_6T, ) -> Results: """ Runs nested sampling for a dark dress system given a signal system dd_s. Saves results and posterior plots. """ # Setup gamma_s_ran...
7e8aa245a25f5b2fccf44145e00b3342d5b77b34
65,957
import tempfile import shutil def process_nxml(nxml_filename, pmid=None, extra_annotations=None, **kwargs): """Process an NXML file using the ISI reader First converts NXML to plain text and preprocesses it, then runs the ISI reader, and processes the output to extract INDRA Statements. Parameters ...
620c9b972642e095f9d9ad4ae9f4b51092468283
65,958
def distinct_brightness(dictionary): """Given the brightness dictionary returns the dictionary that has no items with the same brightness.""" distinct, unique_values = {}, set() for char, brightness in dictionary.items(): if brightness not in unique_values: distinct[char] = brightnes...
7f7bb5dba9bab113e15cc4f90ddd4dfda7bb5f01
65,959
import os def subset_variant_regions(variant_regions, region, out_file): """Return BED file subset by a specified chromosome region. variant_regions is a BED file, region is a chromosome name or tuple of (name, start, end) for a genomic region. """ if region is None: return variant_region...
db4ae89b0833bbaf51a6bab0199a3510af9cb15c
65,960
def hash_file(fpath, blocksize=65536, stride=1, hasher=NoParam, hashlen=NoParam, base=NoParam): """ Hashes the data in a file on disk. The results of this function agree with the standard UNIX commands (e.g. sha1sum, sha512sum, md5sum, etc...) Args: fpath (PathLike): ...
78764a14c2d1604e5662e1ad957f1c1c210b38cf
65,961
def start(start): """Start""" # Create the Session session = Session(engine) # Query the data results = session.query(func.min(Measurement.tobs), func.max(Measurement.tobs), func.avg(Measurement.tobs))\ .filter(Measurement.date >= start)\ .all() # Convert the tuples into a normal list...
a82b675f72fe8ebf91e1f569e933868405ce53df
65,962
def _cc_library_func(ctx, name, hdrs, srcs, copts, dep_ccinfos): """Like cc_library(), but callable from rules. Args: ctx: Rule context. name: Unique name used to generate output files. hdrs: Public headers that can be #included from other rules. srcs: C/C++ source files. dep_ccin...
b4372ce07ae967f9bb1011e6c3fa9922fa68a568
65,963
def get_interaction_extension_pos(frame, primary): """Get the maximum extension position of the interaction/cascade of the first interaction of the primary particle. Parameters ---------- frame : current frame Needed to retrieve I3MCTree primary : I3Particle The particle for whi...
f6ae4023bd2b7d48fc83f70a803a555bb217b3ca
65,964
import re def clean_str(string): """ Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py """ string = re.sub(r"[^A-Za-z0-9(),\+!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) st...
7151767d754ebf4591f30762f8708fe464954ba6
65,965
def import_string(dotted_path): """ Stolen approximately from django. Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import fails. """ try: module_path, class_name = dotted_path.strip(' ').rsplit('.', 1) except...
3f8ed0fca9c56fcb11458a4a76fd31593cf2fc0a
65,966
def mean_filter( array, support, half_width=0, width_z=None, width_y=None, width_x=None, vmin=np.nan, vmax=np.nan, title="Object", debugging=False, ): """ Apply a mean filter to an object defined by a support. Only voxels belonging to the object are taken into accoun...
6ea0d7349ae4eb6a97451b1ea4466aee81658e0c
65,967
def get(cmd, resource_group_name=None, workspace_name=None): """ Get the details of the given (or current) Azure Quantum workspace. """ client = cf_workspaces(cmd.cli_ctx) info = WorkspaceInfo(cmd, resource_group_name, workspace_name, None) if (not info.resource_group) or (not info.name): ...
076c382cee4ced54e206513c54663fd00603cef6
65,968
def get_HNet_D(reactions, compounds): """Representing a metabolic pathway as a bipartite graph and returns the graph resulting from the projection of the bipartite graph on its set of reactions. :param reactions: dict of dicts storing reaction information (obtained by parsing a KGML file) :...
f2db776a2ff99b6b8da928da98f331b51d8172cb
65,969
def debugger_products_list_select_related(): """Run debugger queries for products_list_select_related function.""" return debugger_queries(products_list_select_related)()
e6ed289f8e90c50743cfd197132d1b329ca75d15
65,970
import os def read_config( vkey ): """ Read given configuration file from root directoty and returns options from it as a dict. """ conf_dict = read_configuration(os.path.dirname(os.path.abspath(__file__))+'/'+'setup.cfg' ) return conf_dict.get('metadata')[vkey]
56e3ce00cf783c3a87f949f7fa9306f2e658ca4e
65,971
def transition(input_tensor, nb_filter, dropout_rate=None, weight_decay=1e-4): """Apply BatchNorm, Relu 1x1Conv2D, optional dropout and Maxpooling2D. :param input_tensor: keras model :param nb_filter: int -- number of filters :param dropout_rate: int -- dropout rate :param weight_decay: int -- weig...
e2264b36a5caf2e15e69262b8d7df8979dff2815
65,972
import math def weight_variable(shape, name): """Initializes a tensorflow weight variable with random values centered around 0. """ initial = tf.truncated_normal(shape, stddev=1.0 / math.sqrt(float(shape[0])), dtype=tf.float32) return tf.Variable(initial, name=name)
9f8cf6e4e06cf35c5d0fb32ca465b6c3a34b0faf
65,973
from typing import List def get_nouns(spacy_doc: spacy.tokens.Doc) -> List[spacy.tokens.Token]: """Return a list of noun tokens within a given document. Parameters ---------- spacy_doc : spacy.tokens.Doc spaCy document to parse Returns ------- List[spacy.tokens.Token] A l...
b6cb2a5f3c10f18fc5418db241688132e9400a18
65,974
def _matmul_flops_compute(input, other, *, out=None): """ Count flops for the matmul operation. """ macs = _prod(input.shape) * other.shape[-1] return 2 * macs, macs
20a21bbd75d863a47ad273fde866c4749358ab9c
65,975
def calc_hyper_param_importance(df, hyper_param, target): """Calc hyper param importance relative to given target.""" logger.debug("Calculating importance for hyper_param %s, target is %s.", hyper_param, target) new_df = df[[hyper_param, target]] no_missing_value_df = new_df.dropna() # Can not cal...
289252f781f49775d037e68357791988950a516d
65,976
def render(content, for_link_cb=None): """ render the content, which is wiki markup. :param for_link_cb: takes a link and returns the wiki content for it. """ # if content is None or content is '': # return '' if content is None or content is '': return '' return render_pq(conte...
9482fdd3a744378dc9cc5f83137212049c53a85a
65,977
import torch def norm(x): """ Normalize a tensor to a tensor with unit norm (treating first dim as batch dim) :param x: :return: """ b = x.size()[0] n = torch.norm(x.view(b, -1), p=2, dim=1) while len(n.size()) < len(x.size()): n = n.unsqueeze(1) n.expand_as(x) retu...
b40ba939c80db85e2ac8377b21ea7a17589b1c0f
65,978
def topleftlatlon_from_wkt(wkt_string): """Returns the (lat, lon) of the top-left point of a WKT string.""" wkt_type = wkt_string.split('(', 1)[0].rstrip(' ') coord_string = wkt_string.lstrip(wkt_type + ' (') if wkt_type not in ('POINT', 'LINESTRING', 'POLYGON', 'MULTIPOINT', 'MU...
c26b6eb78d8e9dca3ab38e04470cc025a15db4fa
65,979
import time def __date_since_epoch__(value): """Internal function used for Unix datetime format""" day = time.strftime('%d',time.localtime(value)) month = time.strftime('%m',time.localtime(value)) year = time.strftime('%Y',time.localtime(value)) return day,month,year
34e8ee15f7fa5d6f662a7850b3252a37a3926371
65,980
from typing import Optional def _make_qsub_string( command: str, folder: str, job_name: str = "submitit", tmem: str = "4G", # physical memory limit h_vmem: str = "4G", # virtual memory limit h_rt: str = "00:02:00", # wall time num_gpus: int = 0, smp: int = 1, shell: str = "/bin/bas...
2a0e2416f51b60a54a7113e75b8b885a723ee7d4
65,981
def get_unobs_nd_names(gname): """ For a graph named gname, this method returns a list of the names of its unobserved nodes (i.e., either [], or ["U"] or ["U1", "U2"]) Parameters ---------- gname : str Returns ------- list[str] """ if gname in ["G2", "G3", "G5", "G6", "G10...
3450293f464b1e7cc7ab343888a606bd96d0f094
65,982
def extract_archive(filename, path): """ Extract the contents of the given archive :param filename: The name of the crx file :param path: The path to the crx file :return: Whether the contents of the crx file were extracted successfully or not """ dst_dir = os.path.join(get_script_path(), ...
6307dafb19ddf5cef64dc6022e38cd0a15bf37eb
65,983
import logging def get_commodity_sources(): """ Get a table with prices and emissions manly for 2014. Returns ------- pd.DataFrame Examples -------- >>> get_commodity_sources().loc[2014, 'hard coal']['emission'] * 1000 0.0934 """ logging.info("Get prices and emissions for...
b8648a0c2abd8d02f00fca8fd4b945fb4d5ca6bd
65,984
def criterion_rpc(true_labels, pred_scores, p=1, debug=False): """ Generalised reversed P-Classification with Squared Hinge Loss: \ell_+(v) = 1/p * [1 - pv]_+^2 = [1/sqrt(p) - sqrt(p) * v]_+^2 \ell_-(v) = [1 + v]_+^2 """ if debug: assert len(true_labels.shape) == 2 assert true_la...
aa272e1cbcf7809f71267aaa5a8e4b75fc0ee93b
65,985
from typing import Iterable import sys import subprocess def launch_minecraft(ports, launch_script=DEFAULT_SCRIPT, keep_alive=False, verbose=False): """ Launch Minecraft instances in the background. Function will block until all instances are ready to receive commands. ports - List of ports you want t...
d74b375978145e7dd4e04b60d69e0ab5a403aa45
65,986
def named_entity(docs): """Creates a named entity visualization. Taken from https://github.com/wandb/client/blob/master/wandb/plots/named_entity.py """ spacy = util.get_module( "spacy", required="part_of_speech requires the spacy library, install with `pip install spacy`", ) ut...
e217e244ceef03e62decfdcfb1985171733eedea
65,987
def brightness_state(value): """ Returns the brightness and state according to the current data of given value. """ if value.data > 0: return (value.data / 99) * 255, STATE_ON else: return 255, STATE_OFF
c8e6e8dfcf27bd62164478dbf1d899727246329e
65,988
def find_matching_segments(gt_segments, id_key, sensed_segments): """ id_key represents the kind of segment that we are find matches for. e.g. - trip_id for trips - section_id for sections """ matching_segments_map = {} if len(sensed_segments) == 0: print("Found no sensed segmen...
e94f26b335d1c42af9a8fd1182dbee986543bb80
65,989
from typing import List def recall_at_k(y_true: List[int], y_pred: List[List[np.ndarray]], k: int): """ Calculates recall at k ranking metric. Args: y_true: Labels. Not used in the calculation of the metric. y_predicted: Predictions. Each prediction contains ranking score of a...
cecf2ec6fc3e0d071672c096f42063a3962e081e
65,990
def has_datapoint_with_all_dims(fake_ingest, dims): """ Tests if any datapoints has all of the given dimensions """ for datapoint in fake_ingest.datapoints: if has_all_dims(datapoint, dims): return True return False
9c3ed9ab42d6ac5eae80c30aaf6b8d123520601d
65,991
def norm_weight(nin, nout=None, scale=0.01, ortho=True, **kwargs): """ Get a (orthogonal) Gaussian weight matrix W, scaled if desired (and not orthogonal). :param nin: :param nout: :param scale: :param ortho: :return W: """ logger.warn('Norm weight with range: +/-{}'.format(scale...
ce8120ec5e9a65bcfc5862bb95706b619049d194
65,992
def key_is_private(key): """Determine if a key has a name indicating it is private """ if PRIVATE_RE.search(key): return True else: return False
99809e5e0ea1e87b9deb7d01c01d2f9a83b73edc
65,993
def anonymise_related_objects(obj, anonymised=None): """ See if there are any related models which need to be anonymised. They will be any reverse relations to PrivacyModel subclasses where their OneToOneField and ForeignKey on_delete is ANONYMISE. """ if anonymised is None: anonymised ...
d1f168dbb42df28c44b19e2b7cae86c672d8794e
65,994
from datetime import datetime import os def register_global_func(app): """register function for jinja """ @app.template_global() def current_year(): return datetime.now().year @app.template_global() def is_start(): return Competition.is_start() @app.template_global() ...
388848924bc2b2abe18bdd0a0b5f3822737c6e0f
65,995
import matplotlib.pyplot as plt from matplotlib import ticker def plot_evoked_joint(evoked, times="peaks", title='', picks=None, exclude=None, show=True, ts_args=None, topomap_args=None): """Plot evoked data as butterfly plot and add topomaps for time points. Param...
f810e7092bff0ed8fd6378f45306d2d60bb95761
65,996
import inspect def all_links(cls): """ Each object will have the attributes declared directly on the object in the attrs dictionary. In addition there may be attributes declared by a particular object's parent classes. This function walks the class hierarchy to collect the attrs in the object's parent...
2e3b1e4e527d339b0972345c81b6967857e54298
65,997
from typing import Dict from typing import Callable def get_losses_dict( names_list: list = [], ) -> Dict[str, Callable]: """Get a dict with all the loss functions for semi supervised training. The training step of a given model will iterate over these, instead of manually computing each. Args: ...
9d6906b1a654b4e09d5a39753bf2e1955dd535ad
65,998
def prepare(data, args): """ Run trimming and fastq for each fastq file """ workdir = op.abspath(safe_makedir("prepare")) sample = data['name'] data['trimmed'] = _trimming(data['fastq'], workdir, data['name'], args.is_rrbs, args.is_directional) return data
79eed3f800acbf1d1ceb140913e1a10679053043
65,999