content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
import logging
def dataframe2naf(
df_meta: pd.DataFrame,
overwrite_existing_naf: bool=False,
rerun_files_with_naf_errors: bool=False,
engine: str=None,
naf_version: str=None,
dtd_validation: bool=False,
params: dict={},
nlp=None,
) -> pd.DataFrame:
"""Batch processor for ... | 6bc26b849a456421457868bdd83fd2362ca1e757 | 18,900 |
import json
import re
from datetime import datetime
import random
def dev_view(request, slug=""):
"""View for homepage or individual developer."""
if slug == "":
dev_name = list(Dev.objects.all().values_list('dev_name', flat=True))
dev_img_address = list(Dev.objects.values_list('dev_image_add... | 363819f854e26b8c62f8fe41fbfbf2e64296246f | 18,901 |
def dpuEnableTaskProfile(task):
"""
Enable profiling facility of DPU Task while running to get its performance metrics
task: DPU Task. This parameter should be gotten from the result of dpuCreatTask()
Returns: 0 on success, or report error in case of any failure
"""
return pyc_libn2cube.pyc_... | 5bb1435ca194b214695891d451f2f56a4cdf6857 | 18,902 |
def get_isotopic_distribution(z):
"""
For an element with number ``z``, returns two ``np.ndarray`` objects containing that element's weights and relative abundances.
Args:
z (int): atomic number
Returns:
masses (np.ndarray): list of isotope masses
weights (np.ndarray): list of ... | 4b038319c37dfd13f0ef085c2b3286f6fc2749c3 | 18,903 |
def url_root():
"""根路径"""
return """
<p>Hello ! Welcome to Rabbit's WebServer Platform !</p>
<a href="http://www.miibeian.gov.cn/" target="_blank" style="">京ICP备 18018365 号</a> @2018Rabbit
""" | 2e6d1d5301ac67bdec30cdeeaeed3c8638568de9 | 18,904 |
import uuid
def CreateMatrix(args, context, history_id, gcs_results_root, release_track):
"""Creates a new iOS matrix test in Firebase Test Lab from the user's params.
Args:
args: an argparse namespace. All the arguments that were provided to this
gcloud command invocation (i.e. group and command argum... | e536001e768f2574d6c5d773b70e6b4e58c6c3da | 18,905 |
import os
import requests
from pathlib import Path
def _download_and_extract_zip_from_github(site_info):
"""
from https://pelican-blog/archive/master.zip
to: /path/pelican-blog
"""
unique_id = uuid4().hex
zip_file_url = site_info["ZIP_URL"]
zip_file_name = os.path.join(
settings.P... | 2a6e90434d8cfd1cd1e2084ff3ef575d725f87e4 | 18,906 |
def map_keys(func, d):
""" Returns a new dict with func applied to keys from d, while values
remain unchanged.
>>> D = {'a': 1, 'b': 2}
>>> map_keys(lambda k: k.upper(), D)
{'A': 1, 'B': 2}
>>> assert map_keys(identity, D) == D
>>> map_keys(identity, {})
{}
"""
return dict(... | 5e9798d208db5e43dad497d64a4b8e469c67eb3b | 18,907 |
from qiniu import Auth
def generate_qiniu_token(object_name, use_type, expire_time=600):
"""
用于生成七牛云上传所需要的Token
:param object_name: 上传到七牛后保存的文件名
:param use_type: 操作类型
:param expire_time: token过期时间,默认为600秒,即十分钟
:return:
"""
bucket_name = PRIVATE_QINIU_BUCKET_NAME
# 需要填写你的 Access Ke... | 9d0b65fb08032ad557f50cb73c00b4ed0f8eae5a | 18,908 |
def get_s3_object(bucket, key_name, local_file):
"""Download a S3 object to a local file in the execution environment
Parameters
----------
bucket: string, required
S3 bucket that holds the message
key: string, required
S3 key is the email object
Returns
-------
... | 02b10623e30eff1ee5093d4e0f1ee51b3b97d0ac | 18,909 |
def jaxpr_eqns_input_sizes(jaxpr) -> np.ndarray:
"""Return a list of input sizes for each equation in the jaxpr.
Args:
jaxpr: Jaxpr to get input sizes for.
Returns:
A #eqns * #eqns numpy array of input sizes. cost[l, r] represents the
input size of the l-th to (r - 1)-th equation i... | 0209c0342725ae83ea8051ef47852134e6ad4502 | 18,910 |
def extract_message(raw_html):
"""Returns the content of the message element.
This element appears typically on pages with errors.
:param raw_html: Dump from any page.
"""
results = re_message.findall(raw_html)
if results:
return results[0]
return None | 498ee1c38c08db365b1bf91ecd32a79c2d2f5f68 | 18,911 |
from typing import Callable
from typing import Tuple
def _weighted_essentially_non_oscillatory_vectorized(
eno_order: int, values: Array, spacing: float, boundary_condition: Callable[[Array, int],
Array]) -> Tuple[Array, Array... | debd652ddf02419e191d9d0c5d21640760d3f227 | 18,912 |
def defaults(dictionary, overwriteNone=False, **kwargs):
"""
Set default values of a given dictionary, option to overwrite None values.
Returns given dictionary with values updated by kwargs unless they already existed.
:param dict dictionary:
:param overwriteNone: Whether to overwrite None values.... | 6def5bb71839b3b627a5597ea6fa7fa1b48e463b | 18,913 |
from typing import Union
from typing import Optional
from typing import Dict
import tqdm
def expected_average_shortest_distance_to_miner(
crawl_graph: Union[
ProbabilisticWeightedCrawlGraph[CrawledNode], CrawlGraph[CrawledNode]
],
distances: Optional[np.ndarray] = None,
miner_probability: Opti... | 6ea56881dce6d589eebec6422a0a5ffae41fe153 | 18,914 |
from typing import Callable
def dummy_state_sb(dummy_state: State, dummy_train_dataloader: DataLoader, conv_model: MosaicClassifier,
loss_fun_tuple: Callable, epoch: int, batch: int) -> State:
"""Dummy state with required values set for Selective Backprop
"""
dummy_state.train_dataload... | 4f4af7193ccf0a4fb883a7d4b42ef58da49333b3 | 18,915 |
def create_model(species={}, parameters={}, reactions={}, events={}):
"""Returns an SBML Level 3 model.
Example:
species = { 'E': 1, \
'EM': 0, \
'EM2': 0, \
'F': 100, \
}
parameters = {'k': (1e-06,'per_min'), \
}
r... | 1950509f83b858ef7829aa6f30caaa3734ff2946 | 18,916 |
def get_network_connection_query(endpoint_ids: str, args: dict) -> str:
"""Create the network connection query.
Args:
endpoint_ids (str): The endpoint IDs to use.
args (dict): The arguments to pass to the query.
Returns:
str: The created query.
"""
remote_ip_list = args.get... | 6390c6ae4436632055fb90687e51cfac2ca09a05 | 18,917 |
import json
def dump_into_json(filename, metrics):
"""Dump the metrics dictionary into a JSON file
It will automatically dump the dictionary:
metrics = {'duration': duration,
'voltage_extremes': voltage_extremes,
'num_beats': num_beats,
'mean_hr_bpm': mean_hr_... | 2e6effbcefe7cb3033c4c472cbee3850c00ae06b | 18,918 |
def _costfun(params, pose0, fixed_pt3d, n_cams, n_pts, cam_idxs, pt3d_idxs, pts2d, K, px_err_sd):
"""
Compute residuals.
`params` contains camera parameters and 3-D coordinates.
"""
if isinstance(params, (tuple, list)):
params = np.array(params)
params = np.hstack((pose0, params))
p... | 3e97e7d14712fe8b89b60de958fd743c728e8cba | 18,919 |
def dbg_get_memory_info(*args):
"""
dbg_get_memory_info() -> PyObject *
This function returns the memory configuration of a debugged process.
@return:
None if no debugger is active
tuple(start_ea, end_ea, name, sclass, sbase, bitness, perm)
"""
return _ida_idd.dbg_get_memory_info(*args) | f79234d724f33eb8311aff8b6b04ddb9325953c0 | 18,920 |
import base64
import requests
def get_headers(base_url: str, client_id: str, client_secret: str, grant_type: str, verify: bool):
"""
Create header with OAuth 2.0 authentication information.
:type base_url: ``str``
:param base_url: Base URL of the IdentityIQ tenant.
:type client_id: ``str``
:... | 06ced982595d4abe99e193ec7ab43e366d575f7b | 18,921 |
import logging
from datetime import datetime
def draw_pie(fracs, labels):
"""
This method is to plot the pie chart of labels, then save it into '/tmp/' folder
"""
logging.info("Drawing the pie chart..")
fig = plt.figure()
plt.pie(fracs, labels=labels, autopct=make_autopct(fracs), shadow=True)
... | 18ee8d0b6054467b9612e282c0d12fa9a10c549b | 18,922 |
import re
def eval_function_old(param, param_type):
""" Eval Function (Deprecated)
isOwner 0xe982E462b094850F12AF94d21D470e21bE9D0E9C
:param param:
:param param_type:
:return:
"""
try:
splitted_input = param.split(' ')
except TypeError:
pass
else:
try:
... | 6c28fdad6803330bcea8b086cc2e15209125a8d6 | 18,923 |
def _multi_convert(value):
"""
Function try and convert numerical values to numerical types.
"""
try:
value = int(value, 10)
except ValueError:
try:
value = float(value)
except ValueError:
pass
return value | abcd3656fdf5ce7ab1427ee6884a18853bdfaf59 | 18,924 |
def dbinom(n, p):
"""Binomial Distribution
n = number of repetitions
p = success probability
Used when a certain experiment is repeated n times
with a 0 ≤ P ≤ 1 probability to succeed once.
This doesn't return a value, but rather the specified binomial function
"""
def b(k):
"""Retu... | 8917b3eb5ce189094f2b129c596a99d20dfcdcc5 | 18,925 |
def array_to_image(x, data_format='channels_last'):
"""Converts a 3D Numpy array to a PIL Image instance.
Args:
x: Input Numpy array.
data_format: Image data format, either "channels_first" or "channels_last".
Returns:
A PIL Image instance.
Raises:
ValueError: if inv... | 2278a317e6d820b9d1aee2d7d796261b14d719f2 | 18,926 |
import time
import logging
import re
def worker_process_download_tvtorrent(
tvTorUnit, client = None, maxtime_in_secs = 14400,
num_iters = 1, kill_if_fail = False ):
"""
Used by, e.g., :ref:`get_tv_batch`, to download missing episodes on the Plex_ TV library. Attempts to use the Deluge_ serve... | 899b13f70d1673168eab4b533ce7e5219d25d365 | 18,927 |
from operator import or_
def find_fixture(
gameweek,
team,
was_home=None,
other_team=None,
kickoff_time=None,
season=CURRENT_SEASON,
dbsession=session,
):
"""Get a fixture given a gameweek, team and optionally whether
the team was at home or away, the kickoff time and the other tea... | fcf90acd4fd8dd663c5cdf2ec99bd428c8cf7a45 | 18,928 |
import errno
def plat_specific_errors(*errnames):
"""Return error numbers for all errors in errnames on this platform.
The 'errno' module contains different global constants depending on
the specific platform (OS). This function will return the list of
numeric values for a given list of potential nam... | acb70b2b7d6b16fbe2cfc9f559606efd504b8e3f | 18,929 |
def fft(array, nfft=None, dim=None, dx=None, detrend=None, tapering=False,
shift=True, sym=False, chunks=None):
"""Compute the spectrum on several dimensions of xarray.DataArray objects
using the Fast Fourrier Transform parrallelized with dask.
Parameters
----------
array : xarray.DataArray
Array from w... | dd672487df9f4988c53706a2886f499e56a5ff4c | 18,930 |
from pymatgen.util.num import make_symmetric_matrix_from_upper_tri
from typing import Union
def make_symmetric_matrix(d: Union[list, float]) -> list:
"""
d (list or float):
len(d) == 1: Suppose cubic system
len(d) == 3: Suppose tetragonal or orthorhombic system
len(d) == 6: Suppose the... | 318caf380a8f0a0878eac54bae49c86722e532bb | 18,931 |
def convert_lds_to_block_tridiag(As, bs, Qi_sqrts, ms, Ri_sqrts):
"""
Parameterize the LDS in terms of pairwise linear Gaussian dynamics
and per-timestep Gaussian observations.
p(x_{1:T}; theta)
= [prod_{t=1}^{T-1} N(x_{t+1} | A_t x_t + b_t, Q_t)]
* [prod_{t=1}^T N(x_t |... | d16721ffb77f06cd55ca3c70238ca56fad76970d | 18,932 |
def extract_string_from_tensor(input_ids, mode="single", config=None, tokenizer=None):
"""
Args:
input_ids (Tensor): input sentences with shape [batch_size, seq_len].
mode (str): ["pair", "single"]
"pair" for tasks with paired inputs `<bos> A <eos> B <eos>`,
... | 27cf8905350db53ec908f3b8ef8674a7ac3a17eb | 18,933 |
def schema_validation_matching(source_fields, target_fields):
"""Compare schemas between two dictionary objects"""
results = []
# Go through each source and check if target exists and matches
for source_field_name, source_field_type in source_fields.items():
# target field exists
if sour... | 7af82c39462de09e326c6f4413a2d6be7fd6c977 | 18,934 |
import pkg_resources
def find_thirdparty_marshaller_plugins():
""" Find, but don't load, all third party marshaller plugins.
Third party marshaller plugins declare the entry point
``'hdf5storage.marshallers.plugins'`` with the name being the
Marshaller API version and the target being a function that... | 7aad132f520b67d5b39e857175e4bc006fd3ad72 | 18,935 |
def justTransportResponse(transport):
"""
Helper function for creating a Response which uses the given transport.
All of the other parameters to L{Response.__init__} are filled with
arbitrary values. Only use this method if you don't care about any of
them.
"""
return Response((b'HTTP', 1, ... | 02a18a500cb9a623c287d4e2f3777237e3574ef6 | 18,936 |
import os
def get_tools_location() -> str:
"""Get the path to the Alteryx Python SDK Tools directory."""
admin_path = os.path.join(os.environ["APPDATA"], "Alteryx", "Tools")
user_path = os.path.join(os.environ["PROGRAMDATA"], "Alteryx", "Tools")
if contains_path(__file__, admin_path):
return a... | 4ceedb06eac222939384ef5dff34f10652b37525 | 18,937 |
def object_comparator_lookup(src_obj, dst_obj):
"""
Compare an object with another entry by entry
"""
dont_match = []
no_upstream = []
for i in dst_obj:
count_name = 0
count_value = 0
for j in src_obj:
if list(j.keys())[0] == list(i.keys())[0]:
... | ba5767624255da915d9c07d25b62880c387f6f00 | 18,938 |
def line(
data_frame=None,
x=None,
y=None,
line_group=None,
color=None,
line_dash=None,
hover_name=None,
hover_data=None,
custom_data=None,
text=None,
facet_row=None,
facet_row_weights=None,
facet_col=None,
facet_col_weights=None,
facet_col_wrap=0,
facet_r... | bcedfe2c9297f4d3c049e500265f9ffbc0dde85a | 18,939 |
def is_primitive(v):
"""
Checks if v is of primitive type.
"""
return isinstance(v, (int, float, bool, str)) | d22607c0e2b93b82b1da6beb50de68668624dd71 | 18,940 |
def linkify_only_full_urls(attrs, new=False):
"""Linkify only full links, containing the scheme."""
if not new: # This is an existing <a> tag, leave it be.
return attrs
# If the original text doesn't contain the scheme, don't linkify.
if not attrs['_text'].startswith(('http:', 'https:')):
... | 89fcc7f3fc53353686260779ae8ddb4c0523c57b | 18,941 |
import os
def retrieve_model_list(opt):
"""
retrive the model information from form a directory.
:param opt: parser
:return: list of Checkpoint object.
"""
files = os.listdir(os.path.join(opt.dir, 'models'))
files.sort()
# file name format "address/$NAME_acc_XX.YY_ppl_XX.YY_eZZ.pt"
... | 0b1bcd662d0ca8ec62def67e8e3fe0fff7825de4 | 18,942 |
import os
def _read_filenames_in_dir(path, extension):
"""Returns the name of the Yaml files in a certain directory
Arguments
---------
path: str
Path to directory
extension: str
Extension of files (such as: '.yml' or '.csv')
Returns
-------
list
The list of f... | 6f16cd0f39d7df93fbbf8ede7236e373f1d905df | 18,943 |
import argparse
import os
def setup_cccc_tool_plugin(use_plugin_context=True, binary=None, cccc_config=None):
"""Create an instance of the CCCC plugin."""
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--cccc-bin", dest="cccc_bin")
arg_parser.add_argument("--cccc-config", dest="cccc_c... | 5b3b3e54f01967004a0ecfa938c1a7bec581ce11 | 18,944 |
def Precedence(op):
"""The numeric precedence of a binary operator."""
# Particularly convenient during layout of binary operators.
return float(sum(i * (op in grp[1:])
for i, grp in enumerate(precedence))) / len(precedence) | 0071d2972474c57376c334401c43673f1c4bde49 | 18,945 |
from typing import Dict
from typing import Any
def _FeastToExampleTransform(
pipeline: beam.Pipeline, exec_properties: Dict[str, Any], split_pattern: str
) -> beam.pvalue.PCollection:
"""Read from BigQuery and transform to TF examples.
Args:
pipeline: beam pipeline.
exec_properties: A dict of... | 76451a98b9e11188eda42b5141e73647b87df94b | 18,946 |
import os
def fluxional_mode(atom_indices, span=360.0):
""" Writes the string for each fluxional mode
"""
# Format the aotm indices string
atom_indices = util.format_flux_mode_indices(atom_indices)
# Create dictionary to fill template
flux_mode_keys = {
'atom_indices': atom_indices,
... | 489f1f82e8eaf535ae446b41e2e7307ab97f7cd8 | 18,947 |
import re
import logging
def parse_host_info(qhost_tree, queues_tree, queues_to_ignore=[]):
"""
:return: dictionary key: host, value HostInfo
"""
dctRet = {}
for host_node in qhost_tree.findall('host'):
host_name = host_node.get('name')
dct_hostvalues = dict([(hostvalue_node.get('n... | a5f5154ac50d358b4a523872ffcaba3030d2f722 | 18,948 |
import click
def _get_param_type_from_str(
type_name: str = None,
param_doc: docstring_parser.DocstringParam = None,
) -> t.Tuple[_ParamArgs, t.Union[click.ParamType, None]]:
"""Guess parameter type from parameter type name."""
type_name = type_name or ""
desc = param_doc.description if pa... | a13621ffbed428fbc32f6285e2fc0a2b53097cad | 18,949 |
def solve(task: str) -> int:
"""How many differently colored bags can contain shiny gold?"""
parents = process_data(task)
seen = set()
candidates = parents["shiny gold"]
while candidates:
candidate = candidates.pop()
if candidate not in seen:
seen.add(candidate)
... | ea505c346a4482b9516ad22baa71d251b7e1dc41 | 18,950 |
import urllib
import base64
import hashlib
import requests
def cityDesc(codePostal):
"""
code de retour :
100 : tout est normal
200 : la requete n'a pas abouti
300 : pas de cine dans la ville
400 : la ville n'existe pas
"""
headersUA = init_connect()
YMDstr = getDate()
searchField = codePostal
... | 06da49d9afe5420869204a423a2db31df11cc58e | 18,951 |
async def get_reposet(request: AthenianWebRequest, id: int) -> web.Response:
"""List a repository set.
:param id: Numeric identifier of the repository set to list.
:type id: repository set ID.
"""
rs_cols = [
RepositorySet.name,
RepositorySet.items,
RepositorySet.precomputed... | a3a2cf6cb1152aadb81798cfa3e1be214635edad | 18,952 |
from xgboost_ray.elastic import _maybe_schedule_new_actors, \
def _train(params: Dict,
dtrain: RayDMatrix,
model_factory: Type[LGBMModel],
boost_rounds_left: int,
*args,
evals=(),
ray_params: RayParams,
cpus_per_actor: int,
gpus_p... | f52508ffb67e4e29dde7300099e616973c7d6740 | 18,953 |
def is_called_at_module_level() -> bool:
"""
Check if the current function is being called at the module level.
Raise `RuntimeError` if `is_called_at_module_level()` is not called in a function.
"""
if not (frame := getcallerframe().f_back):
raise RuntimeError(
"is_called_at_mo... | 0c807205472021b20c7b7bad27c8b5f7a634dd85 | 18,954 |
def extract_dominant_keypoints2D(keypoint_2D, dominant_hand):
""" Extract keypoint 2D.
# Look Later with Octavio
# Arguments
keypoint_2D: Numpy array of shape (num_keypoints, 1).
dominant_hand: List of size (2) with booleans.
# Returns
keypoint_visibility_2D_21: Numpy array of s... | 2581b4cb68d6dad2da3933259582f9160224eef9 | 18,955 |
def translation_ev(h, t, tol=1e6):
"""Compute the eigenvalues of the translation operator of a lead.
Adapted from kwant.physics.leads.modes.
Parameters
----------
h : numpy array, real or complex, shape (N, N) The unit cell
Hamiltonian of the lead unit cell.
t : numpy array, real or co... | b5534b782b487ca195ab9b78438e68e81a62e74a | 18,956 |
def bsearch(n, pred):
"""
Given a boolean function pred that takes index arguments in [0, n).
Assume the boolean function pred returns all False and then all True for
values. Return the index of the first True, or n if that does not exist.
"""
# invariant: last False lies in [l, r) and pred(l) i... | 9274732aa9e24a0d0f73399ff50c19a544ac06a7 | 18,957 |
def test_rotating_file_handler_interval(tmpdir, logger, monkeypatch):
"""Test the rotating file handler when the rollover return a time smaller
than the current time.
"""
def rollover(obj, current_time):
return current_time - 0.1
monkeypatch.setattr(DayRotatingTimeHandler, 'computeRollover... | f6394f215e452fd7875b1fc624db9cb50cc19ed8 | 18,958 |
def compute_zero_crossing_wavelength(period, water_depth, gravity=GRAVITY):
"""Computes zero-crossing wavelength from given period.
This uses the dispersion relation for linear waves.
"""
return wavenumber_to_wavelength(
frequency_to_wavenumber(1. / period, water_depth, gravity)
) | 575ff3d251575fa7a232c120bde15f8f57c1dac9 | 18,959 |
def launch_transport_listener(transport, bindaddr, role, remote_addrport, pt_config, ext_or_cookie_file=None):
"""
Launch a listener for 'transport' in role 'role' (socks/client/server/ext_server).
If 'bindaddr' is set, then listen on bindaddr. Otherwise, listen
on an ephemeral port on localhost.
'... | 98ba849b3adc58b14b8983d0e61a409bc5ce3af7 | 18,960 |
import os
def div(style, render=False, label=''):
"""Render divider."""
if len(style) == 1:
if label == '':
res = hfill('', style)
else:
res = hfill(style * 2 + ' ' + label + ' ', style)
elif style[0] == style[-1]:
# Windows does line wrapping weird
... | 59a1801f749671e9c68613457cd934ca458c7eb6 | 18,961 |
import socket
import zmq
def send_array(A, flags=0, copy=True, track=False):
"""send a numpy array with metadata
Inputs
------
A: (subplots,dim) np array to transmit
subplots - the amount of subplots that are
defined in the current plot
dim - the amount of data that... | c53a17918c12e3ccec9046aad7fc7fc2f498a8ea | 18,962 |
import json
def api_file_upload(request):
""" Upload a file to the storage system """
try:
fobj = request.FILES["file"]
checksum, ext = fobj._name.split(".")
try:
request.user.check_staged_space(fobj._size, checksum)
except Exception as e:
return HttpRes... | 80b15b4d92b5ba2f3a247f1baf7900e73b18781f | 18,963 |
import logging
def calculateAggregateInterferenceForGwpz(gwpz_record, grants):
"""Calculates per-channel aggregate interference for GWPZ.
Args:
gwpz_record: A GWPZ record dict.
grants: An iterable of CBSD grants of type |data.CbsdGrantInfo|.
Returns:
Aggregate interference to GWPZ in the nested di... | d2b7d1b1270e4a6da302e4d13a261a29d51b0a12 | 18,964 |
import pandas
def from_pandas_ephemeral(
engine: Engine,
df: pandas.DataFrame,
convert_objects: bool,
name: str
) -> DataFrame:
"""
Instantiate a new DataFrame based on the content of a Pandas DataFrame. The data will be represented
using a `select * from values()` query, o... | afa06bd4e89a53aa0d420ab401137c10e3b46d89 | 18,965 |
def set_vars(api, file:str, tess_profile:dict):
"""
Reads the user-specific variables from the tess_profile
:param api:
:param file:
:param tess_profile:
:return:
"""
# Set necessary information
api.SetImageFile(file)
# Set Variable
api.SetVariable("save_blob_choices", "T")
... | a7fbe0c5bc584928623e2eadc36240ea3b0f37de | 18,966 |
def qtrfit(numpoints, defcoords, refcoords, nrot):
"""Find the quaternion, q, [and left rotation matrix, u] that minimizes
| qTXq - Y | ^ 2 [|uX - Y| ^ 2]
This is equivalent to maximizing Re (qTXTqY)
The left rotation matrix, u, is obtained from q by
u = qT1q
Parameters
numpoint... | fdfde9deaf0b220bd468031264b029125c071fab | 18,967 |
import struct
def _embedded_bundles_partial_impl(
ctx,
bundle_embedded_bundles,
embeddable_targets,
frameworks,
plugins,
watch_bundles):
"""Implementation for the embedded bundles processing partial."""
_ignore = [ctx]
embeddable_providers = [
x[_Ap... | fe057887528a922ae89fe4c6d8066590d006e415 | 18,968 |
import yaml
def load_instrument(yml):
"""
Instantiate an instrument from YAML spec.
Parameters
----------
yml : str
filename for the instrument configuration in YAML format.
Returns
-------
hexrd.instrument.HEDMInstrument
Instrument instance.
"""
with open(ym... | a882b3b36def975b40124078c907a0f050b67a6f | 18,969 |
from typing import List
def serialize_model(self: models.Model, excludes: List[str] = None) -> dict:
"""
模型序列化,会根据 select_related 和 prefetch_related 关联查询的结果进行序列化,可以在查询时使用 only、defer 来筛选序列化的字段。
它不会自做主张的去查询数据库,只用你查询出来的结果,成功避免了 N+1 查询问题。
# See:
https://aber.sh/articles/A-new-idea-of-serializing-Djan... | 2c9a95b4d0e671492eefc73800d43196b6daa604 | 18,970 |
def isint(x):
"""
For an ``mpf`` *x*, or any type that can be converted
to ``mpf``, determines whether *x* is exactly
integer-valued::
>>> from sympy.mpmath import *
>>> isint(3), isint(mpf(3)), isint(3.2)
(True, True, False)
"""
if isinstance(x, int_types):
retu... | ec4516fa450cfc0e58c9a69d95f0f9b8aff2443c | 18,971 |
def update_header(file):
"""
Create a standard WCS header from the HDF5 header. To do this we clean up the
header data (which is initially stored in individual arrays). We then create
a new header dictionary with the old cleaned header info. Finally, we use
astropy.wcs.WCS to create an updated WCS h... | 1c46139a747acdf69ea6602ea123d20f540de30b | 18,972 |
def get_MD_psat():
""" MD data for saturation densities:
Thermodynamic properties of the 3D Lennard-Jones/spline model
Bjørn Hafskjold and Karl Patrick Travis and Amanda Bailey Hass and
Morten Hammer and Ailo Aasen and Øivind Wilhelmsen
doi: 10.1080/00268976.2019.1664780
"""
T = np.array([0.... | 363107962628ca9796397977f4f41e5b30bcfbc0 | 18,973 |
import logging
def get_reddit_client():
"""Utility to get a Reddit Client"""
reddit_username = redditUsername
reddit_password = redditPassword
reddit_user_agent = redditUserAgent
reddit_client_secret = redditClientSecret
reddit_client_id = redditClientID
logging.info("Logged in as user (%... | fe3a783a3ceb27954c658bf9dc036a067ab103a8 | 18,974 |
import six
def get_member_id():
"""
Retrieve member if for the current process.
:rtype: ``bytes``
"""
proc_info = system_info.get_process_info()
member_id = six.b('%s_%d' % (proc_info['hostname'], proc_info['pid']))
return member_id | 1d1cc24ffa62cc8982a23ea986bdf3cbecca53ac | 18,975 |
def get_table_arn():
"""A method to get the DynamoDB table ARN string.
Returns
-------
dict
A dictionary with AWS ARN string for the table ARN.
"""
resp = dynamodb_client.describe_table(
TableName=table_name
)
return {
"table_arn": resp['Table']['TableArn']
} | ee6648048b1cabdbc04e6c3507cc4e1992f059b2 | 18,976 |
def replace_characters(request):
"""Function to process execute replace_characters function."""
keys = ['text', 'characters', 'replacement']
values = get_data(request, keys)
if not values[0]:
abort(400, 'missing text parameter')
if not values[2]:
values[2] = ''
return _call('r... | 4765d7c3ace0a0069cac34adb04381efc7043355 | 18,977 |
def serialize_to_jsonable(obj):
"""
Serialize any object to a JSONable form
"""
return repr(obj) | c8632b8b475d49b56d47b29afa8b44676b7882a5 | 18,978 |
def compare(optimizers, problems, runs=20, all_kwargs={}):
"""Compare a set of optimizers.
Args:
optimizers: list/Optimizer; Either a list of optimizers to compare,
or a single optimizer to test on each problem.
problems: list/Problem; Either a problem instance or a list of problem ... | c0f2ed52fe5de8b32e54ca6e3dc05be18145b1e8 | 18,979 |
def az_el2norm(az: float, el: float):
"""Return solar angle as normalized vector."""
theta = np.pi/2-el*np.pi/180
phi = az*np.pi/180
norm = np.asarray(
[
np.sin(theta)*np.cos(phi),
np.sin(theta)*np.sin(phi),
np.cos(theta)
])
return norm | 5d6e53b778846281a6d2944a52acc64c4386ade4 | 18,980 |
async def api_get_user(user_id: int, db: Session = Depends(get_db)):
"""
Gets user entity
- **user_id**: the user id
- **db**: current database session object
"""
try:
user = await User.get_by_id(id=user_id, db=db)
return user
except UserNotFoundException as e:
... | 2d89fed33e4fbc81e3461b4791f93772a4814ffe | 18,981 |
import re
def remove_comments(json_like):
"""
Removes C-style comments from *json_like* and returns the result. Example::
>>> test_json = '''\
{
"foo": "bar", // This is a single-line comment
"baz": "blah" /* Multi-line
Comment */
}'''
>>> r... | 32ddf8dd19a8d1029b0d5f221aed05c3883d8ee5 | 18,982 |
def install_editable(projectroot, **kwargs):
"""Install the given project as an "editable" install."""
return run_pip('install', '-e', projectroot, **kwargs) | 70b4f5dc1da26beaae31bb1aeaed4457a0d055a3 | 18,983 |
import time
def retry_get(tap_stream_id, url, config, params=None):
"""Wrap certain streams in a retry wrapper for frequent 500s"""
retries = 20
delay = 120
backoff = 1.5
attempt = 1
while retries >= attempt:
r = authed_get(tap_stream_id, url, config, params)
if r.status_code !... | af9a0dd8d5c7022467562b7c339f8340b6d87d73 | 18,984 |
from typing import Mapping
from datetime import datetime
from typing import Tuple
def build_trie_from_to(template_dictionary: Mapping, from_timestamp: datetime.datetime, to_timestamp: datetime.datetime) -> Tuple[ahocorasick.Automaton, Mapping]:
"""Function which builds the trie from the first timestamp tot the la... | ddd655235a78834260ce1a46c19d0e251f62aede | 18,985 |
def check_monotonicity_at_split(
tree_df, tree_no, trend, variable, node, child_nodes_left, child_nodes_right
):
"""Function to check monotonic trend is in place at a given split in a single tree."""
if not isinstance(tree_df, pd.DataFrame):
raise TypeError("tree_df should be a pd.DataFrame")
... | 97ed2422c6f85112e364e9c63ff0a54d18b6377d | 18,986 |
def allocate_usda_ers_mlu_land_in_urban_areas(df, attr, fbs_list):
"""
This function is used to allocate the USDA_ERS_MLU activity 'land in
urban areas' to NAICS 2012 sectors. Allocation is dependent on
assumptions defined in 'literature_values.py' as well as results from
allocating 'EIA_CBECS_Land'... | 5fcb797b48b912595d722cde3ac0d499526ea899 | 18,987 |
def get_distances_between_points(ray_points3d, last_bin_width=1e10):
"""Estimates the distance between points in a ray.
Args:
ray_points3d: A tensor of shape `[A1, ..., An, M, 3]`,
where M is the number of points in a ray.
last_bin_width: A scalar indicating the witdth of the last bin.
Returns:
... | 34752bd64bcf4582945006c4bd3489397aa7350d | 18,988 |
def reclassification_heavy_duty_trucks_to_light_commercial_vehicles(register_df: pd.DataFrame) -> pd.DataFrame:
"""
Replace Category to Light Commercial Vehicles for Heavy Duty Trucks of weight below 3500kg
Es Tracta de vehicles registrats TIPUS CAMIONS i per tant classificats en la categoria Heavy Duty Tr... | 638e3281c323c1dac4ddcde5e58e2eeac4131c04 | 18,989 |
def SpComp(rho, U, mesh, fea, penal):
"""Alias SpCompFunction class with the apply method"""
return SpCompFunction.apply(rho, U, mesh, fea, penal) | 4c0997fa5213e291376feb415f74e48e273ea071 | 18,990 |
import json
def remove_event_class(request):
"""
Remove the given event class, and update the
order of the rest classes
"""
if request.user.is_authenticated:
class_id = request.POST.get("classId", None)
event_class = EventClass.get_classes_by_user(request.user.id).get(id=class_id)
... | aa4ac93cb8568e5bdc26c4d5913c9438d418b27e | 18,991 |
def get_landmark_position_from_state(x, ind):
"""
Extract landmark position from state vector
"""
lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :]
return lm | 048d31bbd6810663d51e9db34b5c87ebec9b6f27 | 18,992 |
def get_rectangle(roi):
"""
Get the rectangle that has changing colors in the roi.
Returns boolean success value and the four rectangle points in the image
"""
gaussian = cv2.GaussianBlur(roi, (9, 9), 10.0)
roi = cv2.addWeighted(roi, 1.5, gaussian, -0.5, 0, roi)
nh, nw, r = roi.shape
... | da3e6311f6a598cf57cffd2c0bb06f0ca53fa108 | 18,993 |
async def challenge_process_fixture() -> Challenge:
"""
Populate challenge with:
- Default user
- Is open
- Challenge in process
"""
return await populate_challenge() | cf553c0697c824df4273838c7d87ffe6e8ab6ae7 | 18,994 |
import pkgutil
def _read_pdg_masswidth(filename):
"""Read the PDG mass and width table and return a dictionary.
Parameters
----------
filname : string
Path to the PDG data file, e.g. 'data/pdg/mass_width_2015.mcd'
Returns
-------
particles : dict
A dictionary where the ke... | c61202aeb4ad36e22786457306de1ac5773b56d2 | 18,995 |
import torch
def fps_and_pred(model, batch, **kwargs):
"""
Get fingeprints and predictions from the model.
Args:
model (nff.nn.models): original NFF model loaded
batch (dict): batch of data
Returns:
results (dict): model predictions and its predicted
fingerprints, conformer w... | 1a8cca3ffe0d386e506ab42f6e77e00b1a5975d1 | 18,996 |
import re
def preprocess_text(text):
"""
Should return a list of words
"""
text = contract_words(text)
text = text.lower()
# text = text.replace('"', "").replace(",", "").replace("'", "")
text = text.replace('"', "").replace(",", "").replace("'", "").replace(".", " .") ## added by PAV... | 0b42b57629e68c2f0bf3831dc226a2ba823cfdb3 | 18,997 |
import unicodedata
def unicodeToAscii(s):
"""unicodeToAscii
Turn a Unicode string to plain ASCII, thanks to https://stackoverflow.com/a/518232/2809427
For example, 'Ślusàrski' -> 'Slusarski'
"""
return ''.join(
c for c in unicodedata.normalize('NFD', s)
if unicodedata.category(c) !... | 7791ae244499b2448ac4bc5de0fde35057d1f5d5 | 18,998 |
def update_ip_table(nclicks, value):
"""
Function that updates the IP table in the Elasticsearch Database that
contains the frequency as well as the IP address of the machine querying
that particular domain.
Args:
nclicks: Contains the number of clicks registered by the submit button.
... | ef0df6f1fb79d86a707990d0790dadabecbd22c1 | 18,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.