content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def snrcat(spec,plugmap): """This function calculates the S/N for each fiber. Parameters ---------- spec : SpecFrame object The SpecFrame object that constrains the 1D extracted spectra. plugmap : numpy structured array The plugmap information for each fiber including which...
30b3de8197425b92d0b69c3d49f3a1bca46ca659
9,679
def forward(S, A, O, obs): """Calculates the forward probability matrix F. This is a matrix where each (i, j) entry represents P(o_1, o_2, ... o_j, X_t = i| A, O). In other words, each (i, j) entry is the probability that the observed sequence is o_1, ... o_j and that at position j we are in hidden st...
24c6ddfa053b623a5a56dcc773c8fc4419258df8
9,680
def calculate_state(position, dt): """ Sometimes, a data file will include position only. In those cases, the velocity must be calculated before the regression is run. If the position is | position_11 position_21 | | position_12 position_22 | | ....................... | ...
9db6d94c8d80f99ccebbdcb9e0691e85e03c836d
9,681
from typing import Optional def get_server(name: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetServerResult: """ Use this data source to retrieve an auth server from Okta. ## Example Usage ```python import pulumi import pulumi_okta as okta ...
d1693c032a254397d44f82bea626a54343c2dfef
9,682
import pathos from functools import partial from itertools import repeat from typing import Sequence from typing import Dict from typing import Set def estimate_aps_user_defined(ml, X_c = None, X_d = None, data = None, C: Sequence = None, D: Sequence = None, L: Dict[int, Set] = None, S: ...
23e94a27800e8cdeca140666d23aace3fd8c5b2d
9,683
def shared_vinchain_instance(): """ This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default vinchainio instance that can be reused by multiple classes. """ if not SharedInstance.instance: clear_cache() ...
8668ec7b3b56353545f7fb35fd834918de4207fc
9,684
def generateMfccFeatures(filepath): """ :param filepath: :return: """ y, sr = librosa.load(filepath) mfcc_features = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40) return mfcc_features
985519827a04d7375e021524d9b8ce6b4fb0482f
9,686
def homography_crop_resize(org_img_size, crop_y, resize_img_size): """ compute the homography matrix transform original image to cropped and resized image :param org_img_size: [org_h, org_w] :param crop_y: :param resize_img_size: [resize_h, resize_w] :return: """ # transform original...
85d252627e947306f3ece89eec1a678c2fa86bc9
9,687
def extract_project_info(req_soup, full_name=False): """Extract the relevant project info from a request. Arguments: req_soup (BS4 soup object): The soup of the request. full_name (boolean): Whether or not to capture the entire project name or just the last h...
04064b769cb97688f47133df6c8dca0f806b6544
9,688
from typing import Optional def get_underlying_asset_price(token_symbol: str) -> Optional[Price]: """Gets the underlying asset price for token symbol, if any This function is neither in inquirer.py or chain/ethereum/defi.py due to recursive import problems """ price = None if token_symbol ==...
8b8e7e79e3e77e7e2985d1a7f5aee337da424f87
9,689
import asyncio def do_call_async( fn_name, *args, return_type=None, post_process=None ) -> asyncio.Future: """Perform an asynchronous library function call.""" lib_fn = getattr(get_library(), fn_name) loop = asyncio.get_event_loop() fut = loop.create_future() cf_args = [None, c_int64, c_int64]...
c3d32f9521a58c81231fe70601a9807b4b9841be
9,690
def prefer_static_value(x): """Return static value of tensor `x` if available, else `x`. Args: x: `Tensor` (already converted). Returns: Numpy array (if static value is obtainable), else `Tensor`. """ static_x = tensor_util.constant_value(x) if static_x is not None: return static_x return x
4bd38e5f3a57314b48c86e37f543e6fb69847d1c
9,691
from psyneulink.core.components.component import Component, ComponentsMeta import types import copy def copy_parameter_value(value, shared_types=None, memo=None): """ Returns a copy of **value** used as the value or spec of a Parameter, with exceptions. For example, we assume that if we h...
2586cc79524b63d74920f4b262d0b9b63cb8ef02
9,692
def ajax_login_required(function): """ Decorator for views that checks that the user is logged in, resulting in a 403 Unauthorized response if not. """ @wraps(function, assigned=available_attrs(function)) def wrapped_function(request, *args, **kwargs): if request.user.is_authenticated: ...
194d97cd4f9897482a27addeca74780316c39083
9,693
def compile_str_from_parsed(parsed): """The (quasi-)inverse of string.Formatter.parse. Args: parsed: iterator of (literal_text, field_name, format_spec, conversion) tuples, as yield by string.Formatter.parse Returns: A format string that would produce such a parsed input. >>> ...
bfc3d39ecee6e07e41690ee8f85f969c110de69b
9,694
def calculate_class_weight(labels): """Calculates the inverse of the class cardinalities and normalizes the weights such that the minimum is equal to 1. Args: labels: List of integers representing class labels Returns: Numpy array with weight for each class """ labels =...
ff88ac33b49e90f75ac743aec463e87d36023876
9,695
def CosEnv(length,rft=(0.005),fs=(44100)): """ rft : Rise and fall time [s] length : Total length of window [s] fs : Sampling freq [Hz] """ rfsamp = int(np.round(rft * fs)) windowsamp = int(np.round(length * fs)) flatsamp = windowsamp - (2 * rfsamp) time_index = np.arange(0, 1,...
e15cf02bfad7f0a1935507d8e394718429df6958
9,696
def flatten(nested_list): """ Args: nested_list (list): list of lists Returns: list: flat list Example: >>> import ubelt as ub >>> nested_list = [['a', 'b'], ['c', 'd']] >>> list(ub.flatten(nested_list)) ['a', 'b', 'c', 'd'] """ return it.chain.f...
418c8d76ff97991ef26e59d7740df14690655cd5
9,697
def fetch_reply(query, session_id): """ main function to fetch reply for chatbot and return a reply dict with reply 'type' and 'data' """ response = apiai_response(query, session_id) intent, params = parse_response(response) reply = {} if intent == None: reply['type'] = 'none' reply['data'] = "I didn't u...
bfcb2938042b964da15c33c614d37433948b37f2
9,698
def create_SpatialReference(sr): """ creates an arcpy.spatial reference object """ return arcpy.SpatialReference(sr)
fdb535d4e1c1acda4da4270d78ceb4db9c114584
9,699
def check_in_image(paste_image_location, paste_image_size, canvas_image_size): """Checks whether the location for the pasted image is within the canvas. Args: paste_image_location: a namedtuple of utils.XY, with 'x' and 'y' coordinates of the center of the image we want to paste. paste_image_si...
173ff3ca7961bff34237512990fb2f103dd7ddc9
9,700
import functools def withSEVCHK(fcn): """decorator to raise a ChannelAccessException if the wrapped ca function does not return status = dbr.ECA_NORMAL. This handles the common case of running :func:`PySEVCHK` for a function whose return value is from a corresponding libca function and whose retu...
938468e504cb37a154c6165cc052f59995f806bc
9,701
from . import ism, gradient, referencebased def available_methods(): """Get all available importance scores """ int_modules = [ism, gradient, referencebased] available_methods = {} for m in int_modules: available_methods = merge_dicts(available_methods, m.METHODS) return available_met...
3f452affeebafdae1571cfb54d6af9235871f798
9,703
def is_sketch_list_empty(): """Check to see if any sketches""" return len(_CVB_SKETCH_LIST) == 0
fdaa5b5a251bde8a8b4d2e5a0c8a1d4b4b3d5f7d
9,705
def pb22(): """ Problem 22 : Names scores. We first open the file, suppress the useless ", put everything into lowercase, and split to get a list. We use merge sort to sort the list by alphabetical order (see utils.merge_sort), and then : - for each word in the list - for each character in t...
f8c08fc3c42e0889514d84e2193e10a8be1f8595
9,706
def resize(im, target_size, max_size, stride=0, interpolation = cv2.INTER_LINEAR): """ only resize input image to target size and return scale :param im: BGR image input by opencv :param target_size: one dimensional size (the short side) :param max_size: one dimensional max size (the long side) ...
ba2238bfaeb3c3c08ad4c1b9371e87c5e0653edc
9,707
from typing import List from typing import Tuple import json def _add_qc( samples: List[Sample], namespace: str, overwrite_multiqc: bool ) -> Tuple[str, str]: """ Populates s.qc_values for each Sample object. Returns paths to MultiQC html and json files. """ multiqc_html_path = join( f...
8c93cd7c08c3e392b9f79956189295cb5c486048
9,708
def oscillAnglesOfHKLs(hkls, chi, rMat_c, bMat, wavelength, vInv=None, beamVec=bVec_ref, etaVec=eta_ref): """ Takes a list of unit reciprocal lattice vectors in crystal frame to the specified detector-relative frame, subject to the conditions: 1) the reciprocal lattice vector mus...
37d17027fcaa15613188f0be61b0df4c5965a19c
9,709
def srfFaultSurfaceExtract(SRFfile): """ Generate fault surface from SRF file convention Following the Graves' SRF convention used in BBP and CyberShake """ lines = open( SRFfile, 'r' ).readlines() Nseg = int(lines[1].strip().split()[1]) # loop over segments to get (Nrow,Ncol) of ...
6e1197b76b88f92e0d61bee87d57910660192346
9,710
def _to_response( uploaded_protocol: UploadedProtocol, ) -> route_models.ProtocolResponseAttributes: """Create ProtocolResponse from an UploadedProtocol""" meta = uploaded_protocol.data analysis_result = uploaded_protocol.data.analysis_result return route_models.ProtocolResponseAttributes( i...
1594a90ce1351ad33961819201409167c0f462a7
9,711
def has_valid_chars(token: str) -> bool: """ decides whether this token consists of a reasonable character mix. :param token: the token to inspect :return: True, iff the character mix is considered "reasonable" """ hits = 0 # everything that is not alphanum or '-' or '.' limit = int(l...
b9b65f1bfd3529275847f1d6e227d57dfebea8a8
9,712
import logging def sqlalchemy_engine(args, url): """engine constructor""" environ['PATH'] = args.ora_path # we have to point to oracle client directory url = f'oracle://{args.user}:{pswd(args.host, args.user)}@{args.host}/{args.sid}' logging.info(url) return create_engine(url)
06a670eccf96997c23a9eb5125925db5be33e978
9,713
def shortcut_layer(name: str, shortcut, inputs): """ Creates the typical residual block architecture. Residual blocks are useful for training very deep convolutional neural networks because they act as gradient 'highways' that enable the gradient to flow back into the first few initial convolution...
b680df8c6415d256ee98d292d491fc30a6a4bb4a
9,715
def event_message(iden, event): """Return an event message.""" return {"id": iden, "type": "event", "event": event}
bfc3fca17a9ad8d3767853c82c5453328d4c07e3
9,716
def match(command): """Match function copied from cd_mkdir.py""" return ( command.script.startswith('cd ') and any(( 'no such file or directory' in command.output.lower(), 'cd: can\'t cd to' in command.output.lower(), 'does not exist' in command.output.lower() ...
e49540995f26b40b4c52879814fe905f35b1c8fd
9,717
def db_remove_game(game: str, channel: str) -> bool: """Removes a game from the database, for a specific channel """ if db_check_game_exists(game, channel): cursor.execute( "DELETE FROM deathcount " "WHERE channel=(?) AND game=(?)", (channel.lower(), game.lower(...
536a48201274767f834443d7b1c279c2c5c15e14
9,718
def get_unique_id(): """Return an ID that will be unique over the current segmentation :return: unique_id :rtype: int """ global UNIQUE_ID UNIQUE_ID = UNIQUE_ID + 1 return UNIQUE_ID
e55be0d1619f3435d0b6b76a3da2661c1349213b
9,719
def logout_route(): """logout route""" logout_user() return redirect(url_for('app.index_route'))
097644c147003be394a886c4b796b57e8cc775c7
9,720
def get_repo_name( name: str, in_mode: str, include_host_name: bool = False ) -> str: """ Return the full/short name of a Git repo based on the other name. :param in_mode: the values `full_name` or `short_name` determine how to interpret `name` """ repo_map = get_complete_repo_map(in_mo...
3eebb75487f5eb5c8c8eb7a5a7a46c92dcf4c304
9,722
def binary_search_hi(a,d,lo,hi): """ Created for leetcode prob 34 """ if d!=a[lo]: raise Exception("d should be a[lo]") while hi>lo: mid=(lo+hi)//2+1 if a[mid]==d: lo=mid else: hi=mid-1 if a[hi]==d: return hi else: retur...
4ef9ad63fb83bbb1cb1a9f7d4a3ea4a08ad40d8d
9,723
def check_subscription(func): """Checks if the user signed up for a paid subscription """ @wraps(func) def wrapper(*args, **kwargs): if current_user.is_authenticated(): subscription = current_user.subscription if not subscription.active and subscription.plan.name != 'Free': ...
853b16cc4a05742f2bd17fd159ac570f92fdb16c
9,724
def spikesbetter(P): """ same as the custom cython function _dice6, a python implementation for easy use on other computers does spin selection procedure based on given array of probabilities -------------------------------------------------------------------- Inputs: P: probability of silence a...
75fcff7e53ccbd392361faf46f2c4f171f85e724
9,725
def t3x1_y(y): """ Translation in y. """ return t3x1(0.0, y, 0.0)
26d99e8a5b5ccd676d5488a8e8aafcd76d5272a5
9,726
def perm_data_time(x, indices): """ Permute data matrix, i.e. exchange node ids, so that binary unions form the clustering tree. """ if indices is None: return x N, M, Q = x.shape Mnew = len(indices) assert Mnew >= M xnew = np.empty((N, Mnew, Q)) for i,j in enumerate(ind...
ed1201d34cb35debe7653601d0048f099e32db16
9,727
def check_chromium() -> bool: """Check if chromium is placed at correct path.""" return chromium_executable().exists()
21b60e3070ba707ae46e53f68f31ef8e719aed76
9,728
def plot_edges(lattice : Lattice, labels : np.ndarray = 0, color_scheme : np.ndarray = ['k','r','b'], subset : np.ndarray = slice(None, None, None), directions : np.ndarray = None, ax = None, arrow_h...
8f4b6ef68b6eae62637a772621c68ecb0acc1a55
9,730
def menu_items_api(restaurant_id): """Route handler for api endpoint retreiving menu items for a restaurant. Args: restaurant_id: An int representing the id of the restaurant whose menu items are to be retrieved Returns: response: A json object containing all menu items for a g...
472adaa25cd588246aef9f2b9a621723df399503
9,731
import logging import tqdm def run(indata): """indata: event detection DataArray or DataSet""" if isinstance(indata, xr.DataArray): events = indata else: events = indata["Event_ID"] logging.info("events array defined.") # turn events into time x space by stacking lat & lon: even...
817bb329638adb39950fac3b3f10d81938515f1a
9,732
def format_trace_id(trace_id: int) -> str: """Format the trace id according to b3 specification.""" return format(trace_id, "032x")
2c0541b4a25d85ae990e68e00dd75012aa1ced60
9,733
def get_count_name(df): """Indicate if a person has a 'Name' Parameters ---------- df : panda dataframe Returns ------- Categorical unique code """ # Feature that tells whether a passenger had a cabin on the Titanic df['Words_Count'] = df['Name'].apply(lambda x: len(x.split...
c51dfbcc025908243f20d10f4faa498fa068d4f7
9,734
from django.contrib.auth.models import User def register_action(request): """ 从这个django.contrib/auth.models 库里倒入里User方法。(其实User是orm方式操作用户表的实例) 然后我们直接用User.objects.create_user方法生成一个用户,参数为用户名和密码。然后保存这个生成的用户 就是注册成功了 但是如果用户表中已存在这个用户名,那么,这个生成语句就会报错。所以我们用try来捕获这个异常,如果发送错误那就是“用户已经存在”,如实给用户返回这句话。如果没问题,那么就返回 注...
4e0d4cdd6ba3547846738b6483ba242adacb71e0
9,735
from typing import Callable from typing import Any import asyncio import functools async def run_blocking_io(func: Callable, *args, **kwargs) -> Any: """|coro| Run some blocking function in an event loop. If there is a running loop, ``'func'`` is executed in it. Otherwise, a new loop is being creat...
e277d1fca909f26d0226c3085fe0e0fbf03bf257
9,736
def parse_config(cfg, section): """ parse config data structure, return data of required section """ def is_valid_section(s): valid_sections = ["info", "project", "variables", "refdata"] return s in valid_sections cfg_data = None if is_valid_section(section): try: c...
72d36dfaf93e17da166cac0c9b786da29107db3e
9,737
from hmmlearn import hmm import collections def _predict_states(freqs): """Use frequencies to predict states across a chromosome. Normalize so heterozygote blocks are assigned state 0 and homozygous are assigned state 1. """ freqs = np.column_stack([np.array(freqs)]) model = hmm.GaussianHMM(2...
be1b1b540b644dc9f412a3d648076a36369e9aae
9,738
def tp(*args) -> np.ndarray: """Tensor product. Recursively calls `np.tensordot(a, b, 0)` for argument list `args = [a0, a1, a2, ...]`, yielding, e.g., tp(a0, a1, a2) = tp(tp(a0, a1), a2) Parameters ---------- args : sequence Sequence of tensors Returns ------- np....
c02b74d79d484e7335387e568fda723fcf3851b8
9,739
def aws_aws_page(): """main endpoint""" form = GenericFormTemplate() return render_template( 'aws_page.html', form=form, text=util.get_text(module_path(), config.language), options=g.user.get_options(), )
2605838a948e3b58fe7c669a388a859144c329c6
9,740
def precompute(instr): """ Args: instr: Returns: """ qecc = instr.qecc if qecc.name == '4.4.4.4 Surface Code' and qecc.circuit_compiler.name == 'Check2Circuits': precomputed_data = code_surface4444(instr) elif qecc.name == 'Medial 4.4.4.4 Surface Code' and qecc.circuit_...
789e1f1f5e37f118f791a5c72c1c0dd7df2cf745
9,742
import re def remove_url(txt): """Replace URLs found in a text string with nothing (i.e. it will remove the URL from the string). Parameters ---------- txt : string A text string that you want to parse and remove urls. Returns ------- The same txt string with url's removed. ...
8d1b8b89cb65ca7761c093dc388d1f19729137e7
9,743
def use_database(fn): """ Ensure that the correct database context is used for the wrapped function. """ @wraps(fn) def inner(self, *args, **kwargs): with self.database.bind_ctx(self.models): return fn(self, *args, **kwargs) return inner
71a42974ce2413c0b24863be9397252bcd06f22e
9,744
import imaplib, email, email.header def getImapMailboxEmail(server, user, password, index, path="INBOX", searchSpec=None): """ imap_headers(server, user, password, index, path="INBOX", searchSpec=None) Load specified email header from an imap server. index starts from 0. Exampl...
c04569870f9528539e958cc114c11ad80c36800c
9,745
def nmatches_mem(txt, pat, t, p, mem): """Find number of matches with recursion + memoization using a dictionary (this solution will also crash when recursion limit is reached) nmatches_mem(text, pattern, len(text), len(pattern), {}) """ if (t,p) in mem: return mem[t, p] ...
5b6a10328ca876481fb9b8425bde2442f603d7e1
9,747
def data_get(): """ Get shared data from this server's local store. """ consistency = request.json["consistency"] name = request.json["name"] field = request.json["field"] value = "" error = "ok" if consistency == "strict": store = globalvars.get_data_store(globalvars.STRICT_...
c8a56b4171109800f4818d59aaf2b3bd9eed1b78
9,749
def pad_sequences(sequences, maxlen=None, value=0): """ pad sequences (num_samples, num_timesteps) to same length """ if maxlen is None: maxlen = max(len(x) for x in sequences) outputs = [] for x in sequences: x = x[:maxlen] pad_range = (0, maxlen - len(x)) x = n...
29204f0f47150f6fac0761876b8045f680032da5
9,750
def empty_surface(fill_color, size=None, flags=0): """Returns an empty surface filled with fill_color. :param fill_color: color to fill the surface with :type fill_color: pygame.Color :param size: the size of the new surface, if None its created to be the same size as the screen :type size...
b48d21649f279736f531ca0cb6e7dabf083c813b
9,754
def getNetAddress(ip, netmask): """ Get the netaddress from an host ip and the netmask. :param ip: Hosts IP address :type ip: str :param netmask: Netmask of the network :type netmask: :returns: Address of the network calculated using hostIP and netmask :rtype: str """ ret...
2bc70d21edcc08d82b146de83389ce94d2fa64ee
9,755
def balance_intent_data(df): """Balance the data for intent detection task Args: df (pandas.DataFrame): data to be balance, should contain "Core Relations" column Returns: pandas.DataFrame: balanced data """ relation_counter = build_counter(df, "Core Relations") # augment each...
3f759ae229de5e30fe4f13f42e4b8db18f0c913d
9,758
def npareamajority(values, areaclass): """ numpy area majority procedure :param values: :param areaclass: :return: """ uni,ind = np.unique(areaclass,return_inverse=True) return np.array([np.argmax(np.bincount(values[areaclass == group])) for group in uni])[ind]
9e43244ef81e63d9870d281660b738fa3b73a11f
9,759
def calcReward(eventPos, carPos, closeReward, cancelPenalty, openedPenalty): """ this function calculates the reward that will be achieved assuming event is picked up :param eventPos: position of events :param carPos: position of cars :param closeReward: reward if event is closed :param cancelPe...
52226496b5338a0ebd3433ae9ee779c036c64809
9,760
from typing import Any def b64encode(s: Any, altchars: Any = None) -> bytes: """Encode bytes using the standard Base64 alphabet. Argument ``s`` is a :term:`bytes-like object` to encode. Optional ``altchars`` must be a byte string of length 2 which specifies an alternative alphabet for the '+' and '/...
deef546ada7679a538afa5432a13846ce765b911
9,761
def select_programs(args, filter_paused=True, force=False): """ Return a list of selected programs from command line arguments """ if not (args.all ^ bool(args.names)): if args.all: log.error("You may not specify a program name when you use the -a/--all option (See -h/--help for mor...
8b597b043ac7e245bf16aec17a779c5639d451d9
9,762
import math def three_comp_two_objective_functions(obj_vars, hz: int, ttes: SimpleTTEMeasures, recovery_measures: SimpleRecMeasures): """ Two objective functions for recovery and expenditure error that get all required params as...
f02403d00142556b17371f3adedd32994dbf9fad
9,763
def scale(data, new_min, new_max): """Scales a normalised data series :param data: The norrmalised data series to be scaled :type data: List of numeric values :param new_min: The minimum value of the scaled data series :type new_min: numeric :param new_max: The new maxim...
3e7720ae90cfdbef1253dbfa39b3e4a10fc118bb
9,764
def default_config() -> ClientConfig: """ :return: Default configuration for the experiment """ simulation_config = SimulationConfig(render=False, sleep=0.8, video=True, log_frequency=1, video_fps=5, video_dir=default_output_dir() + "/videos", num_episodes=1000, ...
d7e53ccc4ad8818453cd673ddaa21fe0614dfc5a
9,765
def get_same_padding(kernel_size: int, stride: int, dilation: int) -> int: """Calculates the padding size to obtain same padding. Same padding means that the output will have the shape input_shape / stride. That means, for stride = 1 the output shape is the same as the input, and str...
12548482e855dcfc627c5b0a6ccf69ad4a74b39b
9,766
def move_child_position(context, request): """ Move the child from one position to another. :param context: "Container" node in which the child changes its position. :type context: :class:kotti.resources.Node or descendant :param request: Current request (of method POST). Must contain either ...
082aef1169de6dab4881593ef8abf85e5076f190
9,767
import requests def get_current_version(package: str) -> str: """ Query PyPi index to find latest version of package :param package: str - name of pacahe :return: str - version if available """ url = f'{PYPI_BASE_URL}/pypi/{package}/json' headers = { 'Content-Type': 'application/j...
6d65dcb6d381c8cf6cba7c06ccebf538c16b85c7
9,768
def mconcat(xs : [a]) -> a: """ mconcat :: (Monoid m) => [m] -> m Fold a list using the monoid. """ return Monoid[xs[0]].mconcat(xs)
cd87cc91bb4d2c6d1cf653fb45967ecb59d6749d
9,770
def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask): """If necessary, zero out inputs to a conv for padding positions. Args: inputs: a Tensor with shape [batch, length, ...] kernel_size: an integer or pair of integers nonpadding_mask: a Tensor with shape [batch, length] Returns: Ten...
e53c1e181cac554047b9acb8d70d358baa9f8a4c
9,771
import json def display_json(value): """ Display input JSON as a code """ if value is None: return display_for_value(value) if isinstance(value, str): value = json.loads(value) return display_code(json.dumps(value, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder))
727dc50d9844a5b0b7f01231c348652056d334cc
9,772
def get_rgba_from_color(rgba): """Return typle of R, G, B, A components from given color. Arguments: rgba - color """ r = (rgba & 0xFF000000) >> 24 g = (rgba & 0x00FF0000) >> 16 b = (rgba & 0x0000FF00) >> 8 a = (rgba & 0x000000FF) return r, g, b, a
56d3e0dce01cfc4348ae115de81abb55ec85eb56
9,773
def beauty_factor(G): """Return the "beauty factor" of an arbitrary graph, the minimum distance between a vertex and a non-incident edge.""" V, E = G[0], G[1] dists = [] for (i, u) in enumerate(V): for (j, k) in E: if i == j or i == k: continue v, w = ...
9267a534d8453a17561b2c8e1f67e40942069ffe
9,774
def line_plane_cost(line, plane): """ A cost function for a line and a plane """ P = normalised((line|plane)*I5) L = normalised(meet(P, plane)) return line_cost_function(L, line)
34ab1df71f2018544a52020d232514127e16aa3e
9,775
import numpy def force_full_index(dataframe: pd.DataFrame, resampling_step: int = None, resampling_unit: str = "min", timestamp_start: int = None, timestamp_end: int = None) -> pd.DataFrame: """ forces a full index. Missing index will be replaced by Nan. Note: re...
cc08ee348467e5fe335ebf3239ce78880c0f99c4
9,777
def legislature_to_number(leg): """ Takes a full session and splits it down to the values for FormatDocument.asp. session = '49th-1st-regular' legislature_to_number(session) --> '49Leg/1s' """ l = leg.lower().split('-') return '%sLeg/%s%s' % (l[0][0:2], l[1][0], l[2][0])
cffeeea2bad17d9dadcfd75d70417824c7fe3396
9,778
def get_variable_field_type(variable_name, field_name, error_prefix=''): """ 获取某个变量的某个字段的类型 """ schema = get_variable_schema(variable_name) result_type = schema.get(field_name) if not result_type: raise RuntimeError(utf8(error_prefix) + '变量(%s)不包含字段(%s)' % (utf8(variable_name), utf8(fie...
6038cebd8219350eec5595bd5ca9aa0151f287cf
9,779
def test(input_test_data): """ Run test batches on trained network :return: Test accuracy [0-1] """ print('--- Execute testing ---') one_hot_label = np.zeros(10, dtype=np.uint8) correct_n = 0 total_n = 0 for batch_id, (mini_batch, label) in enumerate(input_test_data): for s...
dcdbaad1c1496f7cc611ca81f0cb086c3dd127fc
9,780
def test(net, example): """ Args: net (FlowNet): Instance of networks.flownet.FlowNet model, only to be used for pre-processing. example (dict): Un-processed example. Returns: good (list, DMatch): List of good SIFT matches. """ net.eval() example = net.preprocess(example...
b0a864e0468304c6c0060d3ee621d579f806c58f
9,781
def get_hashers(): """ 从settings.py中动态导入一连串hashers对象 Read list of hashers from app.settings.py """ hashers = [] # 导入报名 for hasher_path in current_app.config.get('PASSWORD_HASHERS'): hasher_cls = import_string(hasher_path) hasher = hasher_cls() hashers.append(hashers) ...
d44784d077a99ca23190826249fab6bbf8ad57d5
9,782
def str2range(s): """parse a samtools/tabix type region specification 'chr:start-stop' or 'chr:start..stop'""" chrom = None start = 1 stop = None tmp = s.split(':') chrom = tmp[0] if len(tmp)>1: if '-' in tmp[1]: tmp = tmp[1].split('-') else: tmp = tmp...
8a72107495cc0e7587cadc289b80d326b7901c59
9,783
import json def turn_read_content(path, labelIdx, dataIdx): """ sentences: (dialog_num, turn_num, nbest_num, sentence_len) scores: (dialog_num, turn_num, nbest_num) acts: (dialog_num, turn_num, machine_act_len) labels: (dialog_num, turn_num, [label_dim]) """ sentences, scores, acts, labels...
09049b9028ab4331de9c71afb35a79d348bfce08
9,784
def index_page() -> dict: """Get data for Index page , interfaces, dp neighbors, arps, and hsrp""" interfaces = GetThisDataFromDevice.get_interfaces(request.json.get('ip'), request.json.get('port'), request.json.get('username'), request.json.get('password')) neighbors = GetThisDataFromDevice.get_dp_neighbo...
5506031e11e5ab2c8b40e1f294e04a0ed56a96ac
9,785
def reverse_int_bits(n: int, n_bits: int = 10) -> int: """Reverses the bits of *n*, considering it is padded by *n_bits* first""" return int(format(n, '0' + str(n_bits) + 'b')[::-1], 2)
3c76db59296863161b0bb543e057a82383a780a2
9,786
def get_conn(): """ 获取 :return: """ for name in GENERATOR_MAP: print(name) if not hasattr(g, name): setattr(g, name + '_cookies', eval('CookiesRedisClient' + '(name="' + name + '")')) setattr(g, name + '_account', eval('AccountRedisClient' + '(name="' + name +...
7bf4d23db3f829203041560077e0813a94930af0
9,787
def get_rule_satisfaction_matrix(x, y, rules): """ Returns a matrix that shows which instances satisfy which rules Each column of the returned matrix corresponds to a rules and each row to an instance. If an instance satisfies a rule, the corresponding value will be 1, else 0. :param x: np.ndarray ...
1df187006449e2c101f09b88ac2e8fe9851c7698
9,788
def refactor(df, frequency = '1W'): """Refactor/rebin the data to a lower cadence The data is regrouped using pd.Grouper """ low = df.low.groupby(pd.Grouper(freq=frequency)).min() high = df.high.groupby(pd.Grouper(freq=frequency)).max() close = df.close.groupby(pd.Grouper(freq=fr...
217e65236994e9a075ef410488250cbb1051dbb4
9,789
def pendulum_derivatives(theta, omega, g=9.8, l=1): """ \dot{\theta} = \omega \dot{\omega} = -\frac{g \sin\theta}{l} :param theta: angel of the pendulum :param omega: angular velocity of the pendulum :param g: gravitational acceleration :param l: length of the pendulum :return: derivativ...
1e83af5ed6028a9cd0ecf5819d3797986493df25
9,790
def task_edit(request, pk=None): """ """ return edit(request, form_model=TaskForm, model=Task, pk=pk)
8ff6f1bd007ff4f6931030da41f5efeaa2380d3a
9,792
import torch def _gradient(P, T, N, A): """ Creates the gradient operator, starting from the point set P, the topology tensor T, the normal tensor N and the triangle area tensor A Parameters ---------- P : Tensor the (N,3,) point set tensor T : LongTensor the (3,M,) topolo...
dd1118218ca6e8ad3ff3202c2a3c6d603f88a3a9
9,794
from typing import Tuple def breast_tissue_diagnostic_black_pen() -> Tuple[ openslide.OpenSlide, str ]: # pragma: no cover """breast_tissue_diagnostic_black_pen() -> Tuple[openslide.OpenSlide, str] Breast tissue, TCGA-BRCA dataset. Diagnostic slide with black pen marks. This image is available here...
9758d6ac89a5bb4402e89486be624de9fad986d4
9,795
def fitcand(t,fm,p,full=False): """ Perform a non-linear fit to a putative transit. Parameters ---------- t : time fm : flux p : trial parameter (dictionary) full : Retrun tdt and fdt Returns ------- res : result dictionary. """ dtL = LDTwrap(t,fm,p) dt ...
dbf1252d3a4b9d81d092d983b231b7f25a2ef10b
9,796