content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import OrderedDict def merge_nodes(nodes): """ Merge nodes to deduplicate same-name nodes and add a "parents" attribute to each node, which is a list of Node objects. """ def add_parent(unique_node, parent): if getattr(unique_node, 'parents', None): if parent.name ...
1f5a2a7188071d9d6f8b6ab1f25ceff1a0ba8484
3,652,199
def get_cache_timeout(): """Returns timeout according to COOLOFF_TIME.""" cache_timeout = None cool_off = settings.AXES_COOLOFF_TIME if cool_off: if isinstance(cool_off, (int, float)): cache_timeout = timedelta(hours=cool_off).total_seconds() else: cache_timeout =...
4804576c2017aa51edb862e75a99e9e193eb3f20
3,652,201
def find_records(dataset, search_string): """Retrieve records filtered on search string. Parameters: dataset (list): dataset to be searched search_string (str): query string Returns: list: filtered list of records """ records = [] # empty list (accumulator pattern) for ...
c6cbd5c239f410a8658e62c1bbacc877eded5105
3,652,202
from pattern.en import parse, Sentence def mood(sentence, **kwargs): """ Returns IMPERATIVE (command), CONDITIONAL (possibility), SUBJUNCTIVE (wish) or INDICATIVE (fact). """ if isinstance(sentence, basestring): try: # A Sentence is expected but a string given. # Attempt to...
50d495e0a07a89c912288e93bf17a3d72cb78e87
3,652,203
def create_script(*args, **kwargs): """Similar to create_file() but will set permission to 777""" mode = kwargs.pop("mode", 777) path = create_file(*args, **kwargs) path.chmod(mode) return path
24a907b8e8cdb51bd1a224283d98756985ea1030
3,652,204
import torch def unique(x, dim=None): """Unique elements of x and indices of those unique elements https://github.com/pytorch/pytorch/issues/36748#issuecomment-619514810 e.g. unique(tensor([ [1, 2, 3], [1, 2, 4], [1, 2, 3], [1, 2, 5] ]), dim=0) => ten...
8282e6a176b36f75baee8a9101d3cce49f41364d
3,652,205
def _convert_arg(val, name, type, errmsg=None): """ Convert a Python value in CPO and check its value Args: val: Value to convert name: Argument name type: Expected type errmsg: Optional error message """ val = build_cpo_expr(val) assert val.is_kind_of(type), errmsg ...
cf70cc4ec9247ee9941cb715f99180b34f5b378f
3,652,206
import json def into_json(struct): """ Transforms a named tuple into a json object in a nice way. """ return json.dumps(_compile(struct), indent=2)
23470d184caff5540760782c8a1eee1589a61026
3,652,207
import random def generate_integer_seeds(signature): """Generates a set of seeds. Each seed is supposed to be included as a file for AFL. **NOTE** that this method assumes that the signature only have int types. If a non int type is found, None is returned. Param: (str) signature: fu...
c058f730a6bd41d66ca64e3bfeffc5f4f65c2f60
3,652,208
from typing import Tuple def adjust_time(hour: int, minute: int) -> Tuple[int, int]: """Adjust time from sunset using offset in config. Returns: Tuple[int, int]: (hour, minute) of the adjusted time """ today = pendulum.today().at(hour, minute) today = today.add(hours=config.OFFSET_H, min...
bbd3b170976df934a541db91d728cb68420d0a4b
3,652,209
from functools import reduce def flatten(l): """Flatten 2 list """ return reduce(lambda x, y: list(x) + list(y), l, [])
85b4fad4ef0326304c1ee44714d8132841d13b16
3,652,211
def _rep_t_s(byte4): """ 合成置换T', 由非线性变换和线性变换L'复合而成 """ # 非线性变换 b_array = _non_linear_map(_byte_unpack(byte4)) # 线性变换L' return _linear_map_s(_byte_pack(b_array))
d82db42a848cdc84ba042b61a2825113feab5078
3,652,212
def get_mapping(): """ Returns a dictionary with the mapping of Spacy dependency labels to a numeric value, spacy dependency annotations can be found here https://spacy.io/api/annotation :return: dictionary """ keys = ['acl', 'acomp', 'advcl', 'advmod', 'agent', 'amod', 'appos', 'attr', 'aux', '...
164d2292bdd573a5805f9a66f685d21aac92061e
3,652,213
def create_root_folder(path: str, name: str) -> int: """ Creates a root folder if folder not in database. Fetches id if folder already in database. Handles paths with both slash and backslash as separator. :param path: The path to the folder in the users file system. :param name: The name of th...
54ab207501490b7f154111d6091e9a04b59603c9
3,652,214
import logging def get_document_term_matrix(all_documents): """ Counts word occurrences by document. Then transform it into a document-term matrix (dtm). Returns a Tf-idf matrix, first count word occurrences by document. This is transformed into a document-term matrix (dtm). This is also just cal...
b43cd43d68f48c0296a37668c5f48375ac7e38df
3,652,215
def f_raw2(coordinate, packedParams): """ The raw function call, performs no checks on valid parameters.. :return: """ gaussParams = packedParams['pack'] res = 0 for p in gaussParams: res += gaussian_2d.f_noravel(coordinate, *p) return res
2071e4d6c227975b308ea717658d0bf1af567fca
3,652,216
def example_serving_input_fn(): """Build the serving inputs.""" example_bytestring = tf.placeholder( shape=[None], dtype=tf.string, ) features = tf.parse_example( example_bytestring, tf.feature_column.make_parse_example_spec(INPUT_COLUMNS)) return tf.estimator.export.ServingI...
d94f7add7ba7a549263a85ef4d21cd78bae298ca
3,652,217
def add_file_uri_to_path(filepath): """Add the file uri preix: "file://" to the beginning of a path""" if not filepath: return False, "The filepath must be specified" if filepath.lower().startswith(FILE_URI_PREFIX): # # return True, filepath updated_fpath = '%s%s' % (FI...
dc0640f6101b92a8623e360ac6782b3b23b6e45d
3,652,218
def np_slope_diff_spacing(z, xspace, yspace): """ https://github.com/UP-RS-ESP/TopoMetricUncertainty/blob/master/uncertainty.py Provides slope in degrees. """ dy, dx = np.gradient(z, xspace, yspace) return np.arctan(np.sqrt(dx*dx+dy*dy))*180/np.pi
45527de535339a4cae17694dbf5313fb57a02bef
3,652,219
import torch def build_dist( cfg, feat_1, feat_2=None, dist_m=None, verbose=False, ): """Computes distance. Args: input1 (torch.Tensor): 2-D feature matrix. input2 (torch.Tensor): 2-D feature matrix. (optional) Returns: numpy.ndarray: distance matrix. """ if dist_m i...
2022386bf74939f9eb7039af8d67f718121062a0
3,652,220
def call_inverse_cic_single_omp(img_in,yc1,yc2,yi1,yi2,dsi): """ Input: img_in: Magnification Map yc1, yc2: Lens position yi1, yi2: Source position dsi: pixel size on grid """ ny1,ny2 = np.shape(img_in) img_in = np.array(img_in,dtype=ct.c_float) yi1 = np.array(yi1...
286c650117e9c3df17bc081e3d9ddbe47755e010
3,652,221
def filter_spans(spans): """Filter a sequence of spans and remove duplicates or overlaps. Useful for creating named entities (where one token can only be part of one entity) or when merging spans with `Retokenizer.merge`. When spans overlap, the (first) longest span is preferred over shorter spans. ...
3b15a79b14f02ffa870b94eb9b61261c4befc0eb
3,652,222
def get_col_names_for_tick(tick='BCHARTS/BITSTAMPUSD'): """ Return the columns available for the tick. Startdate is late by default to avoid getting much data """ return quandl.get(tick, start_date=None).columns
d80ae9b93b4bb817306f8ade404a083126507802
3,652,223
def check_result(request): """ 通过任务id查询任务结果 :param request: :param task_id: :return: """ task_id = request.data.get('task_id') if task_id is None: return Response({'message': '缺少task_id'}, status=status.HTTP_400_BAD_REQUEST) res = AsyncResult(task_id) if res.ready(): # 检...
b43001fb598188f030a58166ab445a919b9b1d4e
3,652,225
from typing import Tuple def _remove_node(node: int, meta: IntArray, orig_dest: IntArray) -> Tuple[int, int]: """ Parameters ---------- node : int ID of the node to remove meta : ndarray Array with rows containing node, count, and address where address is used to find the f...
1112fc1907e3668f5c2d559d78ee1deba8583754
3,652,227
def forward_many_to_many_without_pr(request): """ Return all the stores with associated books, without using prefetch_related. 100ms overall 8ms on queries 11 queries 1 query to fetch all stores: SELECT "bookstore_store"."id", "bookstore_store"."name" FROM "bookstore_store"...
c67e3af971c67e37f4221147518a054ee49f19a2
3,652,228
import itertools def generate_combinations (n, rlist): """ from n choose r elements """ combs = [list(itertools.combinations(n, r)) for r in rlist] combs = [item for sublist in combs for item in sublist] return combs
7339b61a7ea76813c8356cf4a87b1e81b67ce10e
3,652,229
import six import traceback def conv_datetime(dt, version=2): """Converts dt to string like version 1 = 2014:12:15-00:00:00 version 2 = 2014/12/15 00:00:00 version 3 = 2014/12/15 00:00:00 """ try: if isinstance(dt, six.string_types): if _HAS_PANDAS: dt = pd....
19999cd2517832e06949fbb0939d3b622605d047
3,652,230
def get_description_value(name_of_file): """ :param name_of_file: Source file for function. :return: Description value for particular CVE. """ line = name_of_file.readline() while 'value" :' not in line: line = name_of_file.readline() tmp_list = line.split(':') if len(tmp_list) =...
a7b0915feff7fcd2a175bdb8fe9af48d0d9f14d7
3,652,231
def octaves(p, fs, density=False, frequencies=NOMINAL_OCTAVE_CENTER_FREQUENCIES, ref=REFERENCE_PRESSURE): """Calculate level per 1/1-octave in frequency domain using the FFT. :param x: Instantaneous signal :math:`x(t)`. :param fs: Sample frequency. :param density: Power density ...
98e1604e95bdcb72fa6d401fee020b973f1f19d4
3,652,232
def build_embed(**kwargs): """Creates a discord embed object.""" return create_embed(**kwargs)
b1a181de866cd78959c5b4bec8e14b30e8cd99d7
3,652,233
def VAMA(data, period=8, column='close'): """ Volume Adjusted Moving Average :param pd.DataFrame data: pandas DataFrame with open, high, low, close data :param int period: period used for indicator calculation :param str column: column used for indicator calculation (default = "close") :param p...
5133aae3b33e0f8ef3298790a840dd3dcb6053ce
3,652,234
def doc_vector(text, stop_words, model): """ 计算文档向量,句子向量求平均 :param text: 需要计算的文档 :param stop_words: 停用词表 :param model: 词向量模型 :return: 文档向量 """ sen_list = get_sentences(text) sen_list = [x[1] for x in sen_list] vector = np.zeros(100, ) length = len(sen_list) for sentence i...
73652ced2cd8a5fdf264d68be9b78969dfe2c78d
3,652,236
def get_ether_pkt(src, dst, ethertype=ether.ETH_TYPE_IP): """Creates a Ether packet""" return ethernet.ethernet(src=src, dst=dst, ethertype=ethertype)
94c778e16f680e73a04591e3808fa5d07c8c5afa
3,652,237
import inspect def _resolve_dependency(param: inspect.Parameter, class_obj: Instantiable , app: App): """ Try to get the instance of a parameter from a bound custom resolver for the class which needs it. if not able to do the above, try to get a registered binding for the parameter's Annotation. ...
6bbe3f6fd74d037584ab96c761503a2b47cc901a
3,652,238
import re def parse_compute_hosts(compute_hosts): """ Transform a coma-separated list of host names into a list. :param compute_hosts: A coma-separated list of host names. :type compute_hosts: str :return: A list of host names. :rtype: list(str) """ return filter(None, re.split('[^a-zA...
efbfe7b06290b90d044e89343bfd4ecf94733d9c
3,652,239
def get_bbox(mask_frame): """ get rectangular bounding box for irregular roi Args: mask_frame (np.ndarray): the frame containing the mask Returns: bbox (np.ndarray): numpy array containing the indexes of the bounding box """ bbox = np.zeros(4) bbox[0] = np.min(np.where(np.m...
e7cc63cc8b5dfa1e4d59b0696f6e9747e33f69bc
3,652,240
def view_create_log_entry_verbose(request): """Create a new BehavioralLogEntry. Return the JSON version of the entry""" return view_create_log_entry(request, is_verbose=True)
d461f9f9893756f8e45aa6578e6fb9625957b415
3,652,241
import json import queue import time def webhook_server_factory(free_port): """For making a server that can accept Onshape webhooks.""" servers = [] threads = [] def _webhook_server_factory(): """ Create a factory to handle webhook notifications coming in. :param on_recieved: functio...
66a96cdf0226a2e164492d229bd50e675c7ac667
3,652,242
def generator_validator(file_path: Text): """ Validates that the generator module exists and has all the required methods """ if not exists(file_path): raise ArgumentTypeError(f"File {file_path} could not be found") try: module = import_file("generator", file_path) except S...
4a1f42198ad8421bcbb333d1bc5cfd1fc6ef0b3e
3,652,243
from typing import Optional from typing import List import gzip import google def from_bytes( data: bytes, idx_list: Optional[List[int]] = None, compression: Optional[str] = "gz" ) -> List[ProgramGraph]: """Deserialize Program Graphs from a byte array. :param data: The serialized Program Graphs. :pa...
3d8e0291af3b283616eef06ac1e8161b248bb4e6
3,652,244
def runTimer(t): """t is timer time in milliseconds""" blinkrow = 500 #in milliseconds eachrow = t // 5 for i in range(5): for _ in range(eachrow//(2*blinkrow)): display.show(Image(hourglassImages[i+1])) sleep(blinkrow) display.show(Image(hourglassImages[i]))...
b3d0fa8c5ac2c179b206a1679e9951e91d9c8b44
3,652,245
import math def ascMoveFormula(note_distance, finger_distance, n1, n2, f1, f2): """This is for situations where direction of notes and fingers are opposite, because either way, you want to add the distance between the fingers. """ # The math.ceil part is so it really hits a value in our moveHash. ...
a9f4ef27f1a922eea1f9ec4a400d120e6b0c892b
3,652,246
def create_stomp_connection(garden: Garden) -> Connection: """Create a stomp connection wrapper for a garden Constructs a stomp connection wrapper from the garden's stomp connection parameters. Will ignore subscribe_destination as the router shouldn't be subscribing to anything. Args: gar...
862d6a6862246a02b132313bbf9ab8f62d62a3be
3,652,247
def W_n(S, n_vals, L_vals, J_vals): """ Field-free energy. Includes extra correction terms. -- atomic units -- """ neff = n_vals - get_qd(S, n_vals, L_vals, J_vals) energy = np.array([]) for i, n in enumerate(n_vals): en = -0.5 * (neff[i]**-2.0 - 3.0 * alpha**2.0 / (4.0 * n**4.0) + ...
2a4aa2ab0c6a7d935547ac18933d835848c45d5e
3,652,248
def obter_movimento_manual(tab, peca): # tabuleiro x peca -> tuplo de posicoes """ Recebe uma peca e um tabuleiro e um movimento/posicao introduzidos manualmente, dependendo na fase em que esta o programa. Na fase de colocacao, recebe uma string com uma posicao. Na fase de movimentacao, recebe uma ...
2ac683c047a7852d56b228c11663007b9cdd7a33
3,652,249
import base64 def parse_header(req_header, taint_value): """ 从header头中解析污点的位置 """ header_raw = base64.b64decode(req_header).decode('utf-8').split('\n') for header in header_raw: _header_list = header.split(':') _header_name = _header_list[0] _header_value = ':'.join(_header...
f0ffdf7a823bd07e0648970a7d0791e44ad9c4a9
3,652,250
def fake_batch(obs_space, action_space, batch_size=1): """Create a fake SampleBatch compatible with Policy.learn_on_batch.""" samples = { SampleBatch.CUR_OBS: fake_space_samples(obs_space, batch_size), SampleBatch.ACTIONS: fake_space_samples(action_space, batch_size), SampleBatch.REWARDS...
1e71e17eecdabd8c95aa517564e494e303e10a4b
3,652,252
import collections def compute_macro_f1(answer_stats, prefix=''): """Computes F1, precision, recall for a list of answer scores. This computes the *language-wise macro F1*. For minimal answers, we also compute a partial match score that uses F1, which would be included in this computation via `answer_stats`....
08c774b6a06230c298dcbf031d2e188a643df9ef
3,652,253
def piecewise_linear(x, rng, NUM_PEOPLE): """ This function samples the piecewise linear viral_load model Args: x ([type]): [description] rng (np.random.RandomState): random number generator NUM_PEOPLE (int): [description] Returns: np.array: [description] """ vi...
27c27c89769674d7fcf8008f21334ec12acd588c
3,652,254
def mol_sim_matrix(fingerprints1, fingerprints2, method='cosine', filename=None, max_size=1000, print_progress=True): """Create Matrix of all molecular similarities (based on molecular fingerprints). If filename is n...
43bd1fd26d3c4372d7285c8f93ad3a7e7e7d8a61
3,652,255
def energies_over_delta(syst, p, k_x): """Same as energy_operator(), but returns the square-root of the eigenvalues""" operator = energy_operator(syst, p, k_x) return np.sqrt(np.linalg.eigvalsh(operator))
b610ca896791d6036c1a5ed1295f3293408f898a
3,652,256
def count_matching(d1: Die, d2: Die, num_rolls: int) -> int: """ Roll the given dice a number of times and count when they match. Args: d1 (Die): One Die object (must not be None) d2 (Die): Another Die object (must not be None) num_rolls (int): Positive number of rolls to toss. Ret...
f5e7f119ef639a910b7b824a3aabb47ce7bf1f60
3,652,257
def autoaugment_preproccess( input_size, scale_size, normalize=None, pre_transform=True, **kwargs): """ Args: input_size: scale_size: normalize: pre_transform: **kwargs: Returns: """ if normalize is None: nor...
de24dd19015ff8e4210f98ec5702fbf9ee637ebd
3,652,258
def pubchem_image(cid_or_container, size=500): """ Generate HTML code for a PubChem molecular structure graphic and link. Parameters: cid_or_container: The CID (int, str) or a subscriptable object that contains a key ``cid``. Returns: HTML code for an image from PubChem. ...
ca7f9fd9ad31bf834596460f047bf393e3cfd486
3,652,259
from typing import Optional from typing import List def to_lines(text: str, k: int) -> Optional[List[str]]: """ Given a block of text and a maximum line length k, split the text into lines of length at most k. If this cannot be done, i.e. a word is longer than k, return None. :param text: the block of...
1797f45ce4999a29a9cc74def3f868e473c2775a
3,652,260
def _image_pos(name): """ 查找指定图片在背景图中的位置 """ imsrc = ac.imread('images/bg/{}.png'.format(name[1:])) imobj = ac.imread('images/{}.PNG'.format(name)) # find the match position pos = ac.find_template(imsrc, imobj) circle_center_pos = pos['result'] return circle_center_pos
6d4bd64b252c2acbf86e22e8048150a3e1976045
3,652,261
def product_except_self(nums: list[int]) -> list[int]: """Computes the product of all the elements of given array at each index excluding the value at that index. Note: could also take math.prod(nums) and divide out the num at each index, but corner cases of num_zeros > 1 and num_zeros == 1 make code inele...
15090d4873b0dec9ea6119e7c097ccda781e51fa
3,652,263
import itertools def so_mörk(): """Sagnorð.""" return itertools.chain( # Nafnháttur - nútíð er sleppt og ekki til í þáttíð miðmynd {"sng---", "sng--þ", "snm---"}, # Boðháttur - alltaf 2.p og nútíð string_product({"sb"}, MYND, {"2"}, TALA, {"n"}), # Lýsingarháttur nútíða...
07a5c79a78083392a5ce96cfb74c13d644a5585e
3,652,265
def _histogram(values, value_range, nbins=100, dtype=tf.int32, name=None): """Return histogram of values. Given the tensor `values`, this operation returns a rank 1 histogram counting the number of entries in `values` that fell into every bin. The bins are equal width and determined by the arguments `...
d15d1a8aac528c5641e391d56cb8141f07c244c5
3,652,266
def find_missing_letter(chars): """ chars: string of characters return: missing letter between chars or after """ letters = [char for char in chars][0] chars = [char.lower() for char in chars] alphabet = [char for char in "abcdefghijklmnopqrstuvwxyz"] starting_index = alphabet.index(chars[0]) for lett...
bc663b68ac49095285a24b06554337c1582c8199
3,652,267
def series_to_pyseries( name: str, values: "pl.Series", ) -> "PySeries": """ Construct a PySeries from a Polars Series. """ values.rename(name, in_place=True) return values.inner()
958e08e428948adbdf353b911b9e5ab814e06cdb
3,652,268
def _stagefile(coption, source, destination, filesize, is_stagein, setup=None, **kwargs): """ Stage the file (stagein or stageout) :return: destination file details (checksum, checksum_type) in case of success, throw exception in case of failure :raise: PilotException in case of controlled e...
725fb5d77489746a8ed0dd587a32bda669008456
3,652,269
def tally_cache_file(results_dir): """Return a fake tally cache file for testing.""" file = results_dir / 'tally.npz' file.touch() return file
271c58cc263cf0bfba80f00b0831303326d4d1a8
3,652,270
import torch def get_soft_label(cls_label, num_classes): """ compute soft label replace one-hot label :param cls_label:ground truth class label :param num_classes:mount of classes :return: """ # def metrix_fun(a, b): # torch.IntTensor(a) # torch.IntTensor(b) # metr...
e08e6fc86252bf76dd8a852c63e92776b4fdcfc3
3,652,271
def get_option(args, config, key, default=None): """Gets key option from args if it is provided, otherwise tries to get it from config""" if hasattr(args, key) and getattr(args, key) is not None: return getattr(args, key) return config.get(key, default)
54d77c6ae3e40b2739156b07747facc4a952c237
3,652,272
from operator import index def z_decode(p): """ decode php param from string to python p: bytes """ if p[0]==0x4e: #NULL 0x4e-'N' return None,p[2:] elif p[0]==0x62: #bool 0x62-'b' if p[2] == 0x30: # 0x30-'0' ret...
e4735532f783bdbcc76512ba414b296b743ebeb7
3,652,273
import re def parse_extension(uri): """ Parse the extension of URI. """ patt = re.compile(r'(\.\w+)') return re.findall(patt, uri)[-1]
5ed4eee77b92f04e62390128939113168d715342
3,652,274
import math def rotz(ang): """ Calculate the transform for rotation around the Z-axis. Arguments: angle: Rotation angle in degrees. Returns: A 4x4 numpy array of float32 representing a homogeneous coordinates matrix for rotation around the Z axis. """ rad = math.radia...
4332242c5818ccc00d64cbebf7a861727e080964
3,652,275
def getBits(data, offset, bits=1): """ Get specified bits from integer >>> bin(getBits(0b0011100,2)) '0b1' >>> bin(getBits(0b0011100,0,4)) '0b1100' """ mask = ((1 << bits) - 1) << offset return (data & mask) >> offset
0bdae35f5afa076d0e5a73b91d2743d9cf156f7d
3,652,276
def rescale(img, input_height, input_width): """Code from Loading_Pretrained_Models.ipynb - a Caffe2 tutorial""" aspect = img.shape[1]/float(img.shape[0]) if(aspect>1): # landscape orientation - wide image res = int(aspect * input_height) imgScaled = skimage.transform.resize(img, (in...
6d6ac5cf1f496c9b7209e2b665e314c587471e82
3,652,277
def compute_halfmax_crossings(sig): """ Compute threshold_crossing, linearly interpolated. Note this code assumes there is just one peak in the signal. """ half_max = np.max(sig)/2.0 fwhm_set = np.where(sig > half_max) l_ndx = np.min(fwhm_set) #assumes a clean peak. if l_ndx > 0: ...
81347177aa442bf20ac56194127444ab5948a065
3,652,278
def quote_identities(expression): """ Rewrite sqlglot AST to ensure all identities are quoted. Example: >>> import sqlglot >>> expression = sqlglot.parse_one("SELECT x.a AS a FROM db.x") >>> quote_identities(expression).sql() 'SELECT "x"."a" AS "a" FROM "db"."x"' Args: ...
7689e883eb5360bee7e22c57b4e177be2f732e8b
3,652,279
import struct import zlib def write_png(data, origin='upper', colormap=None): """ Transform an array of data into a PNG string. This can be written to disk using binary I/O, or encoded using base64 for an inline PNG like this: >>> png_str = write_png(array) >>> 'data:image/png;base64,'+png_st...
516c609bbe19974065a1dc32b34de80bab06c17e
3,652,280
def prepare_url(url, source_url=None): """ Operations that purify a url, removes arguments, redirects, and merges relatives with absolutes. """ try: if source_url is not None: source_domain = urlparse(source_url).netloc proper_url = urljoin(source_url, url) ...
867d3eb31a20893f6f5be4bd4f6a925f38d7c1a3
3,652,281
import re def str_contains_num_version_range_with_x(str): """ Check if a string contains a range of number version with x. :param str: the string to check. :return: true if the string contains a a range of number version with x, false else. """ return bool(re.search(r'\d+((\.\d+)+)?(\.x)? < \d...
d11c34d1378b29df279da63882a9e34581fd9c13
3,652,282
from typing import Callable from typing import Coroutine def mpc_coro_ignore( func: Callable[..., Coroutine[SecureElement, None, SecureElement]] ) -> Callable[..., SecureElement]: """ A wrapper for an MPC coroutine that ensures that the behaviour of the code is unaffected by the type annotations. ...
eefd690145067856709c4edf02958eba428a4313
3,652,284
def is_all_in_one(config): """ Returns True if packstack is running allinone setup, otherwise returns False. """ # Even if some host have been excluded from installation, we must count # with them when checking all-in-one. MariaDB host should however be # omitted if we are not installing Mar...
35bd2f2edf3f12575612edb27218509db769d68f
3,652,285
def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simply replace the two lines below with: return auth.wiki() """ response.title = 'Award management' data = {"message":...
6a0e910c793bf538f65826579a9ba6c9401bd4de
3,652,286
import requests import json def session_generate(instanceAddress, appSecret): # pragma: no cover """ **Deprecated** Issue a token to authenticate the user. :param instanceAddress: Specify the misskey instance address. :param appSecret: Specifies the secret key. :type instanceAddress: str ...
69e8b6cf54d92041326cc4f8d2dafa82a0f043a7
3,652,287
def _dream_proposals( currentVectors, history, dimensions, nChains, DEpairs, gamma, jitter, eps ): """ generates and returns proposal vectors given the current states """ sampleRange = history.ncombined_history currentIndex = np.arange(sampleRange - nChains,sampleRange)[:, np.newaxis] combi...
d72075d09589b77f7077a5785db9f77e6a4182b0
3,652,288
import copy import json def compress_r_params(r_params_dict): """ Convert a dictionary of r_paramsters to a compressed string format Parameters ---------- r_params_dict: Dictionary dictionary with parameters for weighting matrix. Proper fields and formats depend on the...
4e56badfb7ea773d9d1104b134aa61b83d8d2f2f
3,652,290
def replace_ext(filename, oldext, newext): """Safely replaces a file extension new a new one""" if filename.endswith(oldext): return filename[:-len(oldext)] + newext else: raise Exception("file '%s' does not have extension '%s'" % (filename, oldext))
33ab99860cfe90b72388635d5d958abe431fa45e
3,652,291
def getAllArt(): """ 1/ verify if user is authenticated (login) 2/ if yes he can post a new article if not he can only read article """ if request.method == "GET": articles = actualArticle.getAll() return articles elif request.method == 'PUT': if 'logged_in...
d7506d4fbe3b4f670c30ce18501fe6ea4d410169
3,652,292
from typing import Union from typing import Tuple import warnings def normalize_citation(line: str) -> Union[Tuple[str, str], Tuple[None, str]]: """Normalize a citation string that might be a crazy URL from a publisher.""" warnings.warn("this function has been externalized to :func:`citation_url.parse`") ...
c004e75aae0bcb625d8906421057a484b6831606
3,652,293
def get_all_comb_pairs(M, b_monitor=False): """returns all possible combination pairs from M repeated measurements (M choose 2) Args: M (int): number of measurements per Returns: indices1, incides2 """ indices1 = np.zeros(int(M*(M-1)/2)) indices2 = np.zeros(int(M*(M-1)/2...
9b537d040463e6db2a0bd0616bc3110cf0c9e7f6
3,652,296
def gomc_sim_completed_properly(job, control_filename_str): """General check to see if the gomc simulation was completed properly.""" with job: job_run_properly_bool = False output_log_file = "out_{}.dat".format(control_filename_str) if job.isfile(output_log_file): # with ope...
95c5b9dec8e38f5a06ad4031c72d14629ebdefe3
3,652,297
import functools import time def debounce(timeout, **kwargs): """Use: @debounce(text=lambda t: t.id, ...) def on_message(self, foo=..., bar=..., text=None, ...)""" keys = sorted(kwargs.items()) def wrapper(f): @functools.wraps(f) def handler(self, *args, **kwargs): # C...
ac457a68834f1a6305ff4be8f7f19607f17e95fb
3,652,298
def isolated_add_event(event, quiet=True): """ Add an event object, but in its own transaction, not bound to an existing transaction scope Returns a dict object of the event as was added to the system :param event: event object :param quiet: boolean indicating if false then exceptions on event add...
e2a20c21738c42dbed36d545b127131c13f98c59
3,652,299
def get_publishers(): """ Fetch and return all registered publishers.""" url = current_app.config['DATABASE'] with psycopg2.connect(url) as conn: with conn.cursor() as cur: cur.execute("SELECT * FROM userrole WHERE is_publisher = %s ORDER BY reg_date DESC;", ('true',)) res = ...
ed6f95ea576e97f6c38074803d447de4db9b8d40
3,652,300
import curses def acs_map(): """call after curses.initscr""" # can this mapping be obtained from curses? return { ord(b'l'): curses.ACS_ULCORNER, ord(b'm'): curses.ACS_LLCORNER, ord(b'k'): curses.ACS_URCORNER, ord(b'j'): curses.ACS_LRCORNER, ord(b't'): curses.ACS_LT...
2121ab5dd650019ae7462d2ab34cf436966cffe9
3,652,301
def get_polymorphic_ancestors_models(ChildModel): """ ENG: Inheritance chain that inherited from the PolymorphicModel include self model. RUS: Наследуется от PolymorphicModel, включая self. """ ancestors = [] for Model in ChildModel.mro(): if isinstance(Model, PolymorphicModelBase): ...
aa7129dd81009e72d9fe86787a2d4516dcca3b29
3,652,302
def plot_load_vs_fractional_freq_shift(all_data,ax=None): """ Plot fractional frequency shift as a function of load temperature for all resonators """ if ax is None: fig,ax = plt.subplots(figsize=(8,8)) for name, group in all_data.groupby('resonator_index'): ax.plot(group.sweep_prima...
24f5bdbee5a904fb72d27986634244f380202a34
3,652,303
def encode_dist_anchor_free_np(gt_ctr, gt_offset, anchor_ctr, anchor_offset=None): """ 3DSSD anchor-free encoder :param: gt_ctr: [bs, points_num, 3] gt_offset: [bs, points_num, 3] anchor_ctr: [bs, points_num, 3] anchor_offset: [bs, points_num, 3] :return: encoded_...
96f3fa686a4b89dac35a4a4725831f550a62107b
3,652,304
def BCrand(h, hu, t, side, mean_h, amplitude, period, phase): """ Conditions aux limites du modele direct, avec plus de paramètres""" if side == 'L': h[0] = mean_h + amplitude * np.sin((t * (2 * np.pi) / period) + phase) hu[0] = 0.0 elif side == 'R': h[-1] = h[-2] hu[-1] = hu...
7113fd81a375bbabc2ac8e1bf4e5c6706d3198c6
3,652,305
import itertools def simplify(graph): """ helper that simplifies the xy to mere node ids.""" d = {} cnt = itertools.count(1) c2 = [] for s, e, dst in graph.edges(): if s not in d: d[s] = next(cnt) if e not in d: d[e] = next(cnt) c2.append((d[s], d[e]...
3ec7950922c5e49bad68f19666eb0381247d8f8f
3,652,307
from typing import Collection def _get_class_for(type): """Returns a :type:`class` corresponding to :param:`type`. Used for getting a class from object type in JSON response. Usually, to instantiate the Python object from response, this function is called in the form of ``_get_class_for(data['object'...
d122fe4dabd8a0486b0ed441b064f5c3d08c6b9b
3,652,308
import requests def _query_jupyterhub_api(method, api_path, post_data=None): """Query Jupyterhub api Detects Jupyterhub environment variables and makes a call to the Hub API Parameters ---------- method : string HTTP method, e.g. GET or POST api_path : string relative path, f...
22ba33ae53908aabae44bf591f9f3f1efcd97219
3,652,309
def PoolingOutputShape(input_shape, pool_size=(2, 2), strides=None, padding='VALID'): """Helper: compute the output shape for the pooling layer.""" dims = (1,) + pool_size + (1,) # NHWC spatial_strides = strides or (1,) * len(pool_size) strides = (1,) + spatial_strides + (1,) pads = co...
185b97b308b8c15aa7fab2701ad40e1ee8241248
3,652,310
def create_app(): """ 工厂函数 """ app = Flask(__name__) register_blueprint(app) # register_plugin(app) register_filter(app) register_logger() return app
06ad3e8c07fd823b0f8ec5f4a18d49a0a430fa93
3,652,312