content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def upload_to_sql(git_commit_filename, commit_people_filename, cc,
git_checkout_path, commits_after_date): # pragma: no cover
"""Writes suspicious git commits to a Cloud SQL database
Args:
cc: a cursor for the Cloud SQL connection
git_checkout_path(str): path to a local git checkout
"""
write_to... | 8,900 |
def l2_normalize_rows(frame):
"""
L_2-normalize the rows of this DataFrame, so their lengths in Euclidean
distance are all 1. This enables cosine similarities to be computed as
dot-products between these rows.
Rows of zeroes will be normalized to zeroes, and frames with no rows will
be returned... | 8,901 |
def install():
""" Installs the webapp code in the virtual environemnt 'web' on the server.
"""
with cd('/home/genomics.www/status'):
with prefix('workon web'):
sudo('python setup.py develop', user='genomics.www') | 8,902 |
def unregister_custom_op(op_name: str) -> None:
""" Unregister a custom operator.
Args:
op_name (str): Name of the custom operator
"""
bound_op_map.pop(op_name) | 8,903 |
def canonical_ipv4_address(ip_addr):
"""Return the IPv4 address in a canonical format"""
return socket.inet_ntoa(socket.inet_aton(ip_addr)) | 8,904 |
def _build_dynatree(site, expanded):
"""Returns a dynatree hash representation of our pages and menu
hierarchy."""
subtree = _pages_subtree(site.doc_root, site.default_language, True, 1,
expanded)
subtree['activate'] = True
pages_node = {
'title': 'Pages',
'key': 'system:page... | 8,905 |
def check_tie_condition(board):
""" tie = if no empty cells and no win """
logging.debug('check_tie_condition()')
# is the board full and no wins
empty_cells = board.count('-')
logging.debug(f'Number of empty cells {empty_cells}')
tie = (empty_cells == 0)
return tie | 8,906 |
def aggregator(df, groupbycols):
"""
Aggregates flowbyactivity or flowbysector df by given groupbycols
:param df: Either flowbyactivity or flowbysector
:param groupbycols: Either flowbyactivity or flowbysector columns
:return:
"""
# tmp replace null values with empty cells
df = replace... | 8,907 |
def test_svr_linear_rfe():
"""
Test to see if normalized SVR dataset is a pandas core dataframe
"""
test_x_train = vse.get_data_rfe()[0]
test_y_train = vse.get_data_rfe()[2]
test_result = vse.svr_linear_rfe(test_x_train, test_y_train)
assert isinstance(test_result[1], pd.core.frame.DataFrame... | 8,908 |
def setup_logging():
"""Set up logging based on provided log params."""
formatter = logging.Formatter(LOG_FORMAT)
ROOTLOGGER.setLevel(config["app"]["log_level"].upper())
sh = logging.StreamHandler()
sh.setLevel(config["app"]["log_level"].upper())
sh.setFormatter(formatter)
ROOTLOGGER.addHan... | 8,909 |
def unpack(X):
""" Unpack a comma separated list of values into a flat list """
return flatten([x.split(",") for x in list(X)]) | 8,910 |
def doize(tock=0.0, **opts):
"""
Decorator that returns Doist compatible decorated generator function.
Usage:
@doize
def f():
pass
Parameters:
tock is default tock attribute of doized f
opts is dictionary of remaining parameters that becomes .opts attribute
o... | 8,911 |
def get_env(path):
"""
Read the environment file from given path.
:param path: Path to the environment file.
:return: the environment (loaded yaml)
"""
with codecs.open(path, 'r', 'UTF-8') as env_file:
conf_string = env_file.read()
env = yaml.load(conf_string)
logging.de... | 8,912 |
def put_value(obj, value):
"""Sets the value of `obj` reference to `value`.
See [ECMA-262 8.7.2] for details."""
if isinstance(obj, Reference):
obj.put_value(value)
else:
raise ReferenceError("Can't put a value of non-reference object %r" % obj) | 8,913 |
def make_chained_transformation(tran_fns, *args, **kwargs):
"""Returns a dataset transformation function that applies a list of
transformations sequentially.
Args:
tran_fns (list): A list of dataset transformation.
*args: Extra arguments for each of the transformation function.
**kw... | 8,914 |
def configure_optimizer(learning_rate):
"""Configures the optimizer used for training.
Args:
learning_rate: A scalar or `Tensor` learning rate.
Returns:
An instance of an optimizer.
Raises:
ValueError: if FLAGS.optimizer is not recognized.
"""
if FLAGS.optimizer == 'adadelta':
optim... | 8,915 |
def train_and_evaluate(config, workdir):
"""Runs a training and evaluation loop.
Args:
config: Configuration to use.
workdir: Working directory for checkpoints and TF summaries. If this
contains checkpoint training will be resumed from the latest checkpoint.
Returns:
Training state.
"""
rn... | 8,916 |
def flail(robot: DynamixelRobotComponent):
"""Commands the robot to flail if it's stuck on an obstacle."""
for _ in range(6):
robot.set_state(
{'all': RobotState(qpos=(np.random.rand(12) - .5) * 3)},
**SET_PARAMS,
timeout=.15,
) | 8,917 |
def deploy(version):
""" depoly app to cloud """
with cd(app_path):
get_app(version)
setup_app(version)
config_app()
nginx_config()
nginx_enable_site('growth-studio.conf')
circus_config()
circus_upstart_config()
circus_start()
nginx_restart() | 8,918 |
def test_publishing_the_same_volumes_with_a_different_target_path():
"""Publishing the same volumes with a different target_path.""" | 8,919 |
def increment(i,k):
""" this is a helper function for a summation of the type :math:`\sum_{0 \leq k \leq i}`,
where i and k are multi-indices.
Parameters
----------
i: numpy.ndarray
integer array, i.size = N
k: numpy.ndarray
integer array, k.size = N... | 8,920 |
def sample_lopt(key: chex.PRNGKey) -> cfgobject.CFGObject:
"""Sample a small lopt model."""
lf = cfgobject.LogFeature
rng = hk.PRNGSequence(key)
task_family_cfg = para_image_mlp.sample_image_mlp(next(rng))
lopt_name = parametric_utils.choice(
next(rng), [
"LearnableAdam", "LearnableSGDM", "L... | 8,921 |
def helper_describe_zones():
"""
Create the zones list in the project
:return:
"""
global zones_list
request = compute_service.zones().list(project=project)
while request is not None:
response = request.execute()
for zone in response['items']:
zones_list.append(... | 8,922 |
def gen_df_groupby_usecase(method_name, groupby_params=None, method_params=''):
"""Generate df groupby method use case"""
groupby_params = {} if groupby_params is None else groupby_params
groupby_params = get_groupby_params(**groupby_params)
func_text = groupby_usecase_tmpl.format(**{
'method_... | 8,923 |
def run_successful_task(action: Action, action_owner_name: str):
"""Run action and expect it succeeds"""
task = action.run()
try:
wait_for_task_and_assert_result(task, status="success")
except AssertionError as error:
raise AssertionError(
f'Action {action.name} should have s... | 8,924 |
def _processor_startup_fn(
pull_port, push_port, sockets_connected_evt, process_fn, event_queue, debug
):
"""
Parameters
----------
pull_port :
push_port :
sockets_connected_evt :
process_fn :
event_queue :
debug :
Returns
-------
"""
bridge = Bridge(debu... | 8,925 |
def hydra_breakpoints(in_bam, pair_stats):
"""Detect structural variation breakpoints with hydra.
"""
in_bed = convert_bam_to_bed(in_bam)
if os.path.getsize(in_bed) > 0:
pair_bed = pair_discordants(in_bed, pair_stats)
dedup_bed = dedup_discordants(pair_bed)
return run_hydra(dedup... | 8,926 |
def merge_csvfiles(options):
""" Think of this as a 'join' across options.mergefiles on equal values of
the column options.timestamp. This function takes each file in
options.mergefiles, reads them, and combines their columns in
options.output. The only common column should be options.timestamp. The
... | 8,927 |
def data_generator(samples, shape, batch_size, correction, sensitivity,
angle_threshold):
"""Used to build an augmented data set for training
Args:
samples (list(str)): list of samples to process
shape (tuple(int)): shape of input
batch_size (int): number of samples... | 8,928 |
async def euphoria():
"""
Trigger a state of "euphoria" emotion, extremely happy and positive bot
"""
async with db.DiscordDB("emotions") as db_obj:
db_obj.write(
{
"happy": EMOTION_CAPS["happy"][1],
"anger": EMOTION_CAPS["anger"][0],
"... | 8,929 |
def row_component(cards):
"""
Creates a horizontal row used to contain cards.
The card and row_component work together to create a
layout that stretches and shrinks when the user changes the size of the window,
or accesses the dashboard from a mobile device.
See https://developer.mozilla.org/en... | 8,930 |
def recCopyElement(oldelement):
"""Generates a copy of an xml element and recursively of all
child elements.
:param oldelement: an instance of lxml.etree._Element
:returns: a copy of the "oldelement"
.. warning::
doesn't copy ``.text`` or ``.tail`` of xml elements
"""
newelement =... | 8,931 |
def NameExpansionIterator(command_name,
debug,
logger,
gsutil_api,
url_strs,
recursion_requested,
all_versions=False,
cmd_supports_recursi... | 8,932 |
def KETAMA(key):
"""
MD5-based hashing algorithm used in consistent hashing scheme
to compensate for servers added/removed from memcached pool.
"""
d = hashlib.md5(key).digest()
c = _signed_int32
h = c((ord(d[3])&0xff) << 24) | c((ord(d[2]) & 0xff) << 16) | \
c((ord(d[1]) & 0xff)... | 8,933 |
def add_months(dt, months):
"""
月加减
"""
month = dt.month - 1 + months
year = dt.year + month / 12
month = month % 12 + 1
day = min(dt.day, calendar.monthrange(year, month)[1])
return dt.replace(year=year, month=month, day=day) | 8,934 |
def create_plot(
file_names,
output_folder_name,
output_prefix,
gat_TATA_constitutive_output,
gat_TATA_variable_output,
palette,
variable1_name,
variable2_name,
):
"""import and process the raw outputs after running gat (Genomic association tester). Then create barplot of constitutiv... | 8,935 |
def install_plugins():
"""Check for existing plugins and removed if they exist..."""
vim_plugins = os.path.join(str(pathlib.Path.home()), '.vim', 'bundle', )
print("Removing existing bundles...")
subprocess.Popen(['rm', '-rf', vim_plugins]).wait()
print("Installing plugins...")
subprocess.Popen... | 8,936 |
def _decomposer_interp(fp, x=None, xp=None):
"""Do the actual interpolation for multiprocessing"""
return np.interp(x, xp, fp) | 8,937 |
def create_nn(x, x_shape, is_training):
"""
Args:
x: input hits array
x_shape: input tensor shape for single event
is_training: placeholder for indicating train or valid/test phase
Note: Only code in `create_nn` function scope will be exctracted and saved
in model directory.... | 8,938 |
def create_new_case(case_dir):
"""Creates new case directory"""
# Check that the specified case directory does not already exist
if os.path.exists(case_dir):
call(["rm", "-r", "snappy"])
#raise RuntimeError(
# 'Refusing to write to existing path: {}'.format(case_dir)
#... | 8,939 |
def generate_outlier_bounds_iqr(df, column, multiplier=1.5):
"""
Takes in a dataframe, the column name, and can specify a multiplier (default=1.5). Returns the upper and lower bounds for the
values in that column that signify outliers.
"""
q1 = df[column].quantile(.25)
q3 = df[column].quantile(.... | 8,940 |
def generate_data(Type):
"""
随机生成CAN帧中所包含的数据
:param Type: 需要生成数据的类型
:return: 生成的随机数据序列,长度为8,如['88', '77', '55', '44', '22', '11', '33'', '44']
"""
data = []
if Type == 1:
# 生成反馈帧单体电池Cell1-24电压信息
standard_vol = 35
offset = random.randint(0, 15)
max_vol = standa... | 8,941 |
def counting_sort(array):
"""
SORTING FUNCTION USING COUNTING SORT ALGORITHM
ARG array = LIST(ARRAY) OF NUMBERS
"""
## counter lists has elements for every
maximum = max(array)
counter = [0]*(maximum+1)
for i in range(len(array)):
counter[array[i]] += 1
for i in range(1, ma... | 8,942 |
def indexedcolor(i, num, npersat=15, lightness=60):
"""Returns an rgb color triplet for a given index, with a finite max 'num'.
Thus if you need 10 colors and want to get color #5, you would call this with (5, 10).
The colors are "repeatable".
"""
import math
from PIL import ImageColor
nsats... | 8,943 |
def make_customer_satisfaction(branch_index='A'):
"""Create average customer satisfaction heat map"""
customer_satisfaction = make_heat_map(branch_index, 'mean(Rating)', 'Average Satisfaction')
return customer_satisfaction | 8,944 |
def extract_infos(fpath):
"""Extract information about file"""
try:
pe = pefile.PE(fpath)
except pefile.PEFormatError:
return {}
res = {}
res['Machine'] = pe.FILE_HEADER.Machine
res['SizeOfOptionalHeader'] = pe.FILE_HEADER.SizeOfOptionalHeader
res['Characteristics'] = pe.FIL... | 8,945 |
def calibrate_eye_in_hand(calibration_inputs):
"""Perform eye-in-hand calibration.
Args:
calibration_inputs: List of HandEyeInput
Returns:
A HandEyeOutput instance containing the eye-in-hand transform
"""
return HandEyeOutput(
_zivid.calibration.calibrate_eye_in_hand(
... | 8,946 |
def get_intersect(A: np.ndarray, B: np.ndarray, C: np.ndarray, D: np.ndarray) -> Optional[np.ndarray]:
"""
Get the intersection of [A, B] and [C, D]. Return False if segment don't cross.
:param A: Point of the first segment
:param B: Point of the first segment
:param C: Point of the second segment
... | 8,947 |
def _make_vector_laplace_scipy_nd(bcs: Boundaries) -> Callable:
""" make a vector Laplacian using the scipy module
This only supports uniform discretizations.
Args:
bcs (:class:`~pde.grids.boundaries.axes.Boundaries`):
|Arg_boundary_conditions|
Returns:
A f... | 8,948 |
def dot_to_dict(values):
"""Convert dot notation to a dict. For example: ["token.pos", "token._.xyz"]
become {"token": {"pos": True, "_": {"xyz": True }}}.
values (iterable): The values to convert.
RETURNS (dict): The converted values.
"""
result = {}
for value in values:
path = res... | 8,949 |
def _draw_edges(G, pos, nodes, ax):
"""Draw the edges of a (small) networkx graph.
Params:
G (nx.classes.*) a networkx graph.
pos (dict) returned by nx.layout methods.
nodes (dict) of Circle patches.
ax (AxesSubplot) mpl axe.
Return:
... | 8,950 |
def benjamini_hochberg_stepup(p_vals):
"""
Given a list of p-values, apply FDR correction and return the q values.
"""
# sort the p_values, but keep the index listed
index = [i[0] for i in sorted(enumerate(p_vals), key=lambda x:x[1])]
# keep the p_values sorted
p_vals = sorted(p_vals)
q... | 8,951 |
def test_3():
"""
Test PCE coefficients w/ lasso
"""
polynomial_basis = TensorProductBasis(dist, max_degree)
lasso = LassoRegression()
pce = PolynomialChaosExpansion(polynomial_basis=polynomial_basis, regression_method=lasso)
pce.fit(x, y)
assert round(pce.coefficients[0][0], 4) == 0.000... | 8,952 |
def remove_transcription_site(rna, foci, nuc_mask, ndim):
"""Distinguish RNA molecules detected in a transcription site from the
rest.
A transcription site is defined as as a foci detected within the nucleus.
Parameters
----------
rna : np.ndarray, np.int64
Coordinates of the detected ... | 8,953 |
def make_div_interp(dirname, profs, pout, gui=False):
"""Interpolate each of the given profiles to the corresponding new levels
in list p and write out."""
make_dirs(dirname, profs['nprof'], gui)
for p in range(profs['nprof']):
if gui:
proffn = dirname + '/{:03d}.py'.format(p + ... | 8,954 |
def hexagonal_numbers(length: int) -> list[int]:
"""
:param len: max number of elements
:type len: int
:return: Hexagonal numbers as a list
Tests:
>>> hexagonal_numbers(10)
[0, 1, 6, 15, 28, 45, 66, 91, 120, 153]
>>> hexagonal_numbers(5)
[0, 1, 6, 15, 28]
>>> hexagona... | 8,955 |
def _meta_model_test():
"""
1. input: [b, c, h, w]
2. get weight and bias like `maml`
3. return : [batch_size, num_classes]
"""
import torch
input = torch.rand(32, 3, 84, 84)
model = MetaConvModel(3, 5, hidden_size=64, feature_size=5 * 5 * 64, embedding=True)
out = model(input)
... | 8,956 |
def get_free_remote_port(node: Node) -> int:
"""Returns a free remote port.
Uses a Python snippet to determine a free port by binding a socket
to port 0 and immediately releasing it.
:param node: Node to find a port on.
"""
output = node.run("python -c 'import socket; s=socket.soc... | 8,957 |
def read_conll_data(data_file_path: str) -> Tuple[List[Sentence], List[DependencyTree]]:
"""
Reads Sentences and Trees from a CONLL formatted data file.
Parameters
----------
data_file_path : ``str``
Path to data to be read.
"""
sentences: List[Sentence] = []
trees: List[Depende... | 8,958 |
def get_algo_meta(name: AlgoMeta) -> Optional[AlgoMeta]:
"""
Get meta information of a built-in or registered algorithm.
Return None if not found.
"""
for algo in get_all_algo_meta():
if algo.name == name:
return algo
return None | 8,959 |
def do_eval(sess,input_ids,input_mask,segment_ids,label_ids,is_training,loss,probabilities,vaildX, vaildY, num_labels,batch_size,cls_id):
"""
evalution on model using validation data
"""
num_eval=1000
vaildX = vaildX[0:num_eval]
vaildY = vaildY[0:num_eval]
number_examples = len(vaildX)
e... | 8,960 |
def read_gbt_target(sdfitsfile, objectname, verbose=False):
"""
Give an object name, get all observations of that object as an 'obsblock'
"""
bintable = _get_bintable(sdfitsfile)
whobject = bintable.data['OBJECT'] == objectname
if verbose:
print("Number of individual scans for Object %... | 8,961 |
def regression_target(label_name=None,
weight_column_name=None,
target_dimension=1):
"""Creates a _TargetColumn for linear regression.
Args:
label_name: String, name of the key in label dict. Can be null if label
is a tensor (single headed models).
weight... | 8,962 |
def write_bin(f, pixel_list, width):
"""Save image in MONO_HMSB format."""
index = 0
list_bytes = []
image_byte = 0
windex = 0
for pix in pixel_list:
image_byte = set_bit(image_byte, index, pix > 0)
index += 1
windex += 1
if index > 7 or windex >= width:
... | 8,963 |
def rdoublegauss(mu1, mu2, sigma1, sigma2, ratio, size=None):
"""random variable from double gaussian"""
r1 = ratio / (1. + ratio)
r2 = 1 - r1
R = np.asarray(np.random.random(size))
Rshape = R.shape
R = np.atleast1d(R)
mask1 = (R < r1)
mask2 = ~mask1
N1 = mask1.sum()
N2 = R.siz... | 8,964 |
def check_add_role(store, id, name):
""" Checks if role exist and then adds record if it doesn't """
role = store.find_role(name)
if role == None:
return store.create_role(id=id, name=name)
else:
return role | 8,965 |
def report_map():
"""
update DB with new version of a container instance's id map
:return: str. 'true' if successful
"""
if not request.json:
logger.error('received non-json data')
abort(400)
logger.info('Received map update from {}'.format(request.remote_addr))
logger.debug(... | 8,966 |
def delta_path(base_path: Path, item_path: Path, new_base_path: Path) -> Path:
"""
Removes a base path from an item, and appends result to a new path
:param base_path: The :py:class:`pathlib.Path` to be removed from `item_path`
:param item_path: The :py:class:`pathlib.Path` to be delta-ed
:param ne... | 8,967 |
async def async_validate_config(hass, config):
"""Validate config."""
automations = list(
filter(
lambda x: x is not None,
await asyncio.gather(
*(
_try_async_validate_config_item(hass, p_config, config)
for _, p_config in c... | 8,968 |
def vm_sanity_check():
"""
Handles periodic VM sanity check
Invoked when scheduler runs task of type 'vm_sanity'
"""
logger.info("ENTERNING VM SANITY CHECK........")
try:
check_vm_sanity()
except:
log_exception()
pass
finally:
logger.debug("EXITING VM SANI... | 8,969 |
def judge_result(problem_id, commit_id, data_num):
"""对输出数据进行评测"""
logging.debug("Judging result")
correct_result = os.path.join(
data_dir, str(problem_id), 'data%s.out' %
data_num)
user_result = os.path.join(
work_dir, str(commit_id), 'out%s.txt' %
data_num)
try:
... | 8,970 |
def _fwd6(y, dt): # pragma: no cover
"""Compute the first derivative of a uniformly-spaced-in-time array with a
sixth-order forward difference scheme.
Parameters
----------
y : (7,...) ndarray
Data to differentiate. The derivative is taken along the... | 8,971 |
def minimize_newton_cg(nrgs, x0, num_params):
"""
Minimzes a structure using a Newton-CG method. This requires a
hopefully fully invertible analytic Hessian that will be used
to minimize geometries.
Parameters
----------
nrgs: [list of functionals]
Energy functions used to compute t... | 8,972 |
def currency(price, currency):
"""
Returns price in currency format
"""
price = float(price)
price *= float(currency.exchange_rate)
try:
return currency.display_format.format(price)
except Exception as e:
raise ImproperlyConfigured('Invalid currency format string: "%s" for cu... | 8,973 |
def project_point(x, R, T, f, c, k, p):
"""
Args
x: Nx3 points in world coordinates
R: 3x3 Camera rotation matrix
T: 3x1 Camera translation parameters
f: 2x1 Camera focal length
c: 2x1 Camera center
k: 3x1 Camera radial distortion coefficients
p: 2x1 Camer... | 8,974 |
def sum_to_scalar(*args):
"""Adding losses/nmsks together that were evaluated in parallel"""
new_args = list()
for arg in args:
new_args.append({k: v.sum() for (k, v) in arg.items()})
return new_args | 8,975 |
def overlay_test():
"""Demonstrates color fading in current overlay technique (mean).
Suggestion: use addition instead of averaging colors.
Update: Average wasn't the problem- no difference in fact due to
normalization. Will revert to that method.
Suggeston: Maybe a different color space?"""
... | 8,976 |
def test_valid_certificate_200(client):
"""Test that a request for a valid certificate with signatories results in a 200"""
certificate = MicromastersCourseCertificateFactory.create()
signatory = CourseCertificateSignatoriesFactory.create(course=certificate.course)
resp = client.get(certificate_url(cert... | 8,977 |
def inv(h_array: np.ndarray) -> np.ndarray:
"""
Calculate pinvh of PSD array. Note pinvh performs poorly
if input matrix is far from being Hermitian, so use pinv2
instead in this case.
Parameters:
----------
h_array : input matrix, assume to be Hermitian
Returns:
----------
... | 8,978 |
def update_risk_cavs(connection):
"""Parse cavs from html to markdown.
Args:
connection: SQLAlchemy connection.
Returns:
ids of risks for which cavs where updated.
"""
cavs_data = connection.execute(
sa.text("""
SELECT cav.id, cav.attribute_value, cav.attributable_id
... | 8,979 |
def prefix_to_number(prefix):
"""Return the number of the prefix."""
if prefix in PREFIXES:
return PREFIXES[prefix]
raise ValueError(f'prefix "{prefix}" not found in list of prefixes') | 8,980 |
def package():
"""
Do nothing -- this group should never be called without a sub-command.
"""
pass | 8,981 |
def is_response_going_to_be_used(request, spider):
"""Check whether the request's response is going to be used."""
callback = get_callback(request, spider)
if is_callback_using_response(callback):
return True
for provider in discover_callback_providers(callback):
if is_provider_using_re... | 8,982 |
def eval_market1501(distmat, q_vids, g_vids, q_camids, g_camids, max_rank=50):
"""Evaluation with Market1501 metrics
Key: for each query identity, its gallery images from the same camera view are discarded.
"""
num_q, num_g = distmat.shape
if num_g < max_rank:
max_rank = num_g
print(... | 8,983 |
def get_band_structure_from_vasp_multiple_branches(dir_name, efermi=None,
projections=False):
"""
This method is used to get band structure info from a VASP directory. It
takes into account that the run can be divided in several branches named
"branch_x... | 8,984 |
def pytype_raise():
"""A pytest.raises wrapper for catching TypeErrors.
Parameters
----------
match : str, default=None
Regular expression to match exception error text against.
Returns
-------
RaisesContext
pytest context manager for catching exception-raising blocks.
... | 8,985 |
def delete_dir(dir_path, recursive=False):
"""
删除目录
:param dir_path:
:param recursive:
:return:
"""
if os.path.exists(dir_path):
if recursive:
fps = get_sub_files(dir_path)
for sub_dir in fps:
if os.path.isdir(sub_dir):
dele... | 8,986 |
def test_block_average_save():
"""Test the save of a file."""
block = exma.electrochemistry.statistics.BlockAverage(
[3.14, 3.15, 3.13, 3.13, 3.15, 3.15, 3.16, 3.12]
)
block.calculate()
block.save()
with open("block_average.csv", "r") as fin:
readed = fin.read()
os.remove("b... | 8,987 |
def test_batch_08():
"""
Test batch: num_parallel_workers=1, drop_remainder default
"""
logger.info("test_batch_08")
# define parameters
batch_size = 6
num_parallel_workers = 1
# apply dataset operations
data1 = ds.TFRecordDataset(DATA_DIR, shuffle=ds.Shuffle.FILES)
data1 = data... | 8,988 |
def lift_split_buffers(lines):
"""Lift the split buffers in the program
For each module, if we find any split buffers with the name "buf_data_split",
we will lift them out of the for loops and put them in the variable declaration
section at the beginning of the module.
Parameters
----------
... | 8,989 |
def peak_finder(
df_run,
cd,
windowlength,
polyorder,
datatype,
lenmax,
peak_thresh):
"""Determines the index of each peak in a dQdV curve
V_series = Pandas series of voltage data
dQdV_series = Pandas series of differential capacity data
cd = eithe... | 8,990 |
def model_output_pipeline(model_outputs=True, visualize_anchors=False,
visualize_anchor_gt_pair=False, verbose=False, very_verbose=False):
"""
model_outputs - flag to enable plotting model outputs
visualize_anchors - flag to visualize anchors
visualize_anchor_gt_pair - flag to ... | 8,991 |
def make_box(world, x_dim, y_dim, z_dim, mass=0.5):
"""Makes a new axis-aligned box centered at the origin with
dimensions width x depth x height. The box is a RigidObject
with automatically determined inertia.
"""
boxgeom = Geometry3D()
boxgeom.loadFile("data/objects/cube.tri")
# box i... | 8,992 |
def as_file(uri):
"""
If the URI is a file (either the ``file`` scheme or no scheme), then returns the normalized
path. Otherwise, returns ``None``.
"""
if _IS_WINDOWS:
# We need this extra check in Windows before urlparse because paths might have a drive
# prefix, e.g. "C:" which w... | 8,993 |
def add_full_name(obj):
"""
A decorator to add __full_name__ to the function being decorated.
This should be done for all decorators used in pywikibot, as any
decorator that does not add __full_name__ will prevent other
decorators in the same chain from being able to obtain it.
This can be use... | 8,994 |
def LikelihoodRedshiftMeasure( measure='', data=[], scenario=False, measureable=False):
"""
returns likelihood functions of redshift for observed data of measure,
can be used to obtain estimate and deviation
Parameters
----------
measure : string
indicate which measure is probed
d... | 8,995 |
def plural_suffix(count: int) -> str:
""""s" when count is not one"""
suffix = ''
if count != 1:
suffix = 's'
return suffix | 8,996 |
def _pr_exists(user, namespace, repo, idx):
""" Utility method checking if a given PR exists. """
repo_obj = pagure.lib.query.get_authorized_project(
flask.g.session, project_name=repo, user=user, namespace=namespace
)
if not repo_obj:
return False
pr_obj = pagure.lib.query.search_... | 8,997 |
def readData(filename):
"""
Read in our data from a CSV file and create a dictionary of records,
where the key is a unique record ID and each value is dict
"""
data_d = {}
with open(filename) as f:
reader = csv.DictReader(f)
for row in reader:
clean_row = ... | 8,998 |
def write_last_activity_index(settings_dir, activity_index, format):
"""
Persists the index of the last exported activity for the given export format
(see also method read_settings())
:param settings_dir: Path to the pickle file
:param activity_index: Positive integer
:param format: Value of arg... | 8,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.