content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def open_tar(path_or_file, *args, **kwargs):
"""
A with-context for tar files. Passes through positional and kwargs to tarfile.open.
If path_or_file is a file, caller must close it separately.
"""
(path, fileobj) = ((path_or_file, None) if isinstance(path_or_file, Compatibility.string)
... | 5,324,500 |
def min_rank(series, ascending=True):
"""
Equivalent to `series.rank(method='min', ascending=ascending)`.
Args:
series: column to rank.
Kwargs:
ascending (bool): whether to rank in ascending order (default is `True`).
"""
ranks = series.rank(method="min", ascending=ascending)
... | 5,324,501 |
def write_config_key(stream, envconfig, key, intro_comment=""):
"""Writes the YAML representation of a single key
This writes a single key of a dict to an output stream and then removes
the key from the dict.
Parameters
----------
stream
Output Stream
envconfig : dict
key
... | 5,324,502 |
def glCurrentViewport(x=None, y=None, width=None, height=None):
""" Returns a (x, y, width, height)-tuple with the current viewport bounds.
If x, y, width and height are given, set the viewport bounds.
"""
# Why? To switch between the size of the onscreen canvas and the offscreen buffer.
# The c... | 5,324,503 |
def test_version():
"""Check that we're using Boreutil's implementation."""
assert check_version("head") | 5,324,504 |
def algorithms():
"""Get a list of the names of the available stemming algorithms.
The only algorithm currently supported is the "english", or porter2,
algorithm.
"""
return ['english'] | 5,324,505 |
def load_yaml(filepath):
"""Import YAML config file."""
with open(filepath, "r") as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc) | 5,324,506 |
def zipmerge(name, srcs):
"""Macro wrapper for zipmerge
Args:
name: Name to be used for this rule. It produces name.zip
srcs: List of zips to be combined.
"""
native.genrule(
name = name,
srcs = srcs,
outs = ["%s.zip" % name],
tools = ["//third_party/libzip:... | 5,324,507 |
def trial_4_detect_plaintext_type_from_otp():
"""
Trial 4
-------
Testing ability to recognize the type of text when the cipher is a real OTP (random key for each specimen)
The task of the ML is to recognize the difference between english text and binary data
Proven to be impossible when t... | 5,324,508 |
def parse_json(json_path):
"""
parser JSON
Args:
json_path: input json file path
Returns:
json_dict: parser json dict result
"""
try:
with open(json_path) as json_file:
json_dict = json.load(json_file)
except Exception:
logging.error("json file load ... | 5,324,509 |
def validate_project_with_external_validator(args, project_path):
"""
Try to use an external validator (typically tng-sdk-validation)
to validate the given service project.
Throws TangoValidationException on validation error.
"""
# check if external validator is available?
try:
from ... | 5,324,510 |
def _get_ex_msg(obj):
""" Get exception message """
return obj.value.message if hasattr(obj, 'value') else obj.message | 5,324,511 |
def __getattr__(name: str) -> Any:
"""Lazily imports modules and items within them.
Args:
name (str): name of sourdough module or item.
Raises:
AttributeError: if there is no module or item matching 'name'.
Returns:
Any: a module or item stored within a module.
... | 5,324,512 |
def check_availabel_resourses(target_fname):
""" Проверка доступности ресурсов до запуска паука."""
rpt = []
all_right = True
target_generator = parser_target_for_spider(target_fname)
for at in target_generator:
info = at[0]
head_rpt_msg = 'Name node: ['+info[0]+']\nUrl: ['+info[1]+'... | 5,324,513 |
def set_R_path(path=""):
"""
Explicitly set path to `R` installation dir.
If R is not available on the path, then it can be explicitly
specified here.
Use path="" to reset to default system path.
"""
settings._R_path = path | 5,324,514 |
def remove_last_period(mm):
"""
Shorten the planning horizon of the model by one period.
"""
m = mm.model
variables = ["harv", "age"]
constraints = ["harv", "age", "env"]
harv_vars = pg.get_variables(m, "harv")
max_period = max([float(i.varName.split(",")[-1][:-1]) for i in harv_va... | 5,324,515 |
def _validate_isofactor(isofactor, signed):
""" [Docstring]
"""
if isofactor[0] == 0.0:
return (False, "Error: 'isovalue' cannot be zero")
if isofactor[1] <= 1.0:
return (False, "Error: 'factor' must be greater than one")
if not signed and isofactor[0] < 0:
return (False,... | 5,324,516 |
def get_response_comments(request, comment_id, page, page_size, requested_fields=None):
"""
Return the list of comments for the given thread response.
Arguments:
request: The django request object used for build_absolute_uri and
determining the requesting user.
comment_id: The i... | 5,324,517 |
def GetParentStatementNode(
node: AST.Node,
) -> Optional[AST.Node]:
"""\
Returns the statement that is the logical parent of this node.
This code attempts to handle the complexities of embedded phrases (for example, a statement that
is made up of other phrases) where this node may be nested... | 5,324,518 |
def count_possibilities(dic):
"""
Counts how many unique names can be created from the
combinations of each lists contained in the passed dictionary.
"""
total = 1
for key, value in dic.items():
total *= len(value)
return total | 5,324,519 |
def user_update():
"""
test
"""
username = request.get_json()['username']
email = request.get_json()['email']
password = request.get_json()['password']
try:
id = g.user.id
currentuser = User.query.get(id)
if password:
currentuser.password = password
... | 5,324,520 |
def feature_matrix_hdf5(smis: Iterable[str], size: int, *,
featurizer: Featurizer = Featurizer(),
name: str = 'fps',
path: str = '.') -> Tuple[str, Set[int]]:
"""Precalculate the fature matrix of xs with the given featurizer and store
the m... | 5,324,521 |
def xpath_error(code, message=None, token=None, prefix='err'):
"""
Returns an XPath error instance related with a code. An XPath/XQuery/XSLT error code
(ref: https://www.w3.org/2005/xqt-errors/) is an alphanumeric token starting with four
uppercase letters and ending with four digits.
:param code: ... | 5,324,522 |
def upgrade(new_rpm_path, local_config_dir=None, overwrite=False):
"""
Copy and upgrade a new presto-server rpm to all of the nodes in the
cluster. Retains existing node configuration.
The existing topology information is read from the config.json file.
Unlike install, there is no provision to supp... | 5,324,523 |
def _setPropertyValue(self, name, value, typeString = ''):
"""Set the typed value of a property by its name, creating a child element
to hold the property if needed."""
method = getattr(self.__class__, "_setPropertyValue" + getTypeString(value))
return method(self, name, value, typeString) | 5,324,524 |
def build_toy_input_feature_values(features,
use_rank_two=False,
has_catset=False):
"""Create a set of input features values.
These examples will fall respectively in the nodes 6, 5, 3, 2 of
_build_toy_random_forest.
Args:
features: Dic... | 5,324,525 |
def parse_arguments():
"""Read arguments from a command line."""
parser = argparse.ArgumentParser(description="Arguments get parsed via --commands")
parser.add_argument(
"-v",
metavar="verbosity",
type=int,
default=4,
help="Verbosity of logging: 0 -critical, 1- error,... | 5,324,526 |
def light_head_preprocess_for_train(image, labels, bboxes,
out_shape, data_format='NHWC',
scope='light_head_preprocess_train'):
"""Preprocesses the given image for training.
Note that the actual resizing scale is sampled from
[`resize_size_min`,... | 5,324,527 |
def get_dgs(align_dg_dict):
"""
Function that creates inverse dictionary of align_dg_dict
align_dg_dict: dict. Dictionary of alignments and clustering DG assignments
Returns dg_align_dict: dict, k=dg_id, v=[alignids]
align_dg_dict comes from get_spectral(graph) or get_cliques(graph)
"""
dgs_... | 5,324,528 |
def DateTime_GetBeginDST(*args, **kwargs):
"""DateTime_GetBeginDST(int year=Inv_Year, int country=Country_Default) -> DateTime"""
return _misc_.DateTime_GetBeginDST(*args, **kwargs) | 5,324,529 |
def apply_voigt1d(fid, pks, snorms, a0, b0, a, b, zp, bw, flo=None,
up=True, link_gg=True, link_ll=True, dx_snr=None, dx_snr_mode='outside',
f_cutoff=0., ftype='voigt', outfile=''):
""" Apply Voigt-1D window function, fit the spectrum, and return the treated SnR & FWHM
... | 5,324,530 |
def show_mail(event=None):
"""Shows the full mail when you click on it."""
global primary_bg_color, secondary_bg_color, fg_color, entry_config, highlight, win
value = str(event.widget).split('.')[-1]
if value.isnumeric() and len(value) > 12:
table_name = connect_to_sql(f"select email from u... | 5,324,531 |
def parse_options(dict_in: Optional[dict], defaults: Optional[dict] = None):
"""
Utility function to be used for e.g. kwargs
1) creates a copy of dict_in, such that it is safe to change its entries
2) converts None to an empty dictionary (this is useful, since empty dictionaries cant be argument default... | 5,324,532 |
def build_optimizer(model, optimizer_cfg):
"""Build optimizer from configs.
Args:
model (:obj:`nn.Module`): The model with parameters to be optimized.
optimizer_cfg (dict): The config dict of the optimizer.
Positional fields are:
- type: class name of the optimizer.
... | 5,324,533 |
def test_normal_sw(data):
"""Shapiro-Wilk"""
norm_data = (data - np.mean(data))/(np.std(data)/np.sqrt(len(data)))
return st.shapiro(norm_data) | 5,324,534 |
def dict_to_namespace(cfg_dict: Dict[str, Any]) -> 'Namespace':
"""Converts a nested dictionary into a nested namespace."""
cfg_dict = deepcopy(cfg_dict)
def expand_dict(cfg):
for k, v in cfg.items():
if isinstance(v, dict) and all(isinstance(k, str) for k in v.keys()):
c... | 5,324,535 |
def country_currency(code, country_name):
"""Gives information about the currency of a country"""
_data = return_country(currency_data, country_name)
if _data:
_, currency_name, the_code, symbol = _data
else:
return click.secho('Country does not exist. Perhaps, write the full n... | 5,324,536 |
def decompose_matrix(matrix):
"""Return sequence of transformations from transformation matrix.
matrix : array_like
Non-degenerative homogeneous transformation matrix
Return tuple of:
scale : vector of 3 scaling factors
shear : list of shear factors for x-y, x-z, y-z axes
a... | 5,324,537 |
def test_integration_with_orion(clean_mongo, clean_crate, entity):
"""
Make sure QL correctly handles headers in Orion's notification
"""
h = {
'Content-Type': 'application/json',
'Fiware-Service': 'myservice',
'Fiware-ServicePath': '/',
}
# Subscribe QL to Orion
par... | 5,324,538 |
def record_load(name:str, data:dict, connection_timeout:float=1.0) -> None:
"""
Load data into epics process variables for given location.
Parameters
----------
name: str
location name
data: dict
location data
{TYPE:str, FLAG:int, JOIN:int, RISE:int, TIME:float, *:float}... | 5,324,539 |
def GetMaxHarmonic( efit ):
"""Determine highest-order of harmonic amplitudes in an ellipse-fit object"""
# We assume that columns named "ai3_err", "ai4_err", "ai5_err", etc.
# exist, up to "aiM_err", where M is the maximum harmonic number
momentNums = [int(cname.rstrip("_err")[2:]) for cname in efit.colNames
... | 5,324,540 |
def gzip_open_to(fin_gz, fout):
"""Unzip a file.gz file."""
with gzip.open(fin_gz, 'rb') as zstrm:
with open(fout, 'wb') as ostrm:
ostrm.write(zstrm.read())
assert os.path.isfile(fout), "COULD NOT GUNZIP({G}) TO FILE({F})".format(G=fin_gz, F=fout)
os.remove(fin_gz) | 5,324,541 |
def export_results(process_results, references, output_dir,
results_file_prefix=""):
"""
Exports an xlsx file with results over all run simulations and an html file
showing plots of the results.
The Plot shows the source demand of all settings. If a reference time
series has been ... | 5,324,542 |
def quaternary_tournament(population, scores, next_gen_number, random_seed=42):
"""Selects next generation using quaternary tournament selection for
single objective.
This function implements quaternary tournament selection to select a
specific number of members for the next generation.
Args:
... | 5,324,543 |
def ctrl(browser, k):
"""Send key combination Ctrl+(k)"""
trigger_keystrokes(browser, "control-%s" % k) | 5,324,544 |
def empty_list():
"""An empty list"""
return [] | 5,324,545 |
def snapshot():
"""Creates a default initialized startup snapshot.
deno_core requires this, although it does not document this outside of a
few random mentions in issues.
"""
return Runtime(will_snapshot=True).snapshot() | 5,324,546 |
def sample_user(email='riti2874@gmail.com', password='Riti#2807'):
"""Createing a smaple user"""
return get_user_model().objects.create_user(email, password) | 5,324,547 |
def is_chinese_prior_leap_month(m_prime, m):
"""Return True if there is a Chinese leap month on or after lunar
month starting on fixed day, m_prime and at or before
lunar month starting at fixed date, m."""
return ((m >= m_prime) and
(is_chinese_no_major_solar_term(m) or
is_chin... | 5,324,548 |
async def botinfo():
"""Get Info About The Bot"""
em = discord.Embed(color=0xea7938) #0xea7938 is the color code
em.add_field(name='Bot Info', value="This bot was created with the library Discord.py\n If you need any help or questions, join the [devs' server](https://discord.gg/km9Yudr)")
em.add_fie... | 5,324,549 |
def print_video_id_with_car_events(annotation_dir):
"""Print car events stats in the stanford dataset.
Args:
annotation_dir: Annotation dir.
video_list_file_path: List of video files to include (Default value = None).
Returns:
"""
annotations = io_util.load_stanford_campus_annotation(... | 5,324,550 |
def main():
"""Fetches tokens from map, returns as compact .json map"""
print(" ===================")
print(" Token Collector ")
print(" ===================")
print("Press ctrl+c or close window to quit.\n")
print("Will take any number of .json map files as command line arguments:")
print... | 5,324,551 |
def parse_wrapper(max_iters,driver,data,file):
"""
The following method is designed to automatically parse each url contained in a long list
of scraped urls, and writes the title, abstract, and doi to a new text file with a user
input "file_name.txt."
Arguments:
max_iters - total number of... | 5,324,552 |
def read_config_file(fname):
"""Reads a JSON or YAML file.
"""
if fname.endswith(".yaml") or fname.endswith(".yml"):
try:
rfunc = partial(yaml.load, Loader=yaml.FullLoader)
except AttributeError:
rfunc = yaml.load
elif fname.endswith(".json"):
rfunc = json... | 5,324,553 |
async def insert_submission(submission: Submission, config: Config = CONFIG):
"""
Store a Submission object into metadata store.
Args:
submission: Submission object
config: Runtime configuration
"""
client = await get_db_client(config)
collection = client[config.db_name][COLLEC... | 5,324,554 |
def plot_wo(wo, legend=True, **plot_kwargs):
"""Plot a water observation bit flag image.
Parameters
----------
wo : xr.DataArray
A DataArray containing water observation bit flags.
legend : bool
Whether to plot a legend. Default True.
plot_kwargs : dict
Keyword argum... | 5,324,555 |
def _get_tweets(db_path="tweets.json"):
"""Get Trump's tweets, caching after first use."""
global TWEETS
# Cache tweets if they haven't been fetched yet
if TWEETS is None:
# Try to read from a saved file
if os.path.exists(db_path):
with open(db_path) as f:
TWE... | 5,324,556 |
def int_list_data():
"""Item data with an in list. [1, 2, 3, 4, 5, 6]"""
return easymodel.ListItemData([1, 2, 3, 4, 5, 6]) | 5,324,557 |
def test_handle_unknown() -> None:
"""
Tests correct output when prediction data is not present in the unseen data.
"""
transformer = DatetimeOneHotEncoderTransformer()
data = DatetimeIndex([datetime(2019, 1, 1, 1, 0, 0)])
unseen_data = DatetimeIndex([datetime(2020, 2, 2, 2, 0, 0)])
correct_... | 5,324,558 |
def check_transaction_threw(receipt: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Check if the transaction threw/reverted or if it executed properly by reading
the transaction receipt.
Returns None in case of success and the transaction receipt if the
transaction's status indicator is 0x0.
... | 5,324,559 |
def button(style: ButtonStyle, label: str, **kwargs) -> Callable[..., Button]:
"""A decorator used to create buttons.
This should be decorating the buttons callback.
Parameters
----------
style: :class:`.ButtonStyle`
The styling to use for the button
label: :class:`str`
The la... | 5,324,560 |
def measure2(rep=REPETITIONS, timeout=TIMEOUT):
"""
The whole thing:
Start processes.
Measure memory.
Hammer servers.
Measure memory.
Kill processes.
"""
f=open("logging.txt", "w")
stdout=stderr=f
processes=startProcessesTotallyIndependent(stdout=stdout, ... | 5,324,561 |
def yaml_export(args, vault):
"""Run this module
:returns: None
"""
print(vault.group.yaml_export()) | 5,324,562 |
def notify(header: str, body: str, urgency: str="normal") -> None:
"""Show a desktop notification via notify-send.
header -- the notification header
body -- the notification body
urgency -- the urgency level (default 'normal') [low|normal|critical]
"""
if which("notify-send"):
subproce... | 5,324,563 |
def cover():
"""runs the unit tests with coverage"""
os.system('coverage run manage.py run_test')
os.system('coverage report')
os.system('coverage html') | 5,324,564 |
def _check_groups_docker():
"""
Check that the current user belongs to the required groups to both run S2E and build S2E images.
"""
if not _user_belongs_to('docker'):
_raise_group_error('docker') | 5,324,565 |
def AuxSource_Cast(*args):
"""
Cast(BaseObject o) -> AuxSource
AuxSource_Cast(Seiscomp::Core::BaseObjectPtr o) -> AuxSource
"""
return _DataModel.AuxSource_Cast(*args) | 5,324,566 |
def to_byte_array(int_value):
"""Creates a list of bytes out of an integer representing data that is
CODESIZE bytes wide."""
byte_array = [0] * CODESIZE
for i in range(CODESIZE):
byte_array[i] = int_value & 0xff
int_value = int_value >> 8
if BIG_ENDIAN:
byte_array.reverse()
... | 5,324,567 |
def no_op(loss_tensors):
"""no op on input"""
return loss_tensors | 5,324,568 |
def get_example_two_cube(session, varcodes, selected_year=None):
""" Create 2D cube of flight routes per selector variable description, per date selector. """
cubes_api = aa.CubesApi(session.api_client)
# If no selected year, no underlying base query
if selected_year is None:
query = create_que... | 5,324,569 |
def svd_reduce(imgs, n_jobs):
"""Reduce data using svd.
Work done in parallel across subjects.
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded ... | 5,324,570 |
def parse_project(record: Record, add_info: dict) -> Tuple[Pair, List[Pair], List[Pair]]:
"""Parse the project record in airtable to Billinge group format.
Return a key-value pair of the project and a list of key-value pairs of the people doc and institution doc
in the project. The record should be denorma... | 5,324,571 |
def forbidden_handler_exc(message):
"""More flexible handling of 403-like errors. Used by raising ForbiddenError.
Args:
message (str) - Custom message to display
"""
return render_template('errors/403.html', message=message), 403 | 5,324,572 |
def run_test():
"""Runs the unit tests without test coverage."""
tests = unittest.TestLoader().discover('./tests', pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
return 1 | 5,324,573 |
def resnet34(num_classes: int = 1000, class_type: str = "single") -> ResNet:
"""
Standard ResNet 34 implementation;
expected input shape is (B, 3, 224, 224)
:param num_classes: the number of classes to classify
:param class_type: one of [single, multi] to support multi class training;
defau... | 5,324,574 |
def linspace(start, stop, num=50):
"""
Linspace with additional points
"""
grid = list(np.linspace(start, stop, num))
step = (stop - start) / (num - 1)
grid.extend([0.1 * step, 0.5 * step, stop - 0.1 * step, stop - 0.5 * step])
return sorted(grid) | 5,324,575 |
def strip_html(markdown):
"""
Strip HTML tags from a markdown string.
Entities present in the markdown will be escaped.
Parameters:
markdown: A :term:`native string` to be stripped and escaped.
Returns:
An escaped, stripped :term:`native string`.
"""
class Parser(HTMLParse... | 5,324,576 |
def test_check_case():
"""Test check_case with non-default options."""
assert check_case('TEST', lower=False) == 'TEST' | 5,324,577 |
def find_character_occurences(processed_txt):
"""
Return a list of actors from `doc` with corresponding occurences.
"""
total_len = len(processed_text)
characters = Counter()
index = 0
for ent in processed_txt.ents:
if ent.label_ == 'PERSON':
characters[ent.lemma_] +... | 5,324,578 |
def parents_similarity(subject1, subject2, values):
"""
This function creates two new subjects by comparing the bits of the binary encoded provided subjects (the
parents). If both parents have the same bit in a certain location, the offspring have a very high probability
of having the same bit too in th... | 5,324,579 |
def generic_fftshift(x,axis=[-2,-1],inverse=False):
"""
Fourier shift to center the low frequency components
Parameters
----------
x : torch Tensor
Input array
inverse : bool
whether the shift is for fft or ifft
Returns
-------
shifted array
"""
... | 5,324,580 |
async def test_flow_user_invalid_auth(hass: HomeAssistant) -> None:
"""Test user initialized flow with invalid authentication."""
with patch_config_flow_tautulli(AsyncMock()) as tautullimock:
tautullimock.side_effect = exceptions.PyTautulliAuthenticationException
result = await hass.config_entri... | 5,324,581 |
def eval_ner(gold, sen, labels):
"""
evaluate NER
"""
if len(gold) != len(sen):
print(len(gold), len(sen))
raise "lenghts not equal"
tp = 0
#tn = 0
fp = 0
fn = 0
list_en = ["LOC", "MISC", "ORG", "PER"]
for en in list_en:
g = list_entities(gold, labels["... | 5,324,582 |
def generate_data(m: int = 1000, n: int = 30, sigma: int = 40):
"""Generates data for regression.
To experiment with your own data, just replace the contents of this
function with code that loads your dataset.
Args
----
m : int
The number of examples.
n : int
The number of ... | 5,324,583 |
def handle_leave(message, text_message=None,
failure_answer=choice(DICTBASE['negation'])):
"""
leave chat if user in userbase and if possible
"""
admin = False
if (message.chat.type != 'private' and
any(user['name'] == message.from_user.username for user in USERBASE)):
... | 5,324,584 |
def read_datafile(path: str):
""" read a flight data file and unpack it """
with open(path, 'rb') as fp:
data = fp.read()
if len(data) != altacc_format.size:
logging.warning(f"invalid data file length, {len(data)} bytes!")
fields = altacc_format.unpack(data)
flight = AltAccDump._m... | 5,324,585 |
def get_compiler_option():
""" Determines the compiler that will be used to build extension modules.
Returns
-------
compiler : str
The compiler option specificied for the build, build_ext, or build_clib
command; or the default compiler for the platform if none was
specified.
... | 5,324,586 |
def create_output_from_files(data_file_path:str, sheet_name:str, yaml_file_path:str, wikifier_filepath:str, output_filepath:str =None, output_format:str ="json"):
"""A convenience function for creating output from files and saving to an output file.
Equivalent to calling KnowledgeGraph.generate_from_files follo... | 5,324,587 |
def delete_article(index_id, task_id, document_id):
"""
从ElasticSearch中删除一篇文档
:param index_id: 目标index
:param task_id: 目标task
:param document_id: 目标document
:return:
"""
doc_id = DocumentTools.get_doc_id(index_id, task_id, document_id)
if document_id == "_all":
BaseTaskContr... | 5,324,588 |
def test_creation_single_row():
""" test the creation of DataClass objects from dicts or arrays;
single row only"""
# ground truth tables - compare against these tables
ground_truth_1 = QTable([[1], [2], [3]], names=('aa', 'bb', 'cc'))
ground_truth_2 = QTable([[1]*u.m, [2]*u.kg, [3]*u.cm/u.s],
... | 5,324,589 |
def make_new_images(dataset, imgs_train, imgs_val):
"""
Split the annotations in dataset into two files train and val
according to the img ids in imgs_train, imgs_val.
"""
table_imgs = {x['id']:x for x in dataset['images']}
table_anns = {x['image_id']:x for x in dataset['annotations']}
keys... | 5,324,590 |
def test_similarity_sample_multiprocess(pk_target):
"""Test similarity cutoff filter"""
def weight(T):
return T ** 4
_filter = SimilaritySamplingFilter(sample_size=10, weight=weight)
pk_target.react_targets = True
pk_target.filters.append(_filter)
pk_target.transform_all(processes=2, g... | 5,324,591 |
def compute_maximum_ts_map(ts_map_results):
"""
Compute maximum TS map across a list of given ts maps.
Parameters
----------
ts_map_results : list
List of `~gammapy.image.SkyImageCollection` objects.
Returns
-------
images : `~gammapy.image.SkyImageCollection`
Images (t... | 5,324,592 |
async def test_form_uuid_error(hass: HomeAssistant) -> None:
"""Test we handle error from bad uuid."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["errors... | 5,324,593 |
def compute_dist(array1, array2, type='euclidean'):
"""Compute the euclidean or cosine distance of all pairs.
Args:
array1: numpy array with shape [m1, n]
array2: numpy array with shape [m2, n]
type: one of ['cosine', 'euclidean']
Returns:
numpy array with shape [m1, m2]
"""
... | 5,324,594 |
def clicr_to_concept_txt(train_file="/mnt/b5320167-5dbd-4498-bf34-173ac5338c8d/Datasets/bmj_case_reports_data/dataset_json_concept_annotated/train1.0.json", out_file="/mnt/b5320167-5dbd-4498-bf34-173ac5338c8d/Datasets/bmj_case_reports_data/dataset_json_concept_annotated/train1.0_concepts.txt"):
"""
Prepare a si... | 5,324,595 |
def timer(step, callback, *args):
"""定时器"""
s = internet.TimerService(step, callback, *args)
s.startService()
return s | 5,324,596 |
def clean_tfreocrds(input_file, output_file):
"""Clean tfrecords file"""
writer = tf.python_io.TFRecordWriter(output_file)
count = 0
for example in tf.python_io.tf_record_iterator(input_file):
result = tf.train.Example.FromString(example)
labels = result.features.feature['label'].float_l... | 5,324,597 |
def download(date_array, tag, sat_id, data_path, user=None, password=None):
"""
Download SuperDARN data from Virginia Tech organized for loading by pysat.
"""
import sys
import os
import pysftp
import davitpy
if user is None:
user = os.environ['DBREADUSER']
if password... | 5,324,598 |
def select_file(title: str) -> str:
"""Opens a file select window and return the path to selected file"""
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(title=title)
return file_path | 5,324,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.