content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def func_name(func): """Get a readable name.""" return '.'.join([func.__module__ or "", func.__name__])
e71a3d293a794bcb98d8a5496102067a5aa695db
669,578
def unique(sorted_list): """Return a new list containing all unique elements in their original order Keyword arguments: sorted_list -- a list of comparable elements in which all duplicates are next to one another """ res = [] last = None for element in sorted_list: ...
d36c4edf296c9d5f10ffbf2ec0e6b699041457f5
669,579
import subprocess def getCondaPackage(module): """ Check the version of any conda package """ try: lines = subprocess.check_output(['conda', 'list', '-f', module]).splitlines() packages=[] # Strip comments for line in lines: if line[:1]=='#': ...
5676ff1b96c091150356efe76700435c5f3f92cc
669,580
import math def compute_quaternion_w( x, y, z ): """Computes the Quaternion W component from the Quaternion X, Y and Z components. """ # extract our W quaternion component w = 1.0 - (x ** 2) - (y ** 2) - (z ** 2) if w < 0.0: w = 0.0 else: w = math.sqrt( w ) return w
ff90a0c2de59c89ecdaf2fc2250ad18611f9a59b
669,581
def add_ovpn_user(device, user): """Add an OpenVPN user (assumes ovpn server is already installed) :Param device: device :type device: Object :param user : client name (Eg: "lan") :type user : str :return: addded user (eg: lan.ovpn) :return type: str """ device.sendline('./openvp...
0f639dade209a29329f5caac55ec428a63955db7
669,582
from typing import Callable from typing import List from typing import Any import time def time_find_two_smallest(find_func: Callable[[List[float]], Any], lst: List[float]) -> float: """Return how many seconds find_func(lst) took to execute. """ t1 = time.perf_counter() find_func(lst) t2 = tim...
24071eddf30ddfb21877b2307be2cffa59736a18
669,583
import os def get_abs_working_dir(path): """Get absolute path to parent dir.""" return os.path.dirname(os.path.abspath(path))
444b5319a970b45684442f279a4551f3a5ac0540
669,584
import re def clean_fn(filename): """ 移除文件名中的特殊字符 :param filename: 文件名 :return: 处理后的文件名 """ return re.sub(r'[\\/:*?"<>|]+', '', filename)
1b893718b15ae98ba0c13ce564d8339039565294
669,585
def replace_arabic(str): """ Replace arabic character with farsi/persian character Parameters ---------- str : str Input letter Returns ------- str Persian character letter """ ar = ['ي', 'ك', '٤', '٥', '٦', 'ة'] fa = ['ی', 'ک', '۴', '۵', '۶', 'ه'] for i...
b9c950208291bde3896b7394ad6a8876a25c3f78
669,586
import math import torch def ucb_scores(parent, children: dict, dir_noise: bool=False): """ The score for an action that would transition between the parent and child. """ c_puct = 5 dir_alpha = 0.35 x_dir = 0.6 prior_scores = {move: child.prior_prob * math.sqrt(parent.visit_count) / ...
06cca5c2c65783742eb25d968b45e7233d363b2d
669,587
def is_in_any_txt(txt, within_txts_list, case_insensitive=False): """is "txt" in any of the texts list ?""" for within_txt in within_txts_list: if case_insensitive: # slower if txt.lower() in within_txt.lower(): return True else: if txt in within_...
5e5316fdbaf21617ee8ae3172a0efe4a3c17ae8c
669,588
import re import json def convert_md_to_json(text, name): """Converts markdown text to JSON, creating a dictionary where its root is: { "document" : document_name "level": 0 "content" : [] } content contains a list where each node has a lower level than any of its children. A node might not ha...
77353691e2b2a7a697c994f9cec707af92daf2ad
669,589
from typing import Dict import gzip import json def load_contexts(context_filepath:str)->Dict[str,str]: """ コンテキスト(Wikipedia記事)を読み込む。 """ contexts={} with gzip.open(context_filepath,mode="rt",encoding="utf-8") as r: for line in r: data = json.loads(line) title=dat...
e10b4cdb45337c5fa50e3389f7f0aaa3918d12a1
669,590
from datetime import datetime async def do_request(client, url, headers, params=None): """Run request to `url` with the provided `params` and `headers`.""" def requester(url): if params: return client.post(url, headers=headers, json=params) else: return client.get(url,...
bfe6b849dc3642e089c380168d123339e075b5e5
669,591
def html_suffix(string): """Replace or add an html extension to a filename string.""" e = string.split('.') return '.'.join(e[:-1]) + '.html' if len(e) > 1 else e[0] + '.html'
0b246f39cac629ce1921f7e5e49a481509412493
669,592
from typing import Tuple from typing import Any def range(query: Tuple[int, int], field_name: str, object: Any) -> bool: """ Check if value of object is in range of query """ return query[0] < getattr(object, field_name) < query[1]
1a4c4422ffb0091c0c008331ae2ba1f0b266347a
669,593
import dataclasses def to_arg_format(cfg): """ Converts the values of a config in dictionary format to tuples (type, value). This is needed to separate dtype from default value for argument parsing. We treat `None` and `MISSING` as `str`, which is a useful default for parsing command line argumen...
c8d01d2b01e9cf4c946fb5dffa53d812dfccc483
669,594
def _read_dump_to_lookup(data_dump): """ reads from a list of file names and creates a dictionary in which keys are file names and values are the content of those files. File names are unique and are http addresses of the original source. included brute error handling to manage corrupt data :p...
4ae917b056e3b52c6fe10b22a9637de5a266f79e
669,595
def cw(bot,input): """Whitelist Clan""" if not input.admin: return False bot.config.set_add('clanwhitelist', input.group(2).lower()) bot.reply("Whitelisted clan {0}".format(input.group(2)))
bedc9c2522e3531be675b16bf6cfd398d5e5bae4
669,596
import tempfile import os def tar_unpacker(tar_path, **kwargs): """ unpacks tar to a tmp directory. Kwargs: tar_path (str): tar file path versbose (bool): True enables verbose returns: tmp_path (generator): extracted contents path Examples: tar_unpacker(tar_path=...
a9a4fba8fc9b918fedcd88fa0c5d0ea69f3f17c1
669,597
def get_Q_HEXC(region, Q, hex, etr_dash_t): """熱交換型換気設備による暖房負荷低減を考慮した補正熱損失係数 Args: region(int): 省エネルギー区分 Q(float): 当該住戸の熱損失係数 (W/m2K) hex(bool): 熱交換換気の有無 etr_dash_t(ndarray): 熱交換型換気設備の補正温度交換効率[-] Returns: float: 熱交換型換気設備による暖房負荷低減を考慮した補正熱損失係数 """ # 地域の区分が 1 地域~7地域において...
93846d2b0ca46c25d62079471c9d8d8fe721e8d1
669,598
import requests def get_client_creds_ad_token(tenant_id, client_id, client_secret): """ NOTE!! this is a simple method that should not be used in production """ url = "https://login.microsoftonline.com/{tenant_id}/oauth2/token".format(tenant_id=tenant_id) payload = "grant_type=client_credenti...
e085ce57e96ac540cf3b23b9fc3c79f6593a73a7
669,599
def get_distinct_ec(ecnumbers): """ 将多功能的EC编号展开,返回唯一的EC编号列表 Args: ecnumbers: EC_number 列 Returns: 排序好的唯一EC列表 """ result_list=[] for item in ecnumbers: ecarray = item.split(',') for subitem in ecarray: result_list+=[subitem.strip()] return sorted(list...
b520fef0ed4bf880e7b0ba398e9fe58b9c50f6ca
669,600
import argparse import os def _parse_args_cfg_subcmd(args: list) -> argparse.Namespace: """Parse arguments of the form 'manim cfg <subcmd> <args>'.""" parser = argparse.ArgumentParser( description="Animation engine for explanatory math videos", prog="manim cfg", epilog="Made with <3 by...
b981dd0f29d1b843a89dab4bea605d4d0dc8991d
669,601
import numpy def calc_inv_d_by_unit_cell_parameters( index_hkl, unit_cell_parameters, flag_unit_cell_parameters: bool = False): """ Calculate 1/d for given reflections hkl and unit cell parameters defined as [a, b, c, alpha, beta, gamma]. """ a, b = unit_cell_parameters[0], unit_ce...
47838b9116e18bb2168a4d77d358fafbe20d84dc
669,603
def convert_dictvals2tuple(args): """Convert from dictionary to tuple of dictionary values.""" for arg in args: if type(args[arg]) == dict: args[arg] = tuple(args[arg].values()) return args
35610da79ce3eb6444a2fe962f8c5efd751b1516
669,604
def reshape_flattened_frames(array): """ Reshapes array shaped [frames, height*width] into array of shape [frames, height, width] Parameters ---------- array : np.array flattened array (frames, height*width) Returns ------- np.array reshaped array (frames, height, widt...
0dfdedb6c7c86116883efa312126af8372daa7b4
669,605
import re def _str_is_float(data): """Verify if data is float.""" return re.match( r"^[-+]?(0|[1-9][0-9]*)(\.[0-9]*)?(e[-+]?[0-9]+)?$", str(data), flags=re.IGNORECASE)
f15e1126b7330b6bcd5cf22546ea9026987d910e
669,606
def _CanReportAnalysis(analysis): """Returns True if the analysis can be reported, False otherwise.""" return analysis.start_time and analysis.end_time
3bea955a3965004cb2e08a2022e8dfdf0bb76b96
669,607
from datetime import datetime def get_time(): """Get the current UTC time""" utc_time = datetime.utcnow() return '## ' + utc_time.strftime("%H:%M") + '\n'
316711a19611e7896303043c29248811c27a2937
669,608
import ast def unwrap_unary_node(node: ast.AST) -> ast.AST: """ Returns a real unwrapped node from the unary wrapper. It recursively unwraps any level of unary operators. Returns the node itself if it is not wrapped in unary operator. """ if not isinstance(node, ast.UnaryOp): return n...
c704115985580f16e21be83c7e6c97921e3f1ea3
669,609
import argparse from pathlib import Path def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--fasta', required=True, type=Path) parser.add_argument('--gtf', required=True, type=Path) parser.add_argument('--output_dir', required=True, ty...
bb7c07749fca33ebdf3f77e661f0718f09e410c5
669,611
def str2ds_fixed(strings): """ Convert dicom tag text of fixed point numbers to :param strings: :return: """ h = ['{:15.10f}'.format(x) for x in strings] return h
affe29099edc9b32c1cb6f8375753bd68d8e43de
669,612
def euclidean_shape(shapes): """ Returns shape of euclidean distance output. Inputs: shapes - Tuple of two shapes. """ shape0, shape1 = shapes return (shape0[0], 1)
94d8cf7f8c25db0b01873797bbca597ff9107e1d
669,613
import random def load_word_set(filename): """loads the words used as bingo labels, first line is the center""" lines = open(filename).readlines() if len(lines) < 25: raise Exception("Not enough labels in %s" % filename) total_word_list = [x.strip() for x in lines] center_word = total_wor...
8f3de270b41c1ea50a18711f19a2e73c3dc8f03b
669,614
def _get_editable_repo_dir(script, package_name): """ Return the repository directory for an editable install. """ return script.venv_path / 'src' / package_name
baf3cd8346eabb73bdc20929ed0e40a5fd543414
669,615
def scaling_model_auto_rules(experiment): """Use dials.scale rules for determining suitable parameters.""" osc_range = experiment.scan.get_oscillation_range() scan_width = osc_range[1] - osc_range[0] if scan_width < 5.0: scale_interval, decay_interval = (1.0, 1.5) elif scan_width < 10.0: ...
77d5dd097a1ed1634e9947dce3cdc47a9f247841
669,616
def LD(s: str, t: str) -> int: """Levenshtein distance""" s = ' ' + s t = ' ' + t d = {} S = len(s) T = len(t) for i in range(S): d[i, 0] = i for j in range (T): d[0, j] = j for j in range(1, T): for i in range(1, S): if s[i] == t[j]: ...
5a188a7b480818d8c51b4a60aa1a6bf46fb4f0fd
669,617
import torch def get_loss_n_accuracy(model, criterion, data_loader, args, num_classes=10): """ Returns the loss and total accuracy, per class accuracy on the supplied data loader """ # disable BN stats during inference model.eval() total_loss, correctly_label...
348b0c8cf08ba23dbf6eddac5ca45627d7244f50
669,618
def distance_km(point1, point2): """ Convert from degrees to km - approximate." Args: point1: Array-like with 2 members (lat/long). point2: Array-like with 2 members (lat/long). Returns: float: distance in kilometres """ return ((point1[0] - point2[0]) ** 2 + (point1[1] ...
cd0cd652340f37fdc93bd4e4bf65c21b0b0628bf
669,619
def is_valid_file(ext, argument): """ Checks if file format is compatible """ formats = { 'output_sdf_path': ['sdf'], 'output_pdb_path': ['pdb'], 'output_simulations': ['json'], 'output_simulation': ['zip'], 'output_pdb_zip_path': ['zip'], 'output_mutations_list_t...
04c6913635a44dd073fed724f2f6c968596b7111
669,620
def sign(value): """Returns the sign of the given value as either 1 or -1""" return value / abs(value)
28daa4de89c4ae8c09745b36c00de468875fb7cd
669,621
from typing import Union from datetime import datetime def time_from_timestamp(timestamp_in: Union[int, float]) -> datetime: """ Convert timestamp to :py:class:`datetime <datetime.datetime>` object. :param timestamp_in: Number representing the epoch. :return: :py:class:`datetime <datetime.datetime>` ...
6abeaced426b4b22e772d7bfa9ec9f5eef182d1d
669,622
def format_html(html): """ Helper function that formats HTML in order for easier comparison :param html: raw HTML text to be formatted :return: Cleaned HTML with no newlines or spaces """ return html.replace('\n', '').replace(' ', '')
6f06f074b0546ed1ca0d0365c250a40f6ddb58e2
669,623
import torch def L1_regularization(model): """ :param model: nn.Modules :return: """ re_l1 = 0 for para in model.parameters(): re_l1 = re_l1 + torch.abs(para).sum() return re_l1
c37cf94a230f0d12ada4368ced6ab4f96c1f14c3
669,624
def _transform_array(data, is_array, is_scalar): """Transform an array into a scalar, single value array or return in unmodified.""" if not is_array: return data[0] if is_scalar: return [data[0]] return data
64c47ffe45bc3e2c58ea2ec17e84600d638fd0d7
669,626
def check_bounds(bounds): """ Check a bounds array is correct, raise ValueError if not Parameters: bounds - the bounds array to check. Of form (minx, miny, maxx, maxy) or (left, bottom, right, top). Returns: the bounds array, if valid """ if not ((bounds[0] <= bound...
99c9ebc3a780831470dc95965e700f1aa5cc612e
669,627
import random def clip_random(number: float, low_b: float, upp_b: float) -> float: """A random clipping. -------------------- Args: number: The number for the clipping. low_b: The lower bound. upp_b: The upper bound. -------------------- Returns: 'random.unifo...
3adeaed2f87987263896ad0aa6ba6b1408697d93
669,628
def curtail_string(s, length=20): """Trim a string nicely to length.""" if len(s) > length: return s[:length] + "..." else: return s
48b6624983b810517651d89185761210ba95ad27
669,629
def merge_utt(conversation, split_token_idx=None, keep_split_in_tail=False, final_token_idx=None): """merge utterances in one conversation. Args: conversation (list of list of int): conversation consist of utterances consist of tokens. split_token_idx (int): index of split token. Defaults to No...
c50ab2fba0203bd601d793d6517e7aa65ecc23a3
669,630
def sort_summoner_name(name, name2, name3): """Adds spacebar formatting for names """ if name2 == "": return name else: concat_name = name + "%20" + name2 if name3 != "": concat_name += "%20" + name3 return concat_name
c6b8e4f8914a20f718bbe781d8af22fc41eb8ad6
669,631
import math def atan(ang_rad): """ tan^-1 in degree """ return math.atan(ang_rad)*180/math.pi
8b2782cf9db69f19d1c42700edf61642cc4081db
669,632
def icingByteFcnSEV(c): """Return severity value of icing pixel. Args: c (unicode): Unicode icing pixel. Returns: int: Value of severity portion of icing pixel. """ return (ord(c) >> 3) & 0x07
8eab1513b0431e89f9b56c4c2e1fe68f77466409
669,633
def iterate_items(dictish): """ Return a consistent (key, value) iterable on dict-like objects, including lists of tuple pairs. Example: >>> list(iterate_items({'a': 1})) [('a', 1)] >>> list(iterate_items([('a', 1), ('b', 2)])) [('a', 1), ('b', 2)] """ if hasattr(di...
0410eacc3f02f1cfb14a90cbd550fb9f503ea319
669,634
def extract_test_prefix(raw_fullname): """Returns a (prefix, fullname) tuple corresponding to raw_fullname.""" fullname = raw_fullname.replace('FLAKY_', '').replace('FAILS_', '') test_prefix = '' if 'FLAKY_' in raw_fullname: test_prefix = 'FLAKY' elif 'FAILS_' in raw_fullname: # pragma: no cover te...
45e12753a6dd24a25577827ac11f6cdcf297da8f
669,635
import time def ms(): """ Arguments: None Description: Returns time in millisecond Returns: Time in millisecond """ return time.time_ns() / (10 ** 6)
0e9e5147885fabe337a80ee11e49fc85c6e42634
669,637
def split_name(name): """Split a name in into parts delimited by commas (at brace-level 0), and each part into words. Returns a list of of lists of words. """ brace_level = 0 parts = [] current_part = [] word = '' for char in name: if char in ' \t,': if brace_lev...
46d7e04b0820b43ab65b80e2d8560eb1705db569
669,638
def verify_entry_compatibility(e1, e2): """ Verify that the two entries @e1 and @e2 are compatible. If the entries are compatible, returns (True, diff). Otherwise, returns (False, diff). Here diff is a list of differences between @e1 and @e2. Each list element is a tuple of (name, e1, e2). In ...
59e4df5944993a54844ad4e27a9e28629bf6ae4d
669,639
from typing import Callable import functools import asyncio def do_after(after_function: Callable) -> Callable: """Decorator to execute a function or coroutine function after the decorated function.""" def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): if as...
de8b68e29cabd9b67075c45ab83249a72ebd3a1e
669,640
from typing import Dict def make_combo_header_text( preposition: str, combo_dict: Dict[str, str], pop_names: Dict[str, str], ) -> str: """ Programmatically generate text to populate the VCF header description for a given variant annotation with specific groupings and subset. For example, if prepositi...
5126a2cd20922668eaa5fa3834e681a8188012b1
669,641
from functools import reduce def move_sequence(state, move_indexes=[]) : """Produces a sequence of states, starting with the input state. For Connect Four, note that a move index may be different from a column number; for example, if the first open column is column 2, it will have a move index of 0.""...
2c031e13f110f7e8304a66adb9c2c0ab080dd1dd
669,642
import torch def get_all_predictions(model, loader, device): """Get All predictions for model Args: model (Net): Trained Model loader (Dataloader): instance of dataloader device (str): Which device to use cuda/cpu Returns: tuple: all predicted values and their targets ...
aca84ffaa16408bc691d60c8207318c7e214a509
669,643
def full_empty(): """Matches an empty string""" return r"^$"
5bdfb79be866eb272303f83a9d46400f01f311c4
669,644
import time def get_current_time(): """ Возращает текущее время в формате "%Y.%m.%d_%H:%M:%S". :return: str """ return time.strftime("%Y.%m.%d_%H:%M:%S")
1ffea5bcad1110018df3161575959a3b9b7255e8
669,645
def format_path(template, name, delimiter): """Fills the placeholders to get the path. Args: template (str): A string that contains blanks to be filled. name (str): An option name of section defined in settings.txt. delimiter (str): The signal of a blank's beginning position. Retur...
d5841d7b3bea208a473758d8fc7ca64c0ec6a044
669,647
def megagcd(a, b): """needs in diophantic function""" if b == 0: return a, 1, 0 d, x, y = megagcd(b, a % b) return d, y, x - y * (a // b)
3ea5f63f7d50b42995cf74e033de8740e1f67a28
669,648
def kwargs_from_keyword(from_kwargs, to_kwargs, keyword, clean_origin=True): """ Looks for keys of the format keyword_value. And return a dictionary with {keyword:value} format Parameters: ----------- from_kwargs : dict Original dictionary to_kwargs : dict Di...
5ac871ae7703ea6a55f742ce6a7ff4f24d0a90ee
669,649
import re def get_drizzle_regex(): """ Returns the compiled regular expression used to find drizzle keywords. Returns ------- drizzle_expression : object A compiled regular expression of the starting keyword name for drizzle. """ drizzle_keyword_pattern = r"d(\d\d\d)" driz...
e846ea4a80897ce2f24047c9f054ac00bb6162ba
669,650
def m_p_s_to_km_p_hr(m_p_s): """Convert to km/hr.""" return m_p_s * 3.6
478e3931dcab3301079b0fbc692124c3c3c93557
669,651
import base64 def base64_decode(base_data): """ base64解密 :param base_data: :return: """ bytes_data = base64.b64decode(base_data) return bytes_data
71c28b1af8a6373dfa0a45e1425f6d60a1e46d34
669,653
from datetime import datetime def convert_eu_to_us_date(date): """Receives a date string in European format of dd/mm/yyyy, e.g. 11/03/2002 Convert it to an American date: mm/dd/yyyy (in this case 03/11/2002). To enforce the use of datetime's strptime / strftime (over slicing) the tests check ...
e9b32acb164c4ef91980b57c0b14028a7c88fb0d
669,654
def check_dataset(adata): """Check that dataset output fits expected API.""" return True
8dd03e90c2e4983a8537c40370f9a90c49a372c8
669,655
def get_utc_time(cur): """Get current time in UTC timezone from Central Server database""" cur.execute("""select current_timestamp at time zone 'UTC'""") return cur.fetchone()[0]
bd80981e5d81dff44f348aab0064cd0f3a2c9ef3
669,656
import re def validate_ip(ip): """ Validates an IPv4 or IPv6 IP address """ regex = re.compile('^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.)' '{3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$|' '(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}| ' ...
ffdafcf172620133a947f5898365b6063707be47
669,657
def list_diff(list1, list2): """Compute list differences in order. Args: - list1: first list - list2: second list Returns: - out: list difference """ out = [] for ele in list1: if not ele in list2: # noqa: E713 out.append(ele) return out
ca2c796ef5fd7b418ba965b899756f5755857e9a
669,658
def extract_name_from_job_arn(arn): """Returns the name used in the API given a full ARN for a training job or hyperparameter tuning job. Args: arn: """ slash_pos = arn.find("/") if slash_pos == -1: raise ValueError("Cannot parse invalid ARN: %s" % arn) return arn[(slash_pos...
8c95295866b876bdcf0088823b805a499d45a126
669,659
def homepage(): """Flask default routing""" return 'greetz fren'
37f509dffe4ed4d2eab079534891c147674fc237
669,660
def convert_to_binary(fb_id_list): """Change the fb ids column in to a minary list. If an id is present represent the value as 1. If none represent as 0. """ final_list = [] for item in fb_id_list: if item == None: final_list.append(0) else: final...
12c22d4274fd2f93a7520fb3b80c54162606f610
669,661
import re def check_boot_var(ssh_conn): """Currently only handles a single boot system statement.""" current_boot = ssh_conn.send_command("show run | inc boot") match = re.search(r"^(boot system flash .*)$", current_boot, flags=re.M) boot_cmd = '' if match: boot_cmd = match.group(1) re...
e659101cd49abee124def27bb96d2b069ad3cef2
669,662
from typing import Tuple import re def get_float(number: str) -> Tuple[float, int, str]: """ Returns a proper float value Args: number: A string of the identified number Returns: A tuple of the float, the float precision and sign """ dots = number.count(".") commas = num...
81c5512cd284e54294cc0d2ec562fcbce947bcd9
669,663
def is_valid_account(screen_name): """Check if Twitter screen name is valid.""" return True
04d23c4335f89093a6eb39cc21d01b31949d6ec3
669,664
def kmers(s, k): """create an array with kmers from one string""" if len(s) <= k: return [s] return [s[i:(i+k)] for i in range(len(s)-k+1)]
890a9bd8f4fe9fc2911c7fef4fbb804ffc8e7562
669,665
import struct def parse_user(user_id): """ Swap bytes order in user id """ return [x for x in struct.unpack("4B", struct.pack("<I", user_id))]
3dd540ec9ae246d50a9d0e47d7d44f7a4410f68a
669,666
def scene_names(self) : """ access method for scene names returns a dict of ( Node names : Node address ) """ if not self._groups2addr : self.load_nodes() return self._groups2addr[:]
df2b4dd54c448a5e70867701ed6cf1d809294c0d
669,667
def transparency(img): """estimate transparency of an image""" (r, g, b, a) = img.split() (a_min, a_max) = a.getextrema() # get min/max values for alpha channel return 1 if a_min == 255 else 0 if a_max == 0 else -1
248c133f4915ca9208b0b47f34406367f88024d8
669,668
def read_data(data_path): """ 数据读入之后,得到一个所有评论的sentences列表 ,和一个与之一一对应的labels列表。 :param data_path: :return: """ senlist = [] labellist = [] with open(data_path, "r", encoding='gb2312', errors='ignore') as f: for data in f.readlines(): data = data.strip() sen = data.split("\t")[2] label = data.split("\t...
cdd4bc439da0f134dfff8b4d4f7ac0013cac261d
669,669
def remover_empty(df): """Funcion que recibe un DataFrame y aplica strip() para remover espacios en blanco en cada columna del DataFrame""" # Para cada columna del df, remover espacios en blanco al inicio, al final y guardar en Dataframe for column in df.columns: df[column]=df[column].str.strip() ...
6db004bad0e28edf82071ef0a28a590316066438
669,670
import pickle def read_file(filename='bins.prdb'): """ Read binner from file :param filename: Path to file :return: Binner instance """ with open(filename, 'rb') as inp: binner = pickle.load(inp) return binner # бининг в файл
a8f7ad3e499d433a0948ec766f0791551df1a51e
669,671
def _add_dicts(*dicts): """ Creates a new dict with a union of the elements of the arguments """ result = {} for d in dicts: result.update(d) return result
073f70d718b2ee8d5a55c9ee6854510766754354
669,672
def cleaned_code(arg): """ Strip discord code blocks """ arg = arg.strip('`') if arg.startswith('py'): arg = arg[2:] return arg.strip()
06271be1adc55d289598ee8fd600346f56faf015
669,673
import sys def _readline(myprompt): """ Prompts the user for input and returns the line read. Used for reading commands in the Ferret command loop. Just uses the built-in function raw_input. Since the readline module was imported, readline features are provided. Arguments: mypro...
8060d38f1e666b61e8fb34b86709683073c57fc7
669,674
def download_complete_check(driver): """ This checks the download list and waits for all the downloads to complete and then closes the webdriver. Args: driver (object): Webdriver object from selenium.webdriver """ if not driver.current_url.startswith("chrome://downloads"): driver.get("chrome://downloads/") ...
85086eeaf9ecf38972881acad7b24f41f207eb37
669,675
import copy def update_model_config(config: dict, suggestions): """returns the updated config if config contains any parameter from suggestions.""" cc = copy.deepcopy(config) def update(c): for k, v in c.items(): if isinstance(v, dict): update(v) elif v.__c...
10ec8d38dbd888386c52f87a4119d49bcabdf2ac
669,676
def edge_index_set_equiv(a, b): """Compare edge_index arrays in an unordered way.""" # [[0, 1], [1, 0]] -> {(0, 1), (1, 0)} a = a.numpy() # numpy gives ints when iterated, tensor gives non-identical scalar tensors. b = b.numpy() return set(zip(a[0], a[1])) == set(zip(b[0], b[1]))
4b214b7061739a77f77240c9f957c2a802dde4ff
669,677
import decimal from datetime import datetime def json_decoder(obj): """ :param obj: python data :return: converted type :raises: """ if isinstance(obj, decimal.Decimal): return float(obj) if isinstance(obj, datetime): return obj.strftime('%Y-%m-%d %H:%M:%S.%f') if isins...
54118235eb0eb8c70cfe5bcf6b08a5c76c4f1d15
669,678
import sys import unicodedata def _get_punct_translation_table(): """Get the punctuation translation table.""" return dict.fromkeys( ( i for i in range(sys.maxunicode) if unicodedata.category(chr(i)).startswith("P") ), " " )
c3423b8ba3a5d222f831e8d1070fb4ba21f4d374
669,679
import uuid def create_random_uid(truncate=False) -> str: """generates globally unique UUID E477FD7C-AA07-40B0-BEF8-825F1B7FCE41 len: 8-4-4-4-12 chars returns: 8-char string (first part of UUID)""" uuid_str = f"{str(uuid.uuid4())}" if truncate: return uuid_str.split("-")[0] else...
37e90bd7df39c96a377cce024564faf1befad8e4
669,680
def sort_data(x, y, filename_y, lab_x=None): """Sort data based on the length of x""" test_lab_x = lab_x test_xy = zip(x, y, filename_y) if not (lab_x is None): test_xy = zip(x, y, filename_y, lab_x) # Sort tuple based on the length of the first entry in the tuple test_xy = sorted(test...
776983530b3805d2f0a7d8dd4f82eb8b1d27a886
669,682
import os def scan_directories(D, testdir): """Recursively scans a directory tree for candidate of relevant directories, where testdir(D,dirs,files) return a True boolean value. We will *not* follow symlinks. The testdir function must have this kind of prototype: testdir(D, dirs, files) where: ...
919466dccf4cf7f1472b9df31ae9b5127431e4cd
669,683
def effector(): """ Creates a function that returns the next item from a sequence each time it is called. If the item is an exception, it will be raised. For use with Mock.side_effect to simulate a mixture of successful calls and exceptions. """ def effector_(sequence): iterator = iter(...
33d772432831dad4db11278a0e85714f642211cc
669,684