content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def outline_to_mask(line, x, y): """Create mask from outline contour Parameters ---------- line: array-like (N, 2) x, y: 1-D grid coordinates (input for meshgrid) Returns ------- mask : 2-D boolean array (True inside) Examples -------- >>> from shapely.geometry import Poin...
1c1ab70ed949b10a052aae1b17239a5d7a08da64
3,633,300
def check_ContentType(): """ HowTo make Pre-Processing for all requests. But: it also can be managed in View Class, just like django-rest-framework """ if request.method != 'GET': if (not request.content_type) or ('application/json' not in request.content_type): msg = jsonify( ...
7fc35fe40621a1cf0486d681b294ff636f293c06
3,633,301
import hashlib def _hash_feature(feature): """Calculate SHA256 hash of feature geometry as WKT""" geom = shape(feature["geometry"]) return hashlib.sha256(geom.to_wkt().encode("utf-8")).hexdigest()
bd1dc2ad46f0960a042066152b5622febe530411
3,633,302
import socket def ssdp_scan(address=None, service=None, timeout=None): """ Returns a list of responses to an SSDP request """ if address is None: address = DEFAULT_ADDR if service is None: service = DEFAULT_SERVICE if timeout is None: timeout = DEFAULT_TIMOUT mes...
43a0f557ed3f8b5b8a9c8085ce71a0e5a45a2f31
3,633,303
def random_walk_timeseries(length: int = 10, freq: str = 'D', mean: float = 0, std: float = 1, start_ts: pd.Timestamp = pd.Timestamp('2000-01-01')) -> 'TimeSeries': """ Creates a random walk TimeSeries by sampling a gaussian distribution with mean 'mean' and standard deviation 's...
754a52be186f6f05fd70c8019c61cf6c27059680
3,633,304
def provider_for(platform: str, source: str) -> ContentProvider: """ A factory method that returns the appropriate data provider. Throws an exception to let you know if the arguments are unsupported. :param platform: One of the PLATFORM_* constants above. :param source: One of the PLATFORM_SOURCE>* ...
8f77453c6ec02d9bae571f12cd2de2a3420976b5
3,633,305
def create_app(config_name: str = "development") -> Flask: """ Factory for the creation of a Flask app. :param config_name: the key for the config setting to use :type config_name: str :return: app: a Flask app instance """ app = Flask(__name__) app.config.from_object(config[config_name]...
ca38c3bb82e19db20aff7a26724f00e848d54b5b
3,633,306
def oneorzero(argument): """Conversion function for the various options that let you choose between 1 and 0.""" return directives.choice(argument, ('0', '1'))
4de687a99c56c5a7e2074d0ae58312690f115472
3,633,307
def encode(s, c): """ s is the scret code c is the clear text """ secret_code_list = list(s) clear_text_list = list(c) encoded_text_list= [] count = 0 for letter in clear_text_list: if letter == ' ': encoded_text_list.append(' ') continue enc...
3af6297fb79b77c542b19789ccf9bc0668f6afd5
3,633,308
import sqlite3 def test_ap_wpa2_eap_sql(dev, apdev, params): """WPA2-Enterprise connection using SQLite for user DB""" try: except ImportError: return "skip" dbfile = os.path.join(params['logdir'], "eap-user.db") try: os.remove(dbfile) except: pass con = sqlite3.con...
cf5139cfc264e18fdb8e60eb4bce75797506db48
3,633,309
import numpy def polyfit(data, time_axis, masked_array, outlier_threshold): """Fit polynomial to data.""" if not masked_array: if outlier_threshold: data, outlier_idx = timeseries.outlier_removal(data, outlier_threshold) coeffs = numpy.ma.polyfit(time_axis, data, 3)[::-1] ...
c58b04e31bea8a028ee464d4b70515c4e5b1e7e2
3,633,310
def update_board(position, board, player): """ Update the board with the user input position if position not taken returns board, True=position taken or False=position not taken and board updated args: position (int 1-9, user input) board (np.array 2d) player ("X" or "O") """ ...
eb53d24c4976499e6611c97757d0c33b4cb3254f
3,633,311
def find_deployed_version(package_name, environment, version=None, revision=None, apptypes=None, apptier=False): """Find a given deployed version for a given package in a given environment for all related app types; search for full tier or host only deployment specifically ...
57bcd217e0a63a610f78a5ce49365578d7540d3e
3,633,312
import itertools import math def stochastic_block_model(sizes, p, nodelist=None, seed=None, directed=False, selfloops=False, sparse=True): """Returns a stochastic block model graph. This model partitions the nodes in blocks of arbitrary sizes, and places edges between pairs of ...
4beb0e20381aa65927a8b60278f8de6cb06f64ca
3,633,313
def get_text_and_links(wikitext): """ Obtain text and links from a wikipedia text. """ parsed = wtp.parse(wikitext) basic_info = parsed.sections[0] saved_links = {} num_links = len(basic_info.wikilinks) for i in range(num_links): index = num_links - i - 1 link = basic_in...
a0b05f72c12529b655dda216e32e129b5fcaad8f
3,633,314
import signal def SobelOperator(image, n): """ 构建了 Sobel 平滑算子和差分算子后,通过这两个算子来完成图像矩阵与 Sobel 算子的 same 卷积, 函数 SobelOperator 实现该功能: 图像矩阵先与垂直方向上的平滑算子卷积得到的卷积结果, 再与水平方向上的差分算子卷积, 这样就得到了图像矩阵与sobel_x 核的卷积。 与该过程类似,图像矩阵先与水平方向上的平滑算子卷积得到的卷积结果, 再与垂直方向上的差分算子卷积, 这样就得到了图像矩阵与 sobe...
e39b807ecff2e78f289a918e6f85ef7fced84427
3,633,315
import typing import pickle def read_model(model_file: typing.IO) -> SVR: """Read the model from the given file.""" return pickle.loads(model_file.read())
32a49bd37da2b6fb33a64d0ff334b8e323030169
3,633,316
def create_nonfixations(stimuli, fixations, index, adjust_n = True, adjust_history=True): """Create nonfixations from fixations for given index stimuli of different sizes will be rescaled to match the target stimulus """ x_factors, y_factors = calculate_nonfixation_factors(stimuli, index) non...
5c4462dd4bb5a3565158a9b2b085b88651d8b5a5
3,633,317
def get_commit_log(url, revnum): """Return the log message for a specific integer revision number.""" out = launchsvn("log --incremental -r%d %s" % (revnum, url)) return recode_stdout_to_file("".join(out[1:]))
fb079051926292fdabf69da99008c6dd5dab47c9
3,633,318
import torch def cov(x, rowvar=False, bias=False, ddof=None, aweights=None): """ Estimates covariance matrix like numpy.cov https://github.com/pytorch/pytorch/issues/19037 """ # ensure at least 2D if x.dim() == 1: x = x.view(-1, 1) # treat each column as a data point, each row as ...
376e89804374979fc21b1412d9db5ed588555d40
3,633,319
def tle_fmt_int(num, digits=5): """ Return an integer right-aligned string with DIGITS of precision, all blank if num=0 Ignores sign. """ if num: num = abs(num) else: return " "*digits string_int = "{:>{DIGITS}d}".format(num,DIGITS=digits) return string_int
8db7938e7a88e68c4a22013b10debbc4f5a9ca72
3,633,320
import six def SignalCollection(metasignals): # noqa: C901 """Class factory for ``SignalCollection`` objects.""" @six.add_metaclass(MetaCollection) class SignalCollection(object): _metasignals = metasignals def __init__(self, psr): self.psrname = psr.name # insta...
627959eb695979f1b8922a5da60ae4a88144ddb0
3,633,321
def get_status(): """Return classifier status.""" return 'ok'
84aedac3659ac2321867b02d3f6e7acb523923a3
3,633,322
def get_config_info() -> dict: """Gets the config from core sqlfluff and sqlfluff plugins and merges them.""" plugin_manager = get_plugin_manager() configs_info = plugin_manager.hook.get_configs_info() return { k: v for config_info_dict in configs_info for k, v in config_info_dict.items() }
c51f5853a54080189c37b1dea49da126d402854d
3,633,323
def landing_page(request, page): """Return resource landing page context.""" edit_resource = check_resource_mode(request) return get_page_context(page, request.user, resource_edit=edit_resource, request=request)
1a78491694a004ed784c50e8205c7341cbe58452
3,633,324
import torch def _smooth_l1_loss(pred: Tensor, target: Tensor, beta: float = 1.) -> Tensor: """(F.smooth_l1_loss()) :param pred: shape(N, In) :param target: shape(N, In) :param beta: smooth线 :return: ()""" diff = torch.abs(target - pred) return torch.mean(torch.where(diff < beta, 0.5 * d...
33cbfbf66360f9dd9d473b82c0f2103af19df676
3,633,325
import scipy def solve_assignment(weights, exclude_zero=False): """Finds matching that maximizes sum of edge weights. Args: weights: 2D array of edge weights. exclude_zero: Exclude pairs with zero weight from result. Returns: Integer array of pairs with shape [num_matches, 2]. """ rs, cs = sci...
d73d2c8b5dc7d5c5cbd08f38a4cc21d0b1ebf62a
3,633,326
import os import logging def _initXDG(): """Initialize config path per XDG basedir-spec and resolve the final location of state file storage. Returns: str: file path to state file as per XDG spec and current env. """ # per the XDG basedir-spec we adhere to $XDG_CONFIG_HOME if it's set, other...
edb3a0355b16a339dcb3112f4fdd99492eb48457
3,633,327
import os def get_stdout(jobname, jobid): """Get stdout for job <jobid> Returns: 200 OK: file (on success) 404 Not Found: Job not found (on NotFoundWarning) 404 Not Found: Result not found (on NotFoundWarning) 500 Internal Server Error (on error) """ user = set_user() ...
11c859cc2100ae08b7f2d1724de657c9ded54f1b
3,633,328
def stepwise_kpca(X, gamma, n_components): """ Implementation of a RBF kernel PCA. Arguments: X: A MxN dataset as NumPy array where the samples are stored as rows (M), and the attributes defined as columns (N). gamma: A free parameter (coefficient) for the RBF kernel. n_c...
3e0abd47e5527191e681f68ccb9ed71587a5adb2
3,633,329
import functools def make_val_and_grad_fn(value_fn): """Function decorator to compute both function value and gradient. For example: ``` @tff.math.make_val_and_grad_fn def quadratic(x): return tf.reduce_sum(scales * (x - minimum) ** 2, axis=-1) ``` Turns `quadratic` into a function that accepts a...
f08e889d62ce5d7e94e70bf96ae0ec8bca31f931
3,633,330
def showCatalog(): """This showCatalog handler will diplay the home page for both a user not logged in and one for a logged in user. """ categories = session.query(Category).order_by(asc(Category.name)) # Limit the query to a maximum of 10 and order by the most recent # items added, which is id...
e2a50c7478536fe573b6f7860e0976de3a832692
3,633,331
def is_fill_compute_seq(seq): """Test whether *seq* can be converted to a FillComputeSeq. True only if it is a FillCompute element or contains at least one such, and it is not a Source sequence. """ if is_source(seq): return False is_fcseq = False try: is_fcseq = any(map...
f6cca52b2ed7065ae950eca48071120c83a735bc
3,633,332
def upload_model(uploadfile, name=None): # noqa: E501 """upload_model # noqa: E501 :param uploadfile: The model YAML file to upload. Can be a GZip-compressed TAR file (.tgz, .tar.gz) or a YAML file (.yaml, .yml). Maximum size is 32MB. :type uploadfile: werkzeug.datastructures.FileStorage :param ...
95a759bc6d5cc806a8a8df1945816275784ab132
3,633,333
from mpl_toolkits.mplot3d import Axes3D import mcubes def visual_callback_3d(fig=None, plot_each=1): """ Returns a callback than can be passed as the argument `iter_callback` of `morphological_geodesic_active_contour` and `morphological_chan_vese` for visualizing the evolution of the levelsets. On...
1f69691a983f9afabbe53e761e95138a1aa64e40
3,633,334
def _erfint(x): """ Integral of the error function. Parameters ---------- x : float or array Argument. Returns ------- float or array Integral of the error function. """ return x * erf(x) - 1.0/np.sqrt(np.pi) * (1.0-np.exp(-x**2))
e397f62fb35caf5d71eaebd3eb9dc8ce0ba5c9d5
3,633,335
def model(x, n_pos, mask_miss1, mask_miss2, is_train=False, reuse=None, data_format='channels_last'): """Defines the entire pose estimation model.""" def _conv2d(x, c, filter_size, strides, act, padding, name): return Conv2d( x, c, filter_size, strides, act, padding, W_init=W_init, b_init=b...
895f9e8695b0564eb8fa3e2d5af320916d443025
3,633,336
from typing import Optional from typing import Union def zeros(shape: Optional[Union[int, tuple, list]] = None) -> 'ArrayInterval': """ Instantiate an `ArrayInterval` filled with zeros. Note: The difference from numpy is that the argument shape is optional. When shape is None, some operations a...
2d6348e327798b3019c6fd2d42827c64660cad02
3,633,337
def anova_total_mean_square(Ns, means, sigmas): """ This function performs an average over multiple sets of observations, each with its own standard deviation. For example: 5 simulations compute RMSDs+-Sigma of the same protein. What is the aggregate? See: http://www.burtonsys.com/climate/composite_stan...
b3cc0aa7fd66521f6692bd10c66b1e7b00e59566
3,633,338
def compute_lsb(n_bits, fsr_min, fsr_max, half_bit=None): """ Computes the least significant bit (LSB) magnitude in the stage MDAC and sub-ADC to achieve a desired full scale range (FSR). The input FSR and output FSR are assumed to be the same so only one value is returned. :param n_bits: Number of...
03520c71de04e654841c47c40a109431d315163d
3,633,339
def proximity_matrix(rf, X, normalize=True): """ Calculate proximity matrix :param rf: :param X: :param normalize: :return: """ leaves = rf.apply(X) n_trees = leaves.shape[1] prox_mat = np.zeros((leaves.shape[0], leaves.shape[0])) for i in range(n_trees): a = leaves...
781c08f242e52afa7430761124a344456c0efec1
3,633,340
def upload_to_s3_v2(local_path: str, bucket_name: str, object_name: str): """ path_output: local dir file path bucket_name: name of s3 bucket key_path: key path + file name = object name """ s3 = boto3.client("s3") response = s3.upload_file(local_path, bucket_name, object_name) return re...
844b1c07daeb44f49e1071516da0802d843d4790
3,633,341
def marks(category, mark=None, category_marks=None, public=False): """Assign marks to a test or suite of tests, grouped by a category.""" def decorator(test_item): if mark is None and category_marks is None: raise ValueError("One of mark or category_marks must be defined") test_item...
2d47a8df4f610dbc081dd57fce169e2f89b88ca4
3,633,342
import secrets def get_random_ua(): """return a random user-agent string from file""" # stop condition, file does not exists, not readable... # + file operation with open('headers.txt') as hbuffer: all = hbuffer.readlines() return secrets.choice(all).strip()
0d6a924c07bbad2398966bed590bf3307f5c475d
3,633,343
def is_nondecreasing(arr): """ Returns true if the sequence is non-decreasing. """ return all([x <= y for x, y in zip(arr, arr[1:])])
593ac54669ef217e258380bf41ce067935ee53f0
3,633,344
def underscore_to_camelcase(value): """ Converts underscore notation (something_named_this) to camelcase notation (somethingNamedThis) >>> underscore_to_camelcase('country_code') 'countryCode' >>> underscore_to_camelcase('country') 'country' >>> underscore_to_camelcase('price_GBP') 'pri...
94bb5c007d3b50112c62ca9b3e97c5bf4f155fff
3,633,345
def findCenter(S): """Find the approximate center atom of a structure. The center of the structure is the atom closest to (0.5, 0.5, 0.5) Returns the index of the atom. """ best = -1 bestd = len(S) center = [0.5, 0.5, 0.5] # the cannonical center for i in range(len(S)): d = S....
634945a5560b3791f3835f3da090decd1b06b933
3,633,346
def add_noise(rots, level): """adds random noise to a rotation matrix.""" noised_rots = [[np.random.uniform(-level,level,4)]*23]*rots.shape[0] noised_rots = Quaternions(np.array(noised_rots)) return rots+noised_rots
8886f11b90a2d0098b4776100ee9834d433012fb
3,633,347
def content_tree_update(request): """Returns all content of a given contenttree.""" assert request.contenttree.patched, "contenttree should be patched here..." # SANITIZE JSON DATA jsoncontent = request.json_body['content'] data = remove_unvalidated_fields(jsoncontent, peerreview_update_schema) ...
dcfc1932aa9fec431e138f205a143b792b6130f7
3,633,348
def compute_overlap_region(db_ref, db_new): """ Computes the overlapping/shared region between two images. Outputs: - Corner coordinates of the overlapping region in the SRS - Corresponding pixel indexes in both input images """ cornerCoord_ref = gdal.Info(db_ref, format='json')['co...
664f1825c75c0b33d0b0c5ba4686d132790ad363
3,633,349
from typing import List import math def _calculate_team_size_score( projects: List[dict], assignments: List[AssignmentTuple], project: dict, student: dict ) -> int: """Calculates the weighted score based on how far away from the average team size this project would be after assigning the student A...
47fcb0ea3feb637b558e6df10abd0aa993dbf965
3,633,350
import string def encode(data): """ Encodes a string to the 'cstring' encoding supported by the replay DTD. Args: data: string value to be encoded Returns: String containing the encoded value Raises: None """ chars = string.letters + string.digits + " ?!:." retur...
9fc3482c53eed42678aa3c7cbbf915c85b28cc68
3,633,351
import types from typing import Dict from typing import Any from typing import List def gen_frame_symbol( data: types.PulseInstruction, formatter: Dict[str, Any], device: device_info.DrawerBackendInfo ) -> List[drawings.TextData]: """Generate a frame change symbol with instruction meta data from provided fram...
8b38222cd294f42eb58dfcc36b10361ce7869a81
3,633,352
def leanlauncher_download_version(version=LATEST_VERSION, path=DEFAULT_INSTALL_PATH): """ Installs the specified version of Minecraft to the specified path Parameters: version (str): the version of Minecraft to be installed, by default the latest path (str): the path to install Minecraft to, by default ~...
35193ec3ca5d1ad1b23b84d35fec002997bb948e
3,633,353
def Weierstrass_Enneper(f, g, z, imag_unit=1j): """ Compute the Weierstrass Enneper parametrization for given 'Weierstrass data'. :param sympy expression f: h'/g, with h the height function :param sympy expression g: Gauss map. :param sympy variable z: Complex variable. :param imag_unit: Represe...
a47648e52600fd5fff37fb0ee7477b67c587ad0b
3,633,354
import os def build_lstm(seq_length): """Builds an LSTM in Keras.""" model = tf.keras.Sequential([ tf.keras.layers.Bidirectional( tf.keras.layers.LSTM(22), input_shape=(seq_length, 3)), # output_shape=(batch, 44) tf.keras.layers.Dense(4, activation="sigmoid") # (batch, 4) ]) ...
392fbb4491c5469499a714e4e4f2a8d65c62c1e3
3,633,355
def human_size(size_bytes): """ format a size in bytes into a 'human' file size, e.g. B, KB, MB, GB, TB, PB Note that bytes will be reported in whole numbers but KB and above will have greater precision. e.g. 43 B, 443 KB, 4.3 MB, 4.43 GB, etc """ suffixes_table = [('B', 0), ('KB', 1), ('MB', ...
d3489ee85c419711d82e35003426ef2915143c17
3,633,356
def html_color_to_rgba(html_colour, alpha): """ :param html_colour: Colour string like FF0088 :param alpha: Alpha value (opacity) :return: RGBA semitransparent version of colour for use in css """ html_colour = html_colour.upper() if html_colour[0] == '#': html_colour = html_colour[1...
4f28938aa89d62198cc3052a480e0e0744560a79
3,633,357
from typing import OrderedDict def _assign_category_colors(uses, cmap, use_colors=None, assigned_colors=None): """Set a dictionary of nice colors for the use blocks. Options allow specifing pre-defined elements for some categories.""" use_colors = OrderedDict() if use_colors is None else use_colors a...
085d0ca707990c84cd51464ee8f65f90500b7060
3,633,358
def GetClientContext(client_id, token): """Get context for the given client id. Get platform, os release, and arch contexts for the client. Args: client_id: The client_id of the host to use. token: Token to use for access. Returns: array of client_context strings """ client_context = [] clie...
3ecddfeb58e99d06951aab4fe359bc1291b43a2a
3,633,359
import math def calculate_slope_intercept(line): """ Calculating slope nd intercept for a line """ for x1, y1, x2, y2 in line: if x2-x1 == 0: return math.inf, 0 slope = (y2-y1)/(x2-x1) intercept = y1 - slope * x1 return slope, intercept
e21ff81a36cef7a995a98f7adf0302e8397a8139
3,633,360
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = {} card_title = "Welcome" speech_output = "I'm the Magic Conch Shell. Ask me a question" # If the user either does not reply to the welcome messag...
8a900efd3ef7129c1a9ff408e49591945dad83a1
3,633,361
from typing import Optional def rmcgs(A: np.ndarray, m: Optional[int] = None, r: Optional[int] = None) -> np.ndarray: """ Compute the product: B <- G * S * A where G has size m * r and elements from the standard normal distribution, rescaled by 1/sqrt(m), and S is a CountSketch of size r * n. The matrix ...
25325d1b2c75a07468fdce63fb5481da99c93105
3,633,362
def start_multi_svf(): """ This is function for satrt multi SVF GUI :return: result, details """ app.logger.info("Try to start multi SVF GUI for test") cli_rest_port_list = [] svf_num = int(request.form.get("svf_num")) try: cli_rest_port_list = StartMultiSvf(svf_num=svf_num, log...
1dd3585e5fcfa96d225645d382ee5ab064bc4073
3,633,363
import glob def get_files_by_pattern(root, pattern='a/b/*.ext', strip_root=False): """Optionally to only return matched sub paths.""" # Get the abspath of each directory images. ret = glob.glob(osp.join(root, pattern)) # exclude the root str, so the ret is spec['patterns']. such as ['images/train/*.jp...
905e4c4d08d228074a8036cdf5511f9eb7330f8c
3,633,364
import torch def gumbel_softmax(logits, temperature=1, hard=False): """ ST-gumple-softmax input: [*, n_class] return: flatten --> [*, n_class] an one-hot vector """ y = gumbel_softmax_sample(logits, temperature) if not hard: return y shape = y.size() _, ind = y.max(dim=-1...
4ce2b64115c4a4ce87677aa99e0422c00524c5d3
3,633,365
def _load_augmentation_aug_all(): """ Load image augmentation model """ def sometimes(aug): return iaa.Sometimes(0.5, aug) return iaa.Sequential( [ # apply the following augmenters to most images iaa.Fliplr(0.5), # horizontally flip 50% of all images ia...
e39a08f0166d8a6a379427a895b196891bf70fe1
3,633,366
import logging import traceback def zk_get_mq_servers(zookeeper_servers, logger = logging.getLogger(__name__)): """ Get list of mq servers from zookeeper :param zookeeper_servers: list of zookeeper servers :param logger: logger to use :return: list of mq servers or None """ mq_servers = No...
2201ac305ea1b44fe8baa0582bfc84bf39472dbe
3,633,367
import os def create_list_of_file_lists(possible_storage_locations, dir_path_to_files, dir_name_appendix): """This function creates a list of the files within each of the file storage locations so the user can inspect them to look for comparison options.""" # Output list of files files_to_compare = [] ...
11886751557e6994e3994f820dee21848584e265
3,633,368
from datetime import datetime def _make_todays_date() -> str: """ build today's date as a standard format """ return datetime.now().strftime("%a %d-%b")
fdb9bc420689081586ac19fe91a17ea871576d59
3,633,369
import re def add_review_suggestion_flags(df, text_col, result_col='result_binary'): """ attempt to add on some logical "manual review suggested" flags onto cases to reduce false positive/negative classifications. currently flags cases w...
e2083d65f54b82dd9eba19b6b2d32806e2cd086d
3,633,370
def create3DMatrix(data, trialTable, events, trialList, trialDur, fs, normalize, baselineDur=0.1): """ """ trials = trialTable.copy() trials = trials[trials['trialNum'].isin(trialList)] totalTrialNum = np.max(trials['trialNum']) m = trials.shape[0] print m, totalTrialNum electrodeNumber...
1627f506a03bb7f07c30c6c70581ac40bd64d7fc
3,633,371
def followed_list(username): """关注列表 """ current_user = models.get_current_user() user = models.get_user(username=username) page = request.args.get('page', 1, type=int) followed_list = user.followed.paginate(page, error_out=False) user_list = [i.followed for i in followed_list.items] ret...
5634ce5e7fc6b344f7ad2b3461e9f294cee225d3
3,633,372
def add_edge_degree(graph, k=3): """ Add k edges to defend based on top edge degree centrality entries :cite:`tong2012gelling`. :param graph: an undirected NetworkX graph :param k: number of edges to add :return: a list of edges to add """ info = defaultdict(list) info['added'] = get_c...
eded75ffc4eabe155124fe95023694df367f3d01
3,633,373
def number_of_fishers(): """ Prompt the user for the number of fishermen entering the draw.""" try: number = int(input("How many fishermen will enter the competition: ")) return number except ValueError: print("Please enter an integer for the number of competing fishermen")
bd3ff25865d67851c8a1742a8cfa808a317716f0
3,633,374
def plot_histogram(df, x, bins, xlabel=None, ylabel=None, title=None, figsize=(8, 5)): """ """ fig = plt.figure(figsize=figsize) ax = fig.gca() ax.hist(df[x], bins=bins, color='#8d1a93') ax.set_xlabel(xlabel, fontsize=16) ax.set_ylabel(ylabel, fontsize=16) ax.set_title(title, fontsize ...
42801361386edea3065974bdca2a589be0b964ef
3,633,375
def pygmo_gaco( criterion, x, lower_bounds, upper_bounds, *, population_size=None, batch_evaluator=None, n_cores=1, seed=None, discard_start_params=False, # stopping_max_iterations=STOPPING_MAX_ITERATIONS_GENETIC, kernel_size=63, speed_parameter_q=1.0, oracle=...
f8cf4e423b928393e4c028412da4f302376fb248
3,633,376
def get_project_by_id(project_id: str) -> Project: """ Get a project by its project_id, with project model and project data joined. :param project_id: project id of the project :return: Project with the project id """ query = ( Project.select(Project, ProjectModel, ProjectData) ...
2a8986c8e2541f43d30bee2cb1bcac14df68b716
3,633,377
def hist_similarity(image_1, image_2): """color hist based image similarity @param image_1: np.array(the first input image) @param image_2: np.array(the second input image) @return similarity: float(range from [0,1], the bigger the more similar) """ if image_1.ndim == 2 and image_2.ndim == ...
76358cff7b3a33f44fecefd289805a1fea88e1c4
3,633,378
def slotter_obj(): """ Return basic slotter object """ return Slotter()
f4b8805c8ca26bfc22da79b49a9c287c35428f86
3,633,379
def get_ncbi_enrichment_domains(): """ Find all domains matched to given node id, then return dictionary with all domains as result. All domains should have matching indices e.g. regulon[1] should be data from matching same node as uniprot[1]. """ # TODO: Validate incoming data using webargs...
2a60168fe953b00aca1870deb1692e018d9297ac
3,633,380
def gaussian(wavelength, w, sigma, amp=1., norm=True): """ Computes a gaussian for a given central wavelength, sigma and amp .. math:: G = \\frac{A}{\sigma \sqrt{2 \pi}} \exp{\left( \\frac{ (w - w_0)^2 }{2 \sigma^2 } \\right) } Args: wavelength (np.ndarray): wavelength array to cal...
7e757691fbe27641a4cfd983678dd0ccd2cbdfbd
3,633,381
def summarize_samples(samples, run_parallel): """Back compatibility for existing pipelines. Should be replaced with summary when ready. """ return samples
20c742e751f9ea1f783572f031fe144baf73293e
3,633,382
def get_keywords(string): """Get keywords for a given string. Args: string (str): A string to get keywords for. Returns: (list): A list of keywords. """ keywords = string.lower().split(' ') keywords = [x.strip() for x in keywords if x] keywords = list(set(keywords)) retur...
8d4e0781701dc3574583baf417c573967638e86f
3,633,383
def calc_mass_loading_factor(OIII_results, OIII_error, hbeta_results, hbeta_error, hbeta_no_outflow_results, hbeta_no_outflow_error, statistical_results, z, header): """ Calculates the mass loading factor eta = M_out/SFR Using the calc_sfr.calc_sfr_koffee and the calc_mass_outflow_rate functions ...
6504b328e749e98eb4b3612533701e562973d882
3,633,384
import os as _os from ..io import json as _json import _pickle def _write_calccache(calc_cache, key_fn, val_fn, json_too=False, comm=None): """ Write `caclcache`, a dictionary of compact polys, to disk in two files, one for the keys and one for the values. This function can be called by multiple rank...
d18f913c61c025acb294bda6b48457f57319ff8f
3,633,385
def truecircle(radius, rho): """Create a "true" circular mask with anti-aliasing. Parameters ---------- samples : `int`, optional number of samples in the square output array radius : `float`, optional radius of the shape in the square output array. radius=1 will fill the rho :...
e721d99d99b89ca24637e20d9577b2725cc29525
3,633,386
def distancia(ponto1, ponto2): """ Calcula a distância entre dois pontos """ xdif = ponto2.getx() - ponto1.getx() ydif = ponto2.gety() - ponto1.gety() dif = (xdif**2 + ydif**2)**0.5 return dif
36a980a1081133fb6496585c25cca5782ceef06d
3,633,387
import time def foo(x, sleep_time): """Dummy function for the tests""" time.sleep(sleep_time) return [{"type": "objective", "name": "objective", "value": x}]
3d55a0b0776acec0badd10e38be724afc3015c2f
3,633,388
def aug_ims(ims, fliplr=0, flipud=0, T=0): """Augment images with flips and transposition.""" ims_aug = np.array(ims, copy=True) for i in range(len(ims_aug)): if fliplr: # flip left right ims_aug[i] = np.fliplr(ims_aug[i]) if flipud: # flip up down ims_aug[i] = np.f...
59f8c44f0efcb70c17f828351b0f59787c3dd677
3,633,389
def bt_search(btree, key): """基于二叉树查询操作""" bt = btree while bt is not None: entry = bt.data if key < entry.key: bt = bt.left elif key > entry.key: bt = bt.right else: return entry.values return None
1b358087c10a4d0d6fe79b023340fafeafb81914
3,633,390
def make_reply(msgname, types, arguments, major): """Helper method for constructing a reply message from a list or tuple Parameters ---------- msgname : str Name of the reply message. types : list of kattypes The types of the reply message parameters (in order). arguments : list...
9c55089e1d6fe6b5a4345f444f2551a2c493f2e3
3,633,391
def empty_coord(): """Return an empty coordinate tensor representing 1 residue-level pad character.""" coord_padding = np.zeros((NUM_COORDS_PER_RES, 3)) coord_padding[:] = GLOBAL_PAD_CHAR return coord_padding
e4d8c4f24ebed354f5b083a4fc072e354c79a149
3,633,392
def grib_clone(msgid_src): """ @brief Create a copy of a message. Create a copy of a given message (\em msgid_src) resulting in a new message in memory (\em msgid_dest) identical to the original one. \b Examples: \ref grib_clone.py "grib_clone.py" @param msgid_src id of message to be cloned...
c01b3f626d11be8d218fdcd598e472c5fe748272
3,633,393
def layernorm(x, epsilon=1e-5, name='lnconv'): """Layer Normalization for conv. x must be [NCHW]""" shape = x.get_shape().as_list() with tf.variable_scope(name): beta = tf.get_variable("beta", [1, shape[1], 1, 1], initializer=tf.constant_initializer(0.)) gamma = tf.get_variable("gamma", [1, ...
9ae3bb3f6e0238de92f167bf45b05e3095541665
3,633,394
def create_graph_from_edges(edges): """ Create a graph from the `edges` """ G = nx.Graph() for e in edges: p1 = e[0] p2 = e[1] dist = LA.norm(np.array(p2) - np.array(p1)) G.add_edge(p1, p2, weight=dist) return G
ac06c424fcfde720fbb4457c0baced0a0a41567d
3,633,395
def far_field(frequency, radius, current, r, theta): """ Calculate the electric and magnetic far fields for a small circular loop. :param r: The range to the field point (m). :param theta: The angle to the field point (rad). :param frequency: The operating frequency (Hz). :param radius: The radi...
29940432e3e4dbc427398a18e1d026d9e4c205c3
3,633,396
def rng_laplace(lambd=1, trunc=None): """ Generate random numbers from a Laplace distribution Parameters ---------- lambd: float The scale of the distribution trunc: None, tuple Specifies whether the distribution is truncated. If it's not None then it must be a 2-tuple i...
d4ad9c23c5edef20babe59671e0464ef70ed74ae
3,633,397
from typing import Sequence from typing import Dict from typing import List def settings_to_connections( settings: amicus.options.Configuration, suffixes: Sequence[str]) -> Dict[str, List[str]]: """[summary] Args: settings (amicus.options.Configuration): [description] suffixes (Sequen...
e2ec469014d5d26848d011feda717191ae8c452b
3,633,398
def radec_from_pointing_object(pointing, # default output in degrees as_radians=False, as_string=False): """Astropy object to ICRS format as strings""" pnt_radec = pointing.transform_to(ICRS()) if as_string: ...
8cdd5c6671ccfd12624df88dfdfce0f6e0f41856
3,633,399