content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def backcasting( predictor, window, curves, distance="RMS", columns=("cases", "deaths"), min_series=14, step=1, ): """ Perform a backcasting performance analysis of the given model. For the sake of this method, the model is just a function that receives an epidemic curve data...
0e0eafc06ab6ab4578be1b299fc70ae88796a72d
3,648,812
from typing import Dict from typing import Callable from typing import List def find_keys(d: Dict[K, V], predicate: Callable[[V], bool]) -> List[K]: """Find keys where values match predicate.""" return [k for k, v in d.items() if predicate(v)]
68febd42bcd65ff52a786e4941dd5abf7d6a36ee
3,648,813
def get_maya_property_name(prop, ignore_channel=False): """ Given a property, return a reasonable Maya name to use for it. If ignore_channel is True, return the property for the whole vector, eg. return '.translate' instead of '.translateX'. This doesn't create or query anything. It just generates...
591a49f054db3936d5a345919a2c69491b6f345e
3,648,814
from typing import Concatenate def model_deepFlavourReference_test(Inputs,nclasses,dropoutRate=0.1,momentum=0.6): """ reference 1x1 convolutional model for 'deepFlavour' with recurrent layers and batch normalisation standard dropout rate it 0.1 should be trained for flavour prediction first. after...
f92f977a5570e647bf394d450bd5a5dea918aeba
3,648,815
import pathlib def load_spyrelet_class(spyrelet_name, cfg): """Load a spyrelet class from a file (whose location is defined in cfg)""" # discover spyrelet file and class spyrelet_path_str, _ = get_config_param(cfg, [CONFIG_SPYRELETS_KEY, spyrelet_name, CONFIG_SPYRELETS_FILE_KEY]) spyrelet_class_name, ...
877c8a626e7abe3e41146475dc030966c0b9f41e
3,648,816
def see_documentation(): """ This function redirects to the api documentation """ return jsonify({ '@context': responses.CONTEXT, 'rdfs:comment': 'See http://www.conceptnet.io for more information about ConceptNet, and http://api.conceptnet.io/docs for the API documentation.' })
46de921c855797b1b7d231a4cb88c57026ece947
3,648,817
from django.shortcuts import render def jhtml_render(request, file_type=None,json_file_url=None, html_template=None, json_render_dict=None, json_render_func=None, file_path=None, url_name=None, app_name=None): """ :param request: :param file_type: json/temp_json :param json_file_url: :param html_...
b5d61d69a2c27d883aad60953c7366c6724b905e
3,648,819
def prefix_sums(A): """ This function calculate of sums of eements in given slice (contiguous segments of array). Its main idea uses prefix sums which are defined as the consecutive totals of the first 0, 1, 2, . . . , n elements of an array. Args: A: an array represents number of mushroom...
d61e49eb4a973f7718ccef864d8e09adf0e09ce2
3,648,823
from run4it.api.scripts import script_import_polar_exercices as script_func def polar_import(): """Import data from Polar and save as workouts""" return script_func('polar_import')
6a7075184e5c44a3092670fffc94360ef9a363c4
3,648,824
def dijkstra(G, Gextra, source, target_set, required_datarate, max_path_latency): """ :returns a successful path from source to a target from target_set with lowest path length """ q = DynamicPriorityQueue() q.put((source, 0.0), priority=0.0) marked = set() parents = {source: None} while not q.empty(): path_l...
6a8ff88b7a56308e099d3f9e50c8645c3281a68e
3,648,825
def build_single_class_dataset(name, class_ind=0, **dataset_params): """ wrapper for the base skeletor dataset loader `build_dataset` this will take in the same arguments, but the loader will only iterate over examples of the given class I'm just going to overwrite standard cifar loading data for n...
c8d05ecc1292562e846bc62724a224c20746037a
3,648,826
def gamma_trace(t): """ trace of a single line of gamma matrices Examples ======== >>> from sympy.physics.hep.gamma_matrices import GammaMatrix as G, \ gamma_trace, LorentzIndex >>> from sympy.tensor.tensor import tensor_indices, tensorhead >>> p, q = tensorhead('p, q', [LorentzInd...
8eb5bf4ba1f1d0e170a88a7b798b65273db8c1fd
3,648,827
import copy def preprocess(comment): """Pre-Process the comment""" copy_comment = copy.deepcopy(comment) # Replacing link final_comment = replace_link(copy_comment) nftokens = get_nf_tokens(comment) return final_comment, nftokens
f7286d5ca3e668b70385cd72485bb81eb8f9eec1
3,648,828
def voc_label_indices(colormap, colormap2label): """Map a RGB color to a label.""" colormap = colormap.astype('int32') idx = ((colormap[:, :, 0] * 256 + colormap[:, :, 1]) * 256 + colormap[:, :, 2]) return colormap2label[idx]
481eccab328da13c4a49b2cf69d8e0e1cf1e48ab
3,648,829
def make_noisy_linear(w=1, std=1): """Factory for linear function <w,x> perturbed by gaussian noise N(0,std^2)""" @Oracle def noisy_linear(x): return np.dot(x, w) + np.random.normal(scale=std) return noisy_linear
80ec4a37dbbe6dc837707fa9a6e93e27d8dea9b9
3,648,830
def distance(turtle, x, y=None): """Return the distance from the turtle to (x,y) in turtle step units. Arguments: turtle -- the turtle x -- a number or a pair/vector of numbers or a turtle instance y -- a number None None call: distan...
f09b320c2b07374bebd2fd8c16084e7bf676523d
3,648,831
import copy def asy_ts(gp, anc_data): """ Returns a recommendation via TS in the asyuential setting. """ anc_data = copy(anc_data) # Always use a random optimiser with a vectorised sampler for TS. if anc_data.acq_opt_method != 'rand': anc_data.acq_opt_method = 'rand' anc_data.max_evals = 4 * anc_data....
1514263314cd92b053bfcd655872a03785b47af0
3,648,832
import re def checkParams(opts): """ 检查模块名是否符合命名规则 检查目录是否存在 """ res = {} for opt, arg in opts: if opt in ('--name'): if re.match('^[a-zA-Z_][a-zA-Z0-9_]*$', arg): res['name'] = arg else: return res elif opt in ('--dir'): ...
5b8306a1c9805786e4a98509dcea3af59ffd04d1
3,648,833
def nms(bboxes, iou_threshold, sigma=0.3, method='nms'): """ Note: soft-nms, https://arxiv.org/pdf/1704.04503.pdf https://github.com/bharatsingh430/soft-nms """ best_bboxes = [] while len(bboxes) > 0: max_ind = np.argmax(bboxes[:, 4]) best_bbox = bboxes[max_ind] be...
10f3f65bd00599aa77f2d832754febfeeed7ca55
3,648,834
def smart_cast(value): """Intelligently cast the given value to a Python data type. :param value: The value to be cast. :type value: str """ # Handle integers first because is_bool() may interpret 0s and 1s as booleans. if is_integer(value, cast=True): return int(value) elif is_flo...
73676278e8c8bf54536fd3c9982cad7f6064cb75
3,648,835
from typing import List from typing import Dict import math def find_host_biz_relations(bk_host_ids: List[int]) -> Dict: """ 查询主机所属拓扑关系 :param bk_host_ids: 主机ID列表 [1, 2, 3] :return: 主机所属拓扑关系 [ { "bk_biz_id": 3, "bk_host_id": 3, "bk_module_id": 59, "b...
9cd9891a97b5ad3db88a0e8a631775b1dc8c24c7
3,648,837
def atom_to_atom_line(atom): """Takes an atomium atom and turns it into a .cif ATOM record. :param Atom atom: the atom to read. :rtype: ``str``""" name = get_atom_name(atom) res_num, res_insert = split_residue_id(atom) return "ATOM {} {} {} . {} {} . {} {} {} {} {} 1 {} {} {} {} {} {} 1".forma...
30e9f9191947b23dffd9e3f6d63f697de325e5f0
3,648,838
from .....main import _get_bot from typing import Union from typing import Optional async def edit_chat_invite_link( token: str = TOKEN_VALIDATION, chat_id: Union[int, str] = Query(..., description='Unique identifier for the target chat or username of the target channel (in the format @channelusername)'), ...
7c83316e0e86eb223b40ed9bf69126d79a4651b4
3,648,839
def post_live_migrate_at_source(adapter, host_uuid, instance, vif): """Performs the post live migrate on the source host. :param adapter: The pypowervm adapter. :param host_uuid: The host UUID for the PowerVM API. :param instance: The nova instance object. :param vif: The virtual interface of the i...
0a4165abe0373a96b2b222d4eaa9316649d607b2
3,648,840
import re def conv2date(dtstr,tstart=None): """Convert epoch string or time interval to matplotlib date""" #we possibly have a timeinterval as input so wrap in exception block m=re.search("([\+\-])([0-9]+)([dm])",dtstr) if m: if m.group(3) == "m": dt=30.5*float(m.group(2)) #s...
b848f45c04bf9ef77fa3af395afb992f6302fb4f
3,648,841
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(MaskedBasicblock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet...
94e339a390723e7dbdec4d95b7f4bb3600faae1f
3,648,842
import pytz def weather(api_token, city, start, end): """ Returns an hourly report of cloud cover, wind and temperature data for the given city. The report is always in full days. Timestamps are in UTC. Start and end dates are interpreted as UTC. """ a = Astral() city = a[city] # hour...
2d8457cc8388613825dad54686988194eed85b2b
3,648,844
from skimage.transform import iradon def skimage_radon_back_projector(sinogram, geometry, range, out=None): """Calculate forward projection using skimage. Parameters ---------- sinogram : `DiscreteLpElement` Sinogram (projections) to backproject. geometry : `Geometry` The projecti...
8158569eca46907091bfbca6aba57cd2a6afa6bf
3,648,845
def get_segment_hosts(master_port): """ """ gparray = GpArray.initFromCatalog( dbconn.DbURL(port=master_port), utility=True ) segments = GpArray.getSegmentsByHostName( gparray.getDbList() ) return segments.keys()
565921e4b7d46ec357666d50dee7dcdb7127759e
3,648,846
from typing import List from typing import Dict from typing import Any def get_saved_albums(sp: Spotify) -> List[Dict[str, Any]]: """Returns the list of albums saved in user library""" albums = [] # type: List[Dict[str, Any]] results = sp.current_user_saved_albums(limit=50) albums.extend(results["ite...
525074d9f957b71c0b355d3d343e088d29792363
3,648,847
def createMergerCatalog(hd_obj, obj_conditions, cosmo, time_since_merger=1): """ Function to create Major Merger (MM) catalog @hd_obj :: header file for the object of interest @obj_conditions :: prior conditions to define the object sample @cosmo :: cosmology used in the notebook (Flat Lambda CDM) ...
ee0ac59fe1a8fa9a40a934caa32ff53cd171f3dc
3,648,848
from typing import Union from typing import Dict from typing import List from typing import Any import json def make_response(code: int, body: Union[Dict, List]) -> Dict[str, Any]: """Build a response. Args: code: HTTP response code. body: Python dictionary or list to jsonify. Returns: ...
bae0a8720085bdf3734724b00df8d856e362602a
3,648,850
def sql2dict(queryset): """Return a SQL alchemy style query result into a list of dicts. Args: queryset (object): The SQL alchemy result. Returns: result (list): The converted query set. """ if queryset is None: return [] return [record.__dict__ for record in queryset]
c55fa18773142cca591aac8ed6bdc37657569961
3,648,851
from typing import OrderedDict import itertools def build_DNN(input_dim, hidden_dim, num_hidden, embedding_dim=1, vocab_size=20,output_dim=1 ,activation_func=nn.Sigmoid): """ Function that automates the generation of a DNN by providing a template for pytorch's nn.Sequential class Parameters --------...
5b7476b20aacb0d6b0f78da6f97f9a1d3262d43c
3,648,852
def float_to_bin(x, m_digits:int): """ Convert a number x in range [0,1] to a binary string truncated to length m_digits arguments: x: float m_digits: integer return: x_bin: string The decimal representation of digits AFTER '0.' Ex: Input 0.75...
f95e72d9449b66681575b230f6c858e8b3833cc2
3,648,853
from typing import Callable from typing import List def apply(func: Callable, args: List): """Call `func` expanding `args`. Example: >>> def add(a, b): >>> return a + b >>> apply(add, [1, 2]) 3 """ return func(*args)
f866087d07c7c036b405f8d97ba993f12c392d76
3,648,854
def random_energy_model_create(db: Session) -> EnergyModelCreate: """ Generate a random energy model create request. """ dataset = fixed_existing_dataset(db) component_1 = fixed_existing_energy_source(db) return EnergyModelCreate(name=f"EnergyModel-{dataset.id}-" + random_lower_string(), ...
db5ac3decf6094bef271005732fd9b78a3870be3
3,648,855
def _indices_3d(f, y, x, py, px, t, nt, interp=True): """Compute time and space indices of parametric line in ``f`` function Parameters ---------- f : :obj:`func` Function computing values of parametric line for stacking y : :obj:`np.ndarray` Slow spatial axis (must be symmetrical a...
43a1f8761fb4e2ad32225ebf9e96f0aa2cdf0afd
3,648,856
def indicators_listing(request,option=None): """ Generate Indicator Listing template. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param option: Whether or not we should generate a CSV (yes if option is "csv") :type option: str :returns: ...
772ec90af7b104b4a9712742064d3aba758aab6f
3,648,857
def parse_sensor(csv): """ Ideally, the output from the sensors would be standardized and a simple list to dict conversion would be possible. However, there are differences between the sensors that need to be accommodated. """ lst = csv.split(";") sensor = lst[SENSOR_QUANTITY] if sen...
6673e12403090d130f0ac5590097794ae8f191aa
3,648,858
from datetime import datetime def samiljeol(year=None): """ :parm year: int :return: Independence Movement Day of Korea """ year = year if year else _year return datetime.date(int(year), 3, 1)
6ae717e12aa3dc5bd1d273e240294d2bc6a294ff
3,648,859
def get_entries(xml_file): """Get every entry from a given XML file: the words, their roots and their definitions. """ tree = get_tree(xml_file) # each <drv> is one entry entries = [] for drv_node in tree.iter('drv'): node_words = get_words_from_kap(drv_node.find('kap')) ro...
f9647cf79be68afa03908433890e1abbff9284bf
3,648,860
def comoving_radial_distance(cosmo, a, status): """comoving_radial_distance(cosmology cosmo, double a, int * status) -> double""" return _ccllib.comoving_radial_distance(cosmo, a, status)
72066b4b51a7728608d52c920bade33ecef0b920
3,648,861
import dateutil def make_legacy_date(date_str): """ Converts a date from the UTC format (used in api v3) to the form in api v2. :param date_str: :return: """ date_obj = dateutil.parser.parse(date_str) try: return date_obj.strftime('%Y%m%d') except: return None
5a2ed526c7bd0dae5a73a55c93d14ec158a0e6df
3,648,862
import torch def l2_mat(b1, b2): """b1 has size B x M x D, b2 has size b2 B x N x D, res has size P x M x N Args: b1: b2: Returns: """ b1_norm = b1.pow(2).sum(dim=-1, keepdim=True) b2_norm = b2.pow(2).sum(dim=-1, keepdim=True) res = torch.addmm(b2_norm.transpose(-2, -1),...
ad254c2c11dccab5dd97c7e72ef3b00c7b6143fb
3,648,863
def take_rich(frame, n, offset=0, columns=None): """ A take operation which also returns the schema, offset and count of the data. Not part of the "public" API, but used by other operations like inspect """ if n is None: data = frame.collect(columns) else: data = frame.take(n, of...
de3514d64a74addae76628c37f679693ba68550b
3,648,865
def default_name(class_or_fn): """Default name for a class or function. This is the naming function by default for registries expecting classes or functions. Args: class_or_fn: class or function to be named. Returns: Default name for registration. """ return camelcase_to_s...
1ed04a87916ae5d0fa9f1173d5fb9f97c26b32e9
3,648,866
def get_ip_result_by_input_method( set_input_method, module_input_method, var_ip_selector, username, bk_biz_id, bk_supplier_account, filter_set, filter_service_template, produce_method, var_module_name="", ): """ @summary 根据输入方式获取ip @param var_module_name: 模块属性名 @...
aa12179a5706f213894962579e5d0be30209f14e
3,648,868
def _single_style_loss(a, g): """ Calculate the style loss at a certain layer Inputs: a is the feature representation of the real image g is the feature representation of the generated image Output: the style loss at a certain layer (which is E_l in the paper) """ N = a.shape...
f19d8fcfc467d4760a44d2cdb872791cc2ad2ffe
3,648,871
def hyp_dist_o(x): """ Computes hyperbolic distance between x and the origin. """ x_norm = x.norm(dim=-1, p=2, keepdim=True) return 2 * arctanh(x_norm)
8864d8625798a8b41e2dd645cfe11e8d73d6d9d3
3,648,872
def check_image(url): """A little wrapper for the :func:`get_image_info` function. If the image doesn't match the ``flaskbb_config`` settings it will return a tuple with a the first value is the custom error message and the second value ``False`` for not passing the check. If the check is successful...
d0587dc987a079d49eb9a863d5203908acab41c4
3,648,873
def preprocess(dataset_file_path, len_bound, num_examples = None, reverse = False): """ It reads the required files, creates input output pairs. """ min_sentence_length = len_bound[0] max_sentence_length = len_bound[1] lines = open(str(dataset_file_path), encoding='utf-8', errors = 'ignore'...
5849c1957ccab997bcf835bce2fec71b0a93cd6d
3,648,874
def read_transcriptome(transcriptome): """ Parse transcriptome as a dictionary. """ result_dict = {} for sequence in SeqIO.parse(transcriptome, 'fasta'): result_dict[sequence.name] = sequence.seq return result_dict
008df223435de465cd6f36978305ca95bb15b270
3,648,875
from re import X def magnus(w, n): """ The 'Magnus' map """ expr = w.subs(x,1+eps*X).subs(y,1+eps*Y) - 1 return limit(expr / eps**n, eps, 0)
7faf1935b9348f41e6968b7da5fa59576ad874a5
3,648,876
def translate_node_coordinates(wn, offset_x, offset_y): """ Translate node coordinates Parameters ----------- wn: wntr WaterNetworkModel A WaterNetworkModel object offset_x: tuple Translation in the x direction, in meters offset_y: float Translation in ...
da886a624b9038296d47ffe85a04e62f71f49def
3,648,878
def get_demo_board(): """Get a demo board""" demo_board_id = 1 query = Board.query.filter(Board.id == demo_board_id) query = query.options(joinedload(Board.tasks)).options(raiseload('*')) board = query.one() return BoardDetailsSchema().dump(board).data
69b20a6c7446dc3813ec8d8c454a7a35443bf103
3,648,879
def cool_KI(n, T): """ Returns Koyama & Inutsuka (2002) cooling function """ return 2e-19*n*n*(np.exp(-1.184e5/(T + 1e3)) + 1.4e-9*T**0.5*np.exp(-92.0/T))
707b9e8d42e4d1b7db069c05b3b74e3f0b37f2e6
3,648,880
def main(args): """ main entry point for the manifest CLI """ if len(args) < 2: return usage("Command expected") command = args[1] rest = args[2:] if "create".startswith(command): return cli_create(rest) elif "query".startswith(command): return cli_query(rest) ...
b89e68c6ef98722a55ff15e8473dec8c8437bf8d
3,648,881
def compute_correlations(states): """compute_correlations. Calculate the average correlation of spin 0 and every other spin. Parameters ---------- states : list of states. ``len(states)`` must be >= 1! Returns ------- correlations : list of floats. """ return [ ...
471949aa63a3d65b262fb9dad1c77d160a3f5ac7
3,648,882
from typing import Sequence from typing import Any def parse_sample_str(elems: Sequence[Any]) -> AOList[str]: """ Choose n floats from a distribution. Examples: >>> c = parse_sample_str([4, ["choose", ["one", "two"]]]) >>> c Sample(4, ChooseS([StrConst('one'), StrConst('two')])) """ str...
5996a3b0ed072d4a7a00d7e01cc74efdc65aa8ee
3,648,883
def htlc(TMPL_RCV, TMPL_OWN, TMPL_FEE, TMPL_HASHIMG, TMPL_HASHFN, TMPL_TIMEOUT): """This contract implements a "hash time lock". The contract will approve transactions spending algos from itself under two circumstances: - If an argument arg_0 is passed to the script ...
9288458b228dabc1663901e03011feaa8ff9765c
3,648,884
def parse(*args, is_flag=False, **kwargs): """alias of parser.parse""" return _parser.parse(*args, is_flag=is_flag, **kwargs)
f40499277a12bd6e492e43fd7e4328124ac59814
3,648,885
def oauth_callback(): """ return: str """ auth = tweepy.OAuthHandler(env.TWITTER_API_KEY, env.TWITTER_API_SECRET) try: auth.request_token = session['REQUEST_TOKEN'] verifier = request.args.get('oauth_verifier') auth.get_access_token(verifier) session['AUTH_TOKEN'],ses...
a15d7c88c97b23a3ce625e363882fff3197c55b5
3,648,886
from typing import Tuple from typing import List import random def generate_random_instance(n_instants: int, cost_dim: int, items_per_instant: int = 1) -> \ Tuple[List[List[float]], List[List[List[float]]], float, float]: """Generates random values, costs and capacity for a Packing Problem instance. I...
57ccf4cd5410d2358c434d94beb9bfbb0ca04820
3,648,887
def recommend_tags_questions(professional_id, threshold=0.01, top=5): """ Recommends tags for an professional depending on answered questions. :param professional_id: ID of the professional :param threshold: Minimum percentage of questions with the tags. :param top: Top N recommende...
1b4bc6d37569d4794294028036e59437f66dc552
3,648,888
from .tools import make_simulationtable from .model import reservoirs def simulationtable(request): """ called when the simulation page starts to get used """ # convert to the right name syntax so you can get the COM ids from the database selected_reservoir = request.body.decode("utf-8") rese...
eaa60d02ee095d5efcc6a4f458bd4bb6745675d0
3,648,889
from datetime import datetime def get_rate_limits(response): """Returns a list of rate limit information from a given response's headers.""" periods = response.headers['X-RateLimit-Period'] if not periods: return [] rate_limits = [] periods = periods.split(',') limits = response.head...
eed6504d712e91110763e28f400dab5faf9300a1
3,648,890
import numpy def plot_breakdown_percents(runs, event_labels=[], title=None, colors=None): """ Plots a bar chart with the percent of the total wall-time of all events for multiple runs. Parameters ---------- runs: Run object or list of Run objects The list of ...
788c0c466223a2e2aaa695c616fdfc649248b963
3,648,891
def gen3_file(mock_gen3_auth): """ Mock Gen3File with auth """ return Gen3File(endpoint=mock_gen3_auth.endpoint, auth_provider=mock_gen3_auth)
ee2af5d8b89c02e205101e0fe56dc58025d72e38
3,648,892
def rhs_of_rule(rule): """ This function takes a grammatical rule, and returns its RHS """ return rule[0]
004b99ac97c50f7b33cc798997463a28c3ae9a6f
3,648,893
from typing import Union from typing import Optional from typing import Any def flow_duration_curve( x: Union[np.ndarray, pd.Series], log: bool = True, plot: bool = True, non_exceeding:bool = True, ax: Optional[Union[SubplotBase, Any]] = None, **kwargs ) -> Uni...
3bec0159553a814ac4c68b198a29bf3075f6d202
3,648,894
def get_fields(filters): """ Return sql fields ready to be used on query """ fields = ( ("(SELECT p.posting_date FROM `tabPurchase Invoice` p Join `tabPurchase Invoice Item` i On p.name = i.parent WHERE i.item_code = `tabItem`.item_code And p.docstatus = 1 limit 1) as pinv_date"), ("CONCAT(`tabItem`._default_...
592d7c051e3af4cb510e43caa774054976f68865
3,648,895
from typing import Counter def count_POS_tag(df_pos): """Count how often each POS tag occurs Args: df_pos ([dataframe]): dataframe, where the entries are list of tuples (token, POS tag) Returns: df_pos_stats ([dataframe]): dataframe containing POS tag statistics """ # POS tag l...
a9ac14f34c020b78b02d6ae629cbddcdde39af8d
3,648,896
import json def catch_all(path): """ Gets dummy message. """ return json.dumps({ 'message': 'no one was here', 'ms': get_epochtime_ms() })
b93190b546705c1115c1612e4bd79210ab0d8f85
3,648,897
import typing from typing import List from functools import reduce def dimensions_to_space_time_index(dims, t_idx = (), t_len = (), s_idx = (), s_len = (), next_idx_valid = 0, invalid = False, min_port_width = 0, max_port_width = 0, total_time = 0,...
bdb24e237ba99288be98112db0f09d6782193594
3,648,899
from io import StringIO def unparse(input_dict, output=None, encoding='utf-8', **kwargs): """Emit an XML document for the given `input_dict` (reverse of `parse`). The resulting XML document is returned as a string, but if `output` (a file-like object) is specified, it is written there instead. Dictionary keys p...
31cd6225144fcd1296105a66d2318c6d1a22bcca
3,648,900
def to_bin(val): """ Receive int and return a string in binary. Padded by 32 bits considering 2's complement for negative values """ COMMON_DIGITS = 32 val_str = "{:b}".format(val) # Count '-' in negative case padded_len = len(val_str) + ((COMMON_DIGITS - (len(val_str) % COMMON_DIGITS)) % COMMON...
819d1c0a9d387f6ad1635f0fe0e2ab98b3ca17b0
3,648,903
def PSingle (refLamb2, lamb2, qflux, qsigma, uflux, usigma, err, nterm=2): """ Fit RM, EVPA0 to Q, U flux measurements Also does error analysis Returns array of fitter parameters, errors for each and Chi Squares of fit refLamb2 = Reference lambda^2 for fit (m^2) lamb2 = Array of lambda^2 f...
29c3fd75203317265cccc804b1114b5436fd12bc
3,648,904
from typing import List def exec_waveform_function(wf_func: str, t: np.ndarray, pulse_info: dict) -> np.ndarray: """ Returns the result of the pulse's waveform function. If the wf_func is defined outside quantify-scheduler then the wf_func is dynamically loaded and executed using :func:`~quantify...
29c44de1cc94f6d63e41fccbbef5c23b67870b4d
3,648,905
def generate_straight_pipeline(): """ Simple linear pipeline """ node_scaling = PrimaryNode('scaling') node_ridge = SecondaryNode('ridge', nodes_from=[node_scaling]) node_linear = SecondaryNode('linear', nodes_from=[node_ridge]) pipeline = Pipeline(node_linear) return pipeline
2ef1d8137aeb100f6216d6a853fe22953758faf3
3,648,906
def get_socialnetwork_image_path(instance, filename): """ Builds a dynamic path for SocialNetwork images. This method takes an instance an builds the path like the next pattern: /simplesite/socialnetwork/PAGE_SLUG/slugified-path.ext """ return '{0}/{1}/{2}/{3}'.format(instance._meta.app_label, ...
b54e53f0c2a79b3b4e6d4d496d6a85264fffcef1
3,648,907
def openReadBytesFile(path: str): """ 以只读模式打开二进制文件 :param path: 文件路径 :return: IO文件对象 """ return openFile(path, "rb")
72fd2be5264a27a2c5c328cb7a8a4e818d799447
3,648,908
from datetime import datetime def diff_time(a:datetime.time,b:datetime.time): """ a-b in seconds """ return 3600 * (a.hour -b.hour) + 60*(a.minute-b.minute) + (a.second-b.second) + (a.microsecond-b.microsecond)/1000000
e0557d3d3e1e9e1184d7ea7a84665813e7d32760
3,648,909
def _create_pseudo_names(tensors, prefix): """Creates pseudo {input | output} names for subclassed Models. Warning: this function should only be used to define default names for `Metics` and `SavedModel`. No other use cases should rely on a `Model`'s input or output names. Example with dict: `{'a': [x1, ...
5e4ee64026e9eaa8aa70dab85d8dcf0ad0b6d89f
3,648,910
import sqlite3 def search_for_breakpoint(db_name, ids): """ Function will retrieve ID of last caluclated grid node to continue interrupted grid caclulation. :param db_name: str; :param ids: numpy.array; list of grid node ids to calculate in this batch :return: int; grid node from which start the ...
3354fcd505de9aefae5f0b4448e1ada7eab0a092
3,648,911
def rgetattr(obj, attr): """ Get named attribute from an object, i.e. getattr(obj, 'a.a') is equivalent to ``obj.a.a''. - obj: object - attr: attribute name(s) >>> class A: pass >>> a = A() >>> a.a = A() >>> a.a.a = 1 >>> rgetattr(a, 'a.a') 1 >>> rgetattr(a, 'a.c') ...
5fb58634c4ba910d0a20753c04addf667614a07f
3,648,913
def lambda1_plus_lambda2(lambda1, lambda2): """Return the sum of the primary objects tidal deformability and the secondary objects tidal deformability """ return lambda1 + lambda2
4ac3ef51bb66861b06b16cec564f0773c7692775
3,648,914
def create_cut_sht(stockOutline,array,features,partSpacing,margin): """ """ numParts = len(array) basePlanes = generate_base_planes_from_array(array) targetPlanes = create_cut_sht_targets(stockOutline,array,margin,partSpacing) if targetPlanes == None: return None else: # converts...
12d8f56a7b38b06cd89d86fdbf0096f5c8d6e869
3,648,916
def unicode_is_ascii(u_string): """Determine if unicode string only contains ASCII characters. :param str u_string: unicode string to check. Must be unicode and not Python 2 `str`. :rtype: bool """ assert isinstance(u_string, str) try: u_string.encode('ascii') return Tru...
2a742c7334d68fe0bf6b546fb79bf00a338355f9
3,648,917
def duplicate_item(api_key: str, board_id: str, item_id: str, *args, **kwargs): """Duplicate an item. Parameters api_key : `str` The monday.com v2 API user key. board_id : `str` The board's unique identifier. item_id : `str` ...
9e24952a2443b4bcf40d2ae5e3e9d65b8485fece
3,648,918
def compute_loss(retriever_logits, retriever_correct, reader_logits, reader_correct): """Compute loss.""" # [] retriever_loss = marginal_log_loss(retriever_logits, retriever_correct) # [] reader_loss = marginal_log_loss( tf.reshape(reader_logits, [-1]), tf.reshape(reader_correct, [-1])...
2576191d23a303e9d045cb7c8bbeccbd49b22b43
3,648,920
def index() -> render_template: """ The main part of the code that is ran when the user visits the address. Parameters: covid_data: This is a dictionary of the data returned from the API request. local_last7days_cases: The number of local cases in the last 7 days. national_last7days_cases: The ...
d9357f29c9329c901e8389497435ead319841242
3,648,922
def r(x): """ Cartesian radius of a point 'x' in 3D space Parameters ---------- x : (3,) array_like 1D vector containing the (x, y, z) coordinates of a point. Returns ------- r : float Radius of point 'x' relative to origin of coordinate system """ return np.sqr...
3729f91a6671c17bc9fda7eebb9809d316a0d714
3,648,923
def solve(*args): """ Crunch the numbers; solve the problem. solve(IM A, IM b) -> IM solve(DM A, DM b) -> DM solve(SX A, SX b) -> SX solve(MX A, MX b) -> MX solve(IM A, IM b, str lsolver, dict opts) -> IM solve(DM A, DM b, str lsolver, dict opts) -> DM solve(SX A, SX b, str lsolver,...
8866fba2efa51e7117d1d39fd7d2b7a259209c66
3,648,924
def NonNegativeInteger(num): """ Ensures that the number is non negative """ if num < 0: raise SmiNetValidationError("A non-negative integer is required") return num
dc5241e8dd7dbd07c5887c35a790ec4eab2593f0
3,648,925
def to_cartesian(r, ang): """Returns the cartesian coordinates of a polar point.""" x = r * np.cos(ang) y = r * np.sin(ang) return x, y
bc4e2e21c42b31a7a45185e58fb20a7b4a4b52e4
3,648,926
def _get_filtered_partially_learnt_topic_summaries( topic_summaries, topic_ids): """Returns a list of summaries of the partially learnt topic ids and the ids of topics that are no longer present. Args: topic_summaries: list(TopicSummary). The list of topic summary domain objects...
c977966381dea0b1b91e904c3f9ec4823d26b006
3,648,927
def build_bar_chart_with_two_bars_per_label(series1, series2, series1_label, series2_label, series1_labels, series2_labels, title, x_axis_label, y_axis_label, output_file_name): """ This function builds a bar chart that has ...
f43c4e525f0a2dd07b815883753974e1aa2e08cf
3,648,928
def calculateDescent(): """ Calculate descent timestep """ global descentTime global tod descentTime = myEndTime line = len(originalTrajectory) for segment in reversed(originalTrajectory): flInit = int(segment[SEGMENT_LEVEL_INIT]) flEnd = int(segment[SEGMENT_LEVEL_END]) status = segment[STATUS] if flIn...
11c04e49ef63f7f51cb874bf19cd245c40f0f6f4
3,648,929
def update_tutorial(request,pk): """View function for updating tutorial """ tutorial = get_object_or_404(Tutorial, pk=pk) form = TutorialForm(request.POST or None, request.FILES or None, instance=tutorial) if form.is_valid(): form.save() messages.success(request=request, message="Congra...
06fe827f26537fe376e79bc95d2ab04f879b971a
3,648,930