content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_abstract_dist(dist): """ Returns an abstract representation of the distribution. For now, it hacks in a way to deal with non-homogeneous Cartesian product sample spaces. """ if dist.is_homogeneous(): n_variables = dist.outcome_length() n_symbols = len(dist.alphabet[0]) ...
d91f6d92ef2aeac8406b24ea086040339962bf50
3,625,123
def dice_loss(y_true, y_pred, logits=True): """ Dice loss Parameters --------------- y_true: np.ndarray True mask y_pred: np.ndarray Predicted mask logits: bool, optional Flag for whether prediction is probability distribution or a...
a6cf92e09f72a11f74810bca16ef2120faca8f73
3,625,124
def fuse_bg_features(feats): """ :param feats: :return: """ fused_feats = [] for feat in feats: feat = feat.flatten(1) feat = feat.mean(dim=0) fused_feats.append(feat) return fused_feats
e268f925b0b54c12c0270a1df6345950f5b21f5f
3,625,125
def welcome(): """List all available api routes.""" return (f"Welcome to the SQL-Alchemy APP API!<br/>" f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/[start_date format:yyyy-mm-dd]<br/>" f"/...
4fc44b0bfb247bd6d7187f936d235c837bf81e0b
3,625,126
def interact(res, val, min_val, max_val): """ Interact with user """ if res == ">=": if(val >= max_val): return val, min_val, max_val, True min_val = val val = ceil((val + max_val) / 2) elif res == "<": if(val < min_val): return val, min_val, m...
6d54a469f9f5b6316a017d93cfcf2d4ff292a617
3,625,127
def staff_of_group(group_id: int) -> list: """ Return collection of students in group :param group_id, required - group' ID. """ return get("staffOfGroup", groupOid=group_id)
0574bb3d662e77217b1c515dc43893e6b9fea5d6
3,625,128
def url_join(*args): """Join combine URL parts to get the full endpoint address.""" return '/'.join(arg.strip('/') for arg in args)
2b8409910186d3058c2e49bbf6f974a7cfceeffb
3,625,129
def run_main(params): """Function to run multiple iterations for testing Args: params: dictionary of parameter values Returns: the field data """ return pipe( dict(e11=0.0, e12=0.0, e22=0.0, eta=None, step_counter=0), iterate_(one_iter(params), params["iterations"]), ...
ed77b629f8a7742a8d29ca6c2355b9a327177472
3,625,130
def filter_word_ids_with_non_zero_probability(word_ids, probas, pad_id=None): """ Filter out entries of word_ids that have exactly zero probability or are mapped to pad positions (if pad_id is not None). Args: word_ids (torch.LongTensor): tensor with word ids. Shape of (batch_size, ...
4e3e79c087dc0a3396dc23468091e8cf58f474a3
3,625,131
import ssl def transcribe(fpath, appid, api_key, api_secret): """ 科大讯飞ASR """ global wsParam, gResult gResult = '' wsParam = Ws_Param(appid, api_key, APISecret=api_secret, AudioFile=fpath) websocket.enableTrace(False) wsUrl = wsParam.create_url() ws = websocket.WebSocketApp(wsUrl, ...
b242de089860404a6187e441ca2e0776a83f32dc
3,625,132
def profile(request, username): """ Simple view of user profile. Template: people/profile.html Context: p_user - user to display profile of """ user = get_object_or_404(User, username=username) return render_to_response('people/profile.html', {'p_user':user}, ...
25f28a0ac3c95a6bc2d51b7e6e7864a8e40c0f1d
3,625,133
def accuracy_at_stg_change_trials(df, subj_unq, prev_w=10, nxt_w=10, conv_w=10): """ The function returns the mean and standard deviation of the changes from a stage to another. Parameters ---------- df : dataframe dataframe containing data. subj_unq : numpy.ndarray array of...
f2c982e397324daaa40048f3c46fb2786793afd3
3,625,134
def quoteattr(data, entities={}): """Escape and quote an attribute value. Escape &, <, and > in a string of data, then quote it for use as an attribute value. The \" character will be escaped as well, if necessary. You can escape other strings of data by passing a dictionary as the optional e...
19b09da057703dff09fe52f27efd60d759ca2dda
3,625,135
def is_pairwise_disjoint(sets): """ This function will determine if a collection of sets is pairwise disjoint. Args: sets (List[set]): A collection of sets """ all_objects = set() for collection in sets: for x in collection: if x in all_objects: retur...
4d5c434b2db2cb167f51aa4c04534a9b12239547
3,625,136
def get_incident_recency(prev_incident: submit_schema.Form, current_incident: submit_schema.Form, timeframe: int): """ Returns a value between min_value and 1 depending on the previous incident type's recency scaled by the timeframe. """ min_value = 0.6 prev_incident.occurrence_time = prev_incident....
e6a68fbe52058de7353d1af9870132e57e82ae2d
3,625,137
def key_of(dic, value): """ Returns the key corresponding to the specified value in the supplied dict. """ if isinstance(value, np.ndarray): return [k for k, v in dic.items() if all(v == value)][0] return [k for k, v in dic.items() if v == value][0]
fd1e625f4073b3dbcbb304d709130d9ab4baeb07
3,625,139
def project_has_hook_attr_value(project, hook, attr, value): """Finds out if project's hook has attribute of given value. :arg project: The project to inspect :type project: pagure.lib.model.Project :arg hook: Name of the hook to inspect :type hook: str :arg attr: Name of hook attribute to insp...
f275c8877d9df2a58a0812d657879b370220532a
3,625,140
import random import sympy import example def place_value(value, sample_args, context=None): """E.g., "Q: What is the tens digit of 31859? A: 5.""" del value # unused for now if context is None: context = composition.Context() entropy, sample_args = sample_args.peel() integer = number.in...
feb396d6f644d045e273ec4214861c82ec3bbfc0
3,625,142
def rep_mat(argin, n, m): """ Ensures 1D result """ return np.squeeze(repmat(argin, n, m))
d091b320c49eb5f0beeaf1c86ec2d5dc17e02582
3,625,143
def value_or_default(value, default=np.nan): """ Returns the given value if it is not none. Otherwise returns the default value. Args: value: The value. default: The default. Returns: Returns the given value if it is not none. Otherwise returns the default value. """ # ...
3424c19b36a165525f2e110f55b500b5a674cc79
3,625,144
def type_to_python(typename, size=None): """type_to_python(typename: str, size: str) -> str Transforms a Declarations.yaml type name into a Python type specification as used for type hints. """ typename = typename.replace(' ', '') # normalize spaces, e.g., 'Generator *' # Disambiguate explici...
ae7131d40e9e8da9d5543d57577661cce5c68d28
3,625,145
def build_find_cmd(opts, paths): """ Builds teh cmd file using ctags. Returns cmd based on the following template: 'find {0} -type f {1} | etags -' """ find_args = build_find_args(get_exts(opts)) return ['find']+paths+['-type', 'f']+find_args
8125ca505ccfe251e847e695747a5e8f1bac7c75
3,625,146
import torch import math def histeq(x, n=1024, dim=None): """Histogram equalization Notes ----- .. The minimum and maximum values of the input tensor are preserved. .. A piecewise linear transform is applied so that the output quantiles match those of a "template" histogram. .. By defa...
e47d6d5f9d2df1e7a212580feb519cde76002f6d
3,625,147
def mc(data): """ Modulus calculation Calculated sqrt(real^2+imag^2) """ return np.sqrt(data.real**2+data.imag**2)
1c2745d05b71e7f6c6b1426e066c80c6f611358f
3,625,148
import re import hashlib def make_safe_label_value(string): """ Valid label values must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between. If the label value is then greate...
979c0ee7968ed666aff0fa0a7caaf0f6aae32c74
3,625,149
def reducePoly(ps): """ Return the basis (e.g., a min subset of ps that implies ps) of the set of eqts input ps using Groebner basis sage: var('a y b q k') (a, y, b, q, k) sage: rs = reducePoly([a*y-b==0,q*y+k-x==0,a*x-a*k-b*q==0]) sage: assert set(rs) == set([a*y - b == 0, q*y + k - x =...
a5aeef11a0b2be3b63b86dbb3004fa178dd0e43e
3,625,150
def _get_saver_or_default(): """Returns the saver from SAVERS collection, or creates a default one. This method is used by other members of the training module, such as `Scaffold`, or `CheckpointSaverHook`. Returns: `Saver`. Raises: RuntimeError: If the SAVERS collection already has more than one i...
6bec4e875fa475d53d149e42e02e48e5ed1834b5
3,625,151
def Bool(value): """Returns a Boolean constant with the given value. :param value: Specify the value :returns: A Boolean constant with the given value """ return get_env().formula_manager.Bool(value)
3a83d2251c4fbffdf0132251669051c2b81cefb6
3,625,153
def get_one_idle_marine(obs): """ check if any idle marine are available :return idle_scv_pos: [x, y], if no, return None """ for unit in obs.observation.feature_units: if unit.unit_type == units.Terran.Marine and int(unit.order_length) == 0: return [unit.x, unit.y] return No...
15463684d089d959931e6b91b11d7ca1e2b7076b
3,625,155
def create_title_font(name, style_name): """ Defines a paragraph style for titles """ return ParagraphStyle(name, fontName=name, fontSize=TITLE_FONT_SIZE, parent=style[style_name], alignment=ALIGNMENT...
4d04ee68eb28939a40d617243954b447de3daeab
3,625,156
def myfunc_s( step ): """ Function used for the making the computation of overlaps parallel via python multiprocessing """ s_sd = step3.mapping.ovlp_mat_arb( sd_states_reindexed_sorted[step], sd_states_reindexed_sorted[step], S_ks[0][step], use_minimal=False ) #print(step, "s_sd as CMATRIX <1|1...
f21bff6e5e139b2792093881d0ee8e3363ae5cd8
3,625,157
def get_auc_roc_curve(y_true, y_pred, n_classes, labels=None): """Plot visualization. Parameters ---------- y_true : sparse labels integers y_pred : prediciton probabilities n_classes : number dataset classes labels=None : name of class labels Returns ------- matplotlib.pyplot.Figure """ y_true=(np.eye(n_cl...
594bbc5be825889bf4f76f31f49ffdef1c9fb0c9
3,625,158
from typing import Sequence def species_download_coding(species_id): """ Generates a fasta file with all coding sequences for a given species :param species_id: Internal ID of the species :return: Response with the fasta file """ output = [] current_species = Species.query.get(species_id...
4b3b53e56a54088b2870e97e9ca7ae3409e1a50d
3,625,159
def check_not_modified(request, last_modified): """Handle 304/If-Modified-Since With Django v1.9.5+ could just use "django.utils.cache.get_conditional_response", but v1.9 is not supported by "logan" dependancy (yet). """ if_modified_since = parse_http_date_safe(request.META.get('HTTP_IF_MODIFIED_S...
ef0fd53fb1c54dc02e9236a8a39ace83a55a3104
3,625,160
def create_action_client(action): """Creates corresponding ROS action client. Args: action: ROS action name. Returns: Corresponding actionlib.SimpleActionClient instance. None if action server not found. """ action_cls = get_action_class(action) client = actionlib.Simpl...
2716afea306422004628e4b654a4121e33dea8d6
3,625,161
def find_reachable_vertices(g: Graph, sources: set) -> set: """ Returns the set of vertices of a graph which are reachable from a set of source vertices. Args: g: Graph, an instance of `Graph` sources: set, a set of integers representing the source vertices Returns: The set o...
f06895c10550d04b39e2c674489b1c6a4713e7ab
3,625,162
def create_course(): """ Администратор может создать учебный курс, указав его название и текстовое описание. """ answer = blank_resp() try: if current_user.status != 'admin': raise Exception('Only admins can create course') form = CourseForm(request.form) if form.va...
116578f64c2b4a367aa168f12ce963fb7bf9dc0c
3,625,163
import random def generate_password(length=16, symbolgroups=DEFAULT_PASSWORD_SYMBOLS): """Generate a random password from the supplied symbol groups. At least one symbol from each group will be included. Unpredictable results if length is less than the number of symbol groups. Believed to be reasona...
aac8adc18010d1448800da95df4b0d9b00da9c7e
3,625,164
def colorize(color, text, *, kind='fg'): """ ** Adds the flags that allow to format the color text. ** Parameters ---------- color : str or tuple Either the name of the color in str, or the result of the function ``_str_to_color``. text : str The text to be formatted. ...
31af133610c8cbb384130fa20833f184a106db09
3,625,165
def interpret_result(yhati, threshold=0.5): """ :param yhati: result of prediction for a file :return: String: the language """ for i in range(0, len(yhati)): if yhati[i] > threshold: return defs.langs[i]
df3e1d1363fd7e207ef755ded40be6d190e419ec
3,625,166
from operator import contains import ast def rewrite_ast(node, name, expr, assumed_result): """ Based on the assumed value of an expression, re-writes the AST tree to constants where possible. """ if name[0] == "CompareOperator": return compare.compare_rewrite(node, name, expr, assumed_res...
2e3cf8d6179b28cf6e8127b0fca4368ae278f044
3,625,168
def getMatrixRepresentation(values, shouldTranspose, n, Z, rateNumerator, rateDenominator): """ @param values: a list of strings, ('-' for empty cell). These represent the values @param shouldTranspose: if True, the values are given column by column (first col1 from top to bottom, then co...
bb6a6a2578502b1221666d15dd19633b243c8046
3,625,169
from . import __version__ def make_auth_anonymous(): """Format an AUTH command line for the ANONYMOUS mechanism Jeepney's higher-level wrappers don't currently use this mechanism, but third-party code may choose to. See <https://tools.ietf.org/html/rfc4505> for details. """ trace = hexlify((...
515440eb0ec5f557f40e70d3c9d5d87f5391f879
3,625,170
def cal_s11_1_port_short(model): """This action should select the short class""" commands = { Model.HP_8753D: 'CLASS11B', } return commands.get(model)
9df660e9e9cd1462e03ba38ef0e377792ccbdbea
3,625,171
def torch_to_np(tensors): """Convert PyTorch tensors to numpy arrays. Args: tensors (tuple): Tuple of data in PyTorch tensors. Returns: tuple[numpy.ndarray]: Tuple of data in numpy arrays. Note: This method is deprecated and now replaced by `metarl.torch._functions.to_numpy`. ...
cc45c30b85617ed44e675593fba0cf139b666d7b
3,625,172
def select_cycle(data, cycle=-1, min_length=0): """ Select current cycle. Notes ----- Calls automatically :func:`detect_strain_cycles()` if needed. Sets `irange` attribute of `data`. """ if not len(data.cycles): data = detect_strain_cycles(data) data.icycle = cycle try:...
9afca242ef23a97dc2793bebc53561a1a6719db7
3,625,173
def welcome(): """List all available api routes.""" return ( f" Hawaii Climate API Surf's Up <br/>" f"Available Routes:<br/>" f"/api/v1.0/precipitation<br/>" f"/api/v1.0/stations<br/>" f"/api/v1.0/tobs<br/>" f"/api/v1.0/start<br/>" f"/api/v1.0/start/end" ...
120c1496fce2f7c477218c486f566ae84c1009e4
3,625,175
import time def transfer(sender, receiver): """ Send datagrams from `sender` to `receiver`. """ datagrams = 0 from_addr = CLIENT_ADDR if sender._is_client else SERVER_ADDR for data, addr in sender.datagrams_to_send(now=time.time()): datagrams += 1 receiver.receive_datagram(data...
7ff7607f76e4de318f757504c442f3070018bae5
3,625,176
def _rapRperiAxiFindStart(R,E,L,pot,rap=False,startsign=1.): """ NAME: _rapRperiAxiFindStart PURPOSE: Find adequate start or end points to solve for rap and rperi INPUT: R - Galactocentric radius E - energy L - angular momentum pot - potential rap - if Tr...
3cb24586ca2dd4b3f623fb329296959990c76db4
3,625,177
def beta_divergence(X, Y, b): """ \beta-divergence Parameters: X: NMFで推定したスペクトログラム Y: 真のスペクトログラム(=入力) b: beta-factor Returns: beta-divergenceの値 """ RX,RY = _adjust_vector_dimensions(X, Y) if b == 1: d = (RY*(sp.log(RY+0.00001)-sp.log(RX+0.00001)...
a1168f975c62ace52524c0f3312988ad0313c81d
3,625,178
from typing import Tuple from typing import List from typing import Dict def _tasks_scheduler_config(venv_path, project_config) -> Tuple[List[Dict], List[str]]: """ tasks_scheduler supervisor config """ async_tasks_config = { 'name': 'async_tasks', 'command': f"{venv_path}/bin/python run.py a...
f308ca9661c3ecdde35b76d48a034102b1e39373
3,625,179
def init_loadlimit_router(loadlimit_notation: str = None): """initializes a route where a client (or any other network peer) can inquire what opal clients are currently connected to the server and on what topics are they registered. If the OPAL server does not have statistics enabled, the route will ...
9610a2c39d1ea8683b3f07c491cdf2c780965db7
3,625,180
def draw_lines(img, lines, color=[255, 0, 0], thickness=2): """ NOTE: this is the function you might want to use as a starting point once you want to average/extrapolate the line segments you detect to map out the full extent of the lane (going from the result shown in raw-lines-example.mp4 to that...
231cba8a15c36eab720db79f6ac88fc3cf7b4729
3,625,181
import codecs def getSimilarChars(): """When user runs this script, similar characters file may be provided as one of optional arguments. User creates similar character groups and put each group on a new line in file and separate those character by comma. E.g. ჟ,უ,ქ,ჭ,ჰ so the method can parse this f...
643b034127a14a7d820a37edfd2f3f25f64b6cff
3,625,182
import re def sanitize_post_body(body): """ >>> sanitize_post_body(None) '' >>> sanitize_post_body(11) '' >>> sanitize_post_body('#this is a h1') 'this is a h1' >>> sanitize_post_body('```lorem ipsum dolor sit amet``` There are many variations of passages') 'lorem ipsum dolor s...
979b780c61956c98433e6931719773dae837f8ab
3,625,183
def precipite(): """Return a JSON list of precipitations for last 12 months from the dataset.""" #create the session session = Session(engine) # Find the most recent date in the data set. recent_date=session.query(measurement.date).order_by(measurement.date.desc()).first() # Design a query to r...
fb5353e6e4b303e03d16d4ef998451d20ae30b9d
3,625,184
import functools def caching_module_getattr(cls): """ Helper decorator for implementing module-level ``__getattr__`` as a class. This decorator must be used at the module toplevel as follows:: @caching_module_getattr class __getattr__: # The class *must* be named ``__getattr__``. ...
17a05df9556947a5760a2341e35395af5376047e
3,625,185
def smallDF(numCells: int): """Creates Xarray of a specific # of experiments Zscores all markers per experiment but pSTAT5 normalized over all experiments Outputs amount of experiments and cell types as an Xarray""" # numCells = Amount of cells per experiment flowArrow = pq.read_table("/opt/andrew/F...
c3f55c6a6c809eeb47e9260a8616893937ce1947
3,625,186
def random(N, prng=None): """Create N p(correct) sampled from a uniform distribution (0-1)""" prng = process_prng(prng) return prng.rand(N), prng
884b1287b65a1035845dec1d3fc2566dd7cf6fda
3,625,187
def carregar_dados_site(): """ Abrindo a lista de portais da transparência e tratando informações que serão tratados como NaN para o pandas. """ return rows.import_from_csv("dados/lista_portais.csv")
44e504a1c3fab96de7ba9628425e1d8118218341
3,625,188
def min_query(): """Convert sentence to query """ return {'hello', 'world', 'of', 'geek'}
98ff87ecc8397c38ecd96eda368153905436a9de
3,625,189
def format_timedelta(days: int = 0, hours: int = 0, minutes: int = 0, seconds: int = 0) -> str: """Returns a simplified string representation of the given timedelta.""" s = '' if days == 0 else f'{days:d}d' if hours > 0: if len(s) > 0: s += ' ' s += f'{hours:...
6414e2be5a01f178d6515ab6f21ea7c5ab4d5004
3,625,190
def create(organisation_id): """Create a new Role.""" form = RoleForm() organisation = Organisation().get(organisation_id=organisation_id) grades = Grade().list(organisation_id=organisation_id) if grades: form.grade.choices = [(grade["id"], grade["name"]) for grade in grades] practices...
23baee090932ddbce47115a44efd932060e144b4
3,625,191
def _try_encode(text, charset): """Attempt to encode using the default charset if none is provided. Should we permit encoding errors?""" if charset: return text.encode(charset) else: return text.encode()
ce418ff0b5e2ee938781fe2074bf146b9ba89447
3,625,192
from typing import Union from typing import Sequence def ones(array_shape: Union[int, Sequence[int]]) -> Array: """Create and fill a shape with ones.""" return full(array_shape, 1.0)
7e85a0078a577ccac75881231962b6fc52a9d20a
3,625,193
import scipy def _fit_curve(fun, x, y, init): """Initial curve fit, without errors.""" fit, cov = scipy.optimize.curve_fit(fun, x, y, p0=init, maxfev=MAX_CURVEFIT_FEV) LOG.info(f"Initial DA fit: {fit} with cov {cov}") return fit, np.sqrt(np.diag(cov))
6809254393eff939f86ccc6c1d19d03e2eb21bc9
3,625,194
def pattern_match(form, token): """ This provides a quick way to extract the contents of a token list, and see if it matches an expected pattern. Variable elements are bound to names in the returned object, to allow for easy retrieval. If the token stream matches: >>> pattern_match(['pointer-t...
133a3b69d49ff1f4d130a04c6ec74640c4dca952
3,625,195
def primalDualSeparable_optimize( prob, K=None, z_0=None, stepsize=None, log_freq=None, log_prefix=None, log_init=True, print_freq=None,): """ Algorithm: Primal-Dual algorithm for separable smooth convex-concave minmax problems of the form g(x, y) = f(x) + <y, Ax> - h(y) [THO]: Lifted Primal-Dual Met...
ab744d0350bdeb4391f191cf60a9e9eb06e782c4
3,625,196
def accuracy(letters, target_string): """ Comparing accuracy to the correct answer. Args: letters(np.array): (num_chars, ) target_string(str) Return: float: accuracy. """ count = 0 assert len(letters) == len(target_string) for i in range(len(target_string)): ...
5898a086997d3b9ff9f9bcf84b747dd553a0e4cb
3,625,197
import array def compute_internal_work_compression(form, force): """Compute the work done by the internal compressive forces of a structure. Parameters ---------- form : FormDiagram The form diagram. force : ForceDiagram The force diagram. Returns ------- float ...
0b5df930369937c7ca9189e892f7a71746396ec1
3,625,199
from typing import Callable import typing import logging import inspect def list_(router_generator) -> Callable: """ list action default using fastapi-pagination to process paginate """ resource = router_generator.cls() action_func = getattr(resource, 'list') # noinspection PyProtectedMember,...
963e6cf6d40da9d0fdd53abf30e171e0a922eae7
3,625,200
def _populate_entity(m): """ """ if not m: return None entity = AuthUserEntity(key=get_key_from_resource_id(m.id)) entity.username = m.username entity.first_name = m.first_name entity.last_name = m.last_name entity.email = m.email return entity
33aa34d0211c99277c83fc2c5e02a080c39c3f35
3,625,202
from typing import List async def cringo_card(list_of_emojis: List[List[str]]) -> List[List[str]]: """This makes the Cringo! card complete with headers.""" top_row = ['🇦', '🇧', '🇨', '🇩', '🇪', '🇫'] side_column = ['<:lemonface:623315737796149257>', '1️⃣', '2️⃣', '3️⃣', '4️⃣', '5️⃣', '6️⃣'] list_...
44421d02c8b9c0b7f873e6d5ad5e8de803ac70d6
3,625,203
def count(object): """ count(object): Count the number of elements in the given object. An element is defined as one of the 7 datatypes supported by ssdf (dict/struct, tuple/list, array, string, int, float, None). """ n = 1 if isstruct(object) or isinstance(object, dict...
00cc1dded43d59210751d955499696cd90bd5bdb
3,625,204
def prepare(desc_file, nocheck_init): """Create and prepare the temporary run directory. The temporary run directory is created with a UUID as its name. Symbolic links are created in the directory to the files and directories specifed to run NEMO. The output of :command:`hg parents` is recorded in ...
3338eaf126910cbf37990d28c9d8eedd0a634230
3,625,205
def get_http_method(query): """Work out if this should be GET, POST, PUT or DELETE""" lower_query = query.strip().lower() http_method = "GET" for method in METHOD_MAP: if method[0] in lower_query: http_method = method[1] break return http_method
e1deabf2f4a5e331fe08936d6afaaee1a02f2b92
3,625,206
def FlowInterestEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
69819eb18842c5094444d19bc4fb94a7d163b09e
3,625,207
import random def lucky_enough(luck=0): """ Check if you lucky enough. :param luck: should be an int between 0-100 :return: Bool """ return random.randint(0, 99) < luck
158179ab5da330561f6d3b7be06697b0b319b1db
3,625,209
def relu(attrs, inputs, proto_obj): """Computes rectified linear function.""" return 'relu', attrs, inputs
d45c7f517c2cef57206db56b1ed7402127e72a01
3,625,210
def remote_empty(draw: st.DataObject) -> TemporaryDirectory: """Create an empty git remote repository.""" root = TemporaryDirectory() _run_helper(args=["init", "--bare"], cwd=root.name) return root
d12acc0b31b0697df53515e1142e39ed61558f60
3,625,212
import re def _reformat_stack(stack): """Post processes the stack trace through _relative_path().""" out = stack.splitlines(True) def replace(l): m = re.match(RE_STACK_TRACE_FILE, l, re.DOTALL) if m: groups = list(m.groups()) groups[1] = _relative_path(groups[1]) return ''.join(groups)...
f3ee98bd9896fc26cdb74bd3c68c0a668af567bb
3,625,213
import logging def check_multiple_insert_param(columns_to_insert, insert_values_dict_lst): """ Checks if the pararmeter passed are of correct order. :param columns_to_insert: :param insert_values_dict_lst: :return: """ column_len = len(columns_to_insert) for row in insert_values_dict_l...
ffb5a4eb595b84a439f3a910d81d699289c1d69a
3,625,215
def KK_RC4(w, Rs, R_values, t_values): """ Kramers-Kronig Function: -RC- Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ return ( Rs + (R_values[0] / (1 + w * 1j * t_values[0])) + (R_values[1] / (1 + w * 1j * t_values[1])) + (R_values[2] / (1...
28a968a4799741cd9cb03f51971fe50cf3d09ce0
3,625,216
def keep_active(useruid: str): """ 試著保持著登入狀態 """ # 取得使用者物件 user = User(useruid) session = get_session(useruid) # 確認登入狀態 if session.active: return True # 嘗試重新登入 try: session.login(user.userid, user.passwd, session.cours...
98399c5e63775265a3c0d67bcc7cf5e40ced06b6
3,625,217
import random import string def random_string(length=16): """Generate a random string of the given length.""" result = "" while len(result) < length: result += random.choice(string.ascii_letters + string.digits) return result
04bf92658ce8d9535aa91c751c5d9f1746827eaf
3,625,218
def getIfacesInZone(zone_ifaces): """ Parse given interfaces for a zone for associating a zone with an interface and set any properties listed to defined values upon fan control starting on the zone. """ ifaces = [] for i in zone_ifaces: iface = {} # Interface name not neede...
040236570a17ea7faf3dd4d839082bfc47ff7337
3,625,219
def calculate_confusion(config, predicted_indices, y_indices): """Helper method that calculates confusion matrix.""" confusion = np.zeros((config.label_size, config.label_size), dtype=np.int32) for i in xrange(len(y_indices)): correct_label = y_indices[i] guessed_label = predicted_indices[i]...
4316587fe9ccc0636878f639a273c2056d19162a
3,625,220
from pathlib import Path def make_surrogates(data, parcellation, scale, spatnull): """ Generates surrogates for `data` using `spatnull` method Parameters ---------- data : (N,) pd.DataFrame parcellation : {'atl-cammoun2012', 'atl-schaefer2018'} scale : str spatnull : {'burt2018', 'bur...
4dbfa59e06e0ff1ec0090f336147b34bde02be01
3,625,221
def add_birth_rate_functions(_tb_model, _input_database, _country_iso3): """ Add crude birth rate function to existing epidemiological model :param _tb_model: EpiModel or StratifiedModel class SUMMER model object to be assigned bcg vaccination coverage functions :param _input_database: sql data...
ea9c13d60c8eb3eeba937598f503fbf15b08db85
3,625,223
def generate_kml_end_str(): """ Generates the footer for a KML file """ kml_str = '</Document>' kml_str += '</kml>' return kml_str
b67ed779e29f0c358a7e76c7662c36a714e50649
3,625,224
def top_ions(df1, df2): """ function to compute the top species, top filename and top species/plant part for each ion Args: df1 = reduced_df, table of with index on sp/part column and features only. df2 = quantitative.csv file, output from MZmine Returns: None """ #compu...
d85146cce080be70519ff67851aff8111d6deb11
3,625,226
from pathlib import Path def get_genome_group(src_loc: Path, config: Config) -> GenomeGroup: """Get the ``GenomeGroup`` based on ``src_loc`` and ``config``. ``Config`` is used to set global filter codes and exclude files on group creation. Args: src_loc: Path, can be directory or file co...
a2060257576d51ee55d22c8739b610bc16fbb64f
3,625,227
def rtl_dashboard(request): """RTL Dashboard page. """ return render(request, "django_sb_admin/sb_admin_rtl_dashboard.html", {"nav_active":"rtl_dashboard"})
1b821aa71d0b0f0839fe4febf06d0e18788650f3
3,625,228
def relationship(flights, planes): """ Here we are having two columns common between flights and planes tables, which are tailnum and year. from above two common fields we consider tailnum column as keys in both the table. In """ print(planes.shape) # (3322, 9) print(planes.tailnum.nuni...
da1f31a4afa1720caeb01fc4bbec445999da4f56
3,625,229
def numpy_unpad(x, pad_width): """Unpad an array. Args: x (numpy.ndarray): array to unpad pad_width (tuple): padding Returns: numpy.ndarray """ slices = [] for c in pad_width: e = None if c[1] == 0 else -c[1] slices.append(slice(c[0], e)) return x[tu...
31f41a7a741d7efa870670c95a8acf8be365975a
3,625,230
def linear(a, b, c): """exec a * b + c""" print('exec linear') ret = a * b + c print('linear: %s * %s + %s = %s' % (a, b, c, ret)) return ret
fc5c1c99bd03f61e5f8fd87d4d1863002469c57d
3,625,231
import json def start(): """start goal""" print("/start <- ") print(request.get_json()) goal_id = request.get_json()['goal_id'] resDB = db.start(goal_id) jsonResult = { "result" : resDB } resJson = json.dumps(jsonResult) print("/start -> ") print(resJson) return r...
a917baf7c352540d87e17d01421e50249d8e33e5
3,625,232
import warnings def get_eer_values(fmr, fnmr): """Returns the value of the Equal Error Rate Equal Error Rate (EER): is the point where FNMR(t) = FMR(t). In practice the score distribution are not continuous so and interval is returned instead. The EER value will be set as the midpoint of this int...
b6242b38a2031c655f17c46e38b0bfd2b0ff897f
3,625,233
def validate_spec(index, spec): """ Validate the value for a parameter specialization. This validator ensures that the value is hashable and not None. Parameters ---------- index : int The integer index of the parameter being specialized. spec : object The parameter specializa...
3612d927ef7e61613e0991ffc04ea76555d1b115
3,625,234
import ctypes def ENgetflowunits(): """Retrieves a code number indicating the units used to express all flow rates.""" j= ctypes.c_int() ierr= _lib.ENgetflowunits(ctypes.byref(j)) if ierr!=0: raise ENtoolkitError(ierr) return j.value
41bdaa84d2e14a3ba63b9d42e8b790be196d5499
3,625,235