content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _get_instance_id(instance_list, identity): """ Return instance UUID by name or ID, if found. """ for i in instance_list.items: if identity in (i.properties.name, i.id): return i.id return None
f466e10028e9b84f23bd4ace1f02ad8f792517ee
13,494
def isPageWatched(user, trunk): """Is the page being watched by the user?""" result = (models.Subscription.all(). filter('user =', user). filter('trunk =', trunk). filter('method !=', models.Subscription.METH_MEH)) return result.count(1) != 0
07335b32e11ef275a8c23281e295ed175b2b5854
13,496
def _parse_constants(): """Read the code in St7API and parse out the constants.""" def is_int(x): try: _ = int(x) return True except ValueError: return False with open(St7API.__file__) as f_st7api: current_comment = None seen_comments = ...
ca3c10b1eda6d46f86e21f318b960781b8875cc3
13,498
def verify_outcome(msg, prefix, lista): """ Compare message to list of claims: values. :param prefix: prefix string :param lista: list of claims=value :return: list of possible strings """ assert msg.startswith(prefix) qsl = ["{}={}".format(k, v[0]) for k, v in parse_qs(msg[len(prefix) ...
dd24e16c3029c911b939af4a50f4c7c7a71c8722
13,499
import string def equationMaker(congruency=None, beat_type=None, structure=None, n=None, perms=None, catch = False): """ Function to create equation stimuli, like in Landy & Goldstone, e.g. "b + d * f + y" required inputs: congruency: 'congruent' or 'incongruent' ...
b2a81696055c77fa8803ab218e7b115a66a542aa
13,500
def get_deadline_delta(target_horizon): """Returns number of days between official contest submission deadline date and start date of target period (14 for week 3-4 target, as it's 14 days away, 28 for week 5-6 target, as it's 28 days away) Args: target_horizon: "34w" or "56w" indicating whe...
df09b04fc2e7065056b724cfe5d8966c06240b79
13,501
def perform_tensorflow_model_inference(model_name, sample): """ Perform evaluations from model (must be configured) Args: model_name ([type]): [description] sample ([type]): [description] Returns: [type]: [description] """ reloaded_model = tf.keras.models.load_model(model_n...
3c374dd76d4d40dbaffc7758694ff358ad1aefeb
13,502
def check_ntru(f, g, F, G): """Check that f * G - g * F = 1 mod (x ** n + 1).""" a = karamul(f, G) b = karamul(g, F) c = [a[i] - b[i] for i in range(len(f))] return ((c[0] == q) and all(coef == 0 for coef in c[1:]))
1c2ff2fbaadcdf80e5fd9ac49f39a301c9606ada
13,503
def Search_tau(A, y, S, args, normalize=True, min_delta=0): """ Complete parameter search for sparse regression method S. Input: A,y : from linear system Ax=y S : sparse regression method args : arguments for sparse regression method normalize : boolean. Normalize co...
30c74b0fed304df8851b9037e7091fb95be58554
13,505
def get_entry_accounts(entry: Directive) -> list[str]: """Accounts for an entry. Args: entry: An entry. Returns: A list with the entry's accounts ordered by priority: For transactions the posting accounts are listed in reverse order. """ if isinstance(entry, Transaction): ...
dec8da3ced1956b4ae4dca08e2de812c66dcb412
13,506
def enter_fastboot(adb_serial, adb_path=None): """Enters fastboot mode by calling 'adb reboot bootloader' for the adb_serial provided. Args: adb_serial (str): Device serial number. adb_path (str): optional alternative path to adb executable Raises: RuntimeError: if adb_path is invalid or adb e...
9f7a8dfe8d0ce47a172cf7d07feb1bd5d2e8b273
13,507
def thesaurus_manager_menu_header(context, request, view, manager): # pylint: disable=unused-argument """Thesaurus manager menu header""" return THESAURUS_MANAGER_LABEL
7c37e69d4a662e4a155ed6a63a473e2eb52fe28b
13,508
def create_compiled_keras_model(): """Create compiled keras model.""" model = models.create_keras_model() model.compile( loss=tf.keras.losses.sparse_categorical_crossentropy, optimizer=utils.get_optimizer_from_flags('client'), metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]) return mo...
252fe18678e302e216b7b05121dfedd3bb46a180
13,509
def psycopg2_string(): """ Generates a connection string for psycopg2 """ return 'dbname={db} user={user} password={password} host={host} port={port}'.format( db=settings.DATABASES['default']['NAME'], user=settings.DATABASES['default']['USER'], password=settings.DATABASES['defaul...
187fe1b576337613f791df657fd76ca8a4f783df
13,511
def get_phase_relation(protophase: np.ndarray, N: int = 0) -> np.ndarray: """ relation between protophase and phase Parameters ---------- protophase : np.ndarray N : int, optional number of fourier terms need to be used Returns ------- np.ndarray ...
828f200f55f8d17071a51244465311f8c99866f7
13,512
import re def handle_articlepeople(utils, mention): """ Handles #articlepeople functionality. Parameters ---------- utils : `Utils object` extends tweepy api wrapper mention : `Status object` a single mention Returns ------- None """ urls = re.findall(r'(h...
efdf2d7cda6124a163290aa7c3197a7462703749
13,513
from pathlib import Path def bak_del_cmd(filename:Path, bakfile_number:int, quietly=False): """ Deletes a bakfile by number """ console = Console() _bakfile = None bakfiles = db_handler.get_bakfile_entries(filename) if not bakfiles: console.print(f"No bakfiles found for {filename}") ...
3ded066c23708a3fdcc2e38fb07706dc0e0cd628
13,514
def fetch_county_data(file_reference): """The name of this function is displayed to the user when there is a cache miss.""" path = file_reference.filename return (pd .read_csv(path) .assign(date = lambda d: pd.to_datetime(d.date)) )
d29459efc5a46901cce970c2ddf4e499094f1aea
13,515
def preston_sad(abund_vector, b=None, normalized = 'no'): """Plot histogram of species abundances on a log2 scale""" if b == None: q = np.exp2(list(range(0, 25))) b = q [(q <= max(abund_vector)*2)] if normalized == 'no': hist_ab = np.histogram(abund_vector, bins = b) if ...
97eec01c5d23ca7b48951d4c62c7066b77ffb467
13,516
def exp_rearrangement(): """Example demonstrating of Word-Blot for pairwise local similarity search on two randomly generated sequencees with motif sequences violating collinearity :math:`S=M_1M_2M_3, T=M'_1M'_1M'_3M'_2` where motif pairs :math:`(M_i, M'_i)_{i=1,2,3}` have lengths 200, 400, 600 and are ...
fdd7650d2ab0340bd11d150f7f6ad5e60ddd2d09
13,517
def package_install_site(name='', user=False, plat_specific=False): """pip-inspired, distutils-based method for fetching the default install location (site-packages path). Returns virtual environment or system site-packages, unless `user=True` in which case returns user-site (typ. under `~/.local/ ...
31b477208954886f847bd33651464f386a4e6adf
13,518
def atlas_slice(atlas, slice_number): """ A function that pulls the data for a specific atlas slice. Parameters ---------- atlas: nrrd Atlas segmentation file that has a stack of slices. slice_number: int The number in the slice that corresponds to the fixed image for r...
bafe5d886568203792b0f6178302f3ca5d536e5b
13,519
def enviar_cambio_estado(request): """ Cambio de estado de una nota técnica y avisar por email al personal de stib """ if request.method == "POST" or request.POST.get("nota_tecnica"): try: nota_tecnica = get_object_or_404(NotasTecnicas, pk=request.POST.get("nota_tecnica")) ...
176a9a9d1bf7fd0ba1bec0c34526180581d33a8d
13,520
from typing import Dict import aiohttp async def head(url: str) -> Dict: """Fetch headers returned http GET request. :param str url: The URL to perform the GET request for. :rtype: dict :returns: dictionary of lowercase headers """ async with aiohttp.request("HEAD", url) as re...
b4decbfb4e92863c07c5202e2c884c02e590943f
13,522
def node_vectors(node_id): """Get the vectors of a node. You must specify the node id in the url. You can pass direction (incoming/outgoing/all) and failed (True/False/all). """ exp = Experiment(session) # get the parameters direction = request_parameter(parameter="direction", default="...
c61d85e4f4ae975bdd015f6bd181d1ae78aa245d
13,524
def newFlatDict(store, selectKeys=None, labelPrefix=''): """ Takes a list of dictionaries and returns a dictionary of 1D lists. If a dictionary did not have that key or list element, then 'None' is put in its place Parameters ---------- store : list of dicts The dictionaries would be e...
d44dec60de06779a8e965eb9e3771c66dd25e10b
13,525
from typing import Any from typing import List from typing import Union async def get_races( db: Any, token: str, raceplan_id: str ) -> List[Union[IndividualSprintRace, IntervalStartRace]]: """Check if the event has a races.""" races = await RacesService.get_races_by_raceplan_id(db, raceplan_id) if le...
393a38992be404e5a82517b13d24e85b42b57b30
13,526
from typing import Any def yaml_load(data: str) -> Any: """Deserializes a yaml representation of known objects into those objects. Parameters ---------- data : str The serialized YAML blob. Returns ------- Any The deserialized Python objects. """ yaml = yaml_import...
2e721698ef0bde3bd084127556d41503417ee516
13,528
def _get_current_branch(): """Retrieves the branch Git is currently in. Returns: (str): The name of the current Git branch. """ branch_name_line = _run_cmd(GIT_CMD_GET_STATUS).splitlines()[0] return branch_name_line.split(' ')[2]
1b0d93d6e69205981c06f4dc8a45cf21259f4ccd
13,529
from models.progressive_gan import ProgressiveGAN as PGAN def PGAN(pretrained=False, *args, **kwargs): """ Progressive growing model pretrained (bool): load a pretrained model ? model_name (string): if pretrained, load one of the following models celebaHQ-256, celebaHQ-512, DTD, celeba, cifar10. D...
cb78031a6aeca887c2ed17d02419c2b551a4b1ba
13,530
def _runge_kutta_step(func, y0, f0, t0, dt, tableau=_DORMAND_PRINCE_TABLEAU, name=None): """Take an arbitrary Runge-Kutta step and estimate error. Args: func: Function to evaluate...
f106c6842a7f9faed6e37bcb4305adbd4bd83146
13,532
def _create_serialize(cls, serializers): """ Create a new serialize method with extra serializer functions. """ def serialize(self, value): for serializer in serializers: value = serializer(value) value = super(cls, self).serialize(value) return value serialize._...
522f6a14fe3e2bca70c141f14dc8b400be1ca680
13,533
def confusion_matrix(y_true, y_pred, labels=None): """Compute confusion matrix to evaluate the accuracy of a classification By definition a confusion matrix cm is such that cm[i, j] is equal to the number of observations known to be in group i but predicted to be in group j. Parameters -------...
53d143a5388b23a61f927f4b8b4407cf8a051d3f
13,534
def dialect_selector(s): """Return a dialect given it's name.""" s = s or 'ansi' lookup = { 'ansi': ansi_dialect } return lookup[s]
e9232e22e2ef0789d98a16c8e2f3fd7efa5a7981
13,535
import unittest def importlib_only(fxn): """Decorator to skip a test if using __builtins__.__import__.""" return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
3cdc1ac5e0a2062b6822291973770459f6bf2318
13,536
def bf(x): """ returns the given bitfield value from within a register Parameters: x: a pandas DataFrame line - with a column named BF_NUMBER which holds the definition of given bit_field reg_val: integer Returns: -------- res: str the bit field value from within the register """...
6167666cf7c6c5df8b121b2f418d29ff95df8898
13,537
from typing import Union def get_mean_brightness( frame: np.ndarray, mask: Union[ np.ndarray, None, ] = None, ) -> int: """Return the mean brightness of a frame. Load the frame, calculate a histogram, and iterate through the bins until half or more of the pixels have been counted....
825afe97500f247aee4b1ccb045555fb21300cfe
13,538
def rearrange(s): """ Args: s Returns: [] """ if not can_arrange_palindrome2(s): return [] m = {} for c in s: if c in m: m[c] += 1 else: m[c] = 1 middle = "" for k in m: if m[k] % 2 == 0: m[k] /= 2...
bb6e03d35cc3f786c52ce7535628e02b51abd3a0
13,539
def get_org_memberships(user_id: str): """Return a list of organizations and roles where the input user is a member""" query = ( model.Session.query(model.Group, model.Member.capacity) .join(model.Member, model.Member.group_id == model.Group.id) .join(model.User, model.User.id == model.M...
eaa5ba796798289185816719a176efb31d7f25e6
13,540
def standardize_concentration(df, columns, unit="nM"): """Make all concentrations match the given unit. For a given DataFrame and column, convert mM, uM, nM, and pM concentration values to the specified unit (default nM). Rename the column to include ({unit}). Parameters ---------- d...
79f889640faf10e5b66989b0444a235cba872fd2
13,541
from visonic import alarm as visonicalarm def setup(hass, config): """ Setup the Visonic Alarm component.""" global HUB HUB = VisonicAlarmHub(config[DOMAIN], visonicalarm) if not HUB.connect(): return False HUB.update() # Load the supported platforms for component in ('sensor', '...
be11f167b393ed97d318f6f516c353ad1df39670
13,542
def generate_http_request_md_fenced_code_block( language=None, fence_string='```', **kwargs, ): """Wraps [``generate_http_request_code``](#generate_http_request_code) function result in a Markdown fenced code block. Args: fence_string (str): Code block fence string used wrapping the cod...
a34581e8c0d40542a625d222183adb601c60b408
13,544
def confident_hit_ratio(y_true, y_pred, cut_off=0.1): """ This function return the hit ratio of the true-positive for confident molecules. Confident molecules are defined as confidence values that are higher than the cutoff. :param y_true: :param y_pred: :param cut_off: confident value that defi...
0a7dbe9f3d81b877c309fd1fffb2840ec71dbeee
13,545
import click def onion(ctx, port, onion_version, private_key, show_private_key, detach): """ Add a temporary onion-service to the Tor we connect to. This keeps an onion-service running as long as this command is running with an arbitrary list of forwarded ports. """ if len(port) == 0: ...
7f36e967fc30877b504fda79699c7d3347a4f410
13,546
def determine_if_pb_should_be_filtered(row, min_junc_after_stop_codon): """PB should be filtered if NMD, a truncation, or protein classification is not likely protein coding (intergenic, antisense, fusion,...) Args: row (pandas Series): protein classification row min_junc_after_stop_codon (...
29ab7ce53ac7569c4d8a29e8e8564eab33b3f545
13,547
from typing import MutableMapping import hashlib def _get_hashed_id(full_name: str, name_from_id: MutableMapping[int, str]) -> int: """Converts the string-typed name to int-typed ID.""" # Built-in hash function will not exceed the range of int64, whi...
2eadfac0369d33ae29e4c054691180720995ef93
13,549
def find_adjustment(tdata : tuple, xdata : tuple, ydata : tuple, numstept=10,numstepx=10,tol=1e-6) -> tuple: """ Find best fit of data with temporal and spatial offset in range. Returns the tuple err, dt, dx. Finds a temporal and spatial offset to apply to the temporal and spatial locatio...
4efe607c40606b1235a5f9d62c3002a673a47828
13,550
import yaml def get_params(): """Loads ./config.yml in a dict and returns it""" with open(HERE/'config.yml') as file: params = yaml.load(file) return params
8e2e1b3ae47ff9a296aab7945562e3ea8ad43598
13,551
def get_textgrid(path_transcription): """Get data from TextGrid file""" data = textgriddf_reader(path_file=path_transcription) text_df = textgriddf_df(data, item_no=2) sentences = textgriddf_converter(text_df) return sentences
d3e037ff10488eb1eed777e008599769ddf9d81f
13,553
import http def accessible_required(f): """Decorator for an endpoint that requires a user have accessible or read permission in the given room. The function must take a `room` argument by name, as is typically used with flask endpoints with a `<Room:room>` argument.""" @wraps(f) def required_acc...
e4e13632963fb80377dcbdaa36e90c4c62dd9a1f
13,554
import warnings def make_erb_cos_filters_nx(signal_length, sr, n, low_lim, hi_lim, sample_factor, padding_size=None, full_filter=True, strict=True, **kwargs): """Create ERB cosine filters, oversampled by a factor provided by "sample_factor" Args: signal_length (int): Length of signal to be filtered with the ...
207a9d3be6b732c1d86a5ed5bde069d5ea760347
13,555
def button_ld_train_first_day(criteria, min_reversal_number): """ This function creates a csv file for the LD Train test. Each row will be the first day the animal ran the test. At the end, the function will ask the user to save the newly created csv file in a directory. :param criteria: A widget that ...
9de68279f6ffb8253275a7a7051a1ed9b2df8f8e
13,556
def analyze_video(file, name, api): """ Call Scenescoop analyze with a video """ args = Namespace(video=file, name=name, input_data=None, api=True) scene_content = scenescoop(args) content = '' maxframes = 0 for description in scene_content: if(len(scene_content[description]) > maxframes): con...
92e176a5c951d038aa8477db7aec0705fba0152c
13,557
def encdec_model(input_shape, output_sequence_length, english_vocab_size, french_vocab_size): """ Build and train an encoder-decoder model on x and y :param input_shape: Tuple of input shape :param output_sequence_length: Length of output sequence :param english_vocab_size: Number of unique English ...
47fa1893cc04b491292461db6c8a3418b464ba45
13,559
def close_to_cron(crontab_time, time_struct): """coron的指定范围(crontab_time)中 最接近 指定时间 time_struct 的值""" close_time = time_struct cindex = 0 for val_struct in time_struct: offset_min = val_struct val_close = val_struct for val_cron in crontab_time[cindex]: offset_tmp = v...
7ce04d9b4260e7ea1ed7c3e95e7c36928989024e
13,560
def remove_stop_words(words_list: list) -> list: """ Remove stop words from strings list """ en_stop_words = set(stopwords.words('english')) return [w for w in words_list if str(w).lower not in en_stop_words]
a6e3c117ea805bdfaffe80c17fc5e340a869d55d
13,561
def min_geodesic_distance_rotmats_pairwise_tf(r1s, r2s): """Compute min geodesic distance for each R1 wrt R2.""" # These are the traces of R1^T R2 trace = tf.einsum('...aij,...bij->...ab', r1s, r2s) # closest rotation has max trace max_trace = tf.reduce_max(trace, axis=-1) return tf.acos(tf.clip_by_value((m...
a4da40aa9594c301b0366da0a26d73afce83e05f
13,563
def project_to_2D(xyz): """Projection to (0, X, Z) plane.""" return xyz[0], xyz[2]
c6cdb8bd6dce65f6ce39b14b9e56622832f35752
13,564
def Geom2dInt_Geom2dCurveTool_D2(*args): """ :param C: :type C: Adaptor2d_Curve2d & :param U: :type U: float :param P: :type P: gp_Pnt2d :param T: :type T: gp_Vec2d :param N: :type N: gp_Vec2d :rtype: void """ return _Geom2dInt.Geom2dInt_Geom2dCurveTool_D2(*args)
6ac157e171af9d4bab852a9677287e33bb1d90f2
13,565
def notfound(request): """ Common notfound return message """ msg = CustomError.NOT_FOUND_ERROR.format(request.url, request.method) log.error(msg) request.response.status = 404 return {'error': 'true', 'code': 404, 'message': msg}
b690d9b879db15e192e8ee50d4ea2b0847ba658b
13,566
def l2norm(a): """Return the l2 norm of a, flattened out. Implemented as a separate function (not a call to norm() for speed).""" return np.sqrt(np.sum(np.absolute(a)**2))
b5ce94bfc0f3472e60a4338c379bc4dfe490e623
13,567
def create_container(request): """ Creates a container (empty object of type application/directory) """ storage_url = get_endpoint(request, 'adminURL') auth_token = get_token_id(request) http_conn = client.http_connection(storage_url, insecure=settings.SWIFT_INSEC...
15c25df933f7620cee71319f9f41e92e29880d1c
13,568
def get_searchable_models(): """ Returns a list of all models in the Django project which implement ISearchable """ app = AppCache(); return filter(lambda klass: implements(klass, ISearchable), app.get_models())
ad7c56f17ec4e0fc77942fe1466b879bd45eb191
13,570
def create_updated_alert_from_slack_message(payload, time, alert_json): """ Create an updated raw alert (json) from an update request in Slack """ values = payload['view']['state']['values'] for value in values: for key in values[value]: if key == 'alert_id': cont...
a685a0c0da472f055dc8860bdf09970a1ecc8aff
13,571
def enforce(*types): """ decorator function enforcing, and converting, argument data types """ def decorator(fn): def new_function(*args, **kwargs): # convert args into something mutable, list in this case newargs = [] for original_argument, type_to_convert in...
217ad3adccdaa9fc83ceaf5ef2c0905b8d54f1ed
13,572
from typing import Type from typing import Any from typing import Sequence from enum import Enum from datetime import datetime def modify_repr(_cls: Type[Any]) -> None: """Improved dataclass repr function. Only show non-default non-internal values, and summarize containers. """ # let classes still cr...
ddc860bbe3c9d04723a3cc0b4cdcce960d0ecf71
13,573
def _is_binary(path): """Checks if the file at |path| is an ELF executable. This is done by inspecting its FourCC header. """ with open(path, 'rb') as f: file_tag = f.read(4) return file_tag == '\x7fELF'
0c5bc0917f405604a6d36495b786c9fbc9268ad1
13,574
from typing import Optional import typing def update_item(*, table: str, hash_key: str, sort_key: Optional[str] = None, update_expression: Optional[str], expression_attribute_values: typing.Dict, return_values: str = 'ALL_NEW'): """ Update an item from a dynamoDB table. Will determine the ...
a6efc6638708d1c5dfc79d89216cfa866e3a24fa
13,575
import re def google_login_required(fn): """Return 403 unless the user is logged in from a @google.com domain.""" def wrapper(self, *args, **kwargs): user = users.get_current_user() if not user: self.redirect(users.create_login_url(self.request.uri)) return email_match = re.match('^(.*)@(....
1e45f2ea026e772b6b4c9048dddf93b2fe3ec991
13,577
def init_res_fig(n_subplots, max_sess=None, modif=False): """ init_res_fig(n_subplots) Initializes a figure in which to plot summary results. Required args: - n_subplots (int): number of subplots Optional args: - max_sess (int): maximum number of sessions plotted ...
3c12c18c16a371d10977d165875a2aa346c009bf
13,578
import json def change_personal_data_settings(request): """ Creates a question with summarized data to be changed :param request: POST request from "Change personal data settings" Dialogflow intent :return: JSON with summarized data to be changed """ language = request.data['queryResult']['lan...
c18641ea4cc32e8d2703dfca90066b6736c5103a
13,579
def get_selected_cells(mesh, startpos, endpos): """ Return a list of cells contained in the startpos-endpos rectangle """ xstart, ystart = startpos xend, yend = endpos selected_cells = set() vertex_coords = mesh.coordinates() for cell in dolfin.cells(mesh): cell_vertices = cell....
c637bfa195aae4125e65553b1f4023cc3dae1f3a
13,580
def flip_axis(array, axis): """ Flip the given axis of an array. Note that the ordering follows the numpy convention and may be unintuitive; that is, the first axis flips the axis horizontally, and the second axis flips the axis vertically. :param array: The array to be flipped. :type array: `n...
e2839125ddf3b22dea732857763fda636b748dda
13,581
def fizz_buzz_tree(input_tree): """ traverses a tree and performs fizz buzz on each element, agumenting the val """ input_tree.in_order_trav(lambda x: fizzbuzz(x)) return input_tree
29b7380fb6215bf8ecf67fa85321445b8954abdc
13,582
def generate_key(keysize=KEY_SIZE): """Generate a RSA key pair Keyword Arguments: keysize {int} -- Key (default: {KEY_SIZE}) Returns: bytes -- Secret key bytes -- Public key """ key = RSA.generate(keysize) public_key = key.publickey().exportKey() secret_key = key.ex...
0a38221269b167c4ceefc95eb4cee3452f2aaffe
13,585
import functools def get_api_endpoint(func): """Register a GET endpoint.""" @json_api.route(f"/{func.__name__}", methods=["GET"]) @functools.wraps(func) def _wrapper(*args, **kwargs): return jsonify({"success": True, "data": func(*args, **kwargs)}) return _wrapper
d49dc725e7538374910e3819f8eae647250747f7
13,586
def get_mt4(alias=DEFAULT_MT4_NAME): """ Notes: return mt4 object which is initialized. Args: alias(string): mt4 object alias name. default value is DEFAULT_MT4_NAME Returns: mt4 object(metatrader.backtest.MT4): instantiated mt4 object """ global _mt4s if alias in _mt4s: ...
ee228ced5790124768c8a41e70bf596181a55ca2
13,588
import warnings def get_log_probability_function(model=None): """ Builds a theano function from a PyMC3 model which takes a numpy array of shape ``(n_parameters)`` as an input and returns returns the total log probability of the model. This function takes the **transformed** random variables defi...
8e4332ce6943341b196d1628942f3360ce9f4e05
13,589
def get_health(check_celery=True): """ Gets the health of the all the external services. :return: dictionary with key: service name like etcd, celery, elasticsearch value: dictionary of health status :rtype: dict """ health_status = { 'etcd': _check_etcd(), 'sto...
95fec6ee762ab81a8e27ebe796b914be6d38c59d
13,590
def add_quotation_items(quotation_items_data): """ 添加信息 :param quotation_items_data: :return: None/Value of user.id :except: """ return db_instance.add(QuotationItems, quotation_items_data)
09f60cc4e8182909acb34bb0b406336849bf8543
13,591
def load_cifar10_human_readable(path: str, img_nums: list) -> np.array: """ Loads the Cifar10 images in human readable format. Args: path: The path to the to the folder with mnist images. img_nums: A list with the numbers of the images we want to load. Returns: ...
991ff4cd7192c0ed4b1d6e2d566ed1f0ce446db5
13,592
import typing def get_project_linked_to_object(object_id: int) -> typing.Optional[Project]: """ Return the project linked to a given object, or None. :param object_id: the ID of an existing object :return: the linked project or None :raise errors.ObjectDoesNotExistError: if no object with the giv...
189282be5acfb063678ca2c6765eeb1a7fa6b6c5
13,594
def calc_distances_for_everyon_in_frame(everyone_in_frame, people_graph, too_far_distance, minimum_distance_change): """ :param everyone_in_frame: [PersonPath] :type everyone_in_frame: list :param people_graph: :type people_graph: Graph :param too_far_distance: :param minimum_distance_...
83dcb204b53d2ac784d1cc8bb0da61a114a41768
13,596
import torch def conv2d(input: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor = None, stride=1, padding=0, dilation=1, groups=1, mode=None): """Standard conv2d. Returns the input if weight=None.""" if weight is None: ...
b43b975d96d273fa1ee1cfe4034ca1fd195b5019
13,597
import tqdm import torch def infer(model, loader_test): """ Returns the prediction of a model in a dataset. Parameters ---------- model: PyTorch model loader_test: PyTorch DataLoader. Returns ------- tuple y_true and y_pred """ model.eval() ys, ys_h...
956b17d8b3869eeff6d35019ac82cd3ca5d4092e
13,598
import keyword def validate_project(project_name): """ Check the defined project name against keywords, builtins and existing modules to avoid name clashing """ if not project_name_rx.search(project_name): return None if keyword.iskeyword(project_name): return None if proje...
569fdb1d6d37ce50b144facc6cba725a0575b2f6
13,599
def _print_available_filters(supported_filters): """Prints information on available filters and their thresholds.""" widths = (20, 40, 20) data = [("Filter", "Description", "Threshold Values"), ("------", "-----------", "----------------")] # this is stupid for f, (d, t, c) in supported_...
49a769a27d2a4a0beaba1021821c8d1e551f53eb
13,600
def _get_dates(i, *args, **kwargs): """ Get dates from arguments """ try: start_date = kwargs['start_date'] except: try: start_date = args[i] except: start_date = None try: end_date = kwargs['end_date'] except: try: ...
708bc0fcc5be80ef3b3008b9569bb14a01c4bace
13,601
def home_page(): """Shows home page""" html = """ <html> <body> <h1>Home Page</h1> <p>Welcome to my simple app!</p> <a href='/hello'>Go to hello page</a> </body> </html> """ return html
444833ab61803d1fe52676834e211ac79e770b4e
13,602
def GetPDFHexString(s, i, iend): """Convert and return pdf hex string starting at s[i], ending at s[iend-1].""" j = i + 1 v = [] c = '' jend = iend - 1 while j < jend: p = _re_pswhitespaceandcomments.match(s, j) if p: j = p.end() d = chr(ordat(s, j)) ...
516d7c33bcd1b2237eb482e9722de4552ac79ce2
13,603
def get_edge_syslog_info(edge_id): """Get syslog information for specific edge id""" nsxv = get_nsxv_client() syslog_info = nsxv.get_edge_syslog(edge_id)[1] if not syslog_info['enabled']: return 'Disabled' output = "" if 'protocol' in syslog_info: output += syslog_info['protoco...
5c5ea79109b9a9053f95945a7902d9e6322a6ba6
13,604
from typing import List def _get_rec_suffix(operations:List[str]) -> str: """ finished, checked, Parameters ---------- operations: list of str, names of operations to perform (or has performed), Returns ------- suffix: str, suffix of the filename of the preprocessed ecg s...
270a1b3749342d05819eafef3fa5175da393b1ad
13,605
def get_A_text(params, func_type=None): """ Get text associated with the fit of A(s) """ line1 = r'$A(s|r)$ is assumed to take the form:' line2 = (r'$A(s|r) = s^{-1}\bigg{(}\frac{s}{\Sigma(r)}\bigg{)}^a ' r'exp\bigg{(}{-\bigg{(}\frac{s}{\Sigma(r)}\bigg{)}^b}\bigg{)}$') a, b = params...
ec68c49a7912dc5630e3c96a09d667ce52f89914
13,606
def transform_to_dict(closest_list: list) -> dict: """ Returns dict {(latitude, longitude): {film1, film2, ...}, ...} from closest_list [[film1, (latitude, longitude)], ...], where film1, film2 are titles of films, (latitude, longitude) is a coordinates of a place where those films were shoot. ...
e7c6fae73792a828d85db03e794bfb69c7b1fe87
13,607
def get_numpy_val_from_form_input(input_name): """Get a NumPy-compatible numerical value from the request object""" return get_numpy_val(input_name, request.form[input_name])
fadfbf106c82088103674e5da5f526e08e2a05ac
13,609
import numpy def load_model(model, path): """Load a the model parameters from a file and set them. Parameters ---------- model : a :class:`Layer` instance The model with unset parameters. path : string The file with the model parameters. Returns ------- a :class:`Laye...
dae27ffc78be7aa7476c645c4f021d4acaef5b44
13,610
def node_id_at_cells(shape): """Node ID at each cell. Parameters ---------- shape : tuple of int Shape of grid of nodes. Returns ------- ndarray : ID of node associated with each cell. Examples -------- >>> from landlab.grid.structured_quad.cells import node_id...
f089f598cacc4d5ec6885477098dcca741358820
13,611
def search_media(search_queries, media, ignore_likes=True): """Return a list of media matching a queary that searches for a match in the comments, likes, and tags in a list of media""" # Initialize update message update_message = print_update_message(len(media)) update_message.send(None) # Init...
23ed38496310cc86c4d3d7f8aff4e1d5c61f9d69
13,612
def get_produced_messages(func): """Returns a list of message fqn and channel pairs. Args: func (Function): function object Returns: list """ result = [] for msg, channel in func.produces: result.append((_build_msg_fqn(msg), channel)) return result
b63d9305f3af3e474beb1fb328881123d8f4ece6
13,614
from pathlib import Path from typing import Sequence def find_coverage_files(src_path: Path) -> Sequence: """ Find the coverage files within the specified src_path. Parameters: src_path (Path): The path in which to look for the .coverage files. Returns: (Sequence) The set of .cov...
53fd9b2d2405ed6fe895718e22cc6b1ddb86f4df
13,615