content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def links_detail(request): """ Links list """ links = Link.objects.all() links_json = serializers.serialize('json', links) return render( request, 'link_detail.html', context={ 'links': links_json })
2bb3726f5b7cee784c1e5543d62dbb3a40820789
65,167
def secretary(request): """ Renders the secretary page giving access to excuses and ChapterEvents """ print utils.verify_secretary(request.user) if not utils.verify_secretary(request.user): messages.error(request, "Secretary Access Denied!") return HttpResponseRedirect(reverse('dashboard:hom...
bde9f4720de97c68cacf013526718693c2511961
65,168
def process_noise(pulses, noise_list, dims, t1=None, t2=None, device_noise=False): """ Apply noise to the input list of pulses. It does not modify the input pulse, but return a new one containing the noise. Parameters ---------- pulses: list of :class:`qutip.qip.Pulse` ...
c5ffafd096fcbaeed59addf6e2388e5ce5cb48eb
65,169
def ensure_user_access(model: models.Model, pk: int, user): """ensure user has access to specified model""" if model is None: return None return get_object_or_404(model, pk=pk, user=user)
49346035358ceb0a24b46eacc2a3ceb0b47421e1
65,170
def init_region(conf, region=None): """ Initialize the caching module. """ cache_region = make_region(function_key_generator=keygen_function) kwargs = dict( (k, conf[k]) for k in ("arguments", "expiration_time") if k in conf) cache_region.configure(conf["backend"], **kwargs) ...
51a9df1669c29dbff4d511faca22248167c72012
65,171
import calendar from datetime import datetime def get_month_start_end(dt): """ Returns the first and last day of the month for the specified date. :param dt: :return: """ month_range = calendar.monthrange(dt.year, dt.month) month_start = pd.to_datetime(datetime( dt.year, dt.month,...
096211697617da95a025ef6fd1047872249717d5
65,172
import re def get_found_exceptions(text, to_lower=False): """Extract exception and errors from logs""" unique_exceptions = set() found_exceptions = [] for word in split_words(text, to_lower=to_lower): for key_word in ["error", "exception", "failure"]: if re.search(r"[^\s]{3,}%s(\s|...
bdf6b460eec646f0d6ae320332338a5ae25ef32f
65,173
def peak_intensity(P,radius): """For Gaussian beams, the peak intensity is 2x that of a flat top. I.e.: P/((pi*radius**2)/2). Power is in W, radius in m. Returns W/cm**2 """ w = radius*100 #convert from m to cm return P/((np.pi*w**2)/2)
d1bb8362c31115f52ac3e1f163308be3aa0905be
65,174
def factRecursive(k): """factorial value from recursive algorithm""" if k == 0: return 1 else: return k*factorial(k-1)
aa45a772a01e269fa042eee5c624486f71ed2bcd
65,175
def expand_node(tree, path, plane): """Splits a `tree` at the node given by `path` using `plane`. Returns a copy of the original tree but with the split node :param tree: tree to split :type tree: `bsp_tree.BSPTree` :param path: path pointing to the node to split :type path: tuple :param pl...
4cf03ba1aa6fccac5cdb794df4aa800f8a937adf
65,176
def fs_write(obj, file_path): """ Convenience function to write an Object to a FilePath Args: obj (varies): The Object to write out file_path (str): The Full path including filename to write to Returns: The object that was written """ try: with open(str(file_path), 'w')...
c94db2399283a26529bf4416f5b05a93fafb4e07
65,177
def find_max_locs(df): """Find iloc location of maximum values in pd.DataFrame""" num_df = df.apply(pd.to_numeric, errors='coerce').values row_max = num_df.max(axis=1) ij_max = [] for i, i_max in enumerate(row_max): if np.isnan(i_max): # ignore nan values continue for j...
7fdca73a2a75566771ccc068000199a2896fe662
65,178
import re def handle_line(fname, state, lines, linenum, line, app_state): """Parse, process and replace a single line in a list of lines.""" # skip comments if re.match(r"^ *#", line): return "n" # skip function decorators that are inline, these are too hard elif re.match(r"^ *@", line):...
37f32398412196ad57719689ccdd4f697c824afd
65,179
from datetime import datetime def utcnow(): """Quick UTC Now for default purposes""" return datetime.utcnow().replace(tzinfo=bson.utc)
e950f5416de2f0d4688eeb00ffaf809fa4ce5f64
65,180
def mock_results(methods, swallow_not_found=False): """Mock API methods more easily. :type methods: dict :param methods: A dictionary containing one callable for each API method. :type swallow_not_found: bool :param swallow_not_found: Whether to return {'result': {}} on unmocked API method...
63653995518f725359c1805b8ba78d3830dcdf7a
65,181
def check_string(arg, allow_none=False, message='Argument "%(string)s" of type %(actual)s is not a string', level=1): """ >>> check_string([1, 2, 3]) Traceback (most recent call last): ... AssertionError: Argument "[1, 2, 3]" of type <class 'list'> is not a string >>> check_string(3) Tra...
bc3a2e2ed6d756c18867a92ca475c6f3dcf488a6
65,182
def complex_dot_pattern(kind_num=3, whole_repeat=2, fg_color=np.array([1.0, 1.0, 1.0]), bg_color=np.array([0.15, 0.15, 0.15])): """ dot pattern 作る。 Parameters ---------- kind_num : integer 作成するドットサイズの種類。 例えば、kind_num=3 ならば、1dot, 2dot, ...
1b36b21dc7f63da3ec4e696feb1091fcdcac10a8
65,183
def get_task_category(request): """ @summary 获取所有模板分类列表 :param request: :return: """ groups = [] for category in TASK_CATEGORY: groups.append({ 'value': category[0], 'name': category[1], }) return JsonResponse({'result': True, 'data': groups})
b37980a67d05a6f34df1d99ed2ca5658dd58454e
65,184
def preprocess_once(set_x, set_y, gray_scale=True, dist_ratio=3.8/4.0): """ This method detects the face in the gray-scale (if user wants) and detects a bounding box around the face using the keypoints. It is done once for all the dataset, at the beginning of training. Parameters: ----------- ...
644a19efb1bff13d634e8f8283658bb0585aa3fe
65,185
def get_raster_data(fp): """Get the digital number of the raster file. Parameters ---------- fp: str File path of the raster file. Returns ------- data : ndarray Digital number of the raster file whose shape will be (rows, cols, bnads). Examples -------- >>> im...
040d01453cbff02d1285b8b72f1e10bcc94976c9
65,186
def login(request): """ 测试账户 mark mark1234 :param request: :return: """ if request.method == 'POST': response = {'user': None, 'msg': None} input_user = request.POST.get('user') pwd = request.POST.get('pwd') valid_code = request.POST.get('valid_code') ...
889c7b691c712c77c7d655dae3ed05f1695e01cd
65,187
def snake_dict_to_camel_dict(snake_dict, capitalize_first=False): """ Perhaps unexpectedly, snake_dict_to_camel_dict returns dromedaryCase rather than true CamelCase. Passing capitalize_first=True returns CamelCase. The default remains False as that was the original implementation """ def camel...
d20ce57f25a417286427ea08d58fd23e473b035e
65,188
import typing import pathlib def from_python( filepath: typing.Union[str, pathlib.Path, typing.IO[bytes]] ) -> typing.Union[Categorization, HierarchicalCategorization]: """Read Categorization or HierarchicalCategorization from a python cache file. Note that this executes the python cache file. Only load ...
d746c19eddbba1062b996621f2b5693f8bfa3d9f
65,189
def createTriangle(vertices, resolution = 1): """ Creates a staircase triangle with an array of small pillars. coordinates given should form a right angled triangle with two sides parallel to grid axes. Arguments:- vertices (list): List of cartesian coordinates of vertices of triangle resolution (int): Smalle...
3ec56369d0d5c015862c36b21a5a0da7e7195b1e
65,190
import json def get_json(inp_dict): """Converts a given dictionary to prettified JSON string. Parameters ---------- inp_dict: map Input dictionary to be converted to JSON. Returns ------- Prettified JSON string """ return json.dumps(inp_dict, indent=4)
9404064536a12595fe9b601363eee07b09a97bc8
65,191
def feature_vecs_DOC(train_pos, train_neg, test_pos, test_neg): """ Returns the feature vectors for all text in the train and test datasets. """ # Doc2Vec requires LabeledSentence objects as input. # Turn the datasets from lists of words to lists of LabeledSentence objects. labeled_train_pos=[] ...
3f5161b157d2f8248f9b3ceea708cf5b13da0d1c
65,192
def trimf(x, abc): """ Triangular membership function generator. Parameters ---------- x : 1d array Independent variable. abc : 1d array, length 3 Three-element vector controlling shape of triangular function. Requires a <= b <= c. Returns ------- y : 1d arr...
33b0d215274885c51fd61d342953a9be39545da8
65,193
import torch def mul_edge_softmax(graph, edge_val): """ Returns: Softmax values of multi-dimension edge values. shape: [E, H] """ csr_edge_softmax = CONFIGS["csr_edge_softmax"] if csr_edge_softmax is not None and edge_val.device.type != "cpu": val = csr_edge_softmax(graph.row_indpt...
dfedc4895defd4d5525882d7b4502e1521c4437d
65,194
from typing import Union from typing import List def get_online_retail_dataset( number_of_documents: Union[None, int] = 1000, select_fields: list = [] ) -> List: """ Download an example online retail dataset from UCI machine learning \n Total Len: 541909 \n Sample document: >>> {'Country': '...
d330b434b2997f53f7ccf8effe90a2304586d00d
65,195
def build_compound_annotation_df( pset_dict: dict, column_dict: dict={'compound_id': str, 'smiles': str, 'inchikey': str, 'pubchem': str, 'FDA': bool}, rename_dict: dict={'rownames': 'compound_id', 'cid': 'pubchem', 'FDA': 'fda_status'} ) -> pd.DataFrame: """ Build a table mapp...
8779241f605a36bcd37b31022166c56c9d373f15
65,196
from datetime import datetime def parse_matches(patient_id, match_objs): """Parse a list of matchmaker matches objects and returns a readable list of matches to display in matchmaker matches view. Args: patient_id(str): id of a mme patient match_objs(list): list of match objs returned ...
2404de0e238269f1f4a1b6fe32143093494c1cb2
65,197
def message_url_path(course_key, access_point): """Determine the URL path for the message explaining why the user was blocked. This is configured per-course. See `RestrictedCourse` in the `embargo.models` module for more details. Arguments: course_key (CourseKey): The location of the course. ...
7da091b791f55186f6cbffdd5bdc88b0bb852c44
65,198
def is_discard_class(outter_key, inner_key) -> None: """Prints discard class""" values = {} if outter_key == "discard-class": values['discard_class'] = ', '.join(is_instance(inner_key.get('discard-class', {}))) return values
9446ff5d448fd45d009365d90eaec2cabf382b4e
65,199
def objectify(value): """converts almost anything to an Obj()""" if isinstance(value, Obj): return value if hasattr(value, '__float__'): return float(value) if hasattr(value, '__dict__'): value = value.__dict__ if isinstance(value, dict): value = Obj(value) elif i...
5ccb93af73cac891b7a2c92988f432095f026839
65,200
import re def find_IMGT_alignment(filename, HLAtyping, header_line = 8): """ Find the aligned sequence from the database file """ # Read alignment file alignment_list = IMGTdbIO.read_IMGT_alignment(filename, header_line) HLAtyping_pattern = re.compile(re.escape(HLAtyping)) ## pattern - f...
23045feb406d25d00b7ae14325acbc5c9e3a598b
65,204
def rbc_intersects(rbc, rbcs, max_overlap): """Check if `rbc` intersects any rbc in `rbcs`""" if len(rbcs) == 0: return False rs = np.array([x.radius for x in rbcs]) pos = np.array([x.position for x in rbcs]) dists = (((rbc.position - pos))**2).sum(axis=1) ** 0.5 overlaps = linear_spher...
2a39df42188c16089d08b417feb853ba6d4063a8
65,205
import MySQLdb def getCurrentDimm(): """ Return current DIMM measurement """ cnx = MySQLdb.connect(host='eeva',user='select_user',passwd='select_pass',db='SiteData') cursor = cnx.cursor() cursor.execute("""SELECT AVG((fwhmhorl+fwhmvert+fwhmverl)/3) FROM RoboDimmING WHERE DateTi...
b72562dafc490f2165390251da784eb57f839e92
65,206
def grad_eigh(w, v, vg): """Gradient for eigenvalues and vectors of a symmetric matrix. Parameters ---------- w: eigenvalues v: eigenvectors vg: adjoint eigenvectors """ vc = v # real N = 3 # wg, vg = g # Gradient w.r.t. eigenvalues, eigenvectors. w_repeated = np...
9dcdda89efcb84a88ef3b6501091412fbd06b33e
65,207
def _confusion_matrix(y_true, y_pred): """Creates a confusion matrix.""" cm = np.zeros((10, 10)) for true_digit in range(10): y_pred_digit = y_pred[y_true == true_digit] digits, counts = np.unique(y_pred_digit, return_counts=True) for digit, count in zip(digits, counts): ...
32129d162f3a8196e3b658ab818b2b45316b216c
65,209
from datetime import datetime def get_next_market_open_hours(market='XNYS'): """Get next market open hours. Default market is NYSE for US market hours.""" today_market_open_dict = rs.markets.get_market_today_hours(market=market) current_time = parser.parse(datetime.now(timezone.utc).isoformat()) if to...
e380cec0caa48ddda09d1e5901d217b879f235ef
65,210
import math def increase_worth_reporting(value, new_value=None, *, total=None): """ Make reporting sparser and sparser as values grow larger - report every 1.1**N or so - if we know total, report every percent """ if new_value is None: new_value = value value = new_value - 1 if...
7bb1577f5e73e91ea2e6a46af8db0e74386984cb
65,211
def find_flowline_in_list(aFlowline_in, pFlowline_in): """[find the index of a flowline in a list] Args: aFlowline_in ([type]): [description] pFlowline_in ([type]): [description] Returns: [type]: [description] """ iFlag_exist = 0 lIndex= -1 nFlowline= len(aFlowline_...
4cec86e218f3bab9e4ac73510d908f7fe8271830
65,212
def decov_loss(xs): """Decov loss as described in https://arxiv.org/pdf/1511.06068.pdf 'Reducing Overfitting In Deep Networks by Decorrelating Representation' """ x = tf.reshape(xs, [int(xs.get_shape()[0]), -1]) m = tf.reduce_mean(x, 0, True) z = tf.expand_dims(x-m, 2) corr = tf.reduce_mean(...
c1c58a84f56760a6fb434deca8a764aeebd4603e
65,213
def verify_interface_protocol(device, interface, expected_protocol, invert=False, max_time=60, check_interval=10): """ Verify protocol shown via show interfaces te...
af05814dcc7b8e6a7f7e364dfc27c20bee483c3a
65,214
from typing import Tuple from typing import Dict def calc_stats_around_peak(time: np.ndarray, signal: np.ndarray, peak_bounds: Tuple[int], valley_rel: float = 0.05, time_scale: float = TIME_SCALE, ...
6e937b3ecedddca42e0e350ca433f71a427b248e
65,215
def create_one_hots_from_labels(labels, n_classes): """ Create one-hot vector from the class label distribution. self.one_hots -> np.array([[0,0,1,0], [0,1,0,0], [0,0,0,1], ... ,[0,1,0,0]]) """ length = len(labels) one_hots = np.zeros((length, n_classes), dtype=float) one_hots[(np.arange(len...
8cd94dacc6b38c4a11378f88f5159f72b4580ec3
65,216
def TPrsStd_ConstraintTools_ComputePlacement(*args): """ :param aConst: :type aConst: Handle_TDataXtd_Constraint & :param anAIS: :type anAIS: Handle_AIS_InteractiveObject & :rtype: void """ return _TPrsStd.TPrsStd_ConstraintTools_ComputePlacement(*args)
2e9af45fe4e7289afa3916c91ad23c980207cd71
65,217
from typing import Dict from typing import List import logging def process_clean( data: Dict[str, List[Dict[str, str]]], *, save_pickle=False ) -> Dict[str, pd.DataFrame]: """ Takes a dict with values representing types of data (cases, deaths, tests...). Each value is a list of ordered dictionaries co...
71a80c76e4894a4ccc84158c924d2a5a132bfb62
65,218
def login(): """Login a user.""" form = LoginForm() if form.validate_on_submit(): user = db_session.query(User).filter_by(username=form.username.data).first() if user is None or user.password != form.password.data: user = db_session.query(User).filter_by(email=form.username.data...
4646f36f9ac68e0c8bb3ca9887c75cc0d7e32a7c
65,219
def getConfig(config, key): """ 获取指定key的配置【NC】 :param key: :return: """ return config[key]
cf53e746a5004705b8265024c1ac884fc9c6adce
65,220
import re def explode(collapsed): """Explode collapsed references like 'C1-C3,C7,C10-C13' into [C1,C2,C3,C7,C10,C11,C12,C13]. Args: collapsed (string): String of collapsed references. Returns: list: list of reference strings. """ if collapsed == "": return [] indivi...
1f837c1538a2feda2cfe6a4b4023db20c456f338
65,221
from typing import List from typing import Optional def get_domain_index(query: str, domains: List[Domain]) -> Optional[int]: """Finds the earliest index of a domain in a list of domains, if present.""" for index, domain in enumerate(domains): if query == domain.type: return index retu...
dd10361407d5e8338668406abe5f478be956cc7a
65,222
import calendar def month_delta(date, months): """Add or subtract months from date.""" day = date.day # subtract one because months are not zero-based month = date.month + months - 1 year = date.year + month // 12 # now add it back month = month % 12 + 1 days_in_month = calendar.monthr...
afa064af13c67be776a7f01ce48fc6ed2f33f581
65,223
def flat(num_samples, **kwargs): """ method to run a sampling for a flat distribution IN: num_samples : number of samples to be returned x (float) : The flat value for sampling OUT: a list of num_samples zeros """ x = kwargs['x'] return np.ones(num_samples) * x
30e7fae9623b0ca82629618e014bf073a89ae896
65,224
def patch(img, gt_boxes, gt_landmarks): """Generating random patch and adjusting image and ground truth objects to this patch. After this operation some of the ground truth boxes / objects could be removed from the image. However, these objects are not excluded from the output, only the coordinates are chan...
d1dac57c210dc76c0585003c939297e0a5c865ec
65,225
from typing import Any def detect_flow_directions(exprs): """ Return a mapper from Dimensions to Iterables of IterationDirections representing the theoretically necessary directions to evaluate ``exprs`` so that the information "naturally flows" from an iteration to another. """ exprs = as...
a6dff9a6a5c19265c3a098a0802e2f8688bb4d3d
65,226
def get_config(workflow: "Workflow") -> DictNone: """Returns the compose-flow project config file By default, this will check for a compose-flow file in compose/ with the same name as the project name, e.g. compose/compose-flow.my-project.yml. when a file with the same name as the project is not found...
c71d87a1e7aa7209322c819ba4a4e1f9c2921188
65,227
def private_vars_at_toplevel(abstract_syntax_tree): """Check that private variables defined at the top level are used later.""" errors = [] variables_set = find_all.toplevel_set_private_vars(abstract_syntax_tree) def _not_in_variables_set(node): """Return false if in variables_set.""" ...
8f495e1bfb991c5c5dd4b00e2d6c082635151a65
65,228
async def format_stats(color: str, equip: str): """Formats stats to create a uniform message block. Args: color (str): color of the gem equip (str): the equip slot to use Returns: str: a formatted message with all values and stats """ for stat, stat_values in values[color]...
248690a81dba350a19b6b94092cddce54b5b7e65
65,231
def select_rimed_node(data_cont): """select the rimed nodes from a peaktree data container The nodes are filtered by the rule: ``abs(n['v'][0]-n['v'][-1]) > 1.5`` Args: data_cont: peakTree data container Returns: data_container with selected indices in ``var`` of shape ``(time, ran...
1b6e2dffed07ec54244c67cb9c711f7470d9340f
65,232
def immediateload(*keys): """Return a ``MapperOption`` that will convert the property of the given name or series of mapped attributes into an immediate load. The "immediate" load means the attribute will be fetched with a separate SELECT statement per parent in the same way as lazy loading -...
f57805d0417e546dcfb12292dfe07e951a8a5f4a
65,233
def get_best_worst_cost(petri_net, initial_marking, final_marking, parameters=None): """ Gets the best worst cost of an alignment Parameters ----------- petri_net Petri net initial_marking Initial marking final_marking Final marking Returns ----------- b...
e52838e654b8f35173062d1b3f1a042a2f8f1da5
65,234
def get_vat(env: GymEnv) -> np.ndarray: """ Checks whether gym env exposes a method returning valid action trees :param env: the Gym environment to get masks from :return: A numpy array of the masks """ if isinstance(env, VecEnv): return np.stack(env.env_method(EXPECTED_METHOD_NAME)) ...
e399462b31b3548f2c5a61074d6cbc9897479444
65,235
def animate_line(data, animate_over='t', animate=True, vmin=None, vmax=None, fps=10, save_as=None, sep_pos=None, ax=None, controls=True, **kwargs): """ Plots a line plot which is animated with time. Currently only supports 1D+1 data, which it plots with animatplot's Line a...
4311ea0916f8101056ddead4c259525e9e3ea129
65,236
from typing import Dict def spike_count(data: Dict[int, np.ndarray]) -> int: """ Count the number of total spikes emitted by the neural network in the data. :param data: A dictionary keyed by neuron ID and valued by a numpy array of spike times. :return: The number of spikes. """ num_...
b49a3f2fc75d0a90e1caff4bd49a4c1dfde84a79
65,237
from io import StringIO import re def dqstring2bracestring(dq): """!Converts a bash-style double quote string to a tripple brace string. @param dq The bash-style double quote string, minus the surrounding double quotes.""" output=StringIO.StringIO() for m in re.finditer(r'''(?xs) ( ...
7412d29cd6f4b0c45f503b94abf860f5a94bae19
65,238
def get_attribute(obj, key): """ Get an attribute from an object, regardless of whether it is a dict or an object """ if not isinstance(obj, dict): return getattr(obj, key) return obj[key]
bb20ac5809cf89b8043ff1fc60b9e4775ca95d18
65,239
def make_encoder_layer(inc, outc): """ makes complex encoder layers Parameters ---------- inc: int number of input channel(s) outc: int number of output channel(s) Returns ------- Sequential a sequential neural net consisting a convolution layer, batch normal...
7446ad79a4e956f900873adad72b9054fc498f03
65,240
def m2q(m): """Convert rotation matrix into SPICE quaternion. Parameters ---------- m: np.array 3x3 rotation matrix. Returns ------- np.array SPICE quaternion. Raises ------ ValueError If the rotation matrix does not contains 9 elements. ValueError ...
56602dc92761eaf60ced5ba9003a32a9a8eacfe9
65,241
import requests import time def getData(base, path, parms=None): """ this is a general-purpose query helper """ u = base + path try: r = requests.get(u, timeout=3, params=parms) # print(r.url) except requests.Timeout: print(f"{time.asctime()}: Timeout fetching {u} {parms}") ...
42d6271422c112b6ebf2469d340ae46ebb5a95e4
65,242
def GetMatchingServices(all_services, args_services): """Return a list of services to act on based on user arguments. Args: all_services: list of Services representing all services in the project. args_services: list of string, service IDs to filter for, from arguments given by the user to the comman...
b781f6e147d16778b4fd1085b4283c8a5cb0b451
65,243
def tokenize(text): """Tokenize text into words and keep only some words.""" words = nltk.word_tokenize(text) return list(set([word for word in words if len(word) > 1 and not word in english_stopwords and not (word.isnumeric() and len(word) is n...
9109b319bc446d83b6fce0e3dd29c919acaf9c64
65,244
from web.apps.vibora_app import ViboraApplication from vibora import Request, Response def vibora_app(port): """ With logging """ app = ViboraApplication() class AsyncHandler(Handler): async def __call__(self, request: Request) -> Response: return super().__call__(request...
ec8fc6f879911a4d92c3887a355ecc82081c5a52
65,245
def sales_product(): """ Monthly sales of a plastic manufacturer's product, Jan 2001 - May 2012 """ return _get_df_from_file("monthly-sales-of-product-a-for-a.csv")
ff812d947940d771abd5d8ad9af833176b6800c0
65,246
def make_blueprint(db_connection_string=None): """Create blueprint. """ controllers = Controllers(db_connection_string) # Create instance blueprint = Blueprint('taxonomies', 'taxonomies') # Controller Proxies @check_permission([Permissions.taxonomyRead]) def query_taxonomies_(): ...
d16e929dfe0790db764c727cca4cab2ad80c3144
65,248
from typing import List from typing import Tuple def make_mask_ternary(mask): """ Takes 0/1 mask and makes -1/0/1 mask, setting 0 to -1, and those -1, which are far away from 1 to 0 (so we do not look at them) """ useless_cells:List[Tuple[int, int]] = [] for i in range(mask.shape[0]): ...
90518f1db10961c7cb1e0647d491a47786b6caba
65,249
def api_token_required(func): """Ensure the request is authenticated via API token.""" @wraps(func) def wrapper(*args, **kwargs): api_token = _find_valid_api_token() if api_token is None: www_authenticate = WWWAuthenticate('Bearer') abort(401, www_authenticate=www_a...
4b7561efec212d28cdb11575034d29f4b2c0d94f
65,250
from datetime import datetime def lease(queue_name, owner, count=1, timeout_seconds=60): """Leases a work item from a queue, usually the oldest task available. Args: queue_name: Name of the queue to lease work from. owner: Who or what is leasing the task. count: Lease up to this many ...
0b01ad2f4871c89073de8b17ef637033bd587f5c
65,251
import html def display_current_user_message(page): """Displays current user message Arguments: page (obj): Page content Returns: str: Welcoming message """ if page and current_user.is_authenticated: return html.Div( children=["Welcome " + current_user.userna...
24090ab8530fe0dcab05905ec3dfb18b5c22ef38
65,252
def get_time_range_for_smoothing(user_id): # type: (uuid.UUID) -> emission.storage.timeseries.timequery.TimeQuery # Returns the time range for the trips that have not yet been converted into sections. # Note that this is a query against the trip database, so we cannot search using the # "write_ts" query...
7ba44c569ba04e7aa1e1cf5e58cf1873396de0d4
65,254
import math def check_anomaly(day_data_tuple): """ Find mean, std, and maximum values for the day. Using a single pass (online) mean/std algorithm allows us to only read through the day's data once. Note: M2 = 2nd moment, variance day_data is an iterable, returned from groupby, and we reque...
50cf3820a8839584aafefaba1e3219dbdf6a24d0
65,255
import joblib def generate_data( constants: SimDataGenConfig, run_idx: int = 0, return_raw: bool = True ): """ Generate a training and testing dataset of idealised disease treatment. """ data_path = ( f"data/test/idt_{constants.n}_{constants.p_0}_{constants.mode}_{run_idx}.joblib" ) ...
766787b06f0899074aa5c1212b15607fd988e2f8
65,256
def search_talks(page=None, sort=None): """ Get Talks from by Topic from ElasticSearch """ client = Elasticsearch([{ 'host': settings.ELASTICSEARCH['default']['HOSTNAME'], 'port': settings.ELASTICSEARCH['default']['PORT'], }]) s = Search(using=client, index="vtalks") # Paginati...
4f652fa5c56e092efacf105d125684a01c6bfdd1
65,258
import lumapi from typing import Optional from typing import Tuple from typing import OrderedDict def run_wavelength_sweep( component: Component, session: Optional[object] = None, port_in: Tuple = None, ports_out: Tuple = None, wavelength_range: Tuple = (1.500, 1.600), n_points: int = 1000, ...
8fcd960dea9946e7cac0c4aab553a178702eaf63
65,259
from typing import Callable from typing import Union from typing import Sequence def grad( fun: Callable, argnums: Union[int, Sequence[int]] = 0, has_aux: bool = False, holomorphic: bool = False, allow_int: bool = False, ) -> Callable: """Create a function that evaluates the gradient of `fun`....
7ba3873c6f7fb15dfa310e956e813daf047d71b7
65,260
def load_room(name): """ There is a potential security problem here. Who gets to set name? Can that expose a variable? """ return globals().get(name)
3673f14c5313b649043e905e4f697669853bd49d
65,261
def root_mean_squared_error(vector): """Calculate the root mean squared error of an error vector""" return np.sqrt(np.mean(np.square(vector)))
c010b2afa3027911da4fe4d2157aeef09953cfb0
65,262
def reload_cmd(virtualenv_conf): # type: (VirtualenvConf) -> unicode """ This returns the command line to reload the webserver after deploying changes. If you set HostConf.reload_once to True, it will be called only once for each host, else it will be called for each virtualenv. :param virtuale...
59ae066a3a7354e08360a4b2a15493a9bea2d94b
65,263
import astropy.units as u def ROI_defCoords(ROI_Lon_Lat_Wd_Ht): """ Define a ROI on Map Coordinates """ lon0, lat0, width, height = ROI_Lon_Lat_Wd_Ht Coords = { "lon": (lon0 * u.deg, (lon0 + width) * u.deg), "lat": (lat0 * u.deg, (lat0 + height) * u.deg), } return Coords
8402cfe81e5803d52adda5d88538b75470e785cf
65,264
def mellowmax(x, t=1.0): """Numerically stable mellow maximum of a vector Unlike softmax, mellowmax is a contraction mapping, which means it has a unique fixed point. Args: x (numpy array): Vector of values to take mellow maximum of t (float): Temperature parameter. As t -> 0, this resemb...
e8e3d0c23653832e2a756e7327bbe0153d3e981f
65,265
def check_log_group_exists(log_group_name, access_key, secret_key, region): """ Check wheter the given cloudwatch log group already exists in AWS account Args: log_group_name (str): Cloudwatch log group name access_key (str): AWS Access Key secret_key (str): AWS Secret Key r...
76673c36654db182ef06ac819814fd43c870aa58
65,266
def is_pem_private(pem, keytype='rsa'): """ <Purpose> Checks if a passed PEM formatted string is a PRIVATE key, by looking for the following patterns: '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----' >>> rsa_k...
2e65066b8458dc50aefde553cdd9386c015f9956
65,267
def buildModel(): """ Gathers information from the DB and calls creates an HMAC/OMAC Model ..note:: Call this before optimize() This resets/rebuils the global object Model :returns: True if Model was built; False if not. """ global DBConn global OptimizationModel logger.info(Messages.Buildin...
c17c4791704f2e2f92f9e8a23d0e3de1a502a150
65,268
import sqlite3 def csrf_validate_and_comment(username, request) -> bool: """ validator function defined for the CSRF lesson. checks if request came from same host. If not, and the validateReq field contains the right value, insert a comment and complete the lesson request - a flask request object ...
02939c1a908a516e3ea15c8958d93663ed9c50d4
65,269
def float_env(var_name, default=0.0): """ Get an environment variable coerced to a float value. This has the same arguments as bool_env. If a value cannot be coerced to a float, a ValueError will be raised. """ return float(getenv(var_name, default))
4dafb32ef87a710f0a2d5c65f4da82cb9368114c
65,270
def parse_message(message, doc): """ In XNotify settings, you are allowed to add placeholders for the invoice's grand total and the invoice number. This function allows you to 'compile' the message and returns a new string with the placeholders replaced with actual information from the Sales Invoice doctype object...
793e6e5184ae520c35cb33225cde99090acd27de
65,271
from datetime import datetime import csv def clean_data(header, data_list, out_file="cleaned_data.csv", **kwargs): """ Function cleas data, removes rows which don't fit the parameters set in kwargs :param header: list -> Header row for csv output file :param data_list: list(list(), list(), ...) -> Lis...
642de30dd7d3a9b81e34a0419a150de54e6d0b7d
65,272
import tqdm def SCW_II(x_list, y_list, mu, sigma, C, eta): """ Update weight parameter using SCW-I update rule on the given data. Params: x_list(csr_matrix): list of feature vector y_list(list): list of labels mu(csr_matrix): current weight parameters sigma(csr_matrix): current...
7c4ba73f8321765929d4d25db151ded18103cbf7
65,273
def evans_full_combined(): """ compute the evans function for the non-axial non-diagonal case. """ bif = np.loadtxt('evans_full.ode.all_info.dat') # sample evans zeros reA = bif[420,8] imA = bif[420,9] reB = bif[244,8] imB = bif[244,9] fig = plt.figure(figsize=(8,5)) ...
ae1a453c526b3ad88335553e0633b9a0402904b7
65,274
def all_clusters_conf(): """ 获取所有HDFS集群的连接信息,包括区域列表,以及区域对应的hive metastore地址信息。 :return: 字典,包含HDFS集群的连接信息。 """ result = {GEOG_AREAS: [], HIVE_METASTORE_URIS: {}, HDFS_CONF: {}} for geog_area in list(HIVE_METASTORE_SERVER.keys()): port = HIVE_METASTORE_SERVER.get(geog_area, {}).get(HIVE_ME...
dbdb62c3d923b31df75c8c420df4851d2bbd8d99
65,275