content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def macd_cross_func_pd(data):
"""
神一样的指标:MACD
"""
if (ST.VERBOSE in data.columns):
print('Phase macd_cross_func', QA_util_timestamp_to_str())
MACD = QA.QA_indicator_MACD(data)
MACD_CROSS = pd.DataFrame(columns=[ST.MACD_CROSS,
FLD.MACD_CROSS_JX... | 5,345,300 |
def jsonp_response(data, callback="f", status=200, serializer=None):
"""
Returns an HttpResponse object containing JSON serialized data,
wrapped in a JSONP callback.
The mime-type is set to application/x-javascript, and the charset to UTF-8.
"""
val = json.dumps(data, default=serializer)
re... | 5,345,301 |
def enhance_bonds(bond_dataframe, structure_dict):
"""Enhance the bonds dataframe by including derived information.
Args:
bond_dataframe: Pandas dataframe read from train.csv or test.csv.
structure_dict: Output of :func:`make_structure_dict`, after running :func:`enhance_structure_dict`.
R... | 5,345,302 |
def _tofloat(value):
"""Convert a parameter to float or float array"""
if isiterable(value):
try:
value = np.asanyarray(value, dtype=np.float)
except (TypeError, ValueError):
# catch arrays with strings or user errors like different
# types of parameters in a... | 5,345,303 |
def sp2mgc(sp, order=20, alpha=0.35, gamma=-0.41, miniter=2,
maxiter=30, criteria=0.001, otype=0, verbose=False):
"""
Accepts 1D or 2D one-sided spectrum (complex or real valued).
If 2D, assumes time is axis 0.
Returns mel generalized cepstral coefficients.
Based on r9y9 Julia code
ht... | 5,345,304 |
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
for key, val in word_dic.items():
if key.startswith(sub_s):
return True
else:
pass
return False | 5,345,305 |
def _package_data(vec_f_image, vec_f_imageBscan3d, downscale_size, downscale_size_bscan, crop_size, num_octa,
str_angiography, str_structure, str_bscan, vec_str_layer, vec_str_layer_bscan3d, str_bscan_layer,
dict_layer_order, dict_layer_order_bscan3d):
"""
Organizes the angio... | 5,345,306 |
def add_to_db(kb_db_name, obj_file_path):
"""
Add knowledge about the target object manipulation to the database.
Args:
kb_db_name(str): The knowledge base database file name.
obj_file_path(str): File path to the .obj file.
"""
# create vpython scene that is used for graphical repre... | 5,345,307 |
def server(
settings: TangoGlobalSettings,
workspace: Optional[str],
workspace_dir: Optional[Union[str, os.PathLike]] = None,
):
"""
Run a local webserver that watches a workspace.
"""
from tango.server.workspace_server import WorkspaceServer
from tango.workspaces import LocalWorkspace
... | 5,345,308 |
def apply_padding_by_last(list_of_lists):
""" The same as applying pad_into_lists followed by carry_previous_over_none
but takes a list of lists instead of events
Args:
lists_of_lists: list of lists with possibly different lengths
Returns:
lists of lists padded to the same length by ... | 5,345,309 |
def combine_patterns(
*patterns: str, seperator: Expression = None, combine_all=False
) -> str:
"""
Intelligently combine following input patterns.
Parameters
----------
patterns :
The patterns to combine.
seperator :
The seperator to use. If None, the default seperator :dat... | 5,345,310 |
def fetch_and_merge_reports(
project_id: str,
pipeline_id: int,
merged_report_output_file: io.TextIOWrapper,
) -> None:
"""
Fetches and merges the JUnit XML reports of each pytest
integration job in pipeline `pipeline_id` of project `project_id`,
and writes the result to `merged_report_outpu... | 5,345,311 |
def _add_unlinked_object(self: JSONClassObject,
field_name: str,
obj: JSONClassObject) -> None:
"""Add an object into unlinked objects pool."""
if not self._unlinked_objects.get(field_name):
self._unlinked_objects[field_name] = []
if obj not in self.... | 5,345,312 |
async def utc_timediff(t1, t2):
"""
Calculate the absolute difference between two UTC time strings
Parameters
----------
t1, t2 : str
"""
time1 = datetime.datetime.strptime(t1, timefmt)
time2 = datetime.datetime.strptime(t2, timefmt)
timedelt = time1 - time2
return abs(timedelt... | 5,345,313 |
def function():
"""
>>> function()
'decorated function'
"""
return 'function' | 5,345,314 |
def load_stopwords(file_path):
"""
:param file_path: Stop word file path
:return: Stop word list
"""
stopwords = [line.strip() for line in open(file_path, 'r', encoding='utf-8').readlines()]
return stopwords | 5,345,315 |
def test_gen_choice_1(item):
"""Select a random value from integer values."""
choices = range(5)
result = gen_choice(choices)
assert result in choices | 5,345,316 |
def hello():
"""Return a friendly HTTP greeting."""
return 'abc' | 5,345,317 |
def draw_graph(x, y):
"""Draw graph with x and y coordinates."""
plt.plot(x, y)
plt.xlabel('x-coordinate')
plt.ylabel('y-coordinate')
plt.title('projectile motion of a ball') | 5,345,318 |
def show_ip_ospf_route(
enode,
_shell='vtysh',
_shell_args={
'matches': None,
'newline': True,
'timeout': None,
'connection': None
}
):
"""
Show ospf detail.
This function runs the following vtysh command:
::
# show ip ospf route
:param dic... | 5,345,319 |
def fc1():
""" Test function 1 """
print("fc1") | 5,345,320 |
def test_field_serialize_None():
"""If you attempt to serialize None (because you passed data instead of obj)
an error should be raised"""
class MapperBase(Mapper):
__type__ = TestType
score = Integer()
mapper = MapperBase(data={})
with pytest.raises(MapperError):
mapper... | 5,345,321 |
def _PutTestResultsLog(platform, test_results_log):
"""Pushes the given test results log to google storage."""
temp_dir = util.MakeTempDir()
log_name = TEST_LOG_FORMAT % platform
log_path = os.path.join(temp_dir, log_name)
with open(log_path, 'wb') as log_file:
json.dump(test_results_log, log_file)
if s... | 5,345,322 |
def attrs_classes(
verb,
typ,
ctx,
pre_hook="__json_pre_decode__",
post_hook="__json_post_encode__",
check="__json_check__",
):
"""
Handle an ``@attr.s`` or ``@dataclass`` decorated class.
This rule also implements several hooks to handle complex cases, especially to
manage back... | 5,345,323 |
def delta(pricer, *, create_graph: bool = False, **kwargs) -> torch.Tensor:
"""Computes and returns the delta of a derivative.
Args:
pricer (callable): Pricing formula of a derivative.
create_graph (bool): If True, graph of the derivative will be
constructed, allowing to compute hig... | 5,345,324 |
def formula_search(min_texts, max_texts, min_entries, max_entries):
"""Filter search results"""
result = Cf.query.filter(
Cf.n_entries >= (min_entries or MIN),
Cf.n_entries <= (max_entries or MAX),
Cf.unique_text >= (min_texts or MIN),
Cf.unique_text <= (max_texts or MAX)
).... | 5,345,325 |
def versioneer():
"""
Function used to generate a new version string when saving a new Service
bundle. User can also override this function to get a customized version format
"""
date_string = datetime.now().strftime("%Y%m%d")
random_hash = uuid.uuid4().hex[:6].upper()
# Example output: '20... | 5,345,326 |
def request_url(method, url):
"""Request the specific url and return data"""
try:
r = http.request(method, url)
if r.status == 200:
return r.data.decode('utf-8')
else:
raise Exception("Fail to {} data from {}".format(method, url))
except Exception as e:
... | 5,345,327 |
def _ifail(repo, mynode, orig, fcd, fco, fca, toolconf, labels=None):
"""
Rather than attempting to merge files that were modified on both
branches, it marks them as unresolved. The resolve command must be
used to resolve these conflicts."""
# for change/delete conflicts write out the changed versio... | 5,345,328 |
def __noise_with_pdf(im_arr: np.ndarray, pdf: Callable, **kwargs) -> np.ndarray:
"""Apply noise to given image array using pdf function that generates random values."""
util.check_input(im_arr)
im_arr = im_arr/255.0
noise = pdf(**kwargs, size=im_arr.shape)
out_im = im_arr + noise
out_im = np.cli... | 5,345,329 |
def get_git_revision_hash():
"""Returns the git version of this project"""
return subprocess.check_output(
["git", "describe", "--always"], universal_newlines=True
) | 5,345,330 |
def train_test_split(df, frac):
"""
Create a Train/Test split function for a dataframe and return both
the Training and Testing sets.
Frac refers to the percent of data you would like to set aside
for training.
"""
frac = round(len(df)*frac)
train = df[:frac]
test = df[frac:]
r... | 5,345,331 |
def print_table(d, words, n=20):
"""
Prints table of stable and unstable words in the following format:
<stable words> | <unstable words>
Arguments:
d - distance distribution
words - list of words - indices of d and words must match
n - numbe... | 5,345,332 |
def load_special_config(config_filename, special_type, image_type='extent'):
"""Loads the google earth ("google"), science on a sphere ("sos"), or any other
special type of image config.
"""
cfg = load_config(config_filename)
# Promote the image type's keys
cfg = _merge_keys(cfg, cfg[image_typ... | 5,345,333 |
def test_optimiser_updatemodel():
"""Test that the method for updating an oogeso optimisation models"""
energy_system_data = make_test_data()
# convert profile data to dictionary of dataframes needed internally:
profiles_df = {"forecast": pd.DataFrame(), "nowcast": pd.DataFrame()}
for pr in energy_... | 5,345,334 |
def softmax_strategy_cim(attrs, inputs, out_type, target):
"""softmax cim strategy"""
strategy = _op.OpStrategy()
strategy.add_implementation(
wrap_compute_softmax(topi.nn.softmax),
wrap_topi_schedule(topi.cim.schedule_softmax),
name="softmax.cim",
)
return strategy | 5,345,335 |
def get_statements_by_hash(hash_list, ev_limit=100, best_first=True, tries=2):
"""Get fully formed statements from a list of hashes.
Parameters
----------
hash_list : list[int or str]
A list of statement hashes.
ev_limit : int or None
Limit the amount of evidence returned per Statem... | 5,345,336 |
def test_save_load_model():
"""Test saving/loading a fitted model to disk"""
X_train, y_train, X_dev, y_dev, label_list = toxic_test_data()
model = BertClassifier()
model.max_seq_length = 64
model.train_batch_size = 8
model.epochs= 1
model.multilabel = True
model.label_list = label_lis... | 5,345,337 |
def _is_in(val_set):
"""Check if a value is included in a set of values"""
def inner(val, val_set):
if val not in val_set:
if isinstance(val_set, xrange):
acceptable = "[%d-%d]" % (val_set[0], val_set[-1])
else:
acceptable = "{%s}" % ", ".join(val_... | 5,345,338 |
def commit_config(config):
"""
:param config:
:return:
"""
try:
json_response = apply_config(config, False) # Checks for config validation with Write Param set to False
if "message" in json_response: # If config is valid write the config
return json_response
if ... | 5,345,339 |
def onebyone(transform, loglikelihood, parameter_names, prior, start = 0.5, ftol=0.1, disp=0, nsteps=40000,
parallel=False, find_uncertainties=False, **args):
"""
**Convex optimization based on Brent's method**
A strict assumption of one optimum between the parameter limits is used.
The bounds are narrowed until... | 5,345,340 |
def load_ucs_manager_config():
"""
loads the test configuration into the UCS Manger
"""
logs.info_1('Loading UCSPE emulator from {0}'.format(fit_common.fitcfg()['ucsm_config_file']))
try:
handle = ucshandle.UcsHandle(UCSM_IP, UCSM_USER, UCSM_PASS)
if not ... | 5,345,341 |
def test_data():
"""Test data object for the main PlantCV module."""
return TestData() | 5,345,342 |
def file_with_reftrack(request, tmpdir, parent_reftrack):
"""Return a filename to a scene with the reftracks from parent_reftrack fixture."""
fn = tmpdir.join("test1.mb")
f = cmds.file(rename=fn.dirname)
cmds.file(save=True, type='mayaBinary')
def fin():
os.remove(f)
request.addfinaliz... | 5,345,343 |
def make_cmap(infile):
"""Call correct cmap function depending on file."""
cornames = ["coherence-cog.tif", "phsig.cor.geo.vrt", "topophase.cor.geo.vrt"]
phsnames = ["unwrapped-phase-cog.tif", "filt_topophase.unw.geo.vrt"]
if infile in cornames:
cpt = make_coherence_cmap()
elif infile in ph... | 5,345,344 |
def tail_correction(r, V, r_switch):
"""Apply a tail correction to a potential making it go to zero smoothly.
Parameters
----------
r : np.ndarray, shape=(n_points,), dtype=float
The radius values at which the potential is given.
V : np.ndarray, shape=r.shape, dtype=float
The potent... | 5,345,345 |
def process_input(input_string):
"""
>>> for i in range (0, 5):
... parent_node = Node(None)
... parent_node.random_tree(4)
... new_node = process_input(parent_node.get_test_string())
... parent_node.compute_meta_value() - new_node.compute_meta_value()
0
0
0
0
... | 5,345,346 |
def _get_version_info(blade_root_dir, svn_roots):
"""Gets svn root dir info. """
svn_info_map = {}
if os.path.exists("%s/.git" % blade_root_dir):
cmd = "git log -n 1"
dirname = os.path.dirname(blade_root_dir)
version_info = _exec_get_version_info(cmd, None)
if version_info:
... | 5,345,347 |
def equiv_alpha(x,y):
"""check if two closed terms are equivalent module alpha
conversion. for now, we assume the terms are closed
"""
if x == y:
return True
if il.is_lambda(x) and il.is_lambda(y):
return x.body == il.substitute(y.body,zip(x.variables,y.variables))
return False
... | 5,345,348 |
def delete(isamAppliance, file_id, check_mode=False, force=False):
"""
Clearing a common log file
"""
ret_obj = {'warnings': ''}
try:
ret_obj = get(isamAppliance, file_id, start=1, size=1)
delete_required = True # Exception thrown if the file is empty
# Check for Docker
... | 5,345,349 |
def filter_imgs(df, properties = [], values = []):
"""Filters pandas dataframe according to properties and a range of values
Input:
df - Pandas dataframe
properties - Array of column names to be filtered
values - Array of tuples containing bounds for each filter
Output:
df - Filter... | 5,345,350 |
def conjugate_term(term: tuple) -> tuple:
"""Returns the sorted hermitian conjugate of the term."""
conj_term = [conjugate_field(field) for field in term]
return tuple(sorted(conj_term)) | 5,345,351 |
def create_notify_policy_if_not_exists(project, user, level=NotifyLevel.involved):
"""
Given a project and user, create notification policy for it.
"""
model_cls = apps.get_model("notifications", "NotifyPolicy")
try:
result = model_cls.objects.get_or_create(project=project,
... | 5,345,352 |
def test_parser_parse():
"""
Abstract
----------
Testing module.parser.parse function
"""
args = Parser.parse() | 5,345,353 |
def test():
"""
This function show how you can write a simple python function
"""
print("Hey Python!") | 5,345,354 |
def plot_hp_sensitivities(experiment_folder, variable_name, hp_name, hp_fixed={}, details=False, box_pts=1, show=False):
""" plot hyper-parameter sensitivities """
dpaths = subdir_paths(experiment_folder)
cfg_global = {}
# read in events into dictionary for chosen hyperparameter and variable respecting... | 5,345,355 |
def parse_table(soup, start_gen, end_gen):
"""
- Finds the PKMN names in the soup object and puts them into a list.
- Establishes a gen range.
- Gets rid of repeated entries (formes, e.g. Deoxys) using an OrderedSet.
- Joins the list with commas.
- Handles both Nidorans having 'unmappable' chara... | 5,345,356 |
def get_expert_parallel_src_rank():
"""Calculate the global rank corresponding to a local rank zero
in the expert parallel group."""
global_rank = torch.distributed.get_rank()
local_world_size = get_expert_parallel_world_size()
return (global_rank // local_world_size) * local_world_size | 5,345,357 |
def plot_network(network, labels, edge_weights=(0.1, 2), layout_seed=None, figsize=(10, 6)):
"""Plot network.
Notes: uses the spring_layout approach for setting the layout.
"""
plt.figure(figsize=figsize)
# Compute the edges weights to visualize in the plot
weights = [network[ii][jj]['weight'... | 5,345,358 |
def _add_extra_kwargs(
kwargs: Dict[str, Any], extra_kwargs: Optional[Dict[str, Any]] = None
) -> Dict[str, Any]:
"""
Safely add additional keyword arguments to an existing dictionary
Parameters
----------
kwargs : dict
Keyword argument dictionary
extra_kwargs : dict, default None
... | 5,345,359 |
def Hiker(n,xLst,yLst,dist):
"""
Hiker is a function to generate lists of x and y
coordinates of n steps for a random walk of n steps
along with distance between the first and last point
"""
x0=0
y0=0
x=x0
y=y0
xLst[1] = x0
yLst[1] = y0
for i in range... | 5,345,360 |
def set_read_access_projects():
"""
Assign the list of projects (as strings of project ids) for which the user
has read access to ``flask.g.read_access_projects``.
The user has read access, firstly, to the projects for which they directly
have read permissions, and also to projects with availabilit... | 5,345,361 |
def extractdata(csvName='US_SP_Restructured.csv'):
"""
Parameters
----------
:string csvName: Name of csv file. e.g. 'US_SP_Restructured.csv'
"""
df = pd.read_csv(csvName)
df['index'] = df.index
# extract alternative specific variables
cost = pd.melt(df, id_vars=['quest', 'index'],
value_vars=['Ca... | 5,345,362 |
def fix_sentence_BIO(sentence):
"""Corrects BIO sequence errors in given Sentence by modifying
Token tag attributes.
"""
# Extract tags into format used by old fixbio functions, invoke
# fix_BIO() to do the work, and re-insert tags. Empty "sentences"
# are inored.
if not sentence.tokens:
... | 5,345,363 |
def has_field(entry: EntryType, field: str) -> bool:
"""Check if a given entry has non empty field"""
return has_data(get_field(entry, field)) | 5,345,364 |
def generate_random_fires(fire_schemas, n=100):
"""
Given a list of fire product schemas (account, loan, derivative_cash_flow,
security), generate random data and associated random relations (customer,
issuer, collateral, etc.)
TODO: add config to set number of products, min/max for dates etc.
... | 5,345,365 |
def open_file(app_id, file_name, mode):
# type: (int, str, int) -> str
""" Call to open_file.
:param app_id: Application identifier.
:param file_name: File name reference.
:param mode: Open mode.
:return: The real file name.
"""
return _COMPSs.open_file(app_id, file_name, mode) | 5,345,366 |
def get_light():
"""Get all light readings"""
try:
lux = ltr559.get_lux()
prox = ltr559.get_proximity()
LUX.set(lux)
PROXIMITY.set(prox)
except IOError:
logging.error("Could not get lux and proximity readings. Resetting i2c.")
reset_i2c() | 5,345,367 |
def _raise_error():
"""Helper function for `Trimmed` that raises an error."""
raise ValueError('Please do not call fdl.build() on a config tree with '
'Trimmed() nodes. These nodes are for visualization only.') | 5,345,368 |
def is_valid_network(name, ip_network, **kwargs):
"""Valid the format of an Ip network."""
if isinstance(ip_network, list):
return all([
is_valid_network(name, item, **kwargs) for item in ip_network
])
try:
netaddr.IPNetwork(ip_network)
except Exception:
loggi... | 5,345,369 |
def test_promise_resolved_after():
"""
The first argument to 'then' must be called when a promise is
fulfilled.
"""
c = Counter()
e = Event()
def check(v, c):
assert v == 5
e.set()
c.tick()
p1 = Promise()
p2 = p1.then(lambda v: check(v, c))
p1.do_resolv... | 5,345,370 |
def correct_repeat_line():
""" Matches repeat spec above """
return "2|1|2|3|4|5|6|7" | 5,345,371 |
def load_materials(material_dir):
"""
Load materials from a directory. We assume that the directory contains .blend
files with one material each. The file X.blend has a single NodeTree item named
X; this NodeTree item must have a "Color" input that accepts an RGBA value.
"""
for fn in os.listdir... | 5,345,372 |
async def party_bunker(ctx):
"""
Функция выводит список игроков
На вход: ctx - инфо пользователя
"""
if not users_bunker:
await ctx.send("Игроков нет")
return
content = "Список игроков:\n" + "\n".join(
[f"<@{user}>" for user in users_bunker]
)
a... | 5,345,373 |
def get_byte_range_bounds(byte_range_str: str, total_size: int) -> Tuple[int, int]:
"""Return the start and end byte of a byte range string."""
byte_range_str = byte_range_str.replace("bytes=", "")
segments = byte_range_str.split("-")
start_byte = int(segments[0])
# chrome does not send end_byte but... | 5,345,374 |
def train(cfg):
"""Trains the backbone embedding network."""
utils.set_seeds(cfg.random_seed)
if torch.cuda.is_available():
gpu_idx = utils.get_gpu_by_usage()
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_idx)
open_set_datasets = ["cars196", "stanfordonlineproducts", "cub200"]
ds = hydra.utils.instant... | 5,345,375 |
def privmsg(recipient, s, prefix='', msg=None):
"""Returns a PRIVMSG to recipient with the message msg."""
if conf.supybot.protocols.irc.strictRfc():
assert (areReceivers(recipient)), repr(recipient)
assert s, 's must not be empty.'
if minisix.PY2 and isinstance(s, unicode):
s = s.en... | 5,345,376 |
def char_decoding(value):
""" Decode from 'UTF-8' string to unicode.
:param value:
:return:
"""
if isinstance(value, bytes):
return value.decode('utf-8')
# return directly if unicode or exc happens.
return value | 5,345,377 |
def rebin_file(filename, rebin):
"""Rebin the contents of a file, be it a light curve or a spectrum."""
ftype, contents = get_file_type(filename)
do_dyn = False
if 'dyn{0}'.format(ftype) in contents.keys():
do_dyn = True
if ftype == 'lc':
x = contents['time']
y = contents['l... | 5,345,378 |
def throw_tims_error(dll_handle):
"""Raise the last thronw timsdata error as a
:exc:`RuntimeError`
"""
size = dll_handle.tims_get_last_error_string(None, 0)
buff = create_string_buffer(size)
dll_handle.tims_get_last_error_string(buff, size)
raise RuntimeError(buff.value) | 5,345,379 |
def inv2(x: np.ndarray) -> np.ndarray:
"""矩阵求逆"""
# np.matrix()废弃
return np.matrix(x).I | 5,345,380 |
def clean_remaining_artifacts(image):
"""
Method still on development. Use at own risk!
Remove remaining artifacts from image
:param image: Path to Image or 3D Matrix representing RGB image
:return: Image
"""
img, *_ = __image__(image)
blur = cv2.GaussianBlur(img, (3, 3), 0)
# conve... | 5,345,381 |
def cpplint_process(cmd, filename):
"""Has to have a special process since it just
prints sutff to stdout willy nilly"""
lint = subprocess.check_output("%s %s" % (cmd, filename), shell=True)
if "Total errors found: 0" not in lint:
logger.info("Error: %s" % lint)
sys.exit(1) | 5,345,382 |
def write_new_word(word, go):
"""
Clears the comm.log and loads a game on the turtle_gui side.
Doesn't generate gui, just preps it.
"""
hm.clear_log(True)
hm.load_game(word)
print('-'*20)
hm.gogogo()
if go != 'go':
sys.exit() | 5,345,383 |
def max_simple_dividers(a):
"""
:param a: число от 1 до 1000
:return: самый большой простой делитель числа
"""
return max(simple_dividers(a)) | 5,345,384 |
def to_light_low_sat(img, new_dims, new_scale, interp_order=1 ):
"""
Turn an image into lightness
Args:
im : (H x W x K) ndarray
new_dims : (height, width) tuple of new dimensions.
new_scale : (min, max) tuple of new scale.
interp_order : interpolation order, de... | 5,345,385 |
def test_question_load0():
"""Empty iterator.
"""
tupl = ()
quest = exam.Question()
quest.load_sequentially(iter(tupl))
assert quest.text == ""
assert quest.subject == ""
assert quest.image == Path()
assert quest.level == 0
assert quest.answers == () | 5,345,386 |
def get_slug_blacklist(lang=None, variant=None):
"""
Returns a list of KA slugs to skip when creating the channel.
Combines the "global" slug blacklist that applies for all channels, and
additional customization for specific languages or curriculum variants.
"""
SLUG_BLACKLIST = GLOBAL_SLUG_BLAC... | 5,345,387 |
def get_level_rise(station):
"""For a MonitoringStation object (station), returns a the rate of water level rise, specifically
the average value over the last 2 days"""
#Fetch data (if no data available, return None)
times, values = fetch_measure_levels(station.measure_id, timedelta(days=2))
#O... | 5,345,388 |
def get_mask_indices(path):
"""Helper function to get raster mask for NYC
Returns:
list: returns list of tuples (row, column) that represent area of interest
"""
raster = tiff_to_array(path)
indices = []
it = np.nditer(raster, flags=['multi_index'])
while not it.finished:
if i... | 5,345,389 |
def about(isin:str):
"""
Get company description.
Parameters
----------
isin : str
Desired company ISIN. ISIN must be of type EQUITY or BOND, see instrument_information() -> instrumentTypeKey
Returns
-------
TYPE
Dict with description.
"""
params = {'isin': is... | 5,345,390 |
def test_set_cookie_with_cookiejar() -> None:
"""
Send a request including a cookie, using a `CookieJar` instance.
"""
url = "http://example.org/echo_cookies"
cookies = CookieJar()
cookie = Cookie(
version=0,
name="example-name",
value="example-value",
port=None,... | 5,345,391 |
def aesEncrypt(message):
"""
Encrypts a message with a fresh key using AES-GCM.
Returns: (key, ciphertext)
"""
key = get_random_bytes(symmetricKeySizeBytes)
cipher = AES.new(key, AES.MODE_GCM)
ctext, tag = cipher.encrypt_and_digest(message)
# Concatenate (nonce, tag, ctext) and return ... | 5,345,392 |
def pyro_nameserver(host=None,
port=None,
auto_clean=0,
auto_start=False):
"""Runs a Pyro name server.
The name server must be running in order to use distributed cameras with POCS. The name server
should be started before starting camera servers ... | 5,345,393 |
def _get_library_path() -> str:
"""Find library path for compiled IK fast libraries.
Look for sub-package 'linux_so', or '.reach/third_party/ikfast/linux-so'
Only supports Linux "so" file.
Returns:
Library path.
"""
if _is_running_on_google3:
return "./"
current_folder = os.path.dirname(os.pat... | 5,345,394 |
def view_img(
stat_map_img,
bg_img="MNI152",
cut_coords=None,
colorbar=True,
title=None,
threshold=1e-6,
annotate=True,
draw_cross=True,
black_bg="auto",
cmap=cm.cold_hot,
symmetric_cmap=True,
dim="auto",
vmax=None,
vmin=None,
resampling_interpolation="continu... | 5,345,395 |
async def test_fire_event_sensor(hass):
"""Test fire event."""
await async_setup_component(
hass,
"rfxtrx",
{
"rfxtrx": {
"device": "/dev/serial/by-id/usb"
+ "-RFXCOM_RFXtrx433_A1Y0NJGR-if00-port0",
"dummy": True,
... | 5,345,396 |
def getType(o):
"""There could be only return o.__class__.__name__"""
if isinstance(o, LispObj):
return o.type
return o.__class__.__name__ | 5,345,397 |
def cli(ctx, opt_input, opt_output):
"""Convert VFRAME JSON to CVAT XML"""
# ------------------------------------------------
# imports
from os.path import join
from vframe.utils import file_utils
from vframe.settings import app_cfg
from vframe.models.pipe_item import PipeContextHeader
# -----------... | 5,345,398 |
def cr2_to_pgm(
cr2_fname,
pgm_fname=None,
overwrite=True, *args,
**kwargs): # pragma: no cover
""" Convert CR2 file to PGM
Converts a raw Canon CR2 file to a netpbm PGM file via `dcraw`. Assumes
`dcraw` is installed on the system
Note:
This is a blocking call
... | 5,345,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.