content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import struct
def write_object(definition, *args):
"""
Unpacks a structure using the given data and definition.
"""
obj = {}
object_size = 0
data = b""
i = 0
for (name, stype) in definition:
object_size += struct.calcsize(stype)
arg = args[i]
try:
da... | cc2dd41900de2788efd3213b649513208a7aa504 | 687,092 |
def _with_defaults(defargs, clobber=True):
"""Decorator to set functions' default arguments
The decorator takes a dictionary as an argument, which will
supply default values for all the function arguments that match
one of its keys.
The decorator doesn't reorder function arguments. This means that... | cc434dc598528c990070b56b4aed2c1c30013198 | 687,093 |
import uuid
def generate_password():
"""Generate a random password.
:returns: random password
"""
return hash(str(uuid.uuid1())) | 3a42cc4d9157430b3b05801c3e5e13fe1c771844 | 687,094 |
def _get_services(soup_body):
"""
Returns services being provided by Escort as a list
Returns:
dict: dict containing `tags` key and list of provided services
"""
tags_soup = soup_body.find_all('p', attrs={'class': 'tag'})
tags_list = [tag.get_text(strip=True).lower() for tag in tags_sou... | 5e90d4f26255fe13fb9739e5c7b059113c451db9 | 687,095 |
def search4vowels(phrase: str) -> set: # Informando ao usuário que deve retornar um conjunto no fim
"""
Função que procura vogais em palavras
:param phrase:str palavra provida para procurar vogais
:return: retorna a inserseção de vowels com word
"""
return set('aeiou').intersection(set(phrase.lo... | dd51574eab6d9b52de28c7e31a194d15b79e9979 | 687,097 |
import typing
import functools
import pickle
def memoize(func):
"""単純なメモ化のデコレーター。"""
cache: typing.Dict[bytes, typing.Any] = {}
@functools.wraps(func)
def memoized_func(*args, **kwargs):
key = pickle.dumps((args, kwargs))
if key not in cache:
cache[key] = func(*args, **kwa... | 310992b7bbaa9e5dfbd342d2e4d93efaa6d84fca | 687,098 |
from io import StringIO
def get_number(token):
""" Turn leading part of a string into a number, if possible.
"""
num = StringIO()
for ch in token:
if ch.isdigit() or ch == '.' or ch == '-':
num.write(ch)
else:
break
val = num.getvalue()
num.close()
r... | 43e703f8fc1993aabc325de3729f87ca27c8fc85 | 687,099 |
def remove(pred):
"""Remove any item from collection on traversal if that item meets condition
specified in pred."""
def generator(coll):
for item in coll:
if not pred(item):
yield item
return generator | 11c81269977d1161a5a79f8aa16ec66246233707 | 687,100 |
def new_task_id(sources, prefix=""):
"""Generate a new unique task ID
The task ID will be unique for the given sources, and with the given prefix.
"""
existing_ids = set()
for source in sources:
existing_ids |= {int(key[len(prefix):]) for key in source.task_ids
if ke... | 4e91551f74c5354458ae73a70f919e50b44a02a8 | 687,101 |
import os
import re
def basename(path, suffix=None):
"""Get basename command with optional suffix."""
basename = os.path.basename(path)
if suffix is not None:
basename = re.sub(suffix + '$', '', basename)
return basename.strip() | 7ffada0e2e75afc18cff0d867cfb5ead21f1db1f | 687,102 |
import os
def get_env_file(variable_name: str) -> str:
"""Returns a environment variable as path"""
try:
path = os.path.abspath(os.environ[variable_name])
if not path:
raise RuntimeError(f"Variable is null, Check {variable_name}.")
with open(path, "r") as f:
con... | db937da86a38a66a47a5d623a7f41ddd7c015e4c | 687,103 |
def replace(serverName, itemId, value, date, quality):
"""Replaces values on the OPC-HDA server if the given item ID
exists.
Args:
serverName (str): The name of the defined OPC-HDA server.
itemId (str): The item ID to perform the operation on.
value (object): The value to replace.
... | 1c37bdb45000bcfe61693db47d319ba00d97a5f9 | 687,104 |
def distance_difference_calc(r2, s1, gap):
"""
Computes the necessary distance between mocks given geometrical
components of the survey.
Parameters
-----------
r2 : `float`
s1 : `float`
gap : `float`
Returns
----------
dist_diff : `float`
"""
# Converting to float... | 499fbfddab00c2e3d2a81861b0e23ed07d4e0b5c | 687,105 |
def NORM1(LX, X):
"""
NORM1 normalize an array by its first element
p.23
"""
X1 = X[0]
if (LX <= 0):
return X
for I in range(LX):
X[I] /= X1
return X | 4d5d052479efb013d0a6aebed2573a7a65b56b5b | 687,106 |
import csv
def read_gold_qdmrs(file_path):
"""Reads csv file of QDMR strings
and converts it into a csv containing processed QDMRs
Parameters
----------
file_path : str
Path to csv file containing,
question_id, question text, question decomposition
Returns
--... | ac5bbbc6fcc7cba14b8fcb8195f071f416861bb9 | 687,107 |
import sys
import re
def get_string(prompt=None):
"""
Read a line of text from standard input and return it as a string,
sans trailing line ending. Supports CR (\r), LF (\n), and CRLF (\r\n)
as line endings. If user inputs only a line ending, returns "", not None.
Returns None upon error or no inp... | 2e3bc7955bd70530a586401e66e0f34120ae7434 | 687,108 |
def get_attr_groups(attr_name_file):
"""
Read attribute names one by one from attr_name_file and based on the common prefix, separate them into different attribute groups
Return list of starting indices of those groups
"""
new_group_idx = [0]
with open(attr_name_file, 'r') as f:
all_line... | db2338320fa09c7e6b7e864ea42f8244d76337b9 | 687,109 |
def _service_and_endpoint_labels_from_method(method_name):
"""Get normalized service_label, endpoint_label tuple from method name"""
name_parts = method_name.split("/")
if len(name_parts) != 3 or name_parts[0] != "" or name_parts[1] == "" or name_parts[2] == "":
raise AssertionError("Invalid method ... | e10f2aae174691aad0713c6ea4bbd0fdd830b828 | 687,110 |
def mean_bounds():
"""The upper and lower bounds for which the computed mean is considered correct
"""
bounds = {
'perp': {
'lower': -0.01,
'upper': 0.01,
},
'par': {
'lower': 0.99,
'upper': 1.01,
},
'ref': {
... | 3308ea54a243270aaea08dfe90127092db02f5ce | 687,111 |
def _get_default_columns(model):
"""
@summary:
"""
relationships = {
next(iter(r.local_columns)).key: r.key
for r in model.__mapper__.relationships
}
return set([
relationships.get(c.key, c.key)
for c in model.__mapper__.iterate_properties
]) | 1b46b81ac2011cef8b4f460f2cc98bb355effa80 | 687,112 |
import torch
def repeated_over(colours, alpha, depth):
"""
Args:
colours: [layers, views, height, width, 3] range [0, 1]
alpha: [layers, views, height, width] it's alpha, range [0, 1]
depth: integer
"""
if depth < 1:
return colours[0] * alpha[0].unsqueeze(-1)
complement_alpha = 1. - alpha... | 2b5d7f4754e9f5897987638cd51dff77882d81a4 | 687,113 |
from typing import Union
from typing import Sequence
from typing import Optional
import os
def listdir(directory, skip_suffixes: Union[Sequence, str] = (), full_path: Optional[bool] = False):
"""Convenience function to replace `os.listdir` for skipping annoying mac hidden files."""
if isinstance(skip_suffixes... | 17c688b49e5fca1264bdb09f35cd3a836148ef20 | 687,114 |
import numpy
def block_diag(A, B):
"""Return a block diagonal matrix
A 0
0 B
"""
ma = A.shape[0]
mb = B.shape[0]
na = A.shape[1]
nb = B.shape[1]
z1 = numpy.zeros((ma, nb))
z2 = numpy.zeros((mb, na))
M1 = numpy.hstack((A, z1))
M2 = numpy.hstack((z2, B))
return... | b3fd37ff3b4515a69834fc2efd0161ba8aea4f93 | 687,116 |
import six
def parse_bool(arg, default=False):
"""
NZBGet uses 'yes' and 'no' as well as other strings such as 'on' or
'off' etch to handle boolean operations from it's control interface.
This method can just simplify checks to these variables.
If the content could not be parsed, then the defaul... | 4dc2f701dbf1d6f662bff3f5ebd4087eafe19156 | 687,117 |
def keep_t2(filenames):
"""
Keeps only filenames which pertain to T2 weighted images and labels
Args:
filenames (list): a list of a list of filenames. T2 images are found
in indexes filenames[i][2].
Returns:
list of list: a list with len(filenames). Each element is a list of... | 038ab2fc2e5ede5aa167eaf8f2b43f46adfa5af7 | 687,118 |
import argparse
def valid_longitude(arg):
"""Validates longitude input"""
value = float(arg)
if value > 180 or value < -180:
msg = "%r is not a valid longitude" % arg
raise argparse.ArgumentTypeError(msg)
return value | 507b0cacb638562f93bdc82ccdf591f86e017076 | 687,119 |
import sys
def get_platform():
"""Returns the current platform: Linux, Windows, or OS X"""
if sys.platform.startswith("linux"):
return "Linux"
if sys.platform == "win32":
return "Windows"
if sys.platform == "darwin":
return "OS X"
sys.exit(f"ERROR: Unsupported operati... | ef3d94ccb275357b3e3b5bd968d63d87fc0f773c | 687,121 |
def old_hindu_lunar_leap(date):
"""Return the leap field of an Old Hindu lunar
date = [year, month, leap, day]."""
return date[2] | d11c9efab99552f608fe59761a16ee3a0dbf3246 | 687,122 |
def get_elem_wt():
"""Returns dict with built-in element names and atomic weights [kg/kmol].
Attributes
----------
None
Returns
-------
elem_wt : dict
Dictionary with element name keys and atomic weight [kg/kmol] values.
"""
elem_wt = dict([
('h', 1.00794), ('he', 4... | bf4e68825a83f5fbb43341776aca76e2e29d4b62 | 687,123 |
def get_duplicates(setlist):
"""
Takes a list of sets, and returns a set of items that are found in
more than one set in the list
"""
duplicates = set()
for i, myset in enumerate(setlist):
othersets = set().union(*setlist[i+1:])
duplicates.update(myset & othersets)
return dup... | 0d0e481ffb9490b6a422b83447d950c0fc09536b | 687,124 |
def _on_load_callback(n_clicks, **kwargs):
"""
This gets triggered on load; we use it to fix loading screen
"""
return "loading-non-main", False | 683c8d67e88ac59171e7f60fbee4b514e7659153 | 687,125 |
import json
def read_config(configFile):
"""read config file into config object"""
cfg = open(configFile)
contents = json.load(cfg)
return contents | fcf1ad50ef89bd192ffbb66f81148f722c569448 | 687,126 |
import binascii
import itertools
def xor(data, key):
"""Return `data` xor-ed with `key`."""
key = key.lstrip("0x")
key = binascii.unhexlify(key)
return bytearray([x ^ y for x, y in zip(data, itertools.cycle(key))]) | 59ed91cbdd7b67638b264f6a071eeb82e3c03e3f | 687,127 |
def get_true_ratio(magmom_list: list, in_poscar_data: list) -> int:
"""
Args:
magmom_list (list) - list of magnetic moments
in_poscar_data (list) - list of string in correct POSCAR
Return:
true_ratio (int)
"""
true_num_atoms = len(in_poscar_data[8:])
current_num_atoms... | 19098a83fff096023d3f04d668545404591e0b2f | 687,128 |
import json
def get_bundle_id_list(redis):
""" Get the list of current ids """
bundles = redis.get("b:index") or "[]"
return json.loads(bundles) | 4938d87878c21f612ba6b8b1de04f993b21d6b9a | 687,129 |
def step_count(group_idx):
"""Return the amount of index changes within group_idx."""
cmp_pos = 0
steps = 1
if len(group_idx) < 1:
return 0
for i in range(len(group_idx)):
if group_idx[cmp_pos] != group_idx[i]:
cmp_pos = i
steps += 1
return steps | fdae2ff6be5c48699d61e6b3c32f459d5f7f508a | 687,131 |
def f3(x, y):
"""
Returns the value of multiplication between two valid numbers
"""
return x * y | f1c21c07481be431214910d2a65cd239c22fdda9 | 687,133 |
def method_map_fixture(method, base_path, classes, get):
"""Generic method to generate paths to method/property with a package."""
filetype_to_class = {get(cls): f"{base_path[0]}.{cls}.{method}" for cls in classes}
return filetype_to_class | 204de3a39c21d8d19a22648d9e65633f08ec8a16 | 687,134 |
def ds_read_mock(data_set, *args, **kwargs):
"""
Mock of IkatsApi.ts.fid method
Same parameters and types as the original function
"""
return {"description": "description of my data set",
"ts_list": ['00001',
'00002',
'00003',
... | 1da970015a3affe088f54022b4b3da5e5f036dce | 687,135 |
def ns(s):
"""remove namespace, but only it there is a namespace to begin with"""
if '}' in s:
return '}'.join(s.split('}')[1:])
else:
return s | 5eeb2af8e22c91c7ae32f326fbfcca6611e4cba8 | 687,136 |
import inspect
def get_mro(cls):
"""
Wrapper on top of :func:`inspect.getmro` that recognizes ``None`` as a
type (treated like ``type(None)``).
"""
if cls is type(None) or cls is None:
return (type(None), object)
else:
assert isinstance(cls, type)
return inspect.getmro(... | 950616cd4e9f297638e0c48b78b42b5aa16d1776 | 687,137 |
def create_new_code(questionnaire, configuration):
"""
Create a new code for a Questionnaire based on the configuration.
Args:
questionnaire (Questionnaire): The Questionnaire object.
configuration (str): The code of the configuration.
Returns:
str.
"""
return '{}_{}'.f... | 0807033c1d251d257281d31269e8657e53867b39 | 687,138 |
def get_dbot_level(threat_level_id: str) -> int:
"""
MISP to DBOT:
4 = 0 (UNDEFINED to UNKNOWN)
3 = 2 (LOW to SUSPICIOUS)
1 | 2 = 3 (MED/HIGH to MALICIOUS)
Args:
threat_level_id (str):
Returns:
int: DBOT score
"""
if threat_level_id in ('1', '2'):
return 3
... | f7e89532664ee09f9d06f43e255cf7b495327b35 | 687,139 |
def project_using_projection_matrix(data_to_transform, projection_matrix):
"""
Projects given data into lower dimentional subspace using the provided
projection_matrix.
"""
projected_data = data_to_transform * projection_matrix;
return projected_data | 748f2098e00230328c301033af2fe36f2331ae9e | 687,140 |
def get_pronoun_usages(tree, gender):
"""
Returns a dictionary relating the occurrences of a given gender's pronouns as the
subject and object of a sentence.
:param tree: dependency tree for a document, output of **generate_dependency_tree**
:param gender: `Gender` to check
:return: Dictionary ... | 842597c0b3ac52afdfe8f67ced7d11672ad84b8a | 687,142 |
import pkg_resources
def is_pre_ansible211():
"""
Check if the version of Ansible is less than 2.11.
CI tests with either ansible-core (>=2.11), ansible-base (==2.10), and ansible (<=2.9).
"""
try:
if pkg_resources.get_distribution('ansible-core').version:
return False
ex... | fc5af0a61b43f1003ff1c0a511b3fd6fb16e8e24 | 687,143 |
import math
def constrain_angle(angle: float) -> float:
"""Wrap an angle to the interval [-pi, pi]."""
return math.atan2(math.sin(angle), math.cos(angle)) | f283fc8c87abd06492e3a2acc6da6dfc76db602c | 687,146 |
def get_meta_file_metainfo(img_file, labels):
"""Return meta information about image in 'img_file' file. This information
includes synset (str), numerical class label and human readeable set of
class labels (comma separated str)
"""
synset = img_file.split('/')[-2]
if synset not in labels:... | 207a61de6421dc4734e96ff59ed5ea5c1f49c7b8 | 687,147 |
def parseDataFile(filename):
"""Parse data from file"""
# print("parsing data from file...")
# parsed data will be a list of
# dictionaries in the format:
#
# {
# "id": "ID",
# "text": "The Text...",
# "truth": {
# "topic": "TOPIC",
# "polarity": "POLARITY",
# "genre": "GENRE"
... | 5159f38fe80c7bc8973d6aea90e4d4ee39afa67a | 687,148 |
import difflib
import sys
import platform
def default_file_diff(file_path1, file_path2, print_diff=True, ignore_lines=tuple(), max_diff_in_log=25):
""" compare two files line by line:
@:return: False if a difference is found
"""
file1 = open(file_path1, 'r')
file2 = open(file_path2, 'r')
... | b08b26960d618203434c85072fe0ff2a439c8d1f | 687,149 |
import itertools
def generate_final_heads(*iterables):
"""
Generate unique headers from files
:param iterables: headers file
:return: a unique set of headers
"""
return {
head for head in itertools.chain(*iterables)
} | 30aecb86f7fcb6355d552a6ef8ac7d277c1e1185 | 687,150 |
def bytearray_to_hex(data):
"""Convert bytearray into array of hexes to be printed."""
return ' '.join(hex(ord(byte)) for byte in data) | 7fce7b245f276d4a03d6db78ce87d9371e9afb3c | 687,151 |
def get_attr_connections(source_attr):
"""
It returns the inputs and outputs connections of an attribute.
:param source_attr: Attribute Object.
:return: dictionary with the inputs and outputs connections.
"""
return {'inputs': source_attr.inputs(p=True), 'outputs': source_attr.outputs(p=True)} | 400f0370287168a00c1bb9168bda1218e6bc6e6f | 687,152 |
def _to_lower(items):
"""
Converts a list of strings into a list of lower case strings.
Parameters
----------
items : list
A list of strings.
Returns
-------
The list of items all converted to lower case.
"""
return [item.lower() for item in items] | fbe7bccd1fd77089a5c2776a7d5911187ed840bb | 687,153 |
import codecs
def _convert_text_eb2asc(value_to_convert):
"""
Converts a string from ebcdic to ascii
:param value_to_convert: The ebcdic value to convert
:return: converted ascii text
"""
val = codecs.encode(codecs.decode(value_to_convert, "cp500"), "latin-1")
return val | 1f74909f8f615fdbf9431e4eb759bad778290b88 | 687,154 |
import numpy
def feedforwards(A, B, Q = None):
"""
The formula for Kff can be derived as follows:
r(n+1) = A*r(n) + B*u_ff
B*u_ff = r(n+1) - A*r(n)
u_ff = pinv(B)*(r(n+1) - A*r(n))
Kff = pinv(B)
u_ff = Kff*(r(n+1) - A*r(n))
There is also an LQR-weighted solution, bu... | 2b0944a366a5419f2511675f95db5a5f815af87e | 687,155 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
Get management authorization - roles
"""
return isamAppliance.invoke_get("Get management authorization - roles",
"/authorization/roles/v1") | c84c622e903ee7bc79d167a71b87a6aabd4d093b | 687,156 |
import os
def fix_path(path, project_dir=None):
"""Resolves absolute path:
absolute path is reported as is
resolve paths with user home (~)
other relative paths resolved against project dir"""
path = os.path.expanduser(path)
if not os.path.isabs(path) and project_dir:
path ... | 6c8331554f0b7b86dda83c89ea43785dcf6989ef | 687,157 |
def determine_deltas(my_insts, my_last_insts):
"""
Create lists of created and deleted instances since previous run.
"""
if not my_last_insts:
return None, my_insts
else:
idict = {a['myname']:a for a in my_insts}
ldict = {a['myname']:a for a in my_last_insts}
set_ins... | 33f95406bf731f4dce1a0e54f5d590efc049b61c | 687,158 |
def generate_global(keep, scores, check_keep, check_scores):
"""
Use a simple global threshold sweep to predict if the examples in
check_scores were training data or not, using the ground truth answer from
check_keep.
"""
prediction = []
answers = []
for ans, sc in zip(check_keep, check_... | 98d0eea10c7c4b6ef260bb9d0263d3b5b3e794cb | 687,160 |
import pathlib
import sqlite3
def open_db(
path: pathlib.Path = pathlib.Path(__file__).parent.parent.joinpath(
"data"
).resolve()
) -> sqlite3.Connection:
"""Opens a connection to the bot_o_mat.db file.
Configures the row_factory to return a List[dict] instead of List[tuple].
Returns the c... | 79816dc1152fee53bb7d1371cd15bd85211262d1 | 687,161 |
def helper(node, parent):
"""
the purpose is to check the left/right subtree of parent!
Note the parent in this case is the node of intrest!!
and node could be parent.left or parent.right
Take this simple tree as example:
4
/
4
To check the upper 4 (4root) with it's left... | 7ca069c9f6a80e2eb4b355079998369b3cbad386 | 687,162 |
def put(a, ind, v, mode='raise'):
"""Set a.flat[n] = v[n] for all n in ind.
If v is shorter than ind, it will repeat.
Parameters
----------
a : array_like (contiguous)
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
Values to pl... | e37a481b678d791845d12aa1230b8df801bfd1ac | 687,163 |
def isIterable(obj, returnTrueForNone=False):
"""
# To test out of the systemtools-venv:
isIterable(np.arange(0.0, 0.5, 0.1)
:example:
>>> isIterable([])
True
>>> isIterable([1])
True
>>> isIterable([None])
True
>>> isIterable(None)
... | d5fb00b998fe095a183c76714d08eb757958fec9 | 687,164 |
import re
def get_meanings(search_glosses):
"""
returns a cleanly parsed dict of meanings of the entry, from its glosses
:param search_glosses: list of string (glosses of a entry)
:return: dict of list of string
"""
# list_of_string = search[0].glosses
meanings = {}
synonyms = []
c... | 129f9e44b1ad380616b9cd7ce8a54879e11cf118 | 687,165 |
def vp_from_ke(m):
"""
Computes the vanishing point from the product of the intrinsic and extrinsic
matrices C = KE.
The vanishing point is defined as lim x->infinity C (x, 0, 0, 1).T
"""
return (m[0, 0]/m[2,0], m[1,0]/m[2,0]) | 7c695ea6c1a0a8a73a5dd2833756b0e5da70b8ef | 687,166 |
def make_commands_str(command_aliases):
"""Format a string representation of a number of command aliases."""
commands = command_aliases[:]
commands.sort()
if len(commands) == 1:
return str(commands[0])
elif len(commands) == 2:
return '%s (or %s)' % (str(commands[0]), str(commands[1]))
else:
retu... | 41edc29af6bdb5a952cc0d3d81e05487c2401e58 | 687,167 |
from pathlib import Path
def get_cache_folder() -> Path:
"""Removes all cached datasets.
This can be helpful in case of download issue
"""
return Path(__file__).parent / "data" | b601cead121795023820c92d1f83ed223c7ededf | 687,168 |
from typing import List
from typing import Dict
import yaml
def load_website_sources_list(
config_filename: str = "website_sources.yaml",
) -> List[Dict]:
"""
Loads a list of websites with attributes about those websites as a List of Dicts.
"""
# loads the websites to scrape from
with open(con... | 272da21ef146ad0c3c7bbe9c44f39fcee88192d3 | 687,169 |
import sys
def sanity_checks(config, progress, teacher_path):
"""Some sanity checks on config.json and progress.txt, etc.
This will act as an extra layer of protection in case we have scp errors.
Remember that `config` was saved as we ran Offline RL. And that we have to
consider different top-level d... | b8a175bee3a1223636d146f246ae2d3d6b57047d | 687,171 |
def case_fold(text):
"""Converts text to lower case."""
return text.lower() | 65728e8c9ebec65f4b77786b6125136f2168d79a | 687,172 |
import torch
def smooth_l1_loss(pred, target, beta=1.0):
"""
Smooth L1 Loss introduced in [1].
Args:
pred (:obj:`torch.Tensor`): The predictions.
target (:obj:`torch.Tensor`): The learning targets.
beta (float, optional): The threshold in the piecewise function.
Defaul... | 77a98308c43e9c3c2c4fc723365d23870f6a90f3 | 687,173 |
from functools import reduce
def find_bscs(ckt, a):
""" Return all of the gates that are a fan-in to thortpartition. """
return reduce(lambda x, y: x | y, [ckt[x].fins for x in a]).difference(set(a)) | b89e59eae617a4f040aead84bc76b900d07c634d | 687,174 |
def get_ta(tr, n_slices):
""" Get slice timing. """
return tr - tr/float(n_slices) | c1cba31153cd44ac6b72235b876da352c37eb7e2 | 687,175 |
def alma_query(ra, dec, mirror="almascience.eso.org", radius=1, extra=''):
"""
Open browser with ALMA archive query around central position
"""
#ra, dec = self.get('pan fk5').strip().split()
url = (f"https://{mirror}/asax/?result_view=observation"
f"&raDec={ra}%20{dec},{radius}{extra}")
... | b4aa4a50dca1691d8c95b1a9cae6d7db98fbff8f | 687,176 |
def is_left(p0, p1, p2):
"""
Tests if a point is on left or right of an infinite line
input: three points p0, p1, p2
returns: >0 if p2 is left of line thru p0 and p1
=0 if p2 is on line
<0 if p2 is right of the line
"""
return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) *... | e756ee1c86cd7bbd050d238a1a0d9f1f761e8398 | 687,177 |
def get_message_index(response, message):
"""Returns the index of message in search response, -1 if not found"""
for n, result in enumerate(response):
if result.object == message:
return n
return -1 | 825324d54eeb7c19251f3aaa25a3ccb1c556f502 | 687,178 |
import math
import functools
import operator
def log_beta(x, y, tol=0.):
"""
Computes log Beta function.
When ``tol >= 0.02`` this uses a shifted Stirling's approximation to the
log Beta function. The approximation adapts Stirling's approximation of the
log Gamma function::
lgamma(z) ≈ (... | 3147fdfaed82e7ba7141f158c0ee7c5d16f2ee12 | 687,180 |
def truncatechars_noellipses(value, arg):
"""Truncate a string after `arg` number of characters."""
try:
length = int(arg)
except ValueError: # Invalid literal for int().
return value # Fail silently.
return value[:length] | 8c531125a97e9b3f0e19935f6b9972fc9409e6d1 | 687,181 |
def stations_by_river(stations):
"""Returns a dictionary mapping the names of rivers with a list of their monitoring stations"""
# Creates a dictionary of rivers that map to a list of their monitoring stations
rivers = dict()
for station in stations:
# Adds names of monitoring stations into the... | abce331a1f76374216ba6a5b2e9a203c889fd8d6 | 687,183 |
def create_field_matching_dict(airtable_records, value_field, key_field = None, swap_pairs = False):
"""Uses airtable_download() output to create a dictionary that matches field values from
the same record together. Useful for keeping track of relational data.
If second_field is `None`, then the dictio... | df5fbf24edb7047fc569b10a73eec47fb1234fcd | 687,184 |
import re
def all_matches(names, pattern):
"""If all the filenames in the item/filename mapping match the
pattern, return a dictionary mapping the items to dictionaries
giving the value for each named subpattern in the match. Otherwise,
return None.
"""
matches = {}
for item, name in names... | 17a6a6c57ac528acba45d8f5c2cc3514ccee8a77 | 687,186 |
def gen_rect(t, b, l, r):
"""
:param t: top latitude
:param b: bottom latitude
:param l: left longitude
:param r: right longitude
:return: GeoJSON rect with specified borders
"""
ret = {
'type': 'Feature',
'properties': {},
'geometry': {
'type': 'Polyg... | c93b12cd668316977437813e85bea0bb92ee8cd8 | 687,187 |
def add_ratings(df, rat_off, rat_def, rat_hfa):
"""
Helper function for Massey Ratings
"""
df["H_Off_Rat"] = df["HomeTeam"].map(rat_off)
df["H_Def_Rat"] = df["HomeTeam"].map(rat_def)
df["A_Off_Rat"] = df["AwayTeam"].map(rat_off)
df["A_Def_Rat"] = df["AwayTeam"].map(rat_def)
df["HFA"] = r... | c49ad9c6cc21245c69754a16215894d56e1aea4d | 687,188 |
import torch
def calculate_P_pi(P, pi):
"""
calculates P_pi
P_pi(s,t) = \sum_a pi(s,a) p(s, a, t)
:param P: transition matrix of size |S|x|A|x|S|
:param pi: matrix of size |S| x |A| indicating the policy
:return: a matrix of size |S| x |S|
"""
return torch.einsum('sat,sa->st', P, pi) | 609fc1361884cda9f89ee77fe5e7de2d08bf1f61 | 687,189 |
import os
def default_config_path(filename='config.json'):
"""デフォルトとなる設定ファイルのパスを返す"""
abspath = os.path.abspath(__file__)
return os.path.abspath(os.path.dirname(abspath) + '/' + filename) | 7177109697504e82975166668f0535f2f6bd808c | 687,190 |
def file_exists(name, run_command):
"""Checks for existence of USS file on the host machine."""
rc, stdout, stderr = run_command('file {0}'.format(name))
if stdout and ('FSUM6484' in stdout):
return False, stdout
# file is missing
return True, '' | 4d6de37b7625abd0ab8850a9f158988263bdf0d0 | 687,191 |
import copy
def exact_to_1st_order_model(model):
"""Convert model training on exact augmented objective to model training on
1st order approximation.
"""
model_1st = copy.deepcopy(model)
model_1st.approx = True
model_1st.feature_avg = True
model_1st.regularization = False
return model_... | 4ab21851eb6c8be9915efe1b06f01b5b4c621643 | 687,192 |
def running_mean(mylist, N):
"""
return the list with a running mean acroos the array, with a given kernel size
@param mylist array,list over which to average
@param value length of the averaging kernel
"""
cumsum, moving_aves = [0], []
for i, x in enumerate(mylist, 1):
cumsum... | 963d187e1c971f1de9a86ea7a4b31db981f054cb | 687,193 |
def kmp(S):
"""Runs the Knuth-Morris-Pratt algorithm on S.
Returns a table F such that F[i] is the longest proper suffix of S[0...i]
that is also a prefix of S[0...i].
"""
n = len(S)
if n == 0:
return []
F = [0] * n
for i in range(1, n):
k = F[i - 1]
while k ... | 3989f51253abbb497f86031316f27e62019a4528 | 687,194 |
def get_args(string):
"""Devolve dois objetos de argumentos e flags baseado na string passada por parâmetro.
Args:
string (str): Cadeia de caracteres a ser processada.
Returns:
tuple(list(str), dict): Retorna uma tuple com dois valores, sendo eles uma list de argumentos e um dict de flags.
"""
# @NO... | 09da1ebd8131e518e11bfcf80789b7e1c8a59439 | 687,195 |
def quat_real(quaternion):
"""Return real part of quaternion.
>>> quat_real([3, 0, 1, 2])
3.0
"""
return float(quaternion[0]) | 9b472adf7afebfb7b216afe4b9f1d360732afc2a | 687,196 |
import torch
def log_mean_exp(data):
"""
Возвращает логарифм среднего по последнему измерению от экспоненты данной матрицы.
Подсказка: не забывайте про вычислительную стабильность!
Вход: mtx, Tensor - тензор размера n_1 x n_2 x ... x n_K.
Возвращаемое значение: Tensor, тензор размера n_1 x n_2 x ,... | b2e42091dd61bf8031833cd945ca023ddd7e7f8a | 687,197 |
import tqdm
def execute_serial(action,unitlist,*args):
"""
Wrapper takes in unitlist and additional arguments and
then applies target operations to individual units in
serial
"""
if(action.monitor): unitlist = tqdm.tqdm(unitlist)
listresult = [action.target(action,unit,*args) for unit in... | 0a728f5e957c3db784b49e808916e7e954982c10 | 687,198 |
def find_eq_letters(chain_info, letter):
"""
Find chain letters with the same chain description
Parameters
----------
chain_info : dict
keys are chain descriptions and values are lists of letters
corresponding to that chain description
letter : string
letter whose equiva... | b8ed5a409881d09f8902ccbb602e3764b7cf8e4b | 687,199 |
import os
def is_dirname_log_record(dir_path: str) -> bool:
"""
检查dir_path是否是一个合法的log目录。合法的log目录里必须包含meta.log。
:param dir_path: 被检测的路径
:return: 是否合法
"""
if not os.path.isdir(dir_path):
return False
return os.path.exists(os.path.join(dir_path, 'meta.log')) | 25cc728c56d9b9e19107739b94e6e613590f209d | 687,200 |
def calc_plan(plan, beam_set, norm):
"""Calculate and normalize treatment plan.
Parameters
----------
plan : connect.connect_cpython.PyScriptObject
Current treatment plan.
beam_set : connect.connect_cpython.PyScriptObject
Current beam set.
norm : (str, float, float)
Regi... | e37f09da88ae9092f8b6b89f8f76811ead93d354 | 687,202 |
import hashlib
def sha256sum(body):
"""Get a SHA256 digest from a string."""
h = hashlib.sha256()
if body:
h.update(body)
return h.hexdigest() | 4fcbd9b6d020f5a52fc7ee80343f623c059dff1d | 687,203 |
import os
def path_to_songname(path: str)->str:
"""
Extracts song name from a filepath. Used to identify which songs
have already been fingerprinted on disk.
"""
return os.path.splitext(os.path.basename(path))[0] | 9195d5f25cf1820ad28b8e2e35cbf396971138d6 | 687,204 |
def region_to_area(context):
"""A region *contains*, areas."""
return None | ba53b9edcc942e3f3b5f338a989fec2835aabeb7 | 687,205 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.