content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def fit( X, y, batch_size = 4, validation_split = 0.05, epochs = 1250, learning_rate=0.001):
"""Fit a BNN with mean field posterior and trainable prior to a data set X,y.
Args:
X (np.array): Input data x (features)
y (np.array): Input data y (target)
batch_size (int, optional): Batch si... | 72,600 |
def jacob_f(x, u):
"""
Jacobian of Motion Model
motion model
x_{t+1} = x_t+v*dt*cos(yaw)
y_{t+1} = y_t+v*dt*sin(yaw)
yaw_{t+1} = yaw_t+omega*dt
v_{t+1} = v{t}
so
dx/dyaw = -v*dt*sin(yaw)
dx/dv = dt*cos(yaw)
dy/dyaw = v*dt*cos(yaw)
dy/dv = dt*sin(yaw)
"""
yaw = x[... | 72,601 |
def manage_ebs_volume(config, instanceid, instance_infos):
""" Manage the whole EBS process
:param ebs_config dict The EBS parameters
- tags dict: The tag name and tag value to set if a new EBS
volumes is created.
- filters dict: The tag name and ta... | 72,602 |
async def _test(verbose: int, host_bulb: str):
"""Power cycle, end program in off state"""
# setup
bulb = await _test_setup(verbose=verbose, host_bulb=host_bulb)
print("[Bulb - Test] turn off. expect: True, actual:", await bulb.off(transition=0))
print("[Bulb - Test] turn on. expect: True, actual:",... | 72,603 |
def download_file(url, filepath, sha256=None, force_overwrite=False,
logger=NULL_LOGGER, msg_update_callback=NullPrinter()):
"""Download a file from a url to local filepath.
Will not overwrite files unless @sha256 is given.
Recursively creates specified directories in @filepath.
:par... | 72,604 |
def save_by_name(admin: dict):
"""
Save a new admin with field name as index
:return:
"""
name = admin.get('name')
if not name:
raise Error(10003, 'Field name required!')
admin['updated_at'] = china_tz(datetime.now())
admin['created_at'] = china_tz(datetime.now())
if '_id' in... | 72,605 |
def create(tknzr_name: str, **kwargs: Any) -> BaseTknzr:
"""Create tokenizer instance by tokenizer's name.
Tokenizer's arguments are collected in ``**kwargs`` and are passed directly to tokenizer's constructor.
Parameters
----------
tknzr_name: str
Name of the tokenizer to create.
kwargs: typing.Any, ... | 72,606 |
def load_options(parser, options, config, if_exists=True):
"""
Given a parser object and the parsed options and a configuration
object or filename, this will load the configuration into the
parsed options.
"""
types = {}
dests = {}
aliases = {}
for option in parser.option_list:
... | 72,607 |
def p_fieldlist(p):
"""fillnullcmd : FILLNULL fillvalue fieldlist"""
p[0] = ParseTreeNode('COMMAND', raw='fillnull')
p[0].add_child(p[2])
p[0].add_children(p[3].children) | 72,608 |
def logitRegression(data):
"""
训练模型,并画出模型的ROC曲线
"""
data = transLabel(data)
features = ["age", "education_num", "capital_gain", "capital_loss", "hours_per_week"]
labels = "label_code"
trainSet, testSet = train_test_split(data, test_size=0.3, random_state=2310)
model = trainModel(trainSet... | 72,609 |
def jet_libes_get_data(exp_id=None, data_name=None, no_data=False,
options={}, coordinates=None, data_source="JET_LIBES"):
""" Data read function for the JET Li-BES diagnostic
data_name: channel data can be reached under: "BES-ADCxx", "JPF/DH/KY6D-DOWN:xxx",
... | 72,610 |
def get_optimal_girvan_newman_partition(G):
"""
Compute a partition of G with the Girvan-Newman algorithm
:param G: A networkx graph
:return: a partition on G
"""
# Get an iterator to ALL partitions produced by this algorithm
coms = nx.algorithms.community.centrality.girvan_newman(G)
#... | 72,611 |
def is_numlike(obj):
"""return true if *obj* looks like a number"""
return isinstance(obj, (numbers.Number, np.number)) | 72,612 |
def create_win_putty(folders):
"""
create a batch file to start scite
@param folders see @see fn create_win_batches
@return operations (list of what was done)
"""
text = ['@echo off',
'set CURRENT2=%~dp0',
'call %CURRENT2%env.bat',
's... | 72,613 |
def float2bin(afloat: float):
"""소수점 이하의 값이 있는 실수를 이진수로 변환
Args:
afloat: 이진수로 변환할 실수
Returns:
이진수 ('0b' prefix가 없는 실수의 형태)
"""
integer_part = int(afloat) # 정수부분
decimal_part = afloat - integer_part # 소수부분
decimal_bin = "." # 소수부문에 대한 이진표현
while decimal_part != 0.0:
... | 72,614 |
def get_errors(data: dict):
"""
Extracts value from a dict with errors key, log the errors if they exist and raises
a GithubError
:param dict: data extracted from Github's API
"""
errors = data.get('errors')
if errors:
for error in errors:
logging.getLogger(__name__).erro... | 72,615 |
def test_usage_on_subparser() -> None:
"""usage(...) example line should contain subcommand name."""
bar = Genbu(
name="bar",
description="Bar subcommand",
callback=callback,
)
Genbu(
name="foo",
description="Foo command",
callback=callback,
subpar... | 72,616 |
def get_sequential_param_pairs(params, name1, name2):
"""Returns a dict of two sets of sequentially named parameters using the
value of name1 as the key and the value of name2 of the value.
"""
one = get_sequential_params(params, name1)
two = get_sequential_params(params, name2)
if len(one) != l... | 72,617 |
def _get_newest_model(path: str) -> str:
""" In folder with daluke_pu_0.pt, daluke_pu_10.pt, daluke_pu_2.pt, daluke_pu_10.pt is returned """
pattern = re.compile(MODEL_FILE.format(i=r"\d+"))
models = list()
for f in os.listdir(path):
if pattern.match(f):
models.append(f)
if not m... | 72,618 |
def create_grid(bbox,height):
"""Create a vector-based grid
Args:
bbox ([type]): [description]
height ([type]): [description]
Returns:
[type]: [description]
"""
# set xmin,ymin,xmax,and ymax of the grid
xmin, ymin = pygeos.total_bounds(bbox)[0],pygeos.total_bounds(... | 72,619 |
def divmod_vectorize(df):
"""
1. Use divmod to transfom HHMMSSCC to miliseconds integer with vectorize
2. Outside the njit function cast date as np.datetime and time to timedelta
3. Sum date and time
"""
@vectorize([int32(int32)])
def _fix_time(mtime):
aux, cent = divmo... | 72,620 |
def hello():
"""Print 'hello module'."""
print('hello module') | 72,621 |
def sendWebmention(sourceURL, targetURL, webmention=None, test_urls=True, vouchDomain=None,
headers=None, timeout=None, debug=False):
"""Send to the :targetURL: a WebMention for the :sourceURL:
The WebMention will be discovered if not given in the :webmention:
parameter.
:param sour... | 72,622 |
def fib_mem(n, computed={0:0,1:1}):
"""find fibonacci number using memoization"""
if n not in computed:
computed[n] = fib_mem(n-1, computed) + fib_mem (n-2, computed)
return computed[n] | 72,623 |
def modify_fare(df, n: int = 4):
"""Introduce n new intervals (based on quantiles) for the feature fare, such that it is modified from
being continuous to being discrete
Parameters
----------
df : panda dataframe
n: number of new intervals (int)
Returns
-------
Original datafra... | 72,624 |
def learning_curves(
train_stats_per_model: List[dict],
output_feature_name: Union[str, None] = None,
model_names: Union[str, List[str]] = None,
output_directory: str = None,
file_format: str = 'pdf',
**kwargs
) -> None:
"""Show how model metrics change over training ... | 72,625 |
def synthesizeChebyshevNTF(order=3, OSR=64, opt=0, H_inf=1.5, f0=0.):
"""Synthesize a noise transfer function for a delta-sigma modulator.
The NTF is a type-2 highpass Chebyshev function.
:func:`synthesizeNTF` assumes that magnitude of the denominator of the NTF
is approximately constant in the passba... | 72,626 |
def get_alert_by_id(id=1):
"""Get alert data from DB given id."""
results = alert_db.read(AlertModel.id == int(id))
return Response(json.dumps(results, cls=AlchemyEncoder), mimetype='application/json') | 72,627 |
def list(sort_by,
descending,
get_data,
search,
pagination_offset,
pagination_size,
logger,
client):
"""List all user groups
"""
logger.info('Listing all user groups...')
user_groups_list = client.user_groups.list(
sort=sort_by,
... | 72,628 |
def get_name_url_pairs(request):
"""
Return a list of (group name, group calendar URL) pairs.
Make sure that the Brothers or Pledges pair is last in the list, because
the embedded calendar is set to the URL from the last pair in the list,
and we want office positions' calendars to show up with prio... | 72,629 |
def mean(dataframe):
"""
Compute mean of column's element in a dataframe.
"""
mean = [
compute_mean(serie)
for _, serie in dataframe.iteritems()
]
return mean | 72,630 |
def setup_ts_test(name, deps = [], **kwargs):
""" Sets up default test configuration to compile ts sources with npm hosted deps
@param name - name of the target (required)
@param deps - list of internal targets that this build relies on
- external npm deps is already been... | 72,631 |
def cli():
"""
Use reddit like a doge.
"""
pass | 72,632 |
def search_nearest_point(points, base_point):
"""
Parameters
-----------
points : numpy.ndarray, shape is (2, N)
base_point : numpy.ndarray, shape is (2, 1)
Returns
-------
nearest_index :
nearest_point :
"""
distance_mat = np.sqrt(np.sum((points - base_point)**2, axis=0))... | 72,633 |
def test_is_geographic(proj, expected):
"""CRS is or is not geographic"""
assert _CRS.from_dict(proj).is_geographic is expected | 72,634 |
def determine_electrode_name(name, **kwargs):
"""electrode names"""
electrode_patterns = [
"(Pt|pt)[-]{0,1}[\W]ring",
"(PDX_Ch1)((_|)|dis(c|k))",
"(PDX_Ch2)((_|)|ring)",
"(PDX P[1-9]{1}K)(-|)(Ch[1-3]{1})",
"(#[1-3]{1}_|)((D|d)is(c|k)|(R|r)ing)",
"(#[1-3]{1}_|)Dis(... | 72,635 |
def test_md002_bad_improper_setext_heading_start():
"""
Test to make sure we get the expected behavior after scanning a bad file from the
test/resources/rules/md002 directory starting with a setext heading of ----- to
create a h2 heading.
"""
# Arrange
scanner = MarkdownScanner()
suppli... | 72,636 |
def inference(Sampled_image,Binary_Point_Map, keep_prob, Num_Channels,model_dir):
# Build network and load initial weights
#image: tf tensor of the input image
#keep_prob: Probabality for dropout only applied during training
"""
:param image: input image. Should have values in range 0-255
... | 72,637 |
def towns_flooding_risk(stations, N):
""" Return list of towns and risk of flooding """
#find the flooding level of each town
towns_level = towns_average_level(stations)[:N]
towns_risk = []
#give a rating of each water level in town
for town, level in towns_level:
risk = "Low"
if... | 72,638 |
async def send_message_to_session(session_id: str, message: dict = Body(...)):
"""Send a message to a session identified by session ID."""
if session_id not in sessions:
raise HTTPException(
status_code=404, detail=f"No session matching {session_id} found"
)
session = sessions[se... | 72,639 |
def adjust_learning_rate(optimizer, epoch):
"""decrease the learning rate"""
lr = args.lr
if epoch >= 100:
lr = args.lr * 0.1
if epoch >= 150:
lr = args.lr * 0.01
for param_group in optimizer.param_groups:
param_group['lr'] = lr
return lr | 72,640 |
def continuous_mlp_baseline_tf_ppo_benchmarks():
"""Run benchmarking experiments for Continuous MLP Baseline on TF-PPO."""
iterate_experiments(continuous_mlp_baseline,
MuJoCo1M_ENV_SET,
seeds=_seeds) | 72,641 |
def main():
"""
input file format: id, volume, weight, uniform_score, histogram_weights (these columns must
appear in that order as the first four columns, followed by any additional
columns)
(tabs not commas)
id - the unique id of the record
volume - the volume that the record repre... | 72,642 |
def pytest_generate_tests(metafunc):
"""
Entrypoint for tests (built-in pytest function for dynamic generation of test cases).
"""
# Launch EC2 mocking and env preparation
mock_ebs.start()
test_volumes = mock_ebs.create_env_volumes(ebs_volumes, region)
account = Account(region=region)
... | 72,643 |
def get_hash_tuple(a_dict, included_keys=None):
""" Helps in hashing a dictionary by flattening it to a flat list of its keys and values, and then converting it into a tuple (which is what the hash function expects). """
if included_keys is not None:
a_dict = {included_key:a_dict[included_key] for inclu... | 72,644 |
async def test_update_failure(saunabox, hass, config, caplog):
"""Test that update failures are logged."""
caplog.set_level(logging.ERROR)
feature_mock, entity_id = saunabox
feature_mock.async_update = AsyncMock(side_effect=blebox_uniapi.error.ClientError)
await async_setup_entity(hass, config, en... | 72,645 |
def distance_transform(im: np.ndarray) -> np.ndarray:
"""
A function that computes the distance to the closest boundary pixel.
args:
im: np.ndarray of shape (H, W) with boolean values (dtype=np.bool)
return:
(np.ndarray) of shape (H, W). dtype=np.int32
"""
##... | 72,646 |
def _check_python_ok_for_pygame():
"""If we're on a Mac, is this a full Framework python?
There is a problem with PyGame on Macs running in a virtual env.
If the Python used is from the venv, it will not allow full window and
keyboard interaction. Instead, we need the original framework Python
to g... | 72,647 |
def get_cfg_option(cfg, sec, opt, verbose=False):
"""
Retrieve value of a specific option of a configuration.
Parameters
----------
cfg : configparser.ConfigParser()
Configuration as retrieved by the function read_cfg_file().
sec : str
The section in which the option is located.... | 72,648 |
def search_serpapi(search_terms):
"""
Query serapapi
Save in a text file
"""
results = ''
for term in search_terms:
startNums = np.arange(0,50,2)
if len(term) > 30: startNums = np.arange(0,2,1)
for starts in startNums:
params = {
... | 72,649 |
def send_text(openid, content):
"""组装文本回复数据"""
data = {
"touser": openid,
"msgtype": "text",
"text":
{
"content": content
}
}
return send_message(data) | 72,650 |
def test_random_3D_vectors():
"""Test instantiating Vectors layer with random coordinate-like 3D data."""
shape = (10, 2, 3)
np.random.seed(0)
data = np.random.random(shape)
data[:, 0, :] = 20 * data[:, 0, :]
layer = Vectors(data)
assert np.all(layer.data == data)
assert layer.data.shape... | 72,651 |
def elina_dimperm_compose(perm, perm1, perm2):
"""
Compose 2 permutations and store the result into an already allocated permutation.
The size of both permutations should be equal.
At exit, we have perm.dim[i] = perm2.dim[perm1.dim[i]].
Parameters
----------
perm : ElinaDimpermPtr
... | 72,652 |
def save_xml_file(path, xml_tree):
""" Save XML File
Converts xml_tree into structured string and then saves as "strings.xml"
:param path: The path where file should be saved.
:param xml_tree: XML object containing information to be saved.
:return:
"""
try:
xml_string = e... | 72,653 |
def RecognizeCAPTCHA(captcha):
"""
暴露给Login的接口,这里就不能把model作为参数了
:param captcha: 验证码图片
:return: 验证码结果
"""
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
session = InteractiveSession(config=config)
model... | 72,654 |
def version():
"""CLI's version"""
console.print(f"Minos CLI {__version__}") | 72,655 |
def run_aqrm_task(epsilon, env, learned_rm_file, tester_true, tester_learned, curriculum, show_print, is_rm_learned, currentstep, previous_testing_reward, q):
"""
This code runs one training episode.
- rm_file: It is the path towards the RM machine to solve on this episode
- environment_rm: an e... | 72,656 |
def empty_folder(path):
"""Clears all file of a folder"""
for filename in os.listdir(path):
file_path = os.path.join(path, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
... | 72,657 |
def parse_modifier(modifier):
"""Parse modifier part, return list with name, function and number."""
return [func(value) for value, func in zip(
modifier, (lambda x: x, get_action_function, int))] | 72,658 |
def parse(keypoints, path, img_res, node_type, filename, cli):
"""
Given a set of pose estimated keypoints, parses those points, and
returns a list of Networkx augmented graphs containing those points,
if the cli flag is False, otherwise returns None.
:param keypoints: set of keypoints generated by ... | 72,659 |
def RePackFromDataPackStrings(inputs,
allowlist,
suppress_removed_key_output=False):
"""Combines all inputs into one.
Args:
inputs: a list of (resources_by_id, encoding) tuples to be combined.
allowlist: a list of resource IDs that should be k... | 72,660 |
def test_load_attributes_switches(sample_attributes):
"""Test switches are loaded correctly"""
_, switches = load_attributes(sample_attributes)
assert switches[5]["travelling_status-20"] == 1 | 72,661 |
def toTypes(thing, types, typeError='wrong type'):
"""Convert something to any of the given types, printing an error if impossible."""
if needsLazyEvaluation(thing):
# cannot check the type now; create proxy object to check type after evaluation
return TypeChecker(thing, types, typeError)
else:
return coerceTo... | 72,662 |
def load_data(
mgf_filename: str,
*,
range_spectrum: tuple = (0, 1600), # spectrum range
min_intensity: Optional[float] = None, # determine threshold to remove
mz_binning_width: float = 5.0,
) -> Tuple[List[float], List[float]]:
"""
Process and return date from xml file
:param mgf_fil... | 72,663 |
def find_plane_corner(object_name, x, y, axis, camera=None, *args, **kwargs):
"""Find the location in camera space of a plane's corner"""
if args or kwargs:
# I've added args / kwargs as a compatibility measure with future versions
warnings.warn("Unknown Parameters Passed to \"Images as Planes\"... | 72,664 |
def _get_python_include(repository_ctx, python_bin):
"""Gets the python include path."""
result = _execute(
repository_ctx,
[
python_bin,
"-c",
"from __future__ import print_function;" +
"from distutils import sysconfig;" +
"print(sysco... | 72,665 |
def test_score():
"""Assert that the score method works as intended."""
atom = ATOMClassifier(X_bin, y_bin, random_state=1)
pytest.raises(NotFittedError, atom.score, X_bin, y_bin)
atom.run("LR")
assert isinstance(atom.score(X_bin, y_bin), float) | 72,666 |
def check_if_data_is_downloaded():
"""Removed, do not use."""
raise NotImplementedError("check_if_data_is_downloaded has been removed") | 72,667 |
def read_csv_dict_file(filepath, fieldnames=None, dialect=None):
"""Iterates over a csv file, yielding each line as a dict.
This uses csv.DictReader, so the file should be in a form appropriate to
that. The fieldnames and dialect arguments are supplied to the csv reader.
Note this means that if fieldna... | 72,668 |
def within_index(b, e, s, i):
"""Return a boolean value that indicates if i is within the given index.
Parameters
----------
b : Expr
beginning of the index
e : Expr
end of the index
s : Expr
strides of index
i : Expr
array position
Returns
-------
se... | 72,669 |
def add_model_components(m, d, scenario_directory, subproblem, stage):
"""
The following Pyomo model components are defined in this module:
+-------------------------------------------------------------------------+
| Sets |
+======... | 72,670 |
def opcode_j(renderer, line_join):
"""Set line join style (see p. 216)"""
renderer.gs.line_join = line_join | 72,671 |
def directed_triplet_motif_index(G):
"""Return the directed motif index of three-node graph G (G is a nx graph type)
The motif index is then computed as follows:
Each possible (undirected) edge on the nodes of G is sorted in lexicographic order.
For each pair of vertices, two bits encode, in order, the... | 72,672 |
def twitter_auth():
"""OAuth procedure for the Twitter API"""
consumer_key = '8U4SH1S8MqMlxFASj6GlgeobL'
consumer_secret = 'iHGgrHBnGJJhnLfH7g2ZaggAwuun2QuNEspvg2ftUD4Ij6UnTp'
access_token = '928672057042391043-Niz2uWC8iXeXepr0NVn8GEzZ8yh5gDG'
access_token_secret = 'DSIXLThko0e0Dcem7OGsa1ht2zpR... | 72,673 |
def index():
"""Index view."""
if current_user.is_authenticated:
if current_user.role == 2:
issues = Issue.query.order_by(Issue.id).all()
elif current_user.roles.role_label == 'assignee':
issues = Issue.query.order_by(Issue.id).filter((Issue.assignee == current_user.id)... | 72,674 |
def fn_name(depth = 0):
"""Get the function name from the call stack.
Args:
depth: call stack depth to return, 0=parent, 1=grandparent, etc.
Returns:
The function name from the call stack, at the depth given.
"""
return sys._getframe(depth + 1).f_code.co_name | 72,675 |
def get_data_parallel_rank():
"""Return my rank for the data parallel group."""
dp_group = get_data_parallel_group()
if dp_group is not None:
return get_rank(dp_group)
else:
return get_global_rank() | 72,676 |
def kelvin_to_rgb(kelvin):
"""
Convert a color temperature given in kelvin to an approximate RGB value.
:param kelvin: Color temp in K
:return: Tuple of (r, g, b), equivalent color for the temperature
"""
temp = kelvin / 100.0
# Calculate Red:
if temp <= 66:
red = 255
else:... | 72,677 |
def get_priors(source, version):
"""Retrieves prior pdfs for each parameter
"""
params = get_parameter(source=source, version=version, parameter='param_keys')
pdfs = {}
for param in params:
default = source_defaults['priors'][source].get(param, flat_prior)
v_definition = version_defi... | 72,678 |
def get_package_relative(file, package_dir):
"""
Get path of file relative to package directory.
If the file is not in the package directory, an error is raised.
Args:
file (File): The file.
package_dir (string): The package directory, for instance gotten from `get_package_dirname`.
Returns:
st... | 72,679 |
def prepare_study_with_trials(
no_trials: bool = False,
less_than_two: bool = False,
more_than_three: bool = False,
with_c_d: bool = True,
n_objectives: int = 1,
direction: str = "minimize",
) -> Study:
"""Prepare a study for tests.
Args:
no_trials: If :obj:`False`, create a st... | 72,680 |
def write_to_kafka(kafka_server: Tuple[Popen, int], message: bytes) -> None:
"""Write a message to kafka_server."""
_, kafka_port = kafka_server
producer = KafkaProducer(bootstrap_servers='localhost:{}'.format(kafka_port))
producer.send(TOPIC, message)
producer.flush() | 72,681 |
def get_from_algorithm_wrapper_registry(algorithm_name: str) -> Callable:
"""
Gets a wrapper function from algorithm wrapper registry.
:param algorithm_name: Algorithm for which the wrapper should be returned.
:return: The previously registered wrapper function.
"""
if algorithm_name in _algorit... | 72,682 |
def read_hdf(hdf_fname, key):
"""
Read contents of HDF file *hdf_fname* associated with *key* and
return a :class:`DataFrame`, header tuple.
"""
if not os.path.isfile(hdf_fname):
raise ValueError('file {} does not exist'.format(hdf_fname))
with PD.HDFStore(hdf_fname) as store:
df... | 72,683 |
def run_simulator(fitparams):
"""
runs the function simulator with the multiprocessing manager (if function is called sequentially, this stores memory, otherwise same as calling sumulator directly)
fitparams: list, for description see function simulator
return: returns dictionary ne... | 72,684 |
def nthRuler(n, dow):
""" Returns the n-th hour ruler since last sunrise
by day of week. Both arguments are zero based.
"""
index = (dow * 24 + n) % 7
return ROUND_LIST[index] | 72,685 |
def load_vowel(file, sr=None, normalize=True):
"""Use librosa to to load a single vowel with a specified sample rate
"""
data, rate = librosa.load(file, sr=sr)
if normalize:
data = normalize_vowel(data)
return data | 72,686 |
def make_pass_instance_decorator(obj, ensure=False):
"""Given an object type this creates a decorator that will work
similar to :func:`pass_obj` but instead of passing the object of the
current context, it will inject the passed object instance.
This generates a decorator that works roughly like this::... | 72,687 |
def parse_projects_for_TMS(instance, **kwargs):
"""Parse projects for the given TMS.
Creates new Django model projects objects with parsed data.
Arguments:
instance - Django TMS object instance
"""
logging.info('parse_tms started')
logging.debug('parse_projects_for_TMS kwargs: {}'.form... | 72,688 |
def clip_channel(coord: float, bounds: Bounds) -> float:
"""Clipping channel."""
a = bounds.lower # type: Optional[float]
b = bounds.upper # type: Optional[float]
is_bound = isinstance(bounds, GamutBound)
# These parameters are unbounded
if not is_bound: # pragma: no cover
# Will no... | 72,689 |
def members_to_rep(otus):
"""Provides a lookup for a cluster member to its rep"""
res = {}
for rep, members in otus.iteritems():
for member in members:
res[member] = rep
return res | 72,690 |
def load_content(path: str, class_indices: Mapping[str, int]):
"""
Load .content files.
.content files (like used in cora) contain node features on separate lines. Each
line is of the form
```
node_id feature_0 feature_1 ... class_label
```
where values are separated by tabs ("\t") and ... | 72,691 |
def num_2_byte_list(num):
"""
convert num to byte list
:param num:
:return:
"""
byte = []
while num > 0:
b = num & 0xff # 获取最低位的一个字节的值
byte.append(b)
num = num >> 8 # 移除最低位的一个字节
return list(reversed(byte)) | 72,692 |
def fixoutaff(outpath='',newaff='1'):
""" quick way to create test data sets - set all aff to 1 or 2 for
some hapmap data and then merge
[rerla@beast galaxy]$ head tool-data/rg/library/pbed/affyHM_CEU.fam
1341 14 0 0 2 1
1341 2 13 14 2 1
1341 13 0 0 1 1
1340 9 0 0 1 1
1340 10 0 0 2 1
... | 72,693 |
def update_accel_time(driver, at):
"""
Updates the accel time of the driver
:param driver: driver
:param at: new accel time
:type driver: DriverProfile
:return: updated driver profile
"""
return driver.update_accel_time(at) | 72,694 |
def _simplify(shp, tol=0.05):
"""
Generate a simplified shape, within a specified tolerance.
"""
simp = None
for thresh in [0.001, 0.0005, 0.0004, 0.0003, 0.0002, 0.0001]:
simp = shp.simplify(thresh)
if shp.difference(simp).area / shp.area < tol:
break
return simp | 72,695 |
def parse_voc_annotation(data_path, file_type, anno_path,
use_difficult_bbox=False, cfg=None):
"""
解析 pascal voc数据集的annotation, 表示的形式为[image_global_path xmin,ymin,xmax,ymax,cls_id]
:param data_path: 数据集的路径 , 如 D:\doc\data\VOC\VOCtrainval-2007\VOCdevkit\VOC2007
:param file_type: ... | 72,696 |
def _match(pattern, value):
"""User-defined function to implement SQL MATCH/STIX MATCHES"""
return bool(re.match(pattern, value)) | 72,697 |
def assemble_today(calendars="/c/calendars", destination="/c/outgoing", priority="/c/priority.txt", include_week=False, quotes="/c/yoga/golden_present.txt"):
"""
look through all calendar items for events coming up
today (at minumum) and
this week (optionally)
create a new log file for today and pl... | 72,698 |
def get_ds_kernels(opt):
"""
Use the previously extracted realistic estimated kernels
(kernelGAN, etc) to downscale images with.
Ref:
https://openaccess.thecvf.com/content_ICCV_2019/papers/Zhou_Kernel_Modeling_Super-Resolution_on_Real_Low-Resolution_Images_ICCV_2019_paper.pdf
https... | 72,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.