content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def display_map(energy_type, year, scope): """ Docs """ # scope = "Africa" df = df_notna.query("Year==@year & energy_type==@energy_type") fig = px.choropleth( df, locations="Code", color="percentage", hover_name="Entity", hover_data={ "Year": ...
0aaa7bf715d9b9bbd510c7448941a6f36ad55478
43,297
from typing import Mapping from typing import Callable from pathlib import Path def build_indicator_module_from_yaml( filename: PathLike, name: str | None = None, indices: Mapping[str, Callable] | ModuleType | PathLike | None = None, translations: dict[str, dict | PathLike] | None = None, mode: st...
f40f57965c41a1c208da8d262fad4f9221d834b9
43,298
def getnameinfo(sockaddr, flags): """ getnameinfo(sockaddr, flags) -> (host, port) Get host and port for a sockaddr. .. seealso:: :doc:`/dns` """ return get_hub().resolver.getnameinfo(sockaddr, flags)
2d9d7fb72244b9188b895d8430b6075f1d5d6630
43,299
def meta_track_name(txt): """ Creates a track name meta message. Parameters ---------- txt : string The track name for the message. """ return text_meta_message(kTrackName, txt)
bf969e023107b8517bd6df9cf7d9040e52b7b00d
43,301
from pathlib import Path def model_path(base_path: Path, training_run): """Returns the path of the model of a given training run. Arguments: base_path: A Path object pointing to the base directory where the training run is located. training_run: The name of the directory of the training run. ...
cea149172aa12a2e35fb558fa867dcbfe17eda3e
43,302
import tqdm import random import copy def process_images(): """ 新增实现: 1. 记录每个图像样本包含的caption出现的concept词,按照dict_concept_to_index编码记录 2. 如果是origin模式,则直接将karpathy的划分方案继承下来,不做改动 3. 如果是fewshot模式,则按照我们希望的,按照BaseTrain、BaseVal、BaseTest、Support、Test的方式进行划分 4. 划分的修改结果返回到下一步处理 """ ...
c9f9bd5e768792877cc50ed0cdebe580d3108e48
43,303
import threading def countLinkCheckThreads(): """ Count LinkCheckThread threads. @return: number of LinkCheckThread threads @rtype: int """ i = 0 for thread in threading.enumerate(): if isinstance(thread, LinkCheckThread): i += 1 return i
077c9a6b00f9ba438981fa0769b4244d931c5db1
43,304
def predict_class_name_and_confidence(img, model, input_size): """predict image class and confidence according to trained model Args: img: image to predict model: pytorch model Returns: class_name: class index confidence: class confidence """ class_idx, confidence = ...
58d2e8b9b4f05e259e6612c4f1342c01e91cf12f
43,305
def laplace(arr): """Laplace filtered signal as features. Parameters ---------- arr : ndarray, shape (n_channels, n_times) Returns ------- output : (n_channels * n_times,) """ c4 = 4 * arr[8] - (arr[2] + arr[7] + arr[14] + arr[9]) c3 = 4 * arr[4] - (arr[0] + arr[3] + arr[10] + ...
021f65a6e1bf58892929168f05c664b6191e8988
43,307
def plot_block_diffs( blocks, truths, title=None, active_label=1, fig_fname=None): """ Show percent of datapoints in each block where truth value is equal to active_label :param blocks: array of block or meta-values :type blocks: np.array with shape (num_samples,) :param tru...
d5357e0b81e262caf20a5d4157b9fea30348fb69
43,308
def assign_road_name(x): """Assign road conditions as paved or unpaved to Province roads Parameters x - Pandas DataFrame of values - code - Numeric code for type of asset - level - Numeric code for level of asset Returns String value as paved or unpaved """ ...
01bf8bccca43aa833e3d9edfcbfe0213e30d9ac0
43,309
def _check_fm(fm): """Check Field Index map value types""" if not isinstance(fm, dict): return False for f in fm: if not isinstance(f, basestring): return False if not isinstance(fm[f], set): return False for m in fm[f]: if not isinstance(m, fm[f]): return False retur...
a7f3e7cd68232c6e6e0f83bed88b3e51db187ef0
43,311
from typing import Union from typing import Dict from typing import List def fixed_param_names_from_stragegy(config: model.ModelConfig, params: Union[Dict, mx.gluon.ParameterDict], strategy: str) -> List[str]: """ Generate a fixed paramet...
415a56e6a5161634e9732596cb85f7e2d50f9c27
43,312
from typing import Any def valid_publish_topic(value: Any) -> str: """Validate that we can publish using this MQTT topic.""" value = valid_topic(value) if "+" in value or "#" in value: raise vol.Invalid("Wildcards can not be used in topic names") return value
f3d04117779bfdc01f78c21fdef7954752e2933b
43,313
def get_ownership_filter(filter_str: str) -> Filter: """Get an OwnershipFilter from its id string.""" filter_dict = { UNOWNED_FILTER: UnownedFilter(), OWNED_FILTER: OwnedFilter(), ALL_FILTER: None, } return _get_filter(filter_dict=filter_dict, filter_str=filter_str)
6bd8544a83687e12c0aa3b22c2901f0af4be29d8
43,314
def forgot_password_request(): """Respond to existing user's request to reset their password.""" if not current_user.is_anonymous: return redirect(url_for('main.index')) form = RequestResetPasswordForm() if form.validate_on_submit(): user = User.objects(email=form.email.data).first() ...
5b2fbbff95701aaaa5ec6a489e20456ac27e4579
43,315
from pathlib import Path def get_cached_bc_file_path( project: Project, binary: ProjectBinaryWrapper, required_bc_file_extensions: tp.Optional[tp.List[BCFileExtensions]] = None, ) -> Path: """ Look up the path to a BC file from the BC cache. Args: project: the project binary: ...
5b40d32bb985bdea80ce2ecd4dd8877ae45dad7b
43,316
import logging def get_data(parts_of_interest): """ Given a dictionary of classes with sub-dicts of required properties, returns a dictionary keyed first by class and then by instance_id of those extracted properties. """ component_dict = defaultdict(dict) ## verbose log entry detailing what ...
acd672f7ff1c7a12902437dfa192b7d288011086
43,317
def buildClassifier(input_shape=(100, 100, 3)): """ This creates the CNN algorithm. Args: input_shape(tuple): This is the image shape of (100,100,3) Returns: classifier(sequential): This is the sequential model. """ # Initialising the CNN classifier = Sequential() classif...
bbad10918aec4d1b42c30d8dac58237287023e98
43,318
def exp_categorical_crossentropy_Im_mc(exp=1.0, class_weights=[],nclass=2,ncluster=[]): """ :param exp: exponent. 1.0 for no exponential effect. """ def inner(y_true, y_pred): # sz=y_pred.shape mv=tf.reduce_max(y_true) I_weight = tf.cond(tf.greater(mv,50), lambda: tf.add(1.0,0.0...
b6ff25cec0d276700d9e09cd272f6854a0c5c93c
43,319
import math def cubic_approx_quadratic(cubic, tolerance, _2_3=2/3): """Approximate a cubic Bezier with a single quadratic within a given tolerance. Args: cubic (sequence): Four complex numbers representing control points of the cubic Bezier curve. tolerance (double): Permitted dev...
28e5f23f4d9aa5179f72f7361a834db9353654ee
43,320
def __substituteGamma(expr, *args, gamma=IndexedBase('\gamma', integer=True, shape=1)): """ Substitute gamma[i] by args[i] in expression. :param Expr expr: expression :param args: entries of the gamma vector :param Expr gamma: optional symbol to use for gamma :return: expr with gamma[i] substit...
3398775dd0fbb39d73178ef4f866d187fd0d9678
43,322
def generate_password(): """Funtion that generates random password for the user""" gen_password = Credentials.generate_password() return gen_password
f982e8dc3f825cd855921d67eb5a2c9e0d7a5a0e
43,323
def hyphenation(word): """ Split word in syllables :param word: input string :return: a list containing syllables of the word """ if not word or word == '': return [] # elif len(word) == 3 and (is_vowel(word[1]) and is_vowel(word[2]) and not is_toned_vowel(word[2]) and ( # no...
1d202c285195730ba9b4b3d7fe6616fc71895808
43,324
def create_dictionary(generator): """ Creates dictionary (key=CVE id, value=list of links) <class 'generator'> -> dict """ cves = dict() for item in generator: if item.startswith('CVE'): header = item links = list() else: links.append(item...
271c3bdb5f1062ebc8a7f4eb69afbf54af5743eb
43,325
def GetBusNumberToDeviceTreeMap(fast=True): """Gets devices currently attached. Args: fast [bool]: whether to do it fast (only get description, not the whole dictionary, from lsusb) Returns: map of {bus number: bus object} where the bus object has all the devices attached to it in a tree. """ ...
b871c3bb2503b28ea78e2dc7b8183cb3d7ceae04
43,326
def logprob_angle(xa, ya, xb, yb,ha,measured_angle, std): """logprob that a, b and c are in (xa,ya),(xb,yb),(xc,yc) under the measured angle. Args: xa: abscissa of point a ya: ordinate of point a xb: abscissa of point b yb: ordinate of point b measured_dist: measured...
a16294f05cfe837a759ef3403b6ef281c7541ba0
43,327
def get_partype(cdragon_bin, ddragon_language): """ Gets partype in the requested language. This is a backup to relying on ddragon, still not pretty, could use improvement """ if 'arType' not in cdragon_bin['primaryAbilityResource']: return translate.t(ddragon_language, "game_ability_resourc...
8edbf97ca54266e22b09b4f1edaf4ca5bec230f6
43,328
def GetGap ( classes, gap_list ): """ Input classes: {课号:{教师姓名:[完成课时,完成课时比例,完成业绩]}} (dict) Output availableT: available teacher list,在职教师名及其完成业绩(tuple) unavailableT: unavailable teacher list,离职 & 管理岗教师名及其完成业绩(tuple) gap:由离职 & 管理岗教师产生的业绩缺口(float) """ gap = 0 availableT = [] ...
4c9bba825d4763e8c98c3f01f623b331d97a5cd4
43,329
def filter_exists(name): """ Check whether a filter named "name" exists. """ hdata = weechat.hdata_get("filter") filters = weechat.hdata_get_list(hdata, "gui_filters") filter = weechat.hdata_search(hdata, filters, "${filter.name} == %s" % name, 1) return bool(filter)
826c985b6c6c2a4b56788fb0c181a7b51c585197
43,330
def normalize_image(image, mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)): """Normalize the input image. Parameters ---------- image : numpy.ndarray Input image. mean : tuple, optional Mean values ​​for each of the three RGB channels w...
4b64d92e53508c9018894ca556c98fb39a7599a5
43,331
def indel_equivalence_solver(df, genome, refgene, chr_prefixed): """Solve indel equivalence and calculates indels_per_gene (ipg) Args: df (pandas.DataFrame) genome (pysam.FastaFile): reference genome refgene (str): path to refCodingExon.bed.gz chr_prefixed (bool): True ...
845f3712d98b44bc9ac31fd40ff2bf3e762df6dd
43,332
def strain(transport: Transport): """Assume total recrystallization during transport.""" return 0
2f2294f64902a65d17ab9d6214949f9709b3a8fc
43,333
def generateMessage(estopState, enable, right_vel, left_vel): """ Accepts an input of two bools for estop and enable. Then two velocities for right and left wheels between -100 and 100 """ # Empty list to fill with our message messageToSend = [] # Check the directions of the motors, False =...
3c0d2f912ee1fca4e819b0b5813de48b7f1bb338
43,334
def editItem(category_name, item_id): """Item edit page handler, retrieves item from database and renders the edit item page""" # Get item from the database item = session.query(Product).filter_by(id=item_id).one() if "username" not in login_session: # If user not logged in, redirect to lo...
0ec3b9920b5ab7994d80419641294a57c89f9c6a
43,335
def atom_periodic_number_convert(coord_input): """ Add a new column contain periodic number of the corresponding atom :param coord_input: coordinate dataframe of 2D or 3D data :type: pandas.DataFrame :return coord: same dataframe with added column of periodic number """ # check input type ...
650fca5997755faee9bb673211391beb791e8416
43,336
def response_md5_is_valid(response): """Checks the MD5 hash of ``response.content`` against that response's "content-md5" header. Returns ``True`` if they match, else ``False``. If the response does not include a ``content-md5`` header, we can't verify it, but we should not hold up that response. Thus,...
2c38e1a50dd7d657a0a99f6e9c7a8a93f7c5aab7
43,337
def unpatch_task(task): """Deprecated API. The new API uses signals that can be deactivated via unpatch() API. This API is now a no-op implementation so it doesn't affect instrumented tasks. """ deprecation( name='ddtrace.contrib.celery.patch_task', message='Use `unpatch()` instead',...
0d926173ab5779e2f34d5d8b76b73977a54d0e0f
43,338
def cost_deriv(a, y): """Mean squared error derivative""" return a - y
15d02e49af734f9ad95e63214055f4dda58d41f4
43,339
def hsvColor(hue, sat=1.0, val=1.0, alpha=1.0): """Generate a QColor from HSVa values. (all arguments are float 0.0-1.0)""" c = QtGui.QColor() c.setHsvF(hue, sat, val, alpha) return c
bf99bd9064d11336b78b34f38fe4559422cbf7d9
43,340
def choose_shift(count_data, min_shift=2, max_shift=12): """ Helper function to choose the best shift to apply to the data before applying mixture model. This helps automatically pick a shift vs. just having a fixed """ best_fit = None best_shift = None for count_shift in range(min_shift, m...
6a58fa9fafbdbd2d4a915c747a1d4cbdddf09827
43,341
def general_pdist(points, distance_function = haversine): """ Calculate the distance bewteen each pair in a set of points given a distance function. Author: Piotr Sapiezynski Source: https://github.com/sapiezynski/haversinevec Input ----- points : array-like (shape=(N, 2)) ...
319f275a078b3e69ef6be48daae1665ae5975fdc
43,342
def get_conf_option(cfp,sec): """ 读取监控配置文件(nmshosts.conf)中某部分的选项 """ adict = {} #print(sec) #print('---------------') global V3OPTIONS for o in V3OPTIONS: try: adict[o] = cfp.get(sec,o) except: print("%s:exception!!"%o) adict[o]= None ...
4beaabdb544c46d45956aa3e269a44845cb6d081
43,343
import psutil import socket import ipaddress def get_interface_name(): """ Returns the interface name of the first not link_local and not loopback interface. """ interface_name = '' interfaces = psutil.net_if_addrs() for name, details in interfaces.items(): for detail in details: ...
fee777918e588ed2fc44bcee46c37bc976fbc7fc
43,344
def difference(seq1, seq2): """ Return all items in seq1 only """ return [item for item in seq1 if item not in seq2]
bd012e943e06e92ea2cf42b93a1127a2ab823e61
43,345
def get_training_data(): """ Return python dict of data and its paths """ train_and_validation_data = {} image_id_and_path = {} datasets = {"validation": VALIDATION_DATASETS, "training": TRAINING_DATASETS} for training_data_type, training_data in datasets.items(): for imagery_datase...
a83eab1fd92cdf1d03b8a0e4b8826f273a91cca7
43,346
def update_query_string(context, **kwargs): """Return the current query string updated with the provided kwargs.""" parameters = dict(context["request"].GET.items()) parameters.update(kwargs) return "?" + urlencode(parameters)
3583a383940474b09e8b14d5fb8399e92efc101a
43,347
def default_pim_interface_policies(existing, jp_bidir): """Generates command list that will be used default interface policies used for PIM such as neighbor and join-prune policies Args: existing (dict): key/values of the existing config jp_bidir (bool): flag to detrmine if join-prune po...
cc6745ad9b9b34f8ddaa2e882be12850232e25c4
43,348
def _get_cuda_arch_flags(cflags=None): """Return the CUDA arch flags.""" if cflags is not None: for flag in cflags: if 'arch' in flag: return [] supported_arches = ['3.5', '3.7', '5.0', '5.2', '5.3', '6.0', '6.1', '6.2', ...
f7504fa193c07e794e76c7339482971fa8990297
43,349
def get_payload_for_v36_cluster_upgrade(params): """Construct telemetry payload of v35 cluster upgrade. :param dict params: defined entity instance, telemetry source_description :return: json telemetry data for the operation :type: dict """ def_entity = params.get(CLUSTER_ENTITY) native_e...
64098a9c99b4d6ab698ac9c2f9e36d39c2d13b5f
43,350
def fetch_desikan_killiany(*args, **kwargs): """ Fetches Desikan-Killiany atlas shipped with `abagen` Returns ------- atlas : dict Dictionary with keys ['image', 'info'] pointing to atlas image (.nii.gz) and information (.csv) files References ---------- Desikan, R. S.,...
9a636ca9ee03fb99bee69f30f00a4bf472ade57b
43,351
def conditional_cov_full(X1, X2, X, mu_ell_X1, mu_ell_X2, mu_ell_X, mu_ss_X1, mu_ss_X2, mu_ss_X, nonstat, V): """ part of the conditional post cov matrix. """ num_func = 1 # Fixed for one latent function num_data = tf.shape(X)[0] ...
695828b25330440daaf673fc90f3a896b9c54907
43,352
def ratio(matrix, objectives, weights): """Execute ratio MOORA without any validation.""" # change the sign the minimization criteria # If we multiply by -1 (min) the weights, # when we multipliying this weights by the matrix we emulate # the -+ ratio mora strategy objective_x_weights = weights ...
102ec9321f7f165449b08154da335b6a20e03427
43,354
import click def choose_profile(config_files): """Show brief info on each Okta environment found in loaded configuration profiles""" click.echo("[*] Choose a configuration profile to load. E.g. 1") while True: choice = click.prompt("[*] Enter the number of the configuration profile to load", typ...
be29a6636823ee880912d4e51621a76612a95351
43,356
def add_new_attending(username_id, email, phone): """Creates a dictionary for a new attending physician Every time the user wants to add a new attending physician to the attending physician database, this function must be called. This function reads in from the user the physician’s user name, their...
d8015642c91d4217b83eb3309e47c51ee62889c2
43,357
def getCaptureArea(): # Fix not aborting issue here. """ Get area to work with. """ p1 = Pos() p2 = Pos() kill_key = "f2" def getPos(p): nonlocal kill_key while (not keyboard.is_pressed(kill_key)) and (not ABORT_SIGNALED): # fix loop here QSlee...
e57d89d2939db7baa46b58390f102ed5760b9c3b
43,358
from typing import Callable def _validate_input(dataset: np.ndarray, explain_instance: Callable, sample_size: int, explanations_number: int) -> bool: """ Validates input for submodular pick. For the input parameters description, warnings and exceptions please see the documentation...
b72e305b8f077077e5cc48154470e7b3e6a5420f
43,359
def wcmp(a,b): """ A strict ordering whisker segments in a frame """ return cmp( a.y[0], b.y[0] )
036ab24f24464a98f0c171b719f05e9a5581ad35
43,360
from typing import List from typing import Dict def render_cit_ref(tpl: str, parts: List[str], data: Dict[str, str]) -> str: """ >>> render_cit_ref("cit_réf", ["Dictionnaire quelconque", "2007"], defaultdict(str)) '<i>Dictionnaire quelconque</i>, 2007' >>> render_cit_ref("cit_réf", [], defaultdict(str...
289d7fce334078009fc34b0e30092f56f814f52c
43,361
import scipy def bandpass(samples, sample_rate): """Applies a 20-30khz bandpass FIR filter""" # 25-40KHz is the range of the pinger for the roboboat competition fir = scipy.signal.firwin( 128, [19e3 / (sample_rate / 2), 41e3 / (sample_rate / 2)], window='hann', pass_zero=False) ...
6e23fe91b52b2795f33fb45ee4ba006ef7f0ac49
43,362
def list_blobs_with_prefix(bucket_name, prefix, delimiter=None): """Lists all the blobs in the bucket that begin with the prefix. This can be used to list all blobs in a "folder", e.g. "public/". The delimiter argument can be used to restrict the results to only the "files" in the given "folder". With...
adf7825e118fb6aaf0e8c59c579b4fd57fe48b56
43,363
import time def utc_to_local_tt(y, m, d, hrs_utc): """Converts from a UTC time to a local time. y,m,d: The year, month, day for which the conversion is desired. hrs_tc: Floating point number with the number of hours since midnight in UTC. Returns: A timetuple with the local time. ...
314457a106a135f00bac1e9b302a788336d39f27
43,364
def test_requests_bs4(monkeypatch): """test the requests and bs4 Lua interfaces""" def get(url): return { 'https://test.invalid/plain.txt': Dummy(headers={'Content-Type': 'text/plain'}, text='<span>This</span> is <b>plain</b> text'), 'http://...
ed711eb8a0975fc276c7cdc37a0bb737b0089a3c
43,365
def feature_max_q(q1, q2, q3, q4): """ Computes the max values of each signal for each quarter-window, plus the paired differences of max values of each signal for the quarter-windows, i.e., feature_max(q1), feature_max(q2), feature_max(q3), feature_max(q4), (feature_max(q1) - feature_max(q2)), (feature_max(q1) ...
56274913c8af25036bd49fb6dabbb9396e328405
43,366
import math def get_heading(tank1,tank2): """returns heading of the tank in degrees, assuming tank1, tank2 are dict""" x1,y1 = tank1["x"], tank2["y"] x2,y2 = tank2["x"], tank2["y"] heading = float(math.atan2((y2-y1)/(x2-x1))) #returns heading in radians heading = float(math.degrees(heading)) ...
4b4be25a2693b6c81a9992d67a72df8c0c16a659
43,367
from typing import Callable import asyncio def async_wrap(func: Callable): """Wrap a synchronous running function to make it run asynchronous.""" async def run(*args, loop=None, executor=None, **kwargs) -> Callable: """Run sync function async.""" if loop is None: loop = asyncio.ge...
92ff9c0b796f88f9a4033fb84b0b95b7c2fd26cc
43,369
def is_gs_line(line): """Returns True if line is a GS line""" return line.startswith('#=GS')
cceec8ce733cef9e9a31cc5c55687c1c2f28983f
43,370
import re def replace_lookups(pre: str, partition: str, active: str) -> JNDIParts: """Replace Log4J lookups. See https://logging.apache.org/log4j/2.x/manual/lookups.html and https://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution """ jndi_parts = JNDIParts( ori...
e93cfd794d4c4259a68abe49d055a4b9b715bbe8
43,371
def bar(n): """Test helper for foo.""" return foo(n-1)
1f34951f55250dd0db52f381cb7c94f7ab16f951
43,373
from pathlib import Path def read_cd_files(prefix: Path, fname: str) -> dict: """ result[name] = path-to-the-file name: e.g., 08-1413.jpg pato-to-the-file: e.g., /cifs/toor/work/2011/cyclid data/./CD9/2008-06-19/08-1413.jpg """ result = {} with open(fname) as f: for line in f: ...
c8b16b01819d00be0efb2f12cc25eeb7730facf9
43,375
def _items(mappingorseq): """Wrapper for efficient iteration over mappings represented by dicts or sequences:: >>> for k, v in _items((i, i*i) for i in xrange(5)): ... assert k*k == v >>> for k, v in _items(dict((i, i*i) for i in xrange(5))): ... assert k*k == v """ ...
dbd9949e6cf567bb5d8df1e15db19a7c4977168d
43,376
from typing import Union def apply_capping( df: pd.DataFrame, metric: str, sd_threshold: int = 5, method: Union[str, CappingMethod] = CappingMethod.STANDARD, metric_raw: str = None, ) -> pd.Series: """Calculates metrics capped at threshold of given SDs from mean (upper bound capping only). Int...
715369dec8c51a7e908fc38242c145b419b7951a
43,378
def list_user_emails(): """ List user names and emails Returns: A JsonResponse that contains a list of user information (ID, name, and email) """ sess = GlobalDB.db().session users = sess.query(User) if not g.user.website_admin: relevant_cgacs = [aff.cgac_id for aff in g...
35770abd522277bf65a5cc183bbc38de46714259
43,379
def create_subnetList(topo, num): """ Create the subnet list of the certain Pod. """ subnetList = [] remainder = num % (topo.pod/2) if topo.pod == 4: if remainder == 0: subnetList = [num-1, num] elif remainder == 1: subnetList = [num, num+1] el...
50590d893ccb5e640c258427b9f756b60fd25c90
43,380
def phimat(phi): """ Build a Busing & Levy PHI matrix. Input is in radians """ result = np.zeros((3, 3,), dtype='float64') result[0][0] = cos(phi) result[0][1] = sin(phi) result[1][0] = -sin(phi) result[1][1] = cos(phi) result[2][2] = 1. return result
ddfd74aa5385464b94acecf5f90ae314d1487e9f
43,381
def _get_cube_list_for_table(cell_data, row_labels, col_labels, col_units): """Create :class:`iris.cube.CubeList` representing a table.""" aux_coord = iris.coords.AuxCoord(row_labels, long_name='dataset') cubes = iris.cube.CubeList() for (idx, label) in enumerate(col_labels): if label in ('ECS',...
6a744d0d8188abbd904d04dee083fc6c7ffbe3aa
43,382
def _generate_spaxel_list(spectrum): """ Generates a list wuth tuples, each one addressing the (x,y) coordinates of a spaxel in a 3-D spectrum cube. Parameters ---------- spectrum : :class:`specutils.spectrum.Spectrum1D` The spectrum that stores the cube in its 'flux' attribute. Re...
9d4b5339f18022607f349c326dc83e319a690a26
43,383
from .basic import calc_info_rand as calc_info from .basic import calc_info_neighborhood_avg as calc_info from .basic import calc_info_neighborhood_voting as calc_info from .basic import calc_info_gaussian_laplacian as calc_info from .basic import calc_info_mean_laplacian as calc_info from .basic import calc_info_local...
aa99cb7d8b2207384191343f864ac4db2e2ec2aa
43,384
import re def get_frame_rate_list(fmt): """Get the list of supported frame rates for a video format. This function works arround an issue with older versions of GI that does not support the GstValueList type""" try: rates = fmt.get_value("framerate") except TypeError: # Workaround ...
d3db15553a9bd28dc7be0754c7c8202e20aab8d2
43,387
import torch def cosine_loss(X, mu_tilde, pi_tilde, alpha): """ Computes the Cosine loss. Arguments: X: array-like, shape=(batch_size, n_features) Input batch matrix. mu_tilde: array-like, shape=(batch_size, n_features) Matrix in which each row represents the assign...
af31a24c66690105b926099c5a5ac8da47243b5b
43,388
import torch def construct_loader(x, y, batch_size, shuffle=True): """Construct a data loader for the provided data. Args: x (list): A list of molecule features. y (list): A list of the corresponding labels. batch_size (int): The batch size. shuffle (bool): If True the data wi...
f8fa64b95d14fe2a85d68e88ea075c09907a8e41
43,389
def cpp_texlist(listoflines): """function that parses a .tex file from https://github.com/cplusplus/draft.git and extracts all section headings as well as all impldef statements into a flat list The return value contains tuples, tuple[0] ... line number (starting from 1) that matched the item tuple...
bdef835f1086ce8eaa36bf32f319ee0d1fc804a8
43,390
def show_index(): """Display / route.""" context = {} return flask.render_template("index.html", **context)
5bed243cf0be3822a1701882e5f9fedee6b128fc
43,391
import html def create_header(): """page header""" header = html.Header( html.Nav( [ html.Div( [html.Div([app.title], className="navbar-brand navbar-left")], className="container", ) ], classNam...
cebb3958435eb04c9dcfb9e997bf049194301c7c
43,392
def update_regex_extractor(regex_extractor_id: int): """更新""" data: dict = request.get_json() regex_extractor = RegexExtractor.query.filter( RegexExtractor.regex_extractor_id == regex_extractor_id ).first() if not regex_extractor: return dbu.inner_error("该不存在或已被删除") dbu.update...
215ee431e30b269012848e86b9d06886cb8baa24
43,393
def count(_id): """Update a group """ if request.method == 'GET': try: group = get_group(_id) if not group: return jsonify({'code': 400, 'msg': 'can not found group by id [{0}]'.format(_id)}) else: result = count_group(_id) ...
b01fc38fa4369043a63dc338578eb2e0797540c2
43,394
def create_network_from_yml(directory_name): """ Creates a Network object form a yaml file. """ params_input = load_parameters(directory_name) params = fill_out_dictionary(params_input) for clss in params['arrival_distributions']: dists = [] for dist in params['arrival_distributi...
4a3390a45d6ba589a8985fd38550c2fb395f2fbd
43,395
def gmail_filters(): """Returns GMail labels object exposing labels API. Args: None Returns: GMail labels object. """ return __gmail_v1__().settings().filters()
3e33348ad438118884fd9fc0e3c2a8e8d57f6790
43,396
def transition_matrix(embeddings, **kwargs): """ Calls similarity matrix. Builds a probabilistic transition matrix from word embeddings. """ #ipdb.set_trace() ## Get Similarity matrix L = similarity_matrix(embeddings, **kwargs) Dinv = np.diag([1. / np.sqrt(L[i].sum()) if L[i].sum() ...
aaf56084c56d610e78d974794d1d0dab21c38348
43,397
from typing import List def domain_nameservers_should_be_exactly(value: List[str] = None, ns: List[str] = None) -> bool: """ Check the given nameservers are exactly the domain's nameservers. """ return set(value) == set(ns)
a0021c1c7820d51196c1045e976b6c1281bb148e
43,398
def get_user_pagination(page=1, per_page=10, *args, **kwargs): """ 获取列表(分页) Usage: items: 信息列表 has_next: 如果本页之后还有超过一个分页,则返回True has_prev: 如果本页之前还有超过一个分页,则返回True next_num: 返回下一页的页码 prev_num: 返回上一页的页码 iter_pages(): 页码列表 iter_pages(left_edge=2, left_curre...
0c566284ac2fb1450562baea4c0c695691e32795
43,399
def convert_null_to_zero(event, field_or_field_list): """ Converts the value in a field or field list from None to 0 :param event: a dict with the event :param field_or_field_list: A single field or list of fields to convert to 0 if null :return: the updated event Examples: .. code-block:: py...
c81bf5909d13b9cb2ce759c3ab0643e03b95c203
43,400
def is_mul(a): """Return `True` if `a` is an expression of the form b * c. >>> x, y = Ints('x y') >>> is_mul(x * y) True >>> is_mul(x - y) False """ return is_app_of(a, Kind.MULT)
333fa73e5a1d15df8edb53ce744148a766522eca
43,401
def procura_frase_lacunas_respostas_dicionario(): """Esta função retorna a frase, as lacunas e as respostas correspondentes para o nível selecionado pelo usuário. """ frase = frases_lacunas_respostas_por_dificuldade[nivel]['frase'] lacunas = frases_lacunas_respostas_por_dificuldade[nivel]['lacunas']...
0c15e5208b0e0c33a41d909a94b1145b0a94a1fd
43,402
def refresh(): """Pull fresh data from Open AQ and replace existing data.""" DB.drop_all() DB.create_all() api = openaq.OpenAQ() status, body = api.measurements(city='Atlantic City', country='US', parameter='pm25') results = body['results'] for ii in range(len(results)): db_record = ...
b3ef9492d88048fc17efd27c9d8a3df02ac0a029
43,403
def index(): """Renders home page.""" return render_template('index.html')
0ea6f0b0c0f4f2c5596d68d7a4ea8268a7c8f2f6
43,404
def obtener_cantidad_dias_estancia_media_estimados_en_ciudad_en_rango_anios_mensualmente(Ciudad, AnioInicio, AnioFin): """ Dado una ciudad y un año obtiene los dias de estancia media estimados en dicha ciudad en ese rango de años dividido por meses Dado una ciudad y un año obtiene los dias de estancia media...
d58fe973c5b4197e45d37e76f6a5db6f8d1d7cd7
43,406
def setBit(int_type, offset, value): """following 2 functions derived from https://wiki.python.org/moin/BitManipulation, this one sets a specific bit""" if value == 1: mask = 1 << offset return(int_type | mask) if value == 0: mask = ~(1 << offset) return(int_type & mask)
642e8ffb41aaf3c5514038e525275c053a4cd8b1
43,407
def parse_values(params, defaults): """Parses a Values parameter which should have only two values separated by a comma. Used to override ON/OFF type messages. """ try: split = params("Values").split(",") if len(split) != 2: return defaults else: return sp...
539fa14aee5133ef3f4d1d4f45f7944da33866ce
43,408
def _get_activation_fn(activation): """Return an activation function given a string""" if activation == "relu": return F.relu if activation == "gelu": return F.gelu if activation == "glu": return F.glu if activation == "leaky_relu": return F.leaky_relu raise Runti...
48fbe91d2f701187a398296c6728744a4c4be6c0
43,409