content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _gen_3d_examples(x1_size: float, x2_size: float, num_examples: int, noise_prob: float): """Generates 3D examples Each example has coordinates [x1, x2] where: - x1 is on interval [0, x1] - x2 is on interval [0, x2] Args: x1_size: Size of first axis. x2_s...
cb0837163a9293c1ee7f9a3935cace420000547c
39,932
from typing import List def get_target_args(args: List[Arg]) -> List[Arg]: """Given args for a controlled operation, get the args that are being acted on""" return [arg for arg in args if arg[0] < 2 and arg[1] > -1]
6497788de387cb752dd7af5fe44377aefd38ebfe
39,933
def gen_stats_grouped_accum(_, group_type): """ Args: _: Http Request (ignored in this function) group_type: Keyword defining group label (day,month,year) Returns: Activities grouped by (day or month or year) wrapped on response's object """ error_messages = [] success_messages = [] status = HTTP_200_OK ...
9a743c1af582288d7d2e67496c1b1a5f5aec180a
39,934
def ClassWeightedLabelSmoothingLoss(real,pred,weights,vocab_size,epsilon): """ pred (FloatTensor): batch_size x seq_len x vocab_size real (LongTensor): batch_size x seq_len weights (FloatTensor): vocab_size """ real = tf.cast(real,tf.int32) real_onehot = tf.one_hot(real,depth=vocab_size) ...
4a67e21f32391589da5297565849f63cd5390b38
39,935
def get_compilation_step_args(session, task): """Prepare arguments passe to each compilation step.""" latex_document = _get_node_from_dictionary( task.depends_on, session.config["latex_source_key"] ).value compiled_document = _get_node_from_dictionary( task.produces, session.config["late...
ff3f7cfaa2985deb93515d4ad639ab224dc39fa4
39,937
def persistent_q_learning( q_tm1: Array, a_tm1: Numeric, r_t: Numeric, discount_t: Numeric, q_t: Array, action_gap_scale: float, stop_target_gradients: bool = True, ) -> Numeric: """Calculates the persistent Q-learning temporal difference error. See "Increasing the Action Gap: New Opera...
ed8a3ee5f88f604394f64e6759161d9692638ff3
39,938
def preprocess_data(tokenizer, task): """Preprocess dataset to test.""" log.info('Loading dev data...') if task == 'QA': # question_answering batchify_fn = nlp.data.batchify.Tuple( nlp.data.batchify.Stack(), nlp.data.batchify.Pad(axis=0, pad_val=vocab[vocab.padding_to...
72997e909944b9722669958278009393ffb6d604
39,939
def do_with_retry(func, *args, **kwargs): """ Tries a function 3 times using exponential backoff according to Google API specs. Optional kwargs: `_attempts` - override the number of attempts before giving up. `_catch` - tuple of exception types used in `except types as e`. """ MINIM...
daef1d5a87d0d287fbc55baddefedaf1ae2edd4c
39,940
def to_int(s): """convert a string to an integer with PRECISION""" assert isinstance(s, str) # don't convert twice! result = int(float(s) * PRECISION) return result
da57a39bfa545a1058ab98f6ad5d786fc5bbbbce
39,941
def cast(value): """ Casts a RETS value into a Python data type Since RETS servers can return non-Boolean strings (like 'yes' or 'no') or numeric values (namely 0 or 1) for Booleans, these values are left alone and are NOT cast into Python Booleans. Application developers should decide on a cas...
4bf96080c555014907462ef09675a46ac50591e9
39,942
def submit_txn_sold(): """ Endpoint to create a new transaction via our application. """ guid = request.form["guid"] fish = fetch_fish(guid) if fish == None: # Error looking up fish. It might not exist? print("Fish is None") return redirect('/') lastConsumption = fi...
ae4af629531d432f83c75d5bc12b4846e5f553d4
39,943
from datetime import datetime def validate_calendar_date(date_to_validate): """Checks to see if date (yyyy, yyy-mm, or yyyy-mm-dd) is a valid Gregorian calendar date. """ parts = str(date_to_validate).split('-') if len(parts) == 3: year = parts[0] month = parts[1] day = ...
afdd7a2a1586e66fa26340424e791be805a4b57e
39,945
def ListMessagesMatchingQuery(service, user_id, query=''): """List all Messages of the user's mailbox matching the query. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. query: String used to filter me...
c80b7afc4d52250038bdd8c1c3b2f6d860e41423
39,947
import time def convert_time(t): """Takes epoch time and translates it to a human readable version""" return time.strftime('%Y-%m-%d', time.localtime(t))
e591e32e30a8ceb81c9934f4e67556896a56b79a
39,949
import typing import types def convert( value: typing.Any, *, schema: oa_types.Schema, read_only: typing.Optional[bool] = None, ) -> types.TOptObjectDict: """ Convert object schema value to dictionary. Args: value: The value to convert. schema: The schema for the value. ...
7b195dffe6190dbb6bc4b0d96d91a5340fa5816e
39,950
def _get_proto_summaries( proto_expressions ): """Gets the proto summaries.""" result = [] # type: List[ProtoRequirements] for expr in proto_expressions: def get_summary(tensor_of_protos, desc): for summary in result: if id(summary.tensor) == id( tensor_of_protos) and summary.d...
eaaa5bbf2e279997afc102a254fb0e6a07c083da
39,952
from typing import List from functools import reduce def singleNumber(nums: List[int]) -> int: """ 思路:排序,哈希,位运算(异或) 0^1 = 1, 1^1 = 0 """ # n = 0 # for val in nums: # n ^= val # return n return reduce(lambda x, y: x ^ y, nums)
444b2e2685d42bcc717d95058a6c86dc4da31609
39,953
def getPort(): """ Retreives the current TCP port. Returns: hostIP(str): Current TCP port """ return port
c9e589df3abaef21f324b98a9b4508319409dae6
39,954
def setup_prior(prior=None, num_causes=None): """Setup for prior array Parameters ---------- prior : array_like, optional Prior distribution to use. If not specified, each cause bin will be assigned an equal probability (default is None, and uniform prior will be used). num_...
1301833c7801e0ce8df1e9f1c61de64665f9a2d5
39,955
def get_intact_complex_portal_xrefs_df() -> pd.DataFrame: """Get IntAct-Complex Portal xrefs.""" df = _get_complexportal_df() df['source_ns'] = 'intact' df['target_ns'] = 'complexportal' df['source'] = COMPLEXPORTAL_MAPPINGS df = df[['source_ns', 'source_id', 'target_ns', 'target_id', 'source']]...
8bc35dc888c5b6e5652fabdf99d92eddcc59c249
39,956
def normalize_img(image, label): """Normalizes images: `uint8` -> `float32`.""" return tf.cast(image, tf.float32) * 255, label
c91c747b04fdcc876859907cec826563020daba4
39,957
def valid_box(box, host_extent): """Returns True if the entire box is within a grid of size host_extent. input arguments (unmodified): box: numpy int array of shape (2, 3) lower & upper indices in 3 dimensions defining a logical cuboid subset of a 3D cartesian grid in python protocol...
c6b1bc144e23b35002a1fbf17d4e02d9ba904655
39,958
import numpy as np from scipy.interpolate import interp1d def spec_stich_n_norm(spec, wave, cont, sig): """This stitches and continuum normalises CARMENES E2DS spectra into 1D spectra for use in molecfit. N. Borsato - 24-02-2021""" #These arrays will be filled with the stiched data. Total_Specs ...
7ffc89b7d3b3ca2898f2e990c67d712f28c0cfba
39,959
def average(self, key_selector=None): """Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. Example res = source.average(); res = source.average(lambda x: x.value) ...
a9ecd7c4509a3a3203f96bc9fd33bc453fb76ba7
39,960
def disparate_impact_remover(structured_data): """ Perform disparate impact removal from dataset and convert to pandas dataframe. Parameters: aif_standard_data (aif360.datasets.standard_dataset.StandardDataset): Structured dataset. Returns: data_transf_df (pandas dataframe): Pandas dat...
950549d2bd042890830c9adc389d6e46ceed3fff
39,961
def PyDateTime_DATE_GET_SECOND(space, w_obj): """Return the second, as an int from 0 through 59. """ try: return space.int_w(space.getattr(w_obj, space.newtext("second"))) except OperationError: return 0 # see comments in PyDateTime_DATE_GET_HOUR
8b64a6ed2fa7cd57d5a79646f8bbc381ca0972fc
39,962
def get_market_tops(symbols=None, **kwargs): """ Top-level function to obtain TOPS data for a symbol or list of symbols Parameters ---------- symbols: str or list, default None, optional A symbol or list of symbols kwargs: Additional Request Parameters (see base class) """ ...
081bccdedf7dfe888c6508a6df1cbb0deada3da7
39,963
def has_all_params_ortho(**params) -> bool: """ Returns True, if all 12 keys of an orthotropic material are provided.""" return len(missing_params_ortho(**params)) == 0
52d30d36dbd7e52119353af177fa10d0a24513c2
39,964
def hgw_init(): """Instantiate all the needed objects and setups references between them.""" collector = DataCollector() cabinet = FilingCabinet() broker = MessageBroker() adc = AsynchronousDataCarrier() sdc = SynchronousDataCarrier() # NOTE: collector -> cabinet <-> broker <-> carrier collector.cabinet = ca...
bc375a934151b08f8e7ce075491ec753a6ca409e
39,965
def piechartgrid(x='None', y='None', data='None', legendmode ='on', legendposition = 'auto', subfigsize=(2,2), dpi=100, latex=True, **kwargs): """Generates a of pie charts for categorial data. Based on the unique values in dataframe columns ``x`` and ``y`` the grid of subplots is constructed and the associate...
ddc441657fcc5db41b7e6723bb648f1866ebea69
39,966
def fix_curie(curie:str) -> str: """ Biothings explorer has some very weird curie prefixes, like "HP:HP:0012092" and "MESH.DISEASE:ICD10CM:E11.8". This method chooses the first prefix that appears in the response of the bioentities endpoint. If it can't fix the curie then it returns it. Example...
d92b4a51390506e64f840c7a2acb7efd9cd29ef9
39,967
def answer(request, question_id): """ Add an answer to a question """ question = get_object_or_404(Question, pk=question_id) try: answer_text = request.POST.get('answertext') if answer_text: # check to make sure that a new answer was entered and then save it ...
96b18ee4a14b861c018c28c638b436c7d6bcffab
39,968
def map_genome_events(time, domains, header): """Map a genome's properties to its state Args: time: time of the current state domains: dictionary of the genome. keys are gene names, values are the genome objects header: csv header to make sure we have the values in the right order Re...
bf59018ab32ae200ef71ba2256863a62305600a3
39,969
def replace_check_sum(data): """ data[2:-2]のチェックサムを計算し data[-2:]を置き換える @param data データ。4バイト以上の長さが必要 @return 最終2バイトをチェックサムに置き換えたデータ """ cksum = 0 for i in range(2, len(data) - 2): cksum += data[i] return data[:-2] + pack('BB', cksum % 256, cksum // 256)
f7e444d6ca166e73503f5635189f2d9695d7635a
39,970
def conv3x3(in_channels, out_channels, stride=1, padding=1, dilation=1): """3x3 convolution""" return nn.Conv2d( in_channels, out_channels, kernel_size=3, stride=stride, padding=padding, dilation=dilation, bias=False, )
a18e885a6d3a08ac242d9966f6bb0b19b9360d90
39,971
import json def set_event_type(request, event_id): """ Set event type. Should be an AJAX POST. :param request: Django request object (Required) :type request: :class:`django.http.HttpRequest` :param event_id: The ObjectId of the event to update. :type event_id: str :returns: :class:`djang...
ad437ded87ca01f2dc4017810ba7d41b24ed5e47
39,972
def rect(x: np.ndarray) -> np.ndarray: """ Rectangle function. """ try: return np.array( [ 1.0 if (x_i < 0.5 and x_i > -0.5) else 0. for x_i in x ] ) except: return 1.0 if (x < 0.5 and x > -0.5) else 0.
9c65576b6d0e3f6bf915517a1f10648c92626404
39,973
async def challenge(msg, mobj): """ The Challenge Picks a random Dota 2 hero to play and gives you 3 items to work towards Optional: supply a hero and get the 3 items to play (sd/ap/rd applicable) Example: !challenge -> Bloodseeker: Guardian Greaves, Abyssal Blade, Dagon """ ms...
edcd9c99e589d148f9ce8494aeac9b88e81811f1
39,974
from typing import Sequence def generate_pydot_graph(root, visibility_level): """ Generate the pydot graph - this is usually the first step in rendering the tree to file. See also :py:func:`render_dot_tree`. Args: root (:class:`~py_trees.behaviour.Behaviour`): the root of a tree, or subtree ...
937a1d97e4a029a22e86cf8573df18b64b13ad14
39,976
def _lookahead(param, lookahead_ema, step, beta_lookahead=0.5, lookahead_every_nth_iter=4): """lookahead at the param level instead of group level""" condition = step % lookahead_every_nth_iter < 0.5 # == 0. but inexact to deal with roundoffs lookahead_ema = jnp.where(condition, beta_lookahead*lookahead_ema...
2a5faedcaad366a015549f9246b3608900fc5363
39,978
import dill as cPickle import cPickle def load_pickle(h5f, safe=True): """ Deserialize and load a pickled object within a hickle file WARNING: Pickle has Parameters ---------- h5f: h5py.File object safe (bool): Disable automatic depickling of arbitrary python objects. DO NOT set this to Fal...
7fe94a91c331fbf685f2dbc7cbeb09c2d16c3b2a
39,980
from typing import Generator def dataset_using_generator(samples, reader, **kwargs): """ A generator class which wraps samples so that they can be used with tf.data.Dataset.from_generator Parameters ---------- samples : [:obj:`object`] A list of samples to be given to ``reader`` to loa...
f95a00ba20aaa99afe673628aa55f17106e1914f
39,981
import yaml def yaml_dump_result(obj, stream): """Redefinition of yaml.safe_dump with added float representer The float representer uses float precision of four decimal digits """ def float_representer(dumper, value): text = '{0:.4f}'.format(value) return dumper.represent_scalar(u'tag...
55a8a06e918276060505224a680e1cb136d4a541
39,983
import time from bs4 import BeautifulSoup def scrape_last_patch_change(names, save=True): """ Scrapes the last patch in which each champion was changed from League Wiki and saves them to a csv file, but returns nothing Parameters ---------- names : pandas series Contains the c...
cd1ddc78192f145c97bfb1e2be5edd00af38439b
39,985
def delete_all(): """ Delete all predictions in the database. Args: None. """ return Prediction.objects.all().delete()
011f5332d568195b639b41104354584fd9ede600
39,986
def strip_readonly(model: ModelNormal): """Strip read only fields before sending to server""" for field in [ elt for elt in model.attribute_map.values() if hasattr(model, elt) and isinstance( getattr(model, elt), (models.Id16ReadOnly, models.Id16ReadOnlyNu...
412f87ea0b17996dea8fb939412bc736b59dccfa
39,987
def get_stock_rack_assembler(entity, rack_barcodes, excluded_racks=None, requested_tubes=None, include_dummy_output=False, **kw): """ Factory method generating a stock rack assembler (XL20 worklist generator) tool for the passed entity. The generator...
f9a7aed7c2c4d9c55736fb2b4c1512ec34e35cf4
39,988
import string import random def random_string(length=-1, charset=string.ascii_letters): """ Returns a random string of "length" characters. If no length is specified, resulting string is in between 6 and 15 characters. A character set can be specified, defaulting to just alpha letters. """ if ...
170082275e16d19d6e2bd37178e1c654b75ef261
39,989
def rho_NFW(r, rs, rhos): """ The density profile [GeV/cm**3] of an NFW halo. Parameters ---------- r : the distance from the center [kpc] rs : the NFW r_s parameter [kpc] rhos : the NFW rho_s parameter [GeV/cm**3] """ res = rhos/(r/rs)/(1.+r/rs)**2 return res
3b8f97713610c1622815e15f13a75d39ad7e64ba
39,990
def _load_local_auth(): """Returns a LocalAuthParameters tuple from LUCI_CONTEXT. Returns: LocalAuthParameters for connecting to a local auth server. Raises: BadLuciContextParameters if file is missing or not valid. """ data = luci_context.read('local_auth') if data is None: raise BadLuciConte...
f1bf1f5ab11723956c81a3d852dc9094d0bef8b3
39,992
def ifequal(parser, token): """ Output the contents of the block if the two arguments equal each other. Examples:: {% ifequal user.id comment.user_id %} ... {% endifequal %} {% ifnotequal user.id comment.user_id %} ... {% else %} ... ...
18ef87d1c957620083a493661f90f92aa831c13d
39,993
from skimage.metrics import structural_similarity def ssim(x: np.ndarray, y: np.ndarray) -> float: """Calculate the structural similarity metric (SSIM) between images. Note: This function requires skimage. """ assert x.dtype == y.dtype return structural_similarity(x, y, channel_axis=2, ...
6183c839168a9043c39c12d722142b8de751b1b4
39,994
def get_config_data(request): """ Sends form configuration data to the frontend. This allows clientside validation to mirror serverside validation. """ return JsonResponse({ "nameMaxLength": settings.CONTACTFORM_NAME_MAX_LENGTH, "organizationMaxLength": settings.CONTACTFORM_ORGANIZA...
e93e6b790af947008410bf99ce76f1e10f8caeb3
39,995
def read(fileObj, securityTrader=None, _flowType=None): """ 读取 excel 文件,并返回 :param fileObj: 已经打开的 file 文件实例,限制 file 实例是为了可以不依赖磁盘文件,直接使用内存 :param securityTrader: 对应的券商 :param _flowType: :return: """ flowing = Flowing.open(fileObj, securityTrader) return flowing
90d34bde95d80cc91c5868e44c9880be3adf1d67
39,996
def register_for_init_call(m): """ Decorator that tags a method to be called at the end of processing cmds. NOTE: This decorator MUST BE the outermost decorator used on a method decorated with multiple decorators! The custom user attributes of a method aren't preserved in python 2.7 even...
8d10aadd600e2e83089d0095d320a8b2a2aac3e1
39,998
def breakup_names(df): """Breakup full name into surname, title, first name""" df[['surname','given_name']] = df['Name'].str.split(",", expand= True) df[['title', 'first_name']] = df['given_name'].str.split(n=1, expand= True) df = df.drop(columns=['Name', 'given_name']) return df
ee76975b88702daf47fa9638c4d1217ca22e1e6e
39,999
import typing def get_state_change_with_balance_proof( storage: sqlite.SQLiteStorage, chain_id: typing.ChainID, token_network_identifier: typing.TokenNetworkID, channel_identifier: typing.ChannelID, balance_hash: typing.BalanceHash, sender: typing.Address, ) -> sqlite.S...
e8e7d3ec2e77ddd34fc9a667ffb163e9e6348e32
40,003
import random def best_down_collapse(X,kX,dimq,signal): """Returns the down-collapse V which minimize the topological reconstructione error ||s-phi*_Vpsi*_V(s)|^2 """ s=np.array(signal)**2 Bq=kX[dimq] BT=Bq.copy() C=BT.tolil() ind=C.rows possible_min_WQ=[] possible_min_value=[] ...
2af47e329fea00db7cab5e8e8cb56099cf3e2a5a
40,004
def evaluate_lambda_t(t, phi_start, linear, phase0): """ Evaluates firing rate(t, x) = tuning_curve(x) * theta_modulation(t, x) at given time points :param t: sample time points :param phi_start: starting point of the place field (in rad) :param linear: flag for circular vs. linear track -> slightly...
04a6830e34945dea83c70c5fca969c09bf17594e
40,005
import struct def _mapc(ctx, input_files, resource_info): """Creates actions that compile a Core Data mapping model files. Each file should be contained inside a .xcmappingmodel directory. Args: ctx: The Skylark context. input_files: An iterable of files in all mapping models that should be ...
2c38e2b69f30763b31ab3b9d4b88deeb3e4dcbf7
40,006
from pathlib import Path def image_content_type(outfile: Path) -> str: """ Derives a content type from an image file's suffix """ return f"image/{outfile.suffix[1:]}"
4c1545dbdcaa31826fd8567cabe2935ed7237961
40,007
def play_again() -> str: """Ask the user if he wants to play another turn""" yes_or_no = input('Play again? [y/n]: ') while yes_or_no not in ['y', 'n']: yes_or_no = input('Please insert "y" or "n": ') return yes_or_no
8b3d74456b7ce13a0ffffab8dc9e946cbb5e594c
40,008
def create_session (user, is_trusted): """ Perform user authentication User.password and role activations. This method must be called once per user prior to calling other methods within this module. The successful result is Session that contains target user's RBAC User.roles. This API will... ...
c87c2e58420dca6923cf251736728e9320aa1bde
40,009
def ansi_wrap(value: str, width: int = 80, left_pad: int = 6) -> str: """Wrap characers relative to their cell width.""" decoded_text = decode_ansi(value) wrapped_text = "\n".join(_wrap_ansi(decoded_text, width=width, left_pad=left_pad)) return wrapped_text
611eacafdb15d99aaa7f20a2b0af61c23f402d12
40,010
def hashcolumns(dframe, columns, maxval): """ Hash each value of multiple dataframe columns. """ columnvals = list(zip(*(dframe[col] for col in columns))) return list(hashval(v, maxval) for v in columnvals)
0cec3d573c743459ef40e6c877cd32eb7e48d7fb
40,011
import random def random_triangles(n=3): """ Draw n triangles which can overlap """ coords = [] for i in range(n*3): coords.append([random.random()*5, random.random()*5,random.random()*5]) coords = np.array(coords) faces = [] for i in range(n): faces.append([i*3, i*3+1, i*3+...
c7fb47b0c8054d052d1f3e883a62111fb67c563a
40,012
def get_config(): """Get the default hyperparameter configuration.""" config = ml_collections.ConfigDict() config.problem = "classification" config.env_model = "MLP" config.agent = "KalmanFilter" config.seed = 0 config.nsteps = 20 config.ntrials = 20 config.train_batch_size = 1 ...
dee1e80ad054c3dbaf543a36eb00b0ae88ae2475
40,013
def make_vbox(model_dict: dict) -> widgets.VBox: """ :param model_dict: :return: """ labels = [] for k in model_dict: if type(model_dict[k]) is not dict: string = str(model_dict[k]) labels.append(make_setting_hbox(k, string)) else: mini_labels...
cde09236834d63fcb3e2067d2dffe2a02f164a22
40,015
def UserTypingFilter(cli): """Determine if the input field is empty.""" return (cli.current_buffer.document.text and cli.current_buffer.document.text != cli.config.context)
420b24cdeb17cb97294a937e49096c5462d4061e
40,016
from typing import Sequence def create_myst_config( settings: frontend.Values, excluded: Sequence[str], config_cls=MdParserConfig, prefix: str = "myst_", ): """Create a configuration instance from the given settings.""" values = {} for attribute in config_cls.get_fields(): if attri...
c01965aa451b871cf7a37a5470f121122ac9132b
40,017
def scale_image(image, new_width=600): """ scales the image to new_width while maintaining aspect ratio """ new_w = new_width (old_w, old_h) = image.size aspect_ratio = float(old_h)/float(old_w) new_h = int(aspect_ratio * new_w) new_dim = (new_w, new_h) image = image.resize(new_dim) ...
e9bfdf6309cf97b1a7f44dff96b655aa09d64fd5
40,019
def get_container_metadata(item): """Extract desired metadata from Docker container object.""" if type(item) is str: return item tags = getattr(item, 'tags', None) if tags is not None: return tags[0] else: return str(item)
bf805e33f17dc664a62989f36ae164ee3c348b3e
40,020
def leaky_relu(alpha=0.1, name='LeakyReLU', collect=False): """Modified version of ReLU, introducing a nonzero gradient for negative input. Args: alpha: `int`, the multiplier. name: operation name. collect: whether to collect this metric under the metric collection. """ def _le...
de44b67e4dcd3e84e86aca8b00ec57f37b5f4c69
40,021
def show_sample_attributes(request): """ show the user-defined sample attribute home page """ ctxd = {} ctx = RequestContext(request, ctxd) return render_to_response( "rundb/sample/sampleattributes.html", context_instance=ctx, mimetype="text/html" )
76574030051e108a4d9e0590a153728e0531fb21
40,022
def get_pks(constraints): """Get primary key(s) given constraint list""" pks = {} if constraints: for name, constraint in constraints.items(): if constraint['type'] == PRIMARY and len(constraint['columns']) == 1: column = constraint['columns'][0] pks[colu...
0033779e880bee0fc7736adfbb0effb5934d038f
40,023
def _invoke_function(function_name, json_args, json_kwargs): """Invokes callback with given function_name. This function is meant to be used by frontend when proxying data from secure iframe into kernel. For example: _invoke_function(fn_name, "'''" + JSON.stringify(data) + "'''") Note the trip...
df3423ba5ce31ffb70b7b34a5684de69b0327fc2
40,024
def single_particle_first2p_zbt_metafit(fitfn, exp_list, **kwargs): """Fit to zero body terms for all available normal-ordering schemes, taking only the first 2 points from each """ return single_particle_metafit_int( fitfn, exp_list, dpath_sources=DPATH_FILES_INT, dpath_plots=DPATH_PLOT...
1381cccb1482f6cb240c6d965b5930b37377c8f9
40,025
def interact_GxG(pheno,snps1,snps2=None,K=None,covs=None): """ Epistasis test between two sets of SNPs Args: pheno: [N x 1] SP.array of 1 phenotype for N individuals snps1: [N x S1] SP.array of S1 SNPs for N individuals snps2: [N x S2] SP.array of S2 SNPs for N individuals ...
d04ee8132fe002e4aaf63bf71273244c19e379c0
40,026
def _get_clone_readiness(media, dtype): """ Checks the given media for clones and determines their readiness for archiving. """ if dtype == "image": return _get_single_clone_readiness(media, "image") if dtype == "video": return _get_single_clone_readiness(media, "archival") if dt...
0103942413fea87b7ac630f80a0374b7a64afdb9
40,027
def bot_is_public(): """Don't use this elsewhere.""" async def bot_public(ctx: SalamanderContext) -> bool: assert isinstance(ctx.cog, Meta), "safe enough" # nosec cog: Meta = ctx.cog info = await cog.cached_info.get_app_info() return info.bot_public or await ctx.bot.is_owner(ct...
85f412d7ba91f7748bc9561cfb7eac3dade91240
40,028
def objmap_streamfunc_uvh(xd, yd, ud, vd, hd, xm, ym, l, SNR, fcor, g=9.81, return_err=False): """Map velocity and height observations to non-divergent geostrophic stream function. The Coriolis parameter fcor and gravity (or reduced gravity) g should be specified.""" xd = np.asarray(xd).ravel() yd = np....
0d2b9853b063b324262a1a1ecb9c6cd3a61a8769
40,029
import html def visualize_game_round_count(): """ Prints round count of a game. :return: html code """ return html.Span('Rounds: {0}'.format(len(pre.round_names)), style={'padding': '5px', 'fontSize': '16px'})
cac271ea54abb0c91eadb426f1965bbfe864b1eb
40,030
def get_window_icon(hwnd): """Return QPixmap.""" #hicon = win32gui.GetClassLong(hwnd, win32con.GCL_HICON) hicon = get_hicon(hwnd) if not valid_handle(hicon): return None try: return make_qicon(hicon) except: return None #info = win32gui.GetIconInfo(hicon) #try: ...
5dcc6af381f06d3c3d422c2c5b67721fbd7b5ca4
40,031
def ec_entity(response): """ Return URL or File entity in Demisto format for use in entry context depending on data in 'response' (the report) Parameters ---------- response : dict Object returned by ANYRUN API call in 'get_report' function. Returns ------- dict Fil...
81ec1a9d3a932de63b3edd0ca93c88988ea380fd
40,032
def generate_map(df: pd.DataFrame): """" Generates the map for the dashboard Parameters ---------- df : pandas dataframe The dataframe that contains the data to plot. Returns ------- chart : html of altair Chart The generated map converted to html """ world_map ...
cbb4af10249b538ed4bbc276b854221b8984dd28
40,033
def mapped_route_add(request): """ Страница конструктора, которая позволит задавать последовательность остановок, Далее, открыть карту и построить промежуточные маршруты, Подтвердить и исходранить маршрут в БД. :param request: :return: Template of constructor """ template_name = 'admin_...
447f236c2560953e8ddcb3594e9a3e9aa91d0b9b
40,034
def percentage(sub, all): """Calculate percent relation between "sub" and "all". Args: sub (int): Some value. all (int): Maximum value. Returns: int: (sum * 100) / all """ return int((sub * 100) / all)
21b398c81f76de0ec81be9d26b2f79d8b0d08edc
40,035
def symbolicTz(z = 0): """ Translation on «z» axis. Returns Dual Quaternion in matrix form """ return Matrix([[1], [0], [0], [0], [0], [0], [0], [0.5 * z]])
19a9c3c1476593f776117a4787cd1a7bba7191b8
40,036
def get_branch_all(git_dir): """ Return all branch names). """ try: output = git('-C', git_dir, 'branch', '--all') except ErrorReturnCode as e: return failed_util_call_results(e) else: return succeeded_util_call_results(output)
3a5bfc05832a5f9eb474ff9aae0f2ef79baecdf0
40,037
from typing import List def _databases(is_refresh: bool, current_path: str, session: ObjectExplorerSession, match_params: dict) -> List[NodeInfo]: """Function to generate a list of databases""" _default_node_generator(is_refresh, current_path, session, match_params) is_system = 'systemdatabase' in current...
614943d8fd13324476495d207018107761c7a26e
40,038
def get_run_runtime(dataset_id, vm_id, run_id): """ loads a runtime file (runtime.txt) and parses the string to return time, runtime_info""" run_dir = (RUNS_DIR_PATH / dataset_id / vm_id / run_id) if not (run_dir / "runtime.txt").exists(): return None runtime = open(run_dir / "runtime.txt", 'r'...
f393a61a314099f906801f9520af666576fb65cf
40,039
def metrics(bb1, bb2): """Computes metrics between two boxes""" i1, j1, w1, h1 = to_tlwh(bb1) i2, j2, w2, h2 = to_tlwh(bb2) top = max(i1, i2) bottom = min(i1 + h1, i2 + h2) left = max(j1, j2) right = min(j1 + w1, j2 + w2) overlap_height = bottom - top overlap_width = right - left ...
28199a66e8c84387a846ced8956d125f851e29b1
40,040
def web_tokenizer(sentence): """ The web tokenizer works like the :func:`word_tokenizer`, but does not split URIs or e-mail addresses. It also un-escapes all escape sequences (except in URIs or email addresses). """ return [token for i, span in enumerate(web_tokenizer.split(sentence)) fo...
bfaee7d3c7f2dddc21699371d69932922523bee3
40,041
import re def _check_directory_files_permission(block_id, block_dict, extra_args=None): """ Check all files permission inside a directory """ path = runner_utils.get_param_for_module(block_id, block_dict, 'path') permission = runner_utils.get_param_for_module(block_id, block_dict, 'permission') ...
0483ff9c9fe3ce00d099333e7e725c62bb696be7
40,042
from datetime import datetime def async_parse_date_datetime( value: str, entity_id: str, device_class: SensorDeviceClass | str | None ) -> datetime | date | None: """Parse datetime string to a data or datetime.""" if device_class == SensorDeviceClass.TIMESTAMP: if (parsed_timestamp := dt_util.pars...
d305ce88627d8d7bb98307399db69be64fc0b6df
40,043
def region_of_interest(img, vertices): """ Applies an image mask. Only keeps the region of the image defined by the polygon formed from `vertices`. The rest of the image is set to black. """ #defining a blank mask to start with mask = np.zeros_like(img) #defining a 3 channel...
741d7a2af2e6c91d99d69020161981e4fedbbc51
40,044
async def app_factory() -> web.Application: """Created to launch app from gunicorn (see docker/boot.sh)""" app_settings = ApplicationSettings() assert app_settings.SC_BUILD_TARGET # nosec log.info("Application settings: %s", app_settings.json(indent=2, sort_keys=True)) app, _ = _setup_app_from_se...
10916d0ec81941621dc475603797f6082b2a5228
40,045
def makeone(pb, params, where, compdir=None): """ Crée une donnée pour l'apprentissage du problème "Le jardinier et les taupes" : 1. Génère une instance du problème dans la version du module `pb`, pour les paramètres `params`. 2. Résout cette instance. 3. Sauvegarde la gri...
40c5f7f65bc4146d38d189efe61dbd4410fdc202
40,046
from dateutil import tz def _collapse_to_cwl_record(samples, want_attrs): """Convert nested samples from batches into a CWL record, based on input keys. """ input_keys = sorted(list(set().union(*[d["cwl_keys"] for d in samples])), key=lambda x: (-len(x), tuple(x))) out = {} for key in input_keys: ...
ed5efb1a6c8c072cc7ed063676b8948789dff219
40,047
def open_old_stds(name, type, dbif=None): """This function opens an existing space time dataset and return the created and initialized object of the specified type. This function will call exit() or raise a grass.pygrass.messages.FatalError in case the type is wrong, or the space time d...
c0def972f41cc8bd2a15d5ce14b81cc388e02725
40,048