content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def GetIntervalVarFromMatlab(doc:NexDoc, MatrixName): """Imports the specified matrix containing intervals from Matlab.""" return NexRun("GetIntervalVarFromMatlab", locals())
74c9e836f08972dedab768af0fb348b65b22a121
42,300
def get_display_backend_size(): """Function to get the display backend size resolution :return : display resolution size as x,y :rtype : integer """ xc, yc = default_display_backend_size.split('x') x = int(xc) y = int(yc) return x, y
2f111dac7d49c9db79fb6319e14c2745b6bba8ea
42,301
from typing import Sequence from typing import Optional from typing import Mapping from typing import Tuple def _skip_block( lines: Sequence[bytes], sline: int, scol: int, sstr: bytes, estr: bytes, skips: Optional[Mapping[bytes, SkipFun]] = None, ) -> Optional[Tuple[int, int]]: """A generi...
83f7618be5543776a2d4e21876fecd41b2f8c39b
42,302
def get_database_connection(file_path, timeout=0.0): """ Gets a Connection to an Sqlite Database :param timeout: how long in seconds the driver will attempt to execute a statement before aborting. :param file_path: path to the sqlite database :return: a connection to the database """ db_co...
87a23c2df027d52cfa22a3bc0545b6fb441858eb
42,303
def cartesian_product(p_dict): """ Compute Cartesian product on parameter dict: In: {"number": [1,2,3], "color": ["orange","blue"] } Out: [ {"number": 1, "color": "orange"}, {"number": 1, "color": "blue"}, {"number": 2, "color": "orange"}, {"number": 2, "col...
36009609a77083a24bdf720f89c0bde1227db9c8
42,304
def normalize(vector, pre_computed=None): """Return the normalized version of a vector. Parameters ---------- vector : np.array pre_computed : float, optional The pre-computed norm for optimization. If not given, the norm will be computed. """ n = pre_computed if pre_compute...
ab0c2690ddacc29c43faafbc1b503e324373edba
42,305
def has_valid_padding(cipher_bytes): """ Decrypt cipher_bytes using AES CBC mode, then ... - return True if it has valid padding (PKCS7) - otherwise (catch an Exception for padding) return False """ # NOTE: This function is the padding oracle. It only return True or False on padding...
a58980bd49a9f00ddc2fdf1ff74ae76f4e538530
42,306
def account_unlock(account, token): """ Unlock account Note that if you call account_lock, you must always unlock account, otherwise it will be locked until process restart """ if config.keep_integrity: with lock_account_token: l = account_lockers.get(account.upper()) ...
528b9dc2a995d85b886400d4d8b0c90b63afb274
42,307
def activate_detection(timeout: int = 10000) -> str: """Active sound detection Parameter: timeout: duration of detection default 10 sec (value in milisec) """ msg = 'Sound detected in the room !' no_sound_msg = "No sound detected in the room." # waiting for edge cases for sete...
f0af4701ae27d4e00f4a15e61caea55e355a99b6
42,308
async def get_ohlcv(ticker: str = "KRW-BTC", interval: str = "day", count: int = 200, to: str = None, contain_req: bool = False) -> tuple or DataFrame: """Candle data request Args: ticker (str, optional): Coin's ticker. De...
d391ee4f131598bae9dcb1d816fc755b93e87695
42,309
def reset_window_environment() -> BoxLayout: """Remove PythonHere app widgets and styles.""" # import Window inside function to avoid early loading of the app config from kivy.core.window import Window # pylint: disable=import-outside-toplevel for widget in Window.children: widget.clear_widget...
47bbb3cfb994c9c6bfae0a0c83c4c8c15701da1d
42,310
from typing import Iterable from typing import Callable from typing import Iterator import math def partition_sequentially( items: Iterable[_T], *, key: Callable[[_T], str], size_target: int, size_max: int | None = None, ) -> Iterator[list[_T]]: """Stably partitions the given items into batche...
7cd9f2db83c145f1b7b3d6cf75c33508f710cf31
42,311
import torch def quad_kappa_loss(input, targets, y_pow=1, eps=1e-15): """ https://github.com/JeffreyDF/kaggle_diabetic_retinopathy/blob/master/losses.py#L22 :param input: :param targets: :param y_pow: :param eps: :return: """ batch_size = input.size(0) num_ratings = 5 asse...
f7aab107d9264384f04f1b8ba331223adcb495aa
42,312
def parse_response(xml): """ Converts the response into an XML element """ # Uncomment for debugging # print("Parsing xml: {}".format(xml)) return ET.fromstring(xml)
d5894faaf7c1d872e6cc6cffb35476d2fd89384e
42,313
def clamp_remaining(max_timeout: float) -> float: """Return the remaining timeout clamped to a max value.""" timeout = remaining() if timeout is None: return max_timeout return min(timeout, max_timeout)
e16b1ccb3c6168aa82159e34d477e9ff3efba306
42,314
def is_tag_exists( lf_client, account_id: str, key: str, ) -> bool: """ Check if an Lake Formation tag exists or not Ref: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/lakeformation.html#LakeFormation.Client.get_lf_tag """ try: lf_client.get_lf_tag(C...
9f323ee97d4dfc67b183f5bcdc46229fd328eff6
42,315
def browse_repository(script, project, repository): """ Gets the list of repositories for the specified project :param script: A TestScript instance :type script: TestScript :param project: The project for the repository :type project: str :param repository: The repository to browse :typ...
c3c98c625b3ed0e1de3e795861eb29c9825ef5e8
42,316
def baseline(saver, model, y, data, T, lr, lmd=None, name='baseline'): # TODO other optimizers? """ BASELINE EXECUTION (valid also for oracle and final training, with optimized values of lambda) :param saver: `Saver` object (can be None) :param name: optional name for the saver :param data:...
12e6e0d4e1de9b86d732e24c3d8878e1eccd75c7
42,317
import collections def build_node_statistics(nodes, images): """Build a dictionary of cache statistics about a group of nodes.""" # Generic statistics applicable to all groups of nodes. node_statistics = { 'provisioned': len(list(filter(lambda n: n.provisioned, nodes))), 'not provisioned':...
6f1b6a7128a088168f3d31054458275d5f13df53
42,318
from typing import Union from typing import Sequence def track_local_coordinate_systems( markers: TimeSeries, /, segments: Union[str, Sequence[str]], *, method: int = 1) -> TimeSeries: """ Create local coordinate system definitions based on static markers. Paramete...
b7a2d7f113eec550e0c59f3be1eab1bc99d9e188
42,319
def select_white(image): """ Threshold to select a white color objects :param image: Undistorted image :return: Thresholded image Ref: Udacity reviewer suggestion """ lower = np.array([210, 210, 210]) upper = np.array([255, 255, 255]) mask = cv2.inRange(image, lower, upper) retur...
f51995cf0d74668c383c280e2169817dbfa31d87
42,320
def is_libpsp(): """Was libbinding successfully loaded in this module?""" return __is_libpsp__
73844759e0b4f9dbd36bdd2f1c2b9709ce387b2f
42,321
def run_batch(args: dict) -> int: """Runs a batch operation for the given arguments.""" batcher.run_project( project_directory=args.get('project_directory'), log_path=args.get('logging_path'), output_directory=args.get('output_directory'), shared_data=load_shared_data(args.get('s...
1ad412c206e6bb67c8754476ec6cf24ba1a4c0a1
42,322
from re import S def prepare(statement, variables, extra_data={}): """ Set variable in statement and return the prepared statement """ template = Template(statement) data = extra_data.copy() for variable in variables: if variable == S.LOGIN_VARIABLE: data[variable] = Settin...
cbc570f4ec020ee87674267f8746bdcbff7880e9
42,323
def privatekey_to_publickey(private_key_bin: bytes) -> bytes: """ Returns public key in bitcoins 'bin' encoding. """ if not ishash(private_key_bin): raise ValueError('private_key_bin format mismatch. maybe hex encoded?') return keys.PrivateKey(private_key_bin).public_key.to_bytes()
541b3791017df8b72825ee647f436ac4adf32618
42,324
def single_value_rnn_regressor(num_units, sequence_feature_columns, context_feature_columns=None, cell_type='basic_rnn', num_rnn_layers=1, optimizer_type='SGD', ...
c1af7a4fa74d8f66052fba9a2a221d441a0b2d43
42,325
import torch import copy def k_fold( n_splits, epochs, batch_size, transforms, criterion, model, dataset, device): """ Perform K-fold cross validation. Parameters ---------- n_splits: int Number of splits to make of the data....
e4c596756f1980c6c32150caffb17ec5be0cd0f1
42,326
def render_instruction(name, content): """ Render an arbitrary in-line instruction with the given name and content """ return ':{}: {}'.format(name, content)
2200ab1c865dbad871395476fc2227cc8995b3d1
42,327
def check_nan_columns(df: pd.DataFrame) -> pd.Series: """Check whether the columns of the DataFrame object contain missing values. Arguement: df: the DataFrame object to be checked whether its columns contain the missing values Return: _: the Series object whose values are True ...
414c7ad9a7387a01bc7c6e74a8304f9c5cb9f45f
42,328
def site_time() -> Timestamp: """Wrapper for site server time.""" return _site.server_time()
737a92448b4aa72eb491b6b6d5e294c8ec025768
42,329
def contract_id(owner_id, nonce): """ Compute the contract id of a contract :param owner_id: the account creating the conctract :param nonce: the nonce of the contract creation transaction """ return hash_encode("ct", decode(owner_id) + _int(nonce))
9bc6352acf7ed5279f6ac492f9b519a05222fb22
42,330
def json_patch_link(url, title, description): """Generate a json patch Link object.""" return serializers.Link( url=url, title=title, description=description + " (Using an RFC6902 JSON Patch)", action="patch", )
a7cf77287fc32f3bba3c2a2372520de07437d0c3
42,331
import json def sign_up_post(request: HttpRequest, *args, **kwargs): """用户邮箱验证注册。""" body = json.loads(request.body) if keys_missed(body, ['email', 'password', 'code']): response = HttpResponse(MSG_BAD_REQUEST, status=400) else: exists = User.objects.filter(email=body['email']) ...
abf60ec83a77703e21b70b18312859687e3b1bae
42,332
def balanced_decomp_unsafe(sequence, open_to_close): """ Same as :func:`balanced_decomp` but assumes that ``sequence`` is valid balanced sequence in order to execute faster. """ gen = generate_balance_unsafe(sequence, open_to_close) bal_curr, tok_curr = next(gen) pop_open = sequence[0:1] ...
524dc6074c06e5d3927789b8a3ee15afafe8376d
42,333
def parse(args: list = None) -> dict: """ Parses the command line arguments and returns a dictionary containing the results. :param args: The command line arguments to parse. If None, the system command line arguments will be used instead. """ parser = ArgumentParser(description...
93c8abb53b855dbcbad02809528746b58367bc62
42,334
def GetPlayerNames(player_ids): """Loads player_ids into Steam Account cache. This will take in a list of account ids and load the Steam Accounts into db cache from the Steam API. Args: player_ids (list): List of SteamID64s to lookup. Returns: dict. Returns dict of player_i...
f06507c61eafd9eb23410ac439a9c5606943e4dd
42,335
def _verify_node(cmd): """Verify that the node command exists and is at least the minimum supported version of node. Parameters ---------- cmd : string Node command to verify (i.e 'node').""" try: out, err, return_code = get_output_error_code([cmd, '--version']) except OSErr...
1d84124c75d35316da011f00e194e5693b538ff9
42,336
def random_crop_info(h, w, border_ratio): """ :return: random cropsize 原尺寸 * random scale [0.9, 1.0, 1.1] random center 设置 border 随机取中心 """ # h,w: ori image size if np.random.random() < 1.0: # random scale random_scale = np.random.choice(np.arange(0.8, 1.2, 0.1)) ...
5646717cf910eedf98df124978b401984f2e1e43
42,337
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) if unload_ok: entry_data = hass.data[DOMAIN].pop(entry.entry_id) vlc = entry_data[DATA_VLC] awa...
08c25c611b677435339b13b64bc268b7e5607390
42,338
def _create_pem_projected_volume(cert_secret_name): """ Create volume for pem certificate """ items = [client.V1KeyToPath(key="tls.crt", path="keystore.pem"), client.V1KeyToPath(key="ca.crt", path="truststore.pem"), client.V1KeyToPath(key="tls.key", path="key.pem")] sec_pro...
c7fa4198b3f35e832a6c35fafc41d48df88c1e4d
42,339
def assign_random(scores, vector_quotas=None, pi_init=None, sigma_init=None, envy_init=None): """ Assigns refugee at random Inputs: assignment: A NxM matrix describing assignment scores: The scoring matrix describing refugee-locality integration scores refugee: The index of the refuge...
bf8db44acd672f7145444cf296496b9f2ca3b787
42,340
def get_alerts(alert_id=None, filt=None): """In short: Get one or many alerts. The client uses the get_alerts command to get alert information. If the command sent by the client was valid, the connector will reply with a list of alerts to the client. """ root = etree.Element("get_alerts") i...
84f7389d12b103d7ec0ad4c8bde9a66d7ecdac03
42,341
def similar(app_id, detailed=False, hl="en", gl="us"): """Sends a GET request, follows the redirect, and retrieves a list of applications similar to the specified app. :param app_id: the app to retrieve details from, e.g. 'com.nintendo.zaaa' :param detailed: if True, sends request per app for its full ...
4e3532f4b9d9f3857c67ada633576052bd2aef6a
42,342
def gcd(x, y): """ greatest common divisor """ while y != 0: (x, y) = (y, x % y) return x
5ed0e0cd20e6a73bca895fc4ea76ea65f71fb9f3
42,343
def parse_agent_req_file(contents): """ Returns a dictionary mapping {check-package-name --> pinned_version} from the given file contents. We can assume lines are in the form: datadog-active-directory==1.1.1; sys_platform == 'win32' """ catalog = {} for line in contents.splitlines(): ...
7d3516327ffaf147ee85c150921c876ba5ee2980
42,344
def evaluate_metrics_stopping(model_list, metric_name, bigger_is_better, search_criteria, possible_model_number): """ This function given a list of dict that contains the value of metric_name will manually go through the early stopping condition and see if the randomized grid search will give us the correct...
69665b6b4406519075d029bbb86de38aacc98f31
42,345
def svn_wc_external_item2_create(*args): """svn_wc_external_item2_create(apr_pool_t pool) -> svn_error_t""" return _wc.svn_wc_external_item2_create(*args)
ea103aff72e382d14440d638bbd3f4fecbe81665
42,346
def __get_recruiter_hamburger_menu_items(): """ allows multiple templates to pull the same menu list items from one source of truth Returns(str): html5 list elements for the hamburger menu """ return \ "<li><a href='/jobs'><span class='glyphicon glyphicon-briefcase'></span> &nbsp; Jobs</a...
31556527b117d2fca8c86ae4750b63df7d9f34e2
42,347
def SampleSum(dists, n): """Draws a sample of sums from a list of distributions. dists: sequence of Pmf or Cdf objects n: sample size returns: new Pmf of sums """ pmf = Pmf(RandomSum(dists) for i in range(n)) return pmf
76dce20f47ebc598ca8ce007712b2abc15ce4a4f
42,348
def transform(shape, from_crs, to_crs): """Transform a shape from one crs to another.""" project = partial(pyproj.transform, from_crs, to_crs) return s_transform(project, shape)
2ae02747dd75df7cf435ea2d8fe106ee270d326b
42,349
from heapq import heappush, heappop def optimum_policy2D(): """ This algorithm keeps track of all the paths through the grid. It always expands the least expensive path, thus avoiding unnecessary work on paths that are too expensive to follow. A path starts at the initial position. Each time a ne...
ef09e2a598ce3620c95246cb06a9843748c8cb7d
42,350
def make_etag(hasher): """Build etag function based on `hasher` algorithm.""" def etag(buf): h = hasher() for chunk in buf: h.update(chunk) return '"' + h.hexdigest() + '"' return etag
31963ebacf886298a60e383d2a0c278293a59012
42,351
def Siamese(vocab_size=41699, d_model=128, mode='train'): """Returns a Siamese model. Args: vocab_size (int, optional): Length of the vocabulary. Defaults to len(vocab). d_model (int, optional): Depth of the model. Defaults to 128. mode (str, optional): 'train', 'eval' or 'predict', pre...
85e0d572e5b39ef3ef907d01e082b507a3470997
42,352
def indexof(ilist, item): """ returns the index of item in the list """ i = 0 for list_item in ilist: list_item = list_item.strip() if list_item == item: return i i += 1 print("ERROR failed to parse config, can't find item:", item) exit(-4)
e6b24d8b6455433f7b6afd824045fbec0dfabfc6
42,353
def im(data): """ imshow puts eta (first axis) on y-axis inverts the y-axis resulting in a plot like W | | eta | | E v --------> N xi S So flipping brings us to W | | eta | | E v --------> S xi N And rotation to N | | xi | | S v --------> E xi W """ retur...
4e173bb1c9fcc7708d7a3cf9e0cc5103bd4be7d9
42,354
def update_loc_dict(new_file_name, file_name="loc_dict"): """ Updates loc_dict with locations new file and saves it as python object. :param new_file_name: string, name of file with new data :param file_name: string, name of file to update, default "loc_dict" :return loc_dict: dictionary, keys - loc...
5167092aada49252643f1c3012c36213ff0ea6bc
42,355
def make_1397(pc, target_list, skill_id, skill_lv, damage_list, color_list): """スキル使用結果通知(対象:自分)""" if not target_list: target_list = () damage_list = () color_list = () else: assert len(target_list) == len(damage_list) assert len(damage_list) == len(color_list) i = len(target_list) result = pack_short(s...
fd06bd507e930063495d4a1d91e17b47b5eb5cab
42,356
def _contains(shape, x, y): """ Try to use the shape's contains method directly on XY. Does not currently work on anything. """ raise NotImplementedError() return shape.contains((x, y))
146178e2ac8101b306228a89de2d72493ec7a270
42,357
from typing import Optional def _api_tier_validator(value: str) -> Optional[str]: """ Determines if input value is a valid API tier """ try: KrakenAPITier(value.upper()) except ValueError: return "No such Kraken API Tier."
0d618afa4aff17ba3c4e1a097ac218976e777abf
42,358
def ecdf(x): """ Generate empirical CDF """ n = len(x) xs = np.sort(x) ys = np.arange(1, n+1)/n return xs, ys
41f990dbfdf2dcf80dcaaf8db6600f6c0f727bcd
42,359
def _get_pyramid(img, num_scales, pooling_fn=tf.nn.avg_pool2d): """Generates a pyramid from the input image/tensor at different scales. This function behaves similarly to `tfg.image.pyramid.split()`. Instead of using an image resize operation, it uses average pooling to give each input pixel equal weight in c...
845c541901a448d0fb3cc3a042bd9f4f6d666954
42,360
def get_partner_rows(*args, **kwargs): """ 获取列表 :param args: :param kwargs: :return: """ return db_instance.get_rows(AAPartner, *args, **kwargs)
962dc226d6fa56d6219984c688fe625db5e2ebff
42,361
def random_val(matrix,mean,std): """Function to apply normally distributed random noise to the matrix that represents sarcomeres as voxels.""" mat = np.random.normal(mean,std,matrix.shape) matrix += mat return matrix
baa36e2bd5ae92f1f02aa5ed5860e25bd5e48c1c
42,362
def verificacion(autor): """ Se utiliza el metodo de la clase Contribucion para obtener la cantidad de objetos instanciados. Se inicialista una lista de calificaciones como lista vacia por cada contribucion se realiza el llamado al metodo del autor para verificar calificaci...
488cea0153c2b51e33e2bd90c04a6338e8eac484
42,363
import gzip import struct def load_mnist_labels(file_name, onehot, num_classes=10): """Load MNIST image labels.""" with gzip.open(file_name, 'rb') as mnist_file: _, num_labels = struct.unpack( ">II", mnist_file.read(8)) buf = mnist_file.read(num_labels) labels = np.frombuff...
d1ed83386750af081ea4c5a23643a5b17778e5f4
42,364
import os def preprocess(instr, cpp_path='cpp', cpp_args='', include_paths=[], defines=[]): """ Preprocess a a string using cpp. instr: c code to preprocess. cpp_path: cpp_args: Refer to the documentation of parse_file for the meaning of these arguments....
df0bb205c9ec45d674d20684689d0fa526202442
42,365
def sinr( received_signal_dbm: float, received_interference_dbm: float, noise_floor_dbm: float, ): """ Calculate the Signal Interference Noise Ratio in decibels. That means that $10^{sinr/10} . (noise+interference) = signal$ Should always hold. """ # We need to convert to watts...
4f7dd997ce76574bf7c3bad04efb94dca850b704
42,366
def load_services(config, bus, path=None): """Load builtin services as well as service plugins The builtin service folder is scanned (or a folder indicated by the path parameter) for services and plugins registered with the "mycroft.plugin.audioservice" entrypoint group. Args: config: conf...
ab92e41492ffc9fd3245d30a538c3fcfebaad8e4
42,367
def generateInput_v4(fout=False): """ Generate complete observation matrix """ des, X = generate_corina_features('ca') pvt = X[:,2] # poverty index of each CA popul = X[:,0].reshape(X.shape[0],1) # poi_cnt = getFourSquareCount() # poi_cnt = np.divide(poi_cnt, popul) * 10000 ...
1c437669f706b54caa2891668f6efc2288167299
42,368
def validate_gwdevice_list(data, valid_values=None): """Validate the list of devices.""" if not data: # Devices must be provided msg = _("Cannot create a gateway with an empty device list") return msg try: for device in data: interface_data = device.get(constants....
7b87dba712d18c7577ef70fc6190806fbb702b95
42,369
import sys from importlib import import_module import os def load_log2seq(conf): """Return parser object log2seq.LogParser . Amulog accepts following additional keys extracted by log2seq. - host: device hostname, mandatory - lid: Log message identifier, optional The configuration is described in...
6b035d3a383f4f8da2cd736ede699671133c3efa
42,370
from typing import List from typing import Tuple def deflate_spans( spans: List[Tuple[int, int, int]] ) -> List[List[Tuple[int, int]]]: """[summary] Args: spans (List[Tuple[int, int, int]]): [description] Returns: List[List[Tuple[int, int]]]: [description] """ # assuming last...
037c11b0c5d4707b2d19a0b0cc457a93908f5186
42,371
def correlation_coeff(score, gold_data): """ It will take the list of similarity score and calculates pearson correlation and spearman correlation. Finally, it returns the score as per competition standard. """ a = spearmanr(score, gold_data)[0] b = pearsonr(score, gold_data)[0] return (2*a...
82784c270c039af087887a4b7a8b0faaa41b36d7
42,372
def operate_status_template(open_now: bool) -> tuple: """Flex Message 餐廳營業狀況 Args: open_now (bool): 營業中 Returns: tuple: (營業狀況, 營業文字顏色) """ if open_now: operate_status = { "type": "text", "text": "營業中", "size": "xs", "color": "...
366d291b5e847192401f76f0c8a560c02452cef7
42,373
def paramset_to_rootnames(paramset): """ Generates parameter names for parameters in the set as ROOT would do. Args: paramset (:obj:`pyhf.paramsets.paramset`): The parameter set. Returns: :obj:`List[str]` or :obj:`str`: The generated parameter names (for the non-scalar/scalar c...
0fc4732a7accff55f8015c5b46cb1c44c002ef18
42,374
import base64 import json from datetime import datetime def create_access_token(token): # type: (str) -> azure.core.credentials.AccessToken """Creates an instance of azure.core.credentials.AccessToken from a string token. The input string is jwt token in the following form: <token_header>.<token_paylo...
2cad1e621c717305742aaae9b6b101973f4ca23e
42,375
def get_resolution(token): """Parse a <resolution> token in ddpx.""" if token.type == 'dimension': factor = RESOLUTION_TO_DPPX.get(token.unit) if factor is not None: return token.value * factor
2bb6e05610ebdb5275c7ed4910bb980e99edc564
42,376
from datetime import datetime def format_date(date_string, date_format): """ """ formatted_date = datetime.datetime.strptime(date_string, date_format) year_directives = ['%y', '%Y', '%c', '%x'] contains_year = any(directive in date_format for directive in year_directives) if not contains_ye...
7445438c83822f5407963375aa633061304906bd
42,377
def query_neo_nodes(port, pwd): """ 查询所有的节点 Args: port: pwd: Returns: """ graph = Graph(f"bolt://{NEO_HOST}:" + port, password=pwd) nodes_matcher = NodeMatcher(graph) nodes = list(nodes_matcher.match()) return {node.identity: node["s_name"] for node in nodes}
c594f108ca1fa0b3704f3ad5458a850b9984c082
42,378
def __select_constraints_pairwise(data, labels, samples, samples_labels, n_neighbors): """select constraints of the form x-y where x,y have different labels""" constraints = [] # nearest neighbors are selected from the entire set neighbors = {} data_by_label = {} smallest_norm = np.inf for i...
03b01a8aa47528822ab5a398594c29a2f2ef7312
42,379
from typing import Callable from typing import Iterable from typing import Tuple def take_while(predicate: Callable, iterable: Iterable) -> Tuple: """ Constructs a iterable list by taking elements from ``iterable`` while ``predicate`` is true, Stop taking after the first element falsifies the predicate. ...
01a32a6484e209dcc48d6f9e67f4fd8ba9b1270b
42,380
def comprobar_restricciones_check(parameters, check): """Comprueba las restricciones CHECK :param parameters: tipo de dato Number: ["Number", nombre_col, precision, escala] tipo de dato String: ["String", nombre_col, varying, max_size] :param check: campo check de la sent...
69874b8f21f66586b1d971e4d7f87ae253e681b3
42,381
from typing import Optional async def check_response_route( uid: int = Query.i(description="user id", gt=10, lt=1000), email: Optional[str] = Query.i(default="example@xxx.com", description="user email"), user_name: str = Query.i(description="user name", min_length=2, max_length=4), age: int = Query.i(...
ce889fa36b1cd0d78d72c2f636cebbc66d1a1689
42,382
import sys import os def cpu_count(): """:return:number of CPUs in the system :note: inspired by multiprocessing""" num = 0 try: if sys.platform == 'win32': num = int(os.environ['NUMBER_OF_PROCESSORS']) elif 'bsd' in sys.platform or sys.platform == 'darwin': num...
d19d54432f4ec7336e51c5f6e381b8d835004e74
42,383
def _n_dist(v, n, randomize=False): """ Creates grouping factor with distributed excess elements """ len_v = float(len(v)) divisor = len_v / n # Create range the length of v (+1 because it starts at 0) # Divide each element and get everything but the first element (0) v_divided = ...
5ff74c95a78acbe4e6415a85584dc80e848b9758
42,384
def forward_sensitivity_model(t, s, args): """ This solves a system of (P+1)*N differential equations (needs to solve the original ODE in conjunction) """ y = s.reshape((2, 5))[:, 0] sensitivities = s.reshape((2, 5))[:, 1:] del_f__del_u = jax.jacobian(model, argnums=1)(t, y, args) del_f...
d565c1f1a82613082931c59a965f1c261a2c85ad
42,385
def create_code_index(model, **kwargs): """ Creates an value/id index of the model args: model: datatstore class, babel datastore table kwargs: dict, filters to be applied to query returns: idx: dict, {column value: datastore id} """ idx = {} with session_scope() as s...
5c98aa00b0262572bff29079a50ce2db82a5e369
42,386
def get_exploration_recommendations(exp_id): """Gets a list of ids of at most 10 recommended explorations to play after completing the exploration keyed by exp_id. Args: exp_id: str. The ID of the exploration for which to get the recommendations. Returns: list(str). List of...
fff4f812086dfa01161a15e1409d876010302f5f
42,387
def BNNoReLU(x, name=None): """ A shorthand of BatchNormalization. """ if name is None: x = BatchNorm('bn', x) else: x = BatchNorm(name, x) return x
af0c0cbe3a8c78f207afd54c4adf7799d67200db
42,388
def symPT(x, Ps, Ts, window_half): """ Measure of asymmetry between oscillatory peaks and troughs Parameters ---------- x : array-like 1d voltage time series Ps : array-like 1d time points of oscillatory peaks Ts : array-like 1d time points of oscillatory troughs ...
49ec586d8925e0154313a91747d3c7ea5d8780e2
42,389
import time def get_items_serial_number(prefix, obj): """获取物品唯一货号""" date_str = time.strftime("%Y%m%d%H%M%S", time.localtime(time.time())) # 生成一个固定6位数的流水号 objmodel = obj.objects.last() serial_number = objmodel.id if objmodel else 0 serial_number = "{0:06d}".format(serial_number + 1) return...
c8482b0debe680b36845d3ee933d0771c4efe05f
42,390
import time def tmtuple(tmsecs=None): """ Return a time tuple. This is currently an alias for gmtime(), but allows later tweaking. """ # avoid problems due to timezones etc. - especially a underflow if -86400 <= tmsecs <= 86400: # if we are around 0, we maybe had tmsecs = 0 ...
5c848afca1247e55215a3858a774419a6b6c8961
42,391
def make_gaussian_prf(size): """Generate various pRFs based on 2d Gaussian kernel with different parameters. Return a pRF matrixs which shape is (size, size, size*size*fwhm#) """ fwhm_num = 10 fwhms = np.arange(1, fwhm_num+1) prfs = np.zeros((size, size, size*size*fwhm_num)) for k in r...
bb8d2058508652426a99b609d188c75160a99bb7
42,392
def split(array, nrows, ncols): """Split a matrix into sub-matrices.""" r, h = array.shape return (array.reshape(h // nrows, nrows, -1, ncols) .swapaxes(1, 2) .reshape(-1, nrows, ncols))
be105c055c08288ff3d387f34975bda223030faf
42,393
import os import time def write_patches_data_to_file(patches_data_file, patch_shape, data_file, patch_overlap=0, indices=None): """ write all the patches (data, GT, indices, and normalization factors (mean, std)) to a file, using multiple processes executing 'write_patches_d...
a784ee6e2510f691ef53917258756b86ff92d218
42,394
from typing import Optional from typing import Union from typing import Tuple from typing import List def enumerate_blobs_to_file( output_file: str, account_name: str, container_name: str, sas_token: Optional[str] = None, blob_prefix: Optional[str] = None, blob_suffix: ...
595b464efb2a8ba7a96562688bcba8064ffb4f18
42,395
def origin_trial_enabled_function_name(definition_or_member): """Returns the name of the OriginTrials enabled function. An exception is raised if both the OriginTrialEnabled and RuntimeEnabled extended attributes are applied to the same IDL member. Only one of the two attributes can be applied to any m...
6284f1a3ab8773382f3cc2a1e121cd68592b7553
42,396
def validate_yn(answer): """Validate y/n prompts :param answer: User response to y/n prompt. If a boolean value is passed (e.g. if a prompt received parsed_input=True), it is treated as a y/n answer and considered valid input :return: True if user answered yes, False if user answered no ...
4b41cfeeca6eebc6f287c37090379d7423bc6aca
42,397
from httplib import HTTPConnection def wget(URL): """Upload a file across the network using HTTP protocol data: content of the file to upload. URL: e.g. "http://id14timing3.cars.aps.anl.gov/tmp/test.txt" """ URL = URL.replace("http://","") ip_address = URL.split("/")[0] script = "/"+"/".jo...
0f97206943941aefa0d542931a57f68a3fadfdc5
42,398
def other_document(database, document): """ Returns: Document: Copy of 'document' fixture, but with an additional revision. """ other_document = Document(database, document.doc_id) other_document.retrieve() other_document.data['more'] = 'stuff' other_document.create_update() retu...
0e9936408c4618aceaec853d42af2c5799bcd83b
42,399