content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def random_nat(n: int) -> int: """ Generate a random natural number L{n} bytes long. """ return utils.int_from_bytes(random_bytes(n), 'big', signed=False)
bb95e603f1b252c44378b423447b939633727cc1
3,621,148
import base64 def getNumAtoms(ctab): """ Counts number of atoms of given compounds. CTAB is urlsafe_base64 encoded string containing single molfile or concatenation of multiple molfiles. cURL examples: curl -X GET ${BEAKER_ROOT_URL}getNumAtoms/$(cat aspirin.mol | base64 -w 0 | tr "+/" "-_") """ dat...
60be1d8ae075cd13a02de83f72ebf9752e89682f
3,621,149
import pkg_resources def get_requirement_version(package_name, dependency_name): """Get assigned version to a dependency in package requirements.""" package_name = package_name.replace('pollination.', 'pollination_') package_name = name_to_pollination(package_name) dependency_name = dependency_name.re...
30a898236698ed76a8cb45fe078eb42fa7666a2e
3,621,150
from typing import Counter import math def cosine(s1, s2): """ Retuns the cosine value between two strings >>> cosine("This is a sentence", "This is a sentence") 1.0 """ vec1 = Counter(s1.split()) vec2 = Counter(s2.split()) intersection = set(vec1.keys()) & set(vec2.keys()) nume...
c1864a986cae8ca3be43dc6a0a02afa4419217f7
3,621,151
from pathlib import Path import typing def generate_multiple_simulations(path_sumo_cfg: Path, flow_configs: typing.Dict[str, typing.Dict], n_simulation: int) -> typing.List[Path]: """Generate "n_simulation" configuration files while updating valu...
44a69fcfbc0261a19e8c096d551f487a7a5b4a71
3,621,152
def get_all_types(inactive=0): """Get all non-deleted instance_types. Pass true as argument if you want deleted instance types returned also. """ return db.instance_type_get_all(context.get_admin_context(), inactive)
2202e99d0bac38bd89427d17a829e4e56f93fbf7
3,621,153
def get_predicates(rules, roles): """Extract predicate information from the rules""" preds = set() pred_names = set() predTypes = {} # maps places to the equivalence class they're in ec = TypedEquivalenceClass() for r in rules: goal_place_types = {} if r.get_head().get_relation() == 'goal': score = r.get...
fa757d35d2a476456c9d114ea6511fa69a6f3483
3,621,155
def comment_dicts_to_entities(comment_dicts): """Converts the list of comment dicts to the list of comment entities.""" return [comment_dict_to_entity(comment_dict) for comment_dict in comment_dicts]
6904c1758f03c67913a3aa5629cf2f9216b0d70e
3,621,156
def get_comment(id, check_author=True): """Get a comment and its post and its author by id. Checks that the id exists and optionally that the current user is the author of its post. :param id: id of comment to get :param check_author: require the current user to be the author :return: the comm...
8025ce6760c0f30d8e254dab689e1949945f4858
3,621,157
import string def letter_extractor(raws): """letter_ Frequencies of 26 English letters in a given text, case insensitive. Known differences with Writeprints Static feature "letter frequency": None. Args: raws: List of documents. Returns: Frequencies of English letters in the do...
54dde1c58b7f5c59af313f11294483196ba917dc
3,621,158
def crop_frames(frames, speaker): """ frames: (b h w c) """ if speaker == "chem" or speaker == "hs": return frames elif speaker == "chess": return frames[:, 270:460, 770:1130] elif speaker == "dl" or speaker == "eh": return frames[:, int(frames.shape[1] * 3 / 4) :, int(fr...
1d92d7f6ea62f26a8bfead47594681602f2051c4
3,621,159
def request_unaffiliated_research_access(request): """ Submit request for unaffiliated research access """ name = "%s %s" % (request.user.first_name, request.user.last_name) form = form_for_request(request, UnaffiliatedResearchRequestForm, initial={'name': name, 'email': request.user.email}) if request...
a7035d715ed70a2e356ff922edc3d6eb05ce6411
3,621,160
def builddict(fin): """ Build a dictionary mapping from username to country for all classes. Takes as input an open csv.reader on the edX supplied file that lists classname, country, and username and returns a dictionary that maps from username to country """ retdict = {} for cours...
ddf9272e0da6616abd0495b7b159807a36a83dcc
3,621,161
from datetime import datetime def get_timeseries(length, delta=datetime.timedelta(hours=1)): """Generate timeseries data""" start = datetime.datetime.now() timeseries = [start] for i in range(length - 1): timeseries.append(timeseries[i] + delta) return timeseries
7846d2237e49bc64e8e581bce6f51dc199dd234f
3,621,162
def add_static_values(caomlist, statics, data_type, header_type): """ Add entries from the statics dictionary to the caomlist by looking at properties of data_type and header_type. The add_value_caomxml module is used to actually create the CAOMxml objects and add them to the caomlist. """ caomlis...
3597dbb0b1789b5dc5ddddeeb55299d8666d1079
3,621,163
def dict_to_stix2(stix_dict, allow_custom=False, version=None): """convert dictionary to full python-stix2 object Args: stix_dict (dict): a python dictionary of a STIX object that (presumably) is semantically correct to be parsed into a full python-stix2 obj allow_custom...
0a7167673b96b6266fc6030e656371adf8fdfb6f
3,621,164
from typing import Callable from typing import Type def connector(schema: str) -> Callable[[Type[Connector]], Type[Connector]]: """ The @connector class decorator used to register the connector to the global registry. Parameters ---------- schema The schema for the connector, for exam...
5ec1429dd98356a5127d236e76e93792295d10a3
3,621,165
def resource_show(expression): """returns the metadata of a resource""" url = OPENDATA_URL + "resource_show?{expression}".format(expression=expression) return _request_json(url).get("result", dict())
5a92c08f3c81b87b70df06c01d7b5eaf430e5380
3,621,166
import numpy as np def n_overlap_1 ( ri, ei, box, r, e ): """Takes in coordinates and orientations of a molecule and counts overlaps. Values of box and partner coordinate array are supplied. Fast or slow algorithm selected. """ # In general, r will be a subset of the complete set of simulation ...
20b1f27677e24f42410d9821f211d781df567e02
3,621,167
def HJB_ode(y, time, b, I_func): """ Hamilton-Jacobi-Bellman equation """ u, v, w = y dudt = cost_effort(b(T_max - time)) + b(T_max - time) * \ I_func(T_max - time) * (v - u) - vac(T_max - time) * u dvdt = cost_infection(time) + gamma * (w - v) dwdt = rho * (u - w) return dudt, d...
c625d8947db0630d92698303b2390ef568062894
3,621,168
def decision_tree_predict(tree, testing_example, max_value_in_target_attribute): """ :param max_value_in_target_attribute: If we are not able to classify due to less data, we return this value when testing :param tree: This is the trained tree which we will use for finding the class of the given instance ...
39adeafcc247c397b6511001eeab183d1e542b05
3,621,171
def load_data(census_region: int, filepath: str = "nhts_census_updated.mat"): """Load the data at nhts_census.mat. :param int census_region: the census region to load data from. :param str filepath: the path to the matfile. :raises ValueError: if the census division is not between 1 and 9, inclusive. ...
fc9ae6f96c8f886a1436b34d54d68d62483f1e5e
3,621,172
import win32api def getFileProperties(fname): """ Read all properties of the given file return them as a dictionary. """ propNames = ( "Comments", "InternalName", "ProductName", "CompanyName", "LegalCopyright", "ProductVersion", "FileDescription...
319179b3f4528a1f92a2949b81c2168247aa0686
3,621,173
def setup_scanner(hass, config, see, discovery_info=None): """Set up the Volvo tracker.""" if discovery_info is None: return vin, _ = discovery_info vehicle = hass.data[DATA_KEY].vehicles[vin] def see_vehicle(vehicle): """Handle the reporting of the vehicle position.""" hos...
76f930dc3ffe3cce94fa78cf26bafa24161bf2e4
3,621,174
def check_satisfy_program(w, program): """ For each rule in the program, this function checks whether the head exists if all literals(or atoms) in the body exists in each ruler interval of the given Window ``w'' . Args: w (a Window instance): program (a list of rules): Returns: ...
7129a21922108ed5e1fd23af16b0d4b859f48fe6
3,621,176
import pdb def extend(start,end,vector,holevector) : """ Extend the subgrids one point if possible, to avoid edges """ s=np.max([0,start-1]) e=np.min([len(vector),end+1]) hs=np.max([0,np.where(np.isclose(holevector,vector[s]))[0][0]]) he=np.min([len(holevector),np.where(np.isclose(holevector,v...
5ec18fb1dc84a5170934fb45b2e69aa109d383e0
3,621,177
def array(obj, row_major=0): """Wrapper around numpy.ndarray. It gives you the option of specifying the order of the contents. """ if not isinstance(obj, np.ndarray): obj = np.array(obj) if row_major == 0: if obj.flags.f_contiguous: return obj else: dim = ...
e431d744afcada334fea115bf834314ffa7138bd
3,621,178
def get_reverse_depends(name, capability_instances): """Gets the reverse dependencies of a given Capability :param name: Name of the Capability which the instances might depend on :type name: str :param capability_instances: list of instances to search for having a dependency on the given Capab...
fda11bb01d6352b18e87365f1060f48a5c07f266
3,621,179
import random def normal2(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.randrange(1, 100001) idgirand...
d60ba311afc9b80e4c3c95dd97e984c184b586ff
3,621,180
import collections def node_degree_counter(g, node, cache=True): """Returns a Counter object with edge_kind tuples as keys and the number of edges with the specified edge_kind incident to the node as counts. """ node_data = g.node[node] if cache and 'degree_counter' in node_data: return no...
08c08f240e3170f4159e72bc7e69d99b69c37408
3,621,181
async def get_account_id(db, name): """Get account id from account name.""" return await db.query_one("SELECT find_account_id( (:name)::VARCHAR, True )", name=name)
3dd6b46abd8726eb34eb4f8e1850dc56c3632e5c
3,621,182
def params_to_payload(params, config): """Converts a set of parameters into a payload for a GET or POST request. """ base_payload = {config['param-api-key']: config['api-key']} return dict(base_payload, **params)
aec633ab62cf18c0acf685115d4e291cd6198cb3
3,621,183
def colorize_img(value, vmin=None, vmax=None, cmap='jet'): """ A utility function for TensorFlow that maps a grayscale image to a matplotlib colormap for use with TensorBoard image summaries. By default it will normalize the input value to the range 0..1 before mapping to a grayscale colormap. A...
f76593bb8427bf0332fa47f9098ef11e2fe56c23
3,621,184
from typing import Mapping import types def evaluate_models( models: Mapping[K, RewardModel], batch: types.Transitions ) -> Mapping[K, np.ndarray]: """Computes prediction of reward models.""" reward_outputs = {k: m.reward for k, m in models.items()} feed_dict = make_feed_dict(models.values(), batch) ...
d9b7337836f72e85a443b409bc69b5079a80b13e
3,621,185
from typing import Any def is_a_string(v: Any) -> bool: """Returns if v is an instance of str. """ return isinstance(v, str)
f729f5784434ef255ea9b2f0ca7cdfbf726e7539
3,621,187
def wheel_speed_commands(u_ref, w_ref, d, r): """Converts reference speeds to wheel speed commands""" leftSpeed = float((2 * u_ref - d * w_ref) / (2 * r)) rightSpeed = float((2 * u_ref + d * w_ref) / (2 * r)) leftSpeed = np.sign(leftSpeed) * min(np.abs(leftSpeed), MAX_SPEED) rightSpeed = np.sig...
262603298ec5acd948eca0b873ca7051395e1515
3,621,188
def _get_dataset_from_filename(filename_skip_take, do_skip, do_take): """Returns a tf.data.Dataset instance from given (filename, skip, take).""" filename, skip, take = (filename_skip_take['filename'], filename_skip_take['skip'], filename_skip_take['take'],) dat...
0f2964a1585ad0be0729544a4451ccabba65abd8
3,621,189
def kde_normalize(arr, mask=None, modality="T1w", norm_value=1): """ Use kernel density estimation to find the peak of the white matter in the histogram of a skull-stripped image. Then normalize intensitites to a normalization value. Parameters ---------- arr: array the input data. ...
488093f13adcf091aa2eeaa7d8254f58b6bce11f
3,621,190
def nfour_connectivity(I): """ Returns an image of four-connectivity for each pixel, where the pixel value is the number of 4-connected neighbors. """ Ir = np.ravel(I) edgeidcs = edge_coords(I.shape, dtype='flat') allpix = set(np.where(Ir==1)[0]) dopix = allpix - edgeidcs...
c8763e33cf29167b99bbbbfed95d5f547080c9b9
3,621,192
def plot_bargraph(count_plot_df, plot_df): """ Plots the bargraph Arguments: count_plot_df - The dataframe that contains lemma counts plot_df - the dataframe that contains the odds ratio and lemmas """ graph = ( p9.ggplot(count_plot_df.astype({"count": int}), p9.aes(x="lemma...
f0543c5cc860d5ec520521830f37ad87bc2abb25
3,621,193
def flip_labels(Y, p): """Returns binary class labels with proportion p randomly flipped.""" assert set(Y) == {1, 2} Y = np.copy(Y) for i, e in enumerate(Y): if np.random.rand() < p: if e == 1: Y[i] = 2 else: Y[i] = 1 return Y
54abf9429add794203602b67368ede818fbb1646
3,621,194
def find_key(obj, predicate=None): """This method is like :func:`pydash.arrays.find_index` except that it returns the key of the first element that passes the predicate check, instead of the element itself. Args: obj (list|dict): Object to search. predicate (mixed): Predicate applied pe...
bee0e0fe07df7a7a43a53b68527007962b125a48
3,621,195
def reports_home(request): """Some default page for reports home page.""" try: blank_date = '..' * 23 blank_time = '.' * 20 address = 'P.O Box %s' % ('.' * 30) params, location = {}, '.' * 20 form = CaseLoad(request.user) if request.method == 'POST': d...
97ef40998cdc28d6f6ec76fb518b4bdddae60dec
3,621,197
def historical(): """" Retrieve stored data from datastore. """ return { 'page': 'historical', }
91933b3372e2972c37aaae2d8c83696e9398c19c
3,621,198
import time import json import requests def catch_distribution(): """抓取行政区域确诊分布数据""" data = dict() url = "https://view.inews.qq.com/g2/getOnsInfo?name=wuwei_ww_area_counts&callback=&_=%d" %int(time.time()*1000) for item in json.loads(requests.get(url=url).json()["data"]): if item["area"] not ...
4ce28940e9a3852a7622ceec489c186429fc9745
3,621,201
from settings import SECRET_KEY def create_securityhash(action_tuples): """ Create a SHA1 hash based on the KEY and action string """ action_string = "".join(["_%s%s" % a for a in action_tuples]) security_hash = sha1(action_string + SECRET_KEY).hexdigest() return security_hash
db2444a8b2e07a9afe6f947974968cc0a301602b
3,621,202
def mae( original, prediction, hinge: float = 0): """ Mean Absolute Error (mean over channels and batches) :param original: :param prediction: :param hinge: hinge value """ d = tf.abs(original - prediction) if hinge != 0.0: d = keras.layers.ReLU(threshold...
47c4d47a9cc14a8132284329d23055d072b66588
3,621,203
def record_to_index(record): """Route the given record to the right index and document type.""" def doc_type(alias): try: return list(current_search_client.indices.get_alias(index=alias, ignore=[404]).keys())[0] except: return alias if is_deposit(record.model): ...
e3b03d1631f3a1d8c329c3c2635b4dde053fce94
3,621,204
def get_two_point_vel_corr_roll(ui, x, y, z=None, roll_axis=1, n_bins=None, x0=None, x1=None, y0=None, y1=None, z0=None, z1=None, t0=None, t1=None, coarse=1.0, coarse2=0.2, ...
5629fe51437103cf3a7707b505ce8cd64a292e57
3,621,206
from typing import Dict import torch from typing import Union from typing import Tuple def random_year_img(dataset: Dict[str, torch.Tensor], writer: Union[int, None] = None, rand: np.random.RandomState = np.random.RandomState(seed=1234), **kwargs) -> Tuple[t...
72fe81110389f2b55a448f5af09ff5751120e719
3,621,207
import random def encrypt(sk, b, mbits=N): """Encrypt a bit into a Q-bit integer based on the provided key.""" # Random N-bit integer with the same parity as b m = (random.randint(2**(mbits-2), 2**(mbits-1) -1) << 1) + b # Random Q-bit integer q = random.randint(2**(Q-1), 2**Q) - 1 ...
7366d1239190ccf0fc9bbd6308139a63436ac02e
3,621,209
import json def english_to_french(english_text): """Translate eng to french""" translation = language_translator.translate( text=english_text, model_id='en-fr').get_result() print(json.dumps(translation, indent=2, ensure_ascii=False)) return french_text
0acee15db440fb3d347704c8fd66ad457a53abe2
3,621,210
def rebin_data(x, y, dx_new, method='sum'): """Rebin some data to an arbitrary new data resolution. Either sum the data points in the new bins or average them. Parameters ---------- x: iterable The dependent variable with some resolution dx_old = x[1]-x[0] y: iterable The inde...
a1115268f67cc3ff7452dc235cb2882ab5eb5204
3,621,211
def register(): """Register new user.""" form = RegisterForm(request.form) if form.validate_on_submit(): User.create(username=form.username.data, email=form.email.data, password=form.password.data, active=True) flash('Thank you for registering. You can now log in.', 'success') return...
d07cc4d6886a555bfdabaf690513e3ebefd62ec4
3,621,212
import json def _ParseFioJson(fio_json): """Parse fio json output. Args: fio_json: string. Json output from fio comomand. Returns: A list of sample.Sample object. """ samples = [] for job in json.loads(fio_json)['jobs']: cmd = job['fio_command'] # Get rid of ./fio. cmd = ' '.join(cmd...
61acc14ab815061125ddb5756d3e22ae2a90c459
3,621,214
from typing import Optional import textwrap def dedent(text: str, num_spaces: Optional[int] = None) -> str: """Wrapper around textwrap.dedent Dedents at most num_spaces. If num_spaces is not specified, dedents as much as possible. Args: text: Text that will be dedented. num_spaces...
3c86dd9073fd9cf385de3806f0fc8462ab4972bc
3,621,215
from ihome import api_1_0 from ihome.web_html import html def create_app(config_name): """ 创建flask的应用对象 :param config_name: str 配置模式的模式的名字 ("develop", "product") :return: """ app = Flask(__name__) # 根据配置模式的名字获取配置参数的类 config_class = config_map.get(config_name) app.config.from_obj...
6d18018167113e9bd37dbd39c99f845f3be039f4
3,621,216
import struct def cyclic_pattern_offset(value, pattern=None): """ Search a value if it is a part of cyclic pattern Args: - value: value to search for (String/Int) Returns: - offset in pattern if found """ pattern = pattern or cyclic_pattern().encode() if isinstance(value, i...
965e85cfd9221e478fc3599bd428e79d02a31c23
3,621,217
def lookup_file(): """Uses listify_ticked and select_file to query the session database. Returns all file information for all files tagged with tags selected in Properties prefixed with 'Tags to filter'. """ if not session: no_session_warning() return None taglist = listify_t...
b44335114e49f75ea3f6964d77fd8f7fc42ee67d
3,621,218
def _find_and_set_index(data_frame: TfsDataFrame) -> TfsDataFrame: """ Looks for a column with a name starting with the index identifier, and sets it as index if found. The index identifier will be stripped from the column name first. Args: data_frame (TfsDataFrame): the ``TfsDataFrame`` to loo...
b91b878ad4f3877be635cb12290f662bf42fb184
3,621,219
def default_adv_xxx_bigram_polarity(bigram, negation=None, prior_polarity_score=False, linear_score=None): """Calculates the bigram polarity based on a empirical factor from each adverb group and SENTIWORDNET word polarity """ second_word_polarity = word_polarity(bigram['second_word'], bigram['second_wor...
e4d938832db2e6cb1bcdd3be77aa37355776953b
3,621,220
import tqdm def convert_examples_to_dualfeatures(examples, label_list, max_seq_length, tokenizer, output_mode): """Loads a data file into a list of dual input features.""" ''' output_mode: classification or regression ''' features = [] for (ex_index, example) in enumerate(tqdm(examples)): if ex_index % 10000...
04433ae65ab897416cdd0b6afd58497ee083c102
3,621,222
def _configure_lat_type(spec, loader): """ configures latitude type """ return _configure_geo_type(spec, loader, -90.0, 90.0, '_lat')
5d3af830214bf61023d2c0d0a43852910617216c
3,621,223
def read_csv_input(csv_file, isotopes): """ Read the csv input file creating a pandas dataframe Use the matches from the light, heavy channel or both based on the user preferences """ df = pd.read_csv(csv_file) # Applies the filter of light/heavy ions specified by the user if isotopes == 'l...
b297e8dad1fc191245695d79c107682cc3554021
3,621,224
def _mutual_info(lab1, lab2): """Call sklearn's mutual info function.""" return mutual_info_score(lab1, lab2)
959ee5cade5ce84559646a8862a8b69c796d9de5
3,621,225
def decrypt_in_cbc(ciphertext, key=None, IV=None): """ Arguments must be bytes strings. """ key = key if key else bytes([0] * 16) IV = IV if IV else bytes([0] * len(key)) block_size = len(key) block_count = int(len(ciphertext) / block_size) cipher = AESEncryption(key, 'ECB') plaintext = b...
95354836a679400952cb17ee0fbea9723c7ab766
3,621,226
def rowFeaturise(row, features, timeSeriesName, wavelet, level): """ Input: - row: pandas Series The row of the features table that is going to be processed. - features: pandas DataFrame Table with pointers to JSON files that is going to have new columns with the extracte...
aa6a9679a824b9aae8085a81fd8ade408995826d
3,621,228
import tqdm def q5_plot_chromatic_num_bounds_by_prob(n, prange, pstep, k=None, clique_finder=greedy_find_clique_number): """Plots a graph of number of colours against edge probability, for each of the various lower/upper bounds of chromatic number""" probs = np.arange(prange[0], prange[1], pstep) prin...
87478f5b80c4201c3a88c93aadae9fdd47efdbfd
3,621,229
def reconstructTypeFunctionType(typeFunction, args, kwargs): """Reconstruct a type from the values returned by 'isTypeFunctionType'""" #note that our 'key' objects are dict-in-tuple-form, because dicts are #not hashable. So to keyword-call with them, we have to convert back to a dict... return typeFunc...
e57658bb7e4b368a8caf86a72db05157b689500e
3,621,230
def draw_bounding_box(img, line, color=(255, 0, 0)): """ :param line: (xmin, ymin, xmax, ymax) """ img = cv2.line(img, (line[0], line[1]), (line[2], line[1]), color) img = cv2.line(img, (line[2], line[1]), (line[2], line[3]), color) img = cv2.line(img, (line[2], line[3]), (line[0], line[3]), col...
c5a72bc07c72d3ac4bb11fcf0b8257814d98cf42
3,621,231
def flatnonzero(a): """Return indices that are non-zero in the flattened version of a. This is equivalent to a.ravel().nonzero()[0]. Args: a (cupy.ndarray): input array Returns: cupy.ndarray: Output array, containing the indices of the elements of a.ravel() that are non-zero. ...
4fd5a088e3eb2daf63454d2add9db1327483b554
3,621,232
def create_optim_modifier_trainable(project_id: str, optim_id: str): """ Route for creating a new trainable modifier for a given project optim. Raises an HTTPNotFoundError if the project or the optim are not found in the database. :param project_id: the id of the project to create a trainable modif...
84e915108495fa89ed3fb738d5acde1ebd58c56a
3,621,233
import socket def find_data_gateway(): """ Returns 200 or 404, depending on whether the data-gateway is reachable or not :return: 200 or 404 """ try: socket.gethostbyname('data-gateway') return jsonify('success'), 200 except socket.gaierror as e: return jsonify(str(e)...
b98f15f69f621b13201db6f16840f80a83873866
3,621,235
def str_to_dict( text: str, /, *keys: str, sep: str = ",", ) -> dict[str, str]: """ Parameters ---------- text: str The text which should be split into multiple values. keys: str The keys for the values. sep: str The separator for the values. Returns ...
0b34ea1b47d217929fd9df760231f4786150e661
3,621,236
def get_list_control_ranges(data): """Build a list of extended regions around given ranges that doesn't overlap with any given range Parameters ---------- data: `pd.DataFrame()` Likely coming from pd.DataFrame() it should contain ["chrom", "start", "end", "dna_string", "score", "bound"] ...
faa364d068648501f3629e83c9e9ba9ab87fcdaa
3,621,237
def test_disabledimmingresolvestorelay(FW): """ When dimming changes to the value 'disallowed' the crownstone must change from IGBT mode to relay. """ print("##### test_disabledimmingresolvestorelay #####") result = [] for intensity in [0,50,100]: result += [test_disabledimmingresol...
8ca4a75fad7101cbebcd0878d058240f0d2999fb
3,621,238
import requests def change_password(client: Client, user_id: str, password: str) -> bool: """Changes password for child user account via the `/users/{user_id}/password` endpoint. :param client: Client object :param user_id: The ID of the user account :param password: New password :return: `Tr...
0a2b2479da6714c4ee4cc7ee1ab5ef6d24e3d79b
3,621,239
def keyset(): """ Creates a set of numeric keys centered around 0 Provides a comparison function based on numeric closeness of the keys """ class KeySet: extent = 10 def __init__(self): self.key = "0" self.all = [self.key] for i in range(KeyS...
ebdc08f13d9b82136042dae9b02206e4c6bb30d9
3,621,240
def enable(include_pyrin=True, include_app=True): """ enables locale management for the application. :param bool include_pyrin: specifies that it should extract pyrin localizable messages. defaults to True if not provided. :param bool include_app: specifies that it shoul...
d00a101517d44b81599fb21e9b7e266154fa0e9f
3,621,241
def autoencoder(X, X_test, encoding_dim): """ Parameters: X: training data, X_test: testing data, encoding_dim: dimension of most hidden layer Return hidden layer representions of training and testing data. """ # this is our input placeholder input_X = Input(shape=(36,)) encoded = Dense(24, activation='rel...
483f64e95cac157a455e0c1e1c87c0892adeac65
3,621,242
from datetime import datetime import logging def add_point(slug): """Create a new point based on get parameters.""" try: timestamp = None str_timestamp = request.args.get('time', None) if str_timestamp: timestamp = datetime.strptime(str_timestamp, "%Y-%m-%dT%H:%M:%S.%fZ") ...
9dbf64cd6c18c07f25671ef61e7ff0dc7a7f69d0
3,621,243
def sp_conv3x3_block(in_channels, out_channels): """ 3x3 version of the SuperPointNet specific convolution block. Parameters: ---------- in_channels : int Number of input channels. out_channels : int Number of output channels. """ return SPConvBlock(...
ec16079ce9b1d4792a29837e2408209b78e03325
3,621,244
def correlation(a: np.ndarray, b: np.ndarray, missing: float, method="pearson"): """ Calculate correlation similarity between two vectors""" assert a.shape == b.shape assert method in CORR_METHODS threshold = a.shape[0] * missing values = ~np.logical_or(np.isnan(b), np.isnan(a)) # find missing valu...
e7f4026d011e821f7404aabf949177278c2459d6
3,621,245
from typing import Counter import base64 import json def mfa_backup_tokens(backup_secret): """ Writes MFA secrets encrypted with backup_secret and base64 encoded to stdout. """ tokens = [] for token in list_mfa_tokens(): token_data = mfa_read_token(token) if token_data['token_secret'].star...
0218b794b5c81baaa2310c8572be770a6ad895e5
3,621,246
def create_content(): """ Generate fake content to populate the email with Generates textual contents that are randomly generated and defined to include 5 random IPs, 5 random URLs, 5 random sha1 hashes, 5 random sha256 hashes, 5 random md5 hashes, 5 random email addresses, 5 random domains and 100...
a97feb2fa01dace5fdb1f87fc7f8663c50b4bba5
3,621,247
def Mresnet(**kwargs): """Constructs a modified ResNet model. """ model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs) return model
ee991ee945047f28afc59921f9b8c3331003de1b
3,621,248
def getschemasbyuuid(): """Get all schemas by uuid. :rtype: dict """ return _REGISTRY.getschemasbyuuid()
00006546a2a0e3393e85bd86204ac86357888581
3,621,249
def get_dynamic_db_settings(server_root, username, password, dbname, installed_apps): """ Get dynamic database settings. Other apps can use this if they want to change settings """ server = get_server_url(server_root, username, password) database = "%(server)s/%(database)s" % {"server": server...
b40bf8b06426f3282323904eda30093553a6ffad
3,621,250
import numpy def calc_fm_3d_by_density(mult_i, den_i, np, volume, moment_2d, phase_3d): """ Calculate magnetic structure factor. [hkl, points, symmetry] F_M = V_uc / (Ns * Np) mult_i den_i moment_2d[i, s] * phase_3d[hkl, i, s] V_uc is volume of unit cell Ns is the number of symmetry element...
40f807f00422af17897ec4fa15c5826e1b73abd8
3,621,251
def parse_args(apps: str, tables: str) -> t.List[FixtureConfig]: """ Works out which apps and tables the user is referring to. """ finder = Finder() app_names = [] if apps == "all": app_names = finder.get_sorted_app_names() elif "," in apps: app_names = apps.split(",") e...
405455bb8608904694643730e43eeae25e682db1
3,621,252
def get_randoms(n, m): """Create n random integers out of m.""" if n > m: n = m res = [] for i in range(n): while True: int = randint(0, m - 1) if not int in res: res.append(int) break return res
0e758234260b2d29f5df2e74bafd05cddde48a23
3,621,253
def install_compiler(spec: str) -> None: """Install a compiler based on a spack specification e.g. gcc@9.3.0""" run_subprocess('spack', 'compiler', 'find') stdout, _ = run_subprocess('spack', 'compilers') for line in stdout: if spec in line: return # Found the correct compiler! ...
f1aeb6b6d22c2418ac1cf7f0276f69a9c205305d
3,621,254
from typing import List from re import T from typing import Union def stree( source: List[T], func: Union[Func, QueryFunction] = QueryFunction.SUM ) -> AbstractSegmentTree: """ Automatically detects the type of input container, and uses the fastest possible segment tree implementation. """ try...
713ae7ff2ed4ebc4b58c4bebd7b965caa18106d7
3,621,255
import warnings def deprecated(func): """ This function is a decorator, which diplays a deprecation warning. """ @wraps(func) def __inner(*args, **kwargs): warnings.simplefilter('always', DeprecationWarning) warnings.warn("{}".format(func.__name__), DeprecationWarning, stacklevel=2...
9c89656fee8f4a5fa051a5f7eb59a798f103ea24
3,621,256
def radial_histogram(r, weights=None, nbins=1000): """ Performs histogramming of the varibale r using non-equally space bins """ r2 = r*r dr2 = (max(r2)-min(r2))/(nbins-2); r2_edges = np.linspace(min(r2), max(r2) + 0.5*dr2, nbins); dr2 = r2_edges[1]-r2_edges[0] edges = np.sqrt(r2_edges) ...
afbf637b2eb4a93d8eb977b4229e18d833eccf5d
3,621,258
import functools def dict_to_function(arg_dict): """ We need functions for Tensorflow ops, so we will use this function to dynamically create functions from dictionaries. """ def inner_function(lookup, **inner_dict): return inner_dict[lookup] new_function = functools.partial(inner_fu...
b6bfb0a11393eeb93733cc41fe7395ce99136713
3,621,259
def resreid_train(images, num_class=751, trainable=True): """use resnet50 as backbone, modify the stride of last layer to be 1 for rich person features """ with flow.scope.namespace("base"): stem = layer0(images, trainable=trainable) body = resnet_conv_x_body(stem, lambda x: x, trainable=trainab...
fa977b2a8342988192746e5b4301e75837e56d0c
3,621,260
import math def _g(rd): """ See page 3 at http://www.glicko.net/glicko/glicko.pdf """ return 1 / math.sqrt(1 + 3 * (Q ** 2) * (rd ** 2) / (math.pi ** 2))
9d6c23cee114f6699bc53b0dd0d7f129ebb504f1
3,621,261
def ecdh_reply(p,g,ag): """ Generates a random integer b, then computes the shared secred ab*g. Input: p A prime number g An ECPt ag An ECPt multiple of g Output: A tuple (int, ECPt, ECPt) = (b, b*g, ab*g). Remarks: This routine...
ed8a4077176fe6c1d018d563dc2209933acc3cc1
3,621,262
def findStars_old(imgData,apertureType='radius',maxima_size=5,maxima_sigma=2,maxima_footprint=None,aperture_radii=[],threshold=None, saturate=None,margin=None,binStruct=None,fit_method='elliptical moffat',id=None): """ Detect possible sources in an image and attempt to fit them to a specified pr...
35aa612480c03f894334e214212c4d3e569cb175
3,621,264