max_stars_repo_path
stringlengths 4
245
| max_stars_repo_name
stringlengths 7
115
| max_stars_count
int64 101
368k
| id
stringlengths 2
8
| content
stringlengths 6
1.03M
|
---|---|---|---|---|
hail/python/test/hail/expr/test_functions.py | tdeboer-ilmn/hail | 789 | 12605287 | import hail as hl
import scipy.stats as spst
import pytest
def test_deprecated_binom_test():
assert hl.eval(hl.binom_test(2, 10, 0.5, 'two.sided')) == \
pytest.approx(spst.binom_test(2, 10, 0.5, 'two-sided'))
def test_binom_test():
arglists = [[2, 10, 0.5, 'two-sided'],
[4, 10, 0.5, 'less'],
[32, 50, 0.4, 'greater']]
for args in arglists:
assert hl.eval(hl.binom_test(*args)) == pytest.approx(spst.binom_test(*args)), args
def test_pchisqtail():
def right_tail_from_scipy(x, df, ncp):
if ncp:
return 1 - spst.ncx2.cdf(x, df, ncp)
else:
return 1 - spst.chi2.cdf(x, df)
arglists = [[3, 1, 2],
[5, 1, None],
[1, 3, 4],
[1, 3, None],
[3, 6, 0],
[3, 6, None]]
for args in arglists:
assert hl.eval(hl.pchisqtail(*args)) == pytest.approx(right_tail_from_scipy(*args)), args
def test_shuffle():
assert set(hl.eval(hl.shuffle(hl.range(5)))) == set(range(5))
|
ltr/helpers/ranklib_result.py | tanjie123/hello-ltr | 109 | 12605296 |
import re
class RanklibResult:
""" A result of ranklib training, either for a
single training operation
(where trainingLogs is just set, and has a single item)
or k-folds cross validation
(where the foldResults/kcv are set; with a result for
each fold that is run """
def __init__(self, trainingLogs, foldResults,
kcvTestAvg, kcvTrainAvg):
self.trainingLogs = trainingLogs
self.foldResults = foldResults
self.kcvTrainAvg = kcvTrainAvg
self.kcvTestAvg = kcvTestAvg
class TrainingLog:
def __init__(self, rounds, impacts, trainMetricName, trainMetricVal):
self.impacts = impacts
self.rounds = rounds
self.trainMetricName = trainMetricName
self.trainMetricVal = trainMetricVal
def metric(self):
if self.trainMetricName is not None:
return self.trainMetricVal
if len(self.rounds) > 0:
return self.rounds[-1]
else:
return 0
class FoldResult:
def __init__(self, foldId, trainMetric, testMetric):
self.foldNum = foldId
self.trainMetric = trainMetric
self.testMetric = testMetric
impactRe = re.compile(' Feature (\d+) reduced error (.*)')
roundsRe = re.compile('(\d+)\s+\| (\d+)')
foldsRe = re.compile('^Fold (\d+)\s+\|(.*)\|(.*)')
avgRe = re.compile('^Avg.\s+\|(.*)\|(.*)')
trainMetricRe = re.compile('(.*@.*) on training data: (.*)')
def parse_training_log(rawResult):
""" Takes raw result from Ranklib training and
gathers the feature impacts, training rounds,
and any cross-validation information """
lines = rawResult.split('\n')
# Fold 1 | 0.9396 | 0.8764
train = False
logs = []
folds = []
impacts = {}
rounds = []
trainMetricName = None
trainMetricVal = 0.0
kcvTestAvg = kcvTrainAvg = None
for line in lines:
if 'Training starts...' in line:
if train:
log = TrainingLog(rounds=rounds,
impacts=impacts,
trainMetricName=trainMetricName,
trainMetricVal=trainMetricVal)
logs.append(log)
impacts = {}
rounds = []
train = True
if train:
m = re.match(impactRe, line)
if m:
ftrId = m.group(1)
error = float(m.group(2))
impacts[ftrId] = error
m = re.match(roundsRe, line)
if m:
values = line.split('|')
metricTrain = float(values[1])
rounds.append(metricTrain)
m = re.match(trainMetricRe, line)
if m:
trainMetricVal = float(m.group(2))
trainMetricName = m.group(1)
m = re.match(foldsRe, line)
if m:
foldId = m.group(1)
trainMetric = float(m.group(2))
testMetric = float(m.group(3))
folds.append(FoldResult(foldId=foldId,
testMetric=testMetric,
trainMetric=trainMetric))
m = re.match(avgRe, line)
if m:
kcvTrainAvg = float(m.group(1))
kcvTestAvg = float(m.group(2))
if train:
log = TrainingLog(rounds=rounds,
impacts=impacts,
trainMetricName=trainMetricName,
trainMetricVal=trainMetricVal)
logs.append(log)
return RanklibResult(trainingLogs=logs,
foldResults=folds,
kcvTrainAvg=kcvTrainAvg,
kcvTestAvg=kcvTestAvg)
|
tools/compute_bottleneck.py | agarwalutkarsh554/dataset | 4,359 | 12605309 | #!/usr/bin/env python
#
# Copyright 2016 The Open Images Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
#
# This script takes an Inception v3 checkpoint, runs the classifier
# on the image and prints the values from the bottleneck layer.
# Example:
# $ wget -O /tmp/cat.jpg https://farm6.staticflickr.com/5470/9372235876_d7d69f1790_b.jpg
# $ ./tools/compute_bottleneck.py /tmp/cat.jpg
#
# Make sure to download the ANN weights and support data with:
# $ ./tools/download_data.sh
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import math
import sys
import os.path
import numpy as np
import tensorflow as tf
from tensorflow.contrib.slim.python.slim.nets import inception
from tensorflow.python.framework import ops
from tensorflow.python.training import saver as tf_saver
from tensorflow.python.training import supervisor
slim = tf.contrib.slim
FLAGS = None
def PreprocessImage(image_path, central_fraction=0.875):
"""Load and preprocess an image.
Args:
image_path: path to an image
central_fraction: do a central crop with the specified
fraction of image covered.
Returns:
An ops.Tensor that produces the preprocessed image.
"""
if not os.path.exists(image_path):
tf.logging.fatal('Input image does not exist %s', image_path)
img_data = tf.gfile.FastGFile(image_path).read()
# Decode Jpeg data and convert to float.
img = tf.cast(tf.image.decode_jpeg(img_data, channels=3), tf.float32)
img = tf.image.central_crop(img, central_fraction=central_fraction)
# Make into a 4D tensor by setting a 'batch size' of 1.
img = tf.expand_dims(img, [0])
img = tf.image.resize_bilinear(img,
[FLAGS.image_size, FLAGS.image_size],
align_corners=False)
# Center the image about 128.0 (which is done during training) and normalize.
img = tf.multiply(img, 1.0/127.5)
return tf.subtract(img, 1.0)
def main(args):
if not os.path.exists(FLAGS.checkpoint):
tf.logging.fatal(
'Checkpoint %s does not exist. Have you download it? See tools/download_data.sh',
FLAGS.checkpoint)
g = tf.Graph()
with g.as_default():
input_image = PreprocessImage(FLAGS.image_path[0])
with slim.arg_scope(inception.inception_v3_arg_scope()):
logits, end_points = inception.inception_v3(
input_image, num_classes=FLAGS.num_classes, is_training=False)
bottleneck = end_points['PreLogits']
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer(),
tf.tables_initializer())
saver = tf_saver.Saver()
sess = tf.Session()
saver.restore(sess, FLAGS.checkpoint)
# Run the evaluation on the image
bottleneck_eval = np.squeeze(sess.run(bottleneck))
first = True
for val in bottleneck_eval:
if not first:
sys.stdout.write(",")
first = False
sys.stdout.write('{:.3f}'.format(val))
sys.stdout.write('\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--checkpoint', type=str, default='data/2016_08/model.ckpt',
help='Checkpoint to run inference on.')
parser.add_argument('--image_size', type=int, default=299,
help='Image size to run inference on.')
parser.add_argument('--num_classes', type=int, default=6012,
help='Number of output classes.')
parser.add_argument('image_path', nargs=1, default='')
FLAGS = parser.parse_args()
tf.app.run()
|
singleton__using_abc.py | DazEB2/SimplePyScripts | 117 | 12605326 | <filename>singleton__using_abc.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
# SOURCE: https://stackoverflow.com/a/39186313/5909792
from abc import ABC
def singleton(real_cls):
class SingletonFactory(ABC):
instance = None
def __new__(cls, *args, **kwargs):
if not cls.instance:
cls.instance = real_cls(*args, **kwargs)
return cls.instance
SingletonFactory.register(real_cls)
return SingletonFactory
if __name__ == '__main__':
@singleton
class MyClass:
pass
x1 = MyClass()
x2 = MyClass()
x3 = MyClass()
print(id(x1), id(x2), id(x3), id(MyClass.instance))
assert id(x1) == id(x2) == id(x3) == id(MyClass.instance)
|
bambi/priors/__init__.py | yannmclatchie/bambi | 793 | 12605338 | <gh_stars>100-1000
"""Classes to represent prior distributions and methods to set automatic priors"""
from .prior import Prior
from .scaler_mle import PriorScalerMLE
from .scaler_default import PriorScaler
__all__ = [
"Prior",
"PriorScaler",
"PriorScalerMLE",
]
|
toad/nn/trainer/history_test.py | brianWeng0223/toad | 325 | 12605387 | import torch
import numpy as np
from .history import History
def test_history_log():
history = History()
for i in range(10):
history.log('tensor', torch.rand(3, 5))
assert history['tensor'].shape == (30, 5)
|
tests/test_timeline_clock.py | rvega/isobar | 241 | 12605397 | <reponame>rvega/isobar<filename>tests/test_timeline_clock.py<gh_stars>100-1000
""" Unit tests for isobar """
import isobar as iso
import pytest
import time
def test_timeline_clock_accuracy():
#--------------------------------------------------------------------------------
# 480 ticks per beat @ 125bpm = 1 tick per 1ms
#--------------------------------------------------------------------------------
timeline = iso.Timeline(125, output_device=iso.DummyOutputDevice())
timeline.stop_when_done = True
timeline.ticks_per_beat = 480
timeline.event_times = []
timeline.schedule({
iso.EVENT_ACTION: lambda: timeline.event_times.append(time.time()),
iso.EVENT_DURATION: iso.PSequence([ 0.001 ], 50)
})
timeline.run()
#--------------------------------------------------------------------------------
# Check that timing is accurate to +/- 1ms
#--------------------------------------------------------------------------------
for index, t in enumerate(timeline.event_times[:-1]):
dt = timeline.event_times[index + 1] - t
assert 0.0002 < dt < 0.002
@pytest.mark.parametrize("ticks_per_beat", [ 24, 96, 480 ])
def test_timeline_ticks_per_beat(ticks_per_beat):
#--------------------------------------------------------------------------------
# Schedule a single event
#--------------------------------------------------------------------------------
delay_time = 0.1
timeline = iso.Timeline(120, output_device=iso.DummyOutputDevice())
timeline.stop_when_done = True
timeline.ticks_per_beat = ticks_per_beat
timeline.event_times = []
timeline.schedule({
iso.EVENT_ACTION: lambda: timeline.event_times.append(time.time()),
iso.EVENT_DURATION: iso.PSequence([ timeline.seconds_to_beats(delay_time) ], 2)
})
timeline.run()
for index, t in enumerate(timeline.event_times[:-1]):
dt = timeline.event_times[index + 1] - t
assert (delay_time * 0.95) < dt < (delay_time * 1.05)
def test_timeline_clock_midi_sync_out():
pass
def test_timeline_clock_midi_sync_in():
pass
|
tools/third_party/html5lib/html5lib/tests/test_encoding.py | meyerweb/wpt | 2,479 | 12605466 | <filename>tools/third_party/html5lib/html5lib/tests/test_encoding.py
from __future__ import absolute_import, division, unicode_literals
import os
import pytest
from .support import get_data_files, test_dir, errorMessage, TestData as _TestData
from html5lib import HTMLParser, _inputstream
def test_basic_prescan_length():
data = "<title>Caf\u00E9</title><!--a--><meta charset='utf-8'>".encode('utf-8')
pad = 1024 - len(data) + 1
data = data.replace(b"-a-", b"-" + (b"a" * pad) + b"-")
assert len(data) == 1024 # Sanity
stream = _inputstream.HTMLBinaryInputStream(data, useChardet=False)
assert 'utf-8' == stream.charEncoding[0].name
def test_parser_reparse():
data = "<title>Caf\u00E9</title><!--a--><meta charset='utf-8'>".encode('utf-8')
pad = 10240 - len(data) + 1
data = data.replace(b"-a-", b"-" + (b"a" * pad) + b"-")
assert len(data) == 10240 # Sanity
stream = _inputstream.HTMLBinaryInputStream(data, useChardet=False)
assert 'windows-1252' == stream.charEncoding[0].name
p = HTMLParser(namespaceHTMLElements=False)
doc = p.parse(data, useChardet=False)
assert 'utf-8' == p.documentEncoding
assert doc.find(".//title").text == "Caf\u00E9"
@pytest.mark.parametrize("expected,data,kwargs", [
("utf-16le", b"\xFF\xFE", {"override_encoding": "iso-8859-2"}),
("utf-16be", b"\xFE\xFF", {"override_encoding": "iso-8859-2"}),
("utf-8", b"\xEF\xBB\xBF", {"override_encoding": "iso-8859-2"}),
("iso-8859-2", b"", {"override_encoding": "iso-8859-2", "transport_encoding": "iso-8859-3"}),
("iso-8859-2", b"<meta charset=iso-8859-3>", {"transport_encoding": "iso-8859-2"}),
("iso-8859-2", b"<meta charset=iso-8859-2>", {"same_origin_parent_encoding": "iso-8859-3"}),
("iso-8859-2", b"", {"same_origin_parent_encoding": "iso-8859-2", "likely_encoding": "iso-8859-3"}),
("iso-8859-2", b"", {"same_origin_parent_encoding": "utf-16", "likely_encoding": "iso-8859-2"}),
("iso-8859-2", b"", {"same_origin_parent_encoding": "utf-16be", "likely_encoding": "iso-8859-2"}),
("iso-8859-2", b"", {"same_origin_parent_encoding": "utf-16le", "likely_encoding": "iso-8859-2"}),
("iso-8859-2", b"", {"likely_encoding": "iso-8859-2", "default_encoding": "iso-8859-3"}),
("iso-8859-2", b"", {"default_encoding": "iso-8859-2"}),
("windows-1252", b"", {"default_encoding": "totally-bogus-string"}),
("windows-1252", b"", {}),
])
def test_parser_args(expected, data, kwargs):
stream = _inputstream.HTMLBinaryInputStream(data, useChardet=False, **kwargs)
assert expected == stream.charEncoding[0].name
p = HTMLParser()
p.parse(data, useChardet=False, **kwargs)
assert expected == p.documentEncoding
@pytest.mark.parametrize("kwargs", [
{"override_encoding": "iso-8859-2"},
{"override_encoding": None},
{"transport_encoding": "iso-8859-2"},
{"transport_encoding": None},
{"same_origin_parent_encoding": "iso-8859-2"},
{"same_origin_parent_encoding": None},
{"likely_encoding": "iso-8859-2"},
{"likely_encoding": None},
{"default_encoding": "iso-8859-2"},
{"default_encoding": None},
{"foo_encoding": "iso-8859-2"},
{"foo_encoding": None},
])
def test_parser_args_raises(kwargs):
with pytest.raises(TypeError) as exc_info:
p = HTMLParser()
p.parse("", useChardet=False, **kwargs)
assert exc_info.value.args[0].startswith("Cannot set an encoding with a unicode input")
def param_encoding():
for filename in get_data_files("encoding"):
tests = _TestData(filename, b"data", encoding=None)
for test in tests:
yield test[b'data'], test[b'encoding']
@pytest.mark.parametrize("data, encoding", param_encoding())
def test_parser_encoding(data, encoding):
p = HTMLParser()
assert p.documentEncoding is None
p.parse(data, useChardet=False)
encoding = encoding.lower().decode("ascii")
assert encoding == p.documentEncoding, errorMessage(data, encoding, p.documentEncoding)
@pytest.mark.parametrize("data, encoding", param_encoding())
def test_prescan_encoding(data, encoding):
stream = _inputstream.HTMLBinaryInputStream(data, useChardet=False)
encoding = encoding.lower().decode("ascii")
# Very crude way to ignore irrelevant tests
if len(data) > stream.numBytesMeta:
return
assert encoding == stream.charEncoding[0].name, errorMessage(data, encoding, stream.charEncoding[0].name)
# pylint:disable=wrong-import-position
try:
import chardet # noqa
except ImportError:
print("chardet not found, skipping chardet tests")
else:
def test_chardet():
with open(os.path.join(test_dir, "encoding", "chardet", "test_big5.txt"), "rb") as fp:
encoding = _inputstream.HTMLInputStream(fp.read()).charEncoding
assert encoding[0].name == "big5"
# pylint:enable=wrong-import-position
|
kivymd/tools/packaging/pyinstaller/__init__.py | ibrahimcetin/KivyMD | 1,111 | 12605478 | <gh_stars>1000+
"""
PyInstaller hooks
=================
Add ``hookspath=[kivymd.hooks_path]`` to your .spec file.
Example of .spec file
=====================
.. code-block:: python
# -*- mode: python ; coding: utf-8 -*-
import sys
import os
from kivy_deps import sdl2, glew
from kivymd import hooks_path as kivymd_hooks_path
path = os.path.abspath(".")
a = Analysis(
["main.py"],
pathex=[path],
hookspath=[kivymd_hooks_path],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=None,
noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=None)
exe = EXE(
pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)],
debug=False,
strip=False,
upx=True,
name="app_name",
console=True,
)
"""
__all__ = ("hooks_path", "get_hook_dirs", "get_pyinstaller_tests")
import os
from pathlib import Path
import kivymd
hooks_path = str(Path(__file__).absolute().parent)
"""Path to hook directory to use with PyInstaller.
See :mod:`kivymd.tools.packaging.pyinstaller` for more information."""
def get_hook_dirs():
return [hooks_path]
def get_pyinstaller_tests():
return [os.path.join(kivymd.path, "tests", "pyinstaller")]
if __name__ == "__main__":
print(hooks_path)
print(get_hook_dirs())
print(get_pyinstaller_tests())
|
flametree/DiskFileManager.py | Edinburgh-Genome-Foundry/Flametree | 165 | 12605483 | import os
import shutil
class DiskFileManager:
"""Reader and Writer for disk files.
target
A directory on the disk. If it doesn't exist, it will be created.
replace
If the ``target`` directory exists, should it be completely replaced
or simply appended to ?
"""
def __init__(self, target, replace=False):
self.target = target
if replace and os.path.exists(target):
shutil.rmtree(target)
if not os.path.exists(target):
os.makedirs(target)
@staticmethod
def list_directory_content(directory, element_type="file"):
"""Return the list of all file or dir objects in the directory."""
filtr = os.path.isfile if (element_type == "file") else os.path.isdir
path = directory._path
return (
[]
if not os.path.exists(path)
else [name for name in os.listdir(path) if filtr(os.path.join(path, name))]
)
@classmethod
def list_files(cls, directory):
"""Return the list of all file objects in the directory."""
return cls.list_directory_content(directory, element_type="file")
@classmethod
def list_dirs(cls, directory):
"""Return the list of all directory objects in the directory."""
return cls.list_directory_content(directory, element_type="dirs")
@staticmethod
def read(fileobject, mode="r"):
"""Return the entire content of a file. The mode can be 'r' or 'rb'."""
with open(fileobject._path, mode=mode) as f:
result = f.read()
return result
@staticmethod
def write(fileobject, content, mode="a"):
"""Write the content (str, bytes) to the given file object."""
with open(fileobject._path, mode=mode) as f:
f.write(content)
@staticmethod
def delete(target):
"""Delete the file on disk."""
if target._is_dir:
shutil.rmtree(target._path)
else:
os.remove(target._path)
def create(self, target, replace=False):
"""Create a new, empty file or directory on disk."""
path = target._path
if replace and os.path.exists(path):
self.delete(target)
if replace or (not os.path.exists(path)):
if target._is_dir:
os.mkdir(path)
else:
with open(path, "w") as f:
pass
@staticmethod
def join_paths(*paths):
"""Join paths in a system/independent way -- actually os.path.join."""
return os.path.join(*paths)
@staticmethod
def close():
"""This method does nothing for DiskFileManagers."""
pass
def open(self, fileobject, mode="a"):
"""Open a file on disk at the location given by the file object."""
return open(fileobject._path, mode=mode)
|
pymagnitude/third_party/allennlp/modules/seq2seq_encoders/pass_through_encoder.py | tpeng/magnitude | 1,520 | 12605487 | <filename>pymagnitude/third_party/allennlp/modules/seq2seq_encoders/pass_through_encoder.py
from __future__ import absolute_import
#overrides
import torch
from allennlp.modules.seq2seq_encoders.seq2seq_encoder import Seq2SeqEncoder
class PassThroughEncoder(Seq2SeqEncoder):
u"""
This class allows you to specify skipping a ``Seq2SeqEncoder`` just
by changing a configuration file. This is useful for ablations and
measuring the impact of different elements of your model.
"""
def __init__(self, input_dim ) :
super(PassThroughEncoder, self).__init__()
self._input_dim = input_dim
#overrides
def get_input_dim(self) :
return self._input_dim
#overrides
def get_output_dim(self) :
return self._input_dim
#overrides
def is_bidirectional(self):
return False
#overrides
def forward(self, # pylint: disable=arguments-differ
inputs ,
mask = None) :
# pylint: disable=unused-argument
return inputs
PassThroughEncoder = Seq2SeqEncoder.register(u"pass_through")(PassThroughEncoder)
|
django/contrib/messages/storage/__init__.py | pomarec/django | 285 | 12605520 | from django.conf import settings
from django.utils.module_loading import import_by_path as get_storage
# Callable with the same interface as the storage classes i.e. accepts a
# 'request' object. It is wrapped in a lambda to stop 'settings' being used at
# the module level
default_storage = lambda request: get_storage(settings.MESSAGE_STORAGE)(request)
|
recipes/Python/456362_relative_import_shortcut/recipe-456362.py | tdiprima/code | 2,023 | 12605543 | import os
import sys
def pythonImport(name):
current_path = os.path.dirname(os.path.abspath(__file__))
base_name = os.path.basename(current_path).split('.')[0]
sys.path[:] = [path for path in sys.path
if os.path.abspath(path) != os.path.abspath(current_path)]
original_module = sys.modules[name]
del sys.modules[name]
python_module = __import__(name)
python_module_name = 'python_%s' % name
sys.modules[python_module_name] = python_module
sys.path.append(current_path)
sys.modules[name] = original_module
return python_module_name, python_module
|
Chapter09/image_scope_demo.py | kennartfoundation/flask_10 | 173 | 12605545 | import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
tk.Label(self, image=tk.PhotoImage(file='smile.gif')).pack()
smile = tk.PhotoImage(file='smile.gif')
tk.Label(self, image=smile).pack()
self.smile = tk.PhotoImage(file='smile.gif')
tk.Label(self, image=self.smile).pack()
App().mainloop()
|
cfgov/v1/management/commands/sync_image_storage.py | Colin-Seifer/consumerfinance.gov | 156 | 12605623 | from django.core.management.base import BaseCommand
from wagtail.images import get_image_model
from ._sync_storage_base import SyncStorageCommandMixin
class Command(SyncStorageCommandMixin, BaseCommand):
def get_storage_directories(self):
return ["images", "original_images"]
def get_queryset(self):
return get_image_model().objects.all()
def handle_instance(self, instance, log_prefix):
super().handle_instance(instance, log_prefix)
renditions = instance.renditions.all()
rendition_count = renditions.count()
for j, rendition in enumerate(renditions):
rendition_prefix = "%d/%d (%d) " % (
j + 1,
rendition_count,
rendition.pk,
)
self.stdout.write(log_prefix + rendition_prefix, ending="")
self.save(rendition.file.name)
|
mmwave/tracking/gtrack_unit.py | gimac/OpenRadar | 275 | 12605634 | import numpy as np
import copy
from . import ekf_utils
gtrack_MIN_DISPERSION_ALPHA = 0.1
gtrack_EST_POINTS = 10
gtrack_MIN_POINTS_TO_UPDATE_DISPERSION = 3
gtrack_KNOWN_TARGET_POINTS_THRESHOLD = 50
# GTRACK Module calls this function to instantiate GTRACK Unit with desired configuration parameters.
# Function returns a handle, which is used my module to call units' methods
def unit_create(params):
inst = ekf_utils.GtrackUnitInstance()
inst.gatingParams = params.gatingParams
inst.stateParams = params.stateParams
inst.allocationParams = params.allocationParams
inst.unrollingParams = params.unrollingParams
inst.variationParams = params.variationParams
inst.sceneryParams = params.sceneryParams
inst.uid = params.uid
inst.maxAcceleration = params.maxAcceleration
inst.maxRadialVelocity = params.maxRadialVelocity
inst.radialVelocityResolution = params.radialVelocityResolution
inst.verbose = params.verbose
inst.initialRadialVelocity = params.initialRadialVelocity
inst.F4 = params.F4
inst.Q4 = params.Q4
inst.F6 = params.F6
inst.Q6 = params.Q6
if params.stateVectorType == ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DA:
inst.stateVectorType = ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DA
inst.stateVectorLength = 6
inst.measurementVectorLength = 3
else:
raise ValueError('not supported, unit_create')
inst.dt = params.deltaT
inst.state = ekf_utils.TrackState().TRACK_STATE_FREE
return inst
# GTRACK Module calls this function to run GTRACK unit prediction step
def unit_predict(handle):
inst = handle
inst.heartBeatCount += 1
temp1 = np.zeros(shape=(36,), dtype=np.float32)
temp2 = np.zeros(shape=(36,), dtype=np.float32)
temp3 = np.zeros(shape=(36,), dtype=np.float32)
# Current state vector length
sLen = inst.stateVectorLength
if inst.processVariance != 0:
inst.S_apriori_hat = ekf_utils.gtrack_matrixMultiply(sLen, sLen, 1, inst.F, inst.S_hat)
temp1 = ekf_utils.gtrack_matrixMultiply(6, 6, 6, inst.F, inst.P_hat)
temp2 = ekf_utils.gtrack_matrixTransposeMultiply(6, 6, 6, temp1, inst.F)
temp1 = ekf_utils.gtrack_matrixScalerMultiply(sLen, sLen, inst.Q, inst.processVariance)
temp3 = ekf_utils.gtrack_matrixAdd(sLen, sLen, temp1, temp2)
inst.P_apriori_hat = ekf_utils.gtrack_matrixMakeSymmetrical(sLen, temp3)
else:
inst.S_apriori_hat = copy.deepcopy(inst.S_hat)
inst.P_apriori_hat = copy.deepcopy(inst.P_hat)
ekf_utils.gtrack_cartesian2spherical(inst.stateVectorType, inst.S_apriori_hat, inst.H_s)
# GTRACK Module calls this function to obtain the measurement vector scoring from the GTRACK unit perspective
def unit_score(handle, point, best_score, best_ind, num):
limits = np.zeros(shape=(3,), dtype=np.float32)
u_tilda = np.zeros(shape=(3,), dtype=np.float32)
inst = handle
limits[0] = inst.gatingParams.limits[0].length
limits[1] = inst.gatingParams.limits[0].width
limits[2] = inst.gatingParams.limits[0].vel
if inst.processVariance == 0:
inst.G = 1
else:
inst.G = ekf_utils.gtrack_gateCreateLim(inst.gatingParams.volume, inst.gC_inv, inst.H_s[0], limits)
det = ekf_utils.gtrack_matrixDet3(inst.gC)
log_det = np.float32(np.log(det))
for n in range(num):
if best_ind[n] == ekf_utils.gtrack_ID_POINT_BEHIND_THE_WALL:
continue
u_tilda[0] = np.float32(point[n].range - inst.H_s[0])
u_tilda[1] = np.float32(point[n].angle - inst.H_s[1])
if inst.velocityHandling < ekf_utils.VelocityHandlingState().VELOCITY_LOCKED:
# Radial velocity estimation is not yet known, unroll based on velocity measured at allocation time
rv_out = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.allocationVelocity,
point[n].doppler)
u_tilda[2] = np.float32(rv_out - inst.allocationVelocity)
else:
# Radial velocity estimation is known
rv_out = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.H_s[2], point[n].doppler)
u_tilda[2] = np.float32(rv_out - inst.H_s[2])
chi2 = ekf_utils.gtrack_computeMahalanobis3(u_tilda, inst.gC_inv)
# print(inst.gC_inv)
if chi2 < inst.G:
score = np.float32(log_det + chi2)
if score < best_score[n]:
best_score[n] = score
best_ind[n] = np.uint8(inst.uid)
point[n].doppler = rv_out
# GTRACK Module calls this function to start target tracking. This function is called during modules' allocation step,
# once new set of points passes allocation thresholds
def unit_start(handle, time_stamp, tid, um):
inst = handle
m = np.zeros(shape=(3,), dtype=np.float32)
inst.tid = tid
inst.heartBeatCount = time_stamp
inst.allocationTime = time_stamp
inst.allocationRange = um[0]
inst.allocationVelocity = um[2]
inst.associatedPoints = 0
inst.state = ekf_utils.TrackState().TRACK_STATE_DETECTION
inst.currentStateVectorType = ekf_utils.gtrack_STATE_VECTOR_TYPE().gtrack_STATE_VECTORS_2DA
inst.stateVectorLength = 6
inst.processVariance = (0.5 * inst.maxAcceleration) * (0.5 * inst.maxAcceleration)
inst.F = inst.F6
inst.Q = inst.Q6
inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_INIT
m[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.initialRadialVelocity, um[2])
inst.rangeRate = m[2]
m[0] = um[0]
m[1] = um[1]
ekf_utils.gtrack_spherical2cartesian(inst.currentStateVectorType, m, inst.S_apriori_hat)
inst.H_s = copy.deepcopy(m)
inst.P_apriori_hat = copy.deepcopy(ekf_utils.pinit6x6)
inst.gD = copy.deepcopy(ekf_utils.zero3x3)
inst.G = 1.
# GTRACK Module calls this function to perform an update step for the tracking unit.
def unit_update(handle, point, var, pInd, num):
J = np.zeros(shape=(18,), dtype=np.float32) # 3x6
PJ = np.zeros(shape=(18,), dtype=np.float32) # 6x3
JPJ = np.zeros(shape=(9,), dtype=np.float32) # 3x3
U = np.zeros(shape=(3,), dtype=np.float32)
u_tilda = np.zeros(shape=(3,), dtype=np.float32)
cC = np.zeros(shape=(9,), dtype=np.float32)
cC_inv = np.zeros(shape=(9,), dtype=np.float32)
K = np.zeros(shape=(18,), dtype=np.float32) # 6x3
u_mean = ekf_utils.gtrack_measurementPoint()
D = np.zeros(shape=(9,), dtype=np.float32)
Rm = np.zeros(shape=(9,), dtype=np.float32)
Rc = np.zeros(shape=(9,), dtype=np.float32)
temp1 = np.zeros(shape=(36,), dtype=np.float32)
inst = handle
mlen = inst.measurementVectorLength
slen = inst.stateVectorLength
myPointNum = 0
for n in range(num):
if pInd[n] == inst.uid:
myPointNum += 1
u_mean.range += point[n].range
u_mean.angle += point[n].angle
if var != None:
Rm[0] += var[n].rangeVar
Rm[4] += var[n].angleVar
Rm[8] += var[n].dopplerVar
if myPointNum == 1:
rvPilot = point[n].doppler
u_mean.doppler = rvPilot
else:
rvCurrent = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, rvPilot, point[n].doppler)
point[n].doppler = rvCurrent
u_mean.doppler += rvCurrent
if myPointNum == 0:
# INACTIVE
if (np.abs(inst.S_hat[2]) < inst.radialVelocityResolution) and \
(np.abs(inst.S_hat[3]) < inst.radialVelocityResolution):
inst.S_hat = np.zeros(shape=(inst.S_hat.shape), dtype=np.float32)
inst.S_hat[0] = inst.S_apriori_hat[0]
inst.S_hat[1] = inst.S_apriori_hat[1]
inst.P_hat = copy.deepcopy(inst.P_apriori_hat)
inst.processVariance = 0
else:
inst.S_hat = copy.deepcopy(inst.S_apriori_hat)
inst.P_hat = copy.deepcopy(inst.P_apriori_hat)
unit_event(inst, myPointNum)
return inst.state
inst.associatedPoints += myPointNum
if inst.processVariance == 0:
inst.processVariance = np.float32((0.5 * (inst.maxAcceleration)) * (0.5 * (inst.maxAcceleration)))
u_mean.range = np.float32(u_mean.range / myPointNum)
u_mean.angle = np.float32(u_mean.angle / myPointNum)
u_mean.doppler = np.float32(u_mean.doppler / myPointNum)
if var != None:
Rm[0] = np.float32(Rm[0] / myPointNum)
Rm[4] = np.float32(Rm[4] / myPointNum)
Rm[8] = np.float32(Rm[8] / myPointNum)
else:
dRangeVar = np.float32((inst.variationParams.lengthStd) * (inst.variationParams.lengthStd))
dDopplerVar = np.float32((inst.variationParams.dopplerStd) * (inst.variationParams.dopplerStd))
Rm[0] = dRangeVar
angleStd = np.float32(2 * np.float32(np.arctan(0.5 * (inst.variationParams.widthStd) / inst.H_s[0])))
Rm[4] = angleStd * angleStd
Rm[8] = dDopplerVar
U[0] = u_mean.range
U[1] = u_mean.angle
U[2] = u_mean.doppler
velocity_state_handling(inst, U)
if myPointNum > gtrack_MIN_POINTS_TO_UPDATE_DISPERSION:
for n in range(num):
if pInd[n] == inst.uid:
D[0] += np.float32((point[n].range - u_mean.range) * (point[n].range - u_mean.range))
D[4] += np.float32((point[n].angle - u_mean.angle) * (point[n].angle - u_mean.angle))
D[8] += np.float32((point[n].doppler - u_mean.doppler) * (point[n].doppler - u_mean.doppler))
D[1] += np.float32((point[n].range - u_mean.range) * (point[n].angle - u_mean.angle))
D[2] += np.float32((point[n].range - u_mean.range) * (point[n].doppler - u_mean.doppler))
D[5] += np.float32((point[n].angle - u_mean.angle) * (point[n].doppler - u_mean.doppler))
D[0] = np.float32(D[0] / myPointNum)
D[4] = np.float32(D[4] / myPointNum)
D[8] = np.float32(D[8] / myPointNum)
D[1] = np.float32(D[1] / myPointNum)
D[2] = np.float32(D[2] / myPointNum)
D[5] = np.float32(D[5] / myPointNum)
alpha = np.float32(myPointNum / (inst.associatedPoints))
# print(alpha)
if alpha < gtrack_MIN_DISPERSION_ALPHA:
alpha = gtrack_MIN_DISPERSION_ALPHA
inst.gD[0] = np.float32((1. - alpha) * inst.gD[0] + alpha * D[0])
inst.gD[1] = np.float32((1. - alpha) * inst.gD[1] + alpha * D[1])
inst.gD[2] = np.float32((1. - alpha) * inst.gD[2] + alpha * D[2])
inst.gD[3] = np.float32(inst.gD[1])
inst.gD[4] = np.float32((1. - alpha) * inst.gD[4] + alpha * D[4])
inst.gD[5] = np.float32((1. - alpha) * inst.gD[5] + alpha * D[5])
inst.gD[6] = np.float32(inst.gD[2])
inst.gD[7] = np.float32(inst.gD[5])
inst.gD[8] = np.float32((1. - alpha) * inst.gD[8] + alpha * D[8])
if myPointNum > gtrack_EST_POINTS:
alpha = 0
else:
alpha = np.float32((gtrack_EST_POINTS - myPointNum) / ((gtrack_EST_POINTS - 1) * myPointNum))
Rc[0] = np.float32((Rm[0] / myPointNum) + alpha * (inst.gD[0]))
Rc[4] = np.float32((Rm[4] / myPointNum) + alpha * (inst.gD[4]))
Rc[8] = np.float32((Rm[8] / myPointNum) + alpha * (inst.gD[8]))
ekf_utils.gtrack_computeJacobian(inst.currentStateVectorType, inst.S_apriori_hat, J)
u_tilda = ekf_utils.gtrack_matrixSub(mlen, 1, U, inst.H_s)
PJ = ekf_utils.gtrack_matrixComputePJT(inst.P_apriori_hat, J)
JPJ = ekf_utils.gtrack_matrixMultiply(mlen, slen, mlen, J, PJ)
cC = ekf_utils.gtrack_matrixAdd(mlen, mlen, JPJ, Rc)
cC_inv = ekf_utils.gtrack_matrixInv3(cC)
K = ekf_utils.gtrack_matrixMultiply(slen, mlen, mlen, PJ, cC_inv)
temp1 = ekf_utils.gtrack_matrixMultiply(slen, mlen, 1, K, u_tilda)
inst.S_hat = ekf_utils.gtrack_matrixAdd(slen, 1, inst.S_apriori_hat, temp1)
# print(temp1)
temp1 = ekf_utils.gtrack_matrixTransposeMultiply(slen, mlen, slen, K, PJ)
inst.P_hat = ekf_utils.gtrack_matrixSub(slen, slen, inst.P_apriori_hat, temp1)
temp1 = ekf_utils.gtrack_matrixAdd(mlen, mlen, JPJ, Rm)
inst.gC = ekf_utils.gtrack_matrixAdd(mlen, mlen, temp1, inst.gD)
inst.gC_inv = ekf_utils.gtrack_matrixInv3(inst.gC)
unit_event(inst, myPointNum)
return inst.state
# this is the helper function for GTRACK unit update
def velocity_state_handling(handle, um):
inst = handle
rvIn = um[2]
# print(inst.velocityHandling)
if inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_INIT:
um[2] = inst.rangeRate
inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_RATE_FILTER
elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_RATE_FILTER:
instanteneousRangeRate = np.float32(
(um[0] - inst.allocationRange) / ((inst.heartBeatCount - inst.allocationTime) * (inst.dt)))
inst.rangeRate = np.float32((inst.unrollingParams.alpha) * (inst.rangeRate) + (
1 - (inst.unrollingParams.alpha)) * instanteneousRangeRate)
um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.rangeRate, rvIn)
rrError = np.float32((instanteneousRangeRate - inst.rangeRate) / inst.rangeRate)
if np.abs(rrError) < inst.unrollingParams.confidence:
inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_TRACKING
elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_TRACKING:
instanteneousRangeRate = np.float32(
(um[0] - inst.allocationRange) / ((inst.heartBeatCount - inst.allocationTime) * inst.dt))
inst.rangeRate = np.float32(
(inst.unrollingParams.alpha) * inst.rangeRate + (1 - inst.unrollingParams.alpha) * instanteneousRangeRate)
um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.rangeRate, rvIn)
rvError = np.float32((inst.H_s[2] - um[2]) / um[2])
if np.abs(rvError) < 0.1:
inst.velocityHandling = ekf_utils.VelocityHandlingState().VELOCITY_LOCKED
elif inst.velocityHandling == ekf_utils.VelocityHandlingState().VELOCITY_LOCKED:
um[2] = ekf_utils.gtrack_unrollRadialVelocity(inst.maxRadialVelocity, inst.H_s[2], um[2])
# GTRACK Module calls this function to run GTRACK unit level state machine
def unit_event(handle, num):
inst = handle
if inst.state == ekf_utils.TrackState().TRACK_STATE_DETECTION:
if num > inst.allocationParams.pointsThre:
inst.detect2freeCount = 0
inst.detect2activeCount += 1
if inst.detect2activeCount > inst.stateParams.det2actThre:
inst.state = ekf_utils.TrackState().TRACK_STATE_ACTIVE
else:
if num == 0:
inst.detect2freeCount += 1
if inst.detect2activeCount > 0:
inst.detect2activeCount -= 1
if inst.detect2freeCount > inst.stateParams.det2freeThre:
inst.state = ekf_utils.TrackState().TRACK_STATE_FREE
elif inst.state == ekf_utils.TrackState().TRACK_STATE_ACTIVE:
if num != 0:
inst.active2freeCount = 0
else:
inst.active2freeCount += 1
if inst.sceneryParams.numStaticBoxes != 0:
thre = inst.stateParams.exit2freeThre
for numBoxes in range(inst.sceneryParams.numStaticBoxes):
if ekf_utils.isPointInsideBox(inst.S_hat[0], inst.S_hat[1],
inst.sceneryParams.boundaryBox[numBoxes]) == 1:
if inst.processVariance == 0:
thre = inst.stateParams.static2freeThre
else:
thre = inst.stateParams.active2freeThre
break
else:
thre = inst.stateParams.active2freeThre
if thre > inst.heartBeatCount:
thre = np.uint16(inst.heartBeatCount)
if inst.active2freeCount > thre:
inst.state = ekf_utils.TrackState().TRACK_STATE_FREE
# GTRACK Module calls this function to report GTRACK unit results to the target descriptor
def unit_report(handle, target):
inst = handle
target.uid = inst.uid
target.tid = inst.tid
target.S = copy.deepcopy(inst.S_hat)
target.EC = copy.deepcopy(inst.gC_inv)
target.G = inst.G
|
testing/MLDB-1884-timestamp-consistency.py | kstepanmpmg/mldb | 665 | 12605717 | #
# MLDB-1884-timestamp-consistency.py
# <NAME>, 2016-08-12
# This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved.
#
from mldb import mldb, MldbUnitTest, ResponseException
class Mldb1884TimestampConsistency(MldbUnitTest): # noqa
def test_null(self):
res = mldb.get('/v1/query', q="SELECT null")
mldb.log(res)
def test_str(self):
res = mldb.get('/v1/query', q="SELECT 'patate'")
mldb.log(res)
def test_operator(self):
res = mldb.get('/v1/query', q="SELECT NULL LIKE 'abc'")
mldb.log(res)
if __name__ == '__main__':
mldb.run_tests()
|
language-python-test/test/features/closures/closure_update_free_var.py | wbadart/language-python | 137 | 12605746 | def f():
x = 5
def g(y):
print (x + y)
g(1)
x = 6
g(1)
x = 7
g(1)
f()
|
challenges/8.7.Keyword_Arguments/main.py | pradeepsaiu/python-coding-challenges | 141 | 12605760 | <reponame>pradeepsaiu/python-coding-challenges<gh_stars>100-1000
def keyword_argument_example(your_age, **kwargs):
return your_age, kwargs
### Write your code below this line ###
about_me = "Replace this string with the correct function call."
### Write your code above this line ###
print(about_me)
|
tests/test_praw_scrapers/test_live_scrapers/test_utils/test_StreamGenerator.py | JosephLai241/Reddit-Scraper | 318 | 12605777 | """
Testing `StreamGenerator.py`.
"""
import os
import praw
import types
from dotenv import load_dotenv
from urs.praw_scrapers.live_scrapers.utils import StreamGenerator
class Login():
"""
Create a Reddit object with PRAW API credentials.
"""
@staticmethod
def create_reddit_object():
load_dotenv()
return praw.Reddit(
client_id = os.getenv("CLIENT_ID"),
client_secret = os.getenv("CLIENT_SECRET"),
user_agent = os.getenv("USER_AGENT"),
username = os.getenv("REDDIT_USERNAME"),
password = os.getenv("REDDIT_PASSWORD")
)
class TestStreamGeneratorStreamSubmissionsMethod():
"""
Testing StreamGenerator class stream_submissions() method.
"""
def test_stream_submissions_method(self):
reddit = Login.create_reddit_object()
subreddit = reddit.subreddit("askreddit")
generator = StreamGenerator.StreamGenerator.stream_submissions(subreddit.stream)
assert isinstance(generator, types.GeneratorType)
for obj in generator:
if isinstance(obj, dict):
assert True
break
class TestStreamGeneratorStreamCommentsMethod():
"""
Testing StreamGenerator class stream_comments() method.
"""
def test_stream_comments_method(self):
reddit = Login.create_reddit_object()
subreddit = reddit.subreddit("askreddit")
generator = StreamGenerator.StreamGenerator.stream_comments(subreddit.stream)
assert isinstance(generator, types.GeneratorType)
for obj in generator:
if isinstance(obj, dict):
assert True
break
|
lib/det_opr/cascade_roi_target.py | niqbal996/CrowdDetection | 252 | 12605789 | # -*- coding: utf-8 -*-
import megengine as mge
import megengine.random as rand
import megengine.functional as F
import numpy as np
from config import config
from det_opr.utils import mask_to_inds
from det_opr.bbox_opr import box_overlap_opr, bbox_transform_opr, box_overlap_ignore_opr
def cascade_roi_target(rpn_rois, im_info, gt_boxes, pos_threshold=0.5, top_k=1):
return_rois = []
return_labels = []
return_bbox_targets = []
# get per image proposals and gt_boxes
for bid in range(config.batch_per_gpu):
gt_boxes_perimg = gt_boxes[bid, :im_info[bid, 5], :]
batch_inds = mge.ones((gt_boxes_perimg.shapeof()[0], 1)) * bid
#if config.proposal_append_gt:
gt_rois = F.concat([batch_inds, gt_boxes_perimg[:, :4]], axis=1)
batch_roi_mask = rpn_rois[:, 0] == bid
batch_roi_inds = mask_to_inds(batch_roi_mask)
all_rois = F.concat([rpn_rois.ai[batch_roi_inds], gt_rois], axis=0)
overlaps_normal, overlaps_ignore = box_overlap_ignore_opr(
all_rois[:, 1:5], gt_boxes_perimg)
overlaps_normal, overlaps_normal_indices = F.argsort(overlaps_normal, descending=True)
overlaps_ignore, overlaps_ignore_indices = F.argsort(overlaps_ignore, descending=True)
# gt max and indices, ignore max and indices
max_overlaps_normal = overlaps_normal[:, :top_k].reshape(-1)
gt_assignment_normal = overlaps_normal_indices[:, :top_k].reshape(-1)
max_overlaps_ignore = overlaps_ignore[:, :top_k].reshape(-1)
gt_assignment_ignore = overlaps_ignore_indices[:, :top_k].reshape(-1)
# cons masks
ignore_assign_mask = (max_overlaps_normal < config.fg_threshold) * (
max_overlaps_ignore > max_overlaps_normal)
max_overlaps = max_overlaps_normal * (1 - ignore_assign_mask) + \
max_overlaps_ignore * ignore_assign_mask
gt_assignment = gt_assignment_normal * (1- ignore_assign_mask) + \
gt_assignment_ignore * ignore_assign_mask
gt_assignment = gt_assignment.astype(np.int32)
labels = gt_boxes_perimg.ai[gt_assignment, 4]
fg_mask = (max_overlaps >= config.fg_threshold) * (1 - F.equal(labels, config.ignore_label))
bg_mask = (max_overlaps < config.bg_threshold_high) * (
max_overlaps >= config.bg_threshold_low)
fg_mask = fg_mask.reshape(-1, top_k)
bg_mask = bg_mask.reshape(-1, top_k)
#pos_max = config.num_rois * config.fg_ratio
#fg_inds_mask = _bernoulli_sample_masks(fg_mask[:, 0], pos_max, 1)
#neg_max = config.num_rois - fg_inds_mask.sum()
#bg_inds_mask = _bernoulli_sample_masks(bg_mask[:, 0], neg_max, 1)
labels = labels * fg_mask.reshape(-1)
#keep_mask = fg_inds_mask + bg_inds_mask
#keep_inds = mask_to_inds(keep_mask)
#keep_inds = keep_inds[:F.minimum(config.num_rois, keep_inds.shapeof()[0])]
# labels
labels = labels.reshape(-1, top_k)
gt_assignment = gt_assignment.reshape(-1, top_k).reshape(-1)
target_boxes = gt_boxes_perimg.ai[gt_assignment, :4]
#rois = all_rois.ai[keep_inds]
target_shape = (all_rois.shapeof()[0], top_k, all_rois.shapeof()[-1])
target_rois = F.add_axis(all_rois, 1).broadcast(target_shape).reshape(-1, all_rois.shapeof()[-1])
bbox_targets = bbox_transform_opr(target_rois[:, 1:5], target_boxes)
if config.rcnn_bbox_normalize_targets:
std_opr = mge.tensor(config.bbox_normalize_stds[None, :])
mean_opr = mge.tensor(config.bbox_normalize_means[None, :])
minus_opr = mean_opr / std_opr
bbox_targets = bbox_targets / std_opr - minus_opr
bbox_targets = bbox_targets.reshape(-1, top_k * 4)
return_rois.append(all_rois)
return_labels.append(labels)
return_bbox_targets.append(bbox_targets)
if config.batch_per_gpu == 1:
return F.zero_grad(all_rois), F.zero_grad(labels), F.zero_grad(bbox_targets)
else:
return_rois = F.concat(return_rois, axis=0)
return_labels = F.concat(return_labels, axis=0)
return_bbox_targets = F.concat(return_bbox_targets, axis=0)
return F.zero_grad(return_rois), F.zero_grad(return_labels), F.zero_grad(return_bbox_targets) |
aps/sse/bss/sepformer.py | ishine/aps | 117 | 12605804 | <reponame>ishine/aps<gh_stars>100-1000
# Copyright 2021 <NAME>
# License: Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
import torch as th
import torch.nn as nn
import torch.nn.functional as tf
from aps.transform.asr import TFTransposeTransform
from aps.asr.transformer.encoder import TransformerEncoder
from aps.sse.base import SSEBase, MaskNonLinear, tf_masking
from aps.sse.bss.tcn import normalize_layer
from aps.libs import ApsRegisters
from typing import Dict, List, Union, Optional
class Transformer(nn.Module):
"""
For wrapping of the inter/intra Transformer
"""
def __init__(self,
arch: str = "xfmr",
num_layers: int = 2,
arch_kwargs: Dict = {}):
super(Transformer, self).__init__()
self.transformer = TransformerEncoder(arch,
-1,
num_layers=num_layers,
proj="none",
pose="abs",
arch_kwargs=arch_kwargs)
def forward(self, chunk: th.Tensor) -> th.Tensor:
"""
Sequence modeling along axis K
Args:
chunk (Tensor): N x K x L x C
Return:
chunk (Tensor): N x L x K x C
"""
# N x K x L x C
N, K, L, C = chunk.shape
# N x L x K x C
chunk = chunk.transpose(1, 2)
# NL x K x C
chunk = chunk.contiguous()
chunk = chunk.view(-1, K, C)
# K x NL x C
chunk, _ = self.transformer(chunk, None)
# NL x K x C
chunk = chunk.transpose(0, 1)
# N x L x K x C
return chunk.view(N, L, K, C)
class SepFormer(nn.Module):
"""
Main network of SepFormer proposed in Attention is All You Need in Speech Separation
"""
def __init__(self,
arch: str,
num_bins: int = 256,
num_spks: int = 2,
num_blocks: int = 2,
num_layers: int = 2,
chunk_size: int = 320,
arch_kwargs: Dict = {}):
super(SepFormer, self).__init__()
self.chunk_size = chunk_size
xfmr_kwargs = {
"arch": arch,
"num_layers": num_layers,
"arch_kwargs": arch_kwargs
}
separator = []
separator += [nn.Linear(num_bins, arch_kwargs["att_dim"])]
# [intra, inter, intra, inter, ...]
separator += [Transformer(**xfmr_kwargs) for _ in range(num_blocks * 2)]
separator += [nn.PReLU(), nn.Linear(arch_kwargs["att_dim"], num_bins)]
self.separator = nn.Sequential(*separator)
self.mask = nn.Conv1d(num_bins, num_bins * num_spks, 1)
def forward(self, inp: th.Tensor) -> th.Tensor:
"""
Args:
inp (Tensor): N x C x T
Return:
masks (Tensor): N x S*C x T
"""
batch_size, num_bins, num_frames = inp.shape
# N x C x T x 1 => N x CK x L
chunks = tf.unfold(inp[..., None], (self.chunk_size, 1),
stride=self.chunk_size // 2)
# N x C x K x L
chunks = chunks.view(batch_size, num_bins, self.chunk_size, -1)
# N x L x K x C
chunks = chunks.transpose(1, -1)
# N x K x L x C
chunks = self.separator(chunks)
# N x C x K x L
chunks = chunks.transpose(1, -1)
# N x CK x L
chunks = chunks.contiguous()
chunks = chunks.view(batch_size, -1, chunks.shape[-1])
# N x C x T x 1
out = tf.fold(chunks, (num_frames, 1), (self.chunk_size, 1),
stride=self.chunk_size // 2)
# N x C*S x T
return self.mask(out[..., 0])
@ApsRegisters.sse.register("sse@time_sepformer")
class TimeSeqFormer(SSEBase):
"""
SeqFormer network in time domain
"""
def __init__(self,
arch: str = "xfmr",
stride: int = 8,
kernel: int = 16,
num_bins: int = 256,
num_spks: int = 2,
non_linear: str = "relu",
num_blocks: int = 2,
num_layers: int = 2,
chunk_size: int = 320,
arch_kwargs: Dict = {}):
super(TimeSeqFormer, self).__init__(None, training_mode="time")
self.encoder = nn.Conv1d(1,
num_bins,
kernel_size=kernel,
stride=stride,
padding=0)
self.norm = normalize_layer("cLN", num_bins)
self.separator = SepFormer(arch,
num_bins=num_bins,
num_spks=num_spks,
num_blocks=num_blocks,
num_layers=num_layers,
chunk_size=chunk_size,
arch_kwargs=arch_kwargs)
self.mask = MaskNonLinear(non_linear, enable="positive_wo_softmax")
self.decoder = nn.ConvTranspose1d(num_bins,
1,
kernel_size=kernel,
stride=stride,
bias=True)
self.num_spks = num_spks
def infer(self,
mix: th.Tensor,
mode: str = "time") -> Union[th.Tensor, List[th.Tensor]]:
"""
Args:
mix (Tensor): S
Return:
sep ([Tensor, ...]): S
"""
self.check_args(mix, training=False, valid_dim=[1])
with th.no_grad():
mix = mix[None, ...]
sep = self.forward(mix)
return sep[0] if self.num_spks == 1 else [s[0] for s in sep]
def forward(self, mix: th.Tensor) -> Union[th.Tensor, List[th.Tensor]]:
"""
Args:
mix (Tensor): N x S
Return:
[Tensor, ...]: N x S
"""
self.check_args(mix, training=True, valid_dim=[2])
# N x 1 x S => N x C x T
w = self.norm(th.relu(self.encoder(mix[:, None])))
# N x C*S x T
m = self.mask(self.separator(w))
# [N x C x T, ...]
m = th.chunk(m, self.num_spks, 1)
# spks x [n x N x T] => spks x [n x S]
bss = [self.decoder(w * m[n])[:, 0] for n in range(self.num_spks)]
return bss[0] if self.num_spks == 1 else bss
@ApsRegisters.sse.register("sse@freq_sepformer")
class FreqSeqFormer(SSEBase):
"""
SeqFormer network in frequency domain
"""
def __init__(self,
arch: str = "xfmr",
enh_transform: Optional[nn.Module] = None,
num_bins: int = 257,
num_spks: int = 2,
non_linear: str = "relu",
num_blocks: int = 2,
num_layers: int = 2,
chunk_size: int = 64,
arch_kwargs: Dict = {},
training_mode: str = "freq"):
super(FreqSeqFormer, self).__init__(enh_transform,
training_mode=training_mode)
assert enh_transform is not None
self.swap = TFTransposeTransform()
self.separator = SepFormer(arch,
num_bins=num_bins,
num_spks=num_spks,
num_blocks=num_blocks,
num_layers=num_layers,
chunk_size=chunk_size,
arch_kwargs=arch_kwargs)
self.mask = MaskNonLinear(non_linear, enable="common")
self.num_spks = num_spks
def _forward(self, mix: th.Tensor,
mode: str) -> Union[th.Tensor, List[th.Tensor]]:
"""
Forward function in time|freq mode
"""
stft, _ = self.enh_transform.encode(mix, None)
feats = self.enh_transform(stft)
# N x S*F x T
masks = self.mask(self.separator(self.swap(feats)))
# [N x F x T, ...]
masks = th.chunk(masks, self.num_spks, 1)
if mode == "time":
bss_stft = [tf_masking(stft, m) for m in masks]
bss = self.enh_transform.decode(bss_stft)
else:
bss = masks
return bss[0] if self.num_spks == 1 else bss
def infer(self,
mix: th.Tensor,
mode: str = "time") -> Union[th.Tensor, List[th.Tensor]]:
"""
Args:
mix (Tensor): N x S
"""
self.check_args(mix, training=False, valid_dim=[1, 2])
with th.no_grad():
mix = mix[None, :]
ret = self._forward(mix, mode=mode)
return ret[0] if self.num_spks == 1 else [r[0] for r in ret]
def forward(self, mix: th.Tensor) -> Union[th.Tensor, List[th.Tensor]]:
"""
Args
mix (Tensor): N x (C) x S
Return
m (List(Tensor)): [N x F x T, ...] or
s (List(Tensor)): [N x S, ...]
"""
self.check_args(mix, training=True, valid_dim=[2, 3])
return self._forward(mix, mode=self.training_mode)
|
visual-concepts/scripts/script_cat_annotation_files.py | wenhuchen/ethz-bootstrapped-captioner | 167 | 12605808 | <filename>visual-concepts/scripts/script_cat_annotation_files.py<gh_stars>100-1000
import json
with open('../data/captions_train2014.json', 'rt') as f:
j1 = json.load(f)
with open('../data/captions_val2014.json', 'rt') as f:
j2 = json.load(f)
assert(j1['info'] == j2['info'])
assert(j1['type'] == j2['type'])
assert(j1['licenses'] == j2['licenses'])
j1['images'] = j1['images'] + j2['images']
j1['annotations'] = j1['annotations'] + j2['annotations']
with open('../data/captions_trainval2014.json', 'wt') as f:
json.dump(j1, f)
|
tests/bitcoin/test_bitcoin.py | febuiles/two1-python | 415 | 12605841 | import arrow
from calendar import timegm
from two1.bitcoin.block import Block
from two1.bitcoin.crypto import HDKey
from two1.bitcoin.crypto import HDPrivateKey
from two1.bitcoin.crypto import HDPublicKey
from two1.bitcoin.crypto import PrivateKey
from two1.bitcoin.crypto import PublicKey
from two1.bitcoin.hash import Hash
from two1.bitcoin.script import Script
from two1.bitcoin.txn import CoinbaseInput
from two1.bitcoin.txn import Transaction
from two1.bitcoin.txn import TransactionInput
from two1.bitcoin.txn import TransactionOutput
from two1.bitcoin.utils import bytes_to_str
from two1.bitcoin.utils import difficulty_to_target
from two1.bitcoin.utils import target_to_bits
def txn_from_json(txn_json):
inputs = []
for i in txn_json['inputs']:
if 'output_hash' in i:
outpoint = Hash(i['output_hash'])
script = Script(bytes.fromhex(i['script_signature_hex']))
# Do this to test script de/serialization
script._disassemble()
inp = TransactionInput(outpoint,
i['output_index'],
script,
i['sequence'])
else:
# Coinbase txn, we pass in a block version of 1 since the
# coinbase script from api.chain.com already has the
# height in there. Don't want our stuff to repack it in.
inp = CoinbaseInput(txn_json['block_height'],
bytes.fromhex(i['coinbase']),
i['sequence'],
1)
inputs.append(inp)
outputs = []
for o in txn_json['outputs']:
scr = Script(bytes.fromhex(o['script_hex']))
scr._disassemble()
out = TransactionOutput(o['value'], scr)
outputs.append(out)
txn = Transaction(Transaction.DEFAULT_TRANSACTION_VERSION,
inputs,
outputs,
txn_json['lock_time'])
return txn
def test_txn_serialization(txns_json):
''' txn_json: a JSON dict from api.chain.com that also contains
the raw hex of the transaction in the 'hex' key
'''
for txn_json in txns_json:
txn = txn_from_json(txn_json)
txn_bytes = bytes(txn)
txn_hash = txn.hash
try:
assert txn.num_inputs == len(txn_json['inputs'])
assert txn.num_outputs == len(txn_json['outputs'])
assert str(txn_hash) == txn_json['hash'], \
"Hash does not match for txn: %s\nCorrect bytes:\n%s\nConstructed bytes:\n%s\nJSON:\n%s" % (
txn_json['hash'],
txn_json['hex'],
bytes_to_str(txn_bytes),
txn_json)
except AssertionError as e:
print(e)
raise
def test_block(blocks_json):
for block_json in blocks_json:
# Why is it so f*ing hard to get a UNIX-time from a time string?
a = arrow.get(block_json['time'])
time = timegm(a.datetime.timetuple())
# TODO: Need to have a make_txn_from_json() method that's shared
# between here and test_txn()
txns = [txn_from_json(t) for t in block_json['transactions']]
# Create a new Block object
block = Block(block_json['height'],
block_json['version'],
Hash(block_json['previous_block_hash']),
time,
int(block_json['bits'], 16),
block_json['nonce'],
txns)
block_hash = block.hash
try:
assert len(block.txns) == len(block_json['transactions'])
assert block.height == block_json['height']
assert block.block_header.version == block_json['version']
assert block.block_header.prev_block_hash == Hash(block_json['previous_block_hash'])
assert block.block_header.merkle_root_hash == Hash(block_json['merkle_root'])
assert block.block_header.time == time
assert block.block_header.bits == int(block_json['bits'], 16)
assert block.block_header.nonce == block_json['nonce']
assert block_hash == Hash(block_json['hash'])
assert block.block_header.valid
except AssertionError as e:
print(e)
print("block height: %d" % (block.height))
print(" from json: %d" % (block_json['height']))
print(" version: %d" % (block.block_header.version))
print(" from json: %d" % (block_json['version']))
print(" prev_block_hash: %s" % (block.block_header.prev_block_hash))
print(" from json: %s" % (block_json['previous_block_hash']))
print(" merkle_root_hash: %s" % (block.block_header.merkle_root_hash))
print(" from json: %s" % (block_json['merkle_root']))
print(" time: %d" % (block.block_header.time))
print(" from json: %d" % (time))
print(" bits: %d" % (block.block_header.bits))
print(" from json: %d" % (int(block_json['bits'], 16)))
print(" nonce: %d" % (block.block_header.nonce))
print(" from json: %d" % (block_json['nonce']))
raise
def test_crypto():
pts = ((0x50863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b2352,
0x2cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6),
(0xa83b8de893467d3a88d959c0eb4032d9ce3bf80f175d4d9e75892a3ebb8ab7e5,
0x370f723328c24b7a97fe34063ba68f253fb08f8645d7c8b9a4ff98e3c29e7f0d),
(0xf680556678e25084a82fa39e1b1dfd0944f7e69fddaa4e03ce934bd6b291dca0,
0x52c10b721d34447e173721fb0151c68de1106badb089fb661523b8302a9097f5),
(0x241febb8e23cbd77d664a18f66ad6240aaec6ecdc813b088d5b901b2e285131f,
0x513378d9ff94f8d3d6c420bd13981df8cd50fd0fbd0cb5afabb3e66f2750026d))
for pt in pts:
b = bytes([(pt[1] & 0x1) + 0x2]) + pt[0].to_bytes(32, 'big')
b_full = bytes([0x04]) + pt[0].to_bytes(32, 'big') + pt[1].to_bytes(32, 'big')
pk = PublicKey.from_bytes(b)
assert pk.point.y == pt[1]
assert b == pk.compressed_bytes
assert b_full == bytes(pk)
assert bytes(PublicKey.from_hex(pk.to_hex())) == b_full
for i in range(10):
pk = PrivateKey.from_random()
assert PrivateKey.from_hex(pk.to_hex()).key == pk.key
hd_priv = HDPrivateKey.master_key_from_entropy()[0]
hd_priv2 = HDKey.from_hex(hd_priv.to_hex())
hd_pub = hd_priv.public_key
hd_pub2 = HDKey.from_hex(hd_pub.to_hex())
assert isinstance(hd_priv2, HDPrivateKey)
assert hd_priv2._key.key == hd_priv._key.key
assert hd_priv2.chain_code == hd_priv.chain_code
assert isinstance(hd_pub2, HDPublicKey)
assert hd_pub2._key.point.x == hd_pub._key.point.x
assert hd_pub2._key.point.y == hd_pub._key.point.y
assert hd_pub2.chain_code == hd_pub.chain_code
def test_utils():
assert difficulty_to_target(16307.420938523983) == 0x404cb000000000000000000000000000000000000000000000000
assert target_to_bits(0x00000000000404CB000000000000000000000000000000000000000000000000) == 0x1b0404cb
def test_txn():
txn_str = "0100000001205607fb482a03600b736fb0c257dfd4faa49e45db3990e2c4994796031eae6e000000008b483045022100ed84be709227397fb1bc13b749f235e1f98f07ef8216f15da79e926b99d2bdeb02206ff39819d91bc81fecd74e59a721a38b00725389abb9cbecb42ad1c939fd8262014104e674caf81eb3bb4a97f2acf81b54dc930d9db6a6805fd46ca74ac3ab212c0bbf62164a11e7edaf31fbf24a878087d925303079f2556664f3b32d125f2138cbefffffffff0128230000000000001976a914f1fd1dc65af03c30fe743ac63cef3a120ffab57d88ac00000000" # nopep8
tx = Transaction.from_hex(txn_str)
output_address = "1P4X54WbgeVKAnbKziaGP5n9b6Qvc9R8RZ"
assert tx.output_index_for_address(output_address) == 0
assert not tx.output_index_for_address("1CmzK6oqWMwdyo4J7f2vkQTd6uu1RwtERP")
addrs = tx.get_addresses()
assert len(addrs['inputs']) == 1
assert len(addrs['outputs']) == 1
assert addrs['inputs'] == [["1NKxQnbtKDdL6BY1UaKdrzCxQHfn3TQnqZ"]]
assert addrs['outputs'] == [[output_address]]
txn_str = "0100000002cb246d110b6087cd3b5e3d3b7a74505ea995721208ddfc15b6b3b718271e0b41010000006b48304502201f2cf747f9f8e3f770bef848e6787c9fca31e3086c390e505c1339936a15a78f022100a9e5f761162b8a4387c4009ce9469e92302fda68afe85371181b6e13b84f052d01210339e1274cd66db3dbe23e4def7ae9eb81644c15347cf0b39c741fb947c8ef1f12ffffffffb828405fca4f578073fe02bb00e999407bbaa3f5556f4c3571fd5fef28e47de8010000006a47304402206b7a8851fb2284201f31854bc857a8e1a1c4d5dbd19efe76d89d2c02083ff397022029a231c2750005b5ec4c437a8fa7163eaffe02e5fb51d9b8bb5edc5bb88040720121036744acff73b223a6f04190b60a980f8de1ed0271bba92144850e90c1af489fb3ffffffff0232530000000000001976a9146037aac7480f0fa0c7740560a7bf2f37ec17597988acb0ad01000000000017a914ef5a22f491632b2f18c59352dd64fa4ec346a8118700000000" # nopep8
tx = Transaction.from_hex(txn_str)
output_address = "19mkZEZinQ77SrXbzxd5QJksikQFmfUNfo"
assert tx.output_index_for_address(output_address) == 0
output_address = "3PWbQBs5YDbmFCe5RdDjzqApJxs25Apvnd"
assert tx.output_index_for_address(output_address) == 1
addrs = tx.get_addresses()
assert len(addrs['inputs']) == 2
assert len(addrs['outputs']) == 2
assert addrs['inputs'] == [["16R5HjRwvsd5NdriQW6bBJsCFrAdqhPC1g"],
["18HMSYbh3PbXfxL6f6Cy9FjCK7AC4tB2ZX"]]
assert addrs['outputs'] == [["19mkZEZinQ77SrXbzxd5QJksikQFmfUNfo"],
["3PWbQBs5YDbmFCe5RdDjzqApJxs25Apvnd"]]
|
rpython/jit/backend/arm/test/test_del.py | nanjekyejoannah/pypy | 381 | 12605849 |
from rpython.jit.backend.arm.test.support import JitARMMixin
from rpython.jit.metainterp.test.test_del import DelTests
class TestDel(JitARMMixin, DelTests):
# for the individual tests see
# ====> ../../../metainterp/test/test_del.py
pass
|
release/stubs.min/Grasshopper/Kernel/Types/__init__.py | htlcnn/ironpython-stubs | 182 | 12605878 | # encoding: utf-8
# module Grasshopper.Kernel.Types calls itself Types
# from Grasshopper,Version=1.0.0.20,Culture=neutral,PublicKeyToken=dda4f5ec2cd80803
# by generator 1.145
""" NamespaceTracker represent a CLS namespace. """
# no imports
# no functions
# classes
class Complex(object):
"""
Complex(real_component: float)
Complex(real_component: float,imaginary_component: float)
"""
def ACos(self):
""" ACos(self: Complex) -> Complex """
pass
def ASin(self):
""" ASin(self: Complex) -> Complex """
pass
def ATan(self):
""" ATan(self: Complex) -> Complex """
pass
def Cos(self):
""" Cos(self: Complex) -> Complex """
pass
def Cosecant(self):
""" Cosecant(self: Complex) -> Complex """
pass
def CoTan(self):
""" CoTan(self: Complex) -> Complex """
pass
def Exponential(self):
""" Exponential(self: Complex) -> Complex """
pass
def GetHashCode(self):
""" GetHashCode(self: Complex) -> int """
pass
def Log(self):
""" Log(self: Complex) -> Complex """
pass
def Log10(self):
""" Log10(self: Complex) -> Complex """
pass
def Modulus(self):
""" Modulus(self: Complex) -> float """
pass
def ModulusSquared(self):
""" ModulusSquared(self: Complex) -> float """
pass
def Power(self,exponent):
""" Power(self: Complex,exponent: Complex) -> Complex """
pass
def Root(self,rootexponent):
""" Root(self: Complex,rootexponent: Complex) -> Complex """
pass
def Secant(self):
""" Secant(self: Complex) -> Complex """
pass
def Sin(self):
""" Sin(self: Complex) -> Complex """
pass
def Square(self):
""" Square(self: Complex) -> Complex """
pass
def SquareRoot(self):
""" SquareRoot(self: Complex) -> Complex """
pass
def Tan(self):
""" Tan(self: Complex) -> Complex """
pass
def __add__(self,*args):
""" x.__add__(y) <==> x+yx.__add__(y) <==> x+y """
pass
def __div__(self,*args):
""" x.__div__(y) <==> x/yx.__div__(y) <==> x/y """
pass
def __mul__(self,*args):
""" x.__mul__(y) <==> x*yx.__mul__(y) <==> x*y """
pass
def __neg__(self,*args):
""" x.__neg__() <==> -x """
pass
@staticmethod
def __new__(self,real_component,imaginary_component=None):
"""
__new__(cls: type,real_component: float)
__new__(cls: type,real_component: float,imaginary_component: float)
__new__[Complex]() -> Complex
"""
pass
def __pos__(self,*args):
""" __pos__(summand: Complex) -> Complex """
pass
def __pow__(self,*args):
""" x.__pow__(y[,z]) <==> pow(x,y[,z]) """
pass
def __radd__(self,*args):
"""
__radd__(A: float,B: Complex) -> Complex
__radd__(A: Complex,B: Complex) -> Complex
"""
pass
def __rdiv__(self,*args):
"""
__rdiv__(dividend: float,divisor: Complex) -> Complex
__rdiv__(dividend: Complex,divisor: Complex) -> Complex
"""
pass
def __rmul__(self,*args):
"""
__rmul__(A: float,B: Complex) -> Complex
__rmul__(A: Complex,B: Complex) -> Complex
"""
pass
def __rsub__(self,*args):
"""
__rsub__(A: float,B: Complex) -> Complex
__rsub__(A: Complex,B: Complex) -> Complex
"""
pass
def __sub__(self,*args):
""" x.__sub__(y) <==> x-yx.__sub__(y) <==> x-y """
pass
Argument=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Argument(self: Complex) -> float
Set: Argument(self: Complex)=value
"""
Imaginary=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Imaginary(self: Complex) -> float
Set: Imaginary(self: Complex)=value
"""
IsReal=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsReal(self: Complex) -> bool
"""
IsRealNonNegative=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsRealNonNegative(self: Complex) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: Complex) -> bool
"""
IsZero=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsZero(self: Complex) -> bool
"""
Real=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Real(self: Complex) -> float
Set: Real(self: Complex)=value
"""
ComplexUnit=None
Infinity=None
NaN=None
NegativeInfinity=None
Zero=None
class GH_Arc(GH_GeometricGoo[Arc],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_Arc()
GH_Arc(arc: Arc)
GH_Arc(other: GH_Arc)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Arc,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Arc,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Arc) -> (bool,T) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Arc,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Arc,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Arc) -> IGH_Goo """
pass
def DuplicateArc(self):
""" DuplicateArc(self: GH_Arc) -> GH_Arc """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Arc) -> IGH_GeometricGoo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Arc) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Arc,xform: Transform) -> BoundingBox """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Arc,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Arc,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Arc) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Arc,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Arc,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,arc: Arc)
__new__(cls: type,other: GH_Arc)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Arc) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Arc) -> BoundingBox
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Arc) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Arc) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Arc) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Arc) -> str
"""
m_value=None
class GH_Boolean(GH_Goo[bool],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_Boolean()
GH_Boolean(bool: bool)
GH_Boolean(other: GH_Boolean)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Boolean,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Boolean) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Boolean) -> IGH_Goo """
pass
def DuplicateBoolean(self):
""" DuplicateBoolean(self: GH_Boolean) -> GH_Boolean """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Boolean) -> IGH_GooProxy """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_Boolean) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_Boolean) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_Boolean,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_Boolean) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_Boolean,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_Boolean) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_Boolean) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_Boolean) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_Boolean) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_Boolean) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_Boolean) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_Boolean) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_Boolean) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_Boolean,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Boolean) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Boolean,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,bool: bool)
__new__(cls: type,other: GH_Boolean)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Boolean) -> bool
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_Boolean) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Boolean) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Boolean) -> str
"""
m_value=None
class GH_Box(GH_GeometricGoo[Box],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_Box()
GH_Box(box: Box)
GH_Box(box: BoundingBox)
GH_Box(id: Guid)
GH_Box(other: GH_Box)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Box,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def Brep(self):
""" Brep(self: GH_Box) -> Brep """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Box,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Box) -> (bool,T) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_Box) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Box,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Box,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Box) -> IGH_Goo """
pass
def DuplicateBox(self):
""" DuplicateBox(self: GH_Box) -> GH_Box """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Box) -> IGH_GeometricGoo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Box) -> IGH_GooProxy """
pass
def Geometry(self,brp,crv,pt):
""" Geometry(self: GH_Box,brp: Brep,crv: Curve,pt: Point) -> (bool,Brep,Curve,Point) """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Box,xform: Transform) -> BoundingBox """
pass
def LoadGeometry(self,doc=None):
""" LoadGeometry(self: GH_Box,doc: RhinoDoc) -> bool """
pass
def Mesh(self):
""" Mesh(self: GH_Box) -> Mesh """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Box,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Box,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Box) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Box,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Box,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,box: Box)
__new__(cls: type,box: BoundingBox)
__new__(cls: type,id: Guid)
__new__(cls: type,other: GH_Box)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Box) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Box) -> BoundingBox
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_Box) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Box) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Box) -> str
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_Box) -> Guid
Set: ReferenceID(self: GH_Box)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Box) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Box) -> str
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_Box) -> Box
Set: Value(self: GH_Box)=value
"""
GH_BoxProxy=None
m_value=None
class GH_Brep(GH_GeometricGoo[Brep],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData,IGH_PreviewMeshData):
"""
GH_Brep()
GH_Brep(brep: Brep)
GH_Brep(id: Guid)
GH_Brep(other: GH_Brep)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Brep,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
@staticmethod
def BrepTightBoundingBox(in):
""" BrepTightBoundingBox(in: Brep) -> BoundingBox """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Brep,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Brep) -> (bool,T) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_Brep) """
pass
def DestroyPreviewMeshes(self):
""" DestroyPreviewMeshes(self: GH_Brep) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Brep,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Brep,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Brep) -> IGH_Goo """
pass
def DuplicateBrep(self):
""" DuplicateBrep(self: GH_Brep) -> GH_Brep """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Brep) -> IGH_GeometricGoo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Brep) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Brep,xform: Transform) -> BoundingBox """
pass
def GetPreviewMeshes(self):
""" GetPreviewMeshes(self: GH_Brep) -> Array[Mesh] """
pass
def LoadGeometry(self,doc=None):
""" LoadGeometry(self: GH_Brep,doc: RhinoDoc) -> bool """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Brep,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Brep,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Brep) -> object """
pass
def ToString(self):
""" ToString(self: GH_Brep) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Brep,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Brep,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,brep: Brep)
__new__(cls: type,id: Guid)
__new__(cls: type,other: GH_Brep)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Brep) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Brep) -> BoundingBox
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_Brep) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Brep) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Brep) -> str
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_Brep) -> Guid
Set: ReferenceID(self: GH_Brep)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Brep) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Brep) -> str
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_Brep) -> Brep
Set: Value(self: GH_Brep)=value
"""
GH_BrepProxy=None
m_value=None
class GH_Circle(GH_GeometricGoo[Circle],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_Circle()
GH_Circle(circle: Circle)
GH_Circle(other: GH_Circle)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Circle,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Circle,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Circle) -> (bool,T) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Circle,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Circle,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Circle) -> IGH_Goo """
pass
def DuplicateCircle(self):
""" DuplicateCircle(self: GH_Circle) -> GH_Circle """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Circle) -> IGH_GeometricGoo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Circle) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Circle,xform: Transform) -> BoundingBox """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Circle,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Circle,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Circle) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Circle,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Circle,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,circle: Circle)
__new__(cls: type,other: GH_Circle)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Circle) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Circle) -> BoundingBox
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Circle) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Circle) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Circle) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Circle) -> str
"""
GH_CircleProxy=None
m_value=None
class GH_Colour(GH_Goo[Color],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_Colour()
GH_Colour(colour: Color)
GH_Colour(other: GH_Colour)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Colour,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Colour) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Colour) -> IGH_Goo """
pass
def DuplicateColour(self):
""" DuplicateColour(self: GH_Colour) -> GH_Colour """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Colour) -> IGH_GooProxy """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_Colour) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_Colour) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_Colour,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_Colour) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_Colour,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_Colour) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_Colour) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_Colour) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_Colour) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_Colour) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_Colour) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_Colour) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_Colour) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_Colour,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Colour) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Colour,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,colour: Color)
__new__(cls: type,other: GH_Colour)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Colour) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Colour) -> str
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_Colour) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Colour) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Colour) -> str
"""
m_value=None
class GH_ComplexNumber(GH_Goo[Complex],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_ComplexNumber()
GH_ComplexNumber(number: Complex)
GH_ComplexNumber(other: GH_ComplexNumber)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_ComplexNumber,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_ComplexNumber) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_ComplexNumber) -> IGH_Goo """
pass
def DuplicateComplex(self):
""" DuplicateComplex(self: GH_ComplexNumber) -> GH_ComplexNumber """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_ComplexNumber) -> IGH_GooProxy """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_ComplexNumber) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_ComplexNumber) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_ComplexNumber,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_ComplexNumber) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_ComplexNumber,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_ComplexNumber) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_ComplexNumber) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_ComplexNumber) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_ComplexNumber) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_ComplexNumber) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_ComplexNumber) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_ComplexNumber) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_ComplexNumber) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_ComplexNumber,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_ComplexNumber) -> str """
pass
def Write(self,writer):
""" Write(self: GH_ComplexNumber,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,number: Complex)
__new__(cls: type,other: GH_ComplexNumber)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_ComplexNumber) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_ComplexNumber) -> str
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_ComplexNumber) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_ComplexNumber) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_ComplexNumber) -> str
"""
m_value=None
class GH_Culture(GH_Goo[CultureInfo],IGH_Goo,GH_ISerializable):
"""
GH_Culture()
GH_Culture(culture: CultureInfo)
GH_Culture(other: GH_Culture)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Culture,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Culture) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Culture) -> IGH_Goo """
pass
def DuplicateCulture(self):
""" DuplicateCulture(self: GH_Culture) -> GH_Culture """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Culture) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_Culture,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Culture) -> object """
pass
def ToString(self):
""" ToString(self: GH_Culture) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Culture,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,culture: CultureInfo)
__new__(cls: type,other: GH_Culture)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Culture) -> bool
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Culture) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Culture) -> str
"""
m_value=None
class GH_Curve(GH_GeometricGoo[Curve],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_Curve()
GH_Curve(curve: Curve)
GH_Curve(ref_guid: Guid)
GH_Curve(ref_guid: Guid,ref_edge: int)
GH_Curve(other: GH_Curve)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Curve,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Curve,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Curve) -> (bool,T) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_Curve) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Curve,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Curve,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Curve) -> IGH_Goo """
pass
def DuplicateCurve(self):
""" DuplicateCurve(self: GH_Curve) -> GH_Curve """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Curve) -> IGH_GeometricGoo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Curve) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Curve,xform: Transform) -> BoundingBox """
pass
def LoadGeometry(self,doc=None):
""" LoadGeometry(self: GH_Curve,doc: RhinoDoc) -> bool """
pass
def MakeDeformable(self):
""" MakeDeformable(self: GH_Curve) -> bool """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Curve,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Curve,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Curve) -> object """
pass
def ToString(self):
""" ToString(self: GH_Curve) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Curve,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Curve,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,curve: Curve)
__new__(cls: type,ref_guid: Guid)
__new__(cls: type,ref_guid: Guid,ref_edge: int)
__new__(cls: type,other: GH_Curve)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Curve) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Curve) -> BoundingBox
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_Curve) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Curve) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Curve) -> str
"""
ReferenceEdge=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceEdge(self: GH_Curve) -> int
Set: ReferenceEdge(self: GH_Curve)=value
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_Curve) -> Guid
Set: ReferenceID(self: GH_Curve)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Curve) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Curve) -> str
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_Curve) -> Curve
Set: Value(self: GH_Curve)=value
"""
GH_CurveProxy=None
m_value=None
class GH_DifferentialSolver(Enum,IComparable,IFormattable,IConvertible):
""" enum GH_DifferentialSolver,values: Euler (1),None (0),RungeKutta2 (2),RungeKutta3 (3),RungeKutta4 (4) """
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Euler=None
None=None
RungeKutta2=None
RungeKutta3=None
RungeKutta4=None
value__=None
class GH_Field(object,IGH_Goo,GH_ISerializable,IGH_PreviewData):
"""
GH_Field()
GH_Field(other: GH_Field)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Field,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Field,target: T) -> (bool,T) """
pass
def CurvatureAt(self,location):
""" CurvatureAt(self: GH_Field,location: Point3d) -> float """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Field,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Field,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Field) -> IGH_Goo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Field) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_Field,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Field) -> object """
pass
def SolveStep(self,location,factor,method):
""" SolveStep(self: GH_Field,location: Point3d,factor: float,method: GH_DifferentialSolver) -> Vector3d """
pass
def SolveSteps(self,location,accuracy,count,method):
""" SolveSteps(self: GH_Field,location: Point3d,accuracy: float,count: int,method: GH_DifferentialSolver) -> Point3dList """
pass
def TensorAt(self,location):
""" TensorAt(self: GH_Field,location: Point3d) -> Vector3d """
pass
def ToString(self):
""" ToString(self: GH_Field) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Field,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,other=None):
"""
__new__(cls: type)
__new__(cls: type,other: GH_Field)
"""
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __str__(self,*args):
pass
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Field) -> BoundingBox
"""
Elements=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Elements(self: GH_Field) -> List[IGH_FieldElement]
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Field) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Field) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Field) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Field) -> str
"""
class GH_FieldElement(object,IGH_FieldElement,GH_ISerializable,IGH_PreviewData):
# no doc
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_FieldElement,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_FieldElement,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_FieldElement) -> IGH_FieldElement """
pass
def Force(self,location):
""" Force(self: GH_FieldElement,location: Point3d) -> Vector3d """
pass
def IsCoincident(self,point,tolerance):
""" IsCoincident(self: GH_FieldElement,point: Point3d,tolerance: float) -> bool """
pass
def Read(self,reader):
""" Read(self: GH_FieldElement,reader: GH_IReader) -> bool """
pass
def Write(self,writer):
""" Write(self: GH_FieldElement,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
BoundingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: BoundingBox(self: GH_FieldElement) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_FieldElement) -> BoundingBox
"""
ElementGuid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ElementGuid(self: GH_FieldElement) -> Guid
"""
IsLimited=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsLimited(self: GH_FieldElement) -> bool
Set: IsLimited(self: GH_FieldElement)=value
"""
Limits=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Limits(self: GH_FieldElement) -> Box
Set: Limits(self: GH_FieldElement)=value
"""
class GH_GeometricGoo(GH_Goo[T],IGH_Goo,GH_ISerializable,IGH_GeometricGoo):
# no doc
def CastFrom(self,source):
""" CastFrom(self: GH_GeometricGoo[T],source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[Q](self: GH_GeometricGoo[T]) -> (bool,Q) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_GeometricGoo[T]) """
pass
def Duplicate(self):
""" Duplicate(self: GH_GeometricGoo[T]) -> IGH_Goo """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_GeometricGoo[T]) -> IGH_GeometricGoo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_GeometricGoo[T]) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_GeometricGoo[T],xform: Transform) -> BoundingBox """
pass
def LoadGeometry(self,doc=None):
"""
LoadGeometry(self: GH_GeometricGoo[T],doc: RhinoDoc) -> bool
LoadGeometry(self: GH_GeometricGoo[T]) -> bool
"""
pass
def Morph(self,xmorph):
""" Morph(self: GH_GeometricGoo[T],xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Transform(self,xform):
""" Transform(self: GH_GeometricGoo[T],xform: Transform) -> IGH_GeometricGoo """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*args): #cannot find CLR constructor
"""
__new__(cls: type)
__new__(cls: type,internal_data: T)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_GeometricGoo[T]) -> BoundingBox
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_GeometricGoo[T]) -> bool
"""
IsReferencedGeometry=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsReferencedGeometry(self: GH_GeometricGoo[T]) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_GeometricGoo[T]) -> bool
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_GeometricGoo[T]) -> Guid
Set: ReferenceID(self: GH_GeometricGoo[T])=value
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_GeometricGoo[T]) -> T
Set: Value(self: GH_GeometricGoo[T])=value
"""
m_value=None
class GH_GeometricGooWrapper(object,IGH_GeometricGoo,IGH_Goo,GH_ISerializable):
"""
GH_GeometricGooWrapper()
GH_GeometricGooWrapper(goo: IGH_GeometricGoo)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_GeometricGooWrapper,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_GeometricGooWrapper,target: T) -> (bool,T) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_GeometricGooWrapper) """
pass
def Duplicate(self):
""" Duplicate(self: GH_GeometricGooWrapper) -> IGH_Goo """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_GeometricGooWrapper) -> IGH_GeometricGoo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_GeometricGooWrapper) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_GeometricGooWrapper,xform: Transform) -> BoundingBox """
pass
def LoadGeometry(self,doc=None):
"""
LoadGeometry(self: GH_GeometricGooWrapper,doc: RhinoDoc) -> bool
LoadGeometry(self: GH_GeometricGooWrapper) -> bool
"""
pass
def Morph(self,xmorph):
""" Morph(self: GH_GeometricGooWrapper,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_GeometricGooWrapper,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_GeometricGooWrapper) -> object """
pass
def ToString(self):
""" ToString(self: GH_GeometricGooWrapper) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_GeometricGooWrapper,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_GeometricGooWrapper,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,goo=None):
"""
__new__(cls: type)
__new__(cls: type,goo: IGH_GeometricGoo)
"""
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_GeometricGooWrapper) -> BoundingBox
"""
InternalGoo=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: InternalGoo(self: GH_GeometricGooWrapper) -> IGH_GeometricGoo
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_GeometricGooWrapper) -> bool
"""
IsReferencedGeometry=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsReferencedGeometry(self: GH_GeometricGooWrapper) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_GeometricGooWrapper) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_GeometricGooWrapper) -> str
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_GeometricGooWrapper) -> Guid
Set: ReferenceID(self: GH_GeometricGooWrapper)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_GeometricGooWrapper) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_GeometricGooWrapper) -> str
"""
class GH_GeometryGroup(object,IGH_GeometricGoo,IGH_Goo,GH_ISerializable,IGH_BakeAwareData,IGH_PreviewData):
""" GH_GeometryGroup() """
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_GeometryGroup,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_GeometryGroup,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_GeometryGroup,target: T) -> (bool,T) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_GeometryGroup) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_GeometryGroup,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_GeometryGroup,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_GeometryGroup) -> IGH_Goo """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_GeometryGroup) -> IGH_GeometricGoo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_GeometryGroup) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_GeometryGroup,xform: Transform) -> BoundingBox """
pass
def LoadGeometry(self,doc=None):
"""
LoadGeometry(self: GH_GeometryGroup,doc: RhinoDoc) -> bool
LoadGeometry(self: GH_GeometryGroup) -> bool
"""
pass
def Morph(self,xmorph):
""" Morph(self: GH_GeometryGroup,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_GeometryGroup,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_GeometryGroup) -> object """
pass
def ToString(self):
""" ToString(self: GH_GeometryGroup) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_GeometryGroup,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_GeometryGroup,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_GeometryGroup) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_GeometryGroup) -> BoundingBox
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_GeometryGroup) -> bool
"""
IsReferencedGeometry=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsReferencedGeometry(self: GH_GeometryGroup) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_GeometryGroup) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_GeometryGroup) -> str
"""
Objects=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Objects(self: GH_GeometryGroup) -> List[IGH_GeometricGoo]
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_GeometryGroup) -> Guid
Set: ReferenceID(self: GH_GeometryGroup)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_GeometryGroup) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_GeometryGroup) -> str
"""
GH_GeometryGroupProxy=None
class GH_Goo(object,IGH_Goo,GH_ISerializable):
# no doc
def CastFrom(self,source):
""" CastFrom(self: GH_Goo[T],source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[Q](self: GH_Goo[T],target: Q) -> (bool,Q) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Goo[T]) -> IGH_Goo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Goo[T]) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_Goo[T],reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Goo[T]) -> object """
pass
def ToString(self):
""" ToString(self: GH_Goo[T]) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Goo[T],writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*args): #cannot find CLR constructor
"""
__new__(cls: type)
__new__(cls: type,internal_data: T)
__new__(cls: type,other: GH_Goo[T])
"""
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Goo[T]) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Goo[T]) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Goo[T]) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Goo[T]) -> str
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_Goo[T]) -> T
Set: Value(self: GH_Goo[T])=value
"""
m_value=None
class GH_GooProxy(object,IGH_GooProxy):
# no doc
def Construct(self):
""" Construct(self: GH_GooProxy[T]) """
pass
def FormatInstance(self):
""" FormatInstance(self: GH_GooProxy[T]) -> str """
pass
def FromString(self,in):
""" FromString(self: GH_GooProxy[T],in: str) -> bool """
pass
def MutateString(self,in):
""" MutateString(self: GH_GooProxy[T],in: str) -> str """
pass
def NumberToString(self,*args):
""" NumberToString(self: GH_GooProxy[T],number: float) -> str """
pass
def StringToNumber(self,*args):
""" StringToNumber(self: GH_GooProxy[T],text: str) -> float """
pass
def ToString(self):
""" ToString(self: GH_GooProxy[T]) -> str """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*args): #cannot find CLR constructor
""" __new__(cls: type,owner: T) """
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __str__(self,*args):
pass
IsParsable=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsParsable(self: GH_GooProxy[T]) -> bool
"""
Owner=property(lambda self: object(),lambda self,v: None,lambda self: None)
ProxyOwner=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ProxyOwner(self: GH_GooProxy[T]) -> IGH_Goo
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_GooProxy[T]) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_GooProxy[T]) -> str
"""
UserString=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: UserString(self: GH_GooProxy[T]) -> str
Set: UserString(self: GH_GooProxy[T])=value
"""
Valid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Valid(self: GH_GooProxy[T]) -> bool
"""
class GH_Guid(GH_Goo[Guid],IGH_Goo,GH_ISerializable):
"""
GH_Guid()
GH_Guid(id: Guid)
GH_Guid(other: GH_Guid)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Guid,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Guid) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Guid) -> IGH_Goo """
pass
def DuplicateGuid(self):
""" DuplicateGuid(self: GH_Guid) -> GH_Guid """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Guid) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_Guid,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Guid) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Guid,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,id: Guid)
__new__(cls: type,other: GH_Guid)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Guid) -> bool
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Guid) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Guid) -> str
"""
m_value=None
class GH_Integer(GH_Goo[int],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_Integer()
GH_Integer(number: int)
GH_Integer(other: GH_Integer)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Integer,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Integer) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Integer) -> IGH_Goo """
pass
def DuplicateInteger(self):
""" DuplicateInteger(self: GH_Integer) -> GH_Integer """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Integer) -> IGH_GooProxy """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_Integer) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_Integer) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_Integer,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_Integer) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_Integer,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_Integer) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_Integer) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_Integer) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_Integer) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_Integer) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_Integer) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_Integer) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_Integer) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_Integer,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Integer) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Integer,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,number: int)
__new__(cls: type,other: GH_Integer)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Integer) -> bool
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_Integer) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Integer) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Integer) -> str
"""
m_value=None
class GH_Interval(GH_Goo[Interval],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_Interval()
GH_Interval(interval: Interval)
GH_Interval(other: GH_Interval)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Interval,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Interval) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Interval) -> IGH_Goo """
pass
def DuplicateInterval(self):
""" DuplicateInterval(self: GH_Interval) -> GH_Interval """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Interval) -> IGH_GooProxy """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_Interval) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_Interval) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_Interval,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_Interval) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_Interval,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_Interval) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_Interval) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_Interval) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_Interval) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_Interval) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_Interval) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_Interval) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_Interval) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_Interval,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Interval) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Interval,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,interval: Interval)
__new__(cls: type,other: GH_Interval)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Interval) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Interval) -> str
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_Interval) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Interval) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Interval) -> str
"""
m_value=None
class GH_Interval2D(GH_Goo[UVInterval],IGH_Goo,GH_ISerializable):
"""
GH_Interval2D()
GH_Interval2D(uv: UVInterval)
GH_Interval2D(other: GH_Interval2D)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Interval2D,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Interval2D,target: T) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Interval2D) -> IGH_Goo """
pass
def DuplicateInterval(self):
""" DuplicateInterval(self: GH_Interval2D) -> GH_Interval2D """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Interval2D) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_Interval2D,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Interval2D) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Interval2D,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,uv: UVInterval)
__new__(cls: type,other: GH_Interval2D)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Interval2D) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Interval2D) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Interval2D) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Interval2D) -> str
"""
GH_Interval2DProxy=None
m_value=None
class GH_Line(GH_GeometricGoo[Line],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_Line()
GH_Line(line: Line)
GH_Line(other: GH_Line)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Line,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Line,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Line) -> (bool,T) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Line,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Line,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Line) -> IGH_Goo """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Line) -> IGH_GeometricGoo """
pass
def DuplicateLine(self):
""" DuplicateLine(self: GH_Line) -> GH_Line """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Line) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Line,xform: Transform) -> BoundingBox """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Line,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Line,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Line) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Line,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Line,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,line: Line)
__new__(cls: type,other: GH_Line)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Line) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Line) -> BoundingBox
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Line) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Line) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Line) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Line) -> str
"""
GH_LineProxy=None
m_value=None
class GH_LineCharge(GH_FieldElement,IGH_FieldElement,GH_ISerializable,IGH_PreviewData):
""" GH_LineCharge() """
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_LineCharge,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_LineCharge) -> IGH_FieldElement """
pass
def Force(self,location):
""" Force(self: GH_LineCharge,location: Point3d) -> Vector3d """
pass
def IsCoincident(self,point,tolerance):
""" IsCoincident(self: GH_LineCharge,point: Point3d,tolerance: float) -> bool """
pass
def Read(self,reader):
""" Read(self: GH_LineCharge,reader: GH_IReader) -> bool """
pass
def Write(self,writer):
""" Write(self: GH_LineCharge,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
BoundingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: BoundingBox(self: GH_LineCharge) -> BoundingBox
"""
Charge=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Charge(self: GH_LineCharge) -> float
Set: Charge(self: GH_LineCharge)=value
"""
ElementGuid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ElementGuid(self: GH_LineCharge) -> Guid
"""
Segment=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Segment(self: GH_LineCharge) -> Line
Set: Segment(self: GH_LineCharge)=value
"""
class GH_LonLatCoordinate(object,IGH_Goo,GH_ISerializable):
"""
GH_LonLatCoordinate()
GH_LonLatCoordinate(longitude: float,latitude: float)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_LonLatCoordinate,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_LonLatCoordinate,target: T) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_LonLatCoordinate) -> IGH_Goo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_LonLatCoordinate) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_LonLatCoordinate,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_LonLatCoordinate) -> object """
pass
def ToString(self):
""" ToString(self: GH_LonLatCoordinate) -> str """
pass
def Write(self,writer):
""" Write(self: GH_LonLatCoordinate,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,longitude=None,latitude=None):
"""
__new__(cls: type)
__new__(cls: type,longitude: float,latitude: float)
"""
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_LonLatCoordinate) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_LonLatCoordinate) -> str
"""
Latitude=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Latitude(self: GH_LonLatCoordinate) -> float
Set: Latitude(self: GH_LonLatCoordinate)=value
"""
Longitude=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Longitude(self: GH_LonLatCoordinate) -> float
Set: Longitude(self: GH_LonLatCoordinate)=value
"""
SphereUParameter=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: SphereUParameter(self: GH_LonLatCoordinate) -> float
"""
SphereVParameter=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: SphereVParameter(self: GH_LonLatCoordinate) -> float
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_LonLatCoordinate) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_LonLatCoordinate) -> str
"""
class GH_Material(GH_Goo[DisplayMaterial],IGH_Goo,GH_ISerializable):
"""
GH_Material()
GH_Material(rdk_id: Guid)
GH_Material(diffuse: Color)
GH_Material(other: DisplayMaterial)
GH_Material(other: GH_Material)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Material,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Material,target: T) -> (bool,T) """
pass
@staticmethod
def CreateStandardMaterial(colour):
""" CreateStandardMaterial(colour: Color) -> DisplayMaterial """
pass
def Duplicate(self):
""" Duplicate(self: GH_Material) -> IGH_Goo """
pass
def DuplicateMaterial(self):
""" DuplicateMaterial(self: GH_Material) -> GH_Material """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Material) -> IGH_GooProxy """
pass
@staticmethod
def GetModuleHandle(lpModuleName):
""" GetModuleHandle(lpModuleName: str) -> (IntPtr,str) """
pass
@staticmethod
def RDK_GetMaterial():
""" RDK_GetMaterial() -> Guid """
pass
@staticmethod
def RDK_GetMaterialSimulation(id,on_material_ptr):
""" RDK_GetMaterialSimulation(id: Guid,on_material_ptr: IntPtr) -> bool """
pass
def Read(self,reader):
""" Read(self: GH_Material,reader: GH_IReader) -> bool """
pass
def RefreshReferenceData(self):
""" RefreshReferenceData(self: GH_Material) -> RDK_GL_Result """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Material) -> object """
pass
def ToString(self):
""" ToString(self: GH_Material) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Material,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,rdk_id: Guid)
__new__(cls: type,diffuse: Color)
__new__(cls: type,other: DisplayMaterial)
__new__(cls: type,other: GH_Material)
"""
pass
def __str__(self,*args):
pass
IsReferencedShader=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsReferencedShader(self: GH_Material) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Material) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Material) -> str
"""
RDK_ID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: RDK_ID(self: GH_Material) -> Guid
Set: RDK_ID(self: GH_Material)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Material) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Material) -> str
"""
GH_Material_Proxy=None
m_rdk_id=None
m_value=None
RDK_GL_Result=None
class GH_Matrix(GH_Goo[Matrix],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_Matrix()
GH_Matrix(matrix: Matrix)
GH_Matrix(other: GH_Matrix)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Matrix,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Matrix) -> (bool,T) """
pass
@staticmethod
def CloneMatrix(matrix):
""" CloneMatrix(matrix: Matrix) -> Matrix """
pass
def Duplicate(self):
""" Duplicate(self: GH_Matrix) -> IGH_Goo """
pass
def DuplicateMatrix(self):
""" DuplicateMatrix(self: GH_Matrix) -> GH_Matrix """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_Matrix) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_Matrix) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_Matrix,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_Matrix) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_Matrix,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_Matrix) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_Matrix) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_Matrix) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_Matrix) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_Matrix) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_Matrix) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_Matrix) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_Matrix) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_Matrix,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Matrix) -> object """
pass
def ToString(self):
""" ToString(self: GH_Matrix) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Matrix,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,matrix: Matrix)
__new__(cls: type,other: GH_Matrix)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Matrix) -> bool
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_Matrix) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Matrix) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Matrix) -> str
"""
m_value=None
class GH_Mesh(GH_GeometricGoo[Mesh],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_Mesh()
GH_Mesh(mesh: Mesh)
GH_Mesh(id: Guid)
GH_Mesh(other: GH_Mesh)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Mesh,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Mesh,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Mesh) -> (bool,T) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_Mesh) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Mesh,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Mesh,args: GH_PreviewWireArgs) """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Mesh) -> IGH_GeometricGoo """
pass
def DuplicateMesh(self):
""" DuplicateMesh(self: GH_Mesh) -> GH_Mesh """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Mesh) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Mesh,xform: Transform) -> BoundingBox """
pass
def LoadGeometry(self,doc=None):
""" LoadGeometry(self: GH_Mesh,doc: RhinoDoc) -> bool """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Mesh,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Mesh,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Mesh) -> object """
pass
def ToString(self):
""" ToString(self: GH_Mesh) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Mesh,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Mesh,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,mesh: Mesh)
__new__(cls: type,id: Guid)
__new__(cls: type,other: GH_Mesh)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Mesh) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Mesh) -> BoundingBox
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_Mesh) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Mesh) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Mesh) -> str
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_Mesh) -> Guid
Set: ReferenceID(self: GH_Mesh)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Mesh) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Mesh) -> str
"""
GH_MeshProxy=None
m_value=None
class GH_MeshFace(GH_Goo[MeshFace],IGH_Goo,GH_ISerializable):
"""
GH_MeshFace()
GH_MeshFace(nA: int,nB: int,nC: int)
GH_MeshFace(nA: int,nB: int,nC: int,nD: int)
GH_MeshFace(other: MeshFace)
GH_MeshFace(other: GH_MeshFace)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_MeshFace,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_MeshFace,target: T) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_MeshFace) -> IGH_Goo """
pass
def DuplicateMeshFace(self):
""" DuplicateMeshFace(self: GH_MeshFace) -> GH_MeshFace """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_MeshFace) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_MeshFace,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_MeshFace) -> str """
pass
def Write(self,writer):
""" Write(self: GH_MeshFace,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,nA: int,nB: int,nC: int)
__new__(cls: type,nA: int,nB: int,nC: int,nD: int)
__new__(cls: type,other: MeshFace)
__new__(cls: type,other: GH_MeshFace)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_MeshFace) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_MeshFace) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_MeshFace) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_MeshFace) -> str
"""
GH_MeshFaceProxy=None
m_value=None
class GH_MeshingParameters(GH_Goo[MeshingParameters],IGH_Goo,GH_ISerializable):
"""
GH_MeshingParameters()
GH_MeshingParameters(other: MeshingParameters)
"""
def Duplicate(self):
""" Duplicate(self: GH_MeshingParameters) -> IGH_Goo """
pass
def DuplicateMesherSettings(self):
""" DuplicateMesherSettings(self: GH_MeshingParameters) -> GH_MeshingParameters """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_MeshingParameters) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_MeshingParameters,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_MeshingParameters) -> str """
pass
def Write(self,writer):
""" Write(self: GH_MeshingParameters,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,other=None):
"""
__new__(cls: type)
__new__(cls: type,other: MeshingParameters)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_MeshingParameters) -> bool
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_MeshingParameters) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_MeshingParameters) -> str
"""
m_value=None
RhMesherSettings_Proxy=None
class GH_Number(GH_Goo[float],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_Number()
GH_Number(number: float)
GH_Number(other: GH_Number)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Number,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Number) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Number) -> IGH_Goo """
pass
def DuplicateNumber(self):
""" DuplicateNumber(self: GH_Number) -> GH_Number """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Number) -> IGH_GooProxy """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_Number) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_Number) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_Number,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_Number) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_Number,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_Number) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_Number) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_Number) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_Number) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_Number) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_Number) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_Number) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_Number) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_Number,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Number) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Number,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,number: float)
__new__(cls: type,other: GH_Number)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Number) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Number) -> str
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_Number) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Number) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Number) -> str
"""
m_value=None
class GH_ObjectWrapper(GH_Goo[object],IGH_Goo,GH_ISerializable,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_ObjectWrapper()
GH_ObjectWrapper(obj: object)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_ObjectWrapper,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_ObjectWrapper,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_ObjectWrapper) -> (bool,T) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_ObjectWrapper,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_ObjectWrapper,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_ObjectWrapper) -> IGH_Goo """
pass
def DuplicateObject(self):
""" DuplicateObject(self: GH_ObjectWrapper) -> GH_ObjectWrapper """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_ObjectWrapper) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_ObjectWrapper,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_ObjectWrapper) -> object """
pass
def ToString(self):
""" ToString(self: GH_ObjectWrapper) -> str """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,obj=None):
"""
__new__(cls: type)
__new__(cls: type,obj: object)
"""
pass
def __str__(self,*args):
pass
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_ObjectWrapper) -> BoundingBox
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_ObjectWrapper) -> bool
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_ObjectWrapper) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_ObjectWrapper) -> str
"""
m_value=None
class GH_Plane(GH_GeometricGoo[Plane],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_Plane()
GH_Plane(plane: Plane)
GH_Plane(other: GH_Plane)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Plane,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Plane,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Plane) -> (bool,T) """
pass
@staticmethod
def DrawPlane(display,plane,size=None,frequency=None,grid_color=None,x_color=None,y_color=None,back_color=None):
""" DrawPlane(display: DisplayPipeline,plane: Plane,size: float,frequency: int,grid_color: Color,x_color: Color,y_color: Color)DrawPlane(display: DisplayPipeline,plane: Plane,size: float,frequency: int,grid_color: Color,x_color: Color,y_color: Color,back_color: Color)DrawPlane(display: DisplayPipeline,plane: Plane)DrawPlane(display: DisplayPipeline,plane: Plane,size: float,frequency: int) """
pass
@staticmethod
def DrawPlaneIcon(display,plane,size,edgeColour,fillColour):
""" DrawPlaneIcon(display: DisplayPipeline,plane: Plane,size: float,edgeColour: Color,fillColour: Color) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Plane,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Plane,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Plane) -> IGH_Goo """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Plane) -> IGH_GeometricGoo """
pass
def DuplicatePlane(self):
""" DuplicatePlane(self: GH_Plane) -> GH_Plane """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Plane) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Plane,xform: Transform) -> BoundingBox """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Plane,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Plane,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Plane) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Plane,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Plane,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,plane: Plane)
__new__(cls: type,other: GH_Plane)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Plane) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Plane) -> BoundingBox
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Plane) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Plane) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Plane) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Plane) -> str
"""
GH_PlaneProxy=None
m_value=None
class GH_Point(object,IGH_GeometricGoo,IGH_Goo,GH_ISerializable,IGH_BakeAwareData,IGH_PreviewData,IGH_QuickCast):
"""
GH_Point()
GH_Point(pt: Point3d)
GH_Point(iOther: GH_Point)
GH_Point(rh_obj_id: Guid)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Point,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Point,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Point) -> (bool,T) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_Point) """
pass
def CreateFromCoordinate(self,pt):
""" CreateFromCoordinate(self: GH_Point,pt: Point3d) """
pass
def CreateFromCurveDistance(self,crv_id,crv,t,bFromStart):
""" CreateFromCurveDistance(self: GH_Point,crv_id: Guid,crv: Curve,t: float,bFromStart: bool) """
pass
def CreateFromCurveRatio(self,crv_id,crv,t):
""" CreateFromCurveRatio(self: GH_Point,crv_id: Guid,crv: Curve,t: float) """
pass
def CreateFromEdgeDistance(self,brp_id,edge,e_index,t,bFromStart):
""" CreateFromEdgeDistance(self: GH_Point,brp_id: Guid,edge: Curve,e_index: int,t: float,bFromStart: bool) """
pass
def CreateFromEdgeRatio(self,brp_id,edge,e_index,t):
""" CreateFromEdgeRatio(self: GH_Point,brp_id: Guid,edge: Curve,e_index: int,t: float) """
pass
def CreateFromPointObject(self,id):
""" CreateFromPointObject(self: GH_Point,id: Guid) """
pass
def CreateFromSurfaceParam(self,brp_id,f_index,srf,u,v):
""" CreateFromSurfaceParam(self: GH_Point,brp_id: Guid,f_index: int,srf: Surface,u: float,v: float) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Point,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Point,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Point) -> IGH_Goo """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Point) -> IGH_GeometricGoo """
pass
def DuplicatePoint(self):
""" DuplicatePoint(self: GH_Point) -> GH_Point """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Point) -> IGH_GooProxy """
pass
def EnsureReferenceData(self):
""" EnsureReferenceData(self: GH_Point) """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Point,xform: Transform) -> BoundingBox """
pass
def LoadGeometry(self,doc=None):
"""
LoadGeometry(self: GH_Point,doc: RhinoDoc) -> bool
LoadGeometry(self: GH_Point) -> bool
"""
pass
def Morph(self,xmorph):
""" Morph(self: GH_Point,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_Point) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_Point) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_Point,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_Point) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_Point,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_Point) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_Point) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_Point) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_Point) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_Point) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_Point) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_Point) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_Point) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_Point,reader: GH_IReader) -> bool """
pass
def ReferenceCurve(self,ref=None):
"""
ReferenceCurve(self: GH_Point,ref: RhinoObject) -> Curve
ReferenceCurve(self: GH_Point) -> Curve
"""
pass
def ReferenceIndex(self,new_index=None):
""" ReferenceIndex(self: GH_Point,new_index: int)ReferenceIndex(self: GH_Point) -> int """
pass
def ReferenceParam(self,index,new_param=None):
""" ReferenceParam(self: GH_Point,index: int,new_param: float)ReferenceParam(self: GH_Point,index: int) -> float """
pass
def ReferencesCurve(self):
""" ReferencesCurve(self: GH_Point) -> bool """
pass
def ReferencesEdge(self):
""" ReferencesEdge(self: GH_Point) -> bool """
pass
def ReferenceSurface(self):
""" ReferenceSurface(self: GH_Point) -> BrepFace """
pass
def ReferenceType(self,new_type=None):
""" ReferenceType(self: GH_Point,new_type: GH_PointRefType)ReferenceType(self: GH_Point) -> GH_PointRefType """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Point) -> object """
pass
def SetReferenceParams(self,u,v):
""" SetReferenceParams(self: GH_Point,u: float,v: float) """
pass
def ShowReferenceDialog(self,owner=None):
"""
ShowReferenceDialog(self: GH_Point,owner: IWin32Window) -> DialogResult
ShowReferenceDialog(self: GH_Point) -> DialogResult
"""
pass
def ToString(self):
""" ToString(self: GH_Point) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Point,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Point,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,pt: Point3d)
__new__(cls: type,iOther: GH_Point)
__new__(cls: type,rh_obj_id: Guid)
"""
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Point) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Point) -> BoundingBox
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_Point) -> bool
"""
IsReferencedGeometry=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsReferencedGeometry(self: GH_Point) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Point) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Point) -> str
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_Point) -> GH_QuickCastType
"""
ReferenceData=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceData(self: GH_Point) -> GH_PointRefData
Set: ReferenceData(self: GH_Point)=value
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_Point) -> Guid
Set: ReferenceID(self: GH_Point)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Point) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Point) -> str
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_Point) -> Point3d
Set: Value(self: GH_Point)=value
"""
GH_PointProxy=None
class GH_PointCharge(GH_FieldElement,IGH_FieldElement,GH_ISerializable,IGH_PreviewData):
""" GH_PointCharge() """
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_PointCharge,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_PointCharge) -> IGH_FieldElement """
pass
def Force(self,location):
""" Force(self: GH_PointCharge,location: Point3d) -> Vector3d """
pass
def IsCoincident(self,point,tolerance):
""" IsCoincident(self: GH_PointCharge,point: Point3d,tolerance: float) -> bool """
pass
def Read(self,reader):
""" Read(self: GH_PointCharge,reader: GH_IReader) -> bool """
pass
def Write(self,writer):
""" Write(self: GH_PointCharge,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
BoundingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: BoundingBox(self: GH_PointCharge) -> BoundingBox
"""
Charge=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Charge(self: GH_PointCharge) -> float
Set: Charge(self: GH_PointCharge)=value
"""
Decay=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Decay(self: GH_PointCharge) -> float
Set: Decay(self: GH_PointCharge)=value
"""
ElementGuid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ElementGuid(self: GH_PointCharge) -> Guid
"""
Location=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Location(self: GH_PointCharge) -> Point3d
Set: Location(self: GH_PointCharge)=value
"""
class GH_PointRefData(object):
"""
GH_PointRefData()
GH_PointRefData(iOther: GH_PointRefData)
"""
def EvCurve(self,c):
""" EvCurve(self: GH_PointRefData,c: Curve) -> Point3d """
pass
def EvCurveParam(self,c):
""" EvCurveParam(self: GH_PointRefData,c: Curve) -> float """
pass
def EvSurface(self,s):
""" EvSurface(self: GH_PointRefData,s: Surface) -> Point3d """
pass
def SetCurveDistFromEndParam(self,*args):
""" SetCurveDistFromEndParam(self: GH_PointRefData,c: Curve,t: float) -> bool """
pass
def SetCurveDistFromStartParam(self,*args):
""" SetCurveDistFromStartParam(self: GH_PointRefData,c: Curve,t: float) -> bool """
pass
def SetCurveParam(self,c,t):
""" SetCurveParam(self: GH_PointRefData,c: Curve,t: float) -> bool """
pass
def SetCurveRatioParam(self,*args):
""" SetCurveRatioParam(self: GH_PointRefData,c: Curve,t: float) -> bool """
pass
def SetSurfaceParam(self,srf,u,v):
""" SetSurfaceParam(self: GH_PointRefData,srf: Surface,u: float,v: float) -> bool """
pass
@staticmethod
def __new__(self,iOther=None):
"""
__new__(cls: type)
__new__(cls: type,iOther: GH_PointRefData)
"""
pass
m_RefID=None
m_RefIndex=None
m_RefParam=None
m_RefType=None
class GH_PointRefType(Enum,IComparable,IFormattable,IConvertible):
""" enum GH_PointRefType,values: coordinate (1),curve_dist_end (12),curve_dist_start (11),curve_ratio (10),point_object (2),srf_param (20) """
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
coordinate=None
curve_dist_end=None
curve_dist_start=None
curve_ratio=None
point_object=None
srf_param=None
value__=None
class GH_PointUtil(object):
# no doc
@staticmethod
def FitPlaneThroughPoints(pts):
""" FitPlaneThroughPoints(pts: IEnumerable[GH_Point]) -> Plane """
pass
@staticmethod
def ProjectPointsToPlane(pts,plane,include_nulls):
""" ProjectPointsToPlane(pts: IEnumerable[GH_Point],plane: Plane,include_nulls: bool) -> List[GH_Point] """
pass
@staticmethod
def PullPointsToPlane(pts,plane,include_nulls):
""" PullPointsToPlane(pts: IEnumerable[GH_Point],plane: Plane,include_nulls: bool) -> List[GH_Point] """
pass
@staticmethod
def RemapPointsToPlane(pts,plane,include_nulls):
""" RemapPointsToPlane(pts: IEnumerable[GH_Point],plane: Plane,include_nulls: bool) -> List[GH_Point] """
pass
class GH_QuickCastType(Enum,IComparable,IFormattable,IConvertible):
""" enum GH_QuickCastType,values: bool (0),col (4),complex (7),int (1),interval (8),matrix (9),num (2),pt (5),text (3),vec (6) """
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
bool=None
col=None
complex=None
int=None
interval=None
matrix=None
num=None
pt=None
text=None
value__=None
vec=None
class GH_Rectangle(GH_GeometricGoo[Rectangle3d],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData):
"""
GH_Rectangle()
GH_Rectangle(rec: Rectangle3d)
GH_Rectangle(other: GH_Rectangle)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Rectangle,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Rectangle,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Rectangle) -> (bool,T) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Rectangle,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Rectangle,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Rectangle) -> IGH_Goo """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Rectangle) -> IGH_GeometricGoo """
pass
def DuplicateRectangle(self):
""" DuplicateRectangle(self: GH_Rectangle) -> GH_Rectangle """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Rectangle) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Rectangle,xform: Transform) -> BoundingBox """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Rectangle,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Rectangle,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Rectangle) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Rectangle,xform: Transform) -> IGH_GeometricGoo """
pass
def Write(self,writer):
""" Write(self: GH_Rectangle,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,rec: Rectangle3d)
__new__(cls: type,other: GH_Rectangle)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Rectangle) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Rectangle) -> BoundingBox
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Rectangle) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Rectangle) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Rectangle) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Rectangle) -> str
"""
GH_RectangleProxy=None
m_value=None
class GH_SpinForce(GH_FieldElement,IGH_FieldElement,GH_ISerializable,IGH_PreviewData):
""" GH_SpinForce() """
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_SpinForce,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_SpinForce) -> IGH_FieldElement """
pass
def Force(self,location):
""" Force(self: GH_SpinForce,location: Point3d) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_SpinForce,reader: GH_IReader) -> bool """
pass
def Write(self,writer):
""" Write(self: GH_SpinForce,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
BoundingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: BoundingBox(self: GH_SpinForce) -> BoundingBox
"""
Decay=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Decay(self: GH_SpinForce) -> float
Set: Decay(self: GH_SpinForce)=value
"""
ElementGuid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ElementGuid(self: GH_SpinForce) -> Guid
"""
Plane=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Plane(self: GH_SpinForce) -> Plane
Set: Plane(self: GH_SpinForce)=value
"""
Radius=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Radius(self: GH_SpinForce) -> float
Set: Radius(self: GH_SpinForce)=value
"""
Strength=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Strength(self: GH_SpinForce) -> float
Set: Strength(self: GH_SpinForce)=value
"""
class GH_String(GH_Goo[str],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_String()
GH_String(str: str)
GH_String(other: GH_String)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_String,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_String) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_String) -> IGH_Goo """
pass
def DuplicateString(self):
""" DuplicateString(self: GH_String) -> GH_String """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_String) -> IGH_GooProxy """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_String) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_String) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_String,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_String) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_String,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_String) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_String) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_String) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_String) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_String) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_String) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_String) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_String) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_String,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_String) -> str """
pass
def Write(self,writer):
""" Write(self: GH_String,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,str: str)
__new__(cls: type,other: GH_String)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_String) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_String) -> str
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_String) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_String) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_String) -> str
"""
m_value=None
class GH_StructurePath(GH_Goo[GH_Path],IGH_Goo,GH_ISerializable):
"""
GH_StructurePath()
GH_StructurePath(path: GH_Path)
GH_StructurePath(other: GH_StructurePath)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_StructurePath,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_StructurePath) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_StructurePath) -> IGH_Goo """
pass
def DuplicatePath(self):
""" DuplicatePath(self: GH_StructurePath) -> GH_StructurePath """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_StructurePath) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_StructurePath,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_StructurePath) -> object """
pass
def ToString(self):
""" ToString(self: GH_StructurePath) -> str """
pass
def Write(self,writer):
""" Write(self: GH_StructurePath,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,path: GH_Path)
__new__(cls: type,other: GH_StructurePath)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_StructurePath) -> bool
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_StructurePath) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_StructurePath) -> str
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_StructurePath) -> GH_Path
Set: Value(self: GH_StructurePath)=value
"""
m_value=None
class GH_Surface(GH_GeometricGoo[Brep],IGH_Goo,GH_ISerializable,IGH_GeometricGoo,IGH_BakeAwareData,IGH_PreviewData,IGH_PreviewMeshData):
"""
GH_Surface()
GH_Surface(srf: Surface)
GH_Surface(brep: Brep)
GH_Surface(id: Guid)
GH_Surface(other: GH_Surface)
"""
def BakeGeometry(self,doc,att,obj_guid):
""" BakeGeometry(self: GH_Surface,doc: RhinoDoc,att: ObjectAttributes,obj_guid: Guid) -> (bool,Guid) """
pass
def CastFrom(self,source):
""" CastFrom(self: GH_Surface,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Surface) -> (bool,T) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_Surface) """
pass
def DestroyPreviewMeshes(self):
""" DestroyPreviewMeshes(self: GH_Surface) """
pass
def DrawViewportMeshes(self,args):
""" DrawViewportMeshes(self: GH_Surface,args: GH_PreviewMeshArgs) """
pass
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_Surface,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Surface) -> IGH_Goo """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: GH_Surface) -> IGH_GeometricGoo """
pass
def DuplicateSurface(self):
""" DuplicateSurface(self: GH_Surface) -> GH_Surface """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Surface) -> IGH_GooProxy """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: GH_Surface,xform: Transform) -> BoundingBox """
pass
def GetPreviewMeshes(self):
""" GetPreviewMeshes(self: GH_Surface) -> Array[Mesh] """
pass
def IsPointOnDomain(self,u,v):
""" IsPointOnDomain(self: GH_Surface,u: float,v: float) -> bool """
pass
def IsPointOnFace(self,u,v):
""" IsPointOnFace(self: GH_Surface,u: float,v: float) -> bool """
pass
def LoadGeometry(self,doc=None):
""" LoadGeometry(self: GH_Surface,doc: RhinoDoc) -> bool """
pass
def Morph(self,xmorph):
""" Morph(self: GH_Surface,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Read(self,reader):
""" Read(self: GH_Surface,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Surface) -> object """
pass
def ToString(self):
""" ToString(self: GH_Surface) -> str """
pass
def Transform(self,xform):
""" Transform(self: GH_Surface,xform: Transform) -> IGH_GeometricGoo """
pass
def Untrim(self):
""" Untrim(self: GH_Surface) -> bool """
pass
def Write(self,writer):
""" Write(self: GH_Surface,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,srf: Surface)
__new__(cls: type,brep: Brep)
__new__(cls: type,id: Guid)
__new__(cls: type,other: GH_Surface)
"""
pass
def __str__(self,*args):
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: GH_Surface) -> BoundingBox
"""
ClippingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ClippingBox(self: GH_Surface) -> BoundingBox
"""
Face=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Face(self: GH_Surface) -> BrepFace
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: GH_Surface) -> bool
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Surface) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Surface) -> str
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: GH_Surface) -> Guid
Set: ReferenceID(self: GH_Surface)=value
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Surface) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Surface) -> str
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_Surface) -> Brep
Set: Value(self: GH_Surface)=value
"""
GH_SurfaceProxy=None
m_value=None
class GH_Time(GH_Goo[DateTime],IGH_Goo,GH_ISerializable):
"""
GH_Time()
GH_Time(time: DateTime)
GH_Time(other: GH_Time)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Time,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Time) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Time) -> IGH_Goo """
pass
def DuplicateDateTime(self):
""" DuplicateDateTime(self: GH_Time) -> GH_Time """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Time) -> IGH_GooProxy """
pass
def Read(self,reader):
""" Read(self: GH_Time,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Time) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Time,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,time: DateTime)
__new__(cls: type,other: GH_Time)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Time) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Time) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Time) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Time) -> str
"""
m_value=None
class GH_Transform(GH_Goo[Transform],IGH_Goo,GH_ISerializable):
"""
GH_Transform()
GH_Transform(transform: ITransform)
GH_Transform(transform: Transform)
GH_Transform(other: GH_Transform)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Transform,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[Q](self: GH_Transform,target: Q) -> (bool,Q) """
pass
def ClearCaches(self):
""" ClearCaches(self: GH_Transform) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Transform) -> IGH_Goo """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Transform) -> IGH_GooProxy """
pass
def GetInverse(self):
""" GetInverse(self: GH_Transform) -> GH_Transform """
pass
def Read(self,reader):
""" Read(self: GH_Transform,reader: GH_IReader) -> bool """
pass
def ScriptVariable(self):
""" ScriptVariable(self: GH_Transform) -> object """
pass
def ToString(self):
""" ToString(self: GH_Transform) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Transform,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,transform: ITransform)
__new__(cls: type,transform: Transform)
__new__(cls: type,other: GH_Transform)
"""
pass
def __str__(self,*args):
pass
CompoundTransforms=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: CompoundTransforms(self: GH_Transform) -> List[ITransform]
"""
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Transform) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: GH_Transform) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Transform) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Transform) -> str
"""
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_Transform) -> Transform
Set: Value(self: GH_Transform)=value
"""
m_value=None
class GH_Vector(GH_Goo[Vector3d],IGH_Goo,GH_ISerializable,IGH_QuickCast):
"""
GH_Vector()
GH_Vector(vector: Vector3d)
GH_Vector(other: GH_Vector)
"""
def CastFrom(self,source):
""" CastFrom(self: GH_Vector,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: GH_Vector) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: GH_Vector) -> IGH_Goo """
pass
def DuplicateVector(self):
""" DuplicateVector(self: GH_Vector) -> GH_Vector """
pass
def EmitProxy(self):
""" EmitProxy(self: GH_Vector) -> IGH_GooProxy """
pass
def QC_Bool(self):
""" QC_Bool(self: GH_Vector) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: GH_Vector) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: GH_Vector,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: GH_Vector) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: GH_Vector,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: GH_Vector) -> int """
pass
def QC_Int(self):
""" QC_Int(self: GH_Vector) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: GH_Vector) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: GH_Vector) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: GH_Vector) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: GH_Vector) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: GH_Vector) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: GH_Vector) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_Vector,reader: GH_IReader) -> bool """
pass
def ToString(self):
""" ToString(self: GH_Vector) -> str """
pass
def Write(self,writer):
""" Write(self: GH_Vector,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,*__args):
"""
__new__(cls: type)
__new__(cls: type,vector: Vector3d)
__new__(cls: type,other: GH_Vector)
"""
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: GH_Vector) -> bool
"""
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: GH_Vector) -> GH_QuickCastType
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: GH_Vector) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: GH_Vector) -> str
"""
GH_VectorProxy=None
m_value=None
class GH_VectorForce(GH_FieldElement,IGH_FieldElement,GH_ISerializable,IGH_PreviewData):
""" GH_VectorForce() """
def DrawViewportWires(self,args):
""" DrawViewportWires(self: GH_VectorForce,args: GH_PreviewWireArgs) """
pass
def Duplicate(self):
""" Duplicate(self: GH_VectorForce) -> IGH_FieldElement """
pass
def Force(self,location):
""" Force(self: GH_VectorForce,location: Point3d) -> Vector3d """
pass
def Read(self,reader):
""" Read(self: GH_VectorForce,reader: GH_IReader) -> bool """
pass
def Write(self,writer):
""" Write(self: GH_VectorForce,writer: GH_IWriter) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
BoundingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: BoundingBox(self: GH_VectorForce) -> BoundingBox
"""
Chord=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Chord(self: GH_VectorForce) -> Line
Set: Chord(self: GH_VectorForce)=value
"""
ElementGuid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ElementGuid(self: GH_VectorForce) -> Guid
"""
class GH_WrapperType(object):
# no doc
@staticmethod
def __new__(self,*args): #cannot find CLR constructor
"""
__new__(cls: type)
__new__(cls: type,data: T)
"""
pass
Value=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Value(self: GH_WrapperType[T]) -> T
Set: Value(self: GH_WrapperType[T])=value
"""
m_value=None
class IGH_FieldElement(GH_ISerializable,IGH_PreviewData):
# no doc
def Duplicate(self):
""" Duplicate(self: IGH_FieldElement) -> IGH_FieldElement """
pass
def Force(self,location):
""" Force(self: IGH_FieldElement,location: Point3d) -> Vector3d """
pass
def IsCoincident(self,point,tolerance):
""" IsCoincident(self: IGH_FieldElement,point: Point3d,tolerance: float) -> bool """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
BoundingBox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: BoundingBox(self: IGH_FieldElement) -> BoundingBox
"""
ElementGuid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ElementGuid(self: IGH_FieldElement) -> Guid
"""
IsLimited=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsLimited(self: IGH_FieldElement) -> bool
Set: IsLimited(self: IGH_FieldElement)=value
"""
Limits=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Limits(self: IGH_FieldElement) -> Box
Set: Limits(self: IGH_FieldElement)=value
"""
class IGH_Goo(GH_ISerializable):
# no doc
def CastFrom(self,source):
""" CastFrom(self: IGH_Goo,source: object) -> bool """
pass
def CastTo(self,target):
""" CastTo[T](self: IGH_Goo) -> (bool,T) """
pass
def Duplicate(self):
""" Duplicate(self: IGH_Goo) -> IGH_Goo """
pass
def EmitProxy(self):
""" EmitProxy(self: IGH_Goo) -> IGH_GooProxy """
pass
def ScriptVariable(self):
""" ScriptVariable(self: IGH_Goo) -> object """
pass
def ToString(self):
""" ToString(self: IGH_Goo) -> str """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __str__(self,*args):
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: IGH_Goo) -> bool
"""
IsValidWhyNot=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValidWhyNot(self: IGH_Goo) -> str
"""
TypeDescription=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeDescription(self: IGH_Goo) -> str
"""
TypeName=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: TypeName(self: IGH_Goo) -> str
"""
class IGH_GeometricGoo(IGH_Goo,GH_ISerializable):
# no doc
def ClearCaches(self):
""" ClearCaches(self: IGH_GeometricGoo) """
pass
def DuplicateGeometry(self):
""" DuplicateGeometry(self: IGH_GeometricGoo) -> IGH_GeometricGoo """
pass
def GetBoundingBox(self,xform):
""" GetBoundingBox(self: IGH_GeometricGoo,xform: Transform) -> BoundingBox """
pass
def LoadGeometry(self,doc=None):
"""
LoadGeometry(self: IGH_GeometricGoo,doc: RhinoDoc) -> bool
LoadGeometry(self: IGH_GeometricGoo) -> bool
"""
pass
def Morph(self,xmorph):
""" Morph(self: IGH_GeometricGoo,xmorph: SpaceMorph) -> IGH_GeometricGoo """
pass
def Transform(self,xform):
""" Transform(self: IGH_GeometricGoo,xform: Transform) -> IGH_GeometricGoo """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
Boundingbox=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Boundingbox(self: IGH_GeometricGoo) -> BoundingBox
"""
IsGeometryLoaded=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsGeometryLoaded(self: IGH_GeometricGoo) -> bool
"""
IsReferencedGeometry=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsReferencedGeometry(self: IGH_GeometricGoo) -> bool
"""
ReferenceID=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ReferenceID(self: IGH_GeometricGoo) -> Guid
Set: ReferenceID(self: IGH_GeometricGoo)=value
"""
class IGH_GooProxy:
# no doc
def Construct(self):
""" Construct(self: IGH_GooProxy) """
pass
def FormatInstance(self):
""" FormatInstance(self: IGH_GooProxy) -> str """
pass
def FromString(self,in):
""" FromString(self: IGH_GooProxy,in: str) -> bool """
pass
def MutateString(self,in):
""" MutateString(self: IGH_GooProxy,in: str) -> str """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
IsParsable=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsParsable(self: IGH_GooProxy) -> bool
"""
ProxyOwner=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: ProxyOwner(self: IGH_GooProxy) -> IGH_Goo
"""
UserString=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: UserString(self: IGH_GooProxy) -> str
Set: UserString(self: IGH_GooProxy)=value
"""
Valid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Valid(self: IGH_GooProxy) -> bool
"""
class IGH_QuickCast:
# no doc
def QC_Bool(self):
""" QC_Bool(self: IGH_QuickCast) -> bool """
pass
def QC_Col(self):
""" QC_Col(self: IGH_QuickCast) -> Color """
pass
def QC_CompareTo(self,other):
""" QC_CompareTo(self: IGH_QuickCast,other: IGH_QuickCast) -> int """
pass
def QC_Complex(self):
""" QC_Complex(self: IGH_QuickCast) -> Complex """
pass
def QC_Distance(self,other):
""" QC_Distance(self: IGH_QuickCast,other: IGH_QuickCast) -> float """
pass
def QC_Hash(self):
""" QC_Hash(self: IGH_QuickCast) -> int """
pass
def QC_Int(self):
""" QC_Int(self: IGH_QuickCast) -> int """
pass
def QC_Interval(self):
""" QC_Interval(self: IGH_QuickCast) -> Interval """
pass
def QC_Matrix(self):
""" QC_Matrix(self: IGH_QuickCast) -> Matrix """
pass
def QC_Num(self):
""" QC_Num(self: IGH_QuickCast) -> float """
pass
def QC_Pt(self):
""" QC_Pt(self: IGH_QuickCast) -> Point3d """
pass
def QC_Text(self):
""" QC_Text(self: IGH_QuickCast) -> str """
pass
def QC_Vec(self):
""" QC_Vec(self: IGH_QuickCast) -> Vector3d """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
QC_Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: QC_Type(self: IGH_QuickCast) -> GH_QuickCastType
"""
class UVInterval(object):
""" UVInterval(newU: Interval,newV: Interval) """
@staticmethod
def __new__(self,newU,newV):
"""
__new__(cls: type,newU: Interval,newV: Interval)
__new__[UVInterval]() -> UVInterval
"""
pass
IsValid=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: IsValid(self: UVInterval) -> bool
"""
U=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: U(self: UVInterval) -> Interval
Set: U(self: UVInterval)=value
"""
U0=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: U0(self: UVInterval) -> float
Set: U0(self: UVInterval)=value
"""
U1=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: U1(self: UVInterval) -> float
Set: U1(self: UVInterval)=value
"""
V=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: V(self: UVInterval) -> Interval
Set: V(self: UVInterval)=value
"""
V0=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: V0(self: UVInterval) -> float
Set: V0(self: UVInterval)=value
"""
V1=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: V1(self: UVInterval) -> float
Set: V1(self: UVInterval)=value
"""
# variables with complex values
|
lte/gateway/python/magma/kernsnoopd/tests/byte_counter_tests.py | nstng/magma | 539 | 12605883 | """
Copyright 2020 The Magma Authors.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import unittest
from socket import AF_INET, AF_INET6, htons
from unittest.mock import MagicMock
from magma.kernsnoopd.handlers import ByteCounter
class MockServiceRegistry:
@staticmethod
def list_services():
return ['sessiond', 'subscriberdb']
@staticmethod
def get_service_name(host, port):
service_map = {
('127.0.0.1', 80): 'sessiond',
('127.0.0.1', 443): 'subscriberdb',
}
return service_map[(host, port)]
class ByteCounterTests(unittest.TestCase):
# pylint: disable=protected-access
"""Tests for ByteCounter eBPF handler class"""
def setUp(self) -> None:
registry = MockServiceRegistry()
self.byte_counter = ByteCounter(registry)
@unittest.mock.patch('psutil.Process')
def test_get_source_service_python(self, process_mock):
"""
Test _get_source_service Python service happy path
"""
cmdline_value = 'python3 -m magma.subscriberdb.main'.split(' ')
process_mock.return_value.cmdline.return_value = cmdline_value
key = MagicMock()
self.assertEqual(
'subscriberdb',
self.byte_counter._get_source_service(key),
)
@unittest.mock.patch('psutil.Process')
def test_get_source_service_index_error_with_fallback(self, process_mock):
"""
Test _get_source_service sessiond in service list
"""
cmdline_value = 'sessiond'.split(' ')
process_mock.return_value.cmdline.return_value = cmdline_value
key = MagicMock()
key.comm = b'sessiond'
self.assertEqual(
'sessiond',
self.byte_counter._get_source_service(key),
)
@unittest.mock.patch('psutil.Process')
def test_get_source_service_index_error_fail(self, process_mock):
"""
Test _get_source_service sshd not in service list
"""
cmdline_value = 'sshd'.split(' ')
process_mock.return_value.cmdline.return_value = cmdline_value
key = MagicMock()
key.comm = b'sshd'
self.assertRaises(
ValueError, self.byte_counter._get_source_service,
key,
)
def test_check_cmdline_for_magma_service_python_service_found(self):
"""
Test _check_cmdline_for_magma_service python service name found in cmdline
"""
cmdline_value = 'python3 -m magma.subscriberdb.main'.split(' ')
self.assertEqual(
'subscriberdb',
self.byte_counter._get_service_from_cmdline(cmdline_value),
)
def test_check_cmdline_for_magma_service_native_service_found(self):
"""
Test _check_cmdline_for_magma_service native service name found in cmdline
"""
cmdline_value = 'foo bar magma.sessiond'.split(' ')
self.assertEqual(
'sessiond',
self.byte_counter._get_service_from_cmdline(cmdline_value),
)
def test_check_cmdline_for_magma_service_index_error(self):
"""
Test _check_cmdline_for_magma_service index error
"""
cmdline_value = 'sshd'.split(' ')
self.assertRaises(
IndexError, self.byte_counter._get_service_from_cmdline,
cmdline_value,
)
def test_check_cmdline_for_magma_service_magma_not_found(self):
"""
Test _check_cmdline_for_magma_service no magma. in cmdline
"""
cmdline_value = 'python3 -m subscriberdb.main'.split(' ')
self.assertIsNone(self.byte_counter._get_service_from_cmdline(cmdline_value))
@unittest.mock.patch('magma.kernsnoopd.metrics.MAGMA_BYTES_SENT_TOTAL')
@unittest.mock.patch('psutil.Process')
def test_handle_magma_counters(self, process_mock, bytes_count_mock):
"""
Test handle with Magma service to Magma service traffic
"""
bytes_count_mock.labels = MagicMock(return_value=MagicMock())
cmdline_value = 'python3 -m magma.subscriberdb.main'.split(' ')
process_mock.return_value.cmdline.return_value = cmdline_value
key = MagicMock()
key.family = AF_INET
# 16777343 is "127.0.0.1" packed as a 4 byte int
key.daddr = self.byte_counter.Addr(16777343, 0)
key.dport = htons(80)
count = MagicMock()
count.value = 100
bpf = {'dest_counters': {key: count}}
self.byte_counter.handle(bpf)
bytes_count_mock.labels.assert_called_once_with(
service_name='subscriberdb', dest_service='',
)
bytes_count_mock.labels.return_value.inc.assert_called_once_with(100)
@unittest.mock.patch('magma.kernsnoopd.metrics.LINUX_BYTES_SENT_TOTAL')
@unittest.mock.patch('psutil.Process')
def test_handle_linux_counters(self, process_mock, bytes_count_mock):
"""
Test handle with Linux binary traffic
"""
bytes_count_mock.labels = MagicMock(return_value=MagicMock())
cmdline_value = 'sshd'.split(' ')
process_mock.return_value.cmdline.return_value = cmdline_value
key = MagicMock()
key.comm = b'sshd'
key.family = AF_INET6
# localhost in IPv6 with embedded IPv4
# fdf8:f53e:61e4::18:127.0.0.1 = 0x0100007FFFFF0000
key.daddr = self.byte_counter.Addr(0, 0x0100007FFFFF0000)
count = MagicMock()
count.value = 100
bpf = {'dest_counters': {key: count}}
self.byte_counter.handle(bpf)
bytes_count_mock.labels.assert_called_once_with('sshd')
bytes_count_mock.labels.return_value.inc.assert_called_once_with(100)
|
oandapyV20-examples-master/src/instruments_list.py | cdibble2011/OANDA | 127 | 12605904 | # -*- coding: utf-8 -*-
"""retrieve the tradable instruments for account."""
import json
import oandapyV20
import oandapyV20.endpoints.accounts as accounts
from exampleauth import exampleAuth
accountID, token = exampleAuth()
client = oandapyV20.API(access_token=token)
r = accounts.AccountInstruments(accountID=accountID)
rv = client.request(r)
print(json.dumps(rv, indent=2))
|
tests/test_model.py | dgilland/sqlservice | 166 | 12605924 | from unittest import mock
import sqlalchemy as sa
from sqlalchemy import MetaData
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlservice import as_declarative, core, declarative_base
from sqlservice.model import ModelBase, ModelMeta
from .fixtures import AModel, CModel, DModel, is_subdict, parametrize
def test_declarative_base():
"""Test declarative_base()."""
class MetaClass(DeclarativeMeta):
pass
metadata = MetaData()
Model = declarative_base(metadata=metadata, metaclass=MetaClass)
assert Model.__bases__[0] is ModelBase
assert Model.metadata is metadata
assert Model.metaclass is MetaClass
def test_as_declarative():
"""Test as_declarative()."""
@as_declarative()
class Model:
pass
assert Model.metaclass is ModelMeta
@parametrize("model,expected", [(AModel({"id": 1, "name": "a"}), ((AModel.columns()["id"], 1),))])
def test_model_identity_map(model, expected):
"""Test that model has an identity map equal to its primary key columns and values."""
assert model.identity_map() == expected
@parametrize(
"model,expected",
[
(
AModel(
{
"name": "a",
"c": {"name": "b"},
"ds": [{"id": 1, "name": "d1"}, {"id": 2, "name": "d2"}],
}
),
{
"name": "a",
"c": {"name": "b"},
"ds": [{"id": 1, "name": "d1"}, {"id": 2, "name": "d2"}],
"d_map": {1: {"id": 1, "name": "d1"}, 2: {"id": 2, "name": "d2"}},
},
),
(AModel({"name": "a", "c": None}), {"name": "a", "c": {}}),
],
)
def test_model_to_dict(db, model, expected):
"""Test that a model can be serialized to a dict."""
db.save(model)
model = (
db.query(model.__class__)
.filter(core.identity_map_filter(model))
.options(sa.orm.eagerload("*"))
.first()
)
assert model.to_dict() == dict(model)
assert is_subdict(expected, model.to_dict())
@parametrize(
"adapters,data,expected",
[
(
{list: lambda models, col, _: [model.id for model in models]},
{"ds": [DModel(id=1), DModel(id=2)]},
{"ds": [1, 2]},
),
(
{"ds": lambda models, col, _: [model.id for model in models]},
{"ds": [DModel(id=1), DModel(id=2)]},
{"ds": [1, 2]},
),
({str: lambda val, *_: val[0]}, {"name": "foo"}, {"name": "f"}),
({"name": lambda val, *_: val[0]}, {"name": "foo"}, {"name": "f"}),
(
{"name": lambda val, *_: val[0]},
{"name": "foo", "text": "bar"},
{"name": "f", "text": "bar"},
),
({"text": None}, {"name": "foo", "text": "bar"}, {"name": "foo"}),
(
{"CModel": lambda c, *_: {"name": c.name}},
{"c": CModel(id=1, name="foo")},
{"c": {"name": "foo"}},
),
],
)
def test_model_to_dict_args_adapters(db, adapters, data, expected):
"""Test that Model.__dict_args__['exclude_sequence_types'] can be used to skip nested dict
serialization of those types."""
args = {"adapters": adapters}
expected = data if expected is True else expected
with mock.patch.object(AModel, "__dict_args__", new=args):
model = AModel(data)
assert dict(model) == expected
|
eeauditor/processor/outputs/json-output.py | kbhagi/ElectricEye | 442 | 12605943 | #This file is part of ElectricEye.
#SPDX-License-Identifier: Apache-2.0
#Licensed to the Apache Software Foundation (ASF) under one
#or more contributor license agreements. See the NOTICE file
#distributed with this work for additional information
#regarding copyright ownership. The ASF licenses this file
#to you under the Apache License, Version 2.0 (the
#"License"); you may not use this file except in compliance
#with the License. You may obtain a copy of the License at
#http://www.apache.org/licenses/LICENSE-2.0
#Unless required by applicable law or agreed to in writing,
#software distributed under the License is distributed on an
#"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#KIND, either express or implied. See the License for the
#specific language governing permissions and limitations
#under the License.
import json
import os
from processor.outputs.output_base import ElectricEyeOutput
@ElectricEyeOutput
class JsonProvider(object):
__provider__ = "json"
def write_findings(self, findings: list, output_file: str, **kwargs):
first = True
jsonfile = output_file + ".json"
json_out_location = ""
with open(jsonfile, "w") as json_out:
print(f"Writing {len(findings)} findings to {jsonfile}")
print('{"Findings":[', file=json_out)
json_out_location = os.path.abspath(json_out.name)
for finding in findings:
# print a comma separation between findings except before first finding
if first:
first = False
else:
print(",", file=json_out)
json.dump(finding, json_out, indent=2)
print("]}", file=json_out)
json_out.close()
return True |
lldb/packages/Python/lldbsuite/test/tracking.py | LaudateCorpus1/llvm-project | 765 | 12605958 | <reponame>LaudateCorpus1/llvm-project
#!/usr/bin/env python
import os
import os.path
import datetime
import re
import sys
sys.path.append(os.path.join(os.getcwd(), 'radarclient-python'))
def usage():
print "Run this from somewhere fancy"
print "Install pycurl and radarclient"
print "To install radarclient - while in the LLDB test repository do 'git clone https://[email protected]/git/radarclient-python.git'"
print "To install pycurl - from anywhere, do 'sudo easy_install pycurl'"
sys.exit(1)
try:
from radarclient import *
except:
usage()
def find_session_dir():
# Use heuristic to find the latest session directory.
name = datetime.datetime.now().strftime("%Y-%m-%d-")
dirs = [d for d in os.listdir(os.getcwd()) if d.startswith(name)]
if len(dirs) == 0:
print "No default session directory found, please specify it explicitly."
usage()
session_dir = max(dirs, key=os.path.getmtime)
if not session_dir or not os.path.exists(session_dir):
print "No default session directory found, please specify it explicitly."
usage()
return os.path.join(os.getcwd(), session_dir)
def process_no_bug(path, txt):
print 'Failure %s has no bug tracking (says %s) - why?' % (path, txt)
def process_llvm_bug(path, pr):
print 'Failure %s has an LLVM bug tracking: %s - why no radar?' % (path, pr.group(1))
def process_radar_bug(path, rdr):
rdr = get_radar_details(rdr.group(1))
if not rdr:
print 'Failure %s claims to be tracked by rdar://%s but no such bug exists - consider filing one' % (path, rdr.group(1))
return
print 'Failure %s has a radar bug tracking: rdar://%s %s - cool' % (path, rdr.id, rdr.title)
if rdr.state != 'Analyze':
print 'This radar is not in Analyze anymore - Consider filing a new one, or editing the test case'
print ' Assignee: %s %s' % (rdr.assignee.firstName, rdr.assignee.lastName)
print ' Milestone: %s' % (rdr.milestone[u'name'] if rdr.milestone else 'None')
print ' Priority: %s' % (rdr.priority)
global_radar_client = None
def get_radar_details(id):
global global_radar_client
if global_radar_client is None:
authentication_strategy = AuthenticationStrategySPNego()
system_identifier = ClientSystemIdentifier('lldb-test-tracker', '1.0')
global_radar_client = RadarClient(
authentication_strategy, system_identifier)
global_radar_client.problem_default_fields = [
'id',
'title',
'assignee',
'milestone',
'component',
'priority',
'fixOrder',
'state',
'substate',
'resolution',
'duplicateOfProblemID']
rdar = global_radar_client.radar_for_id(id)
if rdar.state == 'Verify' or rdar.state == 'Closed' and rdar.resolution == 'Duplicate':
return get_radar_details(rdar.duplicateOfProblemID)
return rdar
def process_xfail(path):
marker = 'expected failure (problem id:'
content = ""
with open(path, 'r') as content_file:
content = content_file.read()
name = os.path.basename(path)
try:
name = name[name.find('-') + 1:]
name = name[name.find('-') + 1:]
name = name[name.find('-') + 1:]
name = name.replace('.log', '')
name = name[:name.rfind('.') - 1]
finally:
pass
xfail_line = content[content.find(
'expected failure (problem id:') + len(marker):]
xfail_line = xfail_line[:xfail_line.find('\n')]
m1 = re.search('rdar://([0-9]+)', xfail_line)
m2 = re.search('rdar://problem/([0-9]+)', xfail_line)
m3 = re.search('llvm.org/pr([0-9]+)', xfail_line)
if m1 is None and m2 is None:
if m3 is None:
process_no_bug(name, xfail_line)
else:
process_llvm_bug(name, m3)
else:
process_radar_bug(name, m1 if m1 else m2)
print ""
session_dir_path = find_session_dir()
import os
for root, dirs, files in os.walk(session_dir_path, topdown=False):
for name in files:
if name.startswith("ExpectedFailure"):
process_xfail(os.path.join(session_dir_path, name))
|
5]. Projects/Desktop Development/GUI Projects/08). Scientific_Calculator/Scientific_Calculater.py | Utqrsh04/The-Complete-FAANG-Preparation | 6,969 | 12605961 | from tkinter import *
from tkinter import messagebox as tmsg
import math
import tkinter.messagebox
root = Tk()
root.title("Scientific Calculater--")
root.wm_iconbitmap("cal.ico")
root.configure(background = "powder blue")
root.geometry("495x590+40+40")
root.resizable(width=False, height=False)
calc = Frame(root)
calc.grid()
class Calc():
def __init__(self):
self.total = 0
self.current = ""
self.input_value = True
self.check_sum = False
self.op = ""
self.result = False
def numberEnter(self, num):
self.result = False
firstnum = txtDisplay.get()
secondnum = str(num)
if self.input_value:
self.current = secondnum
self.input_value = False
else:
if secondnum == '.':
if secondnum in firstnum:
return
self.current = firstnum + secondnum
self.display(self.current)
def sum_of_total(self):
self.result = True
self.current = float(self.current)
if self.check_sum == True:
self.valid_function()
else:
self.total = float(txtDisplay.get())
def display(self, value):
txtDisplay.delete(0, END)
txtDisplay.insert(0, value)
def valid_function(self):
if self.op == "add":
self.total += self.current
if self.op == "sub":
self.total -= self.current
if self.op == "multi":
self.total *= self.current
if self.op == "divide":
self.total /= self.current
if self.op == "mod":
self.total %= self.current
self.input_value = True
self.check_sum = False
self.display(self.total)
def operation(self, op):
self.current = float(self.current)
if self.check_sum:
self.valid_function()
elif not self.result:
self.total = self.current
self.input_value = True
self.check_sum = True
self.op = op
self.result = False
def pi(self):
self.result = False
self.current = math.pi
self.display(self.current)
def tau(self):
self.result = False
self.current = math.tau
self.display(self.current)
def e(self):
self.result = False
self.current = math.e
self.display(self.current)
def cos(self):
self.result = False
self.current = math.cos(math.radians(float(txtDisplay.get())))
self.display(self.current)
def tan(self):
self.result = False
self.current = math.tan(math.radians(float(txtDisplay.get())))
self.display(self.current)
def sin(self):
self.result = False
self.current = math.sin(math.radians(float(txtDisplay.get())))
self.display(self.current)
def cosh(self):
self.result = False
self.current = math.cosh(math.radians(float(txtDisplay.get())))
self.display(self.current)
def tanh(self):
self.result = False
self.current = math.tanh(math.radians(float(txtDisplay.get())))
self.display(self.current)
def sinh(self):
self.result = False
self.current = math.sinh(math.radians(float(txtDisplay.get())))
self.display(self.current)
def acosh(self):
self.result = False
self.current = math.acosh(float(txtDisplay.get()))
self.display(self.current)
def atanh(self):
try:
self.result = False
self.current = math.atanh(float(txtDisplay.get()))
self.display(self.current)
except:
pass
def asinh(self):
self.result = False
self.current = math.asinh(float(txtDisplay.get()))
self.display(self.current)
def log(self):
self.result = False
self.current = math.log(float(txtDisplay.get()))
self.display(self.current)
def log2(self):
self.result = False
self.current = math.log2(float(txtDisplay.get()))
self.display(self.current)
def log10(self):
self.result = False
self.current = math.log10(float(txtDisplay.get()))
self.display(self.current)
def exp(self):
self.result = False
self.current = math.exp(float(txtDisplay.get()))
self.display(self.current)
def expm1(self):
self.result = False
self.current = math.expm1(float(txtDisplay.get()))
self.display(self.current)
def log1p(self):
self.result = False
self.current = math.log1p(float(txtDisplay.get()))
self.display(self.current)
def degrees(self):
self.result = False
self.current = math.degrees(float(txtDisplay.get()))
self.display(self.current)
def lgamma(self):
self.result = False
self.current = math.lgamma(float(txtDisplay.get()))
self.display(self.current)
def Clear_Entry(self):
try:
self.current = self.current[:-1]
self.display(self.current)
except:
print("Float value Result not clear")
def all_Clear_Entry(self):
self.result = False
self.current = "0"
self.display(0)
self.input_value = True
def MathsPM(self):
self.result = False
self.current = -(float(txtDisplay.get()))
self.display(self.current)
def squared(self):
self.result = False
self.current = math.sqrt(float(txtDisplay.get()))
self.display(self.current)
def factorial(self):
try:
self.result = False
self.current = math.factorial(int(txtDisplay.get()))
self.display(self.current)
except Exception:
print("Floting Numbers Can Not return factorials")
def fabs(self):
self.result = False
self.current = math.fabs(float(txtDisplay.get()))
self.display(self.current)
def radians(self):
self.result = False
self.current = math.radians(float(txtDisplay.get()))
self.display(self.current)
#============================================Testing===================================
def pow(self, x, y):
self.result = False
self.current = math.pow(int(txtDisplay.get()), int(txtDisplay.get()))
self.display(self.current)
#=======================================================================================
added_value = Calc()
txtDisplay = Entry(calc, font = "arial 20 bold", bg = "powder blue",bd = 30, width = 29, justify = RIGHT)
txtDisplay.grid(row = 0, column = 0, columnspan = 4, pady = 1)
txtDisplay.insert(0, "0")
numberpad = "789456123"
i = 0
btn = []
for j in range(2, 5):
for k in range(3):
btn.append(Button(calc, width = 6, height = 2, font ="arial 20 bold", bd = 4, text = numberpad[i]))
btn[i].grid(row =j, column = k, pady = 1)
btn[i]["command"] = lambda X = numberpad[i]: added_value.numberEnter(X)
i += 1
#====================================Testing=================================================================
btnpow = Button(calc, text = "pow", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.pow)
btnpow.grid(row =3, column = 8, pady = 1)
# btnComma = Button(calc, text = "(", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.numberEnter("("))
# btnComma.grid(row =1, column = 9, pady = 1)
# btnComma = Button(calc, text = ")", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.numberEnter(")"))
# btnComma.grid(row =2, column = 9, pady = 1)
# btnComma = Button(calc, text = ",", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.numberEnter(","))
# btnComma.grid(row =3, column = 9, pady = 1)
#====================================STANDERED CALCULATER==============================================================
btnClar = Button(calc, text = chr(67), width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "red", command = added_value.Clear_Entry)
btnClar.grid(row =1, column = 0, pady = 1)
btnAllClar = Button(calc, text = chr(67) + chr(69), width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "red", command = added_value.all_Clear_Entry)
btnAllClar.grid(row =1, column = 1, pady = 1)
btnSq = Button(calc, text = "√", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.squared)
btnSq.grid(row =1, column = 2, pady = 1)
btnAdd = Button(calc, text = "+", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.operation("add"))
btnAdd.grid(row =1, column = 3, pady = 1)
btnSub = Button(calc, text = "-", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.operation("sub"))
btnSub.grid(row =2, column = 3, pady = 1)
btnMul = Button(calc, text = "*", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.operation("multi"))
btnMul.grid(row =3, column = 3, pady = 1)
btnDiv = Button(calc, text = "÷", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.operation("divide"))
btnDiv.grid(row =4, column = 3, pady = 1)
btnZero = Button(calc, text = "0", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.numberEnter(0))
btnZero.grid(row =5, column = 0, pady = 1)
btnDot = Button(calc, text = ".", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.numberEnter("."))
btnDot.grid(row =5, column = 1, pady = 1)
btnPM = Button(calc, text = "±", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.MathsPM)
btnPM.grid(row =5, column = 2, pady = 1)
btnEquals = Button(calc, text = "=", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = added_value.sum_of_total)
btnEquals.grid(row =5, column = 3, pady = 1)
#===================================SCIENTIFIC CALCULATION=============================================================
btnPi = Button(calc, text ="π" , width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.pi)
btnPi.grid(row =1, column = 4, pady = 1)
btncos = Button(calc, text = "cos", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.cos)
btncos.grid(row =1, column = 5, pady = 1)
btntan = Button(calc, text = "tan", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.tan)
btntan.grid(row =1, column = 6, pady = 1)
btnsin = Button(calc, text = "sin", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.sin)
btnsin.grid(row =1, column = 7, pady = 1)
btnfact = Button(calc, text = "x!", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.factorial)
btnfact.grid(row =1, column = 8, pady = 1)
# btnComma = Button(calc, text = "(", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.numberEnter("("))
# btnComma.grid(row =1, column = 9, pady = 1)
#=======================================================================================================================
btn2Pi = Button(calc, text = "2π", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.tau)
btn2Pi.grid(row =2, column = 4, pady = 1)
btncosh = Button(calc, text = "cosh", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = added_value.cosh)
btncosh.grid(row =2, column = 5, pady = 1)
btntanh = Button(calc, text = "tanh", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = added_value.tanh)
btntanh.grid(row =2, column = 6, pady = 1)
btnsinh = Button(calc, text = "sinh", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = added_value.sinh)
btnsinh.grid(row =2, column = 7, pady = 1)
btnfabs = Button(calc, text = "|x|", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.fabs)
btnfabs.grid(row =2, column = 8, pady = 1)
# btnComma = Button(calc, text = ")", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.numberEnter(")"))
# btnComma.grid(row =2, column = 9, pady = 1)
#=======================================================================================================================
btnlog = Button(calc, text = "ln", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.log)
btnlog.grid(row =3, column = 4, pady = 1)
btnacosh = Button(calc, text = "acosh", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = added_value.acosh)
btnacosh.grid(row =3, column = 5, pady = 1)
btnatanh = Button(calc, text = "atanh", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = added_value.atanh)
btnatanh.grid(row =3, column = 6, pady = 1)
btnasinh = Button(calc, text = "asinh", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = added_value.asinh)
btnasinh.grid(row =3, column = 7, pady = 1)
btnpow = Button(calc, text = "pow", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.pow)
btnpow.grid(row =3, column = 8, pady = 1)
# btnComma = Button(calc, text = ",", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue",command = lambda: added_value.numberEnter(","))
# btnComma.grid(row =3, column = 9, pady = 1)
#=======================================================================================================================
btnlog2 = Button(calc, text = "log2", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.log2)
btnlog2.grid(row =4, column = 4, pady = 1)
btnExp = Button(calc, text = "Exp", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = added_value.exp)
btnExp.grid(row =4, column = 5, pady = 1)
btnMod = Button(calc, text = "%", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = lambda: added_value.operation("mod"))
btnMod.grid(row =4, column = 6, pady = 1)
btnE = Button(calc, text = "e", width = 6, height = 2, font = "arial 20 bold", bd = 4, command = added_value.e)
btnE.grid(row =4, column = 7, pady = 1)
btndeg = Button(calc, text = "deg", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.degrees)
btndeg.grid(row =4, column = 8, pady = 1)
# btndeg = Button(calc, text = "deg", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.degrees)
# btndeg.grid(row =4, column = 9, pady = 1)
#=======================================================================================================================
btnlog10 = Button(calc, text = "log10", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.log10)
btnlog10.grid(row =5, column = 4, pady = 1)
btnlog1p = Button(calc, text = "log1p", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.log1p)
btnlog1p.grid(row =5, column = 5, pady = 1)
btnexpm1 = Button(calc, text = "expm1", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.expm1)
btnexpm1.grid(row =5, column = 6, pady = 1)
btnlgamma = Button(calc, text = "lgamma", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.lgamma)
btnlgamma.grid(row =5, column = 7, pady = 1)
btnrad = Button(calc, text = "rad", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.radians)
btnrad.grid(row =5, column = 8, pady = 1)
# btnrad = Button(calc, text = "rad", width = 6, height = 2, font = "arial 20 bold", bd = 4, bg = "powder blue", command = added_value.radians)
# btnrad.grid(row =5, column = 9, pady = 1)
#=======================================================================================================================
lblDisplay = Label(calc, text = "Scientific Calculater", font = "arial 46 bold", justify = CENTER)
lblDisplay.grid(row = 0, column = 4, columnspan =8)
#=======================================================================================================================
#======================================MENU & FUNCTION================================================================
def iExit():
iExit = tkinter.messagebox.askyesno("Scientific Calculater", "Confirm if you want to exit")
if iExit > 0:
root.destroy()
return
def Standered():
root.resizable(width=False, height=False)
root.geometry("495x568+40+40")
def Scientific():
root.resizable(width=False, height=False)
root.geometry("1085x568+40+40")
def help():
print("I will help you")
tmsg.showinfo("Help", "Code With Sky")
def rate():
print("Rate us , Please!")
val = tmsg.askquestion("How was your experience......."," was your experience Good ")
if val == "yes":
msg = "Greate! Rate us Please."
else:
msg = "Tell us what went wrong"
tmsg.showinfo("Experience",msg)
def about():
pass
menubar = Menu(calc)
filemenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "File", menu = filemenu)
filemenu.add_command(label = "Standered", command = Standered)
filemenu.add_command(label = "Scientific", command = Scientific)
filemenu.add_separator()
filemenu.add_command(label = "Exit", command = iExit )
editmenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Edit", menu = editmenu)
editmenu.add_command(label = "Cut")
editmenu.add_command(label = "Copy")
editmenu.add_separator()
editmenu.add_command(label = "Paste")
helpmenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Help", menu = helpmenu)
helpmenu.add_command(label = "Help", command = help)
helpmenu.add_command(label = "Rate", command = rate)
helpmenu.add_separator()
helpmenu.add_command(label = "About Creater", command = about)
root.config(menu = menubar)
root.mainloop() |
src/chapter-5/app.py | luizyao/pytest-chinese-doc | 283 | 12605965 | <filename>src/chapter-5/app.py
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
Author: <NAME> (<EMAIL>)
Created Date: 2019-10-10 16:38:48
-----
Last Modified: 2019-10-10 17:04:12
Modified By: <NAME> (<EMAIL>)
-----
THIS PROGRAM IS FREE SOFTWARE, IS LICENSED UNDER MIT.
A short and simple permissive license with conditions
only requiring preservation of copyright and license notices.
Copyright © 2019 <NAME>
-----
HISTORY:
Date By Comments
---------- -------- ---------------------------------------------------------
'''
from urllib import request
def get(url):
r = request.urlopen(url)
return r.read().decode('utf-8')
|
office365/sharepoint/utilities/upload_status.py | rikeshtailor/Office365-REST-Python-Client | 544 | 12606036 | <reponame>rikeshtailor/Office365-REST-Python-Client
from office365.runtime.client_value import ClientValue
class UploadStatus(ClientValue):
pass
|
plans/forms.py | tejas1106/django-plans | 112 | 12606078 | <gh_stars>100-1000
from django import forms
from django.core.exceptions import ValidationError
from django.forms.widgets import HiddenInput
from django.utils.translation import gettext
from .models import BillingInfo, Order, PlanPricing
from .utils import get_country_code
class OrderForm(forms.Form):
plan_pricing = forms.ModelChoiceField(queryset=PlanPricing.objects.all(), widget=HiddenInput, required=True)
class CreateOrderForm(forms.ModelForm):
"""
This form is intentionally empty as all values for Order object creation need to be computed inside view
Therefore, when implementing for example a rabat coupons, you can add some fields here
and create "recalculate" button.
"""
class Meta:
model = Order
fields = tuple()
class BillingInfoForm(forms.ModelForm):
class Meta:
model = BillingInfo
exclude = ('user',)
def __init__(self, *args, request=None, **kwargs):
ret_val = super().__init__(*args, **kwargs)
if not self.instance.country:
self.fields['country'].initial = get_country_code(request)
return ret_val
def clean(self):
cleaned_data = super(BillingInfoForm, self).clean()
try:
cleaned_data['tax_number'] = BillingInfo.clean_tax_number(cleaned_data['tax_number'],
cleaned_data.get('country', None))
except ValidationError as e:
self._errors['tax_number'] = e.messages
return cleaned_data
class BillingInfoWithoutShippingForm(BillingInfoForm):
class Meta:
model = BillingInfo
exclude = ('user', 'shipping_name', 'shipping_street', 'shipping_zipcode', 'shipping_city')
class FakePaymentsForm(forms.Form):
status = forms.ChoiceField(choices=Order.STATUS, required=True, label=gettext('Change order status to'))
|
yotta/lib/fsutils_win.py | headlessme/yotta | 176 | 12606098 | # Copyright 2014 ARM Limited
#
# Licensed under the Apache License, Version 2.0
# See LICENSE file for details.
# !!! FIXME: this implementation uses NTFS junctions points:
# http://msdn.microsoft.com/en-gb/library/windows/desktop/aa365006%28v=vs.85%29.aspx
# These don't work when linking a non-local volume (for example a network share)
# If that'll be required in the future, symlinks (CreateSymbolicLink) must be used instead
# ntfsutils, 2-clause BSD, NTFS link handling, pip install ntfsutils
import ntfsutils.junction as junction #pylint: disable=import-error
import os
def dropRootPrivs(fn):
''' decorator to drop su/sudo privilages before running a function on
unix/linux.
** on windows this function does nothing **
'''
def wrapper(*args, **kwargs):
# !!! TODO: what can we do to de-priv on windows?
return fn(*args, **kwargs)
return wrapper
def isLink(path):
return junction.isjunction(path)
def tryReadLink(path):
try:
prevPath, initialPath = path, path
readlinkCount, maxReadlinkCount = 0, 100
while isLink(path):
path = junction.readlink(path)
if path == prevPath: # no idea if this can happen, but why risk it
break
# Prevent infinite loop if circular paths are present (A->B->C->A)
readlinkCount = readlinkCount + 1
if readlinkCount == maxReadlinkCount:
return initialPath
prevPath = path
return path
except:
return None
def _symlink(source, link_name):
junction.create(source, link_name)
def realpath(path):
return os.path.abspath(tryReadLink(path) or path)
def rmLink(path):
# Apparently, it's possible to delete both directory links and file links
# with 'rmdir' in Windows
os.rmdir(path)
def which(program):
''' look for "program" in PATH (respecting PATHEXT), and return the path to
it, or None if it was not found
'''
# current directory / absolute paths:
if os.path.exists(program) and os.access(program, os.X_OK):
return program
# PATH:
for path in os.environ['PATH'].split(os.pathsep):
# path variables may be quoted:
path = path.strip('"')
for ext in os.environ.get('PATHEXT', '').split(os.pathsep):
progpath = os.path.join(path, program + ext)
if os.path.exists(progpath) and os.access(progpath, os.X_OK):
return progpath
# not found
return None
|
featuretools/tests/plugin_tests/utils.py | ridicolos/featuretools | 942 | 12606105 | <gh_stars>100-1000
import os
import subprocess
import sys
def import_featuretools(level=None):
c = ''
if level:
c += 'import os;'
c += 'os.environ["FEATURETOOLS_LOG_LEVEL"] = "%s";' % level
c += 'import featuretools;'
return python('-c', c)
def install_featuretools_plugin():
pwd = os.path.dirname(__file__)
os.chdir(os.path.join(pwd, 'featuretools_plugin'))
return python('-m', 'pip', 'install', '-e', '.')
def python(*args):
command = [sys.executable, *args]
return subprocess.run(command, stdout=subprocess.PIPE)
def uninstall_featuretools_plugin():
return python('-m', 'pip', 'uninstall', 'featuretools_plugin', '-y')
|
indy_node/test/request_handlers/rich_schema/test_all_rich_schema_handlers.py | Rob-S/indy-node | 627 | 12606119 | import copy
import json
import random
import pytest
from indy_common.authorize.auth_constraints import AuthConstraintForbidden
from indy_common.constants import RS_ID, RS_TYPE, RS_NAME, RS_VERSION, RS_CONTENT, ENDORSER, JSON_LD_ID_FIELD, \
JSON_LD_TYPE_FIELD
from indy_node.server.request_handlers.domain_req_handlers.rich_schema.rich_schema_handler import RichSchemaHandler
from indy_node.server.request_handlers.domain_req_handlers.rich_schema.rich_schema_mapping_handler import \
RichSchemaMappingHandler
from indy_node.server.request_handlers.domain_req_handlers.rich_schema.rich_schema_pres_def_handler import \
RichSchemaPresDefHandler
from indy_node.test.request_handlers.helper import add_to_idr
from indy_node.test.request_handlers.rich_schema.helper import context_request, make_rich_schema_object_exist
from plenum.common.constants import OP_VER, TRUSTEE
from plenum.common.exceptions import UnauthorizedClientRequest, InvalidClientRequest
from plenum.common.txn_util import reqToTxn, append_txn_metadata
from plenum.common.util import SortedDict, randomString
def test_update_state(handler_and_request):
handler, request = handler_and_request
seq_no = 1
txn_time = 1560241033
txn = reqToTxn(request)
append_txn_metadata(txn, seq_no, txn_time)
op = request.operation
handler.update_state(txn, None, context_request)
value = {
'id': op[RS_ID],
'rsType': op[RS_TYPE],
'rsName': op[RS_NAME],
'rsVersion': op[RS_VERSION],
'content': op[RS_CONTENT],
'from': request.identifier,
'endorser': request.endorser,
'ver': op[OP_VER],
}
primary_key = op[RS_ID]
secondary_key = "{RS_TYPE}:{RS_NAME}:{RS_VERSION}".format(RS_TYPE=op['rsType'],
RS_NAME=op['rsName'],
RS_VERSION=op['rsVersion']).encode()
value_from_state = handler.get_from_state(primary_key)
assert SortedDict(value_from_state[0]) == SortedDict(value)
assert value_from_state[1] == seq_no
assert value_from_state[2] == txn_time
assert handler.state.get(secondary_key, isCommitted=False) == op[RS_ID].encode()
def test_static_validation_pass(handler_and_request):
handler, request = handler_and_request
handler.static_validation(request)
def test_static_validation_content_is_json(handler_and_request):
handler, request = handler_and_request
request.operation[RS_CONTENT] = randomString()
with pytest.raises(InvalidClientRequest, match="must be a JSON serialized string"):
handler.static_validation(request)
@pytest.mark.parametrize('status', ['missing', 'empty', 'none'])
def test_static_validation_content_is_json_ld_with_atid(handler_and_request, status):
handler, request = handler_and_request
content = copy.deepcopy(json.loads(request.operation[RS_CONTENT]))
if status == 'missing':
content.pop(JSON_LD_ID_FIELD, None)
elif status == 'empty':
content[JSON_LD_ID_FIELD] = ""
elif status == 'none':
content[JSON_LD_ID_FIELD] = None
request.operation[RS_CONTENT] = json.dumps(content)
if not isinstance(handler, (RichSchemaMappingHandler, RichSchemaHandler, RichSchemaPresDefHandler)):
handler.static_validation(request)
return
with pytest.raises(InvalidClientRequest, match="'content' must be a valid JSON-LD and have non-empty '@id' field"):
handler.static_validation(request)
@pytest.mark.parametrize('status', ['missing', 'empty', 'none'])
def test_static_validation_content_is_json_ld_with_attype(handler_and_request, status):
handler, request = handler_and_request
content = copy.deepcopy(json.loads(request.operation[RS_CONTENT]))
if status == 'missing':
content.pop(JSON_LD_TYPE_FIELD, None)
elif status == 'empty':
content[JSON_LD_TYPE_FIELD] = ""
elif status == 'none':
content[JSON_LD_TYPE_FIELD] = None
request.operation[RS_CONTENT] = json.dumps(content)
if not isinstance(handler, (RichSchemaMappingHandler, RichSchemaHandler, RichSchemaPresDefHandler)):
handler.static_validation(request)
return
with pytest.raises(InvalidClientRequest,
match="'content' must be a valid JSON-LD and have non-empty '@type' field"):
handler.static_validation(request)
def test_static_validation_atid_equals_to_id(handler_and_request):
handler, request = handler_and_request
content = copy.deepcopy(json.loads(request.operation[RS_CONTENT]))
content["@id"] = request.operation[RS_ID] + "a"
request.operation[RS_CONTENT] = json.dumps(content)
if not isinstance(handler, (RichSchemaMappingHandler, RichSchemaHandler, RichSchemaPresDefHandler)):
handler.static_validation(request)
return
with pytest.raises(InvalidClientRequest,
match="content's @id must be equal to id={}".format(request.operation[RS_ID])):
handler.static_validation(request)
def test_dynamic_validation_failed_not_authorised(handler_and_request):
handler, request = handler_and_request
add_to_idr(handler.database_manager.idr_cache, request.identifier, None)
with pytest.raises(UnauthorizedClientRequest):
handler.dynamic_validation(request, 0)
def test_dynamic_validation_for_existing(handler_and_request):
handler, request = handler_and_request
make_rich_schema_object_exist(handler, request)
add_to_idr(handler.database_manager.idr_cache, request.identifier, TRUSTEE)
add_to_idr(handler.database_manager.idr_cache, request.endorser, ENDORSER)
with pytest.raises(UnauthorizedClientRequest, match=str(AuthConstraintForbidden())):
handler.dynamic_validation(request, 0)
def test_dynamic_validation_for_existing_metadata(handler_and_request):
handler, request = handler_and_request
make_rich_schema_object_exist(handler, request)
add_to_idr(handler.database_manager.idr_cache, request.identifier, TRUSTEE)
add_to_idr(handler.database_manager.idr_cache, request.endorser, ENDORSER)
request.operation[RS_ID] = randomString()
request.operation[RS_CONTENT] = randomString()
request.reqId = random.randint(10, 1000000000)
with pytest.raises(InvalidClientRequest,
match='An object with rsName="{}", rsVersion="{}" and rsType="{}" already exists. '
'Please choose different rsName, rsVersion or rsType'.format(
request.operation[RS_NAME], request.operation[RS_VERSION], request.operation[RS_TYPE])):
handler.dynamic_validation(request, 0)
|
tools/deploy/main.py | bopopescu/peloton | 617 | 12606221 | <reponame>bopopescu/peloton<gh_stars>100-1000
#!/usr/bin/env python
import argparse
from cluster import Cluster
def parse_args():
parser = argparse.ArgumentParser(description="Script to deploy Peloton")
parser.add_argument(
"-c",
"--config",
required=True,
help="The cluster config file to deploy Peloton",
)
parser.add_argument(
"-f",
"--force",
required=False,
action="store_true",
help="Force the upgrade without confirmation",
)
parser.add_argument(
"-v",
"--verbose",
required=False,
action="store_true",
help="Print more verbose information",
)
args = parser.parse_args()
return args
def main():
args = parse_args()
cluster = Cluster.load(args.config)
if cluster.update(args.force, args.verbose):
print(
"Successfully updated cluster %s to %s"
% (cluster.name, cluster.version)
)
else:
print("Failed to update cluster %s" % cluster.name)
if __name__ == "__main__":
main()
|
vedastr/models/bodies/sequences/transformer/unit/attention/builder.py | csmasters/vedastr | 475 | 12606266 | <reponame>csmasters/vedastr<gh_stars>100-1000
from vedastr.utils import build_from_cfg
from .registry import TRANSFORMER_ATTENTIONS
def build_attention(cfg, default_args=None):
attention = build_from_cfg(cfg, TRANSFORMER_ATTENTIONS, default_args)
return attention
|
migrations/versions/27d55d03f753_add_count_column_upgrade_step.py | chaos-genius/chaos_genius | 320 | 12606282 | <reponame>chaos-genius/chaos_genius
"""Add Count column & upgrade step
Revision ID: 27d55d0<PASSWORD>
Revises: e<PASSWORD>
Create Date: 2022-06-08 14:29:57.525557
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2<PASSWORD>'
down_revision = 'e3<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column("kpi", sa.Column("count_column", sa.Text(), nullable=True))
# ### end Alembic commands ###
update_query = """
UPDATE kpi
SET count_column = 'count'
WHERE data_source IN
( SELECT id FROM data_source WHERE connection_type = 'Druid' )
"""
op.execute(update_query)
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('kpi', 'count_column')
# ### end Alembic commands ###
|
jarbas/core/migrations/0014_add_suspicions_and_probability_to_reimbursements.py | vbarceloscs/serenata-de-amor | 3,001 | 12606303 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2016-12-08 13:03
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0013_create_model_reimbursement'),
]
operations = [
migrations.AddField(
model_name='reimbursement',
name='probability',
field=models.DecimalField(blank=True, decimal_places=5, max_digits=6, null=True, verbose_name='Probability'),
),
migrations.AddField(
model_name='reimbursement',
name='suspicions',
field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True, verbose_name='Suspicions'),
),
]
|
migrations/versions/2020_04_13_3a87adc2088b_user_statistics_tracking.py | tigerdar004/RweddingPoll | 112 | 12606333 | <gh_stars>100-1000
"""User statistics tracking
Revision ID: <KEY>
Revises: 7de7ec98049b
Create Date: 2020-04-13 22:11:20.064789
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "<KEY>"
down_revision = "7de7ec98049b"
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"user_statistic",
sa.Column("date", sa.Date(), nullable=False),
sa.Column("callback_calls", sa.Integer(), nullable=False),
sa.Column("poll_callback_calls", sa.Integer(), nullable=False),
sa.Column("created_polls", sa.Integer(), nullable=False),
sa.Column("inline_shares", sa.Integer(), nullable=False),
sa.Column("user_id", sa.BigInteger(), nullable=False),
sa.ForeignKeyConstraint(
["user_id"], ["user.id"], name="user", ondelete="cascade"
),
sa.PrimaryKeyConstraint("date", "user_id"),
)
op.create_index(
op.f("ix_user_statistic_user_id"), "user_statistic", ["user_id"], unique=False
)
op.alter_column(
"update",
"count",
existing_type=sa.INTEGER(),
server_default=None,
existing_nullable=False,
)
op.add_column(
"user",
sa.Column("banned", sa.Boolean(), server_default="FALSE", nullable=False),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("user", "banned")
op.alter_column(
"update",
"count",
existing_type=sa.INTEGER(),
server_default=sa.text("0"),
existing_nullable=False,
)
op.drop_index(op.f("ix_user_statistic_user_id"), table_name="user_statistic")
op.drop_table("user_statistic")
# ### end Alembic commands ###
|
datadog_checks_tests_helper/datadog_test_libs/utils/mock_dns.py | mchelen-gov/integrations-core | 663 | 12606372 | import os
from contextlib import contextmanager
from datadog_checks.dev import run_command
@contextmanager
def mock_local(src_to_dest_mapping):
"""
Mock 'socket' to resolve hostname based on a provided mapping.
This method has no effect for e2e tests.
:param src_to_dest_mapping: Mapping from source hostname to a tuple of destination hostname and port.
If port is None or evaluates to False, then only the host will be overridden and not the port.
"""
import socket
_orig_getaddrinfo = socket.getaddrinfo
_orig_connect = socket.socket.connect
def patched_getaddrinfo(host, port, *args, **kwargs):
if host in src_to_dest_mapping:
# See socket.getaddrinfo, just updating the hostname here.
# https://docs.python.org/3/library/socket.html#socket.getaddrinfo
dest_addr, dest_port = src_to_dest_mapping[host]
new_port = dest_port or port
return [(2, 1, 6, '', (dest_addr, new_port))]
return _orig_getaddrinfo(host, port, *args, **kwargs)
def patched_connect(self, address):
host, port = address[0], address[1]
if host in src_to_dest_mapping:
dest_addr, dest_port = src_to_dest_mapping[host]
host, port = dest_addr, dest_port
return _orig_connect(self, (host, port))
socket.getaddrinfo = patched_getaddrinfo
socket.socket.connect = patched_connect
try:
yield
except Exception:
raise
finally:
socket.getaddrinfo = _orig_getaddrinfo
socket.socket.connect = _orig_connect
|
lib/models/modules.py | sibeiyang/sgmn | 130 | 12606404 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from model_utils import NormalizeScale
class AttendRelationModule(nn.Module):
def __init__(self, dim_vis_feat, visual_init_norm, jemb_dim, dim_lang_feat, jemb_dropout):
super(AttendRelationModule, self).__init__()
self.vis_feat_normalizer = NormalizeScale(dim_vis_feat, visual_init_norm)
self.lfeat_normalizer = NormalizeScale(5, visual_init_norm)
self.fc = nn.Linear(dim_vis_feat + 5, jemb_dim)
self.matching = RelationMatching(jemb_dim, dim_lang_feat, jemb_dim, jemb_dropout, -1)
def forward(self, cxt_feats, cxt_lfeats, lang_feats):
# cxt_feats: (bs, n, num_cxt, dim_vis_feat); cxt_lfeats: (bs, n, num_cxt, 5); lang_feats: (bs, num_seq, dim_lang)
# compute masks first
masks = (cxt_lfeats.sum(3) != 0).float() # bs, n, num_cxt
# compute joint encoded context
batch, n, num_cxt = cxt_feats.size(0), cxt_feats.size(1), cxt_feats.size(2)
cxt_feats = self.vis_feat_normalizer(cxt_feats.view(batch * n * num_cxt, -1))
cxt_lfeats = self.lfeat_normalizer(cxt_lfeats.view(batch * n * num_cxt, -1))
# joint embed
concat = torch.cat([cxt_feats, cxt_lfeats], 1)
rel_feats = self.fc(concat)
rel_feats = rel_feats.view(batch, n, num_cxt, -1) # bs, n, 10, jemb_dim
attn = self.matching(rel_feats, lang_feats, masks)
return attn
class RelationMatching(nn.Module):
def __init__(self, vis_dim, lang_dim, jemb_dim, jemb_dropout, min_value=-1):
super(RelationMatching, self).__init__()
self.vis_emb_fc = nn.Sequential(nn.Linear(vis_dim, jemb_dim),
nn.BatchNorm1d(jemb_dim),
nn.ReLU(),
nn.Dropout(jemb_dropout),
nn.Linear(jemb_dim, jemb_dim),
nn.BatchNorm1d(jemb_dim))
self.lang_emb_fc = nn.Sequential(nn.Linear(lang_dim, jemb_dim),
nn.BatchNorm1d(jemb_dim),
nn.ReLU(),
nn.Dropout(jemb_dropout),
nn.Linear(jemb_dim, jemb_dim),
nn.BatchNorm1d(jemb_dim))
self.min_value = min_value
def forward(self, vis_input, lang_input, masks):
# vis_input: (bs, n, num_cxt, vim_dim); lang_input: (bs, num_seq, lang_dim); mask(bs, n, num_cxt)
bs, n, num_cxt = vis_input.size(0), vis_input.size(1), vis_input.size(2)
num_seq = lang_input.size(1)
vis_emb = self.vis_emb_fc(vis_input.view(bs * n * num_cxt, -1))
lang_emb = self.lang_emb_fc(lang_input.view(bs * num_seq, -1))
# l2-normalize
vis_emb_normalized = F.normalize(vis_emb, p=2, dim=1)
lang_emb_normalized = F.normalize(lang_emb, p=2, dim=1)
vis_emb_normalized = vis_emb_normalized.view(bs, n, num_cxt, -1)
lang_emb_normalized = lang_emb_normalized.view(bs, num_seq, -1)
# compute cossim
cossim = torch.bmm(lang_emb_normalized,
vis_emb_normalized.view(bs, n * num_cxt, -1).transpose(1, 2)) # bs, num_seq, n*num_cxt
cossim = cossim.view(bs, num_seq, n, num_cxt)
# mask cossim
mask_expand = masks.unsqueeze(1).expand(bs, num_seq, n, num_cxt)
cossim = mask_expand * cossim
cossim[mask_expand == 0] = self.min_value
cossim = F.relu(cossim)
return cossim
class AttendLocationModule(nn.Module):
def __init__(self, visual_init_norm, jemb_dim, dim_lang_feat, jemb_dropout):
super(AttendLocationModule, self).__init__()
self.lfeat_normalizer = NormalizeScale(5, visual_init_norm)
self.fc = nn.Linear(5, jemb_dim)
self.matching = Matching(jemb_dim, dim_lang_feat, jemb_dim, jemb_dropout, -1)
def forward(self, lfeats, lang_feats, cls):
# lfeats: (bs, n, 5); lang_feats: (bs, num_seq, dim_lang_feat)
bs, n = lfeats.size(0), lfeats.size(1)
lfeats = self.lfeat_normalizer(lfeats.view(bs * n, -1))
loc_feats = self.fc(lfeats).view(bs, n, -1)
attn = self.matching(loc_feats, lang_feats, (cls != -1).float())
return attn
class AttendNodeModule(nn.Module):
def __init__(self, dim_vis_feat, visual_init_norm, jemb_dim, dim_lang_feat, jemb_dropout):
super(AttendNodeModule, self).__init__()
self.matching = Matching(dim_vis_feat, dim_lang_feat, jemb_dim, jemb_dropout, -1)
self.feat_normalizer = NormalizeScale(dim_vis_feat, visual_init_norm)
def forward(self, vis_feats, lang_feats, cls):
bs, n = vis_feats.size(0), vis_feats.size(1)
vis_feats = self.feat_normalizer(vis_feats.view(bs * n, -1)).view(bs, n, -1)
attn = self.matching(vis_feats, lang_feats, (cls != -1).float())
return attn
class Matching(nn.Module):
def __init__(self, vis_dim, lang_dim, jemb_dim, jemb_dropout, min_value):
super(Matching, self).__init__()
self.vis_emb_fc = nn.Sequential(nn.Linear(vis_dim, jemb_dim),
nn.BatchNorm1d(jemb_dim),
nn.ReLU(),
nn.Dropout(jemb_dropout),
nn.Linear(jemb_dim, jemb_dim),
nn.BatchNorm1d(jemb_dim))
self.lang_emb_fc = nn.Sequential(nn.Linear(lang_dim, jemb_dim),
nn.BatchNorm1d(jemb_dim),
nn.ReLU(),
nn.Dropout(jemb_dropout),
nn.Linear(jemb_dim, jemb_dim),
nn.BatchNorm1d(jemb_dim))
self.min_value = min_value
def forward(self, vis_input, lang_input, mask):
# vis_input (bs, n, vis_dim); lang_input (bs, num_seq, lang_dim); mask (bs, n)
bs, n = vis_input.size(0), vis_input.size(1)
num_seq = lang_input.size(1)
vis_emb = self.vis_emb_fc(vis_input.view(bs * n, -1))
lang_emb = self.lang_emb_fc(lang_input.view(bs * num_seq, -1))
vis_emb_normalized = F.normalize(vis_emb, p=2, dim=1)
lang_emb_normalized = F.normalize(lang_emb, p=2, dim=1)
vis_emb_normalized = vis_emb_normalized.view(bs, n, -1)
lang_emb_normalized = lang_emb_normalized.view(bs, num_seq, -1)
cossim = torch.bmm(lang_emb_normalized, vis_emb_normalized.transpose(1, 2)) # bs, num_seq, n
mask_expand = mask.unsqueeze(1).expand(bs, num_seq, n).float()
cossim = cossim * mask_expand
cossim[mask_expand == 0] = self.min_value
return cossim
class MergeModule(nn.Module):
def __init__(self, norm_type='cossim', need_norm=True):
super(MergeModule, self).__init__()
self.norm_type = norm_type
self.need_norm = need_norm
self.norm_fun = NormAttnMap(norm_type)
def forward(self, attn_map, global_sub_attn_maps, global_obj_attn_maps, mask_sub, mask_obj):
# attn_map(bs, n); global_attn_maps(bs, num_seq, n); mask(bs, num_seq)
bs, num_seq, n = global_sub_attn_maps.size(0), global_sub_attn_maps.size(1), global_sub_attn_maps.size(2)
mask_sub_expand = (mask_sub == 1).float().unsqueeze(2).expand(bs, num_seq, n)
sub_attn_map_sum = torch.sum(mask_sub_expand * global_sub_attn_maps, dim=1)
mask_obj_expand = (mask_obj == 1).float().unsqueeze(2).expand(bs, num_seq, n)
obj_attn_map_sum = torch.sum(mask_obj_expand * global_obj_attn_maps, dim=1)
attn_map_sum = sub_attn_map_sum + obj_attn_map_sum + attn_map
if self.need_norm:
attn, norm = self.norm_fun(attn_map_sum)
else:
attn = attn_map_sum
return attn
class TransferModule(nn.Module):
def __init__(self, norm_type='cossim', need_norm=True):
super(TransferModule, self).__init__()
self.norm_type = norm_type
self.need_norm = need_norm
self.norm_fun = NormAttnMap(norm_type)
def forward(self, attn_relation, relation_ind, global_sub_attn_maps, sub_mask, global_obj_attn_maps, obj_mask,
attn_obj):
# attn_relation(bs, n, num_cxt), relation_ind(bs, n, num_cxt)
# global_attn_maps(bs, num_seq, n), mask(bs, num_seq)
bs, n, num_cxt = attn_relation.size(0), attn_relation.size(1), attn_relation.size(2)
num_seq = global_sub_attn_maps.size(1)
# first son or no son
sub_num_rel = torch.sum(sub_mask, dim=1)
# get sub son attn
sub_mask_expand = (sub_mask == 1).float().unsqueeze(2).expand(bs, num_seq, n)
sub_son_map = torch.sum(sub_mask_expand * global_sub_attn_maps, dim=1)
sub_num_rel_expand = sub_num_rel.unsqueeze(1).expand(bs, n)
sub_son_map[sub_num_rel_expand == 0] = 0 # bs, n
# get obj son attn
obj_num_rel = torch.sum(obj_mask, dim=1)
obj_mask_expand = (obj_mask == 1).float().unsqueeze(2).expand(bs, num_seq, n)
obj_son_map = torch.sum(obj_mask_expand * global_obj_attn_maps, dim=1)
obj_num_rel_expand = obj_num_rel.unsqueeze(1).expand(bs, n)
obj_son_map[obj_num_rel_expand == 0] = 0
#total son
son_map = sub_son_map + obj_son_map
num_rel_expand = sub_num_rel_expand + obj_num_rel_expand
if self.need_norm:
son_map, norm = self.norm_fun(son_map)
son_map = son_map * (num_rel_expand != 0).float() + attn_obj * (num_rel_expand == 0).float()
offset_idx = torch.tensor(np.array(range(bs)) * n, requires_grad=False).cuda()
offset_idx = offset_idx.unsqueeze(1).unsqueeze(2).expand(bs, n, num_cxt)
select_idx = (relation_ind != -1).long() * relation_ind + offset_idx
select_attn = torch.index_select(son_map.view(bs * n, 1), 0, select_idx.view(-1))
select_attn = select_attn.view(bs, n, num_cxt)
select_attn = (relation_ind != -1).float() * select_attn
attn_map_sum = torch.sum(attn_relation * select_attn, dim=2)
if self.need_norm:
attn, norm = self.norm_fun(attn_map_sum)
else:
attn = attn_map_sum
return attn, son_map
class NormAttnMap(nn.Module):
def __init__(self, norm_type='cossim'):
super(NormAttnMap, self).__init__()
self.norm_type = norm_type
def forward(self, attn_map):
if self.norm_type != 'cosssim':
norm = torch.max(attn_map, dim=1, keepdim=True)[0].detach()
else:
norm = torch.max(torch.abs(attn_map), dim=1, keepdim=True)[0].detach()
norm[norm <= 1] = 1
attn = attn_map / norm
return attn, norm |
fabfile.py | SurvivorT/SRTP | 489 | 12606420 | #!/usr/bin/env python
#
# File: fabfile.py
#
# Created: Wednesday, August 24 2016 by rejuvyesh <<EMAIL>>
# License: GNU GPL 3 <http://www.gnu.org/copyleft/gpl.html>
#
from fabric.api import cd, put, path, task, shell_env, run, env, local, settings
from fabric.contrib.project import rsync_project
import os.path
from time import sleep
env.use_ssh_config = True
RLTOOLS_LOC = '/home/{}/src/python/rltools'.format(env.user)
MADRL_LOC = '/home/{}/src/python/MADRL'.format(env.user)
class Tmux(object):
def __init__(self, name):
self._name = name
with settings(warn_only=True):
test = run('tmux has-session -t {}'.format(self._name))
if test.failed:
run('tmux new-session -d -s {}'.format(self._name))
def run(self, cmd, window=0):
run('tmux send -t {}.{} "{}" ENTER'.format(self._name, window, cmd))
@task
def githash():
git_hash = local('git rev-parse HEAD', capture=True)
return git_hash
@task
def sync():
rsync_project(remote_dir=os.path.split(MADRL_LOC)[0], exclude=['*.h5'])
@task(alias='pipe')
def runpipeline(script, fname):
git_hash = githash()
sync()
pipetm = Tmux('pipeline')
pipetm.run('export PYTHONPATH={}:{}'.format(RLTOOLS_LOC, MADRL_LOC))
pipetm.run('cd {}'.format(MADRL_LOC))
pipetm.run('python {} {} {}'.format(script, fname, git_hash))
sleep(0.5)
pipetm.run('y')
|
slick_reporting/forms.py | ryaustin/django-slick-reporting | 258 | 12606533 | from __future__ import unicode_literals
from django import forms
class OrderByForm(forms.Form):
order_by = forms.CharField(required=False)
def get_order_by(self, default_field=None):
"""
Get the order by specified by teh form or the default field if provided
:param default_field:
:return: tuple of field and direction
"""
if self.is_valid():
order_field = self.cleaned_data['order_by']
order_field = order_field or default_field
if order_field:
return self.parse_order_by_field(order_field)
return None, None
def parse_order_by_field(self, order_field):
"""
Specify the field and direction
:param order_field: the field to order by
:return: tuple of field and direction
"""
if order_field:
asc = True
if order_field[0:1] == '-':
order_field = order_field[1:]
asc = False
return order_field, not asc
return None, None
|
Wenshu_Project/Wenshu/items.py | juvu/Wenshu_Spider | 197 | 12606535 | <filename>Wenshu_Project/Wenshu/items.py
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class WenshuCaseItem(scrapy.Item):
# define the fields for your item here like:
casecourt = scrapy.Field()
casecontent = scrapy.Field()
casetype = scrapy.Field()
# casereason = scrapy.Field()
casejudgedate = scrapy.Field()
# caseparty = scrapy.Field()
caseprocedure = scrapy.Field()
casenumber = scrapy.Field()
casenopublicreason = scrapy.Field()
casedocid = scrapy.Field()
casename = scrapy.Field()
casecontenttype = scrapy.Field()
caseuploaddate = scrapy.Field()
casedoctype = scrapy.Field()
caseclosemethod = scrapy.Field()
caseeffectivelevel = scrapy.Field()
|
backend/www/test/update_follower_test.py | xuantan/viewfinder | 645 | 12606561 | # Copyright 2012 Viewfinder Inc. All Rights Reserved.
"""Tests update_follower method.
"""
__author__ = ['<EMAIL> (<NAME>)']
import mock
from copy import deepcopy
from viewfinder.backend.base.util import SetIfNotNone
from viewfinder.backend.db.db_client import DBKey
from viewfinder.backend.db.device import Device
from viewfinder.backend.db.follower import Follower
from viewfinder.backend.db.operation import Operation
from viewfinder.backend.db.viewpoint import Viewpoint
from viewfinder.backend.services.apns import TestService
from viewfinder.backend.www.test import service_base_test
class UpdateFollowerTestCase(service_base_test.ServiceBaseTestCase):
def setUp(self):
super(UpdateFollowerTestCase, self).setUp()
self._CreateSimpleTestAssets()
self._new_vp_id, ep_id = self._ShareSimpleTestAssets([self._user2.user_id])
self._all_labels_sans_removed = Follower.ALL_LABELS[:]
self._all_labels_sans_removed.remove(Follower.REMOVED)
self._all_labels_sans_removed.remove(Follower.UNREVIVABLE)
def testUpdateFollower(self):
"""Update existing followers."""
# Update follower of default viewpoint.
self._tester.UpdateFollower(self._cookie,
self._user.private_vp_id,
labels=self._all_labels_sans_removed)
# Update shared viewpoint for target user.
self._tester.UpdateFollower(self._cookie2,
self._new_vp_id,
labels=[Follower.CONTRIBUTE])
# Update shared viewpoint for sharing user.
self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=self._all_labels_sans_removed)
def testViewPermissions(self):
"""Update follower attributes with only viewing permission."""
# Only view permission should be required to make these updates.
self._UpdateOrAllocateDBObject(Follower, user_id=self._user.user_id,
viewpoint_id=self._new_vp_id, labels=[])
self._tester.UpdateFollower(self._cookie, self._new_vp_id, viewed_seq=100)
self._tester.UpdateFollower(self._cookie, self._new_vp_id, viewed_seq=101, labels=[])
self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=[Follower.PERSONAL])
self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=[Follower.HIDDEN])
def testUpdateFollowerFailure(self):
"""Error: Update follower with REMOVED labels should fail because it's not allowed."""
self._UpdateOrAllocateDBObject(Follower, user_id=self._user.user_id,
viewpoint_id=self._new_vp_id, labels=[])
self.assertRaisesHttpError(403,
self._tester.UpdateFollower,
self._cookie,
self._new_vp_id,
labels=[Follower.REMOVED])
def testRatchetViewedSeq(self):
"""Verify that attempt to decrease viewed_seq is ignored."""
self._tester.UpdateFollower(self._cookie, self._new_vp_id, viewed_seq=2)
self._tester.UpdateFollower(self._cookie, self._new_vp_id, viewed_seq=1)
def testViewedSeqTooHigh(self):
"""Verify that attempt to set viewed_seq > update_seq is not allowed."""
self._tester.UpdateFollower(self._cookie, self._new_vp_id, viewed_seq=1000)
follower = self._RunAsync(Follower.Query, self._client, self._user2.user_id, self._new_vp_id, None)
self.assertEqual(follower.viewed_seq, 0)
self._tester.UpdateFollower(self._cookie2, self._new_vp_id, viewed_seq=1000)
follower = self._RunAsync(Follower.Query, self._client, self._user2.user_id, self._new_vp_id, None)
self.assertEqual(follower.viewed_seq, 1)
def testNoOpUpdate(self):
"""Update follower attribute to same value as it had before."""
follower = self._RunAsync(Follower.Query, self._client, self._user.user_id, self._new_vp_id, None)
self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=list(follower.labels))
self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=list(follower.labels))
def testRemoveLabels(self):
"""Remove labels from the viewpoint after setting them there."""
self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=self._all_labels_sans_removed)
self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=Follower.PERMISSION_LABELS)
def testSetRemovedLabel(self):
"""Set the REMOVED label when it's already set."""
self._tester.RemoveViewpoint(self._cookie, self._new_vp_id)
self._tester.UpdateFollower(self._cookie, self._new_vp_id, labels=Follower.PERMISSION_LABELS + [Follower.REMOVED])
def testMuteViewpoint(self):
"""Test the MUTED label on a follower."""
# Validate alerts directly in this test rather than relying on cleanup validation.
self._skip_validation_for = ['Alerts']
# Get push token for user #2.
device = self._RunAsync(Device.Query, self._client, self._user2.user_id, self._device_ids[1], None)
push_token = device.push_token[len(TestService.PREFIX):]
# ------------------------------
# Test that APNS and email alerts are suppressed for muted viewpoint.
# ------------------------------
self._tester.UpdateFollower(self._cookie2,
self._new_vp_id,
labels=[Follower.CONTRIBUTE, Follower.MUTED])
self._tester.ShareExisting(self._cookie, self._new_vp_id, [(self._episode_id2, self._photo_ids2)])
self.assertEqual(len(TestService.Instance().GetNotifications(push_token)), 1)
# ------------------------------
# Un-mute and test that alerts are again sent.
# ------------------------------
self._tester.UpdateFollower(self._cookie2,
self._new_vp_id,
labels=[Follower.CONTRIBUTE])
self._tester.PostComment(self._cookie, self._new_vp_id, 'Hi')
self.assertEqual(len(TestService.Instance().GetNotifications(push_token)), 2)
def testAutoSave(self):
"""Test enabling auto-save, then disabling it."""
self._tester.UpdateFollower(self._cookie2, self._new_vp_id, labels=[Follower.CONTRIBUTE, Follower.AUTOSAVE])
self._tester.ShareExisting(self._cookie, self._new_vp_id, [(self._episode_id2, self._photo_ids2[:1])])
self.assertEqual(self._CountEpisodes(self._cookie2, self._user2.private_vp_id), 1)
self._tester.UpdateFollower(self._cookie2, self._new_vp_id, labels=[Follower.CONTRIBUTE])
self._tester.ShareExisting(self._cookie, self._new_vp_id, [(self._episode_id2, self._photo_ids2[1:])])
self.assertEqual(self._CountEpisodes(self._cookie2, self._user2.private_vp_id), 1)
def testAdditionalAttributes(self):
"""Try to update attributes which not available for update."""
for attr in ['sharing_user_id', 'foo', 'title']:
self.assertRaisesHttpError(400,
self._tester.UpdateFollower,
self._cookie,
self._new_vp_id,
attr=attr)
@mock.patch.object(Operation, 'FAILPOINTS_ENABLED', True)
def testIdempotency(self):
"""Force op failure in order to test idempotency."""
self._tester.UpdateFollower(self._cookie, self._new_vp_id, viewed_seq=2, labels=self._all_labels_sans_removed)
def testInvalidViewpoint(self):
"""ERROR: Try to update a follower on a viewpoint that does not exist."""
self.assertRaisesHttpError(403, self._tester.UpdateFollower, self._cookie, 'vunknown')
def testViewpointNotFollowed(self):
"""ERROR: Try to update a viewpoint that is not followed."""
self.assertRaisesHttpError(403, self._tester.UpdateFollower, self._cookie3, self._new_vp_id)
def testClearPermissionLabels(self):
"""ERROR: Try to clear follower permission labels."""
self.assertRaisesHttpError(403,
self._tester.UpdateFollower,
self._cookie,
self._new_vp_id,
labels=[])
def _ValidateUpdateFollower(tester, user_cookie, op_dict, foll_dict):
"""Validates the results of a call to update_follower. Also used to validate update_viewpoint
in the case where only follower attributes are modified (backwards-compatibility case).
"""
validator = tester.validator
user_id, device_id = tester.GetIdsFromCookie(user_cookie)
viewpoint_id = foll_dict['viewpoint_id']
# Validate that viewed_seq value ratchets upwards.
has_viewed_seq = 'viewed_seq' in foll_dict
if has_viewed_seq:
update_seq = validator.GetModelObject(Viewpoint, viewpoint_id).update_seq
old_viewed_seq = validator.GetModelObject(Follower, DBKey(user_id, viewpoint_id)).viewed_seq
if foll_dict['viewed_seq'] > update_seq:
foll_dict['viewed_seq'] = update_seq
if foll_dict['viewed_seq'] < old_viewed_seq:
del foll_dict['viewed_seq']
# Validate Follower object.
foll_dict['user_id'] = user_id
follower = validator.ValidateUpdateDBObject(Follower, **foll_dict)
# Validate notifications for the update.
invalidate = {'viewpoints': [{'viewpoint_id': viewpoint_id,
'get_attributes': True}]}
if has_viewed_seq and 'labels' not in foll_dict:
# Only viewed_seq attribute was updated, and it will be inlined in notification.
invalidate = None
# Only follower attributes were updated, so validate single notification to calling user.
validator.ValidateNotification('update_follower',
user_id,
op_dict,
invalidate,
viewpoint_id=viewpoint_id,
seq_num_pair=(None, follower.viewed_seq if has_viewed_seq else None))
def _TestUpdateFollower(tester, user_cookie, request_dict):
"""Called by the ServiceTester in order to test update_follower service API call."""
user_id, device_id = tester.GetIdsFromCookie(user_cookie)
request_dict = deepcopy(request_dict)
# Send update_follower request.
actual_dict = tester.SendRequest('update_follower', user_cookie, request_dict)
op_dict = tester._DeriveNotificationOpDict(user_id, device_id, request_dict)
# Validate results.
_ValidateUpdateFollower(tester, user_cookie, op_dict, request_dict['follower'])
tester._CompareResponseDicts('update_follower', user_id, request_dict, {}, actual_dict)
return actual_dict
|
src/whylogs/cli/__init__.py | cswarth/whylogs | 603 | 12606617 | <gh_stars>100-1000
from .cli import cli, main
from .demo_cli import main as demo_main
__ALL__ = [
cli,
main,
demo_main,
]
|
tests/sparseml/pytorch/utils/test_ssd_helpers.py | clementpoiret/sparseml | 922 | 12606622 | <filename>tests/sparseml/pytorch/utils/test_ssd_helpers.py
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import pytest
import torch
from sparseml.pytorch.utils import get_default_boxes_300
@pytest.mark.skipif(
os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False),
reason="Skipping pytorch tests",
)
def test_default_box_representations():
default_boxes = get_default_boxes_300()
xywh_boxes = default_boxes.as_xywh()
ltrb_boxes = default_boxes.as_ltrb()
x = 0.5 * (ltrb_boxes[:, 2] + ltrb_boxes[:, 0])
y = 0.5 * (ltrb_boxes[:, 3] + ltrb_boxes[:, 1])
w = ltrb_boxes[:, 2] - ltrb_boxes[:, 0]
h = ltrb_boxes[:, 3] - ltrb_boxes[:, 1]
assert torch.max(torch.abs(xywh_boxes[:, 0] - x)) < 1e-4
assert torch.max(torch.abs(xywh_boxes[:, 1] - y)) < 1e-4
assert torch.max(torch.abs(xywh_boxes[:, 2] - w)) < 1e-4
assert torch.max(torch.abs(xywh_boxes[:, 3] - h)) < 1e-4
@pytest.mark.skipif(
os.getenv("NM_ML_SKIP_PYTORCH_TESTS", False),
reason="Skipping pytorch tests",
)
def test_default_box_encode_decode():
default_boxes = get_default_boxes_300()
boxes = torch.FloatTensor(1, 4).uniform_(0.0, 1.0).sort()[0] # random ltrb box
labels = torch.Tensor([1])
enc_boxes, enc_labels = default_boxes.encode_image_box_labels(boxes, labels)
# create scores to simulate model output
scores = torch.zeros(1, 2, enc_boxes.size(1))
scores[:, 0, :] = 100
scores[:, 0, enc_labels == 1] = 0
scores[:, 1, enc_labels == 1] = 100
dec_boxes, dec_labels, _ = default_boxes.decode_output_batch(
enc_boxes.unsqueeze(0), scores
)[0]
assert dec_labels.size(0) == 1
assert dec_labels.item() == 1
assert torch.max(torch.abs(boxes - dec_boxes)) < 1e-6
|
django_codemod/commands.py | webstar-commit/django-boilerplate | 128 | 12606638 | from abc import ABC
from typing import List, Type
import libcst as cst
from libcst.codemod import (
CodemodContext,
ContextAwareTransformer,
VisitorBasedCodemodCommand,
)
class BaseCodemodCommand(VisitorBasedCodemodCommand, ABC):
"""Base class for our commands."""
transformers: List[Type[ContextAwareTransformer]]
def __init__(self, transformers, context: CodemodContext) -> None:
self.transformers = transformers
super().__init__(context)
def transform_module_impl(self, tree: cst.Module) -> cst.Module:
for transform in self.transformers:
inst = transform(self.context)
tree = inst.transform_module(tree)
return tree
|
eland/utils.py | szabosteve/eland | 335 | 12606658 | <filename>eland/utils.py
# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import functools
import re
import warnings
from collections.abc import Collection as ABCCollection
from typing import Any, Callable, Collection, Iterable, List, TypeVar, Union, cast
import pandas as pd # type: ignore
RT = TypeVar("RT")
def deprecated_api(
replace_with: str,
) -> Callable[[Callable[..., RT]], Callable[..., RT]]:
def wrapper(f: Callable[..., RT]) -> Callable[..., RT]:
@functools.wraps(f)
def wrapped(*args: Any, **kwargs: Any) -> RT:
warnings.warn(
f"{f.__name__} is deprecated, use {replace_with} instead",
DeprecationWarning,
stacklevel=2,
)
return f(*args, **kwargs)
return wrapped
return wrapper
def is_valid_attr_name(s: str) -> bool:
"""
Ensure the given string can be used as attribute on an object instance.
"""
return bool(
isinstance(s, str) and re.search(string=s, pattern=r"^[a-zA-Z_][a-zA-Z0-9_]*$")
)
def to_list(x: Union[Collection[Any], pd.Series]) -> List[Any]:
if isinstance(x, ABCCollection):
return list(x)
elif isinstance(x, pd.Series):
return cast(List[Any], x.to_list())
raise NotImplementedError(f"Could not convert {type(x).__name__} into a list")
def try_sort(iterable: Iterable[str]) -> Iterable[str]:
# Pulled from pandas.core.common since
# it was deprecated and removed in 1.1
listed = list(iterable)
try:
return sorted(listed)
except TypeError:
return listed
|
plugins/dbnd-airflow-export/src/dbnd_airflow_export/metrics.py | busunkim96/dbnd | 224 | 12606668 | <reponame>busunkim96/dbnd
from collections import defaultdict
from contextlib import contextmanager
from functools import wraps
from timeit import default_timer
import flask
class MetricCollector(object):
def __init__(self):
self.d = None
@contextmanager
def use_local(self):
if self.d is not None:
# already local mode
yield self.d
return
self.d = defaultdict(dict)
try:
yield self.d
finally:
self.d = None
def add(self, group, name, value):
if self.d is not None:
self.d[group][name] = value
elif flask.has_app_context():
metrics = getattr(flask.g, group, None)
if metrics is None:
metrics = {}
setattr(flask.g, group, metrics)
metrics[name] = value
METRIC_COLLECTOR = MetricCollector()
def measure_time(f):
@wraps(f)
def wrapped(*args, **kwargs):
start = default_timer()
result = f(*args, **kwargs)
end = default_timer()
METRIC_COLLECTOR.add("perf_metrics", f.__name__, end - start)
return result
return wrapped
def save_result_size(*names):
def decorator(f):
@wraps(f)
def wrapped(*args, **kwargs):
result = f(*args, **kwargs)
values = result
if len(names) == 1:
values = (result,)
for name, value_list in zip(names, values):
METRIC_COLLECTOR.add("size_metrics", name, len(value_list))
return result
return wrapped
return decorator
|
src/encoded/tests/test_upgrade_chip_peak_enrichment_quality_metric.py | procha2/encoded | 102 | 12606679 | <reponame>procha2/encoded<filename>src/encoded/tests/test_upgrade_chip_peak_enrichment_quality_metric.py
import pytest
def test_upgrade_chip_peak_enrichment_quality_metric_1_2(upgrader, chip_peak_enrichment_quality_metric_1):
value = upgrader.upgrade(
"chip_peak_enrichment_quality_metric",
chip_peak_enrichment_quality_metric_1,
current_version="1",
target_version="2",
)
assert value["schema_version"] == "2"
assert value.get("frip") == 0.253147998729
assert 'FRiP' not in value
|
tests/test_typeclass/test_typed_dict.py | ftaebi/classes | 475 | 12606681 | import sys
import pytest
from typing_extensions import TypedDict
from classes import typeclass
if sys.version_info[:2] >= (3, 9): # noqa: C901
pytestmark = pytest.mark.skip('Only python3.7 and python3.8 are supported')
else:
class _User(TypedDict):
name: str
registered: bool
class _UserDictMeta(type):
def __instancecheck__(cls, arg: object) -> bool:
return (
isinstance(arg, dict) and
isinstance(arg.get('name'), str) and
isinstance(arg.get('registered'), bool)
)
_Meta = type('_Meta', (_UserDictMeta, type(TypedDict)), {})
class UserDict(_User, metaclass=_Meta):
"""We use this class to represent a typed dict with instance check."""
@typeclass
def get_name(instance) -> str:
"""Example typeclass."""
@get_name.instance(delegate=UserDict)
def _get_name_user_dict(instance: UserDict) -> str:
return instance['name']
def test_correct_typed_dict():
"""Ensures that typed dict dispatch works."""
user: UserDict = {'name': 'sobolevn', 'registered': True}
assert get_name(user) == 'sobolevn'
@pytest.mark.parametrize('test_value', [
[],
{},
{'name': 'sobolevn', 'registered': None},
{'name': 'sobolevn'},
{'registered': True},
])
def test_wrong_typed_dict(test_value):
"""Ensures that typed dict dispatch works."""
with pytest.raises(NotImplementedError):
get_name(test_value)
|
base_agent/stop_condition.py | kandluis/droidlet | 669 | 12606693 | <reponame>kandluis/droidlet
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
class StopCondition:
def __init__(self, agent):
self.agent = agent
def check(self) -> bool:
raise NotImplementedError("Implemented by subclass")
class NeverStopCondition(StopCondition):
def __init__(self, agent):
super().__init__(agent)
self.name = "never"
def check(self):
return False
|
backend/tests/data/github/auth/test_main.py | rutvikpadhiyar000/github-trends | 157 | 12606743 | import unittest
from src.constants import TEST_TOKEN as TOKEN, TEST_USER_ID as USER_ID
from src.data.github.auth.main import get_unknown_user
class TestTemplate(unittest.TestCase):
def test_get_unknown_user_valid(self):
user_id = get_unknown_user(TOKEN)
self.assertEqual(user_id, USER_ID)
def test_get_unknown_user_invalid(self):
user_id = get_unknown_user("")
self.assertEqual(user_id, None)
# TODO: test authenticate()
|
rotkehlchen/chain/ethereum/modules/makerdao/__init__.py | rotkehlchenio/rotkehlchen | 137 | 12606750 | __all__ = ['MakerdaoDsr', 'MakerdaoVaults']
from .accountant import MakerdaoAccountant # noqa: F401
from .decoder import MakerdaoDecoder # noqa: F401
from .dsr import MakerdaoDsr
from .vaults import MakerdaoVaults
|
base/site-packages/captchas/fields.py | edisonlz/fastor | 285 | 12606766 | import random
from django.conf import settings
from django import forms
from django.utils.translation import ugettext as _
from captchas.widgets import CaptchaWidget
from Captcha import PersistentFactory
from factory import CacheFactory
class CaptchaField(forms.CharField):
"""
Captcha form field
Originally based on the source code found here:
http://kill9.eu/2007/08/17/captcha-widgets-django/
"""
widget = CaptchaWidget
def clean(self, values):
value, captcha_id = values
factory = CacheFactory()
test = factory.get(str(captcha_id))
if not test or not test.valid:
raise forms.ValidationError(_('Please refresh this page to get '
'new image'))
if not test.testSolutions([value.strip()]):
raise forms.ValidationError(_('You did not type the correct '
'text'))
return ''
|
src/analyzer/lexicon/validator_test.py | nogeeky/turkish-morphology | 157 | 12606767 | # coding=utf-8
# Copyright 2019 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for src.analyzer.lexicon.validator."""
import collections
from src.analyzer.lexicon import tags
from src.analyzer.lexicon import validator
from absl.testing import absltest
from absl.testing import parameterized
def setUpModule():
# Inject valid test tags and their expected required and optional features to
# respective dictionaries that are used in validation. This allows us to use
# lexicon entries that are constructed with these tags and features in below
# test cases.
tag_set = (
tags.TagSetItem(tag="TAG-1"),
tags.TagSetItem(
tag="TAG-2",
required_features=collections.OrderedDict([
("Cat1", {"Val11", "Val12"}),
("Cat2", {"Val21", "Val22"}),
]),
),
tags.TagSetItem(
tag="TAG-3",
optional_features={
"Cat1": {"Val12"},
"Cat3": {"Val31"},
},
),
)
tags.VALID_TAGS.update({t.tag for t in tag_set})
tags.REQUIRED_FEATURES.update({t.tag: t.required_features for t in tag_set})
tags.OPTIONAL_FEATURES.update({t.tag: t.optional_features for t in tag_set})
class ValidateTest(parameterized.TestCase):
@parameterized.named_parameters([
{
"testcase_name": "NoFeaturesExpectedNonCompound",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "~",
"features": "~",
"is_compound": "FaLsE",
},
},
{
"testcase_name": "NoFeaturesExpectedNonCompoundWithMorphophonemics",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "FaLsE",
},
},
{
"testcase_name": "NoFeaturesExpectedCompoundWithMorphophonemics",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
},
{
"testcase_name": "RequiredFeaturesExpectedNonCompoundWithFeatures",
"entry": {
"tag": "TaG-2",
"root": "valid-root",
"morphophonemics": "~",
"features": "+[Cat1=Val12]+[Cat2=Val21]",
"is_compound": "FaLsE",
},
},
{
"testcase_name": ("RequiredFeaturesExpectedNonCompoundWithFeaturesAnd"
"Morphophonemics"),
"entry": {
"tag": "TaG-2",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]+[Cat2=Val21]",
"is_compound": "FaLsE",
},
},
{
"testcase_name":
"RequiredFeaturesExpectedCompoundWithFeaturesAndMorphophonemics",
"entry": {
"tag": "TaG-2",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]+[Cat2=Val21]",
"is_compound": "TrUe",
},
},
{
"testcase_name": "OptionalFeaturesExpectedNonCompound",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "~",
"features": "~",
"is_compound": "FaLsE",
},
},
{
"testcase_name":
"OptionalFeaturesExpectedNonCompoundWithMorphophonemics",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "FaLsE",
},
},
{
"testcase_name": "OptionalFeaturesExpectedNonCompoundWithFeatures",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "~",
"features": "+[Cat1=Val12]",
"is_compound": "FaLsE",
},
},
{
"testcase_name": ("OptionalFeaturesExpectedNonCompoundWithFeaturesAnd"
"Morphophonemics"),
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]",
"is_compound": "FaLsE",
},
},
{
"testcase_name":
"OptionalFeaturesExpectedCompoundWithMorphophonemics",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
},
{
"testcase_name":
"OptionalFeaturesExpectedCompoundWithFeaturesAndMorphophonemics",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]",
"is_compound": "TrUe",
},
},
])
def test_success(self, entry):
self.assertIsNone(validator.validate(entry))
@parameterized.named_parameters([
{
"testcase_name": "MissingTag",
"entry": {
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry is missing fields: 'tag'",
},
{
"testcase_name": "MissingRoot",
"entry": {
"tag": "TaG-1",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry is missing fields: 'root'",
},
{
"testcase_name": "MissingMorphophonemics",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry is missing fields: 'morphophonemics'",
},
{
"testcase_name": "MissingFeatures",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"is_compound": "TrUe",
},
"message": "Entry is missing fields: 'features'",
},
{
"testcase_name": "MissingIsCompound",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
},
"message": "Entry is missing fields: 'is_compound'",
},
{
"testcase_name":
"MissingMultipleRequiredField",
"entry": {
"tag": "TaG-1",
"features": "~",
},
"message": ("Entry is missing fields: 'is_compound,"
" morphophonemics, root"),
},
{
"testcase_name": "EmptyTag",
"entry": {
"tag": "",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry fields have empty values: 'tag'",
},
{
"testcase_name": "EmptyRoot",
"entry": {
"tag": "TaG-1",
"root": "",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry fields have empty values: 'root'",
},
{
"testcase_name": "EmptyMorphophonemics",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry fields have empty values: 'morphophonemics'",
},
{
"testcase_name": "EmptyFeatures",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "",
"is_compound": "TrUe",
},
"message": "Entry fields have empty values: 'features'",
},
{
"testcase_name": "EmptyIsCompound",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "",
},
"message": "Entry fields have empty values: 'is_compound'",
},
{
"testcase_name":
"MultipleEmptyRequiredField",
"entry": {
"tag": "TaG-1",
"root": "",
"morphophonemics": "",
"features": "~",
"is_compound": "",
},
"message": ("Entry fields have empty values: 'is_compound,"
" morphophonemics, root'"),
},
{
"testcase_name": "TagContainsInfixWhitespace",
"entry": {
"tag": "TaG 1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry field values contain whitespace: 'tag'",
},
{
"testcase_name": "MorphophonemicsContainsInfixWhitespace",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry field values contain whitespace: 'morphophonemics'",
},
{
"testcase_name": "FeaturesContainsInfixWhitespace",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1 = Val12]",
"is_compound": "TrUe",
},
"message": "Entry field values contain whitespace: 'features'",
},
{
"testcase_name": "MultipleFieldsContainsInfixWhitespace",
"entry": {
"tag": "TaG 3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1 = Val12]",
"is_compound": "TrUe",
},
"message": "Entry field values contain whitespace: 'features, tag'",
},
{
"testcase_name":
"InvalidTag",
"entry": {
"tag": "Invalid-Tag",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
"message": ("Entry 'tag' field has invalid value. It can only be one"
" of the valid tags that are defined in"
" 'morphotactics_compiler/tags.py'."),
},
{
"testcase_name":
"InvalidIsCompound",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "invalid-is-compound",
},
"message": ("Entry 'is_compound' field has invalid value. It can only"
" have the values 'true' or 'false'."),
},
{
"testcase_name":
"InvalidMorphophonemics",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "~",
"features": "~",
"is_compound": "TrUe",
},
"message": ("Entry is marked as ending with compounding marker but it"
" is missing morphophonemics annotation."),
},
{
"testcase_name": "InvalidFeaturesInvalidPrefixCharacters",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "foo+[Cat1=Val12]+[Cat3=Val31]",
"is_compound": "TrUe",
},
"message": "Entry features annotation is invalid.",
},
{
"testcase_name": "InvalidFeaturesInvalidInfixCharacters",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]foo+[Cat3=Val31]",
"is_compound": "TrUe",
},
"message": "Entry features annotation is invalid.",
},
{
"testcase_name": "InvalidFeaturesInvalidSuffixCharacters",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]+[Cat3=Val31]foo",
"is_compound": "TrUe",
},
"message": "Entry features annotation is invalid.",
},
{
"testcase_name": "NoRequiredFeatures",
"entry": {
"tag": "TaG-2",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "~",
"is_compound": "TrUe",
},
"message": "Entry is missing required features.",
},
{
"testcase_name": "MissingRequiredFeatures",
"entry": {
"tag": "TaG-2",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]",
"is_compound": "TrUe",
},
"message": "Entry has invalid required feature category.",
},
{
"testcase_name": "InvalidRequiredFeatureCategory",
"entry": {
"tag": "TaG-2",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]+[Cat3=Val21]",
"is_compound": "TrUe",
},
"message": "Entry has invalid required feature category.",
},
{
"testcase_name": "InvalidRequiredFeatureValue",
"entry": {
"tag": "TaG-2",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]+[Cat2=Val23]",
"is_compound": "TrUe",
},
"message": "Entry has invalid required feature value.",
},
{
"testcase_name": "InvalidOptionalFeatureCategory",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat2=Val12]",
"is_compound": "TrUe",
},
"message": "Entry has invalid optional features.",
},
{
"testcase_name": "InvalidOptionalFeatureValue",
"entry": {
"tag": "TaG-3",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val11]",
"is_compound": "TrUe",
},
"message": "Entry has invalid optional features.",
},
{
"testcase_name": "RedundantFeatures",
"entry": {
"tag": "TaG-1",
"root": "valid-root",
"morphophonemics": "valid-morphophonemics",
"features": "+[Cat1=Val12]",
"is_compound": "TrUe",
},
"message": "Entry has features while it is not expected to have any.",
},
])
def test_raises_exception(self, entry, message):
with self.assertRaisesRegexp(validator.InvalidLexiconEntryError, message):
validator.validate(entry)
if __name__ == "__main__":
absltest.main()
|
cli.py | ParikhKadam/frankenstein | 344 | 12606794 | <filename>cli.py<gh_stars>100-1000
import os, sys
from core.project import Project
from optparse import OptionParser, OptionGroup
def project_main(options, args):
p = Project(options.projectName, allow_create=options.projectCreate)
if options.deleteGroup:
p.group_delete(options.deleteGroup)
if options.loadELF:
p.load_elf(options.loadELF, load_segments=options.loadSegments, load_symbols=options.loadSymbols)
if options.symbolize:
for addr in args[1:]:
addr = int(addr, 0)
name = p.symbolize(addr)
print("0x%x = %s" % (addr, name))
if options.show:
p.show()
def project_optparse(argv):
parser = OptionParser()
parser.add_option("-p", "--project", dest="projectName",
help="Path to project", metavar="DIR", default=".")
parser.add_option("-c", "--create", dest="projectCreate", action="store_true",
help="Create new project", default=False)
parser.add_option("-s", "--show", dest="show", action="store_true",
help="Show project details", default=False)
parser.add_option("-S", "--symbolize", dest="symbolize", action="store_true",
help="Lookup symbol by address", default=False)
# Load
group = OptionGroup(parser, "Loading files")
group.add_option("-e", "--load-elf", dest="loadELF",
help="Path to project", metavar="FILE")
group.add_option("", "--no-symbols", dest="loadSymbols", action="store_false",
help="Create new project", default=True)
group.add_option("", "--no-segments", dest="loadSegments", action="store_false",
help="Create new project", default=True)
parser.add_option_group(group)
# Segment group management
group = OptionGroup(parser, "Group management")
group.add_option("", "--group-delete", dest="deleteGroup",
help="Delete group", default=False)
parser.add_option_group(group)
(options, args) = parser.parse_args(argv)
if len(argv) == 1:
parser.print_help()
parser.error('No action taken')
cfg = os.path.join(options.projectName, "project.json")
if not os.path.isfile(cfg) and not options.projectCreate:
parser.print_help()
parser.error('projectName not given')
project_main(options, args)
def usage():
print("usage %s [module]" % sys.argv[0])
print("Modules:")
print("\tproject Manage projects")
print("\tdjago Django console")
sys.exit(-1)
if len(sys.argv) == 1:
usage()
module = sys.argv[1]
if module == "project":
project_optparse(sys.argv[1:])
elif module == "django":
from django.core.management import execute_from_command_line
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "frankensteinWebUI.settings")
execute_from_command_line(sys.argv[1:])
else:
usage()
|
tests/framework/ROM/TimeSeries/SyntheticHistory/TrainingData/generateFourier.py | rinelson456/raven | 159 | 12606853 | <reponame>rinelson456/raven<filename>tests/framework/ROM/TimeSeries/SyntheticHistory/TrainingData/generateFourier.py<gh_stars>100-1000
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Generates training data in the form of Fourier signals.
"""
import numpy as np
from generators import fourier, toFile
#############
# Fourier A #
#############
seconds = np.arange(100) / 10. # 0 to 10 in 0.1 increments
periods = [2, 5, 10]
amps = [0.5, 1, 2]
phases = [0, np.pi/4, np.pi]
intercept = 42
signal0 = fourier(amps, periods, phases, seconds, mean=intercept)
periods = [3]
amps = [2]
phases = [np.pi]
intercept = 1
signal1 = fourier(amps, periods, phases, seconds, mean=intercept)
out = np.zeros((len(seconds), 3))
out[:, 0] = seconds
out[:, 1] = signal0
out[:, 2] = signal1
toFile(out, 'Wavelet_A', targets=['signal1', 'signal2'], pivotName='seconds')
|
zentral/contrib/mdm/app_manifest.py | janheise/zentral | 634 | 12606854 | from hashlib import md5
import logging
import subprocess
from defusedxml.ElementTree import fromstring, ParseError
logger = logging.getLogger("zentral.contrib.mdm.app_manifest")
MD5_SIZE = 10 * 2**20 # 10MB
def read_distribution_info(package_file):
try:
cp = subprocess.run(["xar", "-f", package_file.temporary_file_path(), "-x", "--to-stdout", "Distribution"],
check=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
except subprocess.CalledProcessError:
raise ValueError("Could not read Distribution file")
try:
installer_script_elm = fromstring(cp.stdout)
except ParseError:
raise ValueError("Invalid Distribution file")
title = installer_script_elm.find("title")
product_elm = installer_script_elm.find("product")
if product_elm is None:
logger.warning("Could not find <product/>")
for pkg_ref in installer_script_elm.findall("pkg-ref"):
try:
product_id = pkg_ref.attrib["id"]
product_version = pkg_ref.attrib["version"]
except KeyError:
continue
else:
if not product_id or not product_version:
continue
else:
break
else:
raise ValueError("Could not find values for product_id and product_name")
else:
try:
product_id = product_elm.attrib["id"]
product_version = product_elm.attrib["version"]
except KeyError as e:
raise ValueError(f"Missing <product/> attr: {e.args[0]}")
if not product_id:
raise ValueError("Product ID is null")
if not product_version:
raise ValueError("Production version is null")
bundles = []
for bundle in installer_script_elm.findall(".//bundle"):
try:
bundles.append({k: bundle.attrib[v]
for k, v in (("version_str", "CFBundleShortVersionString"),
("version", "CFBundleVersion"),
("id", "id"),
("path", "path"))})
except KeyError as e:
logger.error(f"Missing <bundle/> attr: {e.args[0]}")
return title, product_id, product_version, bundles
def get_md5s(package_file, md5_size=MD5_SIZE):
file_chunk_size = 64 * 2**10 # 64KB
md5_size = (md5_size // file_chunk_size) * file_chunk_size
md5s = []
h = md5()
current_size = 0
for chunk in package_file.chunks(chunk_size=file_chunk_size):
h.update(chunk)
current_size += len(chunk)
if current_size == md5_size:
md5s.append(h.hexdigest())
h = md5()
current_size = 0
if current_size:
md5s.append(h.hexdigest())
if len(md5s) == 1:
md5_size = current_size
return md5_size, md5s
def build_enterprise_app_manifest(package_file):
# see https://support.apple.com/lt-lt/guide/deployment-reference-macos/ior5df10f73a/web
title, product_id, product_version, bundles = read_distribution_info(package_file)
md5_size, md5s = get_md5s(package_file)
manifest = {"items": [{"assets": [{"kind": "software-package", "md5-size": md5_size, "md5s": md5s}]}]}
return title, product_id, product_version, manifest, bundles
|
ufora/cumulus/test/TestBase.py | ufora/ufora | 571 | 12606855 | # Copyright 2015 Ufora Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import gzip
import Queue
import logging
import time
import threading
import ufora.FORA.python.FORA as FORA
import ufora.native.FORA as ForaNative
import ufora.native.Cumulus as CumulusNative
import ufora.native.Hash as HashNative
import ufora.util.Teardown as Teardown
import ufora.util.CodeCoverage as CodeCoverage
import cPickle as pickle
import ufora.native.CallbackScheduler as CallbackScheduler
callbackScheduler = CallbackScheduler.singletonForTesting()
IVC = ForaNative.ImplValContainer
callIVC = ForaNative.makeSymbol("Call")
expensiveCalculationText = """fun(count) {
let X = [(-1.83045,-2.05459),(-1.61185,-1.1104),(-2.39371,-2.3851),(-2.30236,-1.85439),(-3.29381,-2.14036),(-2.27295,-1.9858),
(-2.14089,-2.06091),(-0.667216,-0.470452),(-1.35343,-1.91638),(-2.32273,-2.91459),(4.04358,1.35241),(1.03174,3.38565),
(3.84581,1.81709),(1.37791,1.8897),(2.1719,2.35836),(1.20563,2.73266),(2.42006,2.00324),(0.986196,1.38097),
(3.11006,0.378729),(0.171622,2.46585)];
let y = [1.,1.,1.,1.,1.,1.,1.,1.,1.,1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.,-1.];
let DotProduct = fun(u,v) {
let res = 0
for ix in sequence(size(u))
res = res + u[ix] * v[ix]
res
}
let StochGDPrimalForm =
fun( X, Y, b, lambda, N ){
let m = size(X);
let d = size(X[0]);
let dims = (0,1);
let w = dims..apply(fun(d) { 0.0 });
let t = 1;
for i in sequence(N){
for j in sequence(m){
let jt = j; // can be randomized
if ( Y[jt]*( DotProduct( X[jt],w ))< 1.0 ){
let newW = []
let xJT = X[jt];
w = dims..apply({
xJT[_] * Y[jt] / (lambda * t) * (1.0 - 1.0 / t) + w[_]
})
} else {
w = dims..apply({ w[_] * (1.0 - 1.0 / t) } )
};
let mult = min(1.0, 1.0/(lambda*DotProduct(w,w)));
w = dims..apply({w[_] * mult })
t=t+1;
}
}
return w;
};
StochGDPrimalForm( X, y, 0.0, 0.01, count )
}"""
def makeComputationDefinitionFromIVCs(*args):
return CumulusNative.ComputationDefinition.Root(
CumulusNative.ImmutableTreeVectorOfComputationDefinitionTerm(
[CumulusNative.ComputationDefinitionTerm.Value(ForaNative.ImplValContainer(x), None)
for x in args]
)
)
def foraBrownian(x, depth):
brownianIVC = FORA.extractImplValContainer(FORA.eval("builtin.brownian"))
return makeComputationDefinitionFromIVCs(
(brownianIVC, callIVC, IVC(x), IVC(depth))
)
class CumulusTestCases(object):
def evaluateWithGateway(self, computationDefinition, timeout=240.0):
computationId = self.gateway.requestComputation(computationDefinition)
try:
return self.gateway.finalResponses.get(timeout=timeout)
finally:
self.gateway.deprioritizeComputation(computationId)
@Teardown.Teardown
def test_vecWithinVec(self):
self.desirePublisher.desireNumberOfWorkers(4, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let v =
Vector.range(10) ~~ fun(x) {
Vector.range(1000000 + x).paged
};
v = v.paged;
let res = ()
for elt in v
res = res + (elt,)
res..apply(fun(tupElt) { tupElt.sum() })
'got to the end'
}"""
)
)
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
self.assertTrue(response[1].isResult())
self.assertTrue(response[1].asResult.result.pyval == 'got to the end', response[1].asResult.result.pyval)
@Teardown.Teardown
def test_mixedVecOfNothingAndFloat(self):
self.desirePublisher.desireNumberOfWorkers(4, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let v = Vector.range(1000000, fun(x) { if (x%5 == 0) nothing else x });
sum(0,10, fun(ix) { v.apply(fun (nothing) { nothing } (elt) { elt + ix }).sum() })
}"""
)
)
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
self.assertTrue(response[1].isResult())
self.assertTrue(response[1].asResult.result.pyval == 4000036000000, response[1].asResult.result.pyval)
@Teardown.Teardown
def DISABLEDtest_repeatedCalculationOfSomethingComplex(self):
self.desirePublisher.desireNumberOfWorkers(1, blocking=True)
expr = FORA.extractImplValContainer(FORA.eval(expensiveCalculationText))
def calculateTime(count):
t0 = time.time()
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call"),
ForaNative.ImplValContainer(count)
)
)
self.assertTrue(response[1].isResult())
stats = response[2]
return (stats.timeElapsed.timeSpentInInterpreter, stats.timeElapsed.timeSpentInCompiledCode, time.time() - t0)
perSecondValues = []
for base in [500000]:
for ix in range(10):
ratio = 1.0 + ix
interp, compiled, wallClock = calculateTime(base * ratio)
perSecondValues.append( ((base * ratio) / wallClock / 1000000.0) )
print base * ratio, "->", wallClock, " seconds = ", \
"%.2f" % ((base * ratio) / wallClock / 1000000.0), "M per second."
#remove the first few runs
fastest = max(perSecondValues)
#find the point where we saturate
saturationPoint =0
while saturationPoint < len(perSecondValues) and perSecondValues[saturationPoint] < fastest / 2:
saturationPoint += 1
if saturationPoint < len(perSecondValues):
slowest = min(perSecondValues[saturationPoint:])
else:
slowest = 0.0
self.assertTrue(slowest > fastest / 2.0, "Excessive variance in run rates: %s" % perSecondValues)
@Teardown.Teardown
def test_vectorOfPagedVectorApplyWithDropping(self):
self.desirePublisher.desireNumberOfWorkers(3, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let v =
Vector.range(20).apply(fun(ix) {
Vector.range(1250000.0+ix).paged
}).paged
let lookup = fun(ix) { v[ix] }
Vector.range(100).apply(fun(ix) { sum(0, 10**8); cached(lookup(ix)) })
v
}"""
)
)
computation1 = self.gateway.requestComputation(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
try:
response = self.gateway.finalResponses.get(timeout=60.0)
except Queue.Empty:
response = None
self.assertTrue(response is not None, response)
self.gateway.deprioritizeComputation(computation1)
self.desirePublisher.desireNumberOfWorkers(2, blocking=True)
expr2 = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let res = 0
for ix in sequence(10)
res = res + Vector.range(12500000+ix).sum()
return res
}"""
)
)
computation2 = self.gateway.requestComputation(
makeComputationDefinitionFromIVCs(
expr2,
ForaNative.makeSymbol("Call")
)
)
try:
response = self.gateway.finalResponses.get(timeout=60.0)
except Queue.Empty:
response = None
self.assertTrue(response is not None)
self.assertTrue(response[1].isResult())
self.gateway.deprioritizeComputation(computation2)
@Teardown.Teardown
def test_sortALargeVectorWithFourWorkers(self):
self.desirePublisher.desireNumberOfWorkers(4, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let v = Vector.range(12500000, {_%3.1415926});
if (sorting.isSorted(sorting.sort(v))) 'sorted'
}"""
)
)
try:
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
),
timeout=120.0
)
except Queue.Empty:
response = None
if response is None:
try:
dumpFun = self.dumpSchedulerEventStreams
dumpFun()
except:
logging.warn("Wanted to dump CumulusWorkerEvents, but couldn't");
self.assertTrue(response is not None)
self.assertTrue(response[1].isResult())
self.assertTrue(response[1].asResult.result.pyval == 'sorted', response[1].asResult.result.pyval)
@Teardown.Teardown
def test_bigSumWithAdding(self):
self.desirePublisher.desireNumberOfWorkers(1, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() { if (sum(0, 10**11) > 0) 'big_enough' }"""
)
)
computationId = self.gateway.requestComputation(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
time.sleep(5)
self.desirePublisher.desireNumberOfWorkers(2, blocking=True)
try:
response = self.gateway.finalResponses.get(timeout=240.0)
except Queue.Empty:
response = None
if response is None:
try:
dumpFun = self.dumpSchedulerEventStreams
dumpFun()
except:
logging.warn("Wanted to dump CumulusWorkerEvents, but couldn't");
self.assertTrue(response is not None)
self.assertTrue(response[1].isResult())
self.assertTrue(response[1].asResult.result.pyval == 'big_enough', response[1].asResult.result.pyval)
self.gateway.deprioritizeComputation(computationId)
@Teardown.Teardown
def test_manyDuplicateCachecallsAndAdding(self):
self.desirePublisher.desireNumberOfWorkers(2, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let sumf = fun(a,b) {
if (a + 1 >= b) {
return [a + cached(sum(0,10**11))[0]]
}
let mid = (a+b)/2
return sumf(a,mid) + sumf(mid,b)
}
sumf(0,20)
}"""
)
)
computationId = self.gateway.requestComputation(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
time.sleep(5)
self.desirePublisher.desireNumberOfWorkers(4, blocking=True)
try:
response = self.gateway.finalResponses.get(timeout=240.0)
except Queue.Empty:
response = None
self.assertTrue(response is not None)
self.assertTrue(response[1].isResult())
self.gateway.deprioritizeComputation(computationId)
@Teardown.Teardown
def test_sortALargeVectorWithAdding(self):
self.desirePublisher.desireNumberOfWorkers(2, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let v = Vector.range(12500000, {_%3.1415926});
if (sorting.isSorted(sorting.sort(v))) 'sorted_2'
}"""
)
)
computationId = self.gateway.requestComputation(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
time.sleep(10)
self.desirePublisher.desireNumberOfWorkers(4, blocking=True)
try:
response = self.gateway.finalResponses.get(timeout=360.0)
except Queue.Empty:
response = None
self.gateway.deprioritizeComputation(computationId)
if response is None:
try:
dumpFun = self.dumpSchedulerEventStreams
dumpFun()
except:
logging.warn("Wanted to dump CumulusWorkerEvents, but couldn't");
self.assertTrue(response is not None)
self.assertTrue(response[1].isResult())
self.assertTrue(response[1].asResult.result.pyval == 'sorted_2', response[1].asResult.result.pyval)
@Teardown.Teardown
def test_sortALargeVectorWithRemoving(self):
self.desirePublisher.desireNumberOfWorkers(4, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let v = Vector.range(12500000, {_%3.1415926});
if (sorting.isSorted(sorting.sort(v))) 'sorted_3'
}"""
)
)
computationId = self.gateway.requestComputation(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
time.sleep(10)
self.desirePublisher.desireNumberOfWorkers(3, blocking=True)
try:
response = self.gateway.finalResponses.get(timeout=240.0)
except Queue.Empty:
response = None
self.gateway.deprioritizeComputation(computationId)
if response is None:
try:
dumpFun = self.dumpSchedulerEventStreams
dumpFun()
except:
logging.warn("Wanted to dump CumulusWorkerEvents, but couldn't");
self.assertTrue(response is not None)
self.assertTrue(response[1].isResult())
self.assertTrue(response[1].asResult.result.pyval == 'sorted_3', response[1].asResult.result.pyval)
@Teardown.Teardown
def test_vectorApplyWithAdding(self):
self.desirePublisher.desireNumberOfWorkers(2, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let v = [1,2,3,4].paged;
let res = 0
sum(0,20000000000, fun(x) { v[x%4] })
'test_vectorApplyWithAdding'
}"""
)
)
computationId = self.gateway.requestComputation(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
try:
response = self.gateway.finalResponses.get(timeout=5.0)
except Queue.Empty:
response = None
self.assertTrue(response is None, response)
self.desirePublisher.desireNumberOfWorkers(3, blocking=True)
response = self.gateway.finalResponses.get(timeout=240.0)
self.gateway.deprioritizeComputation(computationId)
self.assertTrue(response[1].isResult())
self.assertTrue(response[1].asResult.result.pyval == 'test_vectorApplyWithAdding', response[1].asResult.result.pyval)
@Teardown.Teardown
def test_expensive_brownian(self):
self.desirePublisher.desireNumberOfWorkers(2, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let brownian = fun(x,t) {
if (t == 0)
return sum(0.0, x * 10.0**7.0)
else
{
let (l,r) = cached(brownian(x - 1, t - 1), brownian(x + 1, t - 1));
return sum(0.0, x * 10.0**7.0) + l + r
}
}
brownian(0, 5)
}"""
)
)
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
self.assertTrue(response[1].isResult())
@Teardown.Teardown
def test_simple_computation(self):
self.desirePublisher.desireNumberOfWorkers(2, blocking=True)
simpleFunc = FORA.extractImplValContainer(FORA.eval("fun(){1 + 2}"))
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
simpleFunc,
ForaNative.makeSymbol("Call")
)
)
self.assertEqual(3, response[1].asResult.result.pyval)
@Teardown.Teardown
def test_sortManySmallVectors(self):
self.desirePublisher.desireNumberOfWorkers(4, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
let shouldAllBeTrue =
Vector.range(20, fun(o) {
sorting.isSorted(
sort(Vector.range(50000 + o, fun(x) { x / 10 }))
)
});
for s in shouldAllBeTrue {
if (not s)
return false
}
return true
}"""
)
)
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
self.assertTrue(response[1].isResult())
self.assertTrue(response[1].asResult.result.pyval == True, response[1].asResult.result.pyval)
@Teardown.Teardown
def test_basic_sum_1_worker(self):
self.desirePublisher.desireNumberOfWorkers(1, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
sum(0,10**10)
}"""
)
)
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
self.assertTrue(response[1].isResult())
@Teardown.Teardown
def test_basic_sum_2_workers(self):
self.desirePublisher.desireNumberOfWorkers(2, blocking=True)
expr = FORA.extractImplValContainer(
FORA.eval(
"""fun() {
sum(0,10**10)
}"""
)
)
response = self.evaluateWithGateway(
makeComputationDefinitionFromIVCs(
expr,
ForaNative.makeSymbol("Call")
)
)
self.assertTrue(response[1].isResult())
|
tutorials/stock-wallet/microservices/wallet/src/__init__.py | bhardwajRahul/minos-python | 247 | 12606880 | __author__ = ""
__email__ = ""
__version__ = "0.1.0"
from .aggregates import (
Ticker,
Wallet,
)
from .cli import (
main,
)
from .commands import (
WalletCommandService,
)
from .queries import (
WalletQueryService,
WalletQueryServiceRepository,
)
|
djangoerp/menus/utils.py | xarala221/django-erp | 345 | 12606908 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""This file is part of the django ERP project.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
__author__ = '<NAME> <<EMAIL>>'
__copyright__ = 'Copyright (c) 2013-2015, django ERP Team'
__version__ = '0.0.5'
from django.contrib.auth import get_user_model
from .models import Menu
def get_bookmarks_slug_for(instance):
"""Returns the slug for a bookmark menu valid for the given model instance.
"""
kls = instance.__class__
return "%s_%d_bookmarks" % (kls.__name__.lower(), instance.pk)
def create_bookmarks(instance):
"""Creates a new bookmarks list for the given object.
"""
from djangoerp.core.cache import LoggedInUserCache
logged_cache = LoggedInUserCache()
current_user = logged_cache.user
if isinstance(instance, get_user_model()):
logged_cache.user = instance
kls = instance.__class__
bookmarks, is_new = Menu.objects.get_or_create(slug=get_bookmarks_slug_for(instance), description="Bookmarks for %s:%s" % (kls.__name__, instance.pk))
logged_cache.user = current_user
return bookmarks, is_new
def delete_bookmarks(instance):
"""Deletes the bookmarks list of the given object.
"""
try:
bookmarks = Menu.objects.get(slug=get_bookmarks_slug_for(instance))
bookmarks.delete()
except Menu.DoesNotExist:
pass
def get_bookmarks_for(username):
"""Returns the bookmarks menu for the user with the given username.
"""
user = get_user_model().objects.get(username=username)
return Menu.objects.get(slug=get_bookmarks_slug_for(user))
def get_user_of(bookmarks_menu_slug):
"""Returns the owner of the given bookmarks list.
"""
user_pk = bookmarks_menu_slug.split('_')[1]
return get_user_model().objects.get(pk=user_pk)
def create_detail_navigation(cls):
"""Create a navigation menu for the detail view of the given model class.
This function could be used to automatically create a list of navigation
links (tabs) to be used in the given model class detail view.
"""
cls_name = cls.__name__.lower()
return Menu.objects.get_or_create(slug="%s_detail_navigation" % (cls_name), description="%s navigation" % (cls_name.capitalize()))
def create_detail_actions(cls):
"""Create an action menu for the detail view of the given model class.
This function could be used to automatically create a list of action
links to be used in the given model class detail view.
"""
cls_name = cls.__name__.lower()
return Menu.objects.get_or_create(slug="%s_detail_actions" % (cls_name), description="%s actions" % (cls_name.capitalize()))
def create_list_actions(cls):
"""Create an action menu for the list view of the given model class.
This function could be used to automatically create a list of action
links to be used in the given model class list view.
"""
cls_name = cls.__name__.lower()
return Menu.objects.get_or_create(slug="%s_list_actions" % (cls_name), description="%s list actions" % (cls_name.capitalize()))
|
spacy/lang/ja/tag_orth_map.py | snosrap/spaCy | 22,040 | 12606923 | from ...symbols import DET, PART, PRON, SPACE, X
# mapping from tag bi-gram to pos of previous token
TAG_ORTH_MAP = {
"空白": {" ": SPACE, " ": X},
"助詞-副助詞": {"たり": PART},
"連体詞": {
"あの": DET,
"かの": DET,
"この": DET,
"その": DET,
"どの": DET,
"彼の": DET,
"此の": DET,
"其の": DET,
"ある": PRON,
"こんな": PRON,
"そんな": PRON,
"どんな": PRON,
"あらゆる": PRON,
},
}
|
torchnca/__init__.py | brentyi/nca | 337 | 12606934 | <filename>torchnca/__init__.py
"""A PyTorch implementation of Neighbourhood Components Analysis.
"""
from torchnca.nca import NCA
|
examples/from-wiki/simple_rgb2gray.py | hesom/pycuda | 1,264 | 12606944 | #!python
__author__ = 'ashwin'
import pycuda.driver as drv
import pycuda.tools
import pycuda.autoinit
from pycuda.compiler import SourceModule
import numpy as np
import scipy.misc as scm
import matplotlib.pyplot as p
mod = SourceModule \
(
"""
#include<stdio.h>
#define INDEX(a, b) a*256+b
__global__ void rgb2gray(float *dest,float *r_img, float *g_img, float *b_img)
{
unsigned int idx = threadIdx.x+(blockIdx.x*(blockDim.x*blockDim.y));
unsigned int a = idx/256;
unsigned int b = idx%256;
dest[INDEX(a, b)] = (0.299*r_img[INDEX(a, b)]+0.587*g_img[INDEX(a, b)]+0.114*b_img[INDEX(a, b)]);
}
"""
)
a = scm.imread('Lenna.png').astype(np.float32)
print(a)
r_img = a[:, :, 0].reshape(65536, order='F')
g_img = a[:, :, 1].reshape(65536, order='F')
b_img = a[:, :, 2].reshape(65536, order='F')
dest=r_img
print(dest)
rgb2gray = mod.get_function("rgb2gray")
rgb2gray(drv.Out(dest), drv.In(r_img), drv.In(g_img),drv.In(b_img),block=(1024, 1, 1), grid=(64, 1, 1))
dest=np.reshape(dest,(256,256), order='F')
p.imshow(dest)
p.show()
|
fastreid/config/__init__.py | NTU-ROSE/fast-reid | 2,194 | 12606951 | <reponame>NTU-ROSE/fast-reid
# encoding: utf-8
"""
@author: l1aoxingyu
@contact: <EMAIL>
"""
from .config import CfgNode, get_cfg, global_cfg, set_global_cfg, configurable
__all__ = [
'CfgNode',
'get_cfg',
'global_cfg',
'set_global_cfg',
'configurable'
]
|
coremltools/converters/mil/frontend/tensorflow/__init__.py | freedomtan/coremltools | 2,740 | 12606988 | # Copyright (c) 2020, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
from coremltools._deps import _HAS_TF_1
# suppress TensorFlow stdout prints
import os
import logging
if os.getenv("TF_SUPPRESS_LOGS", "1") == "1":
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" # FATAL
logging.getLogger("tensorflow").setLevel(logging.FATAL)
register_tf_op = None
if _HAS_TF_1:
from .ops import * # register all
from .dialect_ops import * # register tf extension ops
from .tf_op_registry import register_tf_op
|
desktop/core/ext-py/django_celery_results-1.0.4/django_celery_results/migrations/0002_add_task_name_args_kwargs.py | maulikjs/hue | 5,079 | 12607008 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-10-26 16:06
from __future__ import absolute_import, unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('django_celery_results', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='taskresult',
name='task_args',
field=models.TextField(null=True, verbose_name='task arguments'),
),
migrations.AddField(
model_name='taskresult',
name='task_kwargs',
field=models.TextField(null=True, verbose_name='task kwargs'),
),
migrations.AddField(
model_name='taskresult',
name='task_name',
field=models.CharField(max_length=255, null=True,
verbose_name='task name'
),
),
]
|
metadata-ingestion/src/datahub_provider/_lineage_core.py | cuong-pham/datahub | 1,603 | 12607088 | <reponame>cuong-pham/datahub<gh_stars>1000+
from datetime import datetime
from typing import TYPE_CHECKING, Dict, List
import datahub.emitter.mce_builder as builder
from datahub.api.entities.dataprocess.dataprocess_instance import InstanceRunResult
from datahub.configuration.common import ConfigModel
from datahub.utilities.urns.dataset_urn import DatasetUrn
from datahub_provider.client.airflow_generator import AirflowGenerator
from datahub_provider.entities import _Entity
if TYPE_CHECKING:
from airflow import DAG
from airflow.models.baseoperator import BaseOperator
from airflow.models.dagrun import DagRun
from airflow.models.taskinstance import TaskInstance
from datahub_provider.hooks.datahub import DatahubGenericHook
def _entities_to_urn_list(iolets: List[_Entity]) -> List[DatasetUrn]:
return [DatasetUrn.create_from_string(let.urn) for let in iolets]
class DatahubBasicLineageConfig(ConfigModel):
# DataHub hook connection ID.
datahub_conn_id: str
# Cluster to associate with the pipelines and tasks. Defaults to "prod".
cluster: str = builder.DEFAULT_FLOW_CLUSTER
# If true, the owners field of the DAG will be capture as a DataHub corpuser.
capture_ownership_info: bool = True
# If true, the tags field of the DAG will be captured as DataHub tags.
capture_tags_info: bool = True
capture_executions: bool = False
def make_emitter_hook(self) -> "DatahubGenericHook":
# This is necessary to avoid issues with circular imports.
from datahub_provider.hooks.datahub import DatahubGenericHook
return DatahubGenericHook(self.datahub_conn_id)
def send_lineage_to_datahub(
config: DatahubBasicLineageConfig,
operator: "BaseOperator",
inlets: List[_Entity],
outlets: List[_Entity],
context: Dict,
) -> None:
dag: "DAG" = context["dag"]
task: "BaseOperator" = context["task"]
ti: "TaskInstance" = context["task_instance"]
hook = config.make_emitter_hook()
emitter = hook.make_emitter()
dataflow = AirflowGenerator.generate_dataflow(
cluster=config.cluster,
dag=dag,
capture_tags=config.capture_tags_info,
capture_owner=config.capture_ownership_info,
)
dataflow.emit(emitter)
operator.log.info(f"Emitted from Lineage: {dataflow}")
datajob = AirflowGenerator.generate_datajob(
cluster=config.cluster,
task=task,
dag=dag,
capture_tags=config.capture_tags_info,
capture_owner=config.capture_ownership_info,
)
datajob.inlets.extend(_entities_to_urn_list(inlets))
datajob.outlets.extend(_entities_to_urn_list(outlets))
datajob.emit(emitter)
operator.log.info(f"Emitted from Lineage: {datajob}")
if config.capture_executions:
dag_run: "DagRun" = context["dag_run"]
dpi = AirflowGenerator.run_datajob(
emitter=emitter,
cluster=config.cluster,
ti=ti,
dag=dag,
dag_run=dag_run,
datajob=datajob,
emit_templates=False,
)
operator.log.info(f"Emitted from Lineage: {dpi}")
dpi = AirflowGenerator.complete_datajob(
emitter=emitter,
cluster=config.cluster,
ti=ti,
dag=dag,
dag_run=dag_run,
datajob=datajob,
result=InstanceRunResult.SUCCESS,
end_timestamp_millis=int(datetime.utcnow().timestamp() * 1000),
)
operator.log.info(f"Emitted from Lineage: {dpi}")
|
2-Basical_Models/Logistic_Regression.py | haigh1510/TensorFlow2.0-Examples | 1,775 | 12607143 | #! /usr/bin/env python
# coding=utf-8
#================================================================
# Copyright (C) 2019 * Ltd. All rights reserved.
#
# Editor : VIM
# File name : Logistic_Regression.py
# Author : YunYang1994
# Created date: 2019-03-08 22:28:21
# Description :
#
#================================================================
import numpy as np
import tensorflow as tf
# Parameters
learning_rate = 0.001
training_epochs = 6
batch_size = 600
# Import MNIST data
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
train_dataset = (
tf.data.Dataset.from_tensor_slices((tf.reshape(x_train, [-1, 784]), y_train))
.batch(batch_size)
.shuffle(1000)
)
train_dataset = (
train_dataset.map(lambda x, y:
(tf.divide(tf.cast(x, tf.float32), 255.0),
tf.reshape(tf.one_hot(y, 10), (-1, 10))))
)
# Set model weights
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
# Construct model
model = lambda x: tf.nn.softmax(tf.matmul(x, W) + b) # Softmax
# Minimize error using cross entropy
compute_loss = lambda true, pred: tf.reduce_mean(tf.reduce_sum(tf.losses.binary_crossentropy(true, pred), axis=-1))
# caculate accuracy
compute_accuracy = lambda true, pred: tf.reduce_mean(tf.keras.metrics.categorical_accuracy(true, pred))
# Gradient Descent
optimizer = tf.optimizers.Adam(learning_rate)
for epoch in range(training_epochs):
for i, (x_, y_) in enumerate(train_dataset):
with tf.GradientTape() as tape:
pred = model(x_)
loss = compute_loss(y_, pred)
acc = compute_accuracy(y_, pred)
grads = tape.gradient(loss, [W, b])
optimizer.apply_gradients(zip(grads, [W, b]))
print("=> loss %.2f acc %.2f" %(loss.numpy(), acc.numpy()))
|
research/tests_attacks.py | majacQ/fragattacks | 1,104 | 12607160 | <gh_stars>1000+
# Copyright (c) 2020, <NAME> <<EMAIL>>
#
# This code may be distributed under the terms of the BSD license.
# See README for more details.
from fraginternals import *
class AmsduInject(Test):
"""
Inject a frame identical to the one the station would receive when performing
the A-MSDU attack by injecting an IP packet with a specific identification field.
"""
def __init__(self, ptype, malformed=False):
super().__init__([
Action(Action.Connected, Action.GetIp, enc=True),
Action(Action.Connected, Action.Inject, enc=True)]
)
self.ptype = ptype
self.malformed = malformed
def prepare(self, station):
log(STATUS, "Generating A-MSDU attack test frame", color="green")
# Generate the header and payload
header, request, self.check_fn = generate_request(station, self.ptype)
# This checks if the to-DS is set (frame towards the AP) --- XXX Utility function for this?
if header.FCfield & 1 != 0:
src = station.mac
dst = station.get_peermac()
else:
dst = station.peermac
src = station.bss
# Put the request inside an IP packet
if not self.malformed:
p = header/LLC()/SNAP()/IP(dst="192.168.1.2", src="1.2.3.4", id=34)/TCP()
# This works against linux 4.9 and above and against FreeBSD
else:
p = header/LLC()/SNAP()/IP(dst="192.168.1.2", src="3.5.1.1")/TCP()/Raw(b"A" * 748)
p = p/create_msdu_subframe(src, dst, request, last=True)
set_amsdu(p[Dot11QoS])
# Schedule transmission of frame
self.actions[0].frame = p
|
talkgenerator/util/language_util.py | korymath/talk-generator | 110 | 12607173 | <filename>talkgenerator/util/language_util.py
""" Module providing language-related operations to manipulate strings"""
import logging
import re
import string
import inflect
import nltk
logger = logging.getLogger("talkgenerator")
def check_and_download():
required_corpus_list = ["tokenizers/punkt", "taggers/averaged_perceptron_tagger"]
try:
for corpus in required_corpus_list:
_check_and_download_corpus(corpus, corpus.split("/")[1])
except Exception as e:
logging.error(e)
print_corpus_download_warning()
return False
return True
def _check_and_download_corpus(corpus_fullname, corpus_shortname):
try:
nltk.data.find(corpus_fullname)
except LookupError as le:
logging.error(le)
nltk.download(corpus_shortname)
def print_corpus_download_warning():
corpus_warning = """
Hmm...
---------------------
We had some trouble downloading the NLTK corpuses..
Try running the following from a command line. This should
download the needed packages.. but it might also tell you if
there is another issue.
$ python3 -m nltk.downloader punkt averaged_perceptron_tagger
"""
logger.warning(corpus_warning)
# Helpers
def _replace_word_one_case(sentence, word, replacement, flags=0):
return re.sub(
r"(^|\W)" + word + r"(\W|$)", r"\1" + replacement + r"\2", sentence, flags=flags
)
def replace_word(sentence, word, replacement):
lowered = _replace_word_one_case(sentence, word.lower(), replacement.lower())
upper = _replace_word_one_case(lowered, word.upper(), replacement.upper())
titled = _replace_word_one_case(upper, word.title(), replacement.title())
result = _replace_word_one_case(titled, word, replacement, re.I)
return result
def get_pos_tags(word):
""" Returns all possible POS tags for a given word according to nltk """
tags = nltk.pos_tag(nltk.word_tokenize(word))
tags_strings = [tag[1] for tag in tags]
# print(word, ":", tags_strings)
return tags_strings
# Verbs
def get_verb_index(words):
seen_adverb = False
for i in range(len(words)):
tags = get_pos_tags(words[i])
# Is verb: return
if "VB" in tags:
return i
# Is adverb: return next non adverb
if "RB" in tags:
seen_adverb = True
continue
# Something following an adverb thats not an adverb? See as verb
if seen_adverb:
return i
return 0
def apply_function_to_verb(action, func):
words = action.split(" ")
verb_index = get_verb_index(words)
first_word = func(words[verb_index])
if len(words) == 1:
return first_word
return (
" ".join(words[:verb_index])
+ " "
+ first_word
+ " "
+ " ".join(words[verb_index + 1 :])
).strip()
def to_present_participle(action):
return apply_function_to_verb(action, to_ing_form)
# From https://github.com/arsho/46-Simple-Python-Exercises-Solutions/blob/master/problem_25.py
def _make_ing_form(passed_string):
passed_string = passed_string.lower()
letter = list(string.ascii_lowercase)
vowel = ["a", "e", "i", "o", "u"]
consonant = [c for c in letter if c not in vowel]
exception = ["be", "see", "flee", "knee", "lie"]
if passed_string.endswith("ie"):
passed_string = passed_string[:-2]
return passed_string + "ying"
elif passed_string.endswith("e"):
if passed_string in exception:
return passed_string + "ing"
else:
passed_string = passed_string[:-1]
return passed_string + "ing"
elif passed_string.endswith("y") or passed_string.endswith("w"):
return passed_string + "ing"
elif (
len(passed_string) >= 3
and passed_string[-1] in consonant
and passed_string[-2] in vowel
and passed_string[-3] in consonant
):
passed_string += passed_string[-1]
return passed_string + "ing"
else:
return passed_string + "ing"
def to_ing_form(passed_string):
result = _make_ing_form(passed_string)
if passed_string.islower():
return result.lower()
if passed_string.isupper():
return result.upper()
if passed_string.istitle():
return result.title()
return result
inflect_engine = inflect.engine()
def is_singular(word):
return inflect_engine.singular_noun(word) is False
def is_plural(word):
return bool(inflect_engine.singular_noun(word))
def to_plural(word):
if is_singular(word):
if word.startswith("a "):
word = word[2:]
return inflect_engine.plural(word)
return word
def to_singular(word):
if is_plural(word):
return inflect_engine.singular_noun(word)
return word
def add_article(word):
# TODO: Maybe more checks, some u's cause "an", or some big letters in case it's an abbreviation
word_lower = word.lower()
article = "a"
if (
word_lower.startswith("a")
or word_lower.startswith("e")
or word_lower.startswith("i")
or word_lower.startswith("o")
):
article = "an"
return article + " " + word
# Pronouns
def second_to_first_pronouns(sentence):
sentence = replace_word(sentence, "yours", "mine")
sentence = replace_word(sentence, "your", "my")
sentence = replace_word(sentence, "you", "me")
return sentence
# POS tag checkers
# TODO: These don't work well, but might be useful features in our text generation language
def is_noun(word):
return "NN" in get_pos_tags(word)
def is_verb(word):
return "VB" in get_pos_tags(word)
# Special operators
def get_last_noun_and_article(sentence):
tokens = nltk.word_tokenize(sentence)
tags = nltk.pos_tag(tokens)
noun = None
for tag in reversed(tags):
if "NN" in tag[1]:
if noun:
noun = (tag[0] + " " + noun).strip()
else:
noun = tag[0]
# If encountering an article while there is a noun found
elif bool(noun):
if "DT" in tag[1] or "PRP$" in tag[1]:
return tag[0] + " " + noun
return noun
return None
def replace_non_alphabetical_characters(text):
return re.sub(r"[^A-Za-z\s\b -]+", "", text)
def is_vowel(character):
return character in ["a", "e", "i", "o,", "u"]
def is_consonant(character):
return not is_vowel(character)
|
src/features/migrations/0017_auto_20200607_1005.py | augustuswm/flagsmith-api | 1,259 | 12607196 | # Generated by Django 2.2.12 on 2020-06-07 10:05
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('environments', '0012_auto_20200504_1322'),
('segments', '0007_auto_20190906_1416'),
('features', '0016_auto_20190916_1717'),
]
operations = [
# first, add the field, allowing null values
migrations.AddField(
model_name='featuresegment',
name='environment',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='feature_segments', to='environments.Environment'),
),
migrations.AlterUniqueTogether(
name='featuresegment',
unique_together={('feature', 'environment', 'segment')},
),
]
|
buildroot/support/testing/tests/package/sample_python_rpi_gpio.py | superm1/operating-system | 349 | 12607210 | try:
import RPi.GPIO # noqa
except RuntimeError as e:
assert(str(e) == 'This module can only be run on a Raspberry Pi!')
else:
raise RuntimeError('Import succeeded when it should not have!')
|
cosrlib/sources/metadata.py | commonsearch/cosr-back | 141 | 12607235 | <gh_stars>100-1000
from __future__ import absolute_import, division, print_function, unicode_literals
from cosrlib.sources import Source
class MetadataSource(Source):
""" Reads an intermediate dump of document metadata generated by
--plugin plugins.dump.DocumentMetadata
"""
already_parsed = True
def get_documents(self, sqlc):
fileformat = self.args.get("format") or "parquet"
df = getattr(sqlc.read, fileformat)(self.args["path"])
if int(self.args.get("maxdocs") or 0) > 0:
df = df.limit(int(self.args["maxdocs"]))
if self.args.get("fields"):
df = df.select(self.args["fields"].split("+"))
return df
|
test/dml_decision_tree/decision_tree_discrete.py | Edelweiss35/deep-machine-learning | 708 | 12607245 | from __future__ import division
import numpy as np
import scipy as sp
from dml.DT import DTC
X=np.array([
[0,0,0,0,8],
[0,0,0,1,3.5],
[0,1,0,1,3.5],
[0,1,1,0,3.5],
[0,0,0,0,3.5],
[1,0,0,0,3.5],
[1,0,0,1,3.5],
[1,1,1,1,2],
[1,0,1,2,3.5],
[1,0,1,2,3.5],
[2,0,1,2,3.5],
[2,0,1,1,3.5],
[2,1,0,1,3.5],
[2,1,0,2,3.5],
[2,0,0,0,10],
]).transpose()
y=np.array([
[1],
[-1],
[1],
[1],
[-1],
[-1],
[-1],
[1],
[1],
[1],
[1],
[1],
[1],
[1],
[1],
]).transpose()
prop=np.zeros((5,1))
prop[4]=1
a=DTC(X,y,prop)
a.train()
print a.pred(np.array([[0,0,0,0,3.0],[2,1,0,1,2]]).transpose())
|
poco/utils/measurement.py | HBoPRC/Poco | 1,444 | 12607259 | # coding=utf-8
def point_inside(p, bounds):
return bounds[3] <= p[0] <= bounds[1] and bounds[0] <= p[1] <= bounds[2]
|
python/interpret_community/widget/__init__.py | Nanthini10/interpret-community | 338 | 12607262 | <gh_stars>100-1000
# ---------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ---------------------------------------------------------
"""Module for Explanation Dashboard widget."""
from .explanation_dashboard import ExplanationDashboard
__all__ = ['ExplanationDashboard']
|
gltbx/glu.py | dperl-sol/cctbx_project | 155 | 12607273 | <reponame>dperl-sol/cctbx_project
from __future__ import absolute_import, division, print_function
import boost_adaptbx.boost.python as bp
ext = bp.import_ext("gltbx_glu_ext")
from gltbx_glu_ext import *
|
HSequences_bench/tools/opencv_matcher.py | bankbiz/Key.Net | 162 | 12607289 | import cv2
import numpy as np
class OpencvBruteForceMatcher(object):
name = 'opencv_brute_force_matcher'
distances = {}
distances['l2'] = cv2.NORM_L2
distances['hamming'] = cv2.NORM_HAMMING
def __init__(self, distance='l2'):
self._matcher = cv2.BFMatcher(self.distances[distance])
def match(self, descs1, descs2):
"""Compute brute force matches between two sets of descriptors.
"""
assert isinstance(descs1, np.ndarray), type(descs1)
assert isinstance(descs2, np.ndarray), type(descs2)
assert len(descs1.shape) == 2, descs1.shape
assert len(descs2.shape) == 2, descs2.shape
matches = self._matcher.match(descs1, descs2)
return matches
def match_putative(self, descs1, descs2, knn=2, threshold_ratio=0.7):
"""Compute putatives matches betweem two sets of descriptors.
"""
assert isinstance(descs1, np.ndarray), type(descs1)
assert isinstance(descs2, np.ndarray), type(descs2)
assert len(descs1.shape) == 2, descs1.shape
assert len(descs2.shape) == 2, descs2.shape
matches = self._matcher.knnMatch(descs1, descs2, k=knn)
# apply Lowe's ratio test
good = []
for m, n in matches:
if m.distance < threshold_ratio * n.distance:
good.append(m)
return good
def convert_opencv_matches_to_numpy(self, matches):
"""Returns a np.ndarray array with points indices correspondences
with the shape of Nx2 which each N feature is a vector containing
the keypoints id [id_ref, id_dst].
"""
assert isinstance(matches, list), type(matches)
correspondences = []
for match in matches:
assert isinstance(match, cv2.DMatch), type(match)
correspondences.append([match.queryIdx, match.trainIdx])
return np.asarray(correspondences) |
google_problems/problem_47.py | loftwah/Daily-Coding-Problem | 129 | 12607314 | """This problem was asked by Google.
You're given a string consisting solely of (, ), and *. * can represent either a (, ), or an empty string.
Determine whether the parentheses are balanced.
For example, (()* and (*) are balanced. )*( is not balanced.
""" |
tests/test_transforms/test_encoders/test_mean_segment_encoder_transform.py | Pacman1984/etna | 326 | 12607318 | import numpy as np
import pandas as pd
import pytest
from etna.datasets import TSDataset
from etna.metrics import R2
from etna.models import LinearMultiSegmentModel
from etna.transforms import MeanSegmentEncoderTransform
@pytest.mark.parametrize("expected_global_means", ([[3, 30]]))
def test_mean_segment_encoder_fit(simple_df, expected_global_means):
encoder = MeanSegmentEncoderTransform()
encoder.fit(simple_df)
assert (encoder.global_means == expected_global_means).all()
def test_mean_segment_encoder_transform(simple_df, transformed_simple_df):
encoder = MeanSegmentEncoderTransform()
transformed_df = encoder.fit_transform(simple_df)
pd.testing.assert_frame_equal(transformed_df, transformed_simple_df)
@pytest.fixture
def almost_constant_ts(random_seed) -> TSDataset:
df_1 = pd.DataFrame.from_dict({"timestamp": pd.date_range("2021-06-01", "2021-07-01", freq="D")})
df_2 = pd.DataFrame.from_dict({"timestamp": pd.date_range("2021-06-01", "2021-07-01", freq="D")})
df_1["segment"] = "Moscow"
df_1["target"] = 1 + np.random.normal(0, 0.1, size=len(df_1))
df_2["segment"] = "Omsk"
df_2["target"] = 10 + np.random.normal(0, 0.1, size=len(df_1))
classic_df = pd.concat([df_1, df_2], ignore_index=True)
ts = TSDataset(df=TSDataset.to_dataset(classic_df), freq="D")
return ts
def test_mean_segment_encoder_forecast(almost_constant_ts):
"""Test that MeanSegmentEncoderTransform works correctly in forecast pipeline
and helps to correctly forecast almost constant series."""
horizon = 5
model = LinearMultiSegmentModel()
encoder = MeanSegmentEncoderTransform()
train, test = almost_constant_ts.train_test_split(test_size=horizon)
train.fit_transform([encoder])
model.fit(train)
future = train.make_future(horizon)
pred_mean_segment_encoding = model.forecast(future)
metric = R2(mode="macro")
# R2=0 => model predicts the optimal constant
assert np.allclose(metric(pred_mean_segment_encoding, test), 0)
def test_fit_transform_with_nans(ts_diff_endings):
encoder = MeanSegmentEncoderTransform()
ts_diff_endings.fit_transform([encoder])
|
alipay/aop/api/domain/WorldTicketType.py | antopen/alipay-sdk-python-all | 213 | 12607337 | <gh_stars>100-1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class WorldTicketType(object):
def __init__(self):
self._ticket_type_code = None
self._ticket_type_desc = None
self._ticket_type_name = None
@property
def ticket_type_code(self):
return self._ticket_type_code
@ticket_type_code.setter
def ticket_type_code(self, value):
self._ticket_type_code = value
@property
def ticket_type_desc(self):
return self._ticket_type_desc
@ticket_type_desc.setter
def ticket_type_desc(self, value):
self._ticket_type_desc = value
@property
def ticket_type_name(self):
return self._ticket_type_name
@ticket_type_name.setter
def ticket_type_name(self, value):
self._ticket_type_name = value
def to_alipay_dict(self):
params = dict()
if self.ticket_type_code:
if hasattr(self.ticket_type_code, 'to_alipay_dict'):
params['ticket_type_code'] = self.ticket_type_code.to_alipay_dict()
else:
params['ticket_type_code'] = self.ticket_type_code
if self.ticket_type_desc:
if hasattr(self.ticket_type_desc, 'to_alipay_dict'):
params['ticket_type_desc'] = self.ticket_type_desc.to_alipay_dict()
else:
params['ticket_type_desc'] = self.ticket_type_desc
if self.ticket_type_name:
if hasattr(self.ticket_type_name, 'to_alipay_dict'):
params['ticket_type_name'] = self.ticket_type_name.to_alipay_dict()
else:
params['ticket_type_name'] = self.ticket_type_name
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = WorldTicketType()
if 'ticket_type_code' in d:
o.ticket_type_code = d['ticket_type_code']
if 'ticket_type_desc' in d:
o.ticket_type_desc = d['ticket_type_desc']
if 'ticket_type_name' in d:
o.ticket_type_name = d['ticket_type_name']
return o
|
extensions/timers.py | FeliciaXmL/ipython_extensions | 333 | 12607345 | <reponame>FeliciaXmL/ipython_extensions
# coding: utf-8
"""Extension for simple stack-based tic/toc timers
Each %tic starts a timer,
each %toc prints the time since the last tic
`%tic label` results in 'label: ' being printed at the corresponding %toc.
Usage:
In [6]: %tic outer
...: for i in range(4):
...: %tic
...: time.sleep(2 * random.random())
...: %toc
...: %toc
459 ms
250 ms
509 ms
1.79 s
outer: 3.01 s
"""
import sys
import time
from IPython.core.magic import magics_class, line_magic, cell_magic, Magics
from IPython.core.magics.execution import _format_time
@magics_class
class TimerMagics(Magics):
timers = None
tics = None
def __init__(self, *args, **kwargs):
super(TimerMagics, self).__init__(*args, **kwargs)
self.timers = {}
self.tics = []
self.labels = []
@line_magic
def tic(self, line):
"""Start a timer
Usage:
%tic [label]
"""
label = line.strip() or None
now = self.time()
if label in self.timers:
# %tic on an existing name prints the time,
# but does not affect the stack
self.print_time(now - self.timers[label], label)
return
if label:
self.timers[label] = now
self.tics.insert(0, self.time())
self.labels.insert(0, label)
@line_magic
def toc(self, line):
"""Stop and print the timer started by the last call to %tic
Usage:
%toc
"""
now = self.time()
tic = self.tics.pop(0)
label = self.labels.pop(0)
self.timers.pop(label, None)
self.print_time(now - tic, label)
def print_time(self, dt, label):
ts = _format_time(dt)
msg = "%8s" % ts
if label:
msg = "%s: %s" % (label, msg)
print ('%s%s' % (' ' * len(self.tics), msg))
@staticmethod
def time():
"""time.clock seems preferable on Windows"""
if sys.platform.startswith('win'):
return time.clock()
else:
return time.time()
def load_ipython_extension(ip):
"""Load the extension in IPython."""
ip.register_magics(TimerMagics)
|
tests/lib/test_iceil.py | bogdanvuk/pygears | 120 | 12607369 | <gh_stars>100-1000
import math
import pytest
from pygears.lib import iceil
from pygears.lib.verif import directed
from pygears.sim import sim
from pygears.lib.verif import drv
from pygears.typing import Uint
@pytest.mark.parametrize('div', [1, 2, 4, 8])
def test_directed(sim_cls, div):
seq = list(range(256 - div))
ref = [math.ceil(x / div) for x in seq]
directed(
drv(t=Uint[8], seq=seq), f=iceil(sim_cls=sim_cls, div=div), ref=ref)
sim()
|
tests/test_aws.py | ukwa/mrjob | 1,538 | 12607377 | # -*- coding: utf-8 -*-
# Copyright 2016-2018 Yelp
# Copyright 2019 Yelp and Contributors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import socket
from ssl import SSLError
from botocore.exceptions import ClientError
from mrjob.aws import _AWS_MAX_TRIES
from mrjob.aws import _boto3_paginate
from mrjob.aws import _wrap_aws_client
from mrjob.aws import EC2_INSTANCE_TYPE_TO_COMPUTE_UNITS
from mrjob.aws import EC2_INSTANCE_TYPE_TO_MEMORY
from tests.mock_boto3 import MockBoto3TestCase
from tests.py2 import patch
from tests.sandbox import BasicTestCase
class EC2InstanceTypeTestCase(BasicTestCase):
def test_ec2_instance_dicts_match(self):
self.assertEqual(
set(EC2_INSTANCE_TYPE_TO_COMPUTE_UNITS),
set(EC2_INSTANCE_TYPE_TO_MEMORY))
class WrapAWSClientTestCase(MockBoto3TestCase):
"""Test that _wrap_aws_client() works as expected.
We're going to wrap S3Client.list_buckets(), but it should work the
same on any method on any AWS client/resource."""
def setUp(self):
super(WrapAWSClientTestCase, self).setUp()
# don't actually wait between retries
self.sleep = self.start(patch('time.sleep'))
self.log = self.start(patch('mrjob.retry.log'))
self.list_buckets = self.start(patch(
'tests.mock_boto3.s3.MockS3Client.list_buckets',
side_effect=[dict(Buckets=[])]))
self.client = self.client('s3')
self.wrapped_client = _wrap_aws_client(self.client)
def add_transient_error(self, ex):
self.list_buckets.side_effect = (
[ex] + list(self.list_buckets.side_effect))
def test_unwrapped_no_errors(self):
# just a sanity check of our mocks
self.assertEqual(self.client.list_buckets(), dict(Buckets=[]))
def test_unwrapped_with_errors(self):
self.add_transient_error(socket.error(104, 'Connection reset by peer'))
self.assertRaises(socket.error, self.client.list_buckets)
def test_wrapped_no_errors(self):
self.assertEqual(self.wrapped_client.list_buckets(), dict(Buckets=[]))
self.assertFalse(self.log.info.called)
def assert_retry(self, ex):
self.add_transient_error(ex)
self.assertEqual(self.wrapped_client.list_buckets(), dict(Buckets=[]))
self.assertTrue(self.log.info.called)
def assert_no_retry(self, ex):
self.add_transient_error(ex)
self.assertRaises(ex.__class__, self.wrapped_client.list_buckets)
self.assertFalse(self.log.info.called)
def test_socket_connection_reset_by_peer(self):
self.assert_retry(socket.error(104, 'Connection reset by peer'))
def test_socket_connection_timed_out(self):
self.assert_retry(socket.error(110, 'Connection timed out'))
def test_other_socket_errors(self):
self.assert_no_retry(socket.error(111, 'Connection refused'))
def test_ssl_read_op_timed_out_error(self):
self.assert_retry(SSLError('The read operation timed out'))
def test_ssl_write_op_timed_out_error(self):
self.assert_retry(SSLError('The write operation timed out'))
def test_other_ssl_error(self):
self.assert_no_retry(SSLError('certificate verify failed'))
def test_throttling_error(self):
self.assert_retry(ClientError(
dict(
Error=dict(
Code='ThrottlingError'
)
),
'ListBuckets'))
def test_aws_505_error(self):
self.assert_retry(ClientError(
dict(
ResponseMetadata=dict(
HTTPStatusCode=505
)
),
'ListBuckets'))
def test_other_client_error(self):
self.assert_no_retry(ClientError(
dict(
Error=dict(
Code='AccessDenied',
Message='Access Denied',
),
ResponseMetadata=dict(
HTTPStatusCode=403
),
),
'GetBucketLocation'))
def test_other_error(self):
self.assert_no_retry(ValueError())
def test_two_retriable_errors(self):
self.add_transient_error(socket.error(110, 'Connection timed out'))
self.add_transient_error(SSLError('The read operation timed out'))
self.assertEqual(self.wrapped_client.list_buckets(), dict(Buckets=[]))
self.assertTrue(self.log.info.called)
def test_retriable_and_no_retriable_error(self):
# errors are prepended to side effects
# we want socket.error to happen first
self.add_transient_error(ValueError())
self.add_transient_error(socket.error(110, 'Connection timed out'))
self.assertRaises(ValueError, self.wrapped_client.list_buckets)
self.assertTrue(self.log.info.called)
def test_eventually_give_up(self):
for _ in range(_AWS_MAX_TRIES + 1):
self.add_transient_error(socket.error(110, 'Connection timed out'))
self.assertRaises(socket.error, self.wrapped_client.list_buckets)
self.assertTrue(self.log.info.called)
def test_min_backoff(self):
self.wrapped_client = _wrap_aws_client(self.client, min_backoff=1000)
self.add_transient_error(socket.error(110, 'Connection timed out'))
self.assertEqual(self.wrapped_client.list_buckets(), dict(Buckets=[]))
self.sleep.assert_called_with(1000)
self.assertTrue(self.log.info.called)
def test_retry_during_pagination(self):
# regression test for #2005
bucket_names = ['walrus%02d' % i for i in range(100)]
# must set side_effect before adding error
self.list_buckets.side_effect = [dict(Buckets=bucket_names)]
self.add_transient_error(socket.error(110, 'Connection timed out'))
# our mock pagination somewhat messes with this test; rather than
# getting called once per page of bucket names, list_buckets() only
# gets called twice, once to fail with a transient error, and once to
# get the full list of buckets, which mock pagination then breaks
# into "pages". This still tests the important thing though, which is
# that we can retry at all within pagination
self.assertEqual(list(_boto3_paginate(
'Buckets', self.wrapped_client, 'list_buckets')),
bucket_names)
|
corehq/ex-submodules/soil/tests/test_get_task_status.py | dimagilg/commcare-hq | 471 | 12607393 | import datetime
from django.test import SimpleTestCase, override_settings
from soil.progress import get_task_status, TaskStatus, TaskProgress, STATES
@override_settings(CELERY_TASK_ALWAYS_EAGER=False)
class GetTaskStatusTest(SimpleTestCase):
def test_missing(self):
self.assertEqual(get_task_status(self.MockTask(
task_meta={
'date_done': None,
'result': None,
'status': 'PENDING',
'task_args': None,
'task_id': 'obviously fake!',
'task_kwargs': None,
'task_name': None,
'traceback': None
}
)), TaskStatus(
result=None,
error=None,
state=STATES.missing,
progress=TaskProgress(
current=None,
total=None,
percent=None,
error=False,
error_message=''
)
))
def test_not_missing(self):
self.assertEqual(get_task_status(self.MockTask(
task_meta={
'children': [],
'date_done': datetime.datetime(2020, 4, 7, 14, 37, 1, 926615),
'result': {'current': 17076, 'total': 10565489},
'status': 'PROGRESS',
'task_args': None,
'task_id': '2243626c-f725-442e-b257-b018a0860d1b',
'task_kwargs': None,
'task_name': None,
'traceback': None
}
)), TaskStatus(
result=None,
error=None,
state=STATES.started,
progress=TaskProgress(
current=17076,
total=10565489,
percent=100 * 17076 // 10565489,
error=False,
error_message=''
)
))
class MockTask(object):
def __init__(self, task_meta, failed=False, successful=False):
self.__task_meta = task_meta
self.__failed = failed
self.__successful = successful
def _get_task_meta(self):
return self.__task_meta
def failed(self):
return self.__failed
def successful(self):
return self.__successful
@property
def status(self):
return self.__task_meta.get('status')
state = status
@property
def result(self):
return self.__task_meta.get('result')
info = result
|
3]. Competitive Programming/09]. HackerRank/2]. Tutorials/1]. 30 Days of Code/Python/Day_01.py | MLinesCode/The-Complete-FAANG-Preparation | 6,969 | 12607408 | # 2nd Solution
i = 4
d = 4.0
s = 'HackerRank '
a = int(input())
b = float(input())
c = input()
print(i+a)
print(d+b)
print(s+c) |
recipes/Python/577893_Securely_processing_Twilio_requests/recipe-577893.py | tdiprima/code | 2,023 | 12607467 | <reponame>tdiprima/code
# A decorator that lets you require HTTP basic authentication from visitors.
# <NAME> <<EMAIL>> 2011
# Use however makes you happy, but if it breaks, you get to keep both pieces.
# Post with explanation, commentary, etc.:
# http://kelleyk.com/post/7362319243/easy-basic-http-authentication-with-tornado
import base64, logging
import tornado.web
import twilio # From https://github.com/twilio/twilio-python
def require_basic_auth(handler_class):
def wrap_execute(handler_execute):
def require_basic_auth(handler, kwargs):
auth_header = handler.request.headers.get('Authorization')
if auth_header is None or not auth_header.startswith('Basic '):
handler.set_status(401)
handler.set_header('WWW-Authenticate', 'Basic realm=Restricted')
handler._transforms = []
handler.finish()
return False
auth_decoded = base64.decodestring(auth_header[6:])
kwargs['basicauth_user'], kwargs['basicauth_pass'] = auth_decoded.split(':', 2)
return True
def _execute(self, transforms, *args, **kwargs):
if not require_basic_auth(self, kwargs):
return False
return handler_execute(self, transforms, *args, **kwargs)
return _execute
handler_class._execute = wrap_execute(handler_class._execute)
return handler_class
twilio_account_sid = 'INSERT YOUR ACCOUNT ID HERE'
twilio_account_token = 'INSERT YOUR ACCOUNT TOKEN HERE'
@require_basic_auth
class TwilioRequestHandler(tornado.web.RequestHandler):
def post(self, basicauth_user, basicauth_pass):
"""
Receive a Twilio request, return a TwiML response
"""
# We check in two ways that it's really Twilio POSTing to this URL:
# 1. Check that Twilio is sending the username and password we specified
# for it at https://www.twilio.com/user/account/phone-numbers/incoming
# 2. Check that Twilio has signed its request with our secret account token
username = 'CONFIGURE USERNAME AT TWILIO.COM AND ENTER IT HERE'
password = 'CONFIGURE PASSWORD AT TWILIO.COM AND ENTER IT HERE'
if basicauth_user != username or basicauth_pass != password:
raise tornado.web.HTTPError(401, "Invalid username and password for HTTP basic authentication")
# Construct the URL to this handler.
# self.request.full_url() doesn't work, because Twilio sort of has a bug:
# We tell it to POST to our URL with HTTP Authentication like this:
# http://username:[email protected]/api/twilio_request_handler
# ... and Twilio uses *that* URL, with username and password included, as
# part of its signature.
# Also, if we're proxied by Nginx, then Nginx handles the HTTPS protocol and
# connects to Tornado over HTTP
protocol = 'https' if self.request.headers.get('X-Twilio-Ssl') == 'Enabled' else self.request.protocol
url = '%s://%s:%s@%s%s' % (
protocol, username, password, self.request.host, self.request.path,
)
if not twilio.Utils(twilio_account_sid, twilio_account_token).validateRequest(
url,
# arguments has lists like { 'key': [ 'value', ... ] }, so flatten them
{
k: self.request.arguments[k][0]
for k in self.request.arguments
},
self.request.headers.get('X-Twilio-Signature'),
):
logging.error("Invalid Twilio signature to %s: %s" % (
self.request.full_url(), self.request
))
raise tornado.web.HTTPError(401, "Invalid Twilio signature")
# Do your actual processing of Twilio's POST here, using self.get_argument()
|
lab-experiment/helper_functions/visual_degrees.py | robtu328/texture-vs-shape | 687 | 12607510 | #!/usr/bin/env python
#script to calculate visual degrees of experiment.
#copied from: http://osdoc.cogsci.nl/miscellaneous/visual-angle/
from math import atan2, degrees
h = 30.2 # Monitor height in cm
d = 100 # Distance between monitor and participant in cm
r = 1200 # Vertical resolution of the monitor
size_in_px = 256 # The stimulus size in pixels
# Calculate the number of degrees that correspond to a single pixel. This will
# generally be a very small value, something like 0.03.
deg_per_px = degrees(atan2(.5*h, d)) / (.5*r)
print '%s degrees correspond to a single pixel' % deg_per_px
# Calculate the size of the stimulus in degrees
size_in_deg = size_in_px * deg_per_px
print 'The size of the stimulus is %s pixels and %s visual degrees' \
% (size_in_px, size_in_deg)
|
papers/NeurIPS20-SVT/exp2_align_var.py | samellem/autodp | 158 | 12607516 | import numpy as np
import math
import scipy
from autodp import rdp_bank, dp_bank, fdp_bank, utils
from autodp.mechanism_zoo import LaplaceMechanism, LaplaceSVT_Mechanism,StageWiseMechanism
from autodp.transformer_zoo import Composition
import matplotlib.pyplot as plt
from scipy.stats import norm, laplace
from scipy.special import comb
import matplotlib.font_manager as fm
from autodp.mechanism_zoo import ExactGaussianMechanism, PureDP_Mechanism,SubsampleGaussianMechanism, GaussianMechanism, ComposedGaussianMechanism,GaussianSVT_Mechanism, NoisyScreenMechanism
from autodp.transformer_zoo import Composition, AmplificationBySampling
"""
This experiment corresponding to exp 2 in NeurIPS-20 (Figure 2 (a))
We evaluate SVT variants with the same variance of noise by comparing the composed privacy loss for finishing a fixed length sequence of queries.
rho is from Lap(lambda) -> eps_rho = 1/lambda
nu is from Lap(2lambda) -> eps_nu = 1/lambda
eps = (c+1)/lambda, lambda = (c+1)/eps
To align variance between Gaussian-bassed and Laplace-based approaches, we set sigma_1 = sqrt(2) * lambda_rho
"""
delta = 1e-6
lambda_rho = 120
lambda_nu = 240
sigma_1 = lambda_rho*np.sqrt(2)
sigma_2 = 2*sigma_1
eps_1 = 1.0 / lambda_rho
n = 100000 #the length of the fixed query
margin = 1000
def exp_2a():
eps_a = [] #standard SVT
eps_e = [] #Laplace-SVT (via RDP)
eps_g = [] #Gaussian SVT c>1
eps_g_c = [] #c=1 for Gaussian SVT
eps_i = []
eps_kov = [] #generalized SVT
eps_noisy = []
k_list = [int(1.4**i) for i in range(int(math.floor(math.log(n,1.4)))+1)]
print(len(k_list))
query = np.zeros(n)
rho = np.random.normal(scale=sigma_1)
lap_rho = np.random.laplace(loc=0.0, scale=lambda_rho)
"""
compute eps for noisy screening
p = Prob[ nu > Margin]
q = Prob[ nu - 1 > margin]
count_gau counts #tops in Gaussian-SVT
count_lap counts #tops in Laplace-SVT
"""
count_gau = 0
count_lap = 0
# the following is for data-dependent screening in CVPR-20
p = scipy.stats.norm.logsf(margin, scale=sigma_2)
q = scipy.stats.norm.logsf(margin + 1, scale=sigma_2)
params = {}
params['logp'] = p
params['logq'] = q
per_screen_mech = NoisyScreenMechanism(params, name='NoisyScreen')
per_gaussian_mech = ExactGaussianMechanism(sigma_2,name='GM1')
index = []
compose = Composition()
for idx, qu in enumerate(query):
nu = np.random.normal(scale=sigma_2)
lap_nu = np.random.laplace(loc=0.0, scale=lambda_nu)
if nu >= rho + margin:
count_gau += 1
if lap_nu >= lap_rho + margin:
count_lap += 1
count_gau = max(count_gau, 1)
count_lap = max(count_lap, 1)
if idx in k_list:
index.append(idx)
print('number of queries passing threshold', count_gau)
#eps_a records the standard SVT
eps_a.append(eps_1 * count_lap + eps_1)
# compose data-dependent screening
screen_mech = compose([per_screen_mech], [idx])
gaussian_mech = compose([per_gaussian_mech], [idx])
# standard SVT with RDP calculation
param_lap_svt = {}
param_lap_svt['b'] = lambda_rho
param_lap_svt['k'] = idx
param_lap_svt['c'] = count_lap
lapsvtrdp_mech = LaplaceSVT_Mechanism(param_lap_svt)
eps_e.append(lapsvtrdp_mech.get_approxDP(delta))
# stage-wise generalized SVT, k is the maximum length of each chunk
k = int(idx / np.sqrt(count_gau))
generalized_mech = StageWiseMechanism({'sigma':sigma_1,'k':k, 'c':count_gau})
eps_kov.append(generalized_mech.get_approxDP(delta))
# Gaussian-SVT c>1 with RDP, k is the total length before algorithm stops
gaussianSVT_c = GaussianSVT_Mechanism({'sigma':sigma_1,'k':idx, 'c':count_gau}, rdp_c_1=False)
eps_g.append(gaussianSVT_c.get_approxDP(delta))
#Gaussian-SVT with c=1, we use average_k as the approximate maximum length of each chunk, margin is used in Proposition 10
average_k = int(idx / max(count_gau, 1))
params_SVT = {}
params_SVT['k'] = average_k
params_SVT['sigma'] = sigma_1
params_SVT['margin'] = margin
per_gaussianSVT_mech = GaussianSVT_Mechanism(params_SVT)
gaussianSVT_mech = compose([per_gaussianSVT_mech],[max(count_gau, 1)])
eps_g_c.append(gaussianSVT_mech.get_approxDP(delta))
eps_i.append(gaussian_mech.get_approxDP(delta)) # Gaussian Mechanism
eps_noisy.append(screen_mech.get_approxDP(delta))
import matplotlib
import matplotlib.pyplot as plt
font = {'family': 'times',
'weight': 'bold',
'size': 18}
props = fm.FontProperties(family='Gill Sans', fname='/Library/Fonts/GillSans.ttc')
f, ax = plt.subplots()
plt.figure(num=0, figsize=(12, 8), dpi=80, facecolor='w', edgecolor='k')
plt.loglog(index, eps_a, '-r', linewidth=2)
plt.loglog(index, eps_e, '--g^', linewidth=2)
plt.loglog(index, eps_g, '-c^', linewidth=2)
plt.loglog(index, eps_g_c, '-bs', linewidth=2)
plt.loglog(index, eps_i, '--k', linewidth=2)
plt.loglog(index, eps_noisy, color='brown', linewidth=2)
plt.loglog(index, eps_kov, color='hotpink', linewidth=2)
plt.legend(
['Laplace-SVT (Pure-DP from Lyu et al., 2017)', 'Laplace-SVT (via RDP)', 'Gaussian-SVT c>1 (RDP by Theorem 11)',
'Gaussian-SVT c=1 (RDP by Theorem 8)', 'Gaussian Mechanism', 'Noisy Screening (data-dependent RDP)',
'Stage-wise generalized SVT'], loc='best', fontsize=17)
plt.grid(True)
plt.xticks(fontsize=20)
plt.yticks(fontsize=20)
plt.xlabel(r'Iterations', fontsize=20)
plt.ylabel(r'$\epsilon$', fontsize=20)
ax.set_title('Title', fontproperties=props)
plt.savefig('exp2a.pdf', bbox_inches='tight')
exp_2a() |
utils/adapthresh.py | yyu1/SurfaceNet | 117 | 12607521 | import numpy as np
import copy
import os
import sys
import time
import itertools
import sparseCubes
import denoising
def access_partial_Occupancy_ijk(Occ_ijk, shift, D_cube):
"""
access 1/2, 1/4, 1/8 of the cube's Occupancy_ijk,
at the same time, translate the origin to the shifted array.
For example: ijk [1,2,4] of cube with shape1 = (6,6,6)
Its partial cube with shift = (0,-1,1) has shape2 = (6,3,3)
Its shifted ijk --> [1, 2, 4 - 3] --> [1,2,1] (within boarder of shape2)
Note:
This method will use the reference of Occ_ijk, and CHANG it.
-------------
inputs:
Occ_ijk: np.uint (N_voxel, 2/3/...)
shift: np/tuple/list (2/3/..., ), specify which part of the array will be selected
(1,-1,0): np.s_[D_mid:, :D_mid, :]
D_cube: Occ_ijk's upper bound
-------------
outputs:
Occ_partial: np.uint (n_voxel, 2/3/...)
-------------
example:
>>> Occ_ijk = np.array([[1,5,2], [5,2,0], [0,1,5], [2,1,1], [4,5,5]])
>>> gt = Occ_ijk[2:3]-np.array([[0,0,3]])
>>> resul = access_partial_Occupancy_ijk(Occ_ijk, (-1,0,1), D_cube=6)
>>> np.allclose(gt, resul) and (gt.shape == resul.shape) # because allclose(array, empty)=True !
True
>>> np.array_equal(Occ_ijk[1:4,:2], \
access_partial_Occupancy_ijk(Occ_ijk[:,:2], (0,-1), D_cube=6))
True
"""
D_mid = D_cube / 2
N_voxel, n_dim = Occ_ijk.shape
select_ijk = np.ones(shape=(N_voxel,n_dim))
for _dim in range(n_dim):
if shift[_dim] == -1:
select_ijk[:,_dim] = (Occ_ijk[:,_dim] >= 0) & (Occ_ijk[:,_dim] < D_mid)
elif shift[_dim] == 0:
select_ijk[:,_dim] = (Occ_ijk[:,_dim] >= 0) & (Occ_ijk[:,_dim] < D_cube)
elif shift[_dim] == 1:
select_ijk[:,_dim] = (Occ_ijk[:,_dim] >= D_mid) & (Occ_ijk[:,_dim] < D_cube)
Occ_ijk[:, _dim] -= D_mid
else:
raise Warning("shift only support 3 values: -1/0/1, but got {}".format(shift))
select_ijk = select_ijk.all(axis = 1) # (N_voxel, n_dim) --> (N_voxel,)
return Occ_ijk[select_ijk]
def sparseOccupancy_AND_XOR(Occ1, Occ2):
"""
perform AND or XOR operation between 2 occupancy index arrays (only with ijk of occupied indexes)
-------------
inputs:
Occ1: np.uint (n1,2/3/...)
Occ2: np.uint (n2,2/3/...)
-------------
outputs:
resul_AND: how many overlapping elements
resul_XOR: how many non_overlapping elements
-------------
example:
>>> ijk1=np.array([[1,0],[2,3],[222,666],[0,0]])
>>> ijk2=np.array([[11,10],[2,3],[22,66],[0,0],[7,17]])
>>> sparseOccupancy_AND_XOR(ijk1,ijk2)
(2, 5)
"""
n1, ndim1 = Occ1.shape
n2, ndim2 = Occ2.shape
if (n1 == 0) or (n2 == 0):
resul_AND = 0
else:
Occ1_1D = Occ1.view(dtype=Occ1.dtype.descr * ndim1)
Occ2_1D = Occ2.view(dtype=Occ2.dtype.descr * ndim2)
resul_AND = np.intersect1d(Occ1_1D, Occ2_1D).size
resul_XOR = n1 + n2 - resul_AND * 2
return resul_AND, resul_XOR
def adapthresh(save_result_fld, N_refine_iter, D_cube, \
init_probThresh, min_probThresh, max_probThresh,\
rayPool_thresh, beta, gamma, npz_file,\
RGB_visual_ply=True):
data = sparseCubes.load_sparseCubes(npz_file)
prediction_list, rgb_list, vxl_ijk_list, rayPooling_votes_list, \
cube_ijk_np, param_np, viewPair_np = data
## before adapthresh, with init_probThresh and rayPool_thresh
vxl_mask_init_list = sparseCubes.filter_voxels(vxl_mask_list=[],prediction_list=prediction_list, prob_thresh=init_probThresh,\
rayPooling_votes_list=rayPooling_votes_list, rayPool_thresh=rayPool_thresh)
save_result_fld = os.path.join(save_result_fld, "adapThresh_gamma{:.3}_beta{}".format(gamma, beta))
if not os.path.exists(save_result_fld):
os.makedirs(save_result_fld)
vxl_maskDenoised_init_list = denoising.denoise_crossCubes(cube_ijk_np, vxl_ijk_list, vxl_mask_list = vxl_mask_init_list, D_cube = D_cube)
sparseCubes.save_sparseCubes_2ply(vxl_maskDenoised_init_list, vxl_ijk_list, rgb_list, param_np, \
ply_filePath=os.path.join(save_result_fld, 'initialization.ply'), normal_list=None)
neigh_shifts = np.asarray([[1,0,0],[0,1,0],[0,0,1],[-1,0,0],[0,-1,0],[0,0,-1]]).astype(np.int8)
thresh_perturb_list = [0.1, 0, -0.1] # note: the order matters, make sure argmin(cost) will first hit 0 before the perturb which can enlarge the pcd.
# # partial cube access for **dense cube**. For sparse cube: 'sparseOccupancy_AND_XOR'
# slices_3types = np.s_[:D_cube/2, :, D_cube/2:] # corresponding to slices in 3 cases: [-1, 0, 1]
# partial_cube_slc = lambda shift: tuple([slices_3types[_d] for _d in shift + 1]) # [-1,1,0] --> (slcs[0],slcs[2],slcs[1])
# cube_ijk2indx = {tuple(_ijk): _n for _n, _ijk in enumerate(cube_ijk_np)}
cube_ijk2indx = {}
for _n, _ijk in enumerate(cube_ijk_np):
if vxl_mask_init_list[_n].sum() > 0:
cube_ijk2indx.update({tuple(_ijk): _n})
vxl_mask_list = copy.deepcopy(vxl_mask_init_list)
occupied_vxl = lambda indx, thresh_shift: sparseCubes.filter_voxels(vxl_mask_list = [copy.deepcopy(vxl_mask_list[indx])],\
prediction_list = [prediction_list[indx]], prob_thresh = probThresh_list[indx] + thresh_shift)[0]
probThresh_list = [init_probThresh] * len(prediction_list)
update_probThresh_list = copy.deepcopy(probThresh_list)
for _iter in range(N_refine_iter): # each iteration of the algorithm
time_iter = time.time()
if RGB_visual_ply:
tmp_rgb_list = copy.deepcopy(rgb_list)
for _ijk in cube_ijk_np:
if not cube_ijk2indx.has_key(tuple(_ijk)):
continue # this cube is filtered in the very beginning
i_current = cube_ijk2indx[tuple(_ijk)]
element_cost = np.array([0,0,0]).astype(np.float16)
for _ijk_shift in neigh_shifts:
ijk_ovlp = _ijk + _ijk_shift
# ijk_adjc = _ijk + 2 * _ijk_shift
exist_ovlp = cube_ijk2indx.has_key(tuple(ijk_ovlp))
# exist_adjc = cube_ijk2indx.has_key(tuple(ijk_adjc))
if exist_ovlp:
i_ovlp = cube_ijk2indx[tuple(ijk_ovlp)]
tmp_occupancy_ovlp = vxl_ijk_list[i_ovlp][occupied_vxl(i_ovlp, 0)] # this will be changed in the next func.
partial_occ_ovlp = access_partial_Occupancy_ijk(Occ_ijk=tmp_occupancy_ovlp, \
shift=_ijk_shift*-1, D_cube = D_cube)
else:
partial_occ_ovlp = np.empty((0,3), dtype=np.uint8)
for _n_thresh, _thresh_perturb in enumerate(thresh_perturb_list):
tmp_occupancy_current = vxl_ijk_list[i_current][occupied_vxl(i_current, _thresh_perturb)]# this will be changed in the next func.
partial_occ_current = access_partial_Occupancy_ijk(Occ_ijk=tmp_occupancy_current, \
shift=_ijk_shift, D_cube = D_cube)
ovlp_AND, ovlp_XOR = sparseOccupancy_AND_XOR(partial_occ_current, partial_occ_ovlp)
element_cost[_n_thresh] += ovlp_XOR
if partial_occ_current.shape[0] >= 6:
if partial_occ_ovlp.shape[0] >= 6:
element_cost[_n_thresh] -= beta * ovlp_AND
update_probThresh_list[i_current] = probThresh_list[i_current] + thresh_perturb_list[np.argmin(element_cost)]
update_probThresh_list[i_current] = min(update_probThresh_list[i_current], max_probThresh)
if RGB_visual_ply:
tmp_rgb_list[i_current][:,np.argmin(element_cost)] = 255 # R/G/B --> threshold perturbation [-.1, 0, .1]
probThresh_list = copy.deepcopy(update_probThresh_list)
vxl_mask_list = sparseCubes.filter_voxels(vxl_mask_list=vxl_mask_list,prediction_list=prediction_list, prob_thresh=probThresh_list,\
rayPooling_votes_list=None, rayPool_thresh=None)
vxl_maskDenoised_list = denoising.denoise_crossCubes(cube_ijk_np, vxl_ijk_list, vxl_mask_list, D_cube )
ply_filePath = os.path.join(save_result_fld, 'iter{}.ply'.format(_iter))
sparseCubes.save_sparseCubes_2ply(vxl_maskDenoised_list, vxl_ijk_list, rgb_list, \
param_np, ply_filePath=ply_filePath, normal_list=None)
if RGB_visual_ply:
sparseCubes.save_sparseCubes_2ply(vxl_mask_list, vxl_ijk_list, tmp_rgb_list, \
param_np, ply_filePath=os.path.join(save_result_fld, 'iter{}_tmprgb4debug.ply'.format(_iter)), normal_list=None)
print 'updated iteration {}. It took {}s'.format(_iter, time.time() - time_iter)
return ply_filePath
import doctest
doctest.testmod()
|
libraries/botbuilder-core/botbuilder/core/skills/_skill_handler_impl.py | andreikop/botbuilder-python | 388 | 12607551 | <filename>libraries/botbuilder-core/botbuilder/core/skills/_skill_handler_impl.py<gh_stars>100-1000
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from uuid import uuid4
from logging import Logger
from typing import Callable
from botbuilder.core import Bot, BotAdapter, TurnContext
from botbuilder.schema import (
Activity,
ActivityTypes,
ResourceResponse,
CallerIdConstants,
)
from botframework.connector.auth import (
ClaimsIdentity,
JwtTokenValidation,
)
from .skill_conversation_reference import SkillConversationReference
from .conversation_id_factory import ConversationIdFactoryBase
from .skill_handler import SkillHandler
class _SkillHandlerImpl(SkillHandler):
def __init__( # pylint: disable=super-init-not-called
self,
skill_conversation_reference_key: str,
adapter: BotAdapter,
bot: Bot,
conversation_id_factory: ConversationIdFactoryBase,
get_oauth_scope: Callable[[], str],
logger: Logger = None,
):
if not skill_conversation_reference_key:
raise TypeError("skill_conversation_reference_key can't be None")
if not adapter:
raise TypeError("adapter can't be None")
if not bot:
raise TypeError("bot can't be None")
if not conversation_id_factory:
raise TypeError("conversation_id_factory can't be None")
self._skill_conversation_reference_key = skill_conversation_reference_key
self._adapter = adapter
self._bot = bot
self._conversation_id_factory = conversation_id_factory
self._get_oauth_scope = get_oauth_scope or (lambda: "")
self._logger = logger
async def on_send_to_conversation(
self, claims_identity: ClaimsIdentity, conversation_id: str, activity: Activity,
) -> ResourceResponse:
"""
send_to_conversation() API for Skill
This method allows you to send an activity to the end of a conversation.
This is slightly different from ReplyToActivity().
* SendToConversation(conversation_id) - will append the activity to the end
of the conversation according to the timestamp or semantics of the channel.
* ReplyToActivity(conversation_id,ActivityId) - adds the activity as a reply
to another activity, if the channel supports it. If the channel does not
support nested replies, ReplyToActivity falls back to SendToConversation.
Use ReplyToActivity when replying to a specific activity in the
conversation.
Use SendToConversation in all other cases.
:param claims_identity: Claims identity for the bot.
:type claims_identity: :class:`botframework.connector.auth.ClaimsIdentity`
:param conversation_id:The conversation ID.
:type conversation_id: str
:param activity: Activity to send.
:type activity: Activity
:return:
"""
return await self._process_activity(
claims_identity, conversation_id, None, activity,
)
async def on_reply_to_activity(
self,
claims_identity: ClaimsIdentity,
conversation_id: str,
activity_id: str,
activity: Activity,
) -> ResourceResponse:
"""
reply_to_activity() API for Skill.
This method allows you to reply to an activity.
This is slightly different from SendToConversation().
* SendToConversation(conversation_id) - will append the activity to the end
of the conversation according to the timestamp or semantics of the channel.
* ReplyToActivity(conversation_id,ActivityId) - adds the activity as a reply
to another activity, if the channel supports it. If the channel does not
support nested replies, ReplyToActivity falls back to SendToConversation.
Use ReplyToActivity when replying to a specific activity in the
conversation.
Use SendToConversation in all other cases.
:param claims_identity: Claims identity for the bot.
:type claims_identity: :class:`botframework.connector.auth.ClaimsIdentity`
:param conversation_id:The conversation ID.
:type conversation_id: str
:param activity_id: Activity ID to send.
:type activity_id: str
:param activity: Activity to send.
:type activity: Activity
:return:
"""
return await self._process_activity(
claims_identity, conversation_id, activity_id, activity,
)
async def on_delete_activity(
self, claims_identity: ClaimsIdentity, conversation_id: str, activity_id: str
):
skill_conversation_reference = await self._get_skill_conversation_reference(
conversation_id
)
async def callback(turn_context: TurnContext):
turn_context.turn_state[
self.SKILL_CONVERSATION_REFERENCE_KEY
] = skill_conversation_reference
await turn_context.delete_activity(activity_id)
await self._adapter.continue_conversation(
skill_conversation_reference.conversation_reference,
callback,
claims_identity=claims_identity,
audience=skill_conversation_reference.oauth_scope,
)
async def on_update_activity(
self,
claims_identity: ClaimsIdentity,
conversation_id: str,
activity_id: str,
activity: Activity,
) -> ResourceResponse:
skill_conversation_reference = await self._get_skill_conversation_reference(
conversation_id
)
resource_response: ResourceResponse = None
async def callback(turn_context: TurnContext):
nonlocal resource_response
turn_context.turn_state[
self.SKILL_CONVERSATION_REFERENCE_KEY
] = skill_conversation_reference
activity.apply_conversation_reference(
skill_conversation_reference.conversation_reference
)
turn_context.activity.id = activity_id
turn_context.activity.caller_id = (
f"{CallerIdConstants.bot_to_bot_prefix}"
f"{JwtTokenValidation.get_app_id_from_claims(claims_identity.claims)}"
)
resource_response = await turn_context.update_activity(activity)
await self._adapter.continue_conversation(
skill_conversation_reference.conversation_reference,
callback,
claims_identity=claims_identity,
audience=skill_conversation_reference.oauth_scope,
)
return resource_response or ResourceResponse(id=str(uuid4()).replace("-", ""))
@staticmethod
def _apply_skill_activity_to_turn_context_activity(
context: TurnContext, activity: Activity
):
context.activity.type = activity.type
context.activity.text = activity.text
context.activity.code = activity.code
context.activity.name = activity.name
context.activity.relates_to = activity.relates_to
context.activity.reply_to_id = activity.reply_to_id
context.activity.value = activity.value
context.activity.entities = activity.entities
context.activity.locale = activity.locale
context.activity.local_timestamp = activity.local_timestamp
context.activity.timestamp = activity.timestamp
context.activity.channel_data = activity.channel_data
context.activity.additional_properties = activity.additional_properties
async def _process_activity(
self,
claims_identity: ClaimsIdentity,
conversation_id: str,
reply_to_activity_id: str,
activity: Activity,
) -> ResourceResponse:
skill_conversation_reference = await self._get_skill_conversation_reference(
conversation_id
)
# If an activity is sent, return the ResourceResponse
resource_response: ResourceResponse = None
async def callback(context: TurnContext):
nonlocal resource_response
context.turn_state[
SkillHandler.SKILL_CONVERSATION_REFERENCE_KEY
] = skill_conversation_reference
TurnContext.apply_conversation_reference(
activity, skill_conversation_reference.conversation_reference
)
context.activity.id = reply_to_activity_id
app_id = JwtTokenValidation.get_app_id_from_claims(claims_identity.claims)
context.activity.caller_id = (
f"{CallerIdConstants.bot_to_bot_prefix}{app_id}"
)
if activity.type == ActivityTypes.end_of_conversation:
await self._conversation_id_factory.delete_conversation_reference(
conversation_id
)
await self._send_to_bot(activity, context)
elif activity.type == ActivityTypes.event:
await self._send_to_bot(activity, context)
elif activity.type in (ActivityTypes.command, ActivityTypes.command_result):
if activity.name.startswith("application/"):
# Send to channel and capture the resource response for the SendActivityCall so we can return it.
resource_response = await context.send_activity(activity)
else:
await self._send_to_bot(activity, context)
else:
# Capture the resource response for the SendActivityCall so we can return it.
resource_response = await context.send_activity(activity)
await self._adapter.continue_conversation(
skill_conversation_reference.conversation_reference,
callback,
claims_identity=claims_identity,
audience=skill_conversation_reference.oauth_scope,
)
if not resource_response:
resource_response = ResourceResponse(id=str(uuid4()))
return resource_response
async def _get_skill_conversation_reference(
self, conversation_id: str
) -> SkillConversationReference:
# Get the SkillsConversationReference
try:
skill_conversation_reference = await self._conversation_id_factory.get_skill_conversation_reference(
conversation_id
)
except (NotImplementedError, AttributeError):
if self._logger:
self._logger.log(
30,
"Got NotImplementedError when trying to call get_skill_conversation_reference() "
"on the SkillConversationIdFactory, attempting to use deprecated "
"get_conversation_reference() method instead.",
)
# ConversationIdFactory can return either a SkillConversationReference (the newer way),
# or a ConversationReference (the old way, but still here for compatibility). If a
# ConversationReference is returned, build a new SkillConversationReference to simplify
# the remainder of this method.
conversation_reference_result = await self._conversation_id_factory.get_conversation_reference(
conversation_id
)
if isinstance(conversation_reference_result, SkillConversationReference):
skill_conversation_reference: SkillConversationReference = conversation_reference_result
else:
skill_conversation_reference: SkillConversationReference = SkillConversationReference(
conversation_reference=conversation_reference_result,
oauth_scope=self._get_oauth_scope(),
)
if not skill_conversation_reference:
raise KeyError("SkillConversationReference not found")
if not skill_conversation_reference.conversation_reference:
raise KeyError("conversationReference not found")
return skill_conversation_reference
async def _send_to_bot(self, activity: Activity, context: TurnContext):
_SkillHandlerImpl._apply_skill_activity_to_turn_context_activity(
context, activity
)
await self._bot.on_turn(context)
|
src/backend/db/init_db.py | ddddhm1/LuWu | 658 | 12607605 | from core import config
from crud.crud_user import user
from schemas.user import UserCreate
# make sure all SQL Alchemy models are imported before initializing DB
# otherwise, SQL Alchemy might fail to initialize relationships properly
# for more details: https://github.com/tiangolo/full-stack-fastapi-postgresql/issues/28
from db import base
def init_db(db_session):
init_user = user.get_by_username(
db_session, username=config.FIRST_SUPERUSER_USERNAME
)
if not init_user:
user_in = UserCreate(
username=config.FIRST_SUPERUSER_USERNAME,
email=config.FIRST_SUPERUSER_EMAIL,
password=<PASSWORD>,
is_superuser=True,
)
init_user = user.create(db_session, obj_in=user_in)
|
Hackerrank_problems/Sales by Match/solution.py | gbrls/CompetitiveCode | 165 | 12607617 | #!/bin/python3
import math
import os
import random
import re
import sys
# Complete the sockMerchant function below.
def sockMerchant(n, ar):
ar2 = []
ar1 =sorted(ar)
pair = 0
numb = 0
# The while loop is used so that the index in ar1[numb] does not go out of index limit.
# First I tried doing while numb <= len(ar1) which gave indexError.
# Hence I removed the = sign as the range is '1 less than ar1' .
while numb < len(ar1):
# Used this foor loop to slice ar1 in same item lists.
# To use the same list again and again O cleared the list below using del().
for i in ar1:
if i == ar1[numb]:
ar2.append(i)
a = len(ar2)
del(ar2[:])
if a >= 2:
if a % 2 == 0:
pair += round(a/2)
else:
pair += round((a-1)/2)
numb += a
return pair
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
ar = list(map(int, input().rstrip().split()))
result = sockMerchant(n, ar)
fptr.write(str(result) + '\n')
fptr.close()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.