content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def rgb_color(color: str) -> tuple: """Convert an RGB color string to an RGB tuple. >>> rgb_color('#fff') (15, 15, 15) >>> rgb_color('#500100') (80, 1, 0) """ color = color.lstrip('#') if len(color) == 3: return (int(color[0], 16), int(color[1], 16), ...
7b3d6e39db1940190cc695df2bd2a1b234594423
634,693
import os import glob def load_fileset_test_cases(): """ Creates a list of all modules, filesets and testfiles inside for testing. To execute tests for only 1 module, set the env variable TESTING_FILEBEAT_MODULES to the specific module name or a , separated lists of modules. """ modules_dir = ...
5526fd71ee2c4b53d346d714a65723fb00a0273d
634,694
def huffman_encoding_recursion(node, code=''): """ Encoding characters using recursion Args: node(HuffManTreeNode): leaf to save data and non-leaf node assign 0 and 1 to edges code(str): Assign 0 to the left edge and 1 to the right edge Returns: encode_map(dict) : huffman coding map...
ef1f6ec37e895ba12065ac32034a9f64886ad0e2
634,695
def sexticipc(ipparams, position, etc = []): """ This function fits the intra-pixel sensitivity effect using a 2D 6th-order polynomial, with cross terms. Parameters ---------- y#: #-ordered coefficient in y x#: #-ordered coefficient in x y2x: cofficient for cross-term xy^2 x2y: coefficien...
40b46ac9eeef342cc9f809ad648291c5d26bb6d0
634,696
def label2nodename(label): """ convert label e.g. '(1,2)' to nodename e.g. 'n1c2' """ lsplit = label.split(',') return 'n' + lsplit[0][1:] + 'c' + lsplit[1][:-1]
aebb5120d4ea539fe8f91de888c08ed802280539
634,697
def process_action(original_action): """add dummy flight and dummy name in the cases that they are not present.""" if 'flight' not in original_action: original_action['flight'] = 'dummy_flight' if 'name' not in original_action: original_action['name'] = 'dummy_name' return original_action['name'], origi...
4798d17908c5e9307c9d885de750ced8ac31e25a
634,698
def grad_logp(p, alpha0, x): """ d log p / dz """ return (alpha0-1.+x)/p
2f7aca50906f6dd19bd57e121c35491013232ed8
634,699
import socket def is_ipv6(ip: str) -> bool: """ A helper function that checks if a given IP address is a valid IPv6 one. Parameters ---------- ip: :class:`str` A string representing an IP address. """ try: socket.inet_pton(socket.AF_INET6, ip) return True e...
271e52c2b34fe0675e7039212f31308f3a4fa2c3
634,700
def read_form_field_string(model, form, field_name, transformation=None): """ :param model: Model containing string field :param form: Form data from front-end :param field_name: Name of field shared by model and form :param transformation: Transformation of form data to perform before inserting int...
f1b2730189f99dbd0a32ab1912b00d3a20bac268
634,701
from typing import Any from typing import Union from typing import Optional from typing import Match import ssl import re def _dnsname_match( dn: Any, hostname: str, max_wildcards: int = 1 ) -> Union[Optional[Match[str]], bool]: """Matching according to RFC 6125, section 6.4.3 http://tools.ietf.org/html/...
e7c7a3bb3186b7b852629a399935621f9d7476c6
634,702
def no_authentication(func): """ This decorator will be used to disable the default authentication check for the decorated endpoint. """ func.no_authentication = True return func
232279a8868194e3ecd740f7d00f79d64a58d749
634,703
def MAV(data): """ Mean absolute value: the average of the absolute value of the signal. Parameters ---------- data: array-like 2D matrix of shape (time, data) Returns ------- MAVData: 1D numpy array containing average absolute value Reference --------- Hudgins, B., Parker, P., & Scott, R. N. ...
3d67b7057b26807694c26dc850cc518dac042623
634,704
def linear_interpolation(pos): """ Easing function for animations: Linear Interpolation. """ return pos
b632d1efb0d3383a5b53cfc43dd9385793427148
634,705
from typing import List import struct def pack_long(data: List[int]): """ 打包长整数 """ return struct.pack(f"{len(data)}l", *data)
cfe01c4b0f7ec781c987f1cace763524319ebd06
634,706
def add_origin(transcription_pkt_list, origin: str): """[add origin field in transcription packet list] :param transcription_pkt_list: [description] :type transcription_pkt_list: [type] :param origin: [description] :type origin: [type] """ for transcriptions_pkt in transcription_pkt_list: ...
92bf18b03cbf7e5846b7ddc5cb5d23722f1e8ee5
634,707
def get_github_path(owner: str, repo: str) -> str: """Get github path from owner and repo name""" return "%s/%s" % (owner, repo)
189cae1d577ccb32ed5fa0c6f0a0a98fb74768c4
634,708
def seconds_in_a_day(): """Return total seconds(int) in a day.""" return 60 * 60 * 24
d24c7832a4aafd079d545a0120057d2fdcfed65f
634,709
def read_record(length): """Reads a line as a sequence of integers.""" ret = list(map(int, input().split())) if len(ret) != length: raise ValueError('wrong record length') return ret
bbb8319349b2664fc7ca88b6a7243d01d6d89cde
634,710
import itertools def natoms(self): """ Sequence of number of sites of each type associated with the Poscar. Similar to 7th line in vasp 5+ POSCAR or the 6th line in vasp 4 POSCAR. """ return [len(tuple(a[1])) for a in itertools.groupby(self.syms)]
e4348815be3768a280766addbccfaf5d659ccfca
634,711
def invert_dict(dictionary): """Return the functional inverse of a dictionary, raising an exception for values in `d` which map to more than one key producing an undefined inverse. """ inverse = {} for key, value in dictionary.items(): if value in inverse and inverse[value] != key: ...
1cadd7d475dd99f674bd9d35115e8ad5fac9f6ab
634,712
def recookie(wrapped): """ Decorator to mark a session as needing to recookie. This is necessary when setting a new max-age/etc :param wrapped: a function to wrap with this decorator. :returns wrapped_recookie: a wrapped function. """ def wrapped_recookie(session, *arg, **kw): resu...
c9d525ff4f8e70be266b9143ba1cef15a07a0552
634,713
def convertDate(time): """ Returns the converted time, accept only this format DD/MM/YYYY Parameters: time (string) Returns: time (int): return converted time as this format YYYYMM, so year and month """ tmp = time.split("/") retu...
135a148e3a5b5d82c7e8706e92c766ee118a9ebb
634,714
def variant_ascending_position_sort_key(variant): """ Sort key function used to sort variants in ascending order by chromosomal position. This is a function rather than method to make it easier to serialize. Returns ------- tuple of (str, int) """ return (variant.contig, variant.st...
023647936f897629b4668932e9213e921b4ef60d
634,715
def remove_zeros(res): """ res is expected to be a dictionary of dictionaries representing a flow graph. """ res1 = {} for k in res.keys(): res2 = {} for kk in res[k].keys(): if res[k][kk] > 0: res2[kk] = res[k][kk] if len(res2) > 0: ...
de6cf00214325788692d30d31ae3be6869b18391
634,716
def mutindex2pos(x, start, end, mut_pos): """ Convert mutation indices back to genome positions """ if x == -.5: return start elif x == len(mut_pos) - .5: return end else: i = int(x - .5) j = int(x + .5) return (mut_pos[i] + mut_pos[j]) / 2.0
06e09a0a3281ab2de076e28a32cc08e37c610fce
634,718
def letterCombinations( digits): """ :type digits: str :rtype: List[str] """ result = [] if digits == None or len(digits) == 0: return result phoneMap = {} phoneMap['2'] = 'abc' phoneMap['3'] = 'def' phoneMap['4'] = 'ghi' phoneMap['5'] = 'jkl' phoneMap['6'] = 'mno...
cf96e1e4cf456ccc2ca39cd8fd2b422ff97bcc70
634,719
import os import json def _get_analyses_from_json() -> dict: """Opens analysis.json and stores value in dict.""" # Handle if file doesn't exist try: with open(os.path.join('output', 'analysis.json')) as json_file: analysis_json = json.load(json_file) except FileNotFoundError: ...
4082dd1d8f964d7ddafce67796146e1a6d567a2d
634,720
import random def generateSolution( args ) : """ This function returns a possible solution to the problem, in whatever format is desired. It should be in the same format expected by all subsequent functions that will anneal, score, and undo the annealing as needed. """ toVisit = ar...
f135388b9e2381da5aa140a2abd0619c0c238385
634,721
def index_batch(x, idxs): """Index along the batch axis""" assert len(x) == len(idxs) x_indexed = [] for x_i, idxs_i in zip(x, idxs): x_indexed.append(x_i[idxs_i]) return x_indexed
8cd30933de8f3a3736a3d6aedc95a2fb2cc6ef75
634,723
def peel(event): """ Remove an event's top-level skin (where its flavor is determined), and return the core content. """ return list(event.values())[0]
47e1cf4f98cd42f4a7e34bdad83cff76c4f54df0
634,725
def LevenshteinDistance(first, second): """Find the Levenshtein distance between two strings.""" if len(first) > len(second): first, second = second, first if len(second) == 0: return len(first) first_length = len(first) + 1 second_length = len(second) + 1 distance_matrix = [[0] ...
99afb7f07281816fc3ae79bf1bae27658e99cc07
634,726
from typing import Dict import json def cors_web_response(status_code: int, body: Dict[str, str]): """Create a response when dealing with CORS.""" return { 'statusCode': status_code, 'headers': { 'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,X-Amz-Security-Token,Authoriz...
8bbc5c7a8acb96f727e74ef31c31af3084c8260c
634,727
import csv def write_csv(filename,header,rows): """ Returns None Args: filename (str): name of the results file header (str): header of the results file rows (str): row wise data for results file containg words with meaning Returns: None ...
bcb1790fbf2e8cbbd82eee6e94c5c36ef688a99f
634,730
def mac_music_app_play_playlist(playlist: str) -> bool: """mac_music_app_play_playlist(playlist: str) -> bool (internal) """ return bool()
400dc49bb777ebd857185f7489b053122b2bd03e
634,732
def parse_env_var_args(env_var_args): """ :param List[str] env_var_args: List of arguments in the form "VAR_NAME" or "VAR_NAME=VALUE" :return: Dict[str,str] Mapping from "VAR_NAME" to "VALUE" or empty str. """ env_vars = {} if env_var_args is not None: for arg in env_var_...
ab18432454eb10ee2459aac3e2f690a23988f145
634,733
def get_active_sessions_orchestrator( self, ) -> list: """Get all current active sessions on Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - activeSessions - GET - /session/activeSessions :return:...
3dd38d66816e2bdace27ab24b6609ec44ee02057
634,734
def file_parser_old(line, config): """ Parse Markdown page for compomics.github.io pages: - Replace wiki URLs to pages URLs """ line = line.replace( "https://github.com/{}/{}/wiki/".format(config['user'], config['project_name']), "https://compomics.github.io/projects/{}/wiki/".forma...
aee0e7d106422d2b94838949eb029680b454dc5b
634,735
import re def preprocess_sentences(sentences, SOS, EOS): """ Preprocess the input text by lowercasing adding space around punctuation removing strange characters tokenizing on whitespace (optional) reversing the words as suggested by the Seq2Seq paper adding <SOS> and <EOS>...
2710e2f2e8a5f475fedf1620e05b7abf83eb9c10
634,736
def moving_avg(xyw, avg_len): """ Calculate a moving average for a given averaging length :param xyw: output from collapse_into_single_dates :type xyw: dict :param avg_len: average of these number of points, i.e., look-back window :type avg_len: int :return: list of x values, list of y value...
5dbd2c596942638f0c0158e11c6b24e6f5a1ef4b
634,737
import copy def _filter_change_sets(change_sets: list, artifact_filter) -> list: """Filter the change sets with given artifact filter """ result = [] for commit in change_sets: mod_commit = copy.deepcopy(commit) # grab only source files mod_commit["file_path"] = list( ...
2a680214ae29b3e736077c864b2f7d9339d2a6fa
634,738
def wrap_kvs(store, name, *, key_of_id=None, id_of_key=None, obj_of_data=None, data_of_obj=None ): """Make a Store that is wrapped with the given key/val transformers. Args: store: Store class or instance name: Name to give the wrapper class key_of_id: To be th...
e043534bfd7b82d80d6d6a5dbff2c62052b604de
634,739
from typing import Any from typing import List def loop(xs: Any) -> List: """append the starting element of a list to the end""" xs = list(xs) return xs + [xs[0]]
af45721fb490d305ab7af5cff8e1c350038ff561
634,740
def get_all_repo_infos() -> list: """ Get list of all registered repo uris get_manifest_repos Gather together list of dicts for each repo using get_repo_json_data Also insert the repo path from get_repo_path as the path attr into each dict :return list of dicts containing repo info...
7344745f223f06c1f4ed9ded09100981d34743a5
634,742
def _tls_version_check(version, min): """Returns if version >= min, or False if version == None""" if version is None: return False return version >= min
cead61442b56de46ae79af80c58bc2b8f2586c26
634,743
import sys def getter(var): """Create an accessor for given variable.""" frame = sys._getframe(1) return lambda: var in frame.f_locals and frame.f_locals[var] or \ frame.f_globals[var]
137b8c78a3a4b58a7baf45dd7b9f5d02eb7faae1
634,744
def confirm_retry(): """确认是否再次练习""" while True: n = int(input('再练习一次?<Yes…1/No…0>:')) if n == 0 or n == 1: return n
f230079aef2fdc5c7b5d737823c006e05b9da8c1
634,745
def __num_digits(num: int): """internal helper to get the number of digits""" return len(str(num))
aa2b372a90031aec5253c2db0076b39ae3a87211
634,747
def get_serializer_error_response(error): """ Returns error response from serializer :param str error: message :return: error_response :rtype: object """ error_response = {"status": 422, "data": [], "message": error} return error_response
a9e7555535e8f75e5fbac2e427b26035fdcc5487
634,748
def standardize(X): """Z-transform an array param X: An N x D array where N is the number of examples and D is the number of features returns: An N x D array where every column has been rescaled to 0 mean and unit variance """ return (X - X.mean())/X.std(ddof=1)
35e60ed5d73de36fdc80b1d2189033d0c81a6d9b
634,749
def default_prompt(category: str) -> str: """Create the user prompt for selecting categories of options. Args: category (str): The type of thing being selected (assignment, section, etc) Returns: str: The user prompt """ return f"Which {category} would you like to grade? >>> "
9ac72c6ce3e82630197d7301d256d6867ac7fa32
634,750
def energy_intensity(df,df1,distance,col1,col2): """ Inputs: df = dataframe with data df = dataframe with energy factors distance = distance in meters col1 = Replaced_mode col2= Mode_confirm """ df1 = df1.copy() df1[col1] = df1['mode'] dic_ei_factor = dict(zip(df1[col1],df1['ene...
f6235b7d1011e75aedf3373f957c5c881b5396e6
634,751
def append_node_bin(dag, op, arg1, arg2): """This function generates and appends a node, which corresponds to a binary operator application, to the DAG. Returns: the node key. """ k = '('+arg1+op+arg2+')' if k not in dag.keys(): dag[k] = (op, arg1, arg2) return k
fd1dfe0dee839ac2229b242c837699cbe8f0d9dd
634,753
import subprocess def subprocess_call(parameter_list): """ Calls subprocess.call() with the parameter list. Prints the invocation before doing the call. """ print("subprocess.call:\n %s" % " ".join(parameter_list)) return subprocess.call(parameter_list)
6658770a1a5eefdcacfcb7a26a791f4309cf0ce1
634,754
def canPickupPile(top_card, prepared_cards, played_cards, round_index): """Determines if the player can pick up the pile with their suggested play-always True for Liverpool""" return True
426a0b04190b3b06122b910313240e250316bc42
634,755
def get_activations(model, image): """ do a forward pass (ignore the output), then return the _value_hooks """ _ = model(image) return [getattr(module, "_value_hook") for name, module in model.named_modules() if hasattr(module, "_value_hook")]
88c8311ddac898aea6374dc1874c9bcd28e3bd7d
634,756
from typing import List from typing import Tuple import torch def create_grid( grid_sizes: List[int], grid_bounds: List[Tuple[float, float]], extend: bool = True, device="cpu", dtype=torch.float, ) -> List[torch.Tensor]: """ Creates a grid represented by a list of 1D Tensors representing t...
f784bcf1177579e61f7794cecc645c0bbc338929
634,757
from typing import Sequence from typing import Dict from typing import List import random def part_frags( part: Sequence, catalog: Dict, dur: float, ) -> List: """Creates a random rhythmic fragment that conforms to a given partition. The argument 'dur' is the length of the measure. """ n...
267fe566c364795651392c73cc8784369ae10079
634,758
import copy def response_ctrl_ack(**kwargs): """ Policy-based provisioning of ACK value. """ try: tlv, code, policy = kwargs["tlv"], kwargs["code"], kwargs["policy"] new_tlv = copy.deepcopy(tlv) new_tlv['ope'] = 'info' return [new_tlv] except Exception as ex: p...
ee495defb168d58021a4d3295cb8f45e64e5d027
634,759
import uuid def generate_slug(model) -> str: """Generate a unique slug Args: model (cls): Django Model Returns: slug (string) """ query_manager = model.objects slug = uuid.uuid4().hex[:6] while query_manager.filter(slug=slug).exists(): slug = uuid.uu...
5219320b740083843a10055eb8b78409624fcebf
634,760
def _func_or(current, checks): """Implementation of Or.""" return any(check(current) for check in checks)
4cf152cf838299bfd647fa3a1451e82b390180cd
634,762
def grade_duration(durations_pair): """ 对时值打分 - 时值变化剧烈 (超过 4 倍), -1 分 """ duration1, duration2 = durations_pair if duration1 == duration2: return 1.0 elif max(duration1 / duration2, duration2 / duration1) == 2: return 0.75 elif max(duration1 / duration2, duration2 / duration1...
9540c6a0d8ecee9ca4d5927721f859e8bb026232
634,764
def openlog(): """ Open connection to system logger""" return NotImplementedError()
ed7ada856788d996c7a87efe33b6b3fdc3258c96
634,765
def extract_indices_python( original_indices, selected_indices, pid, selected_pid, preserve_particle_index ): """ Go through the sorted arrays `pid` and `selected_pid`, and record the indices (of the array `pid`) where they match, by storing them in the array `selected_indices` (...
6d5d4259ca01ae7bff38cf2017d8c7a1382063f3
634,766
def get_biggest_face(array_of_faces): """ :param array_of_faces: array of faces returned from detector.detectMultiScale() :return: a 1x4 array containing the face with the biggest area (width*height) """ largest_area = 0 largest_face = None for face in array_of_faces: area = face[2] ...
904fafe95756ee164da09e49f286027d8ceceefb
634,767
def prior_data(): """Prepare sample prior data.""" return { "image_size": (300, 300), "feature_maps": (4, 2), "min_sizes": (2, 1), "max_sizes": (3, 2), "strides": (2, 1), "aspect_ratios": ((2, 3), (2,)), }
40ae4c50b673a329d98ca9548b738b446b4a983b
634,768
import time def request_rnn_prediction(input_value, net): """ Accesses a single prediction from the RNN. """ start = time.time() output_value = net.generate_touch(input_value) time_delta = time.time() - start #print("Prediction took:", time_delta) return output_value, time_delta
294e74dae1c43a21a22b57040562d36b9d8ed8d1
634,769
def escapeAttr(sText): """ Escapes special character to HTML-safe sequences. """ sText = sText.replace('&', '&amp;') sText = sText.replace('<', '&lt;') sText = sText.replace('>', '&gt;') return sText.replace('"', '&quot;')
38fdd523bd69c0239e722a3368a585c04b1106a7
634,770
def area(r, shape_constant): """Return the area of a shape from length measurement R.""" assert r > 0, 'A length must be positive' return r * r * shape_constant
e3a3a1178d053ee6857b2cb33b1106d2c5ee294b
634,772
import hashlib def generate_hash(value, hash='sha1'): """ Generate a hash for a given value. By default generate a `sha1` hash. Other hash can be specified. If so all supported hash algorithms are listed in `hashlib.algorithms`. Returns a String. """ sha_obj = getattr(hashlib, hash...
b14aee9b4091020f27cdca1c5df2cef19eaf2f41
634,773
import re def extract_words(sentstr, stops): """ simple utility to word tokenize a text string and remove stop words :param sentstr: input string of text :param stops: list of stop words to remove :return: """ words = re.sub(r"[^\w]", " ", sentstr).split() cleaned_text = [w.lower() for...
8868af10e3ee4924a7fe341b8a5fa0e624fe1bba
634,774
def TTD_TT_UB_rule(M, i, j, w, t): """ Every day of every week for each (window, ttype), there can be no more people scheduled (TourTypeDay) than number of people assigned to TourType[window, ttype]. :param M: Model :param i: window :param j: day :param w: week :param t: tour type ...
7ff1cbd45e518a76bf94dd30d09e1a1da1bef5a1
634,775
def float_or_na(s): """ Convert string to float or NaN for "NA" for missing data Parameters: s - string representation of integer or "NA" Return value: integer value of s or NA_VALUE """ return float("NaN") if s == "NA" else float(s)
808e4bc7a94639e54d0ea9d7e4c7d700a1d66dc4
634,776
def word_count(data): """ 输入一个字符串列表,统计列表中字符串出现的次数 参数 ---- data: list[str],需要统计的字符串列表 返回 ---- re: dict,结果hash表,key为字符串,value为对应的出现次数 """ re = {} for i in data: re[i] = re.get(i, 0) + 1 return re
40edfdcf65e5312ee302b341ba61921fd9f5a46e
634,777
def create_data_set(): """data_set 基础数据集 args: 无需传入参数 returns: 返回数据集和对应的label标签 """ # 特征分别为:长相、学历、幽默、收入、是否喜欢 data_set = [[0, 1, 0, 1, 'yes'], [1, 1, 1, 1, 'yes'], [0, 0, 1, 0, 'no'], [1, 0, 1, 1, 'no'], [1, 1, 0, 1, 'yes...
53482a207aab5bfe133c2b6c5d38600286a4ddea
634,778
import random def gen_next_match_pick_randomly(population): """ Decides next two player indexes who will play against each other by randomly selecting two players from the list of players available""" available_players = [player for player in population if player.available] p1 = random.choice(availab...
50d980169fe39f356831be06d50500eab959bb21
634,780
def list_or_none(lst): """Returns a stringified list or 'None'.""" return ",".join(map(str, lst)) if lst else "None"
5cd555fb07c99e6570d3e53bea5c216d2dcb7cbf
634,781
def GetDimensions(line): """ Parse and extract X, Y and Z dimensions from string Parameters ---------- line: string Line containing x, y, z dimensions Returns ------- (nx,ny,nz): (int,int,int) The dimensions on x, y, and z coordinate respectively ...
39d314cc6892f89a7c5cbfbd363fc2167c319071
634,782
import typing def s3_key_join(parts: typing.List[str], is_dir: bool) -> str: """ A human friendly s3 key join function. This func won't work properly if double slash exists. For example, "prefix//surfix" will become "prefix/surfix" """ # strip ending "/" and duplicate "//" new_parts = list() ...
0a6ed3981d90fa81008ae89c30dfb0c69f1cfcda
634,783
def get_serial_number_key(serial_num: str) -> str: """Get the compressed search serial number key for the MH serial number.""" key: str = '' if not serial_num: return key key = serial_num.strip().upper() if len(key) > 20: return key[0:20] return key
a1dc1836bf5dbc71d2b7275c6b180c1c15e49c36
634,784
def get_bucket_arn(bucket_name, region="", account_id=""): """ We need the arn of a queue """ bucket_arn = f"arn:aws:s3:{region}:{account_id}:{bucket_name}" return bucket_arn
c74b22676897d63d74b6780f019b4c5d76293e24
634,785
import json def load_schema(schema_file_name): """ This function handle the loading of the schema """ try: with open(schema_file_name, 'r') as f: schema = json.load(f) # print(json.dumps(schema, indent=4)) return schema except Exception as e: # print(e) ...
11f16a9273a9343b2c8e5c8f8d1201e78c4ec9d8
634,787
def isValidId(id_, v=0x0110000100000000, y=1): """Reverse Steam ID formula taking full community ID and decoding the account ID. Args: id_ (int) : steam community id v (int, optional) : account type, defaults to user: 0x0110000100000000 y (int, optional) : account universe, defaults to p...
8f9a2b8809ba855095c758c33984f714c8b3b33f
634,788
def df_rolling_params_codegen(): """Generate rolling parameters""" params = ['window', 'min_periods', 'center', 'win_type', 'on', 'axis', 'closed'] return ', '.join(f'self._{p}' for p in params)
53576aa8dd5aae7ca5496da0abfb949dc0e3778f
634,789
def factory_project_oidc_config(): """JSON data to create oidc config.""" oidc_config = { 'project_id': 0, 'client_id': 'ee72e9abab', 'client_secret': '6DjuDS_w7cbFfkotp1l0AumgjJ5Ng8j8lpUCezuC', 'registration_access_token': '633537303539616631306330306235663', 'registrati...
3711bf5b7f4689ad84d244960174ecca503bd23d
634,790
import re def cut_iframes(value): """ Filter which cut <iframe> tags. """ pattern = re.compile(r'<p><iframe .*</iframe></p>') return re.sub(pattern, '', value)
a8ab5e1f0c1c55a225c7d041374aba041d10e6d2
634,791
import os def GetImagesPath(): """ Helper function: Get the relative /images/ path Returns ../../images/, or ./images/, as appropriate """ # Try from the implementation directory: imagesPath = "../../images/" if not os.path.isdir(imagesPath): # Try from the project root: i...
6d99487d368b5907d68bf6a9e854e889f18b6703
634,792
import sys import os def _get_running_interactive_framework(): """ Return the interactive framework whose event loop is currently running, if any, or "headless" if no event loop can be started, or None. Returns ------- Optional[str] One of the following values: "qt5", "qt4", "gtk3", "...
e7fdf09b093c3fb40dd8b887a4a7559d1b801b23
634,793
def find_headers(lines): """Identify headers and line breaks.""" for i in range(len(lines)): if lines[i][1] == '-'*78: lines[i][0] = 'pagebreak' lines[i+2][0] = 'header' i += 3 return lines
5307892c752425d5ef07c691a345706dc127190d
634,794
from datetime import datetime def timestamp_from_dt(dt, epoch=datetime(1970, 1, 1)): """ Convert a datetime to a timestamp. https://stackoverflow.com/a/8778548/141395 """ delta = dt - epoch # return delta.total_seconds() return delta.seconds + delta.days * 86400
700486da04340fd433aa427ef7a537a72554a371
634,796
def _get_specie_str(specie, include_phase): """Gets the specie string Parameters ---------- specie : :class:`~pmutt.empirical.nasa.Nasa` object Specie to use include_phase : bool, optional If True, includes the reaction phase. Default is True Returns ------- ...
33c4e11e7476f12e49b9ce3dd69fa17808d0d6b1
634,797
from typing import List def find_problematic(numbers) -> List[int]: """ - Time: O(n * m) - Space: O(n) * n = len(numbers) * m = len(largest number in numbers) """ non_problematic = {'2', '3', '4', '5', '7'} result = [] for number in numbers: n = str(number) skip = ...
1bcd65fe689b18667d7c172e433b7facd9e8ead3
634,798
def mahalanobis2(x, mu, inv_sigma): """得到马氏距离""" d = x-mu return d.T @ inv_sigma @ d
61969ed9d6246b691978878733cd175d0318c236
634,799
def __find_figures(tex_proj_root, figure_formats=['.pdf', '.png']): """ Finds all figures in 'tex_proj_root' directory. """ figures = {} for _path in tex_proj_root.rglob('*'): if _path.is_file() and _path.suffix in figure_formats: # This can be used without parts, but the path w...
506690cfaf682b4a18a1c45a63ed3fa3b9d309d2
634,800
def line_split(line): """Fastest line-splitter (should be fast for IronPython)""" line_list = [] [line_list.append('"' + chunk + '"') if i%2==1 else line_list.extend(chunk.split()) for i, chunk in enumerate(line.split('"'))] return line_list
364d300c46232fa3386c6b81736b4cb159b73be0
634,801
def f(m, n): """ Parameters ---------- m : int n : int Returns ------- int """ if m == 0: return 2 else: sum_ = 3*f(m-1, n) i = 2 while m-i >= 0: sum_ += (-1)**(i+1) * f(m-i, n) i += 1 sum_ += ((-1)**(n % 2))*(m...
cefe97001dbc0577c95a473b6b19280c068ca9ef
634,802
import hashlib import random def random_token(extra=None, hash_func=hashlib.sha256): """ Extracted from `django-user-accounts` """ if extra is None: extra = [] bits = extra + [str(random.SystemRandom().getrandbits(512))] return hash_func("".join(bits)).hexdigest()
2064e8c2db72bfd98a00982c8275d678a0baf133
634,803
def _log_kwargs(msg='', **kwargs): """ Utility to return a message with kwarg variables appended """ kwarg_msg = ' '.join([('%s: |%s|' % (str(key), kwargs[key])) for key in kwargs]) return "%s %s" % (msg, kwarg_msg)
77fdc6421fdecf17db7d2475493a82c8138e6742
634,804
def fill_nan_in_category(df): """fill NaN with mode""" print(" --- Filling NaN in Categories.") columns = df.columns categorical = [x for x in columns if x.startswith('c_')] df[categorical] = df[categorical].fillna('missing') print(" --- Finished filling NaN in Categories.") return df
88aa1b83069931ad6c1f6af827a0cc71c4219854
634,805
from typing import Any def is_instance(obj: Any, class_or_tuple: type | tuple[type, ...]) -> bool: """A more forgiving isinstance.""" try: return isinstance(obj, class_or_tuple) except: return False
c8d2004f32b3ee38f314339393e6d96e5f3ee4a8
634,806
def getKoreanColors(i, n): """ Make a palette in the korean style """ n = float(i)/float(n)*3. R = (n<=1.)+ (2.-n)*(n>1.)*(n<=2.) G = n*(n<=1.)+ (n>1.)*(n<=2.)+(3.-n)*(n>2.) B = (n-1.)*(n>=1.)*(n<2.)+(n>=2.) R, G, B = [int(i*255) for i in [R,G,B]] return R,G,B
aeeba5521150f6b98b96935e4bacfade438032b7
634,807