content
stringlengths 35
416k
| sha1
stringlengths 40
40
| id
int64 0
710k
|
---|---|---|
def walk_links_for_node(node, callback, direction, obj=None):
"""
Walks the each link from the given node. Raising a StopIteration will terminate the
traversal.
:type node: treestruct.Node
:type callback: (treestruct.Node, treestruct.Node, object) -> ()
:type direction: int
:type obj: Any
:return: Returns `obj` (or None if no `obj` is supplied).
:rtype: Any
"""
try:
visited = set()
queue = [node]
while queue:
node = queue.pop(0)
if node in visited:
continue
visited.add(node)
for connected_node in node.direction(direction):
callback(node, connected_node, obj)
queue.append(connected_node)
except StopIteration:
pass
return obj | a92cb831945a537c55ff4c014eedcb17b26ddd96 | 702,873 |
import configparser
def get_config_parser(filepath):
"""Create parser for config file.
:param filepath: Config file path
:type filepath: str
:return: configparser.ConfigParser instance
"""
config_parser = configparser.ConfigParser(interpolation=None)
# use read_file() instead of read() to catch possible OSError
with open(filepath) as cfg_file:
config_parser.read_file(cfg_file)
return config_parser | 224f524c60161bc45b1324b26eeb6d4715c43054 | 702,874 |
def load_id_map(id_file):
""" Load a ids file in to a barcode -> coordinate dictionary.
"""
id_map = {}
with open(id_file, "r") as fh:
for line in fh:
bc, x, y = line.split("\t")
id_map[bc] = (int(x), int(y))
return id_map | cd2c0635496209c3e19597fa45ae4f486779ceac | 702,875 |
from typing import Set
from typing import Mapping
from typing import Sequence
def expand_related_tasks(tasks: Set[str],
expand_map: Mapping[str, Sequence[str]]) -> Set[str]:
"""The inverse of `collapse_related_tasks`.
Args:
tasks: a list of tasks to expand.
expand_map: map from a collapsed task name to a list of expanded task names.
Returns:
A list of expanded tasks.
"""
expanded_tasks = set()
for task in tasks:
if task in expand_map:
for full_task in expand_map[task]:
expanded_tasks.add(full_task)
else:
expanded_tasks.add(task)
return expanded_tasks | 16abd2160dc972e89ade3e5cb2b40e8451a932a7 | 702,876 |
import sympy
def antal_h_coefficient(index, game_matrix):
"""
Returns the H_index coefficient, according to Antal et al. (2009), as given by equation 2.
H_k = \frac{1}{n^2} \sum_{i=1}^{n} \sum_{j=1}^{n} (a_{kj}-a_{jj})
Parameters
----------
index: int
game_matrix: sympy.Matrix
Returns
-------
out: sympy.Expr
Examples:
--------
>>>a = Symbol('a')
>>>antal_h_coefficient(0, Matrix([[a,2,3],[4,5,6],[7,8,9]]))
Out[1]: (2*a - 29)/9
>>>antal_h_coefficient(0, Matrix([[1,2,3],[4,5,6],[7,8,9]]))
Out[1]: -3
"""
size = game_matrix.shape[0]
suma = 0
for i in range(0, size):
for j in range(0, size):
suma = suma + (game_matrix[index, i] - game_matrix[i, j])
return sympy.together(sympy.simplify(suma / (size ** 2)), size) | 0e05a6a622ef24ff63b18b9c8b80348b860a16c3 | 702,877 |
import hashlib
def getcertpubhash(certobj):
"""
Method 1: Hash from public key
:param certobj:
:return:
"""
if certobj:
pubkey = certobj.get_pubkey().as_der()
pubkeyhash = hashlib.sha256(pubkey).hexdigest()
return pubkeyhash
else:
return None | 3002a8ddba6522acf7de0c1cfa225e68a1e3f141 | 702,878 |
from typing import List
from typing import Dict
def _cx_to_dict(list_of_dicts: List[Dict], key_tag: str = "k", value_tag: str = "v") -> Dict:
"""Convert a CX list of dictionaries to a flat dictionary."""
return {d[key_tag]: d[value_tag] for d in list_of_dicts} | ea80e9a50ea04536c2ed068d19220b56a9bdf3ed | 702,879 |
import typing
import pathlib
import itertools
def find_pyfiles() -> typing.Iterator[pathlib.Path]:
"""Return an iterator of the files to format."""
return itertools.chain(
pathlib.Path("../gdbmongo").rglob("*.py"),
pathlib.Path("../gdbmongo").rglob("*.pyi"),
pathlib.Path("../stubs").rglob("*.pyi"),
pathlib.Path("../tests").rglob("*.py")) | 74b0c11771799fba6090569595d24e70ec68899d | 702,880 |
def merge_args(args, cloud_args):
"""merge_args"""
args_dict = vars(args)
if isinstance(cloud_args, dict):
for key in cloud_args.keys():
val = cloud_args[key]
if key in args_dict and val:
arg_type = type(args_dict[key])
if arg_type is not type(None):
val = arg_type(val)
args_dict[key] = val
return args | 06f84376e23535e9d291eb9bc9514fa27582faa2 | 702,881 |
def visibility_define(config):
"""Return the define value to use for NPY_VISIBILITY_HIDDEN (may be empty
string)."""
hide = '__attribute__((visibility("hidden")))'
if config.check_gcc_function_attribute(hide, 'hideme'):
return hide
else:
return '' | b08e8515440c4bf1ebec51c4100e55fe9f14b17d | 702,882 |
def calculate_num_points_in_solution(solution):
"""Calculates the number of data points in the given solution."""
return sum(len(points) for points in solution.values()) | c75f7cb7d9c8c2731e4698040954c559b6b5d4ec | 702,883 |
import re
def get_polygon_speed(polygon_name):
"""Returns speed unit within a polygon."""
result = re.search(r"\(([0-9.]+)\)", polygon_name)
return float(result.group(1)) if result else None | 2d2cc99f30153c4fbc9ac358ad3debc15fc3227e | 702,884 |
def pt_in_ploy(poly, x, y):
""" 判断 点(x,y) 是否 在 poly 最大和最小坐标之外,粗略 判断点是否在图形之内 """
n = len(poly)
if n < 3:
return False
xmax = xmin = poly[0]['x']
ymax = ymin = poly[0]['y']
for i in range(1, n):
if poly[i]['x'] > xmax:
xmax = poly[i]['x']
elif poly[i]['x'] < xmin:
xmin = poly[i]['x']
if poly[i]['y'] > ymax:
ymax = poly[i]['y']
elif poly[i]['y'] < ymin:
ymin = poly[i]['y']
if x < xmin or x > xmax or y < ymin or y > ymax:
return False
return True | 2e07429edd6929a7e5747e6ba113f4186413dab8 | 702,885 |
def random_node_presence(t_windows, rep, plac, dur):
"""
Generate the occurrence and the presence of a node given occurrence_law(occurrence_param)
and presence_law(presence_param).
:param t_windows: Time window of the Stream Graph
:param rep: Number of segmented nodes
:param plac: Emplacement of each segmented node (sorted array)
:param dur: Length of each interval corresponding to a segmented node
:return: node presence
"""
acc = plac[0] + dur[0]
if acc > t_windows[1]:
# Si on dépasse la borne supérieure de temps de notre Stream Graph
acc = t_windows[1]
n_presence = [plac[0], acc]
return n_presence
n_presence = [plac[0], acc] # Initialisation, [t0,t0+d0]
for i in range(1, rep):
acc = plac[i] + dur[i]
if acc > t_windows[1]:
# Si on dépasse la borne supérieure de temps de notre Stream Graph
acc = t_windows[1]
if acc <= n_presence[-1]:
# Cas ou l'intervalle est inclus dans le précédent
continue
if plac[i] <= n_presence[-1]:
# Cas de l'intersection : on fusionne
n_presence[-1] = acc
else:
# Cas disjoint
n_presence += [plac[i], acc]
return n_presence | 416ea50c4cdd1280dde90816ec735b8eff6f81f1 | 702,886 |
import pdb
import torch
def batch_hard_triplet_loss(labels, embeddings, k, margin=0, margin_type='soft'):
"""Build the triplet loss over a batch of embeddings.
For each anchor, we get the hardest positive and hardest negative to form a triplet.
Args:
labels: labels of the batch, of size (batch_size,)
embeddings: tensor of shape (batch_size, embed_dim)
margin: margin for triplet loss
squared: Boolean. If true, output is the pairwise squared euclidean distance matrix.
If false, output is the pairwise euclidean distance matrix.
Returns:
triplet_loss: scalar tensor containing the triplet loss
"""
k = min(k, labels.shape[0])
# Get the pairwise distance matrix
pairwise_dist = (embeddings.unsqueeze(0) - embeddings.unsqueeze(1)).pow(2).sum(2)
# For each anchor, get the hardest positive
# First, we need to get a mask for every valid positive (they should have same label)
mask_anchor_positive = torch.eq(torch.unsqueeze(labels, 0), torch.unsqueeze(labels, 1)).float()
# We put to 0 any element where (a, p) is not valid (valid if a != p and label(a) == label(p))
anchor_positive_dist = mask_anchor_positive * pairwise_dist
# shape (batch_size, 1)
hardest_positive_dist = torch.topk(anchor_positive_dist, k=k, dim=1, largest=True)[0]
# We add inf in each row to the positives
anchor_negative_dist = pairwise_dist
anchor_negative_dist[mask_anchor_positive.bool()] = float('inf')
# shape (batch_size,)
hardest_negative_dist = torch.topk(anchor_negative_dist, k=k, dim=1, largest=False)[0]
mask = hardest_negative_dist != float('inf')
dpos = hardest_positive_dist[mask]
dneg = hardest_negative_dist[mask]
if dpos.shape[0] == 0 or dneg.shape[0] == 0:
return None
# Combine biggest d(a, p) and smallest d(a, n) into final triplet loss
if margin_type == 'soft':
loss = torch.log1p(torch.exp(dpos - dneg + float(margin)))
else:
loss = torch.clamp(dpos - dneg + float(margin), min=0.0)
# Get thanchor_negative_diste true loss value
loss = torch.mean(loss)
if loss < 0:
pdb.set_trace()
return loss | 2853124d06688eaca4f7da2a5bc19819490656c9 | 702,887 |
import sys
from pathlib import Path
import os
def resource_path(relative_path):
""" Return absolute path for provided relative item based on location
of program.
"""
# If compiled with pyinstaller then sys._MEIPASS points to the location
# of the bundle. Otherwise path of python script is used.
base_path = getattr(sys, '_MEIPASS', str(Path(__file__).parent))
return os.path.join(base_path, relative_path) | 303418a0d61ae2107d7ac4f8e3503c71bac090bf | 702,888 |
def _set_default_voltage_ratio(
voltage_ratio: float, subcategory_id: int, type_id: int
) -> float:
"""Set the default voltage ratio for semiconductors.
:param voltage_ratio: the current voltage ratio.
:param subcategory_id: the subcategory ID of the semiconductor with missing
defaults.
:param type_id: the type ID of the semiconductor with missing defaults.
:return: _voltage_ratio
:rtype: float
"""
if voltage_ratio > 0.0:
return voltage_ratio
try:
return {
1: {
1: 0.7,
2: 0.7,
3: 0.7,
4: 0.7,
5: 0.7,
},
3: {
1: 0.5,
2: 0.8,
},
6: {
1: 0.7,
2: 0.45,
},
13: {
1: 0.5,
2: 0.5,
},
}[subcategory_id][type_id]
except KeyError:
return 1.0 | d084f157c4d105193693af722e72028129e17821 | 702,889 |
import copy
def random_reset_mutation(random, candidate, args):
"""Return the mutants produced by randomly choosing new values.
This function performs random-reset mutation. It assumes that
candidate solutions are composed of discrete values. This function
makes use of the bounder function as specified in the EC's
``evolve`` method, and it assumes that the bounder contains
an attribute called *values* (which is true for instances of
``DiscreteBounder``).
The mutation moves through a candidate solution and, with rate
equal to the *mutation_rate*, randomly chooses a value from the
set of allowed values to be used in that location. Note that this
value may be the same as the original value.
.. Arguments:
random -- the random number generator object
candidate -- the candidate solution
args -- a dictionary of keyword arguments
Optional keyword arguments in args:
- *mutation_rate* -- the rate at which mutation is performed (default 0.1)
The mutation rate is applied on an element by element basis.
"""
bounder = args['_ec'].bounder
try:
values = bounder.values
except AttributeError:
values = None
if values is not None:
rate = args.setdefault('mutation_rate', 0.1)
mutant = copy.copy(candidate)
for i, m in enumerate(mutant):
if random.random() < rate:
mutant[i] = random.choice(values)
return mutant
else:
return candidate | c357237e22e34b7496f8cc17f4ad0efa2bd4621d | 702,891 |
def is_same_data(data1, data2, precision=10**-5):
"""
Compare two data to be the same.
:param data1: given data1
:type data1: list
:param data2: given data2
:type data2: list
:param precision: comparing precision
:type precision: float
:return: True if they are the same
"""
if len(data1) != len(data2):
return False
is_same = map(lambda x, y: abs(x - y) < precision, data1, data2)
return all(is_same) | 16e786a552d9190eebb44721ab75ddd45d7086cf | 702,892 |
import re
def normalise_name(raw_name):
"""
Normalise the name to be used in python package allowable names.
conforms to PEP-423 package naming conventions
:param raw_name: raw string
:return: normalised string
"""
return re.sub(r"[-_. ]+", "_", raw_name).lower() | 2c9aea4a3e83fdb52f952d2308de29d8948f6917 | 702,893 |
def timestr_mod24(timestr):
"""
Given a GTFS HH:MM:SS time string, return a timestring in the same
format but with the hours taken modulo 24.
"""
try:
hours, mins, seconds = [int(x) for x in timestr.split(":")]
hours %= 24
result = "{:02d}:{:02d}:{:02d}".format(hours, mins, seconds)
except:
result = None
return result | ea049f4b31861de56b04dba6f4356ed46930af44 | 702,894 |
def set_ext_api(file_path):
"""Smart Function to set Extension."""
ext = file_path.split('.')[-1]
if ext == 'plist':
return 'plist'
elif ext == 'xml':
return 'xml'
elif ext in ['sqlitedb', 'db', 'sqlite']:
return 'db'
elif ext == 'm':
return 'm'
else:
return 'txt' | 816a7f33c659ff3e0089502530fb916a40982d79 | 702,895 |
def animations():
"""animations() -> tuple
Returns a list of animatable things the user wants to work on.
If this is a command being executed from a menu item in a curve editor, a list of the names of all selected curves is returned. If this list is empty a "No curves selected" error is produced.
If this is a command being executed from the pop-up list in a knob then a list of all the fields in the knob is returned.
If this is a command being executed from the right-mouse-button pop-up list in a field of a knob, the name of that field is returned.
Otherwise this produces an error indicating that the command requries a knob context. You can get such a context by doing "in <knob> {command}"
Also see the 'selected' argument to the animation command.
See also: animation, animationStart, animationEnd, animationIncrement
@return: A tuple of animatable things."""
return (None,) | a30923e499824739c8a0429bdb6a8f10f42928ba | 702,896 |
def add_solution(
respy_obj,
periods_rewards_systematic,
states_number_period,
mapping_state_idx,
periods_emax,
states_all,
*args,
):
"""Add solution to class instance."""
respy_obj.unlock()
respy_obj.set_attr("periods_rewards_systematic", periods_rewards_systematic)
respy_obj.set_attr("states_number_period", states_number_period)
respy_obj.set_attr("mapping_state_idx", mapping_state_idx)
respy_obj.set_attr("periods_emax", periods_emax)
respy_obj.set_attr("states_all", states_all)
respy_obj.set_attr("is_solved", True)
respy_obj.lock()
return respy_obj | ea0660fe5956bf5e8f6706a12e766a0cc5e2f2db | 702,897 |
def mod(source):
"""Create kernel module shared among multiple tests."""
return source.get_module_for_symbol("snd_request_card") | 484afb203021497614ee18c7ac99200e4cb39a12 | 702,898 |
from functools import reduce
def constant_time_compare(x, y):
"""
Compares two byte strings in a way such that execution time is constant
regardless of how much alike the input values are, provided that they
are of the same length.
Comparisons between user input and secret data such as calculated
HMAC values needs to be executed in constant time to avoid leaking
information to the caller via the timing side channel.
Params:
x: the first byte string to compare
y: the second byte string to compare
Return: True if x and y are equal, else False
"""
if len(x) != len(y):
return False
n = reduce(lambda a, b: a | b, (ord(x) ^ ord(y) for x, y in zip(x, y)))
return n == 0 | fe7fc348d367907eee2c9df3b7d0fbe232072714 | 702,900 |
def _str2bool(string):
"""Converts either 'true' or 'false' (not case-sensitively) into a boolean."""
if string is None:
return False
else:
string = string.lower()
if string == 'true':
return True
elif string == 'false':
return False
else:
raise ValueError(
'String should either be `true` or `false`: got {}'.format(string)) | 97755d1901a836bb1e3ce062afdbffc8b5b92de1 | 702,901 |
import math
def _get_alpha_bar_from_time(t):
"""
Noise scheduling method proposed by Nichol et. al to avoid too noisy image especially for smaller resolution.
This strategy creates beta as follows:
alpha_bar(t) = f(t) / f(0)
f(t) = cos((t / T + s) / (1 + s) * PI / 2) ** 2
beta(t) = 1 - alpha_bar(t) / alpha_bar(t-1)
where s = 0.008 (~= 1 / 127.5), which ensures sqrt(beta_0) is slightly smaller than the pixel bin size.
"""
assert 0 <= t <= 1, "t must be normalized by max diffusion timestep (T)."
return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2 | ecb79239e2181d6e17db0b30885ec68d48b0a2d3 | 702,902 |
def decrementAny(tup):
""" the closest tuples to tup: decrementing by 1 along any dimension.
Never go into negatives though. """
res = []
for i, x in enumerate(tup):
if x > 0:
res.append(tuple(list(tup[:i]) + [x - 1] + list(tup[i + 1:])))
return res | 44d5c968231cfb761c641892883a85c6a168c338 | 702,903 |
def ExtractModuleIdIfValidBreakpad(file_path):
"""Extracts breakpad file's module id if the file is valid.
A breakpad file is valid for extracting its module id if it
has a valid MODULE record, formatted like so:
MODULE operatingsystem architecture id name
For example:
MODULE mac x86_64 1240DF90E9AC39038EF400 Chrome Name
See this for more information:
https://chromium.googlesource.com/breakpad/breakpad/+/HEAD/docs/symbol_files.md#records-1
Args:
file_path: Path to breakpad file to extract module id from.
Returns:
Module id if file is a valid breakpad file; None, otherwise.
"""
module_id = None
with open(file_path, 'r') as file_handle:
# Reads a maximum of 200 bytes/characters. Malformed file or binary will
# not have '\n' character.
first_line = file_handle.readline(200)
fragments = first_line.rstrip().split()
if fragments and fragments[0] == 'MODULE' and len(fragments) >= 5:
# Symbolization script's input file format requires module id hexadecimal
# to be upper case.
module_id = fragments[3].upper()
return module_id | e846cf05976c2c1622160d1a2a639d605e072417 | 702,904 |
from datetime import datetime
import pytz
def _timestamp_to_iso_str(timestamp):
"""
Converts the timestamp value into a iso str
Args:
timestamp(float): the timestamp to convert
Returns:
str: converted timestamp
"""
return datetime.fromtimestamp(timestamp).replace(tzinfo=pytz.utc).isoformat() | 89257c74a96c5335bc25ef617e41c0eeeb31021e | 702,905 |
def subtract_mean_vector(frame):
"""
Re-center the vectors in a DataFrame by subtracting the mean vector from
each row.
"""
return frame.sub(frame.mean(axis='rows'), axis='columns') | 4a6207889b958aebd608c349ad889e109ab3f4a9 | 702,906 |
def reduce_level(ast):
"""
The function removes from the abstract syntax tree a declaration current level (pointer or array). For instance it
makes from AST of 'int *a' it makes AST for 'int a'.
:param ast: Current abstract syntax tree.
:return: Abstract syntax tree for the pointer or an array element type.
"""
if len(ast['declarator']) > 1 and \
('pointer' not in ast['declarator'][-1] or ast['declarator'][-1]['pointer'] == 0) and \
('arrays' not in ast['declarator'][-1] or len(ast['declarator'][-1]['arrays']) == 0) and \
'function arguments' not in ast['declarator'][-1]:
ast['declarator'].pop()
return ast | 6d7e61265555106efe9f0733ec5f40b51bdaedf8 | 702,907 |
def to_location(maiden: str, center: bool = False) -> tuple[float, float]:
"""
convert Maidenhead grid to latitude, longitude
Parameters
----------
maiden : str
Maidenhead grid locator of length 2 to 8
center : bool
If true, return the center of provided maidenhead grid square, instead of default south-west corner
Default value = False needed to maidenhead full backward compatibility of this module.
Returns
-------
latLon : tuple of float
Geographic latitude, longitude
"""
maiden = maiden.strip().upper()
N = len(maiden)
if not 8 >= N >= 2 and N % 2 == 0:
raise ValueError("Maidenhead locator requires 2-8 characters, even number of characters")
Oa = ord("A")
lon = -180.0
lat = -90.0
# %% first pair
lon += (ord(maiden[0]) - Oa) * 20
lat += (ord(maiden[1]) - Oa) * 10
# %% second pair
if N >= 4:
lon += int(maiden[2]) * 2
lat += int(maiden[3]) * 1
# %%
if N >= 6:
lon += (ord(maiden[4]) - Oa) * 5.0 / 60
lat += (ord(maiden[5]) - Oa) * 2.5 / 60
# %%
if N >= 8:
lon += int(maiden[6]) * 5.0 / 600
lat += int(maiden[7]) * 2.5 / 600
# %% move lat lon to the center (if requested)
if center:
if N == 2:
lon += 20 / 2
lat += 10 / 2
elif N == 4:
lon += 2 / 2
lat += 1.0 / 2
elif N == 6:
lon += 5.0 / 60 / 2
lat += 2.5 / 60 / 2
elif N >= 8:
lon += 5.0 / 600 / 2
lat += 2.5 / 600 / 2
return lat, lon | fddcbdab4f3e0f812dd7fac3509e66bc63f8fb84 | 702,908 |
def flipDP(directionPointer: int) -> int:
"""
Cycles the directionpointer 0 -> 1, 1 -> 2, 2 -> 3, 3 -> 0
:param directionPointer: unflipped directionPointer
:return: new DirectionPointer
"""
if directionPointer != 3:
return directionPointer + 1
return 0 | 928347a5c1934c822c77434ca9a91d913ef7f3b5 | 702,909 |
def get_datatype(data):
"""
rules defining the sidtype, based on the data dict of the sid.
The keys are always given.
The values can be empty.
:param data:
:return:
"""
subtype = "project"
if "entity" in data.keys():
subtype = "entity"
if data.get("type"):
subtype = "shot_type"
if "cat" in data.keys():
subtype = "asset"
if data.get("cat"):
subtype = "asset_cat"
if data.get("name"):
subtype = "asset_name"
if data.get("type"):
subtype = "asset_type"
if data.get("task"):
subtype = "asset_task"
if data.get("subtask"):
subtype = "asset_subtask"
if data.get("version"):
subtype = "asset_version"
if data.get("state"):
subtype = "asset_state"
if data.get("ext"):
subtype = "asset_file"
elif "seq" in data.keys():
subtype = "shot"
if data.get("seq"):
subtype = "shot_seq"
if data.get("shot"):
subtype = "shot_shot"
if data.get("task"):
subtype = "shot_task"
if data.get("subtask"):
subtype = "shot_subtask"
if data.get("version"):
subtype = "shot_version"
if data.get("state"):
subtype = "shot_state"
if data.get("ext"):
subtype = "shot_file"
return subtype | a7677db6d6aa9a9ccdcbdd9f6fd9d87032fcd18f | 702,911 |
import os
import subprocess
def build(env_meta_path):
"""
Builds the package for `env_meta_path`.
Parameters
----------
env_meta_path : str
path pointing to a 'meta.yaml' file.
Returns
-------
success : the path to the build package
failure : None
"""
if not os.path.exists(env_meta_path):
raise Exception(f"'{env_meta_path}' does not exist!")
env_meta_root = os.path.dirname(env_meta_path)
if not os.path.exists(env_meta_root):
raise Exception(f"'{env_meta_root}' does not exist!")
env_meta_path = os.path.normpath(env_meta_path)
environment = env_meta_path.split(os.sep)[-2]
PY = env_meta_path.split(os.sep)[-3]
OS_CPU = env_meta_path.split(os.sep)[-4]
NUMPY_VER = None
PYTHON_VER = None
with open(env_meta_path) as fd:
for line in fd:
if "- numpy " in line:
NUMPY_VER = line.split("=")[1].strip()
if "- python " in line and PYTHON_VER is None:
PYTHON_VER = line.split("=")[1].strip()
cmd = ["mamba", "build", ".", "--python", PYTHON_VER]
# cmd = ["conda-build", ".", "--python", PYTHON_VER]
if NUMPY_VER:
cmd.extend(["--numpy", NUMPY_VER])
# cmd.extend([f"-c", "conda-forge", "-c", "Semi-ATE"])
cmd.extend([f"-c", "conda-forge"])
print(f" running '{' '.join(cmd)}' in '{env_meta_root}' ... ", end="", flush=True)
p = subprocess.Popen(cmd, cwd=env_meta_root, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = p.communicate()
retval = None
if b"anaconda upload" in output:
print("success.")
retval = output.split(b'anaconda upload \\')[1].replace(b"\r",b"").split(b'\n')[1].decode("utf-8").strip()
print(f" package location = '{retval}'")
else:
print("Failure.")
output_lines = output.decode("utf-8").split("\n")
error_lines = error.decode("utf-8").split("\n")
for line in output_lines:
print(line)
for line in error_lines:
print(line)
return retval | b4802347c3e22ff7b6ae0e8b77ebd31815ebcc7b | 702,912 |
def process_link(link):
"""
Get text and link from an anchor
"""
return link.text_content(), link.get('href') | 34429289076c8518b076fdf0f228eb6948109c6c | 702,913 |
from numpy import interp
def linear(x, y, xref):
"""
Linear interpolation.
:param x:
:param y:
:param xref:
:return:
"""
return interp(xref, x, y, left=None, right=None, period=None) | 16ffc3dd0d73b8bdb395a067bb1962e70d9a255b | 702,914 |
def merge_unique(list1, list2):
"""
Merge two list and keep unique values
"""
for item in list2:
if item not in list1:
list1.append(item)
return list1 | ecfd32178541dcb5956d4c1c74dc9cea2ab1fa45 | 702,916 |
def increment(number: int) -> int:
"""Increment a number.
Args:
number (int): The number to increment.
Returns:
int: The incremented number.
"""
return number + 1 | 27f4becd9afb747b22de991ab4cf030b14d3dac5 | 702,917 |
def CPP(record):
""" "Channel Process if Passive": a CP input link will be treated as
a channel access link and if the linking record is passive,
the linking passive record will be processed any time the linked record
is updated.
Example (Python source)
-----------------------
`my_record.INP = CPP(other_record)`
Example (Generated DB)
----------------------
`field(INP, "other CPP")`
"""
return record('CPP') | 047f19b90e3eb89c8b6f298e1d4ecbf9b035040a | 702,918 |
import re
def normalize_name(name: str) -> str:
"""Replace hyphen (-) and slash (/) with underscore (_) to generate valid
C++ and Python symbols.
"""
name = name.replace('+', '_PLUS_')
return re.sub('[^a-zA-Z0-9_]', '_', name) | 46624c7180b1303e715d73aefe75cdd8e49b4a22 | 702,919 |
def sample(f1, f2, f3, f4):
"""
@see: field 1
@note : is it a field? has space before colon
@param f1: field 3 with an arg
@type f1: integer
@param f2 : is it a field? has space before colon
@return: some value
@param f3: another one
"""
return 1 | 20326992b0a03916b37360edc2a306df706075b3 | 702,920 |
def test_preprocessor_visit_one_children(patch, magic, preprocessor):
"""
Check that a single inline_expression is found
"""
tree = magic()
c1 = magic()
replace = magic()
c1.children = [magic()]
tree.children = [c1]
def is_inline(n):
return n == c1
preprocessor.visit(tree, '.block.', '.entity.', is_inline, replace)
preprocessor.fake_tree.assert_called_with('.block.')
replace.assert_called_with(c1, preprocessor.fake_tree(), '.entity.')
assert replace.call_count == 1 | 4e450c7dbeff77069281fb63d495f0e4770f5fd3 | 702,922 |
def ris_defaultValue_get(fieldsTuple):
"""
params: fieldsTuple, ()
return: fieldVaule_dict, {}
"""
#
ris_element = fieldsTuple[0]
if len(fieldsTuple[1]) != 0:
default_value = fieldsTuple[1][0]
else:
default_value = []
fieldValue_dict = {}
fieldValue_dict[ris_element] = default_value
#
return fieldValue_dict | 0551462066eb984c796ef7ee08d640e9bc4373e5 | 702,923 |
import torch
def project_to_2d(X, camera_params):
"""
Project 3D points to 2D using the Human3.6M camera projection function.
This is a differentiable and batched reimplementation of the original MATLAB script.
Arguments:
X -- 3D points in *camera space* to transform (N, *, 3)
camera_params -- intrinsic parameteres (N, 2+2+3+2=9)
"""
assert X.shape[-1] == 3
assert len(camera_params.shape) == 2
assert camera_params.shape[-1] == 9
assert X.shape[0] == camera_params.shape[0]
while len(camera_params.shape) < len(X.shape):
camera_params = camera_params.unsqueeze(1)
f = camera_params[..., :2]
c = camera_params[..., 2:4]
k = camera_params[..., 4:7]
p = camera_params[..., 7:]
XX = torch.clamp(X[..., :2] / X[..., 2:], min=-1, max=1)
r2 = torch.sum(XX[..., :2]**2, dim=len(XX.shape)-1, keepdim=True)
radial = 1 + torch.sum(k * torch.cat((r2, r2**2, r2**3), dim=len(r2.shape)-1), dim=len(r2.shape)-1, keepdim=True)
tan = torch.sum(p*XX, dim=len(XX.shape)-1, keepdim=True)
XXX = XX*(radial + tan) + p*r2
return f*XXX + c | 0727efaeecfa48540590461f7d9222c8e6071f6d | 702,924 |
def n_coeffs_to_degree(n_coeffs):
"""what is degree if 2d polynomial has n_coeffs coefficients"""
delta_sqrt = int((8 * n_coeffs + 1.)**.5 + 0.5)
if delta_sqrt**2 != (8*n_coeffs+1.):
raise ValueError('Wrong input in n_coeffs_to_degree(): {:}'.format(n_coeffs))
return int((delta_sqrt - 3.) / 2. + 0.5) | 29a767668579d7a9d7c9c871cdb3168c7db3c6c1 | 702,926 |
import hashlib
def checksum_md5(filename, blocksize=8192):
"""Calculate md5sum.
Parameters
----------
filename : str or pathlib.Path
input filename.
blocksize : int
MD5 has 128-byte digest blocks (default: 8192 is 128x64).
Returns
-------
md5 : str
calculated md5sum.
"""
filename = str(filename)
hash_factory = hashlib.md5()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(blocksize), b''):
hash_factory.update(chunk)
return hash_factory.hexdigest() | 759c0c5cbc37ebe0cc85eb8156127308eff354bc | 702,927 |
def normalize_volume_and_number(volume, number):
"""
Padroniza os valores de `volume` e `number`
Args:
volume (None or str): volume se aplicável
number (None or str): número se aplicável
Notas:
- se `number` é igual a `ahead`, equivale a `None`
- se `00`, equivale a `None`
- se `01`, equivale a `1`
- se `""`, equivale a `None`
Returns:
tuple (str or None, str or None)
"""
if number == "ahead":
return None, None
if volume and volume.isdigit():
value = int(volume)
volume = str(value) if value > 0 else None
if number and number.isdigit():
value = int(number)
number = str(value) if value > 0 else None
volume = volume or None
number = number or None
return volume, number | 1ec42912b942f6c1b7e22d2e64c4d842af100877 | 702,928 |
from typing import List
from typing import Tuple
def style_close(style: List[Tuple[str, str]]) -> str:
"""
HTML tags to close a style.
>>> style = [
... ("font", 'color="red" size="32"'),
... ("b", ""),
... ("i", ""),
... ("u", ""),
... ]
>>> style_close(style)
'</u></i></b></font>'
Tags will always be in reverse (of open) order, so open - close will look like::
<b><i><u>text</u></i></b>
"""
return "".join("</{}>".format(x) for x, _ in reversed(style)) | 2043803e50230f139a6a60599b40c53461ed6ed8 | 702,929 |
def get_theta_hat_bw_imd_cm1(theta_star_bw_std):
"""制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(℃)(27b-1)
Args:
theta_star_bw_std(float): 標準条件の沸き上げ温度(
Returns:
float: 制御モードcmの中間条件におけるM1スタンダードモード沸き上げ温度(
"""
# 制御モードがファーストモードの場合
return theta_star_bw_std | caf43cc7c9e17417e3b0096fe89e4a02d41dc0e6 | 702,930 |
import re
def CreateKwargHandler(endpoints, f):
"""
Create methods which contains kwargs
and return the remaining endpoints to handle
"""
index = 0
# endpoints = ["/v2/users", "/v2/users/:id"]
remainEndpoints = []
while index < len(endpoints) - 1:
firstMatches = re.findall("(\/v2[\/\w+]+)", endpoints[index])
secondMatches = re.findall("(\/v2[\/\w+]+)(\/:\w+)(\/\w+)*", endpoints[index + 1])
print(firstMatches, secondMatches)
if len(firstMatches) == len(secondMatches) \
and len(secondMatches[0]) == 3 and secondMatches[0][2] == '' \
and firstMatches[0] == secondMatches[0][0]:
variable = re.findall("(\/:\w+)", endpoints[index + 1])[0]
url = endpoints[index]
#params = ", {}=None".format(variable[2:])
# params = ", *args, {}=None, **kwargs".format(variable[2:])
params = ", {}=None, **kwargs".format(variable[2:])
endpoints[index] = endpoints[index].replace(variable, "")
url = url.replace(variable, "/{}")
splitedValue = endpoints[index][4:].split("/")
funcName = "".join((elem.capitalize() for elem in splitedValue))
payload = """
def {}(self{}):
{}
More details: "https://api.intra.42.fr/apidoc/2.0/{}.html"
{}
extension = "{}/{}".format({}) if {} is not None else "{}"
return HttpMethod(extension, self.session, **kwargs)
"""
# print(payload.format(funcName, params, url, "{}", variables[0][2:], variables[0][2:], url))
f.write(payload.format(funcName, params, '"""', endpoints[index].replace("/v2/", ""), '"""', url, "{}", variable[2:], variable[2:], url))
index += 2
else:
remainEndpoints.append(endpoints[index])
index += 1
return remainEndpoints | a805b8c2b1c1593e973fa0ac781fa780fa4a6d1a | 702,931 |
def pow_many(power, *args):
"""
Функция складывает любое количество цифр и возводит результат в степень power (примеры использования ниже)
:param power: степень
:param args: любое количество цифр
:return: результат вычисления # True -> (1 + 2)**1
"""
rs = 0
for v in args:
rs += v
rp=rs
for i in range(1,power):
rp *= rs
return rp | da0404f24045f5818ffb2219153fccd9b864965b | 702,933 |
import shutil
def gunzip_merge(outfile, list_files):
"""
Merge gunzip files into final file
:param outfile: String for output file
:param list_files: List of files to merge
:type outfile: string
:type list_files: list
"""
list_files = list(list_files)
list_files.sort()
print ("\tMerging files into: ", outfile)
#print ("\tFiles: ", list_files)
with open(outfile, 'wb') as wfp:
for fn in list_files:
with open(fn, 'rb') as rfp:
shutil.copyfileobj(rfp, wfp)
return() | ae37753cc1f16d9fc4cb4cf50587e99ef045a938 | 702,934 |
import subprocess
def _doSysExec(command: str, errorAsOut: bool = True) -> tuple[int, str]:
"""Execute a command and check for errors.
Args:
command (str): commands as a string
errorAsOut (bool, optional): redirect errors to stdout
Raises:
RuntimeWarning: throw a warning should there be a non exit code
Returns:
tuple[int, str]: tuple of return code (int) and stdout (str)
"""
with subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT if errorAsOut else subprocess.PIPE,
encoding="utf-8",
errors="ignore",
) as process:
out = process.communicate()[0]
exitCode = process.returncode
return exitCode, out | 4f6ae92628090c1f00be3268599dcef07c3818ac | 702,935 |
def get_media_pool_clip_list_and_clip_name_list(project):
"""
Parametes
---------
project : Project
a Project instance
Returns
-------
clip_return_list : list
clip list
clip_name_list : list
clip name list
Examples
--------
>>> resolve, project_manager = init_davinci17(
... close_current_project=close_current_project)
>>> get_media_pool_clip_dict_list(project)
[<PyRemoteObject object at 0x000001BB29001630>,
<PyRemoteObject object at 0x000001BB290016D8>,
<PyRemoteObject object at 0x000001BB29001720>]
['dst_grad_tp_1920x1080_b-size_64_[0001-0024].png',
'src_grad_tp_1920x1080_b-size_64_[0000-0023].png',
'dst_grad_tp_1920x1080_b-size_64_resolve_[0000-0023].tif']
"""
media_pool = project.GetMediaPool()
root_folder = media_pool.GetRootFolder()
clip_list = root_folder.GetClipList()
clip_name_list = []
clip_return_list = []
for clip in clip_list:
clip_name_list.append(clip.GetName())
clip_return_list.append(clip)
return clip_return_list, clip_name_list | f69a67d1ae29e714bf8c153519b515238a93875d | 702,936 |
def get_payment_request_with_payment_method(business_identifier: str = 'CP0001234', payment_method: str = 'CC'):
"""Return a payment request object."""
return {
'paymentInfo': {
'methodOfPayment': payment_method
},
'businessInfo': {
'businessIdentifier': business_identifier,
'corpType': 'CP',
'businessName': 'ABC Corp',
'contactInfo': {
'city': 'Victoria',
'postalCode': 'V8P2P2',
'province': 'BC',
'addressLine1': '100 Douglas Street',
'country': 'CA'
}
},
'filingInfo': {
'filingTypes': [
{
'filingTypeCode': 'OTADD',
'filingDescription': 'TEST'
},
{
'filingTypeCode': 'OTANN'
}
]
}
} | c506f2750e0ffe5d1852116eab241e7e022d3b84 | 702,937 |
import os
def _coffea_fn_as_file_wrapper(tmpdir):
""" Writes a wrapper script to run dilled python functions and arguments.
The wrapper takes as arguments the name of three files: function, argument, and output.
The files function and argument have the dilled function and argument, respectively.
The file output is created (or overwritten), with the dilled result of the function call.
The wrapper created is created/deleted according to the lifetime of the work_queue_executor."""
name = os.path.join(tmpdir, 'fn_as_file')
with open(name, mode='w') as f:
f.write("""
#!/usr/bin/env python3
import os
import sys
import dill
import coffea
(fn, arg, out) = sys.argv[1], sys.argv[2], sys.argv[3]
with open(fn, "rb") as f:
exec_function = dill.load(f)
with open(arg, "rb") as f:
exec_item = dill.load(f)
pickle_out = exec_function(exec_item)
with open(out, "wb") as f:
dill.dump(pickle_out, f) """)
return name | d8beac710f818bdc01cd794c586c0f101ea26b9b | 702,939 |
def process_categories(cat_path):
""" Returns the mapping between the identifier of a category in
Places365 and its corresponding name
Args:
cat_path: Path containing the information about the Places365
categories
"""
result = {}
with open(cat_path) as f:
lines = f.readlines()
# Map each position to the corresponding category
for l in lines:
parts = l.split(' ')
raw_cat, num_cat = parts[0].rstrip(), int(parts[1].rstrip())
category = raw_cat[3:] # Erase prefix related to first letter
result[num_cat] = category
return result | f87741b990ee9ab9c8216112df73c7aa5bab8d49 | 702,940 |
import struct
def fread(f,byteLocation,structFormat=None,nBytes=1):
"""
Given an already-open (rb mode) file object, return a certain number of bytes at a specific location.
If a struct format is given, calculate the number of bytes required and return the object it represents.
"""
f.seek(byteLocation)
if structFormat:
val = struct.unpack(structFormat, f.read(struct.calcsize(structFormat)))
val = val[0] if len(val)==1 else list(val)
return val
else:
return f.read(nBytes) | ae86bb1f3bc839053ca34c8bf2b4beb0af04aaee | 702,942 |
def _cast_types(args):
"""
This method performs casting to all types of inputs passed via cmd.
:param args: argparse.ArgumentParser object.
:return: argparse.ArgumentParser object.
"""
args.x_val = int(args.x_val) if args.x_val != 'None' else None
args.test_size = float(args.test_size)
# criterion (string)
# splitter (string)
args.max_depth = None if args.max_depth == 'None' else float(args.max_depth)
args.min_samples_split = int(args.min_samples_split)
args.min_samples_leaf = int(args.min_samples_leaf)
args.min_weight_fraction_leaf = float(args.min_weight_fraction_leaf)
args.max_features = None if args.max_features == 'None' else float(args.max_features)
args.random_state = None if args.random_state == 'None' else float(args.random_state)
args.max_leaf_nodes = None if args.max_leaf_nodes == 'None' else float(args.max_leaf_nodes)
args.min_impurity_decrease = float(args.min_impurity_decrease)
args.class_weight = None if args.class_weight == 'None' else float(args.class_weight)
args.presort = (args.presort in ['True', 'true'] )
return args | 61438940cdc572b08ebd7ee0efe56cae65c1ddd7 | 702,943 |
def _get_year(obj):
"""
Get the year of the entry.
:param obj: year string object
:return: entry year or none if not valid value
"""
year = obj[0:4]
try:
year = int(year)
except ValueError:
year = None
return year | 6d3cbcc8759096ec3e798e90dc3a307b4a34b6ae | 702,945 |
import argparse
def _parse_arguments():
"""Return a parser context result."""
parser = argparse.ArgumentParser(description="CMake AST Dumper")
parser.add_argument("filename", nargs=1, metavar=("FILE"),
help="read FILE")
return parser.parse_args() | a811308be0fdb28294f8a0a0af80bf3a2cceae51 | 702,946 |
def epochPoints(abf):
"""Return a list of time points where each epoch starts and ends."""
if abf.abfVersion["major"] == 1:
return []
position = int(abf.sweepPointCount/64)
epochPoints = [position]
for epochNumber, epochType in enumerate(abf._epochPerDacSection.nEpochType):
pointCount = abf._epochPerDacSection.lEpochInitDuration[epochNumber]
epochPoints.append(position + pointCount)
position += pointCount
return epochPoints | 1eafc6a6cd7a3e68a5136ef6b92a4e7defae0648 | 702,948 |
import math
def lat_meters(lat: float) -> float:
"""
Transform latitude degree to meters.
Parameters
----------
lat : float
This represent latitude value.
Returns
-------
float
Represents the corresponding latitude value in meters.
Examples
--------
Latitude in Fortaleza: -3.71839
>>> from pymove.utils.conversions import lat_meters
>>> lat_meters(-3.71839)
110832.75545918777
"""
rlat = float(lat) * math.pi / 180
# meter per degree Latitude
meters_lat = (
111132.92 - 559.82 * math.cos(2 * rlat) + 1.175 * math.cos(4 * rlat)
)
# meter per degree Longitude
meters_lgn = 111412.84 * math.cos(rlat) - 93.5 * math.cos(3 * rlat)
meters = (meters_lat + meters_lgn) / 2
return meters | c31025552778b0039079d33e134e0b19077b83d4 | 702,949 |
def getFilteredLexicon(lexicondict, allwords):
""" Returns a lexicon with just the necessary words.
Assumes all wanted keys exist in the given lexicon """
return { word: lexicondict[word] for word in allwords } | db3c58b71df848ef5b1d49ebdd4670a552481c64 | 702,951 |
import unittest
def filter_suite(condition, suite):
"""Return tests for which ``condition`` is True in ``suite``.
:param condition: A callable receiving a test and returning True if the
test should be kept.
:param suite: A test suite that can be iterated. It contains either tests
or suite inheriting from ``unittest.TestSuite``.
``suite`` is a tree of tests and suites, the returned suite respect the
received suite layout, only removing empty suites.
"""
filtered_suite = suite.__class__()
for test in suite:
if issubclass(test.__class__, unittest.TestSuite):
# We received a suite, we'll filter a suite
filtered = filter_suite(condition, test)
if filtered.countTestCases():
# Keep only non-empty suites
filtered_suite.addTest(filtered)
elif condition(test):
# The test is kept
filtered_suite.addTest(test)
return filtered_suite | 9131d49d3f87a117d2b9625d521e932db2666860 | 702,952 |
import torch
def collate_fn(batch):
"""Creates mini-batch tensors from the list of tuples (images,
triplets_local_indexes, triplets_global_indexes).
triplets_local_indexes are the indexes referring to each triplet within images.
triplets_global_indexes are the global indexes of each image.
Args:
batch: list of tuple (images, triplets_local_indexes, triplets_global_indexes).
considering each query to have 10 negatives (negs_num_per_query=10):
- images: torch tensor of shape (12, 3, h, w).
- triplets_local_indexes: torch tensor of shape (10, 3).
- triplets_global_indexes: torch tensor of shape (12).
Returns:
images: torch tensor of shape (batch_size*12, 3, h, w).
triplets_local_indexes: torch tensor of shape (batch_size*10, 3).
triplets_global_indexes: torch tensor of shape (batch_size, 12).
"""
images = torch.cat([e[0] for e in batch])
triplets_local_indexes = torch.cat([e[1][None] for e in batch])
triplets_global_indexes = torch.cat([e[2][None] for e in batch])
for i, (local_indexes, global_indexes) in enumerate(zip(triplets_local_indexes, triplets_global_indexes)):
local_indexes += len(global_indexes) * i # Increment local indexes by offset (len(global_indexes) is 12)
return images, torch.cat(tuple(triplets_local_indexes)), triplets_global_indexes | c7267579e6e7f4fa54cca951b5cad15e4ce5283a | 702,953 |
def bytes_to_long(in_bytes):
"""Converts a byte string into a long"""
hexstr = ''.join(["%0.2x" % ord(byte) for byte in in_bytes])
return int(hexstr, 16) | 89d82a72226457c3a1ac1438cab1071d3cbcd62d | 702,955 |
def func():
"""Return a new matrix of given shape and type, without initializing entries.
Parameters
----------
shape : int or tuple of int
Shape of the empty matrix.
dtype : data-type, optional
Desired output data-type.
order : {'C', 'F'}, optional
Whether to store multi-dimensional data in row-major
(C-style) or column-major (Fortran-style) order in
memory.
See Also
--------
empty_like, zeros
Notes
-----
`empty`, unlike `zeros`, does not set the matrix values to zero,
and may therefore be marginally faster. On the other hand, it requires
the user to manually set all the values in the array, and should be
used with caution.
Examples
--------
>>> import numpy.matlib
>>> np.matlib.empty((2, 2)) # filled with random data
matrix([[ 6.76425276e-320, 9.79033856e-307],
[ 7.39337286e-309, 3.22135945e-309]]) #random
>>> np.matlib.empty((2, 2), dtype=int)
matrix([[ 6600475, 0],
[ 6586976, 22740995]]) #random
"""
return 0 | c48914045c296b25fbfef0f1e409b7bc40b1a677 | 702,956 |
def cli(ctx, library_id, access_in="", modify_in="", add_in="", manage_in=""):
"""Set the permissions for a library. Note: it will override all security for this library even if you leave out a permission type.
Output:
General information about the library
"""
return ctx.gi.libraries.set_library_permissions(library_id, access_in=access_in, modify_in=modify_in, add_in=add_in, manage_in=manage_in) | 833f828b5405b29d577a8859da8a895791da22bc | 702,958 |
def get_users():
"""Retrieve information about users"""
return "get users" | 40e2c1e8046beaa6d1b6f7875c2a3e3f7bad8e69 | 702,959 |
import grp
def import_sam_group(samldb, sid, gid, sid_name_use, nt_name, comment, domaindn):
"""Upgrade a SAM group.
:param samldb: SAM database.
:param gid: Group GID
:param sid_name_use: SID name use
:param nt_name: NT Group Name
:param comment: NT Group Comment
:param domaindn: Domain DN
"""
if sid_name_use == 5: # Well-known group
return None
if nt_name in ("Domain Guests", "Domain Users", "Domain Admins"):
return None
if gid == -1:
gr = grp.getgrnam(nt_name)
else:
gr = grp.getgrgid(gid)
if gr is None:
unixname = "UNKNOWN"
else:
unixname = gr.gr_name
assert unixname is not None
samldb.add({
"dn": "cn=%s,%s" % (nt_name, domaindn),
"objectClass": ["top", "group"],
"description": comment,
"cn": nt_name,
"objectSid": sid,
"unixName": unixname,
"samba3SidNameUse": str(sid_name_use)
}) | 05c005c01131684bad78fd45af0b82d4b1b2fedc | 702,960 |
def get_postgres_curie_prefix(curie):
"""The representation in postgres moves things to lowercase, and replaces . with _"""
if ':' not in curie:
raise ValueError(f'Curies ought to contain a colon: {curie}')
prefix = curie.lower().split(':')
prefix = '_'.join(prefix[0].split('.'))
return prefix | 314d59205fffd7e3dcdfb3a5ca7a81a12baffa76 | 702,961 |
import json
def parse_stations(html):
"""
Strips JS code, loads JSON
"""
html = html.replace('SLs.sls=', '').replace(';SLs.showSuggestion();', '')
html = json.loads(html)
return html['suggestions'] | f9fb64d21c0b206b4c034e0f8a5c560eccb9b9e4 | 702,962 |
import json
def json_to_str(json_obj):
"""JSONをstr型へ変換"""
return json.dumps(json_obj, separators=(",", ":"), ensure_ascii=False) | 1ef38962b264991287f5b468489b20bd85be30ff | 702,963 |
def get_color(orig_label=None,
gt_label=None,
target_label=None,
adv_label=None,
targeted_attack=False):
"""Get color according to different possible correctness combinations."""
if ((gt_label is None or orig_label == gt_label) and
(adv_label is None or adv_label == gt_label)):
color = '#4d8021' # 'green': correct prediction
elif adv_label is None:
color = '#b81e26' # 'red': not adversarial, incorrect prediction
elif adv_label == gt_label:
color = '#a8db78' # 'lightgreen': adv_label correct, but orig_label wrong
elif adv_label == orig_label:
color = '#b09b3e' # 'yellow': incorrect, but no change to prediction
elif not targeted_attack and adv_label is not None and adv_label != gt_label:
color = '#b81e26' # 'red': untargeted attack, adv_label changed, success
elif targeted_attack and adv_label == target_label:
color = '#b81e26' # 'red': targeted attack, success
elif targeted_attack and adv_label != target_label:
color = '#d064a6' # 'pink': targeted attack, changed prediction but failed
else:
color = '#6780d8' # 'blue': unaccounted-for result
return color | 8a05dde4c60582bc2559f182423e795d2ecc1c1d | 702,964 |
import re
def read_cpr(path):
"""Read and parse a CPR file. Return masks, which are (id, RLE data).
Note: Python 3.6.4 docs say its XML module is not secure, se we use regexp.
"""
# Example: <Mask id="123">[12 34 56]</Mask>
mask_pattern = r'<Mask\s.*?id="(.*?)".*?>.*?\[(.*?)\].*?</Mask>'
text = path.read_text()
matches = re.finditer(mask_pattern, text, flags=re.DOTALL)
def parse_match(m):
number, mask = m.groups()
number = int(number)
mask = [int(x) for x in mask.split()]
return number, mask
masks = [parse_match(x) for x in matches]
return masks | b5781607c150d0521d816c9027660e2b5e4b0fe0 | 702,965 |
import math
def schaffer6(phenome):
"""The bare-bones Schaffer function 6."""
sum_of_squares = phenome[0] ** 2 + phenome[1] ** 2
result = math.sin(math.sqrt(sum_of_squares)) ** 2 - 0.5
result /= (1.0 + 0.001 * sum_of_squares) ** 2
result += 0.5
return result | 80f19b28ebf4511a0670dfa622ffd3c55e8ec670 | 702,966 |
def take_before_exclusive(iterable, predicate):
"""Yield items up to but excluding including the first match.
If no matching item is present, the result is empty.
Args:
iterable: An iterable series of items.
predicate: A function of one argument used to select the last item.
Returns:
A sequence of items finishing with the first match.
"""
items = []
for item in iterable:
if predicate(item):
return items
items.append(item)
return [] | 3f62a1575541dfcd071424fca4b290f3f50cc518 | 702,967 |
def build_filters(tbinfogolden):
"""
Build for each tb in tbinfo a filter
"""
filter_return = []
"""Each assembler string"""
for tb in tbinfogolden["assembler"]:
tb_filter = []
"""remove first split, as it is empty"""
split = tb.split("[ ")
"""For each line"""
for sp in split[1:]:
"""select address"""
s = sp.split("]")
"""Add to filter"""
tb_filter.append(int("0x" + s[0].strip(), 0))
"""Sort addresses"""
tb_filter.sort()
"""Reverse list so that last element is first"""
tb_filter.reverse()
"""Append to filter list"""
filter_return.append(tb_filter)
"""Filter list for length of filter, so that the longest one is tested first"""
filter_return.sort(key=len)
filter_return.reverse()
return filter_return | fdbf2c0b64c9582a00acb38c8395d249dfeb6f56 | 702,968 |
from pathlib import Path
def data_root_directory():
"""Get a path to the top level data directory. Checks whether you have created the local store of data at the expected
location and returns that as default if found, otherwise returns the location on the shared folder
Returns:
(pathlib Path): A path
"""
return Path(__file__).parents[1] / "extra_data" / "data" | f687ffcf05aa74c521624467c3be7ec108de6a46 | 702,969 |
import re
import socket
def get_host_name() -> str:
"""Get the host name.
:return: A string value.
"""
return re.sub(r"\.(?:local|lan)", "", socket.gethostname()) | 225889a0bf40943ef962903551bde85fd2729ac8 | 702,970 |
def fix_hyphen_commands(raw_cli_arguments):
"""Update options to match their module names with underscores."""
for i in ['gen-sample', 'run-python', 'run-stacker']:
raw_cli_arguments[i.replace('-', '_')] = raw_cli_arguments[i]
raw_cli_arguments.pop(i)
return raw_cli_arguments | cbc420547f1d3a04787d059aa09eb0199df82dba | 702,971 |
def get_data_types(nb_sensors):
"""
What should be the data type for each sensor (1 - integer, 2 - float)
Input
nb_sensors -> how many sensors (int)
Output
data_type_per_sensor -> list of data types for each sensor
"""
print("Choose data type for each sensor: 1-integer / 2-float")
print("Enter 1 or 2 for each sensor, use space as a separator")
nb_type = input("Data Types: ")
print("")
print("****************************************************************")
# split string
data_types = nb_type.split(" ")
allowed_data_types = (1, 2)
data_nbr = len(data_types)
if (nb_sensors == data_nbr):
try:
for idx in range(data_nbr):
if int(data_types[idx]) in allowed_data_types:
continue
else:
raise ValueError
# put splitted data into a list
data_type_per_sensor = [int(data_types[i]) for i in range(data_nbr)]
return data_type_per_sensor
except ValueError:
print("Invalid input. Please try again.")
return get_data_types(nb_sensors)
else:
print("Invalid input. Please try again.")
return get_data_types(nb_sensors) | f3133d415f1d6c8448fec57a1f14fb88d697107d | 702,972 |
def read_line_offset(file, offset):
""" Seek to offset in file, read a line and return the line and new offset """
fp = open(file, "r")
fp.seek(offset, 0)
line = fp.readline()
offset = fp.tell()
fp.close()
return (line, offset) | 429d592cf44e1f287eea5a67302a78473eb2362f | 702,973 |
def calculate_bmi(weight, height):
"""
Calculates BMI given the weight and height as float
"""
bmi = (weight / (height * height)) * 703.0
return bmi | 8495b11598e50516dca80965d5063df92aa78f40 | 702,974 |
import re
def get_task_factor(task_name, overrides, override_type, factor):
"""Check for task override and return factor."""
for task_override in overrides.get(override_type, []):
if re.compile(task_override["task"]).match(task_name):
return task_override["factor"]
return factor | eb58f291c5a21a9974b9f7d4bce739bdc99d5f89 | 702,975 |
def argstr(arg): # pragma: no cover
"""
Return string representation of a function argument.
:param object arg: Argument object. Differs between Python versions.
:return: String name of argument.
"""
if isinstance(arg, str):
return arg
if 'id' in arg._fields:
return arg.id
return arg.arg | 565349fc4a1fb9b28e8333a44893925cea9e72d9 | 702,976 |
def getDistance(sensor):
"""Return the distance of an obstacle for a sensor."""
# Special case, when the sensor doesn't detect anything, we use an
# infinite distance.
if sensor.getValue() == 0:
return float("inf")
return 5.0 * (1.0 - sensor.getValue() / 1024.0) | 68ff9e0c8c4dd7687e328d3b9c4634677cfe25cd | 702,978 |
def test_path_and_query_parameters(
arg1,
arg2,
):
"""
Use same arg name as the one in path for receiving path args
For those args which names not matched path arg names, will be parsed as query parameter
```python
from django_mini_fastapi import Path
@api.get('/test_path_and_query_parameters/{arg1}')
def test_path_and_query_parameters(arg1, arg2):
return dict(arg1=arg1, arg2=arg2)
```
"""
return dict(arg1=arg1, arg2=arg2) | 72823f5fa66065171c36329f6b05e61a710fa065 | 702,979 |
import re
def GENERIC_MAX(segment_pattern, lenv=None, renv=None):
"""Takes the regex pattern for segments being examined for
deletion, and a pair of lists indicating their deletion environment,,
and returns a function that will count how many times a segment
of that class is deleted from an input to an output string."""
# Determine the search parameter first
# If it's a context-free constraint, just use the segment pattern
if lenv == None and renv == None:
inp_parameter = segment_pattern
out_parameter = segment_pattern
# If there is a preceding context (if you need to scan left)
elif lenv != None and renv == None:
inp_parameter = "({0})(\s|\d)*({1})".format(lenv, segment_pattern)
out_parameter = "({0})(\s|[CV])*({1})".format(lenv, segment_pattern)
elif lenv == None and renv != None:
inp_parameter = "({0})(\s|\d)*({1})".format(segment_pattern, renv)
out_parameter = "({0})(\s|[CV])*({1})".format(segment_pattern, renv)
else:
inp_parameter = "({0})(\s|\d)*({1})(\s|\d)*({2})".format(lenv, segment_pattern, renv)
out_parameter = "({0})(\s|[CV])*({1})(\s|[CV])*({2})".format(lenv, segment_pattern, renv)
def F(inp, outp):
# Define default behaviour for empty candidates
if outp == "":
return 1
# First, check to see if the search parameter is present in the input
i_matches = re.findall(inp_parameter, inp)
if len(i_matches) != 0:
# See if you can find all of them in the output
o_matches = re.findall(out_parameter, outp)
if len(o_matches) == len(i_matches):
return 0
else:
return len(re.findall(segment_pattern, inp)) - len(re.findall(segment_pattern, outp))
# Define default behaviour
return 0
return F | d729cb96850397a36b687d2b43c487b3670f7c56 | 702,980 |
import logging
import time
def check_subs(client):
""" Checks that all Subscriptions have been received"""
wcount = 0
while wcount < 10:
for t in client.topic_ack:
wcount += 1
if t[2] == 0:
logging.info("subscription to " + str(t[0]) + " not acknowledged")
break
print("All subs acknowledged")
return True
time.sleep(1)
if not client.running_loop:
client.loop(.01) # check for messages manually
return False | 95892066b9da2a530a28f06a7e5804fdee7e65d0 | 702,982 |
def Get_Items(filename):
"""Convert plain text to class string"""
L = []
with open(filename, 'r') as file:
items = file.readlines()
for line in items:
L.append(line[:-1])
return L | 8b579dcfb8df21de68a05a8dad4d7aff06951f64 | 702,983 |
import math
def circles_intersection(x_a, y_a, r_a, x_b, y_b, r_b):
"""
Returns the point of intersection of two circkes
:param x_a: x coordinate of the center of first circle
:param y_a: y coordinate of the center of first circle
:param r_a: radius of first circle
:param x_b: x coordinate of the center of second circle
:param y_b: y coordinate of the center of second circle
:param r_b: radius of second circle
:return: Array of coordinates of one of the intersection points
"""
k = x_a*x_a - x_b*x_b + y_a*y_a - y_b*y_b - r_a*r_a + r_b*r_b
c = 0.5 * k / (y_a - y_b)
m = (x_a - x_b) / (y_b - y_a)
g = c - y_a
aa = 1 + m*m
bb = 2*m*g - 2*x_a
cc = x_a*x_a + g*g - r_a*r_a
xi = 0.5 * (-bb + math.sqrt(bb*bb - 4*aa*cc)) / aa
yi = m*xi + c
return [xi, yi] | dc504bbe970c83bf1caf7727613ecaa44c1c818e | 702,985 |
def get_grade_map():
"""
Defines a mapping of Fontainebleau grades to integer values
"""
grade_map = {
'6B': 0, # V4
'6B+': 0, # V4
'6C': 1, # V5
'6C+': 1, # V5
'7A': 2, # V6
'7A+': 3, # V7
'7B': 4, # V8
'7B+': 4, # V8
'7C': 5, # V9
'7C+': 6, # V10
'8A': 7, # V11
'8A+': 8, # V12
'8B': 9, # V13
}
return grade_map | 1137d7c21b18556ce69db635314c968024b3394b | 702,986 |
import os
def which(cmd):
"""
Returns full path to a executable.
Args:
cmd (str): Executable command to search for.
Returns:
(str) Full path to command. None if it is not found.
Example::
full_path_to_python = which("python")
"""
def is_exe(fp):
return os.path.isfile(fp) and os.access(fp, os.X_OK)
fpath, fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
return cmd
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, cmd)
if is_exe(exe_file):
return exe_file
return None | db7d9f79d0a7d7f9673d181fb4fb1f0d00aa6fab | 702,987 |
def get_class_mapping(super_mode: str):
"""
Mapping mode into integer
:param super_mode: before, after & both
:return:
"""
class_mapping = ['none', 'replace']
if super_mode == 'both':
class_mapping.extend(['before', 'after'])
else:
class_mapping.append(super_mode)
return {k: v for v, k in enumerate(class_mapping)} | 33e1f40c600f68b6ea760ec9340d04555ecae463 | 702,989 |
import socket
def get_banner():
"""Get the ``banner`` that will be signed in :meth:`adb_shell.adb_device.AdbDevice.connect` / :meth:`adb_shell.adb_device_async.AdbDeviceAsync.connect`.
Returns
-------
bytearray
The hostname, or "unknown" if it could not be determined
"""
try:
return bytearray(socket.gethostname(), 'utf-8')
except: # noqa pylint: disable=bare-except
return bytearray('unknown', 'utf-8') | 9babf7db8d4177b427f46c0785b899c79ba2691c | 702,990 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.