content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def import_odim_hdf5(filename, **kwargs): """Import a precipitation field (and optionally the quality field) from a HDF5 file conforming to the ODIM specification. Parameters ---------- filename : str Name of the file to import. Other Parameters ---------------- qty : {'RATE', ...
650875bb3d04627f4570507892ee26b42912c39e
3,641,329
def sugerir(update: Update, _: CallbackContext) -> int: """Show new choice of buttons""" query = update.callback_query query.answer() keyboard = [ [ InlineKeyboardButton("\U0001F519 Volver", callback_data=str(NINE)), InlineKeyboardButton("\U0001F44B Salir", callba...
e278c6bdab82e4fdfc38c7a4bb58a5511a003515
3,641,330
def clone_subgraph(*, outputs, inputs, new_inputs, suffix="cloned"): """ Take all of the tensorflow nodes between `outputs` and `inputs` and clone them but with `inputs` replaced with `new_inputs`. Args: outputs (List[tf.Tensor]): list of output tensors inputs (List[tf.Tensor]): list of...
b61d73d79635551f8277cbc0c2da97d0c5c2908e
3,641,331
async def refresh_replacements(db, sample_id: str) -> list: """ Remove sample file `replacement` fields if the linked files have been deleted. :param db: the application database client :param sample_id: the id of the sample to refresh :return: the updated files list """ files = await virt...
43667801bf6bb96edbeb59bf9d538b62c9bf9785
3,641,332
def torch_model (model_name, device, checkpoint_path = None): """ select imagenet models by their name and loading weights """ if checkpoint_path: pretrained = False else: pretrained = True model = models.__dict__ [model_name](pretrained) if hasattr (model, 'classifier'): ...
831cf1edd83b76049e7f6d60434961cbd44e4bd9
3,641,333
from typing import Tuple from datetime import datetime def get_timezone() -> Tuple[datetime.tzinfo, str]: """Discover the current time zone and it's standard string representation (for source{d}).""" dt = get_datetime_now().astimezone() tzstr = dt.strftime("%z") tzstr = tzstr[:-2] + ":" + tzstr[-2:] ...
f73cedb8fb91c75a19104d4d8bef29f73bfb9b1a
3,641,334
def get_timed_roadmaps_grid_common( ins: Instance, T: int, size: int, ) -> list[TimedRoadmap]: """[deprecated] get grid roadmap shared by all agents Args: ins (Instance): instance T (int): assumed makespan size (int): size x size grid will be constructed Returns: list[n...
9b8e283ad66db35132393b53af2bfa36fc4aaf83
3,641,337
def arithmetic_series(a: int, n: int, d: int = 1) -> int: """Returns the sum of the arithmetic sequence with parameters a, n, d. a: The first term in the sequence n: The total number of terms in the sequence d: The difference between any two terms in the sequence """ return n * (2 * a + (n - 1...
168f0b07cbe6275ddb54c1a1390b41a0f340b0a6
3,641,338
import re def get_arc_proxy_user(proxy_file=None): """ Returns the owner of the arc proxy. When *proxy_file* is *None*, it defaults to the result of :py:func:`get_arc_proxy_file`. Otherwise, when it evaluates to *False*, ``arcproxy`` is queried without a custom proxy file. """ out = _arc_proxy...
01f1040cd1217d7722a691a78b5884125865cf39
3,641,339
def pass_hot_potato(names, num): """Pass hot potato. A hot potato is sequentially passed to ones in a queue line. After a number of passes, the one who got the hot potato is out. Then the passing hot potato game is launched againg, until the last person is remaining one. """ name_queue = Queue() for name in n...
f78a635bdf3138809329ef8ad97934b125b9335a
3,641,340
import copy def convert_timeseries_dataframe_to_supervised(df: pd.DataFrame, namevars, target, n_in=1, n_out=0, dropT=True): """ Transform a time series in dataframe format into a supervised learning dataset while keeping dataframe intact. Returns the transformed pandas DataFrame, the name of the targ...
b62296680f6a871f20078e55eefa20f09392b012
3,641,341
def build_graph(adj_mat): """build sparse diffusion graph. The adjacency matrix need to preserves divergence.""" # sources, targets = adj_mat.nonzero() # edgelist = list(zip(sources.tolist(), targets.tolist())) # g = Graph(edgelist, edge_attrs={"weight": adj_mat.data.tolist()}, directed=True) g = Gr...
bdc8dc5d1c107086c4c548b500f6958bdbe48103
3,641,342
def retrieve_context_path_comp_service_end_point_end_point(uuid): # noqa: E501 """Retrieve end-point Retrieve operation of resource: end-point # noqa: E501 :param uuid: ID of uuid :type uuid: str :rtype: List[str] """ return 'do some magic!'
e3169e139b5992daf00411b694cf77436fb17fba
3,641,343
def get_external_repos(gh): """ Get all external repositories from the `repos.config` file """ external_repos = [] with open("repos.config") as f: content = f.readlines() content = [x.strip() for x in content] for entry in content: org_name, repo_name = entry.sp...
a83515acd77c7ef9e30bf05d8d4478fa833ab5bc
3,641,344
import json def load_fit_profile(): """ This methods return the FIT profile types based on the Profile.xslx that is included in the Garmin FIT SDK (https://developer.garmin.com/fit/download/). The returned profile can be used to translate e.g. Garmin product names to their corresponding integer product id...
13108546c2d88d77d090b222c1b3ff2b59208310
3,641,346
def mmethod(path, *args, **kwargs): """ Returns a mapper function that runs the path method for each instance of the iterable collection. >>> mmethod('start') is equivalent to >>> lambda thread: thread.start() >>> mmethod('book_set.filter', number_of_pages__gte=100) is equivalent to ...
6ded620d190d338d981c433514018a4182b7e207
3,641,347
def generate_test_demand_design_image() -> TestDataSet: """ Returns ------- test_data : TestDataSet 2800 points of test data, uniformly sampled from (price, time, emotion). Emotion is transformed into img. """ org_test: TestDataSet = generate_test_demand_design(False) treatment = org...
238cf11480e0d23f30b426ed19877126edc010fa
3,641,348
def value_iteration(game, depth_limit, threshold): """Solves for the optimal value function of a game. For small games only! Solves the game using value iteration, with the maximum error for the value function less than threshold. This algorithm works for sequential 1-player games or 2-player zero-sum games,...
2a9ae3903666ee16e86fe30a0458707394fe4695
3,641,349
def _import_and_infer(save_dir, inputs): """Import a SavedModel into a TF 1.x-style graph and run `signature_key`.""" graph = ops.Graph() with graph.as_default(), session_lib.Session() as session: model = loader.load(session, [tag_constants.SERVING], save_dir) signature = model.signature_def[ sign...
1610c4d52fa8d18a770f1f347b9cd30b4652ab8b
3,641,351
def nth(seq, idx): """Return the nth item of a sequence. Constant time if list, tuple, or str; linear time if a generator""" return get(seq, idx)
cca44dca33d19a2e0db355be525009dce752445c
3,641,354
def _build_discretize_fn(value_type, stochastic, beta): """Builds a `tff.tf_computation` for discretization.""" @computations.tf_computation(value_type, tf.float32, tf.float32) def discretize_fn(value, scale_factor, prior_norm_bound): return _discretize_struct(value, scale_factor, stochastic, beta, ...
75f9f50ec376b1a10b5fcb629527a873b8768235
3,641,356
def expand_mapping_target(namespaces, val): """Expand a mapping target, expressed as a comma-separated list of CURIE-like strings potentially prefixed with ^ to express inverse properties, into a list of (uri, inverse) tuples, where uri is a URIRef and inverse is a boolean.""" vals = [v.strip() for...
b4a4f08d39728c8f61b7b373a521890f88d6f912
3,641,357
def home(request): """Handle the default request, for when no endpoint is specified.""" return Response('This is Michael\'s REST API!')
a37a2eaa68366de4d8542357c043c4e29ac7a9f9
3,641,358
def create_message(sender, to, subject, message_text, is_html=False): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. Returns: ...
2b5dc225df5786df9f2650631d209c53e3e8145b
3,641,359
def get_agent(runmode, name): # noqa: E501 """get_agent # noqa: E501 :param runmode: :type runmode: str :param name: :type name: str :rtype: None """ return 'do some magic!'
065302bb7793eff12973208db5f35f3494a83930
3,641,360
def find_splits(array1: list, array2: list) -> list: """Find the split points of the given array of events""" keys = set() for event in array1: keys.add(event["temporalRange"][0]) keys.add(event["temporalRange"][1]) for event in array2: keys.add(event["temporalRange"][0]) ...
c52f696caddf35fa050621e7668eec06686cee14
3,641,361
def to_subtask_dict(subtask): """ :rtype: ``dict`` """ result = { 'id': subtask.id, 'key': subtask.key, 'summary': subtask.fields.summary } return result
5171d055cc693b1aa00976c063188a907a7390dc
3,641,362
from typing import Tuple from typing import Optional def _partition_labeled_span( contents: Text, labeled_span: substitution.LabeledSpan ) -> Tuple[substitution.LabeledSpan, Optional[substitution.LabeledSpan], Optional[substitution.LabeledSpan]]: """Splits a labeled span into first line, intermediate...
6f22341d32c03ba0057fbfd6f08c88ac8736220f
3,641,363
def is_active(relation_id: RelationID) -> bool: """Retrieve an activation record from a relation ID.""" # query to DB try: sups = db.session.query(RelationDB) \ .filter(RelationDB.supercedes_or_suppresses == int(relation_id)) \ .first() except Exception as e: rais...
352f44e2f025ac0918519d0fe8e513b3871be7b9
3,641,364
def vectorize_with_similarities(text, vocab_tokens, vocab_token_to_index, vocab_matrix): """ Generate a vector representation of a text string based on a word similarity matrix. The resulting vector has n positions, where n is the number of words or tokens in the full vocabulary. The value at each position indicate...
5b843ffbfdefbf691fb5766bbe6772459568cf78
3,641,365
def get_puppet_node_cert_from_server(node_name): """ Init environment to connect to Puppet Master and retrieve the certificate for that node in the server (if exists) :param node_name: Name of target node :return: Certificate for that node in Puppet Master or None if this information has not been found ...
7f7fa2164bf7f289ce9dbc1b35f2d8aea546bb60
3,641,366
from typing import Optional def get_notebook_workspace(account_name: Optional[str] = None, notebook_workspace_name: Optional[str] = None, resource_group_name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> Awaitabl...
d9020323c0ea520951730a31b2f457ab80fcc931
3,641,367
def get_current_player(player_one_turn: bool) -> str: """Return 'player one' iff player_one_turn is True; otherwise, return 'player two'. >>> get_current_player(True) 'player one' >>> get_current_player(False) 'player two' """ if player_one_turn: return P1 else: retu...
6bade089054513943aef7656972cadd2d242807c
3,641,368
def is_word(s): """ String `s` counts as a word if it has at least one letter. """ for c in s: if c.isalpha(): return True return False
524ed5cc506769bd8634a46d346617344485e5f7
3,641,370
def index_all_messages(empty_index): """ Expected index of `initial_data` fixture when model.narrow = [] """ return dict(empty_index, **{'all_msg_ids': {537286, 537287, 537288}})
ea2c59a4de8e62d2293f87e26ead1b4c15f15a11
3,641,371
def compute_affine_matrix(in_shape, out_shape, crop=None, degrees=0.0, translate=(0.0, 0.0), flip_h=False, flip_v=False, resize=False, ...
0c3786c44d35341e5e85d3756e50eb59dd473d64
3,641,372
def Bern_to_Fierz_nunu(C,ddll): """From semileptonic Bern basis to Fierz semileptonic basis for Class V. C should be the corresponding leptonic Fierz basis and `ddll` should be of the form 'sbl_enu_tau', 'dbl_munu_e' etc.""" ind = ddll.replace('l_','').replace('nu_','') return { 'F' + in...
4f08f79d6614c8929c3f42096fac71b04bfe7b4b
3,641,373
def enforce_boot_from_volume(client): """Add boot from volume args in create server method call """ class ServerManagerBFV(servers.ServerManager): def __init__(self, client): super(ServerManagerBFV, self).__init__(client) self.bfv_image_client = images.ImageManager(client) ...
4ae4d2624f216c96722e811d9d44cb04caa46e1d
3,641,374
def img_to_yuv(frame, mode, grayscale=False): """Change color space of `frame` from any supported `mode` to YUV Args: frame: 3-D tensor in either [H, W, C] or [C, H, W] mode: A string, must be one of [YV12, YV21, NV12, NV21, RGB, BGR] grayscale: discard uv planes return: ...
002506b3a46fa6b601f4ca65255c8f06b990992d
3,641,375
def assemblenet_kinetics600() -> cfg.ExperimentConfig: """Video classification on Videonet with assemblenet.""" exp = video_classification.video_classification_kinetics600() feature_shape = (32, 224, 224, 3) exp.task.train_data.global_batch_size = 1024 exp.task.validation_data.global_batch_size = 32 exp.ta...
3356b6ea758baf04cc98421d700f25e342884d5a
3,641,376
import math import torch def channel_selection(inputs, module, sparsity=0.5, method='greedy'): """ 현재 모듈의 입력 채널중, 중요도가 높은 채널을 선택합니다. 기존의 output을 가장 근접하게 만들어낼 수 있는 입력 채널을 찾아냅니댜. :param inputs: torch.Tensor, input features map :param module: torch.nn.module, layer :param sparsity: float, 0 ~ 1 h...
957cbcc799185fd6c2547662bfe79205389d44da
3,641,377
import six def format_host(host_tuple): """ Format a host tuple to a string """ if isinstance(host_tuple, (list, tuple)): if len(host_tuple) != 2: raise ValueError('host_tuple has unexpeted length: %s' % host_tuple) return ':'.join([six.text_type(s) for s in host_t...
f4822aec5143a99ccc52bb2657e1f42477c65400
3,641,378
import psutil def get_cpu_stats(): """ Obtains the system's CPU status. :returns: System CPU static. """ return psutil.cpu_stats()
f538977db72083f42c710faa987a97511959c973
3,641,379
def get_minmax_array(X): """Utility method that returns the boundaries for each feature of the input array. Args: X (np.float array of shape (num_instances, num_features)): The input array. Returns: min (np.float array of shape (num_features,)): Minimum values for each feature in array. ...
5453371759af5bf6d876aa8fe5d2caf88ee6eb08
3,641,383
def getAllHeaders(includeText=False): """ Get a dictionary of dream numbers and headers. If includeText=true, also add the text of the dream to the dictionary as 'text' (note that this key is all lowercase so it will not conflict with the usual convention for header names, even if "Text" would be an...
2bbd78d9c9cbfaa50a62e99c25148844d7c5e330
3,641,384
def zscore(arr, period): """ ZScore transformation of `arr` for rolling `period.` ZScore = (X - MEAN(X)) / STDEV(X) :param arr: :param period: :return: """ if period <= 0: raise YaUberAlgoArgumentError("'{}' must be positive number".format(period)) # Do quick sanity checks of a...
8a49afe3ecefc326b3bd889279085cccd1d19a61
3,641,385
import glob import pandas def _load_event_data(prefix, name): """Load per-event data for one single type, e.g. hits, or particles. """ expr = '{!s}-{}.csv*'.format(prefix, name) files = glob.glob(expr) dtype = DTYPES[name] if len(files) == 1: return pandas.read_csv(files[0], header=0, ...
04b2e4a7483ba56fdd282dc6355e9acb2d6da7b1
3,641,386
from datetime import datetime def check_file(file_id: str, upsert: bool = False) -> File: """Checks that the file with file_id exists in the DB Args: file_id: The id for the requested file. upsert: If the file doesn't exist create a placeholder file Returns: The file object ...
2f4e94a064d0bdfea8f001855eb39675f78ab6e5
3,641,387
def parse(volume_str): """Parse combined k8s volume string into a dict. Args: volume_str: The string representation for k8s volume, e.g. "claim_name=c1,mount_path=/path1". Return: A Python dictionary parsed from the given volume string. """ kvs = volume_str.split(",") ...
f6984faf90081eb8ca3fbbb8ffaf636b040c7ffc
3,641,388
def longest_common_substring(text1, text2): """最长公共子字符串,区分大小写""" n = len(text1) m = len(text2) maxlen = 0 span1 = (0, 0) span2 = (0, 0) if n * m == 0: return span1, span2, maxlen dp = np.zeros((n+1, m+1), dtype=np.int32) for i in range(1, n+1): for j in range(1, m+1)...
ed892739d22ee0763a2fe5dd44b48b8d1902605e
3,641,389
def make_subclasses_dict(cls): """ Return a dictionary of the subclasses inheriting from the argument class. Keys are String names of the classes, values the actual classes. :param cls: :return: """ the_dict = {x.__name__:x for x in get_all_subclasses(cls)} the_dict[cls.__name__] = cls ...
36eb7c9242b83a84fcd6ee18b4ca9297038f9ee6
3,641,390
import time def _parse_realtime_data(xmlstr): """ Takes xml a string and returns a list of dicts containing realtime data. """ doc = minidom.parseString(xmlstr) ret = [] elem_map = {"LineID": "id", "DirectionID": "direction", "DestinationStop": "destination" } ack = _singl...
90958c7f66072ecfd6c57b0da95293e35196354c
3,641,391
def tocopo_accuracy_fn(tocopo_logits: dt.BatchedTocopoLogits, target_data: dt.BatchedTrainTocopoTargetData, oov_token_id: int, pad_token_id: int, is_distributed: bool = True) -> AccuracyMetrics: """Computes accuracy metrics. ...
828b7d3db40d488a7e05bbfe1f3d2d94f58d8efa
3,641,392
def cols_from_html_tbl(tbl): """ Extracts columns from html-table tbl and puts columns in a list. tbl must be a results-object from BeautifulSoup)""" rows = tbl.tbody.find_all('tr') if rows: for row in rows: cols = row.find_all('td') for i,cell in enumerate(cols): ...
94bef05b782073955738cf7b774af34d64520499
3,641,393
from typing import List from typing import Tuple def get_score_park(board: List[List[str]]) -> Tuple[int]: """ Calculate the score for the building - park (PRK). Score 1: If ONLY 1 park. Score 3: If the park size is 2. Score 8: If the park size is 3. Score 16: If the par...
2bf1629aeb9937dfd871aa118e675cd9358b65ef
3,641,394
def kernel_epanechnikov(inst: np.ndarray) -> np.ndarray: """Epanechnikov kernel.""" if inst.ndim != 1: raise ValueError("'inst' vector must be one-dimensional!") return 0.75 * (1.0 - np.square(inst)) * (np.abs(inst) < 1.0)
7426e068c3a939595b77c129af4f8d30bbfc89fb
3,641,395
def submission_parser(reddit_submission_object): """Parses a submission and returns selected parameters""" post_timestamp = reddit_submission_object.created_utc post_id = reddit_submission_object.id score = reddit_submission_object.score ups = reddit_submission_object.ups downs = reddit_submiss...
d2b406f38e799230474e918df91d55e48d27f385
3,641,396
def dashboard(): """Displays dashboard to logged in user""" user_type = session.get('user_type') user_id = session.get('user_id') if user_type == None: return redirect ('/login') if user_type == 'band': band = crud.get_band_by_id(user_id) display_name = band.display...
1cec9fcd17a963921f23f03478a8c3195db9a18e
3,641,397
from bs4 import BeautifulSoup def parse_site(site_content, gesture_id): """ Parses the following attributes: title, image, verbs and other_gesture_ids :param site_content: a html string :param gesture_id: the current id :return: { title: str, img: str, id: number, compares...
b9719dbbd2ca7883257c53410423de5e3df3fe93
3,641,398
from multiprocessing import Pool import multiprocessing def test_multiprocessing_function () : """Test parallel processnig with multiprocessing """ logger = getLogger ("ostap.test_multiprocessing_function") logger.info ('Test job submission with module %s' % multiprocessing ) ncpus = mu...
a59635b844b4ff80a090a1ec8e3661e340903269
3,641,399
import math def fnCalculate_Bistatic_Coordinates(a,B): """ Calculate the coordinates of the target in the bistatic plane A,B,C = angles in the triangle a,b,c = length of the side opposite the angle Created: 22 April 2017 """ u = a*math.cos(B); v = a*math.sin(B); return u,v
cc1dce6ef0506b987e42e3967cf36ea7b46a30d7
3,641,400
def _fn_lgamma_ ( self , b = 1 ) : """ Gamma function: f = log(Gamma(ab)) >>> f = >>> a = f.lgamma ( ) >>> a = f.lgamma ( b ) >>> a = lgamma ( f ) """ return _fn_make_fun_ ( self , b , Os...
62183327967840e26dfc009c2357de2c31171082
3,641,401
def convolve_smooth(x, win=10, mode="same"): """Smooth data using a given window size, in units of array elements, using the numpy.convolve function.""" return np.convolve(x, np.ones((win,)), mode=mode) / win
b41edf8c0d58355e28b507a96b129c4720412a81
3,641,402
import array def descent(x0, fn, iterations=1000, gtol=10**(-6), bounds=None, limit=0, args=()): """A gradient descent optimisation solver. Parameters ---------- x0 : array-like n x 1 starting guess of x. fn : obj The objective function to minimise. iterations : int Ma...
ec132e7857cf4a941c54fc5db9085bdf013fb7a2
3,641,404
def count_teams_for_party(party_id: PartyID) -> int: """Return the number of orga teams for that party.""" return db.session \ .query(DbOrgaTeam) \ .filter_by(party_id=party_id) \ .count()
07373325dd7d7ab21ef0cb1145d37b2d85292358
3,641,405
def num_series(datetime_series) -> pd.Series: """Return a datetime series with numeric values.""" return datetime_series(LENGTH)
4d208bfbae5f3e7263663d06102aa0b290f4fd4e
3,641,406
import re def obtain_ranks(outputs, targets, mode=0): """ outputs : tensor of size (batch_size, 1), required_grad = False, model predictions targets : tensor of size (batch_size, ), required_grad = False, labels Assume to be of format [1, 0, ..., 0, 1, 0, ..., 0, ..., 0] mode == 0: rank from ...
72fc737d72fe0d6d3ff4e08a5a16acf05e0e88cb
3,641,407
from typing import Dict from typing import Any def sample_a2c_params(trial: optuna.Trial) -> Dict[str, Any]: """ Sampler for A2C hyperparams. """ lr_schedule = trial.suggest_categorical("lr_schedule", ["linear", "constant"]) learning_rate = trial.suggest_loguniform("learning_rate", 1e-5, 1) n_...
f9f966f3c41a32a15253ba612d94e1254a586e86
3,641,408
def location_parser(selected_variables, column): """ Parse the location variable by creating a list of tuples. Remove the hyphen between the start/stop positions. Convert all elements to integers and create a list of tuples. Parameters: selected_variables (dataframe): The dataframe contain...
106f669269276c37652e92e62eb8c2c52dfe7637
3,641,409
import torch import math def get_qmf_bank(h, n_band): """ Modulates an input protoype filter into a bank of cosine modulated filters Parameters ---------- h: torch.Tensor prototype filter n_band: int number of sub-bands """ k = torch.arange(n_band).reshape(-1, 1) ...
87e8cf3b0d85a6717cce9dc09f7a0a3e3581e498
3,641,410
import math def compare_one(col, cons_aa, aln_size, weights, aa_freqs, pseudo_size): """Compare column amino acid frequencies to overall via G-test.""" observed = count_col(col, weights, aa_freqs, pseudo_size) G = 2 * sum(obsv * math.log(obsv / aa_freqs.get(aa, 0.0)) for aa, obsv in observ...
910431062ac9ddef467d4818d3960385a2d4392b
3,641,411
def open(uri, mode='a', eclass=_eclass.manifest): """Open a Blaze object via an `uri` (Uniform Resource Identifier). Parameters ---------- uri : str Specifies the URI for the Blaze object. It can be a regular file too. The URL scheme indicates the storage type: * carray: Ch...
c0a5069f5d7f39c87aae5af361df86b6f4fc4189
3,641,412
def create_df(dic_in, cols, input_type): """ Convert JSON output from OpenSea API to pandas DataFrame :param dic_in: JSON output from OpenSea API :param cols: Keys in JSON output from OpenSea API :param input_type: <TBD> save the columns with dictionaries as entries seperately :return: Cleaned D...
7b6a9445c956cc5d2850516d4c7dc2208b7391f7
3,641,413
def file_updated_at(file_id, db_cursor): """ Update the last time the file was checked """ db_cursor.execute(queries.file_updated_at, {'file_id': file_id}) db_cursor.execute(queries.insert_log, {'project_id': settings.project_id, 'file_id': file_id, 'log_ar...
bb0ec859c249b96e3ed066c3664e792100f5f23c
3,641,414
def action_to_upper(action): """ action to upper receives an action in pddl_action_representation, and returns it in upper case. :param action: A action in PddlActionRepresentation :return: PddlActionRepresentation: The action in upper case """ if action: action.name = action.name.uppe...
e9266ad79d60a58bf61d6ce81284fa2accbb0b8d
3,641,415
from typing import Type from typing import Dict from typing import Any def generate_model_example(model: Type["Model"], relation_map: Dict = None) -> Dict: """ Generates example to be included in schema in fastapi. :param model: ormar.Model :type model: Type["Model"] :param relation_map: dict wit...
1aafb069ff129453f9012de79d09c326224ceb5b
3,641,417
def compare_folder(request): """ Creates the compare folder path `dione-sr/tests/data/test_name/compare`. """ return get_test_path('compare', request)
b78bc261373d47bd3444c24c54c57a600a3855ad
3,641,418
def _get_param_combinations(lists): """Recursive function which generates a list of all possible parameter values""" if len(lists) == 1: list_p_1 = [[e] for e in lists[0]] return list_p_1 list_p_n_minus_1 = _get_param_combinations(lists[1:]) list_p_1 = [[e] for e in lists[0]] list_...
b4903bea79aebeabf3123f03de986058a06a21f4
3,641,419
def system_mass_spring_dumper(): """マスバネダンパ系の設計例""" # define the system m = 1.0 k = 1.0 c = 1.0 A = np.array([ [0.0, 1.0], [-k/m, -c/m] ]) B = np.array([ [0], [1/m] ]) C = np.eye(2) D = np.zeros((2,1),dtype=float) W = np.diag([1.0, 1.0]) ...
8a054753d7bbaa06b7217ce98d38074122d41f32
3,641,420
import requests def get_green_button_xml( session: requests.Session, start_date: date, end_date: date ) -> str: """Download Green Button XML.""" response = session.get( f'https://myusage.torontohydro.com/cassandra/getfile/period/custom/start_date/{start_date:%m-%d-%Y}/to_date/{end_date:%m-%d-%Y}/f...
2ed71202a40214b75007db7b16d5c1806ae35406
3,641,422
def calculateSecFromEpoch(date,hour): """ Calculates seconds from EPOCH """ months={ '01':'Jan', '02':'Feb', '03':'Mar', '04':'Apr', '05':'May', '06':'Jun', '07':'Jul', '08':'Aug', '09':'Sep', '10':'Oct', '11':'Nov', '12':'Dec' } year=YEAR_PREFIX+date[0:2] month=months[date[2:4]] day=d...
29adf78dbe795c70cb84f66b1dc249674869c417
3,641,423
def star_noise_simulation(Variance, Pk, nongaussian = False): """simulates star + noise signal, Pk is hyperprior on star variability and flat at high frequencies which is stationary noise""" Pk_double = np.concatenate((Pk, Pk)) phases = np.random.uniform(0, 2 * np.pi, len(Pk)) nodes0 = np.sqrt(Pk_double...
5ccc89f455b7347c11cac36abead172b352f7b9c
3,641,424
from datetime import datetime import time def get_seq_num(): """ Simple class for creating sequence numbers Truncate epoch time to 7 digits which is about one month """ t = datetime.datetime.now() mt = time.mktime(t.timetuple()) nextnum = int(mt) retval = nextnum % 10000000 return ...
34a2b3a7082d061987c7a0b67c91df040b86938c
3,641,425
import logging def get_packages_for_file_or_folder(source_file, source_folder): """ Collects all the files based on given parameters. Exactly one of the parameters has to be specified. If source_file is given, it will return with a list containing source_file. If source_folder is given, it will searc...
fc047dd10dfd18fc8efecb240d06aeb91686c0cb
3,641,426
def sanitize_tag(tag: str) -> str: """Clean tag by replacing empty spaces with underscore. Parameters ---------- tag: str Returns ------- str Cleaned tag Examples -------- >>> sanitize_tag(" Machine Learning ") "Machine_Learning" """ return tag.strip().rep...
40ac78846f03e8b57b5660dd246c8a15fed8e008
3,641,427
def _vmf_normalize(kappa, dim): """Compute normalization constant using built-in numpy/scipy Bessel approximations. Works well on small kappa and mu. """ num = np.power(kappa, dim / 2.0 - 1.0) if dim / 2.0 - 1.0 < 1e-15: denom = np.power(2.0 * np.pi, dim / 2.0) * i0(kappa) else: ...
24d22469a572e7ff4b7e1c918fce7001731cec2a
3,641,428
import urllib def twitter_map(): """ Gets all the required information and returns the start page or map with people locations depending on input """ # get arguments from url account = request.args.get('q') count = request.args.get('count') if account and count: # create map a...
54a37f91141e52d24f88214ea476a2f199c78674
3,641,429
def path_states(node): """The sequence of states to get to this node.""" if node in (cutoff, failure, None): return [] return path_states(node.parent) + [node.state]
21ed5eb98eca0113dd5f446066cd10df73665f10
3,641,430
def find_named_variables(mapping): """Find correspondance between variable and relation and its attribute.""" var_dictionary = dict() for relation_instance in mapping.lhs: for i, variable in enumerate(relation_instance.variables): name = relation_instance.relation.name field ...
0b9a78ca94b25e7a91fe88f0f15f8a8d408cb2fd
3,641,431
import urllib def attribute_formatter(attribute): """ translate non-alphabetic chars and 'spaces' to a URL applicable format :param attribute: text string that may contain not url compatible chars (e.g. ' 무작위의') :return: text string with riot API compatible url encoding (e.g. %20%EB%AC%B4%EC%9E%91%EC%9C%8...
6c6745a5cea9a3f6bcee8cbcedb7a1493372dc96
3,641,432
import json def maestro_splits(): """ Get list of indices for each split. Stolen from my work on Perceptual Evaluation of AMT Resynthesized. Leve here for reference. """ d = asmd.Dataset().filter(datasets=['Maestro']) maestro = json.load(open(MAESTRO_JSON)) train, validation, test = ...
119b033d3fd507b77bbb3d16d993237f8658b5f5
3,641,434
def get_choice_selectivity(trials, perf, r): """ Compute d' for choice. """ N = r.shape[-1] L = np.zeros(N) L2 = np.zeros(N) R = np.zeros(N) R2 = np.zeros(N) nL = 0 nR = 0 for n, trial in enumerate(trials): if not perf.decisions[n]: continue ...
f33593ad06bf3c54c950eda562a93e348320a5e1
3,641,435
def author_productivity(pub2author_df, colgroupby = 'AuthorId', colcountby = 'PublicationId', show_progress=False): """ Calculate the total number of publications for each author. Parameters ---------- pub2author_df : DataFrame, default None, Optional A DataFrame with the author2publication...
15c56b22cc9d5014fe4dcfab8be37a9e4b0ef329
3,641,436
def smoothed_epmi(matrix, alpha=0.75): """ Performs smoothed epmi. See smoothed_ppmi for more info. Derived from this: #(w,c) / #(TOT) -------------- (#(w) / #(TOT)) * (#(c)^a / #(TOT)^a) ==> #(w,c) / #(TOT) -------------- (#(w) * #(c)^a) / #(TOT)^(a+1)) ==> #(w,c) ...
e2f72c4169aee2f394445f42e4835f1b55f347c9
3,641,437
import six def encode(input, errors='strict'): """ convert from unicode text (with possible UTF-16 surrogates) to wtf-8 encoded bytes. If this is a python narrow build this will actually produce UTF-16 encoded unicode text (e.g. with surrogates). """ # method to convert surrogate pairs t...
525199690f384304a72176bd1eaeeb1b9cb30880
3,641,438
def forgot_password(request, mobile=False): """Password reset form. This view sends an email with a reset link. """ if request.method == "POST": form = PasswordResetForm(request.POST) valid = form.is_valid() if valid: form.save(use_https=request.is_secure(), ...
ea27378253a7ed1b98cb91fd52fe724e79f35e26
3,641,439
def rotation_components(x, y, eps=1e-12, costh=None): """Components for the operator Rotation(x,y) Together with `rotation_operator` achieves best memory complexity: O(N_batch * N_hidden) Args: x: a tensor from where we want to start y: a tensor at which we want to finish ...
79cec86425bce65ac92ce8cf9c720f98857d7e1a
3,641,440
def erode(np_image_bin, struct_elem='rect', size=3): """Execute erode morphological operation on binaryzed image Keyword argument: np_image_bin -- binaryzed image struct_elem: cross - cross structural element rect - rectangle structural element circ -- cricle structural element(...
4692b40555a8047d70ad8c4b33de636a0c6c87b0
3,641,441
def setup_counter_and_timer(nodemap): """ This function configures the camera to setup a Pulse Width Modulation signal using Counter and Timer functionality. By default, the PWM signal will be set to run at 50hz, with a duty cycle of 70%. :param nodemap: Device nodemap. :type nodemap: INodeMap...
9874b17ce49aca766504891bd9828aad1e075e21
3,641,443
def concat(l1, l2): """ Join two possibly None lists """ if l1 is None: return l2 if l2 is None: return l1 return l1 + l2
9e87bead7eedc4c47f665808b9e0222437bc01b5
3,641,444