content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import socket
def check_remote_port_whether_open(remote_addr, remote_port):
""" Check the remote port whether open
:param remote_addr: Remote host's ip address
:param remote_port: Remote host's tcp port
:type remote_addr: string
:type remote_port: int
:return: A boolean value to decide the po... | 943af8cf5d18561495eed08e1fff763089a422dd | 656,981 |
def stringListaksi(string, delim=",", poistaTyhjat=True):
"""
Paloittelee merkkijonon erottimen (delim) kohdalta listaksi, poistaa listasta tyhjät
merkkijonot (jos poistaTyhjat=True), siivoaa ylimääräiset välilyönnit ja muuttaa
tekstin kirjainkoon pieneksi. Oletuserotin on pilkku.
"""
lista = [s... | 7cec2336d45ab72485b7f5008b089d7eb0be5ef0 | 656,985 |
def are_blocking_checks(checks, ignore_warnings):
"""
Return True if checks are errors or unignored warnings.
:arg dict checks: dictionary with a list of errors/warnings per library
:arg bool ignore_warnings: ignores failed checks of type warning
"""
has_errors = any(p.endswith('Errors') for p ... | cc8d1e8ca9d0ee77b0384d3ea5863fff7d46350f | 656,987 |
def _split_gradient(gradient: float, ratio: float) -> tuple[float, float]:
"""
(s+h)/2 = c
s = 2c-h
---
s-1 = r*(h-1)
s-1 = rh-r
s = rh-r+1
---
2c-h = rh-r+1
h(r+1) = 2c+r-1
h = (2c+r-1)/(r+1)
s = 2c-(2c+r-1)/(r+1) = (2cr+r-1)/(r+1)
"""
highlight = (2 * gradient +... | 6216e5c13ed412b317ff3c07f5dff04bbd98a927 | 656,990 |
def parse_contrast(contrast, samples, check=True):
"""
Extract contrast batch and column, target and reference groups from a DE contrast design.
Check for contrast validity if check = True.
If "all" is in the contrast groups, it is always assumed to be the target
(and expanded to mean all groups in... | 8c9e31662f2ce13b1c069e767a567b9bb8e1b389 | 656,991 |
def update_vehicle_profile(spawn_profile, new_vehicle):
"""
Updates the vehicle profile of the spawning profile
:param new_vehicle: new vehicle profile
:param spawn_profile: spawning profile
:type spawn_profile: SpawningProfile
:type new_vehicle: VehicleProfile
:return: updated spawning prof... | c019c99a66bd8c79927e3ccf63fef6fecc7ae5da | 656,994 |
import operator
def _cross_platform_stable_fs_iter(dir):
"""
Provides a stable ordering across platforms over a directory Path.
This allows iteration across filesystems in a consistent way such that case
sensitivity of the underlying system does not affect how the files are
iterated.
Args:
... | 0cd1de96f754cf4e95e37602fa9666799498d87e | 656,997 |
def count(seq):
""" Count the number of items in seq
Like the builtin ``len`` but works on lazy sequencies.
Not to be confused with ``itertools.count``
See also:
len
"""
if hasattr(seq, '__len__'):
return len(seq)
return sum(1 for i in seq) | 7094eb12434707606336056851c43340b474b96d | 657,000 |
def range_corrector(g_range):
"""Swap start and end if start > end."""
chrom, start_end = g_range.split(":")
start_end_split = start_end.split("-")
start, end = int(start_end_split[0]), int(start_end_split[1])
if start < end:
return g_range
else:
return f"{chrom}:{end}-{start}" | d361c1594d4cd7dfaef123c1dff6a368f6c73fac | 657,001 |
import re
def combine_tops(top_text, itp_texts):
"""
Search through parent topology top_text and replace
#include lines with the relevant child topologies
from the dictionary itp_texts
"""
for itp in itp_texts:
# split on include string, then rejoin around itp file
spl = re.spl... | 2d21b6f4f015844f85f3b7563f538ceb9fc3b4a5 | 657,004 |
def residuals(constants, function, x, y):
"""
Function used to optimise the fit of the curve to the data.
It calculates the distance between y-value from real data and y-value from the function (sigmoid/sine/etc).
"""
return y - function(constants, x) | 55d4a1ba11fdc6854a4820831f3749f2a4e4931d | 657,006 |
def rgb_maximize(r, g, b, scale=255):
""" Calculates full luminosity RGB values from rgb chromacity coordinates
:param r: Red ratio
:param g: Green ratio
:param b: Blue ratio
:param scale: Output R,G,B values scale
:return: RGB tuple
"""
ratio = scale / max(r, g, b)
return tuple(int(... | d52f76ef47e0bf6ff547860411681649e6509eb1 | 657,012 |
from operator import contains
def project_contains_keywords(project, keywords):
"""Returns True if project contains at least one of the keywords."""
# Iterate over all sprites and backdrops, and the project itself.
for child in project["children"] + [project]:
# Perform a DFS on each script look... | 00a2749d54a189d5ff4b6bbe2833e97f3ba89aba | 657,015 |
def filter_lines(infile,outfile,wind,nskip=0) :
""" Read from input linelist file, output comments and lines falling in windows of [w1,w2] to outfile
Args :
infile (str) : name of input file
outfile (str) : name of output file
wind (list of [w1,w2] pairs) : list of window ranges
... | e6b5687f8cc18732fc5b2add132d4bad88d3e3a7 | 657,017 |
def read_file_as_str(filepath):
"""
Reads the file content
Args:
filepath (str): File to read
Returns:
str : File contents in string
"""
with open(rf"{filepath}") as fd:
content = fd.read()
return content | 515d3316485d9608fdb63b447a562b6175a902e0 | 657,018 |
def tile_key(layer, coord, format):
""" Return a tile key string.
"""
name = layer.name()
tile = '%(zoom)d/%(column)d/%(row)d' % coord.__dict__
ext = format.lower()
return str('%(name)s/%(tile)s.%(ext)s' % locals()) | 7307c97bec1743818243530342655346d5f0cd4f | 657,019 |
from typing import List
from typing import Any
from typing import Tuple
def index_2d(seqs: List[List[Any]], target: Any) -> Tuple[int, int]:
"""Finds the first index of a target item within a list of lists.
Args:
seqs: The list of lists to search.
target: The item to find.
Raises:
... | 2129616317c090bde73c56a7420574e0fd2e3208 | 657,024 |
def get_count(results):
"""Creates a dictionary, word being the key, and word count being the value"""
counts_dict = dict()
for word in results:
counts_dict[word] = counts_dict.get(word, 0) + 1
return counts_dict | 2ceb1fcf08704b6a5feb579a6ad1ada2cb33ba7d | 657,026 |
import struct
def memory_read(dev_file: str, address: int, length=1) -> tuple:
"""
reads bytes from a rc2f memory file
@param dev_file: the memory to use
@param address: where to read
@param length: how many bytes to read
@return: the read bytes as a tuple
@rtype: tuple
"""
with op... | 3afa015e4eb9d5702d0fa483f04b3f1c4f261567 | 657,031 |
def dt_to_str(dt, fmt='%Y-%m-%d %H:%M:%S'):
"""
datetime转换为字符串
:param dt: datetime
:param fmt: 字符串格式
:return:
"""
return dt.strftime(fmt) | e92537766c4da60bfbfa6bdbd824b9320aafa758 | 657,041 |
def length(database):
"""Computes the total number of tuning entries"""
num_tuning_entries = 0
for section in database["sections"]:
num_tuning_entries += len(section["results"])
return num_tuning_entries | eb82ca660593d8bc17fac3fab5cba67411e7cf15 | 657,045 |
def eval_e_x_polarized_using_e_x_unpolarized(e_x_unpolarized):
"""Decorator function for computing e_x for spin polarized case.
The spin-scaling relation for exchange energy is used:
e_x(rhoa, rhob) = 0.5 * (e_x(2*rhoa) + e_x(2*rhob))
Args:
e_x_unpolarized: function to evaluate exchange energy density
... | ea79e88a541331d2aee80dc4b558135d1b5887ea | 657,048 |
def minRefuelStops_DP(
target_distance: int, start_fuel: int, stations: list[list[int]]
) -> int:
"""1-D Dynamic Programming
DP_table[num_stops]
the furthest distance (== max gas) that we can get
with num_stops times of refueling.
So for every station, stations[i],
if the curre... | af445b1af66e2758eb5a7f9ac0032a90b60963db | 657,049 |
import torch
def generate_grids(fh: int, fw: int) -> torch.Tensor:
"""generates grids using given feature map dimension
Args:
fh (int): height of the feature map
fw (int): width of the feature map
Returns:
torch.Tensor: fh x fw x 2 as x1,y1
"""
# y: fh x fw
# x: fh x ... | 50e22caa38522f9f369e745fa025927eee472413 | 657,052 |
def normalize(position):
""" Accepts the 'position' of random precision, and returns the block
which contains that position
Params
-------
position: tuple of the len(3)
then Returns:
-------
block_position: tuple of ints of len(3)
"""
x, y, z = position
x, y, z = (int(round(x))... | 3f22b5350183876d9a0da8f76bbf9cd67b8d38cb | 657,055 |
def even_chars(st):
"""
Finds all the even characters in a string.
:param st: string value.
:return: a sequence (index begins with 1) of all the even characters from a string. If the string is smaller than
two characters or longer than 100 characters, the function should return "invalid str... | 9883e3e480767ead87973d6001615876eb69c993 | 657,056 |
def not_yet_found(input_site, d_tracker):
"""if site has not yet been found, return True, else False"""
if input_site not in set(d_tracker.keys()):
return True # not yet
else:
return False | 4e78d8c000ff67303982d3a31fbc3af22e1d5f6c | 657,062 |
def get_num_shards(path):
"""Get number of shards in sharded dataset."""
return int(path.split('@')[-1]) | aac36b741cae2eb9fec605ddcc05e35afb78e844 | 657,064 |
def _get_value_indices(names1, names2, lookups):
"""
>>> _get_value_indices(['foo', 'bar', 'baz'], ['foo', 'bar', 'baz'],
... ['bar', 'foo'])
[1, 0]
>>> _get_value_indices(['foo', 'bar', 'baz'], ['FOO', 'bar', 'baz'],
... ['bar', 'FOO'])
[1, 0]
>>> _... | 1251056d1b6e72b75c97273fcaee05be12ec1de5 | 657,066 |
def byte_to_human(size):
"""Transform the size in bytes into the appropriate unit of measurement.
:param int size: Size in bytes.
:return: Actual size in B/KB/MB/GB.
:rtype: str
"""
try:
size = int(size)
except ValueError:
return (0, "B")
um = "B"
if size < pow(2, 2... | 0cb578eb7415030576cf65dd3ddc3f5dd0b35e08 | 657,069 |
import random
def sort_by_lenght(words):
"""
(basic DSU example)
1. Build a list of tuples with word lenght and a random number as sort keys
2. (reverse) sort the list
3. Extract the (now sorted) elements of the original sequence
"""
l = []
for w in words:
l.append((len(w), ran... | 8c72b4ea7def6a31eb07d4f81ef11161cd12657c | 657,079 |
def half(x: float) -> float:
"""Half the value"""
return x / 2.0 | da3ec8aeca71e88055fd9cd2d73d4e6290b16f35 | 657,083 |
def get_valid_init_tree(trees):
"""Returns first NewickTree entry that is not NoTree"""
for i in range(len(trees)):
if trees[i] == "NoTree":
continue
else:
return trees[i] | 69841abe1e8720c42104a961e8165306b399f710 | 657,084 |
def dict_remove_none(_dict):
"""
Removes key-value pairs from a dictionary where the value is `None`. Does
not handle nested dictionaries.
:param _dict: `dict`
:returns: `dict`
"""
return {k: v for k, v in _dict.items() if v is not None} | 1a3fe2478c1945aa5cadb29f15602820e742d354 | 657,087 |
def lovibond_to_srm(lovibond: float) -> float:
"""
Convert from Degrees Lovibond color system to
Standard Reference Method (SRM) color system.
"""
return 1.3546 * lovibond - 0.76 | 306907abaa1ccc5bd3f8f94c560b72571851425f | 657,088 |
def parser_shortname(parser_argument):
"""Return short name of the parser with dashes and no -- prefix"""
return parser_argument[2:] | 9827697680cab831f0c0a435e743955a3ede1859 | 657,091 |
def retrieve_actor(world, bp_regex, role_name):
""" Retrieves the actor from the world with the given blueprint and the
role_name.
Args:
world: The instance of the simulator to retrieve the actors from.
bp_regex: The actor's blueprint to be retrieved from the simulator.
role_name: T... | ffda48e81ee56ccee1ab2ee2dac851b5035f381b | 657,092 |
def part1(depths):
"""
Count the number of times a depth measurement increases from the previous measurement
How many measurements are larger than the previous measurement?
"""
depth_increases = 0
previous_depth = depths[0]
for depth in depths:
if depth > previous_depth:
... | 56c5dd124d1dfa83ff5aaf6c5570e96fa38cafd7 | 657,094 |
import torch
def convert_to_one_hot(index, action_size):
"""
Converts a given input to a one hot vector
Parameters
----------
index: int
index of the one
size: int
size of tensor
Returns
-------
torch.tensor
output tensor one hot
"""
one_hot_action = torch.zeros((1, action_size))
one_hot_action[0]... | ced45e296c9856eddaf9d94dbe59348cb456bb4d | 657,096 |
import json
import base64
def base64_to_dict(byte_string):
"""
:param byte_string: base64 encoded string
:type byte_string: str
:return: python dictionary decoding of byte_string
:rtype dict
"""
return json.loads(base64.b64decode(byte_string).decode('utf-8')) | 9258a648ea1021e0a45dbf13535c3a9d300c503f | 657,099 |
def get_placesWithMissingTokens(t, net, marking):
"""
Get places with missing tokens
Parameters
----------
t
Transition to enable
net
Petri net
marking
Current marking
"""
placesWithMissing = set()
for a in t.in_arcs:
if marking[a.source] < a.weig... | 4d606c82f888d63425db8ead36f5bbf8413cadfe | 657,100 |
from pathlib import Path
def create_task_name(path: Path, base_name: str):
"""Create the name of a task from a path and the task's base name.
Examples
--------
>>> from pathlib import Path
>>> create_task_name(Path("module.py"), "task_dummy")
'module.py::task_dummy'
"""
return path.a... | 5b9b2e84c3f0a08eab41ac851ed3b3f66cc45b47 | 657,101 |
def parse_latitude(value):
"""
Parse latitude in the form "S10" or "N10".
"""
latsign = {'N': 1, 'S': -1}
if "N" in value or "S" in value:
return latsign[value[0]] * float(value[1:3]) | bad86ed72c3fd2609412cfcdb8d2ac030ddb73e9 | 657,103 |
from typing import List
def build_uri(scheme: str, loc: str, paths: List[str] = [], **kwargs) -> str:
"""
Used to build URIs
:param scheme: scheme e.g. http in http://google.com/
:param loc: netloc e.g. google.com in http://google.com/
:param paths: a list of paths e.g. ["example", "path"] in http... | e2d03f675c5a91631edbc185c7bebca54284b882 | 657,105 |
def series(*resistors):
"""Calculate an equivalent resistory value for series resistors.
Given resistor values as input, assume they are put in series in a circuit, and
return the equivalent resistor value as if they were a single resistor.
"""
return sum(resistors) | 55223cbc69845c2b2fce366d1747cb77a1405e16 | 657,108 |
def _get_mins_and_secs_str_from_secs(delta):
""" Returns minutes and seconds from a seconds number """
mins = round(delta / 60)
secs = round(delta-mins*60)
if (secs == 60):
mins += 1
secs -= 60
time_text = (f"{mins} minute" if mins > 0 else "") + ("s" if mins > 1 else "") + \
... | 7593e168e6de90eb00bcc8844ae66e268c531a7b | 657,113 |
def catch_error(list_like):
"""
if none of the options are true, something has gone wrong
:param list_like: a list_like of bools
:return: true if at least one is true, else returns false
"""
for b in list_like:
if b:
return True
return False | 77521db384a822968a878c836c59d78203ced499 | 657,122 |
from typing import Counter
def plurality_value(examples: list):
"""
Returns the most common classification in a list of examples.
:param examples: list of dictionaries with examples as entries, must
contain the key "classification"
:return: str, most common classification
"""
return C... | caa07726075e45c3bdec5041d55a56f9f6342164 | 657,123 |
import json
def pack_message(routing_id, message):
""" Pack a routing id and Message into a mutlipart zmq message.
Parameters
----------
routing_id : str
The zmq socket identity to place first in the message.
message : Message
The Message object to serialized into the multipart m... | e7ba6aa223c5779dd7d93bc1747bc1624b163909 | 657,124 |
def retry(value, multiplier=1.5, max_value=100000):
"""Creates callable that increases resource value on retries.
This function is intended for use with resources,
especially memory (mem_mb).
Parameters
----------
value : int
The value that will be multiplied on retries.
This v... | b3faa378ab57d17f3ae642204bead127f43b94bd | 657,127 |
def check_distance_residue(AA, H):
"""
Parameters
----------
AA : amino acid from a protein structure object made with PDBParser().
H : hetero residue from a protein structure object made with PDBParser().
Returns
-------
distance : the smallest distance between the two residues
(i... | 3e3ffc8d8b3aaa028040fa49a0d843795b059706 | 657,128 |
import pytz
from datetime import datetime
def float_to_datetime(timestamp, tzinfo=None):
"""
Convert a timestamp to a datetime instance.
If tzinfo is passed, interpret the timestamp in the given timezone.
If tzinfo isn't passed, interpret the timestamp as UTC.
For example, epoch starts at 1am CET... | f74dadce58664115e7f29c92723540be4e5f71e9 | 657,135 |
from typing import Any
import time
def measure_time(func: Any) -> Any:
"""
Measures and prints execution time for function.
Args:
func: Function to monitor.
Returns:
inner function.
"""
def inner(*args, **kwargs):
start = time.time()
try:
return fun... | bc1096ad33752b16f6f2042dead503250dc2dd40 | 657,137 |
import hashlib
def md5_for_file(f, block_size=2**20):
"""
Reads in a file, f, using a configurable block size, block_size.
Returns an md5 hash of the content of the file
"""
m = hashlib.md5()
with open(f , "rb" ) as f:
while True:
buf = f.read(block_size)
if no... | 755bf925b2d1d7d5a474b567f2ae2d9798e2eb65 | 657,138 |
from typing import List
def calculateVoltageDifference(adapters: List[int]) -> int:
"""
Given a list of adapters, calculate product of 1-volt and 3-volt diffs
"""
oneDiff: int = 0
threeDiff: int = 1 # your phone adapter's diff
prev: int = 0
for i in range(len(adapters)):
diff: int = abs(pr... | 83facdd5579c23e817cb04d92e3ce675504812a6 | 657,139 |
def search(misp, **kwargs):
"""
Search the MISP server and return records that match
misp: The MISP server connection object
kwargs: The specification of the search (e.g. controller="attributes", org="CIRCL")
"""
res = {}
try:
r = misp.search(**kwargs)
if r.get('errors'):
... | 1328139502f4968b922e16a080f487c07f34bb4f | 657,141 |
def str_timedelta(dt, max_num_fields=3, short=False, negative_to_zero = False):
"""
Given a dt in seconds, return it in a HH:MM:SS format.
:param dt: a TimeDelta object
:param max_num_fields: maximum number of non-zero fields to show
(for instance if the number of days is non-zero, shows only
... | c083ea4bdb6cc15f15034afd909c373d3af583aa | 657,142 |
import math
def areaToDiameter(area):
"""Returns the diameter of a circle based on a given area
Args:
area (int): The area in pixels.
Returns:
diameter (int): The diameter of the corresponding circle.
"""
return (2 * math.sqrt((area / math.pi))) | 95b9df916d0351148e5a016714ab7aca2d298d80 | 657,143 |
def escape(s):
"""Escape characters forbidden by Telegram API"""
# to_escape = '_*~[]()`#+-|{}.!'
# for c in to_escape:
# s = s.replace(c, '\\' + c)
return s | 3dce0d2ac3dcfb207b9956f803b8bfa9539ff35b | 657,145 |
def proxify(scraped_urls,prefix):
"""
This method takes a list of scraped urls and turns them into urls that
go through the UW Library proxy so that all of them are full access.
"""
proxy_urls = []
for url in scraped_urls:
sd_id = url[32:]
newlink = prefix + sd_id
proxy_... | a9e66c33b1ee0fd9c7b754cf8c443acbb98232f4 | 657,147 |
def get_intent_by_name(intent_list: list, intent_name: str):
"""Get an intent by name from an intent list."""
for intent in intent_list:
if intent.display_name == intent_name:
return intent
return None | 4b1137a788d891baef29bd4b4df26172c773f943 | 657,150 |
def read_file(fname):
"""
Get a file into a list of strings (one entry=one line)
"""
with open(fname) as f:
lines = f.readlines()
return lines | d0322839e510c46209b6716739a6f371292e17a5 | 657,160 |
def sort_dict_desc(dictionary):
"""Sorts dictionary in descending order by values."""
return sorted(dictionary.items(), key=lambda item: item[1], reverse=True) | da218da1f4fea7f7bd9ba9d310e86f37a9ee28e1 | 657,163 |
def modular_geometric_sum(x, n, mod):
""" Compute a_n = (1 + a^1 + ... + a^{n-1}) % mod
using that
a_{2n} = ((x_n + 1) * a_n) % mod
a_{2n+1} = (x^{2n} + a_{2n}) % mod
"""
if n == 1:
return 1 % mod
elif n % 2 == 0:
return ((pow(x, n // 2, mod) + 1) * modular_geometri... | 5ec1af73ec6229679c1075a49c21bdb0eccc53f8 | 657,175 |
from typing import Union
def join(value: Union[tuple, list, str], separator: str = ':') -> str:
"""Uses ``.join`` to squash a list or tuple using a separator.
Args:
value: Value to be squashed.
separator: Separator to be used to squash.
Returns:
str:
A squashed string.
... | 51e0ecd03582e1bf4428c212a65a0c82396f76d4 | 657,177 |
def from_sdss_albd_to_megacam_albd(sdss):
"""Return A(lbd) for the 6 Megecam filters: u, g, r, i_old, i_new, z."""
megacam = {}
megacam['u'] = sdss['u'] - 0.241 * (sdss['u'] - sdss['g'])
megacam['g'] = sdss['g'] - 0.153 * (sdss['g'] - sdss['r'])
megacam['r'] = sdss['r'] - 0.024 * (sdss['g'] - sdss['... | e3e40d9a303a2b64632fe24fe3f6192691585ae0 | 657,181 |
def get_cameras_with_filter(cameras, filter_name):
""" Get a dict of cameras wit the required filter.
Args:
cameras (dict): Dict of cam_name: camera pairs.
filter_name (str): The filter name.
"""
cameras_with_filter = {}
for cam_name, cam in cameras.items():
if cam.filterwhe... | 877b6d7459a562e42140cc7315538f9887920b8f | 657,186 |
import operator
def eval_RPN(tokens: list[str]) -> int:
"""Returns the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, and /. Each operand may be an integer or
another expression. Note that division between two integers should truncate
toward zero. It is gua... | 6e19a2959c9350115fe054673be68091c085a59d | 657,188 |
def _replace_characters(s: str) -> str:
"""Replace characters that are not suitable to present in Labber.
Returns:
Labber compatible string.
"""
if not s:
return ""
chars = [
("\n", " "),
("\r", ""),
('"', "`"),
("'", "`"),
(";", ":"),
... | e64b7501870179fcc9f18d2fcd0a99a8738b4c68 | 657,191 |
def to_classname(filename: str) -> str:
"""
maps divided mock class file name to class names
inverse function of headersplit.to_filename
e.g. map "test/mocks/server/admin_stream.h" to "MockAdminStream"
Args:
filename: string, mock class header file name (might be the whole path instead of t... | afebaa59d2155134c43e16302240ee773c46b0cd | 657,192 |
from io import StringIO
def render_pil(image, fmt="jpg"):
"""
Render PIL Image to base64.
:param image: given image.
:param fmt: image format.
:return: rendered image.
"""
if not callable(getattr(image, "save", None)):
return None
output = StringIO()
image.save... | 9f24fe4e74691c252a06d4da2caf8974f59f8fb1 | 657,193 |
def tuplefy(value):
"""Returns the value in or as a tuple if not already a tuple."""
return value if isinstance(value, tuple) \
else tuple(value) if isinstance(value, list) else (value, ) | 5007719d88f62002425f293af37a6bbc37f8dfcd | 657,195 |
def _sh_cmd(system, *args):
"""
Helper function to build a local shell command
"""
if len(args) == 0:
return None
return args | 232653f8f1170fb5715860206678e560a40000e3 | 657,196 |
def split_alpha_mask(RGBA_mask):
"""Splits alpha mask and RGB image.
# Arguments
RGBA_mask: Tensor [batch, H, W, 4]
# Returns
Color tensor [batch, H, W, 3] and alpha tensor [batch, H, W, 1]
"""
color_mask = RGBA_mask[:, :, :, 0:3]
alpha_mask = RGBA_mask[:, :, :, 3:4]
return... | bebd13559ccd67e4b37ac88449db17d388f2ce23 | 657,198 |
def change_elements(items, old_index, new_index):
"""Switch places of two elements in list collection."""
new_items = items[:]
new_items[old_index], new_items[new_index] = new_items[new_index], new_items[old_index]
return new_items | 0fefd4e6b79b0583b483f5cb0d303de77d0e1c92 | 657,202 |
def event_wrapper(function):
"""
Useful to wrap callbacks for calling in a different context.
"""
def f(event):
function()
return f | a922d7179edb42bac9b0ce08f918e0e72ecc36cc | 657,206 |
import random
def _apply_randomness(value, random_factor):
"""
Applies a random factor to the value
:param value: Input value
:param random_factor: Random factor, must be between 0 (no random) and 1 (output is between 0 and 2* value)
:return: Value with random factor applied
"""
if random_... | f9efa3839e5ac513bf3b5f8dc4dc021d1ad0d03f | 657,207 |
def has_solution(cell):
"""Return True if cell is marked as containing an exercise solution."""
cell_text = cell["source"].replace(" ", "").lower()
first_line = cell_text.split("\n")[0]
return (
cell_text.startswith("#@titlesolution")
or "to_remove" in first_line
and "explanation... | a41780ea85c4dd4c4013f5b562d2a6e7127cee71 | 657,208 |
def af_subtraction(ch1, ch2, m, c):
"""
Subtract ch2 from ch1
ch2 is first adjusted to m * ch2 + c
:param ch1:
:param ch2:
:param m:
:param c:
:return:
"""
af = m * ch2 + c
signal = ch1 - af
return signal | ebf11ffdc9d64860179407a48d7351bacf35492d | 657,209 |
def title2list(news_title):
"""
将一个新闻标题分字并转换成列表
:param news_title: 一个新闻标题字符串 E.g.:'2019年校领导寒假会商会召开'
:return: 一个新闻标题按字切分的列表 ['2','0','1','9','年','校','领','导','寒','假','会','商','会','召','开']
"""
title = []
for i in news_title:
title.append(i)
# print("================title============\... | 2239c1c3a46ae859adb88cad1a68b1e2cc66f781 | 657,213 |
def escape_characters(data: bytes) -> bytes:
"""
Characters that are used for telegram control are replaced with others
so that it easier to parse the message over the wire.
Final character is never replaced.
'\x0d' -> '\x1b\x0e'
'\x1b' -> '\x1b\x1b'
'\x8d' -> '\x1b\x0f'
"""
if not ... | fd98297114b8c106b43324c75f630372eedbda08 | 657,223 |
def from_pairs(pairs):
"""Creates a new object from a list key-value pairs. If a key appears in
multiple pairs, the rightmost pair is included in the object"""
out = {}
for (k, v) in pairs:
out[k] = v
return out | 3b6bc42aa3aa5f5a34373e5a7c25bd130b1c2c49 | 657,226 |
def spmwrite(self, method="", nmode="", inputs="", inputlabels="",
outputs="", outputlabels="", nic="", velacckey="",
fileformat="", **kwargs):
"""Calculates the state-space matrices and writes them to the SPM file.
APDL Command: SPMWRITE
Parameters
----------
method
... | fea18d3ed9edb1d1f16ec0f268fedbae05ed95ab | 657,228 |
def relocate_h2id(soup):
"""Moves the anchor ID to the H2 tag, from the wrapper DIV."""
for h2 in soup.find_all('h2'):
div = h2.find_parent('div')
if div.has_attr('id') and not h2.has_attr('id'):
# print('Move ID: ' + div['id'])
h2['id'] = div['id']
del div['id']
# Also delete embedded... | 536978abb6b1583085b6ea098efac019b2f591c5 | 657,230 |
import ast
def parse_string_value(str_value):
""" parse string to number if possible
e.g. "123" => 123
"12.2" => 12.3
"abc" => "abc"
"$var" => "$var"
"""
try:
return ast.literal_eval(str_value)
except ValueError:
return str_value
except SyntaxError:
... | 9e982a045cc2ee5005b5f14c3d8db8f02efb4feb | 657,231 |
def SmiNetDateTime(python_date):
"""
Datetime as a string in the format `YYYY-MM-DD HH:MM:SS`
Original xsd documentation: SmiNetLabExporters datum- och tidformat (ÅÅÅÅ-MM-DD TT:MM:SS).
"""
return python_date.strftime("%Y-%m-%d %H:%M:%S") | 3f736e4bd0972419815196420f5b4a9edd96d660 | 657,232 |
def dict_filter_keys_start_with(start, row):
"""
Given a dict, returns a new dict with key-value pairs
where the key of each pair starts with start.
"""
return {k[len(start)+1:]: v for k, v in row.items() if k.startswith(start)} | 2187d7fe3af5821633eebf3ac914dbfb3bbeac05 | 657,233 |
def make_image_black_and_white(img, threshold=127):
"""Convert an image to a black and white image."""
#convert('1') converts to black and white;
# use a custom threshold via:
# https://stackoverflow.com/a/50090612/454773
fn = lambda x : 255 if x > threshold else 0
img = img.convert('L').p... | fbe3aa0c344e34075870160476ea9743a7fce97f | 657,236 |
def rectangles_collide(x1, y1, w1, h1, x2, y2, w2, h2):
"""
Return whether or not two rectangles collide.
Arguments:
- ``x1`` -- The horizontal position of the first rectangle.
- ``y1`` -- The vertical position of the first rectangle.
- ``w1`` -- The width of the first rectangle.
- ``h1`` ... | 0d9a6a7b87a454bb242480ce48277ed623816410 | 657,248 |
def give_action_choose_probability_new(episodes, episode, model):
"""
This method gives probability of choosing action according to the episode number and total number of episode.
:param episodes: total number of episodes
:param episode: current running episode
:param model: model number
:return... | cb8daca110946c2f2403d93f25b6f6b669e11e02 | 657,250 |
async def startlist() -> dict:
"""Create a mock startlist object."""
return {
"id": "startlist_1",
"event_id": "event_1",
"no_of_contestants": 8,
"start_entries": ["11", "22", "33", "44", "55", "66", "77", "88"],
} | 6130f79ff308db5dde05af5af02ea4c6d1e7a87e | 657,251 |
def spancmb(class_=None, **kwargs):
""" span combinator
because class is a reserved keyword in python, class_ is the first arg
kwargs keys may be any html global attribute """
cdict = {'class': class_} # put class first (sign the siren song or python preserving key order)
cdict.update(kwarg... | 6a524e035781052ff92b61a35c71faff2bd54b93 | 657,252 |
def node_below_adjacent_elements(node, surface):
"""
node_below_adjacent_elements determines if a node is below any element adjacent to it in the surface.
Consider the following layout:
*-*-*-* Here, the nodes are shown as * and node (0,0) as X. Elements are shown as o and neighboring
|O|O|o| ele... | 71d0e2765f57095fae713e7afd8df108a3dfb490 | 657,254 |
import torch
def sample_pdf(rays, weights, N_importance, det=False, eps=1e-5):
"""
Sample @N_importance samples from @bins with distribution defined by @weights.
from https://github.com/sxyu/pixel-nerf/blob/master/src/render/nerf.py#L120
Inputs:
rays: (N_rays, N_samples_+1) where N_samples_ is... | 5de002923147003787262be60fe0f4f34352579c | 657,255 |
import string
def strip_punctuation(text):
"""
Remove all punctuation from text
:param text: raw headline
:return: parsed headline
"""
if text is None:
text = ""
return text.translate(str.maketrans('', '', string.punctuation)) | 7ad47c0f8cfb9df27ad00c5ec018eed63b84881b | 657,263 |
import requests
def get_access_token(app_id, app_secret, redirect_uri, code):
"""
This method gets the access token that helps you get
user details from facebook. The code argument is
retrieved from the url after the user has accepted
the permissions of your app from facebook
:param app_id:
... | 16525f4ff3ea1573be8f9cb6bb2532e95398569c | 657,268 |
import re
def remove_br_in_ul(content):
"""
Get rid of <br> inside <ul> lists
>>> remove_br_in_ul('<ul><li>abc<br></li></ul>')
'<ul><li>abc</li></ul>'
"""
_re_content_in_pre = re.compile(r"<ul>(.*?)</ul>", re.DOTALL)
return re.sub(_re_content_in_pre, lambda match: match.group().replace('<... | 3091c78b71523b05584c26c071165185104408b3 | 657,270 |
def traditional_constants_basal_equation(tdd):
""" Traditional basal equation with constants from ACE consensus """
a = 0.5
return a * tdd | ec66d8de28c81bd915d74e0bafdbee69f2892b57 | 657,273 |
import pathlib
from typing import Dict
def table_files(sql_file: pathlib.Path) -> Dict[str, str]:
"""
Associates the name of an output file to its SQL table, by reading the
snb-load.sql script
"""
results = {}
with open(sql_file, "r", encoding="utf-8") as in_fd:
for line in in_fd:
... | b6ac2f2030bf12f2121322829b68bb196b850c0f | 657,277 |
def argToInt(value):
""" Given a size or addresse of the type passed in args (ie 512KB or 1MB) then return the value in bytes.
In case of neither KB or MB was specified, 0x prefix can be used.
"""
for letter, multiplier in [("k", 1024), ("m", 1024 * 1024), ("kb", 1024), ("mb", 1024 * 1024), ]:
i... | 089d1d674b249d8ddb24432cce8df013bb9c8abb | 657,278 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.