content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def resolve_ref(spec: dict, ref: str) -> dict: """ Parameters ---------- spec full openapi spec of the app ref reference to look up Returns ------- Part of the schema at the ref """ if not ref.startswith("#/"): raise ValueError(f"Invalid OpenAPI ref {ref}...
9cd9f1cb4596baf5f0840d11294830f459d19385
626,241
def ConstructViceroyBuildDetailsURL(build_id): """Return the dashboard (viceroy) URL for this run. Args: build_id: CIDB id for the master build. Returns: The fully formed URL. """ _link = ('https://viceroy.corp.google.com/' 'chromeos/build_details?build_id=%(build_id)s') return _link % ...
94eca6bb5b089e2379f814195954317ef7181bb1
626,242
def get_object(context): """ Get an object from the context or view. """ object = None view = context.get("view") if view: # View is more reliable then an 'object' variable in the context. # Works if this is a SingleObjectMixin object = getattr(view, "object", None) ...
27f4b346d6e50d9bfe684643133d69511ea9ca22
626,243
def get_next_speaker_and_last_speaker(conversation_posts, author, partner): """ Input: All the current posts in a 2 speaker conversation The two speakers Output: Based on the given list of posts, return who speaks next and who spoke last """ last_speaker = author next_spe...
bb1e06d7f2556eef03f1341ef82349d21dec10ae
626,244
import hashlib def get_hash(file_path: str, hash_func=hashlib.md5) -> str: """ :param file_path: Путь к файлу. :param hash_func: Хэш функция. :return: Хэш файла. """ with open(file_path, "rb") as f: img_hash = hash_func() # Читаем файл частями while chunk := f.read(8192...
f2296966c8d94c61598be7a2257a064dfd4c904e
626,246
def detect(stream): """Returns True if given stream is valid IMS Content Package.""" try: return True except (TypeError): return False
81538e51e2396dce4c19768507ada3622f8b951c
626,247
def interaction_lifeline_group(parent, element): """Add lifeline to interaction.""" element.interaction = parent return True
71b9cb82efc3a16d03c55f91b9090f23ea37a1d4
626,248
def get_schema(buf): """ Extract the schema code embedded in the buffer :param buf: The raw buffer of the FlatBuffers message. :return: The schema name """ return buf[4:8].decode("utf-8")
de99cb7347b39239ee57976b2d3c9c4c4c172040
626,249
def null_heuristic(state): """Admissible, but trivial heuristic""" return 0
890a2f3c42160ea7f0cc3ea6d2794584841d9b2c
626,250
def make_cybox_object(ctype, desc = "", extended_properties = {}): """ makes a cybox object (that goes in cybox list then container) """ cybox_object = {} cybox_object["type"] = ctype cybox_object['description'] = desc cybox_object['extended_properties'] = extended_properties ret...
0c18b7727a8e672de350dbea9feaf7912b9fb81b
626,252
def default_evaluation_params(): """ default_evaluation_params: Default parameters to use for the validation and evaluation. """ return { 'AREA_RECALL_CONSTRAINT': 0.8, 'AREA_PRECISION_CONSTRAINT': 0.4, 'EV_PARAM_IND_CENTER_DIFF_THR': 1, 'MTYPE_OO_O': 1., 'MTY...
a995f7109baece9f0c590c2ca10f67ad33c7d9f0
626,254
import pickle def recv_zipped_pickle(socket, flags=0, protocol=2): """inverse of send_zipped_pickle""" z = socket.recv(flags) # p = zlib.decompress(z) return pickle.loads(z)
953c6e56831e08a024ed0525b7a06aedbfacddbc
626,255
def get_sql_cases(request): """Pytest fixture for parameterized tests.""" return request.param
b43dc6b1fc47bdb934622c6163589bd45ae0fd0c
626,256
def is_resnet(name): """ Simply checks if name represents a resnet, by convention, all resnet names start with 'resnet' :param name: :return: """ name = name.lower() if name.startswith("resnet"): return 'resnet' elif name.startswith('plane'): return 'plane' elif name....
91f31db743c8135543820fdd65ad6d0129f28015
626,258
from datetime import datetime def current_year_short(): """Get current year short.""" return datetime.today().strftime("%y")
7402feb277912c839617f9764fdbc6144b46da7f
626,259
def recognition_result_post_process(_recognition_result, _recognizer_model_type, _str_label_converter): """ 对识别的结果进行后处理,包括ctc decoder以及correct以及词典的矫正 :param _recognition_result: 识别的结果 :param _recognizer_model_type: 识别网路的类型 :param _str_label_converter: 所有识别出来对应的字符标签 :return: 进行后处理后的识别结果 "...
de56176a347c67d9eb139fec0f3c590a25ca112a
626,260
def next_position(pos, vel, acc, h): """ returns next position of particle. """ """ parameters ---------- pos : array current position vector of particle vel : array current velocity vector of particle acc : float current acceleration acting on the particle h : f...
64edb7e4d59392a12359c54c810ea7b672d70519
626,261
def convert_to_ascii(string: str) -> str: """Given a string, omit any non-ascii characters. The knowledge graph only supports ascii. Args: string (str): the string to convert. Returns: str: the same string, without any non-ascii characters. "ñàlom" would be converted to "lom". ...
7c727eed92947199e14472036c7e866b63f863d8
626,262
import re def take_pokemon_id(pokemon_url): """Returns a list with the id of the pokemon based on the url""" temporal_id_list = [] id_list = [] # find all the numbers on the url for item in pokemon_url: temporal_id_list.append(re.findall(r"\d+", item)) # all of they have 2 numbers so w...
1d2efeee2de160a5d38c32b560dfd4f4a6b278f2
626,263
import yaml def write_yaml(data: dict, file: str) -> None: """Write yaml to file..""" with open(file, "w", encoding='utf-8') as fp: return yaml.dump(data=data, stream=fp)
ae2fadaed632a7f69725ea2b28d616509d57bb37
626,264
import itertools from operator import or_ from operator import not_ from operator import and_ def nhot(n, *args): """ Return a CNF expression that means "exactly N input functions are true". """ if not 0 <= n <= len(args): fstr = "expected 0 <= n <= {}, got {}" raise ValueError(fst...
03e4c6a0aa2529d0d354dcc0990c2ea24b7d2fd8
626,265
def row2dict(row): """Converts a database-object to a python dict. This function can be used to serialize an object into JSON, as this cannot be directly done (but a dict can). :param row: any object :return: dict """ d = {} for column in row.__table__.columns: d[column.name] = s...
763fbb8732f9b613ac6a146b4f903904668466ff
626,266
def get_filter_results(twitter_dict, list_of_usernames, filter_dict): """ (Twitterverse dictionary, list of str, filter specification dictionary) -> list of str Apply the filter_dict to the given username list based on twitter_dict to determine which usernames in the list_of_usernames to keep, and ret...
d2c9a7b7ee24009f012ba39ab6a0083006f55007
626,267
def decrease_brightness(img, coord): """ Decrease brightness by 50% """ img_darkened = 0.5 * img / 255.0 return img_darkened, coord
895a1e3278fee467452295fd27c91c94bfbf52de
626,269
def predict_logits(img_x, phrases_x, f_similarity): """ Compute given similarity measure over the last dimension (features) of `img_x` and `phrases_x`. :param img_x: A [*, d1, d2, d3] tensor :param phrases_x: A [*, d1, d2, d3] tensor :param f_similarity: A similarity measure between [*, d3] tensors...
8659a82e2502e3ed9945eb208b4b4eeed0d6a28c
626,270
import json def schema_to_json(schema: dict, indent: int = 2) -> str: """Convert the given JSON schema (dict) into a JSON string.""" return json.dumps(schema, indent=indent)
4424f3dd5548eadb9ee9a36208766a8b6f6f290a
626,271
def _iframe(src, width=650, height=365, content=None, link=None): """Create an iframe html snippet.""" html = ( '<iframe width="%s" height="%s" src="%s" ' 'frameborder="0" allowfullscreen></iframe>' ) % (width, height, src) if not content: return html if link: content...
e1bab08c060b808dc669d7b2d774a67ec6c8b8ee
626,272
import re def stemmer(title: str, min: int) -> str: """提取漫画标题的主干,称为stem 比如 "蓝猫淘气第三部"提取出"蓝猫淘气 Args: title(str) :- 标题 min(int) :- stem的最小长度 """ pattern = r"(?P<deliminator>第[0-9一二三四五六七八九十][部季章]|之)" delimeator = re.search(pattern=pattern, string=title) start_index = len(title...
39e49a3e380e96c00c7f790536caf0224d638729
626,273
def generate_time_str(time): """convert time (in seconds) to a text string""" hours = int(time // 60**2) minutes = int((time - hours*60**2) // 60) seconds = int((time - hours*60**2 - minutes*60) // 1) ret = '' if hours: unit = 'hr' if hours == 1 else 'hrs' ret += f'{hours} {unit...
b1ea7441feb33cbfdb39ec08997ca101eefba21d
626,274
def compute_cumulative_returns(df): """Compute and return the cumulative return values.""" cum_returns = (df/df.ix[0]) - 1 return cum_returns
63795f125c53dec3b9edc264c15d159a5fc2223c
626,276
def get_e_rtd_C(): """定格冷房エネルギー消費効率 Args: Returns: float: 定格冷房エネルギー消費効率 """ # 定格冷房エネルギー消費効率 e_rtd_C = 3.17 return e_rtd_C
99ece7c940f017fa7c2851f16c8c16a5ffa13e6b
626,277
def dash(name): """ >>> dash('Some tag') 'some-tag' :type name: str :rtype: str """ return name.replace(' ', '-').lower()
8f68bb39244bdac26711f2048501a7481e99f5de
626,279
import json def load_json(fil): """ Loads a json file. """ dat = None with open(fil, "rt") as fh: dat = json.load(fh) return dat
56ac60be3583ba82e9116b3d56482d52efe80400
626,280
def split_name(name): """This method splits the header name into a source name and a flow name""" space_split = name.split(" ") upper_case = "" lower_case = "" for s in space_split: first_letter = s[0] if first_letter.isupper(): upper_case = upper_case.strip() + " " + s ...
05980932859146a5042b1f94b29cd187743ac5de
626,281
import numpy as np def gapmask(simseqs, origseqs): """ :param sims: list of (header, sequence) tuples of simulated sequences [no gaps] :param aln: list of (header, sequence) tuples of original sequences :return: """ simdict = dict(simseqs) origdict = dict(origseqs) for k in origdict: ...
4e9ab0387315b4f4413d37944c7b8c71ddf8dd7f
626,282
import os import argparse def valid_archive(string): """Convert string provided by argparse to an archive path.""" path = os.path.abspath(string) try: with open(path, "r") as f: _ = f.read(1) except FileNotFoundError: pass except (OSError, UnicodeError): error =...
17cc825b59ac71a12e4f88a9a0a80a4760968ed3
626,283
def _aperture_mean_nomask(ap, image, **kwargs): """ Calculate the mean flux of an image for a given photutils aperture object. Note that we do not use ``_aperture_area`` here. Instead, we divide by the full area of the aperture, regardless of masked and out-of-range pixels. This avoids problems ...
666c367823f33f9754c8b3277a9c651699e0b994
626,284
def RB_decay_to_gate_fidelity(rb_decay, dimension): """ Derived from eq. 5 of [RB] arxiv paper. Note that 'gate' here typically means an element of the Clifford group, which comprise standard rb sequences. :param rb_decay: Observed decay parameter in standard rb experiment. :param dimension: Dimens...
ecb756c25e3c4b328b85e57c251b636d1e157d34
626,285
def make_00de(): """フレンドリスト(自キャラ)""" return ""
823be2a0f55a62ca8de47e96041649696b95f97a
626,286
def add(summand_a: int, summand_b: int) -> int: """Adds to integers and returns its sum""" return summand_a + summand_b # x = 'this is very very very very long script that has no obvious reason to exist'
dd72c3f31a101e9061023542aafb558a9e79c5e4
626,287
def analyze_header(row, guesses, dialect, has_header): """ :type row: str :param s3_path: The row to analyze. :type guesses: dict :param guesses: The dictionary object containing all guesses. :type dialect: csv.Dialect :param dialect: Dialect object derived from the preview of the ...
56e3f093bab35762a715f78c3f691d61998a794d
626,288
import glob def case_insensitive_glob(pattern, **kwargs): """ Glob without case sensitivity Args: pattern (:obj:`str`): glob pattern **kwargs Returns: :obj:`list` of :obj:`str`: path of files that match the glob pattern """ def either(c): if c.isalpha(): ...
ebbe5ab8674c5aef57bd1beaf632a86f701480b3
626,289
from typing import List import importlib import multiprocessing def get_visible_devices_as_int() -> List[int]: """Return the number of CUDA visible devices as list of ints. Returns: List[int]: Number of available GPUs """ def _get_visible_devices_as_int(conn): tfconfig = importlib.im...
581be86f0f02402a68b6e4e9901ba99ff0d7db00
626,290
import requests def fetch_coupon(num): """ fetches given coupon from Sodexo :param num: number of coupon to be appended to url :return: that coupon content """ cnr = "{:02d}".format(num) url = "https://dlaciebie.sodexo.pl/ekupony/drukuj/id/" + cnr coupon = requests.get(url) return ...
e73d55ff45296ddff132589296ae241ad99eedd6
626,291
def update(array, xstart=0, xstop=-1): """ update(array) Drops all -1s in an array as low as possible Parameters ---------- array : 2D numpy array Returns ---------- 2D numpy array Modified array """ if xstop == -1: xstop = len(array[0]) for col in ...
0d496cd62482f14337aaec306612780393b3ced1
626,292
def account_info(remote, resp): """Retrieve remote account information used to find local user. It returns a dictionary with the following structure: .. code-block:: python { 'user': { 'profile': { 'full_name': 'Full Name', }, ...
2e92558a2fa778bf14d52e7b9bf2686d5e3ec751
626,293
import requests def fetch_player_history(player_id): """ Fetch JSON of a single player's FPL history. """ url = "https://fantasy.premierleague.com/drf/element-summary/{}".format(player_id) r = requests.get(url) return r.json()["history_past"]
07e07bd793c02430eb9605f177301eef00d9bd98
626,294
def generate_list(*args): """ Silly function #1 """ array = [] for entry in args: array.append(entry) return array
b3adfda4be837189250eb0dd2cbacad312647685
626,295
def equals(a, b) -> bool: """ compares two values and check if their values are equal @input: two integers a, b @output: True if a, b have same values, False otherwise """ a, b = int(a), int(b) return a == b
d65d011a4ee77c303354bf0a532d1b28930517e3
626,296
import copy def sanity_check_states(states_spec): """ Sanity checks a states dict, used to define the state space for an MDP. Throws an error or warns if mismatches are found. Args: states_spec (Union[None,dict]): The spec-dict to check (or None). Returns: Tuple of 1) the state space des...
f53e57b1c36ba120fd7f03259ff19df033ba4143
626,297
import re import os def fix_eol( stdout ): """Fixes wrong EOL produced by cmake --build on Windows (\r\r\n instead of \r\n). """ return re.sub( '\r*\n', os.linesep, stdout )
c660377cba40830078a72ef8c18b3cee6e43e7a5
626,298
def get_ids_samples(sample_id_txt): """得到各个ID对应的所有样本的名称 Args: sample_id_txt: 存放各个样本的ID的txt文件的路径 """ ids_samples = {} watched_id = set() with open(sample_id_txt, 'r') as f: for sample_id in f: sample_name = sample_id.split(' ')[0].split('/')[1] sample_id =...
a977524c71370ee67669534d31ec020358c9f340
626,299
import glob def detect(): """Return a list of candidate paths for USB ENOcean dongles. This method is currently a bit simplistic, it may need to be improved to support more configurations and OS. """ globs_to_test = ["/dev/tty*FTOA2PV*", "/dev/serial/by-id/*EnOcean*"] found_paths = [] for...
07b620d2641f44f1236bc898c7ecdcfcb41b32ca
626,301
def rr_and_single(x, y, nx, ny): """Dimensionless production rate for a gene regulated by two repressors with AND logic in the absence of leakage with single occupancy. Parameters ---------- x : float or NumPy array Concentration of first repressor. y : float or NumPy array ...
71099115ffe2a30a4055c42764ff4587493066d8
626,302
import os import json def get_model_config(key: str, config_path: str) -> dict: """ 保存单次训练执行时,模型的对应配置 :param key: 配置key :param config_path: 配置文件路径 :return: 模型配置字典 """ if not os.path.exists(config_path): raise FileNotFoundError("get_model_config: Not such file {}".format(config_path)) ...
3b83619b561503027e4fa3a3af4f3a46f2bbd728
626,303
def _convert_value_to_eo3_type(key: str, value): """ Convert return type as per EO3 specification. Return type is String for "instrument" field in EO3 metadata. """ if key == "instruments": if len(value) > 0: return "_".join([i.upper() for i in value]) else: ...
7aab8f949723ab17846b9417f1b46cab55c73645
626,304
from typing import Dict from typing import Any from typing import Optional from typing import Union def _resolve_name_args(kwargs: Dict[str, Any]) -> Optional[Union[Dict[str, Any], str]]: """Resolve the name-type shortcut arguments by precedence. Pop each key from `kwargs`, even if it's not used. """ ...
86336d8ecb96ee35fc5968688d76c20a88ca6585
626,305
def quadsplit(quad): """Split ccw quad to two triangles""" v1, v2, v3, v4 = quad return [ [v1, v2, v3], [v3, v4, v1]]
9e567beeefad574efbba0b10b7134c78456446ee
626,306
def read_sudoku(file_name): """ Reads a file and returns a two-dimensional list of integers. :param str file_name: Full path of the file containing a sudoku problem :return: Two-dimensional list of integers :rtype: list """ with open(file_name) as stream: data = stream.readlines() ...
b7476b7aa200c032d4542bf37ee600ab21dd21a1
626,307
import torch def synthetic_data(w, b, num_examples): #@save """Generate y = X w + b + noise.""" X = torch.zeros(size=(num_examples, len(w))).normal_() y = torch.matmul(X, w) + b y += torch.zeros(size=y.shape).normal_(std=0.01) return X, y
784d9b00f6d67023d4a90c335cc2e7e7f2bb5088
626,308
def rivers_with_station(stations): """ Returns a set of all rivers monitored by 'stations'. 'stations' is a list of 'MonitoringStation' objects. Documentation for object 'station' can be found by importing 'station' from 'floodsystem' and typing 'help(station.MonitoringStation)' """ river_lis...
09116b99992ef32dd1506a37e4e39622b29c5bd6
626,309
def get_discount(s: float, p: float) -> float: """" Повертає дисконт величини S. Parameters ---------- s : float Нарощена сума боргу p : float Дисконтована вартість (зведена, теперішня величина) суми S Returns ------- D : float Дисконт (== I). """ return ...
f1d240b97086036168665806beb3248189ac5288
626,310
def figure_defaults(): """Generates default figure arguments. Returns: dict: A dictionary of the style { "argument":"value"} """ plot_arguments={ "xcols":[],\ "xvals":"",\ "ycols":[],\ "yvals":"",\ "groups":"",\ "ncomponents":"2",\ "percva...
c85e2f0a2a857d4f18814f6f1c85813ded14f2cb
626,311
def newton_sqrt1(x): """Return the square root of x using Newton's method""" val = x while True: last = val val = (val + x / val) * 0.5 if abs(val - last) < 1e-9: break return val
27c699eb1b26956ca630fce063ee12a336e02883
626,312
def prepend_indent(string, indent_level): """ Add a given indent before every line of the string :string: string to which we want to append the indent :indent_level: integer number of spaces to prepend """ indented = "".join("{}{}\n".format(" "*indent_level, line) for line in string.splitlines(...
191a2c9903278dba23e01c7d215e773b237553cf
626,313
def generate_all_labelings(node_list): """ Returns a list of all permissible orderings of the nodes. A permissible ordering is one in which each child comes after its parent. See e.g. HNW1993 p. 267, Example 12.5. """ labeled = [[node_list[0]]] for i in range(1,len(node_list)): new...
fe4cbbb005b2b23141dc4e71b77c1a52af462cd1
626,315
from typing import Mapping from typing import Any def add_relations(specification: Mapping[str, Any]) -> Mapping[str, Any]: """Add relation keys to specification Args: specification (Mapping[str, Any]): bel specification dictionary Returns: Mapping[str, Any]: bel specification dictionary...
e2ee1db7e50803eb13bd9ac7217f086b6868975d
626,318
def RepresentsFloat(val): """ Takes string and checks if value represents float number >>> RepresentsComplex('10.1') True >>> RepresentsComplex('Am I Float?') False """ try: float(val) return True except: return False
044cbd2ac416d3cecd76765e2fbd5134ca1ec717
626,319
def _project_point_onto_cone(x_val, y_val, z_val, w_val): """ Try to find a point on the cone x0, y0, z0, w0 such that z0 = z_val w0 = w_val x0, y0 lie on the circle x**2 + y**2 == z_val*w_val and are as close as possible to x_val, y_val In order to find such a point, we can require that x0 an...
1e593653d3530c23ab623471618a2774b8a40745
626,320
def group_dn_magic(group_dn, ldap_group_dn): """ -技术部-运维部 转 cn=运维部,cn=技术部,ou=Group,dc=10dream,dc=com :param group_dn: :param ldap_group_dn: like ou=Group,dc=10dream,dc=com :return: """ cns = '' all_cn = group_dn.split('-') all_cn.reverse() # 倒序,注意结果直接在原来的列表里 for i in all_cn: ...
d38d56e6f97782c05d548411ae260c4ea7740d27
626,321
def get_is_head_of_word(naive_tokens, sequence_tokens): """ Return a list of flags whether the token is head(prefix) of naively split tokens ex) naive_tokens: ["hello.", "how", "are", "you?"] sequence_tokens: ["hello", ".", "how", "are", "you", "?"] => [1, 0, 1, 1, 1, 0] *...
d3cb375bf8a6a7eb2e469b0a16c19a7b7089573c
626,322
def half_period_uncoupled(t, x, par): """ Returns the event function Zero of this function is used as the event criteria to stop integration along a trajectory. For symmetric periodic orbits this acts as the half period event when the momentum coordinate is zero. Parameters ---------- t :...
c44c772f60691a31f98b4143341dbf567847e5e7
626,323
def fmt_feature_rate_dict(feature, feature_rate=None): """ This will be turned into a JSON representation of this Feature and its FeatureRate """ if feature_rate is None: feature_rate = feature.get_rate() return { 'name': feature.name, 'feature_type': feature.feature_type, ...
96bf9ba0f0e1e1649063b81351ac466eb21dabae
626,324
import binascii def to_hex(bytestring): """ convert given little-endian bytestring to hex """ return binascii.hexlify(bytestring[::-1])
f2f40cc2b162601a029523f21dc7af19b67ab1cd
626,325
def part_device(part_number): """Given partition number (but string type), return the device for that partition.""" return "/dev/mmcblk0p" + part_number
2e4feb3ad1c93166ebade7fafe8ddccabdc3b9f1
626,327
def disk_create(context, values): """Create a disk from the values dictionary.""" return NotImplemented
3cdf42c0452ee558e6dce22862b053c9af2a8f01
626,328
def get_geoserver_wms(): """ Try to get the built in geoserver wms for this installation if possible. Otherwise point at the chpc geoserver. """ return 'https://demo.geo-solutions.it/geoserver/wms'
88074409cd1ad400f4febb51b29ff4f7f198023f
626,329
from typing import Optional import torch def to_numpy(tensor: Optional[torch.Tensor]): """ Convert a PyTorch Tensor to a Numpy Array. """ if tensor is None: return tensor if tensor.is_quantized: tensor = tensor.dequantize() assert isinstance(tensor, torch.Tensor), f"to_numpy ...
dc37442cba00ff12c2fbc2a03286c0521bf856cb
626,331
def wrap_to_pm(x, to): """Wrap x to [-to,to).""" return (x + to)%(2*to) - to
a6a0bb614972121529dec3e379ce3378587c082d
626,332
from typing import Dict from typing import List def create_dict(n: int) -> Dict[int, List[int]]: """Returns Dictionary with numbers from 0 to n as keys which are mapped to lists containing squares and cubes of the respective keys. doctests: >>> create_dict(1) {0: [0, 0], 1: [1, 1]} ...
c208e595d8724b3a716b30f4db675cbe5368b642
626,333
def err_response(reqid, code, msg, data=None): """ Formats a JSON-RPC error as a dict with keys: 'jsonrpc', 'id', 'error' """ err = {"code": code, "message": msg} if data: err["data"] = data return {"jsonrpc": "2.0", "id": reqid, "error": err}
d8f62af41c25b271c8433b48887ae5ac94564466
626,334
def get_constraint_deficit(model, constraint_id): """Get constraint ID""" if model.P_GC_TYPE[constraint_id] == 'EQ': return model.V_CV_RHS[constraint_id].value + model.V_CV_LHS[constraint_id].value elif model.P_GC_TYPE[constraint_id] in ['LE', 'GE']: return model.V_CV[constraint_id].value ...
524d862d7905e1615faf2fd3e8d2f707fdf85b16
626,335
def magic_square_params(diagonal_size): """ This is a helper function to create the gene_set, optimal_fitness and the expected sum of all the rows, columns and diagonals. :param diagonal_size: The diagonal length of the magic square. :type diagonal_size: int """ numbers = list(range(1, ...
5c1c57388fd94c25c4c4ec6ee26e5519780af135
626,336
import sys def import_class(import_str): """Returns a class from a string including module and class.""" mod_str, _sep, class_str = import_str.rpartition(".") __import__(mod_str) return getattr(sys.modules[mod_str], class_str)
abd607956eb78381d7ed0a199727b5ef8ce46fe6
626,337
def get_translate_str(type_name: str, namespace_: str, name: str) -> str: """ 规范得到翻译序列 :param type_name: 类型 :param namespace_: 命名空间 :param name: 名称 :return: 翻译序列 """ return f"{type_name}.{namespace_}.{name}"
cf03e653ed74ef9df5d30418b6e9e21c05a541bf
626,338
def quick_pow(n: int, k: int, p: int) -> int: """Find n^k % p quickly""" if k == 0: return 1 tmp = quick_pow(n, k // 2, p) ** 2 return tmp % p if k % 2 == 0 else tmp * n % p
b6acec3d10903d41af59882a1a6d708c238a8661
626,339
import itertools def combine_bucket( parts: list, threshold: int, truncate: bool = False, keep_remain: bool = False) -> list: """ Convert parts to buckets with given length(threshold). Parameters ---------- parts: the given parts. threshold: bucket length. ...
c994a6cd19a538ea572f24ed17b100db68877f89
626,341
def remove_dataset_id(df, ds1_trend_column, ds2_trend_column): """deletes the data set id from a given ptcf :param df: PTCF data frame :ds1_trend_column: column name ds 1 :ds2_trend_column: column name ds 2 :return: ds without data set information """ df[ds1_trend_column] = df[ds1_trend_column].str.split('...
b95339fe0d2b7eb6cc6df6cd6c34bc999b7d8c44
626,342
import re def strip_number(number): """Strips the number down to just digits.""" number = re.sub("[^0-9]", "", number) return number
12f627d9ad6f526f39f1919f67c1b1943f82f2fe
626,343
from typing import List from typing import Tuple def stretch_in_row_or_column( stretched_list: list, two_coordinates: tuple ) -> List[Tuple[int, int]]: """ Update a list of coordinates by coordinates between two boundaries of a line. Form a line in horizontal or vertical direction. Args: ...
29840aa92950c11aca997131726b592c934d4645
626,344
import torch def modify_contextualized_embeddings(edus, tokenizer, SEQ_LEN = 80): """ update contextualized embeddings for edus no_context: if true, use the embeddings itself without the context """ sentence = '' for e in edus: sentence += e.sentence sentence_tokens = tokenizer.encode_plus(se...
f660688b9ce5b49fdddc366f2a91a52637d85b30
626,345
def Minify_MoveStyleChangesToFirstLoad(run_subject): """ For each of the modified styles, try moving that style to the base styles. This should leave only the absolutely essential styles being modified. """ # Generate a function for each item in modified_styles for elementId, styles in run_subj...
20e67f191754eca35649f5864d76e049f03e121a
626,346
import math def cylinder_vol(radius,height): """Usage: find volume of a cylinder""" return math.pi*(radius**2*(height))
4db8a4b4c3396b0b4a3165a98d546b423ce8f54d
626,348
def compute_initial_chunksize(number_of_files, num_cpu): """ :param num_cpu: :param number_of_files: :return: """ if number_of_files > num_cpu: return int(number_of_files / 2) else: return number_of_files
9c288f27d846a9380a5f0755983c934289bdf9d9
626,349
import os def npath(path, *pathes): """ robi jednoczesne path.join i normcase zeby skrócić kilometrowe wywołania""" return os.path.normcase(os.path.join(path, *pathes))
1cc18c376e4cf001e2161a32c5a579690d40f93f
626,352
import json import os def get_ref_path(input_json): """ Set full path to reference files Input: reference config file Return: json file with abspath """ with open(input_json) as fh: ref_json = json.load(fh) for k, v in ref_json['reference'].items(): ref_json['refere...
3dd4475a17742b11017c389ccd21e42410e436e0
626,353
import math def normalize_function(foo, interval=(0, 1), precision=100): """ Normalizes function on given interval. Args: foo (function): Function to be normalized. interval (tuple): Interval of normalization. precision (int): Precision of numerical calculations. Returns: ...
449ed42542ec5c86878c6a5ab7507bea1235afee
626,354
import decimal def _calculate_mod_text(line: str, value: float) -> str: """Calculate an item affix's correct value from range and offset. :return: Corrected item affix value.""" start, stop = line.partition("(")[-1].partition(")")[0].split("-") width = float(stop) - float(start) + 1 # Python's ro...
151515c407d1fe18066d7909c5c924164fa15bc3
626,355
def num_in_base(num, base): """Converts an integer to its representation in base in big-endian. e.g., num_in_base(14, 2) = [1, 1, 1, 0]. Args: num: the number to convert. base: the base of the representation. Returns: The list of digits in big-endian. """ if num == 0: return [0] digits...
a75353c571b0cb9db84025d558884b126983b76a
626,356
def compare_lists(list1: list, list2: list): """Returns the diff of the two lists. Returns ------- - (added, removed) ``added`` is a list of elements that are in ``list2`` but not in ``list1``. ``removed`` is a list of elements that are in ``list1`` but not in ``list2``. """ added = ...
dcc7f97c02b6b2b846179772dd81211c9b0cc040
626,357