content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def getInversePermutation(permutation): """Invert a given permutation vector. :param list | tuple | np.ndarray permutation: Permutation vector to invert. :return: Inverted permutation vector. :rtype: list """ inverse = [0] * len(permutation) for i, p in enumerate(permutation): inve...
f8fe339f2b0a7fc8180252b99f3fce742f215a13
77,135
def number2latex(val, **kwargs): """ Converts a number into a representation nicely displayed by latex """ if val.__class__.__name__ == 'Quantity': # assume it is a pint quantity if kwargs.pop('long_unit', False): unit = "\\,{:L}".format(val.units) else: unit = "...
eddd772ff8c345a6925db820d523f9a9da7ed34f
77,136
def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation wo...
b2e8181e54c18618450b13e1182d6d5ea1144b42
77,137
import logging def create_logger(): """ Creates a log in Stackdriver """ instance_name = get_hostname() logname = '%s.log' % instance_name logging_client = logging.Client() logger = logging_client.logger(logname) return logger
9cef87ed4d1fecb93e398b0265b20ae97e55d93b
77,138
def partitionByParentGeocode(block_nodes, num_partitions=None): """ Partition an RDD of geonodes by parent geocode """ return block_nodes \ .map(lambda node: (node.parentGeocode, node)) \ .partitionBy(num_partitions, lambda k: int(k) if len(k)>0 else 0) \ .map(lambda d: (lambda parent_co...
7792125722611c29e4e7af21e8d98ebfb4a81722
77,141
def get_minmax(g): """ Calculate the min and max of the Golly toroid coordinates. """ # get height and width g_xspan = g.getwidth() g_yspan = g.getheight() # calculate min and max g_xmin = - int(g_xspan / 2) g_xmax = g_xspan + g_xmin g_ymin = - int(g_yspan / 2) g_ymax = g_yspan + g_ymin # retu...
00563db83a538483b2b6d5d8f0be0617d2322ea6
77,142
def create_api(): """return api object at startup""" api = Api() api.add_resource(Relay, '/') return api
7089df0e6a2be80b009b94320bb2c2263be684e8
77,143
import scipy def _kolmogn(n, x, cdf=True): """Computes the CDF(or SF) for the two-sided Kolmogorov-Smirnov statistic. x must be of type float, n of type integer. Simard & L'Ecuyer (2011) [7]. """ if np.isnan(n): return n # Keep the same type of nan if int(n) != n or n <= 0: ...
eaff5775f3d8d1aea192fff3653aed4094e78112
77,144
def apply_density_loss(rho, n, m, eta): """Applies loss to an input density matrix and traces out loss modes rho: density matrix over lossy basis (including zero state) n: number of photons m: number of modes eta: power loss (i.e. transmission = 1-eta; t=sqrt(1-eta)) Returns density matrix of sa...
15942f984a46232d9b9720624a9bb382adc02fb4
77,146
from typing import Union from typing import IO from typing import AnyStr from typing import List def _flatsaxParse(fl: Union[FilePath, IO[AnyStr], str]) -> List["Flattenable"]: """ Perform a SAX parse of an XML document with the _ToStan class. @param fl: The XML document to be parsed. @return: a C{l...
f87526292681735ca4557e1ee57790690f959f9c
77,147
def is_image(content_type): """is the given content_type string for an image? Args: content_type: string containing Content-Type HTTP header value Returns: Boolean """ return (str(content_type).count("image") > 0)
c69f163e09d8b68e179dd8765ef8401d988ac433
77,148
def eventLists(): # REPLICATED: utils/botHelperFunctions eventLists() """ Load defined event names Returns ------- searchEV : list of strings (event names) Just grabs every event defined in the file in (hardcoded) `keyEventDB` str varible as of this, that file is listO...
b8e7eb6f069868558dc29f75b10b162c209ea2ce
77,149
def lu_compact(A): """ This performs LU Decomposition on `A` """ assert A.shape[0] == A.shape[1] U = A.astype(np.float64) n = A.shape[0] L = np.eye(n).astype(np.float64) for k in range(n - 1): for j in range(k + 1, n): L[j, k] = U[j, k] / U[k, k] U[j, k:...
ab76c19e4974d0e11036f37551c85f0addd2078c
77,150
def mkcomboentry(prompt, row, table, options): """Create and return a combo entry within a gtk table.""" l = gtk.Label(prompt) l.set_alignment(1.0, 0.5) l.show() table.attach(l, 0, 1, row, row+1, gtk.FILL, gtk.FILL, xpadding=5) c = gtk.combo_box_new_text() c.show() for opt in options: ...
09b60bce908ded14f0992dd6d62567643cc69e32
77,151
def _calcEndPointSep(fiberData, fidx): """ * INTERNAL FUNCTION * Calculates distance between end points INPUT: fiberData - fiber tree containing tractography information fidx - fiber index OUTPUT: D - distance between end points """ endpt = fiberData.pts_per_fiber - 1 ...
360799ceb13412d3eddf75b84c74ee0b850c9f2e
77,152
import numpy def matrix_multiply(m1,m2): """ Multiplies the input matrices. Inputs: m1,m2: the input matrices Returns: result: matrix product of m1 and m2 in a list of floats """ product = numpy.matmul(m1,m2) if type(product) == numpy.int64: return float(pro...
0447553f7fa7968cbb13fcaf7319391650377e49
77,153
def parse_and_append_solute_data(solute_data, solute_data_results, solute_estimator, solute_epi_unc_dict): """ Parse and append the `solute_data` to the `solute_data_results` dictionary. If `solute_epi_unc_dict` is given, it is also parsed and appended to the `solute_data_results` dictionary. It also re...
04410d96139813b1a9c1a758796b33dc4a105a56
77,154
import base64 def read_encoded(filename: str) -> str: """Read a file and return the base64 encoding of its contents.""" with open(filename, 'rb') as infile: return base64.b64encode(infile.read()).decode('utf-8')
4d2c5c8f36b2ebe67a67714f6313a32d4d6bf005
77,155
def dihedral(a, b, c, d): """ Calculate the A - B - C - D dihedral angle in radians. For collinear or close to collinear structures return a warning. """ collinear = 0 if abs(abs(angle(a, b, c)) - 180.) < 5. or abs(abs(angle(b, c, d)) - 180.) < 5.: collinear = 1 b0 = a -...
de935d41deb4424df9193f3c27a93c8297155241
77,156
def entity_types(request): """View to display a list of all the entity types.""" entity_types = EntityTypeList.objects.all() context_data = {'entity_types': entity_types} return render(request, 'eats/view/entity_types.html', context_data)
fe9f573523cefc3c2e7c808c03d693b30ee6e3c4
77,157
def fetch_electricity(data_home=None, silent=True): """A day of electricity prices in New South Wales. The data contains 45,312 items and 8 features. The goal is to predict whether the price of electricity will go up or down at very frequent intervals. Parameters: data_home (str): The director...
3152648c397a0b69c86a3969f7ddf32573e991ce
77,158
import re def strip_irc_colors(data): """Strip mirc colors from string. Expects data to be decoded.""" return re.sub('[\x02\x0F\x16\x1D\x1F]|\x03(\d{1,2}(,\d{1,2})?)?', '', data)
2c4e480cc00e3704a0086522c8bb7409fca0af6e
77,159
from typing import Optional async def get_character_ids_from_class(profile: DestinyAccount, destiny_class: str) -> Optional[list[int]]: """Return the users character_ids that fit the given class or None""" result = await profile.get_character_info() if not result: return # loop through the ...
d8426b4b80154a3d49f464da702c2018ec3ebf6b
77,160
def direct_unordered_attachments(t, m): """Enumerate the ways of directly attaching t unlabelled free nodes to l unlabelled nodes.""" return IntegerPartitions.fixed_length_partitions(t+m, m)
82abe1382c5adb59c2d2554cfaefa60e887906a3
77,161
def deeplift(score_func, X, batch_size=200,task_idx=0, num_refs_per_seq=10,reference="shuffled_ref",one_hot_func=None): """ Arguments: score_func -- deepLIFT scoring function X -- numpy array with shape (n_samples, 1, n_bases_in_sample,4) or list of FASTA sequences batch_size -- numbe...
4452e0127dea0d335384a200431dbe493f958fab
77,162
from typing import List def get_main_corpus() -> List[str]: """Returns the list of tweets (content as text) to consider as the main corpus""" return list(set(get_text_from_all_tweets(city="Caracas")))
a1b94404bd340a6513b912f9229c2db2e2f9f48f
77,163
def get_labels(n_rows=15, seed=None): """ Generates a random vector of labels. """ np.random.seed(seed) return np.random.randint(0, 2, size=(n_rows,))
4265c48e3dfb4dafc17358f772bc7a04d3c01ba2
77,164
def _rotate_mirror_do(im): """ Duplicate an np array (image) of shape (x, y, nb_channels) 8 times, in order to have all the possible rotations and mirrors of that image that fits the possible 90 degrees rotations. It is the D_4 (D4) Dihedral group: https://en.wikipedia.org/wiki/Dihedral_group ...
ffd88b473f120b9893add90031bfc4e841e60b2f
77,165
def do_cavity_freq_sweep(cavity, localos, cavity_freq, acq_ctrl, cavity_pm=10e6, freq_step=1e6, demod_freq=None, delay=0.01, do_plots=True): """ Function which sweeps the cavity frequency around central value by pm_range and measures using given acq_ctr, als...
95a8bc3296f4b847343575cfd8123dc873f54212
77,166
import warnings def normalize(av, vmin=0., vmax=1.): """ normalize an array to the range vmin/vmax """ if vmin == vmax: return np.ones_like(av)*vmin elif vmax < vmin: warnings.warn("swapping vmin and vmax, because vmax < vmin.") vmin, vmax = vmax, vmin norm_one = (av -...
4db466fdb00f01d6846c1e13f6bbc4fee21db4bc
77,168
def PurgeWorkOrder(work_order_file: str, **kwargs): """ Simply resets an existing work order to status 0 by rewriting it :param str work_order_file: file path to a work order file :param kwargs: varios parameters taht all get ignored. Just there for compatiblity reasons :return: True if file writing...
1548b4bebc223b13221591ca9f5dd24b47ecf1a3
77,169
def normalised_ellipse_mask(ellipse): """Return a normalized copy of the supplied ellipse. Here 'normalised' means that the rotation is as close to zero as possible. Examples: >>> normalised_ellipse_mask( ... ((1, 2), (100, 200), 90) ... ) ((1, 2), (200, 100), 0) ""...
af5316ace76642667340a986f3d1c2d69934a333
77,170
def circular_velocity(k, a): """Circular velocity for a given body (k) and semimajor axis (a).""" return circular_velocity_fast(k.to_value(u_km3s2), a.to_value(u.km)) * u_kms
d692ab405718a1edc98dfa02b2490b0ce8a8e09e
77,171
import math def format_bytes(size, precision=2, max_units=True, with_units=True): """ Returns a formatted byte size (e.g. "421.45 MB" or "421,451,273 bytes"). @param precision number of decimals to leave after converting to maximum units @param max_units whether to co...
c1671e5f131341e2823725c5c5e33c648c8a039e
77,172
def line_distance(line1, line2, image_shape): """calculate a distance score between two lines""" # find the intersection of line 1 with the edges of the image line1_image = line_segment_within_image(line1, image_shape) n_points = 10 sample_points = np.arange(0, n_points) / (n_points - 1.0) l...
a59e4537c8278a4c2526312df049e224e1de9f85
77,173
from functools import reduce def xor(*values): """An `exclusive or`_ operation on a list of values. .. _exclusive or: https://en.wikipedia.org/wiki/Exclusive_or :rtype: bool :returns: ``True`` when an odd number of values are ``True`` or ``False`` when an even number of values are ``Tr...
d5dfbff2648f208dc192fd06da0c988c6bb9baaf
77,174
def probability_of_sum(total:int, dice1, dice2): """ Brief: Basic probability - Dice cast Suppose a pair of fair 6-sided dice are thrown. What is the probability that the sum of the rolls is 6? (Answer as a simple fraction of integers) reference: https://statweb.stanford.edu/~susan/courses/s6...
b48e9db4dd40048d24a3dfb481406346076b7132
77,175
def get_source_with_id(result): """Return a document's `_source` field with its `_id` added. Parameters ---------- result : dict A document from a set of Elasticsearch search results. Returns ------- dict The document's `_source` field updated with the doc's `_id`. """...
be9b25ad65a8474aa41d3f927664abdb89a674d5
77,176
def kmeans_pc_clustering(hgt_anom, n_modes=20, n_clusters=4, lat_name=None, lon_name=None, time_name=None, **kwargs): """Perform k-means clustering of leading PCs. Parameters ---------- hgt_anom : xarray DataArray Array containing geopotential h...
3df5c0be37da20d16c598bdcf75a9d755a617b15
77,177
def apply_x_frame(response): """Include X-frame header in http response to protect against clickhiJacking.""" response.headers["X-Frame-Options"] = "SAMEORIGIN" return response
3cc3b572eb64e856512fd8b41191f601bcbcc96c
77,178
def coef_domain2(an1_mid, bn1_mid, an2_mid, bn2_mid, random_start=1, halfwidth0=1, pow=-1): """ return the parameter domain centered at the an1, bn1, an2, bn2 """ domain1 = coef_domain(an1_mid, bn1_mid, random_start=random_start, halfwidth0=halfwidth0, pow=pow) domain2 = coef_domain(an2_mid, bn2_mid...
2b45e1b53d7597570af87544b6b27726e415bd21
77,179
def get_RoI_features(model, features, proposals, with_shared_fcs=False, only_cls_scores=False): """ Extract features from either the RoI pooling layers or shared Fully-connected layers or directly return the class_scores from the final class predictor itself. Args: model (nn.Module): The loaded dete...
81c271f505be60e6662a50e4d03e569e59d623b1
77,180
import token def get_node_output(cid,nid): """Get the latest node output.""" data={"api_token": token, "api_email": user, "c": "get_node_output", "cid": cid, "nid": nid} resp = flowr.POST(headers = standard_headers, data=data) # returns JSON formatted ...
d9db51f278ffacb9c067f46075aa0ec9c097e581
77,181
def create_rest_client(server, retry_multiplier, retry_max_exp, retry_stop, verbose): """ Create a RestClient with retry config set from command line options. """ if verbose: log("Connecting to Entity Matching Server: {}".format(server)) retry_config = ClientWaitingConfiguration(retry_multip...
c1bee6f7abbdf8caff8ba5ef4ef8722b9786dd12
77,182
def multiply_probs(ln_pa, ln_pb): """ Returns the log probability of multiplied probabilities. Pc = Pa * Pb => ln(Pc) = ln(Pa)+ln(Pb) """ return ln_pa+ln_pb
5e541072c9aaf327536196ab4ffc9e3bf488ccf0
77,183
def tapping_XY(ref, pre_l1_tap_flat, pre_l0_tap_flat, prerr_l0_tap_flat, prerr_l0__, mode = 'm1'): """block_models.tapping_XY Tap data from the sensorimotor data stream and build a supervised training set of inputs X and targets Y suitable for machine learning algorithms. """ # print "tapping p...
8ec6bbcd2a0448d50c8a1d5564aaef7c9ff0ec1d
77,185
def _Run(args, holder): """Issues requests necessary to list service attachments.""" client = holder.client request_data = lister.ParseRegionalFlags(args, holder.resources) list_implementation = lister.RegionalLister( client, client.apitools_client.serviceAttachments) return lister.Invoke(request_data...
e7714d6c4846e3410fb822cf902cccdf02b833f8
77,186
def update_user(uid, **kwargs): # pylint: disable=differing-param-doc """Updates an existing user account with the specified properties. Args: uid: A user ID string. kwargs: A series of keyword arguments (optional). Keyword Args: display_name: The user's display name (optional). Ca...
8a3f78186800f4e768cf9a7d622f3efdcfc133f6
77,187
def get_meta_data(**args): """ Get the meta data for a set of bibcodes """ data_dict = {} # This information can be retrieved with one single Solr query # (just an 'OR' query of a list of bibcodes) bibcodes = [bibcode for (bibcode,score) in args['results']] list = " OR ".join(map(lambda ...
65f41d0d0cecae85d3e728069258b1045ce20c42
77,189
def test_data_fetch_relations(filter_id = "WIK_KET_Rioolgemaal"): """Test of related locations goed worden weggegooid.""" tuple_values = data.filters.get_tuples([filter_id]) data.locations.fetch(tuple_values) return "BER-HEE-KER" not in data.locations.df["locationId"]
d158c390b208397af4f2d556f04eed9952665276
77,190
def get_budget(args): """ Метод для получения данных о документах :param args: :return: """ provider = Provider() answer = provider.get_budget(args) return answer
509a36cd157c54f794822a3155ea2701779fd89a
77,193
def newton_dynamics(f, x0, steps, epsilon=0.01): """Just do Newtonian Hamiltonian dynamics, no momentum randomization and no MH reject.""" shape = x0.shape xs = t.zeros((steps + 1,) + shape, dtype=x0.dtype) vs = t.zeros((steps + 1,) + shape, dtype=x0.dtype) v = t.randn_like(x0) x = x0 xs[0],...
309914c8562c607d5600128c7359bc8c702f5700
77,194
def model(inpt, num_actions, scope, reuse=False): """This model takes as input an observation and returns values of all actions.""" with tf.compat.v1.variable_scope(scope, reuse=reuse): out = inpt out = fully_connected(out, num_outputs=64, activation_fn=tf.nn.tanh) out = fully_connected(...
e96390633eba58c5e36ec87d7d15e846f96e8cdc
77,195
def get_height(image): """get_height(image) -> integer height of the image (number of rows). Input image must be rectangular list of lists. The height is taken to be the number of rows. """ return len(image)
3aa94c4b2458d2a233f32ee10889e52566c04ecb
77,196
import time def th_C(tab, tab1, par, nthreads=-1, write=True, plot=False, **kwargs): """ Given two astropy data tables, cross-count pairs in angular space All input parameters that control binning, column names, etc. are passed in a single dictionary ``par``, which can be easily generated wit...
729ae4bf76968793452514c3776f87e00357337f
77,198
def convert_predict_response_into_nparray(response, output_tensor_name): """ :param response: :param output_tensor_name: :return: """ dims = response.outputs[output_tensor_name].tensor_shape.dim shape = tuple(d.size for d in dims) return np.reshape(response.outputs[output_tensor_name]....
648adfc2e30115791d56dda00246dfa2142aa194
77,200
import torch def normalize_image_into_standard_form(img): """the input image should in gray x,y""" img = (img-img.min())/(img.max()-img.min()) sz = [1,1]+ list(img.shape) img_t = torch.Tensor(img) img_t = img_t.view(sz) return img_t
8da901135cffc3cc36d5be969ee2e2f94f75f74e
77,201
def is_power_of_two(n: int) -> bool: """ >>> is_power_of_two(1024) True >>> is_power_of_two(5) False """ return n & (n - 1) == 0
e56997fd768c5b6e74f179969b1681a1e0c33e78
77,202
def api_team_unlock_problems_and_contests(teamID: int): """ 团队用户解锁团队题目和团队比赛和团队习题集 """ user: User = db.session.query(User).filter_by( id=session.get("uid", -1)).one_or_none() if not user: return make_response(-1, message="请登录") team: Team = db.session.query( Team.team_prob...
2ec0deddd6d52d5f7178ddcebc1a625b9dd5d83b
77,203
from typing import List def normalize( path: PathLike, steps: int = 5, chunk_size: int = 512, threshold: float = 0.20, cp_isolation: List[str] = None, cp_exclusion: List[str] = None, preemptive_behaviour: bool = True, ) -> CharsetMatch: """ Take a (text-based) file path and try to ...
a6f30fe16df7bf602f681b14a5e1b6a829cbad01
77,204
def _is_version_satisfied(specifier: str, sys_version) -> bool: """ SpecifierSet("") matches anything, no need to artificially lock down versions at this point @see https://warehouse.readthedocs.io/api-reference/json.html @see https://packaging.pypa.io/en/latest/specifiers.html """ specifie...
6ecc7854de41e28c50f7503ece2260638009cc62
77,206
from datetime import datetime def run_typing_test(topics): """Measure typing speed and accuracy on the command line.""" paragraphs = lines_from_file('data/sample_paragraphs.txt') def select(p): return True if topics: select = about(topics) i = 0 while True: reference = choose(p...
e6d1c74783b9ae2568a2fe9b77ca7b80bc5e473c
77,207
def prepend(value, iterator): """ Prepend a single value in front of an iterator """ return chain([value], iterator)
e7118db2405094d36815f33911b1314c3511360d
77,209
def ATL06_2_gdf(ATL_fn, dataset_dict, ancillary=False): """Wrap ATL_2_gdf with defaults for ATL_06.""" check_name = 'land_ice_segments' return ATL_2_gdf(ATL_fn, dataset_dict, check_name=check_name, ancillary=ancillary)
c16046d745f3241904fab63f2c710a3ba84fb601
77,211
def scenario_1(commodities) -> TScenario: """ Returns the setup for scenario 1 in ADR13. See the module-level docs for details on scenario setups. """ keys = ["9999_80_1", "9999.10_80_2"] collection = create_collection(commodities, keys) changes = [ CommodityChange( col...
8b71ec2bef5fcc096494366c587ad4d37f2b9fb6
77,212
def _GroupSymbolsByOffset(binary_filename): """Produce a map symbol name -> all symbol names at same offset. Suffixes are stripped. """ symbol_infos = [ s._replace(name=RemoveSuffixes(s.name)) for s in symbol_extractor.SymbolInfosFromBinary(binary_filename)] offset_map = symbol_extractor.GroupSym...
8ec0b87ac2d31c1e89f515efa42b3a5e89def1b2
77,213
import bempp.api from scipy.sparse import coo_matrix import numpy as np def p1_trace(fenics_space): """ Return the P1 trace operator. This function returns a pair (space, trace_matrix), where space is a Bempp space object and trace_matrix is the corresponding matrix that maps the coefficients of ...
5e58e76d14970c4f9828a9386b71d62c866865be
77,214
def service_c_hours(request): """ Renders the service chair way of viewing total service hours by brothers """ if not utils.verify_service_chair(request.user): messages.error(request, "Service Chair Access Denied!") return HttpResponseRedirect(reverse('dashboard:home')) brothers = Brother.o...
4f640e29d9a66deb5b179758952cf24ac831366a
77,216
import requests def event_ancestors(id='R-HSA-5673001'): """ The Reactome definition of events includes pathways and reactions. Although events are organised in a hierarchical structure, a single event can be in more than one location, i.e. a reaction can take part in different pathways while, in the ...
35cb3944883ac97a8168ba4d8e1e5f908f094f0f
77,218
def get_word_sentiment(word): """Return a sentiment representing the degree of positive or negative feeling in the given word. >>> sentiment_value(get_word_sentiment('good')) 0.875 >>> sentiment_value(get_word_sentiment('bad')) -0.625 >>> sentiment_value(get_word_sentiment('winning')) 0...
59d6f673eb6744bea78f2be82ae776e42a5c3dd3
77,220
def fit_spec(): """Fit specification.""" data = dict( a=1.0, sig_a=2.0, b=-3.0, sig_b=4.0, r2=5.0, q=6.0, chi2=7.0, nu_chi=8, exp_id=1, idx=0, mddp=9.0, sig_mddp=9.1, x1s=10.0, sig_x1s=10.1, x...
93a348005c0b0ddd132fbe8e0d6923bb0fb25b3c
77,223
from typing import Optional from typing import Callable from typing import Tuple from typing import Dict def make_params_and_inference_fn( observation_size: int, action_size: int, normalize_observations: bool = False, parametric_action_distribution_fn: Optional[Callable[[ int, ], distribut...
807f95ce5865bdf77ff3361e642df39163dcdba5
77,224
def jsonify_dict(d, copy=True): """Make dictionary JSON serializable""" if copy: d = deepcopy(d) for k, v in d.items(): if type(v) == np.ndarray: d[k] = v.tolist() elif type(v) == list: d[k] = jsonify_list(v) elif type(v) == dict: d[k] = js...
005b10fd8b0cae4a8af9b1d6e132fad95f6a6af7
77,225
def format_rows_to_columns(forecast_dict): """ Helper function to reformat list of courses from Student object's self.plan (student_object.py) into a format appropriate for forecast.html i.e. rows from student object will be converted into columns for forecast.html """ # these lists will contain the info for the ...
e7e5fc765641543130be4c103e77b73ed1e2b53e
77,227
def psd_to_flux_density(E, f, Omega): """ Converting phase space density f to flux density S_nu. Returns frequency nu [GHz] and spectral irradiance S_nu = E^3/2./pi^2*f*Omega [Jy]. Parameters ---------- E : array of energy [eV] f : p.s.d Omega : the angle the source subtends [sr] """ ...
fdd1540c68d7fcfa89234e5aa543dbc07d14d9ff
77,228
def _maybe_replace_unmasked(ori, mask, reconstruction): """ Replace the unmasked parts of `reconstruction` with the respective parts from `ori` if configured in `FLAGS`. """ mask_b = np.array(mask, dtype=np.bool) # if mask consists only of False, it means it is empty, in which case we don't want to...
990faae0c048d28c30e2b122dc413aae6ec82faa
77,230
async def bsgn_1(a): """Compute binary sign of a securely. Binary sign of a (1 if a>=0 else -1) is obtained by securely computing (u+v+w - u*v*w)/2 with u=(2a-1 | p), v=(2a+1 | p), and w=(2a+3 | p). """ stype = type(a) await mpc.returnType(stype) Zp = stype.field p = Zp.modulus lege...
218e86dfc7ab3e40a0af91be72a6c6e80c18a8c5
77,233
def get_query_range(count: int, page: int): """Generate query for range of the search results :type count: ``int`` :param count: Max amount of the search results :type page: ``int`` :param page: Current page, depends on count :return: A query range :rtype: ``str`` """ if page < 1:...
c29285c56eed77275d2ec28a45de148ce3b7f591
77,235
import json def mock_md_fetch(monkeypatch): """Mock out the metadata-fetching implementation Override _substitute_metadata so we can test `fetch_metadata' without network IO. doctest.testmod does accept globals-setting parameters (`globs` & `extraglobs'), but they haven't been as easy as just overwri...
b22c52e3038413744b5f0d219ad74a7c992b442c
77,236
def T_stock(Q_plant, C, tubing_color, V_stock): """This function calculates the time after the experiment at which the stock container will run out. Parameters ---------- Q_plant : float flow rate of the plant C : float desired concentration within the plant tubing_color :...
b29278647eca96db0ecfb2c121cee9eb69183b15
77,237
def xT_surface(df, successful_shot_events, failed_shot_events, successful_pass_events, failed_pass_events, successful_dribble_events, failed_dribble_events, event_column_name, l=18, w=12, pitch_length=105, pitch_width=68, use_synthetic=0, df_synthetic=None): """ Iteratively calculates MxN xT value surface. ...
16663a1f2c2bd6b3cbefdf0a31dc1d4f992db33e
77,238
def svn_utf_cstring_to_utf8(*args): """svn_utf_cstring_to_utf8(char dest, char src, apr_pool_t pool) -> svn_error_t""" return apply(_core.svn_utf_cstring_to_utf8, args)
c023085352dc7741b35377a540be642c83d7a20b
77,239
def get_commits_master_url(repo_name): """ Get GitHub API URL for latest commit to master """ return "%s/master" % get_commits_url(replace_special_chars(repo_name))
b22d730892fbb65d80c6a80dde292dfbc8801e27
77,241
def Default(value: DefaultType) -> DefaultType: """ You shouldn't use this function directly. It's used internally to recognize when a default value has been overwritten, even if the overridden default value was truthy. """ return DefaultPlaceholder(value)
a02be19c566c2b41b58d32dee8cbe88e9934b413
77,243
import json def get_deploy_durations_from_file(filename): """ filename: path to a file to be parsed for datetime data The expected input is a paasta service log for the deploy events The way I've been fetching them is by running 'internal logreader command' | grep deploy | grep event > filename ""...
35bd78adf5a863604cd361a10d449199ece88b47
77,244
def chunkify(l, chunk_size): """Return list of evenly sized lists""" book_chunks = [] for i in range(0, len(l), chunk_size): book_chunks.append(l[i:i + chunk_size]) return book_chunks
d205d8a916582e86d736e1372a18d7dd173e4683
77,245
def resize(img, height=None, width=None): """resize the image Args: img (array): png image height (int, optional): pixel. Defaults to None. width (int, optional): pixel. Defaults to None. Returns: image: the raw image """ h, w = img.shape[0], img.shape[1] if hei...
05b47a3638fe5ef6d8298855a6b320e4f93888ad
77,246
def get_abuse_categories(comment_body): """Returning the matching categories of abuse""" cats = [] body = comment_body.lower() for cat in sorted(cfg.CATEGORIES.keys()): if cat in body: # distinguish between the overlapping categories "spam" # and "comment spam" ...
362db333ea463ef1d22f1b0ae51bfb46f81e8b27
77,247
import re def get_alphabet(sequences): """Retrieve alphabet of amino acids with modifications. Parameters ---------- sequences : ar-like peptide sequences. Returns ------- List with modification strings. """ return np.unique( re.findall("-OH|H-|[a-z0-9]+[A-Z]|[A-Z...
0faeca97418a3cf2c3bb1a8c03e6743cc16917a6
77,248
def createRequestWithFuture(): """ Creates a `Request` and populates the `future` field in the same way the `BulkRequestManager` populates it when the request is placed. """ req = Request('http://127.0.0.1:40506', 'test') req.future = injectResultTimestampFn(Future()) return req
50744ed213ddd88a6da99e15e035b19e67e98654
77,249
from typing import Optional import torch def isposinf(x: DNDarray, out: Optional[DNDarray] = None): """ Test if each element of `x` is positive infinite, return result as a boolean :class:`~heat.core.dndarray.DNDarray`. Parameters ---------- x : DNDarray Input tensor out : DNDarra...
a542de41e3784c80b10418e5562aad846c614e0e
77,250
def verifyScoutFlags(logger): """Checks that all of the configuration flags are set correctly Args: logger (logger): (elementals) logger Return Value: True iff all configuration flags are set to a valid value, False otherwise """ global config_flags if config_bitness is None: ...
61bc6761b29c567ac7eb04167437dcf153667afb
77,251
def decodeJSONFitterSteps(fitter : Fitter, dct): """ Function for passing as decoder to Fitter.decodeSettingsJSON(). Constructs scaffold objects from their JSON object encoding. Used as object_hook argument to json.loads as a lambda function to pass fitter: lambda dct: decodeJSONFitterSteps(fitt...
4f789852f0bd00693259247a53bd0dceb6388ba4
77,252
def update_playlist(playlist, client=default): """ Save given playlist data into the API. Metadata are fully replaced by the ones set on given playlist. Args: playlist (dict): The playlist dict to update. Returns: dict: Updated playlist. """ return raw.put( "data/pl...
6fbdad36314d2d6417bc33021c7fc4730d65e714
77,253
def hbdet_bias_plot(start_date, end_date): """Return a <div> element with a weather downtime plot. The plot shows the downtime for the period between start_date (inclusive) and end_date (exclusive). Params: ------- start_date: date Earliest date to include in the plot. end_date: date ...
b10d54a088800bd1a3d67d2f5b144f5607eda213
77,254
import vagrant def check_vagrant_plugins_installed() -> CheckLevels: """ Error if `vagrant-vbguest` is not installed. """ # We import Vagrant here instead of at the top of the file because, if # the Vagrant executable is not found, a warning is logged. # # We want to avoid that warning for...
8c081d366e0fed78c919f9b1f4a4d96504685204
77,256
def remember(function): """ A decorator caching the result of a method. """ memo = {} def wrapper(*args): if args in memo: return memo[args] else: rv = function(*args) memo[args] = rv return rv def _reset(args): if not arg...
a6e9e745e9b8b95fd4dd934ee436b6dcb4bb242b
77,258
def get_worker_cpu_usage(): """[summary] this endpoint retrieves the average CPU user per minute for the past 30 minutes. Returns: [type] -- [description] this endpoints return a json object { isSuccess: boolean indicating if the action is successful, timestamps: list of...
c9283ddffc458dc1b21edf5c79a20e14bdeacab9
77,259
def success(parsed_args): """ :param :py:class:`argparse.Namespace` parsed_args: :return: Nowcast system message type :rtype: str """ logger.info( f"NEMO nowcast-agrif run for " f'{parsed_args.run_date.format("YYYY-MM-DD")} ' f"queued on {parsed_args.host_name}" ) ...
026e1bed8efc995aba417c5d03b82bf274505290
77,260
def nancov(X): """ Generates a covariance matrix excluding nan-components. Parameters --------------- X : :class:`numpy.ndarray` Input array for which to derive a covariance matrix. Returns ------- :class:`numpy.ndarray` """ # tried and true - simply excludes samples ...
7ba961dab9d7f02b41c7bda805f72e3b55e4d6ee
77,261