content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def flavor_create(context, values, projects=None): """Create a new instance type. In order to pass in extra specs, the values dict should contain a 'extra_specs' key/value pair: {'extra_specs' : {'k1': 'v1', 'k2': 'v2', ...}} """ specs = values.get('extra_specs') specs_refs = [] if specs: ...
0250bd710c182a99dd270c535b90688062db5734
3,625,100
from typing import Any def dictlike(var: Any) -> Boolean: """ Determine whether or not var is dict-like (Can contain dict-like items). :param var: Any variable to check :return: Boolean """ try: var.items() return True except (TypeError, AttributeError): return False
5e2a16c4f76112892556de840d4ff8821f98aedd
3,625,101
def plot_vehicle_tri(ax, coords, yaw, color=(0, 0, 1, 0.5), zorder=None): """Plot a marker representing a vehicle (either ground truth or estimate)""" vertices = [ [0, 0], [0.77, -0.5], [0, 0.5], [-0.77, -0.5] ] tri = patches.Polygon( vertices, closed=True, fa...
5adc6da320972630aa4277ca49525cc615568464
3,625,102
def PatchDword(ea, value): """ Change value of a double word @param ea: linear address @param value: new value of the double word @return: 1 if successful, 0 if not """ return idaapi.patch_long(ea, value)
4ed7fee3fae16d0026f616bd725db60341652f77
3,625,103
import os def vgg16_mura_model(path): """Get a vgg16 model. The model can classify bone X-rays into three categories: wrist, shoulder and elbow. Args: path: A string, if there's no model in the path, it will download the weights automatically. Return: A t...
daa494d88e581d8b4008514bfbcd2abc525f5291
3,625,104
import re def _addquotes(vistr: str) -> str: """Add quotes to '=attribute' attributes""" vistr = re.subn(r'=(?!")(.*?)([\s>])', _quote, vistr)[0] return vistr
63ebe29ef8d78450fc8592646f8042710c78371c
3,625,105
from typing import Dict from typing import Any from typing import Iterable import json import os import subprocess import traceback def application( environ: Dict[str, Any], start_response: 'StartResponse' ) -> Iterable[bytes]: """The entry point of this WSGI app.""" try: body = "OK" ...
39d6dcc55729a69efb7a0895a57a84dc971b21ef
3,625,106
from typing import List def readFile(filename: str) -> List[str]: """ Reads a file and returns a list of the data """ try: with open(filename, "r") as fp: return fp.readlines() except: raise Exception(f"Failed to open {filename}")
a5817ab563b83d5cf4999290d10a14a0b68954b6
3,625,107
def calculate_residuals(df, fit, names): """Calculates residuals values by comparing values in df and in fit. Arguments: df (pandas.DataFrame): Holds the data to be fitted. Either concentrations vs time or charge passed vs time depending on the situation. fit (numpy.nda...
5b597dd8ff83241993bee8cae27e6f85c43b1959
3,625,108
def ted(): """ When A POST request with json data is made to this uri, Read the example from the json, predict probability and send it with a response """ # Get decision score for our example that came with the request data = flask.request.json print(data) X = data#["example"]) #...
11a20ecb7ba60d3debea53cf5b52b76454436c32
3,625,109
import yaml def yaml_load(source, loader=yaml.Loader): """ Wrap PyYaml's loader so we can extend it to suit our needs. Load all strings as unicode: http://stackoverflow.com/a/2967461/3609487. """ def construct_yaml_str(self, node): """Override the default string handling function to alwa...
dbf8f52b159b1f563322a1474a4a14733b741143
3,625,110
def _item_to_instance(iterator, instance_pb): """Convert an instance protobuf to the native object. :type iterator: :class:`~google.api_core.page_iterator.Iterator` :param iterator: The iterator that is currently in use. :type instance_pb: :class:`~google.spanner.admin.instance.v1.Instance` :param...
75fceba9caec7fa37d2ef674dca2296a71b4532f
3,625,111
from cube import MoveError import os import time def speedsolve(self) -> dict: """ Solve the cube as fast as you can and give statistics on solve. The cube is scrambled with the default method, and will start timing once the first turn is made, or once 15 seconds (inspection) is reached. Ent...
6e04c325ba1e21dff9bd727746efd642d121128b
3,625,112
def get_trunc_hour_time(obstime): """Truncate obstime to nearest hour""" return((int(obstime)/3600) * 3600)
8379aafc76c1987f537ea294c7def73ad32f1b23
3,625,113
import re def normalize_package_name(python_package_name): """ Normalize Python package name to be used as Debian package name. :param python_package_name: The name of a Python package as found on PyPI (a string). :returns: The normalized name (a string). >>> from py2deb impor...
47a850c601e64b570470a339769742d8f3732e28
3,625,114
def resolve_all(x): """Recursively resolves the given object and all the internals. Make sure there is no indirect reference within the nested object. This procedure might be slow. """ while isinstance(x, PDFObjRef): x = x.resolve() if isinstance(x, list): x = [ resolve_all(...
28e3903b679f842fd8f104780ddb08379f65cfaf
3,625,115
def logout(): """View of logout""" logout_user() flash('Administrator Logged out') return redirect(url_for('main.index'))
85b8df3f281641b823d7a6765316832f96f5202e
3,625,116
import tqdm def create_data_language( text, vocabulary, window_size=2, fill_strategy="zeros", verbose=False ): """Create a supervised dataset for the characte/-lever language model. Parameters ---------- text : str Some text. vocabulary : list Unique list of supported characte...
2da866ac637d4658c17e69d722c8a9db52987983
3,625,117
import dateutil def format_datetime(value, datetime_format="medium"): """Converts a datetime str to a format that is understood by the db. Args: value: A str representing a datetime datetime_format: A str representing the desired format of the returned datetime, accepted values ar...
f526ddf89f030b66aa7e2567b1cc301c98100096
3,625,118
import csv def getDialect(filename): """Get the dialect of the given csv file.""" with open(filename, 'rb') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024)) return dialect
0169c9058a46ba265768ef405cd525cc2d1a132b
3,625,119
def sort_list(source, target): """ This function is used to sort the source and target list on the basis of key found in the source and target list. :param source: :param target: :return: """ # Check the above keys are exist in the dictionary if len(source) > 0: tmp_key = is_...
3344f83e21e31c1cf3145e1ba5334bc9a0d5216b
3,625,120
def get_audio_source(input=None, **kwargs): """ Create and return an AudioSource from input. Parameters ---------- input : str, bytes, "-" or None (default) source to read audio data from. If `str`, it should be a path to a valid audio file. If `bytes`, it is used as raw audio data....
e046b79bd9bafd2c8a23614834dc1533e0ceb3da
3,625,121
def delete_prtg_device(prtg_single_device_obj): """ deletes the host at PRTG WITHOUT confirmation """ result = prtg_single_device_obj.delete(confirm=False) return result
4cb9b2a35294f0c56a62a7dbd220ab2ada81a15d
3,625,122
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
import os import tempfile def _select_given_names(work_dir,infile,translist,remove=True): """ select names by list """ cdo=Cdo() tmplist=[] if not (os.path.exists(work_dir + os.sep + "temp")): os.makedirs(work_dir + os.sep + "temp") for element in translist: tmpfile=work_dir...
ab98b0fd4ee3c66b0f6eb5475e65b7756c03e377
3,625,138
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
def sidak_correction(significance, numtests): """ Sidak correction. TODO: docstring - better explanaition Parameters ---------- significance : float Significance of each individual test. numtests : int The number of hypothesis tests performed. Returns ------- ...
935480d0294c176d67811afb29061ca93b644303
3,625,141
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
import os def GetExecutable(executable, location=None): """Returns the path to the given executable or None if it is not found. This algorithm provides a reasonably accurate determination of whether or not the given executable is on the machine and can be used without knowing its full path. An optional path...
1b4e695e683a81400798cc11c82e0821358a7ccc
3,625,152
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
import os import sys import traceback def validate_config(config, check_with_data): """ Check that the config passed as argument is a valid configuration. :param config: A config dictionary to fetch. :param check_with_data: Whether we should use the available OpenData to check the config valu...
1494fb0ba5c0a5ba7f209d98be43e1d8cf179717
3,625,154
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
def _create_debug_sp_tpls_data(sp, tpls, gap_threshold): """Preprocess sp and tpls for "test_generate_trips_*.""" # create table with relevant information from triplegs and staypoints. tpls["type"] = "tripleg" sp["type"] = "staypoint" sp_tpls = sp[ ["started_at", "finished_at", "user_id", "t...
937896ea03b09a2bff07d3af19e97d316dccc4d1
3,625,167
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 wavelet_analysis(signal, p_exp=None, wt_name='db3', j1=1, j2=10, gamint=0.0, normalization=1, weighted=True): # TODO make function for coef only, use it when p_exp is None """ Compute wavelet coefficient and wavelet leaders. Parameters ---------- signal : ndarray, shap...
e1237095c1f0e7878bf2b267868f0c99cbfe60ed
3,625,174
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 os def _lint(definition_filename: str) -> bool: """Lints the provided job definition file.""" if not os.path.isfile(_YAMLLINT_FILE): print(f"! The yamllint file ({_YAMLLINT_FILE}) is missing") return False with open(definition_filename, "rt", encoding="UTF-8") as definition_file: ...
adbc1473e5526e344ec1a2dbed7593e9b29beda6
3,625,198
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