content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import functools from operator import add def gen_cand_keyword_scores(phrase_words, word_score): """ Computes the score for the input phrases. :param phrase_words: phrases to score :type phrase_words: list :param word_score: calculated word scores :type word_score: list :return: dict *{ph...
d219256938ab2538214cbc075451f7da5a253b06
1,031
def analyze_network(directed=False, base_url=DEFAULT_BASE_URL): """Calculate various network statistics. The results are added to the Node and Edge tables and the Results Panel. The summary statistics in the Results Panel are also returned by the function as a list of named values. Args: d...
0edd9e848e3b3060055e6845aa5fbb2792c7a1f4
1,032
def create_user(): """ Create new user """ # request.get_json(): extract the JSON from the request and return it as # a Python structure. data = request.get_json() or {} # Validate mandatory fields if 'username' not in data or 'email' not in data or \ 'password' not in data: ...
a416e0d5bbb6539cee3ce5174ab3cf1186680ee9
1,033
import hashlib import base64 def hash_long_to_short(long_url): """ turn a long input url into a short url's url-safe 5 character hash this is deterministic and the same long_url will always have the same hash """ encoded = long_url.encode("utf-8") md5_hash = hashlib.md5(encoded).digest() r...
050de3e30feeac46f98b152890d82dd8e416f2d0
1,034
def has_prefix(sub_s): """ Test possibility of sub_s before doing recursion. :param sub_s: sub_string of input word from its head. :return: (boolean) whether word stars with sub_s. """ for word in DATABASE: if word.startswith(sub_s): return True
2dde507f7b0b3c56f8a5a9a582d52b784607dd5d
1,036
def transform_results(search_result, user, department_filters): """ Transform podcast and podcast episode, and userlist and learning path in aggregations Add 'is_favorite' and 'lists' fields to the '_source' attributes for learning resources. Args: search_result (dict): The results from Elastic...
93bbb9cb3effa4b0f602e42549a961f4fd53faeb
1,037
def kl_div_loss(inputs: Tensor, targets: Tensor) -> Tensor: """Computes the Kullback–Leibler divergence loss between two probability distributions.""" return F.kl_div(F.log_softmax(inputs, dim=-1), F.softmax(targets, dim=-1), reduction="none")
9a45dacfe8fd529893cf7fa813869a97da562f65
1,038
from typing import List def get_schema_names(connection: psycopg2.extensions.connection) -> List[psycopg2.extras.RealDictRow]: """Function for getting the schema information from the given connection :param psycopg2.extensions.connection connection: The connection :return: List of rows using key-value p...
69a4e0b70ef443c2480f0fbb1e1e859bbf6f69bd
1,039
def parse(string): """Returns a list of specs from an input string. For creating one spec, see Spec() constructor. """ return SpecParser().parse(string)
788849ebaa29b4dab5e4babcb13573acbc8b8525
1,040
def get_provider_idx(provider_type): """Return the index associated to the type. """ try: return PROVIDERS_TYPE[provider_type]['idx'] except KeyError as error: raise ProviderError( "Provider type (%s) is not supported yet." % (provider_type, ) )
47272903415825c870222b3531fddc11129d62c0
1,041
import collections def file_based_convert_examples_to_features( examples, slot_label_list, intent_label_list, max_seq_length, tokenizer, output_file): """ 将InputExamples转成tf_record,并写入文件 Convert a set of InputExample to a TFRecord file. :param examples: [(text, CRF_label, class_label), ...] ...
b5d4a9228af4169307a8a22f4c56a0c3eb6e8f27
1,042
def create_readme(df): """Retrieve text from README.md and update it.""" readme = str categories = pd.unique(df["category"]) categories.sort() with open('README.md', 'r', encoding='utf-8') as read_me_file: read_me = read_me_file.read() splits = read_me.split('<!---->') # I...
5e0d207baa3d5c1e1f68b6f2e1a347bffece901a
1,043
async def get_leaderboard_info_by_id( # ScoreSaber leaderboardId leaderboardId: float ): """ GET /api/leaderboard/by-id/{leaderboardId}/info """ # request request_url = f'{SERVER}/api/leaderboard/by-id/{leaderboardId}/info' response_dict = await request.get(request_url) return Leade...
ab081d17b462a0738c578c9caed93c7b4a1ec9a6
1,044
def distance(lat1,lon1,lat2,lon2): """Input 2 points in Lat/Lon degrees. Calculates the great circle distance between them in radians """ rlat1= radians(lat1) rlon1= radians(lon1) rlat2= radians(lat2) rlon2= radians(lon2) dlat = rlat1 - rlat2 dlon = rlon1 - rlon2 a = pow(si...
2c6b1692843db3f69c750f4b2acda43d49227e7a
1,045
def minimumSwaps(arr): """ O(nlogn) """ len_arr = len(arr) arr_dict = {key+1:value for key, value in enumerate(arr)} arr_checked = [False]*len_arr total_count = 0 for key, value in arr_dict.items(): count = 0 while key != value and arr_checked[key-1] is False: ...
d5251297fd52f99aefce69986bd5c8c126b7e6b6
1,046
def store_user_bot(user_id, intended_user, bot_id): """Store an uploaded bot in object storage.""" if user_id != intended_user: raise api_util.user_mismatch_error( message="Cannot upload bot for another user.") if bot_id != 0: raise util.APIError( 400, message="Sorry...
2b19e4092df3cb93fdadf5f06176ec4ec9300f63
1,047
def parse_conv(weights_file, cfg_parser, section, layer_dict): """ parse conv layer Args: weights_file (file object): file object of .weights file cfg_parser (ConfigParser object): ConfigParser object of .cfg file for net section (str): name of conv layer lay...
6e7cc1d2b4115dc44eaf2ad90240144f7157b30b
1,049
def generate_format_spec(num_vals, sep, dtypes, decimals=None): """ Generate a format specifier for generic input. -------------------------------------------------------------- Input num_vals : number of wild-cards sep : separator string (could be '_', '-', '--' ...) ...
3b65ad3b436b6c578fa2504a2ea4a475700432ce
1,050
from typing import Optional def products_with_low_stock(threshold: Optional[int] = None): """Return queryset with stock lower than given threshold.""" if threshold is None: threshold = settings.LOW_STOCK_THRESHOLD stocks = ( Stock.objects.select_related("product_variant") .values("...
29bbdd3236b42bf3cef17f84a919ab201946c084
1,051
def robust_topological_sort(deps): """ A topological sorting algorithm which is robust enough to handle cyclic graphs. First, we bucket nodes into strongly connected components (we use Tarjan's linear algorithm for that). Then, we topologically sort these buckets grouping sibling buckets into sets. ...
fb2b70f21ccb97880767e73362b46e27804c2d17
1,052
import inspect import functools import warnings def deprecated(reason): """ This is a decorator which can be used to mark functions and classes as deprecated. It will result in a warning being emitted when the function is used. From https://stackoverflow.com/a/40301488 """ string_types =...
1b75306b9b712caf3cd6c8425d2344b8ca170fcb
1,053
import torch def rotate_tensor(l: torch.Tensor, n: int = 1) -> torch.Tensor: """Roate tensor by n positions to the right Args: l (torch.Tensor): input tensor n (int, optional): positions to rotate. Defaults to 1. Returns: torch.Tensor: rotated tensor """ return torch.cat...
9cdaa7be718f0676ad85e05b01ee918459697c60
1,054
def generate_all_fish( n_fish, n_replica_fish, channel, interaction, k_coh, k_ar, alpha, lim_neighbors, weights = [1], neighbor_weights=None, fish_max_speeds=None, clock_freqs=None, verbose=False, names=None ): """Generate both replica and regular fish Ar...
3924235d7bdcf25a91dcb1ec40220b761b85f15f
1,055
def allclose(a, b): """ close to machine precision """ return np.allclose(a, b, rtol=1e-14, atol=1e-14)
ad7ee29d7432947aec0030936985b456a5919eaa
1,056
def check_pwhash(pwhash, password): """Check a password against a given hash value. Since many forums save md5 passwords with no salt and it's technically impossible to convert this to an sha hash with a salt we use this to be able to check for plain passwords:: plain$$default md5 pass...
618cdc8a9f7f7d7062e1e0ae26cf81157a8dbba7
1,057
def make_markov_model(tweets): """Wrapper around making Markov Chain""" return markovify.Text(" ".join(tweets))
0bd98d1a2f3a5aae37591389b06d402073f1a7ec
1,058
def slice_image(sitk_image, start=(0, 0, 0), end=(-1, -1, -1)): """"Returns the `sitk_image` sliced from the `start` index (x,y,z) to the `end` index. """ size = sitk_image.GetSize() assert len(start) == len(end) == len(size) # replace -1 dim index placeholders with the size of that dimension e...
eda4477c016d1130bb185a5793409ff95b9cd44c
1,059
def MakeGlyphs(src, reverseNormals): """ Glyph the normals on the surface. You may need to adjust the parameters for maskPts, arrow and glyph for a nice appearance. :param: src - the surface to glyph. :param: reverseNormals - if True the normals on the surface are reversed. :return: The gl...
0bb28c943a2c371f5e536851208ac0d4b09cd51a
1,060
def get_tags_categorys(self): """02返回添加文档的变量""" tags = Tag.all() categorys = Category.all() return tags, categorys
557e5182dd3dbf3571e005c4e105a20e2cdd3dd1
1,061
import pprint import warnings def single_mode_constant_rotation(**kwargs): """Return WaveformModes object a single nonzero mode, with phase proportional to time The waveform output by this function will have just one nonzero mode. The behavior of that mode will be fairly simple; it will be given by exp(...
cc31bf0587ff397cb79c42863efd3d8173cddc72
1,063
def get_file(file_pattern: list, sub_type: str = None) -> list: """Get a subset from file patterns that belong to a sub-type. If no sub-type is specified, return all file patterns. Args: file_pattern (list): The input file patterns sub_type (str, optional): A string to search in file patter...
7d39c05fa8a1f7a9370de459472ecf7070aa6569
1,064
def get_all_report_data(db): """ Gets all report data for pre report page """ query = r'SELECT * FROM report WHERE relevent=1 ORDER BY id DESC' return db_get(db, query)
727c4c9ec2125747237d40d7f0dd019b3d116d00
1,066
def find_center_projection(mat1, mat2, flip=True, chunk_height=None, start_row=None, denoise=True, norm=False, use_overlap=False): """ Find the center-of-rotation (COR) using projection images at 0-degree and 180-degree based on a method in Ref. [1]. ...
21661a6b9ed33a220ede918954ac18a420e638ae
1,067
def parse_date(str): """ parsing given str to date """ ymd = str.split('-') return date(int(ymd[0]), int(ymd[1]), int(ymd[2]))
29d0f79e2428e315c072c7801d927154c3bfee57
1,068
def mark_as_widget(view): """ Marks @view as a widget so we can later inspect that attribute, for example, when hiding panels in _vi_enter_normal_mode. Used prominently by '/', '?' and ':'. XXX: This doesn't always work as we expect. For example, changing settings to a panel created insta...
965555660b82f834e09ba3ffc985755d4fd7fa66
1,069
def module_name(ctx, f): """Given Haskell source file path, turn it into a dot-separated module name. module_name( ctx, "some-workspace/some-package/src/Foo/Bar/Baz.hs", ) => "Foo.Bar.Baz" Args: ctx: Rule context. f: Haskell source file. Returns: string: Haskell module name. """ r...
77a38f62211a827ac8fe9af0cc36636b11e561d5
1,070
def store(key): """Gets the configured default store. The default is PickleStore :return store: Store object """ global __stores if __stores is None: __stores = {} if key not in __stores: __stores[key] = __configuration[STORE](key) return __stores[key]
76197d8cedc44e15a75c81f1bcb07d3a4e59e021
1,071
def get_label_for_line(line, leg): """ Can't remember what I was using this for but seems useful to keep """ # leg = line.figure.legends[0] # leg = line.axes.get_legend() for h, t in zip(leg.legendHandles, leg.texts): if h.get_label() == line.get_label(): return t.get_tex...
4180ae7fd7fe5b98ebafa20fbdf2528205e4ec31
1,072
def _node_parent_listener(target, value, oldvalue, initiator): """Listen for Node.parent being modified and update path""" if value != oldvalue: if value is not None: if target._root != (value._root or value): target._update_root(value._root or value) target._upda...
06c06b144c777f33673e2051f1d4173204720f65
1,073
import torch import typing def sequential_to_momentum_net(module: torch.nn.Sequential, split_dim=1, coupling_forward: typing.Optional[typing.List[typing.Optional[typing.Callable]]] = None, coupling_inverse: typing.Optional[ty...
269d45cf845555988c3284a88a7e3ca83fb697b5
1,075
def user_view(request, name): """Render the view page for users""" # argument is the login name, not the uuid in Cassandra user = User.find(name) if not user: return redirect("users:home") ctx = { "req_user": request.user, "user_obj": user, "groups": [Group.find(gna...
f7f5bc01d2b60bcca048e0b2183eefcc5f4eb907
1,076
def grelha_nr_colunas(g): """ grelha_nr_colunas: grelha --> inteiro positivo grelha_nr_colunas(g) devolve o numero de colunas da grelha g. """ return len(g[0])
740b06c186ad1455aecadfaf112f253fb434d5ff
1,077
def rmsd(array_a, array_b): """ Calculate the RMSD between two 1d arrays Parameters ---------- array_a, array_b : 1d numpy arrays The arrays to be compared Returns ------- rmsd : float The Root Mean Square Deviation of the elements of the array """ diff = array_...
7390cebff27d73bc9268cdc23e21c2d362bca2cc
1,078
def readFile(sFile, sMode = 'rb'): """ Reads the entire file. """ oFile = open(sFile, sMode); sRet = oFile.read(); oFile.close(); return sRet;
d44e8217ae7dcab1c826ccbbe80e066d76db31b5
1,079
def VI_cgivens_d( a, b): """ returns cos, sin, r """ c = vsip_cmplx_d(0.0,0.0) s = vsip_cmplx_d(0.0,0.0) r = vsip_cmplx_d(0.0,0.0) am = vsip_cmag_d(a) bm = vsip_cmag_d(b) if am == 0.0: r.r = b.r; r.i=b.i; s.r = 1.0; else: scale = am + bm; alpha ...
7ed08b3c583a805cd9a7b0dfcfb80eb67a054e1e
1,080
import json def documint_request_factory(request): """ Create a function that issues a request to a Documint endpoint. Status codes outside the 2xx range are treated as errors. If error responses are JSON then `DocumintError` is raised, otherwise `MalformedDocumintError` is raised. If the st...
9dc4dcba0df1094c394dbe8d9424f874e3ac3169
1,081
def skip_for_tf2(f): """Decorator that skips tests when using TensorFlow 2.""" def test_wrapper(*args, **kwargs): """Wraps the decorated function to determine whether to skip.""" # Extract test case instance from args. self = args[0] try: # If tf.contrib doesn't exist, we are in TF 2.0. ...
02059cc9c8e6b83ab49dcd3b69d447fa3ec26324
1,084
import yaml def clean_logfile(logfile_lines,to_remove): """Remove yaml fields from a list of lines. Removes from a set of lines the yaml_fields contained in the to_remove list. Arguments: logfile_lines (list): list of the lines of the logfile. Generated from a file by e.g. :py:meth:`~io.IOBase.readlines...
5e066584488230e777684fcf4e8d25784343afaf
1,085
def no_red_sum(tokens): """Using import json is cheating, let's parse it ourselves in a sinlge pass. Hope you like stacks.""" sums = [0] stack = [] is_red = False for token in tokens: if token == 'red' and not is_red and stack[-1] == '{': is_red = True sums[-1] = 0 ...
7945618bcc76c03b457cacf4f995e767d5b6160c
1,086
def get_all_projects(): """ Return a list with all the projects (open and closed). """ return gazu.project.all_projects()
7279d46e9049f3ff9802dcc93b8e41b2e118c9a2
1,087
def install(opts): """ Install one or more resources. """ resources = _load(opts.resources, opts.output_dir) if opts.all: opts.resource_names = ALL success = _install(resources, opts.resource_names, opts.mirror_url, opts.destination, opts.skip_top_level) if suc...
9487490eb9ccb13ce7f9797defacf823161a60a9
1,088
import torch def seq2seq_att(mems, lengths, state, att_net=None): """ :param mems: [B, T, D_mem] This are the memories. I call memory for this variable because I think attention is just like read something and then make alignments with your memories. ...
992fa8329443a2505c6ff0d83e9c34e69be620d4
1,089
def convert_for_webkit(new_path, filename, reference_support_info, host=Host()): """ Converts a file's |contents| so it will function correctly in its |new_path| in Webkit. Returns the list of modified properties and the modified text if the file was modifed, None otherwise.""" contents = host.filesystem.r...
098774b42f9086b1b61dc231318731ab7eb1a998
1,090
import re def clean_repeated_symbols(text): """ Filters text, replacing symbols repeated more than twice (not allowed in most languages) with a single repetition of the symbol. :param text: the text to be filtered :type: str :return: the filtered text :type: str """ pattern = re.co...
bfa758994cfae716caaa715d5a990416a300f9d9
1,092
def sample(x,y, numSamples): """ gives numSamples samples from the distribution funciton fail parameters """ y /= y.sum() return np.random.choice(x, size=numSamples, replace=True, p=y)
4cfbb6977bcd5fa43f27de40b15beff487f1c071
1,093
def make_path_strictly_increase(path): """ Given a warping path, remove all rows that do not strictly increase from the row before """ toKeep = np.ones(path.shape[0]) i0 = 0 for i in range(1, path.shape[0]): if np.abs(path[i0, 0] - path[i, 0]) >= 1 and np.abs(path[i0, 1] - path[i, 1]...
1a5043bdb469c9dd3f9bf57e1b9752ebd8567182
1,094
def set_group_selector(*args): """set_group_selector(sel_t grp, sel_t sel) -> int""" return _idaapi.set_group_selector(*args)
1fbf3807791bf94511f4c7da52278db2815c757e
1,096
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_latency_characteristictraffic_property_name_get(uuid, node_uuid, node_rule_group_uuid, traffic_property_name): # noqa: E501 """data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uui...
5f0aff58f5f5e7f72f6622fdb8a400b03f6aae15
1,097
def getPendingReviewers(db, review): """getPendingReviewers(db, review) -> dictionary Returns a dictionary, like the ones returned by getReviewersAndWatchers(), but with details about remaining unreviewed changes in the review. Changes not assigned to a reviewer are handled the same way.""" cursor = db.curso...
869a6bb752c4e7c1e40a0000b3aceb62adc28ce1
1,098
import base64 def base64_encode_string(string): # type: (str or bytes) -> str """Base64 encode a string :param str or bytes string: string to encode :rtype: str :return: base64-encoded string """ if on_python2(): return base64.b64encode(string) else: return str(base64.b...
0c13ca527171fecdbc5eb93376c6019c0b95e2b7
1,099
def get_error_signature(error_type, n_top, **kwargs): """Generates a signature for the specified settings of pose error calculation. :param error_type: Type of error. :param n_top: Top N pose estimates (with the highest score) to be evaluated for each object class in each image. :return: Gene...
82036a650862a7b3a6b55493458ff3b7dc6cd2ff
1,100
import re def clean_text_from_multiple_consecutive_whitespaces(text): """Cleans the text from multiple consecutive whitespaces, by replacing these with a single whitespace.""" multi_space_regex = re.compile(r"\s+", re.IGNORECASE) return re.sub(multi_space_regex, ' ', text)
f25b27da070d6a984012a4cb5b1ae4a477713033
1,101
import re def run(filename): """ MUST HAVE FUNCTION! Begins the plugin processing Returns a list of endpoints """ run_results = set() r_rule = re.compile(r"(Route\(\"[^,)]+)", flags=re.IGNORECASE) for line in filename: try: route_match = r_rule.search(line) ...
e5ad233e3c3e07769b2f8f61657fa712b1f151c4
1,102
import re from unittest.mock import patch async def setup_script(hass, notify_q, notify_q2, now, source, config=None): """Initialize and load the given pyscript.""" conf_dir = hass.config.path(FOLDER) file_contents = {f"{conf_dir}/hello.py": source} Function.hass = None mock_open = MockOpen() ...
d1d194af7686cbf5bb5e61ebc692d7fd7e9aae71
1,103
def get_assignment_grade_summaries(course_id): """ return a list of a course's assignments with a grade summary for each https://canvas.instructure.com/doc/api/analytics.html#method.analytics_api.course_assignments """ assignments = api.get_list('courses/{}/analytics/assignments'.format(course_id)) ...
69dddeee4389ee457201c3d1195537f869d0ea57
1,104
def _list_descriptors(): """Return a list of all registered XModuleDescriptor classes.""" return sorted( [ desc for (_, desc) in XModuleDescriptor.load_classes() ] + XBLOCK_CLASSES, key=str )
e19b7957b3a65495e1d0fb7c33b4b2748bc1473f
1,105
def e3p0(tof,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10): """ Background function for TOF spectra Parameters ---------- tof : array-like The time-of-flight spectrum p1 : float constant background p2 : float multiplier on 1st exponential p3 : float multiplier on time-...
0ad3aad94c4e8b5f48a6ec4458329d0de6eda612
1,106
def dice_coefficient(pred, gt): """ Computes dice coefficients between two masks :param pred: predicted masks - [0 ,1] :param gt: ground truth masks - [0 ,1] :return: dice coefficient """ d = (2 * np.sum(pred * gt) + 1) / ((np.sum(pred) + np.sum(gt)) + 1) return d
d1d97b749ce365c6181a2b17c41d946195339c96
1,107
def get_keep_score(source_counts, prediction_counts, target_counts): """Compute the keep score (Equation 5 in the paper).""" source_and_prediction_counts = source_counts & prediction_counts source_and_target_counts = source_counts & target_counts true_positives = sum((source_and_prediction_counts & sour...
ce2d94f3ffc353a3a9843f5c0b6a846608efe962
1,108
def dict_comparator(first_dict, second_dict): """ Функция проверяет на совпадение множеств пар ключ-значение для двух словарей Возвращает True в случае совпадения, иначе False """ if set(first_dict.keys()) != set(second_dict.keys()): return False for key, value in first_dict.item...
47f28e8810b8437cc0e3bfca6ccba6734c988890
1,110
def word_check(seq1,seq2,word): """Returns False and aborts if seq2 contains a substring of seq1 of length word. Returns True otherwise""" for i in range(len(seq1)-word+1): if seq2.find(seq1[i:i+word])>-1: return seq2.find(seq1[i:i+word]) return -1
86b4cad571fdbf55073f30f9c5fd9a5e25da46d7
1,111
def plasma_parameter(N_particles, N_grid, dx): """ Estimates the plasma parameter as the number of particles per step. Parameters ---------- N_particles : int, float Number of physical particles N_grid : int Number of grid cells dx : float grid step size """ ...
51d3b96ccba2689db461fd6117cb5c2961dc3812
1,112
import torch def get_ious_and_iou_loss(inputs, targets, weight=None, loss_type="iou", reduction="none"): """ Compute iou loss of type ['iou', 'giou', 'linear_iou'] Args: inputs (tensor): pred v...
302fb70c888caf33cf0077b553cd0d055ff4003a
1,113
def load_chembl(): """Downloads a small subset of the ChEMBL dataset. Returns ------- ic50_train: sparse matrix sparse train matrix ic50_test: sparse matrix sparse test matrix feat: sparse matrix sparse row features """ # load bioactivity and features ic5...
f9c5017ab7892f7fbf6c3ee1a1dd9da0e322f66f
1,114
import re def validate_name_dynamotable(table_name): """Validate if table name matches DynamoDB naming standards.""" if not isinstance(table_name, str): ValueError('Input argument \"name\" must a string') if table_name.__len__() < 3 or table_name.__len__() > (255 - 5): # note: deduct 5 ch...
139391e3ece6cacae24d5bd72fd0fd77b65ecc41
1,115
def delete_item(item_id): """ The method deletes item with the provided id. :param item_id: id of the item to be deleted :return: http response """ try: if DATA_CONTROLLER.delete_bucketlist_item(item_id): return make_response("", 200) else: return make_r...
95e0bb38d30cbda6d617bb5f396dba4cfd4ef328
1,116
def import_from_text_file(filename, defaultExt, readDataFcn, verbose=False): """ Opens a given text file and reads data using the specified function Parameters ---------- filename : str the path of a file defaultExt : str the default extension of the file readDataFcn : calla...
4f5602e09d02446ce9770656e4b42df5dd018ccd
1,117
def is_template_definition(metric_name): """Return if the given metric name is a template definition by convention.""" fields = metric_name.split('/') return fields[0].lower() == TEMPLATE_DEFINITION_PREFIX
da5fb191cf451b542a656c352d64258be74f7710
1,118
def _cm_ramp_points_and_voltages(abf): """ Return [points, voltages] if the sweep contains a ramp suitable for capacitance calculation using a matching doward and upward ramp. points is a list of 3 numbers depicting index values important to this ramp. The first number is the index at the start of ...
c73b5f5cbc44c0794b332f6010864e9f25fcff0c
1,119
def single_model_embeddings_specify(single_model_embeddings): """Returns an instance of MultiTaskLSTMCRF initialized with the default configuration file, loaded embeddings and single specified model.""" single_model_embeddings.specify() return single_model_embeddings
fe23c571ca29dbbf87cbccdbfc1e11aaaf784c01
1,120
import bz2 import gzip import json def load_json(filename): """ Load a JSON file that may be .bz2 or .gz compressed """ if '.bz2' in filename: with bz2.open(filename, 'rt') as infile: return json.load(infile) elif '.gz' in filename: with gzip.open(filename, 'rt') as inf...
1b985db386e85c3b8e87911d89a7652133bfee7b
1,121
def get_future_contracts(underlying_symbol, date=None): """ 获取某期货品种在策略当前日期的可交易合约标的列表 :param security 期货合约品种,如 ‘AG’(白银) :return 某期货品种在策略当前日期的可交易合约标的列表 """ assert underlying_symbol, "underlying_symbol is required" dt = to_date_str(date) return JQDataClient.instance().get_future_contracts(...
9945c897c643e410f8a127da5b77525d6e3ba28c
1,122
import urllib3 import requests def rodeo_query(fc, pallet): # 3.5-4 seconds for 150 elem """ Get pd DataFrame with info from rodeo about pallet/tote in TS Out. :param fc: str :param pallet: Pallet or Tote are accepted. :return: df or "No data was found" if status_code...
926a9f42b5ed82128d4e5fae4adc2c74dab3e567
1,123
import itertools def plan_to_joint_configuration(robot, qgoal, pname='BiRRT', max_iters=20, max_ppiters=40, try_swap=False): """ Plan a trajectory to the given `qgoal` configuration. Parameters ---------- robot: orpy.Robot The OpenRAVE robot qgoal: arra...
78bf727bede2d886ba93825e3a0cd8ccaa99f57e
1,124
def _get_texinfo(data): """Return the texture information of a texture data. Arguments: * data: the texture data as an array. Returns: * texinfo: a dictionary with the information related to the texture data. """ assert data.ndim == 3 size = data.shape[:2] if siz...
9dfa3b88e65b4c7b7eaa60149f4f24381b36e762
1,125
def set_featured_notebooks(notebook_ids): # noqa: E501 """set_featured_notebooks :param notebook_ids: Array of notebook IDs to be featured. :type notebook_ids: List[str] :rtype: None """ update_multiple(ApiNotebook, [], "featured", False) if notebook_ids: update_multiple(ApiNote...
7add2e120bf803cf8fa36c0fa56c854654c447fa
1,126
def speed_to_cadences(bicycle, speed, digits=None): """ Return cadences in hertz (revolutions per second). Speed is measured in kilometers per hour. Assume the following bicycle attributes are non-null and non-empty: - front_cogs - rear_cogs - crank_length - rear_wheel Raise a ``V...
358343831e341f49facd8b2c0af940ee765083aa
1,127
import hashlib def _gen_version(fields): """Looks at BotGroupConfig fields and derives a digest that summarizes them. This digest is going to be sent to the bot in /handshake, and bot would include it in its state (and thus send it with each /poll). If server detects that the bot is using older version of th...
a4bd4420ce548f8a0c40f3120c119f89c158a371
1,128
def pay_and_save_financing(req: request, request_json, account_id): """Set up the financing statement, pay if there is an account id, and save the data.""" # Charge a fee. token: dict = g.jwt_oidc_token_info statement = FinancingStatement.create_from_json(request_json, account_id, token.get('username', ...
0de221d2e6acb090e2e2a135b1280f2daa73b63c
1,130
def resolve_cmds_path(cmds, singlesrv_mode): """Resolve the cmds path if in single server mode. Args: cmds: A list of sender/receiver commands. singlesrv_mode: A bool on whether running in single server mode. Returns: The commands that path has been resolved if needed (in s...
6d7e673a48c657a446785716fc09f47d4f87d81d
1,131
import base64 def _encode_base64(data: str) -> str: """Base 64 encodes a string.""" ebytes = base64.b64encode(data.encode("utf-8")) estring = str(ebytes, "utf-8") return estring
5304972fec4cc54d9fa652cbd977b7c069d228d5
1,132
from typing import Mapping from typing import Any def workflow_spec( dag: DAG, workflow: Workflow, ) -> Mapping[str, Any]: """ Return a minimal representation of a WorkflowSpec for the supplied DAG and metadata. Spec: https://github.com/argoproj/argo-workflows/blob/v3.0.4/docs/fields.md#workflows...
d13b7242f3158ea7528141ca65a17df01968c14e
1,133
def redirect(request): """ Handling what happens when the groupcode is submitted by user and handles input from user's when they are answering questions. :param request: :return: The methods returns the student view page which is the actual game to the user if they entered a correct groupcode, i...
5f906dae9bde9533b5b09bd5540b8458a766e583
1,134
import torch def build_test_fn(policy, optim, log_dir, model_name, train_collector, save_train_buffer, obs_shape, stack_num, env_id, num_episodes): """ Build custom test function for maze world environment """ def custom_test_fn(epoch, env_step): # Save agent print(f"Epoch =...
6fefef23e1a502ce30f556ea9350d933e7303dfd
1,135
def check_score(encoding, min_qual, qual_str): """Return True if the average quality score is at least min_qual """ qscores = [encoding[q] for q in qual_str] return sum(qscores) >= min_qual * len(qscores)
427dd8617d5ab425e3b7989923a271599fc7371a
1,136
import functools import warnings def add_unsafe_warning(func, fig): """ Generate warning if not supported by Paxplot """ @functools.wraps(func) def wrapper(*args, **kwargs): if fig._show_unsafe_warning: warnings.warn( f'The function you have called ({func.__name...
8bca3fbc514315cd4c761b2e8f7f1168e01af7a9
1,137
from typing import List from typing import Optional def update_dask_partitions_shuffle( ddf: dd.DataFrame, table: str, secondary_indices: List[str], metadata_version: int, partition_on: List[str], store_factory: StoreFactoryType, df_serializer: DataFrameSerializer, dataset_uuid: str, ...
d7f050247d89997ec76d00cb6e2e7ed25a7b24fb
1,138
def edit_paycheck(paycheck_id): """ Edit a paycheck """ paycheck = Paycheck.query.get(paycheck_id) form = PaycheckForm(obj=paycheck) return render_template('pay/edit_paycheck.jinja', form=form, paycheck_id=paycheck_id)
9e8a22af102bc818c35c32d49b5a26c348b0f221
1,139
def is_meeting_approved(meeting): """Returns True if the meeting is approved""" if meeting.session_set.first().status.slug == 'apprw': return False else: return True
0dca106890d195f613477334d2bb6187c1587e15
1,140
import requests def check_radarr(): """ Connects to an instance of Radarr and returns a tuple containing the instances status. Returns: (str) an instance of the Status enum value representing the status of the service (str) a short descriptive string representing the status of the service...
f078ba526e0fb23dad323db92e9f6ac861da4bf0
1,142