Dataset Viewer
Auto-converted to Parquet Duplicate
uid
stringlengths
24
24
category
stringclasses
2 values
granularity
stringclasses
1 value
prefix
stringlengths
125
1.24k
suffix
stringlengths
39
35.8k
content
stringlengths
61
35.9k
repo
stringlengths
10
70
path
stringlengths
11
86
3122b1cd3ac999fb01386c9a
function
simple
# from __future__ import absolute_import, print_function import os import sys sys.path.append('./') import numpy as np from util.data_process import load_3d_volume_as_array, binary_dice3d def get_ground_truth_names(g_folder, patient_names_file, year = 15):
assert(year==15 or year == 17) with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_gt_names = [] for patient_name in patient_names: patient_dir = os.path.join(g_folder, patient_name) img_names = os.listdi...
def get_ground_truth_names(g_folder, patient_names_file, year = 15): assert(year==15 or year == 17) with open(patient_names_file) as f: content = f.readlines() patient_names = [x.strip() for x in content] full_gt_names = [] for patient_name in patient_names: patient_dir =...
MohamedHeshamMustafa/Brain-Tumor-Automatic-Detection-and-Segmentation-
util/evaluation.py
0b43fc9a9ff93f5e76021d3c
function
simple
val=1, dtype=tf.float32) return (example_input, (example_target_phons, example_target_mask)) def generate_fake_batch( batch_size: int, channels=83, bins=1024, ) -> List[Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]]:
example_batch = [] for _ in range(batch_size): input_example, ( target_phons_example, target_mask_example) = generate_fake_example( channels=channels, bins=bins) input_example = tf.expand_dims(input_example, axis=0) target_phons_example = tf.expand_dims(target_phons_example, axis=0) ...
def generate_fake_batch( batch_size: int, channels=83, bins=1024, ) -> List[Tuple[tf.Tensor, Tuple[tf.Tensor, tf.Tensor]]]: example_batch = [] for _ in range(batch_size): input_example, ( target_phons_example, target_mask_example) = generate_fake_example( channels=channels, bins=bins) ...
Xtuden-com/korvapuusti
listening_test_summer_2020/modelling/end_to_end_model/neural_model/test_helpers.py
903e859d625006b8f8af186d
function
simple
type(s)) if PY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif PY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s def ensure_text(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): r...
def ensure_text(s, encoding="utf-8", errors="strict"): """Coerce *s* to six.text_type. For Python 2: - `unicode` -> `unicode` - `str` -> `unicode` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if isinstance(s, binary_type): return s.decode(encodin...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
7b35902f68453b027bb2ea35
function
simple
""" if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def ensure_str(s, encoding="utf-8", errors="strict"):
"""Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) if PY2 an...
def ensure_str(s, encoding="utf-8", errors="strict"): """Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if not isinstance(s, (text_type, binary_type)): raise TypeEr...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
bd5b8a9613c5205c1e066287
function
simple
.urllib_robotparser") def __dir__(self): return ["parse", "error", "request", "response", "robotparser"] _importer._add_module( Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib" ) def add_move(move):
"""Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move)
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
838a27d5ee9e6313b6270deb
function
simple
Equal(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs) def assertRegex(self, *args, **kwargs):
return getattr(self, _assertRegex)(*args, **kwargs)
def assertRegex(self, *args, **kwargs): return getattr(self, _assertRegex)(*args, **kwargs)
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
eb7305e335169287e7a80182
function
simple
= "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs) def assertRaisesRegex(self, *args, **kwargs):
return getattr(self, _assertRaisesRegex)(*args, **kwargs)
def assertRaisesRegex(self, *args, **kwargs): return getattr(self, _assertRaisesRegex)(*args, **kwargs)
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
52c59c2ee045081efc58fa09
function
simple
weakref__", None) if hasattr(cls, "__qualname__"): orig_vars["__qualname__"] = cls.__qualname__ return metaclass(cls.__name__, cls.__bases__, orig_vars) return wrapper def ensure_binary(s, encoding="utf-8", errors="strict"):
"""Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.encode(encoding, errors) elif isinstance(s, binary_type)...
def ensure_binary(s, encoding="utf-8", errors="strict"): """Coerce **s** to six.binary_type. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> encoded to `bytes` - `bytes` -> `bytes` """ if isinstance(s, text_type): return s.enc...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
39427e09dfd55fc72c7c204e
function
simple
decoded to `str` """ if isinstance(s, binary_type): return s.decode(encoding, errors) elif isinstance(s, text_type): return s else: raise TypeError("not expecting type '%s'" % type(s)) def python_2_unicode_compatible(klass):
""" A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: if "__str__" not in klass.__dict_...
def python_2_unicode_compatible(klass): """ A decorator that defines __unicode__ and __str__ methods under Python 2. Under Python 3 it does nothing. To support Python 2 and 3 with a single code base, define a __str__ method returning text and apply this decorator to the class. """ if PY2: ...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
c8d052b4f89bf310a7568f5b
function
simple
(X()) except OverflowError: # 32-bit MAXSIZE = int((1 << 31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc):
"""Add documentation to a function.""" func.__doc__ = doc
def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
5632f7ac38ad3183a9fe7d6d
function
simple
", "robotparser"] _importer._add_module( Module_six_moves_urllib(__name__ + ".moves.urllib"), "moves.urllib" ) def add_move(move): """Add an item to six.moves.""" setattr(_MovedItems, move.name, move) def remove_move(name):
"""Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
def remove_move(name): """Remove item from six.moves.""" try: delattr(_MovedItems, name) except AttributeError: try: del moves.__dict__[name] except KeyError: raise AttributeError("no such move, %r" % (name,))
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
ec09a13a489444b23f45beb3
function
simple
IO _assertCountEqual = "assertItemsEqual" _assertRaisesRegex = "assertRaisesRegexp" _assertRegex = "assertRegexpMatches" _add_doc(b, """Byte literal""") _add_doc(u, """Text literal""") def assertCountEqual(self, *args, **kwargs):
return getattr(self, _assertCountEqual)(*args, **kwargs)
def assertCountEqual(self, *args, **kwargs): return getattr(self, _assertCountEqual)(*args, **kwargs)
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
77a9c9ca696bbd3d37597ba3
function
simple
31) - 1) else: # 64-bit MAXSIZE = int((1 << 63) - 1) del X def _add_doc(func, doc): """Add documentation to a function.""" func.__doc__ = doc def _import_module(name):
"""Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
def _import_module(name): """Import module, returning the module after the last dot.""" __import__(name) return sys.modules[name]
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
224d6fdf56f3ac9c2a9c0544
function
simple
ases, d): return meta(name, bases, d) @classmethod def __prepare__(cls, name, this_bases): return meta.__prepare__(name, bases) return type.__new__(metaclass, "temporary_class", (), {}) def add_metaclass(metaclass):
"""Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get("__slots__") if slots is not None: if isinstance(slots, str): slots = [slots] for slots_var in slots: ...
def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() slots = orig_vars.get("__slots__") if slots is not None: if isinstance(slots, str): slots = [slots] for sl...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
07433ba7a17c945822e6b55c
function
simple
functools.WRAPPER_UPDATES, ): def wrapper(f): f = functools.wraps(wrapped, assigned, updated)(f) f.__wrapped__ = wrapped return f return wrapper else: wraps = functools.wraps def with_metaclass(meta, *bases):
"""Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, name, this_bases, d): ret...
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a dummy # metaclass for one level of class instantiation that replaces itself with # the actual metaclass. class metaclass(type): def __new__(cls, nam...
Manny27nyc/oci-python-sdk
src/oci/_vendor/urllib3/packages/six.py
3be4f4c4427650ca566bc656
function
simple
) # seconds # context.driver.set_window_size(1200, 600) context.base_url = BASE_URL # -- SET LOG LEVEL: behave --logging-level=ERROR ... # on behave command-line or in "behave.ini" context.config.setup_logging() def after_all(context):
""" Executed after all tests """ context.driver.quit()
def after_all(context): """ Executed after all tests """ context.driver.quit()
nyu-devops-shopcarts/shopcarts
features/environment.py
ef1a041852a2be10773d5596
function
simple
status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret def sitemap_app(environ, start_response):
status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) requested_url = environ['PATH_INFO'] if requested_url == '/sleep': time.sleep(2) response = 'Done' else: response = sitemap_app.sitemap.get(requested_url) log.debug('Request...
def sitemap_app(environ, start_response): status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) requested_url = environ['PATH_INFO'] if requested_url == '/sleep': time.sleep(2) response = 'Done' else: response = sitemap_app.sitemap...
ahlinc/pomp
tests/mockserver.py
28be5cf22156129bb1fced13
function
simple
response) try: ret = [json.dumps(response).encode('utf-8')] except Exception: log.exception("bla-bla") log.debug('Requested url: %s, ret: %s', requested_url, ret) return ret def make_reponse_body(items, links):
return { 'items': items, 'links': links, }
def make_reponse_body(items, links): return { 'items': items, 'links': links, }
ahlinc/pomp
tests/mockserver.py
e45817a3dc82bb44d830a98f
function
simple
%s, ret: %s', requested_url, ret) return ret def make_reponse_body(items, links): return { 'items': items, 'links': links, } def make_sitemap(level=3, links_on_page=3, sitemap=None, entry='/root'):
sitemap = sitemap if sitemap else {} if level == 0: return sitemap def make_entry(url, sitemap, links_on_page): sitemap.update({ url: make_reponse_body( ['a', 'b'], ['%s/%s' % (url, i) for i in range(0, links_on_page)], ) }) ...
def make_sitemap(level=3, links_on_page=3, sitemap=None, entry='/root'): sitemap = sitemap if sitemap else {} if level == 0: return sitemap def make_entry(url, sitemap, links_on_page): sitemap.update({ url: make_reponse_body( ['a', 'b'], ['%s/%s' ...
ahlinc/pomp
tests/mockserver.py
f50eed5646f8e7a1c33c237a
function
simple
sys.stderr = self._stdout, self._stderr def __exit__(self, exc_type, exc_value, traceback): self._stdout.flush() self._stderr.flush() sys.stdout = self.old_stdout sys.stderr = self.old_stderr def simple_app(environ, start_response):
setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret
def simple_app(environ, start_response): setup_testing_defaults(environ) status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) ret = ["%s: %s\n" % (key, value) for key, value in environ.iteritems()] return ret
ahlinc/pomp
tests/mockserver.py
afd4d5e24037dd985da7919e
function
simple
def HATT(max_byte_size=33554432, memory_estimate_period=1000000, grace_period=200, min_samples_reevaluate=20, split_criterion='info_gain', split_confidence=0.0000001, tie_threshold=0.05, binary_split=False, stop_mem_management=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None): # ...
warnings.warn("'HATT' has been renamed to 'ExtremelyFastDecisionTreeClassifier' in v0.5.0.\n" "The old name will be removed in v0.7.0", category=FutureWarning) return ExtremelyFastDecisionTreeClassifier(max_byte_size=max_byte_size, memory_estimate...
def HATT(max_byte_size=33554432, memory_estimate_period=1000000, grace_period=200, min_samples_reevaluate=20, split_criterion='info_gain', split_confidence=0.0000001, tie_threshold=0.05, binary_split=False, stop_mem_management=False, leaf_prediction='nba', nb_threshold=0, nominal_attributes=None): # ...
imran-salim/scikit-multiflow
src/skmultiflow/trees/extremely_fast_decision_tree.py
3eaf5aeea26b5aaffa3e044e
function
simple
1]) return zp def get_LM_Pos_from_state(x, ind): lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm def search_correspond_LM_ID(xAug, PAug, zi):
""" Landmark association with Mahalanobis distance """ nLM = calc_n_LM(xAug) mdist = [] for i in range(nLM): lm = get_LM_Pos_from_state(xAug, i) y, S, H = calc_innovation(lm, xAug, PAug, zi, i) mdist.append(y.T @ np.linalg.inv(S) @ y) mdist.append(M_DIST_TH) # ne...
def search_correspond_LM_ID(xAug, PAug, zi): """ Landmark association with Mahalanobis distance """ nLM = calc_n_LM(xAug) mdist = [] for i in range(nLM): lm = get_LM_Pos_from_state(xAug, i) y, S, H = calc_innovation(lm, xAug, PAug, zi, i) mdist.append(y.T @ np.linalg.i...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
c5039d2d0d236eeb23cc1c63
function
simple
u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T * jF * Fx return G, Fx, def calc_LM_Pos(x, z):
zp = np.zeros((2, 1)) zp[0, 0] = x[0, 0] + z[0] * math.cos(x[2, 0] + z[1]) zp[1, 0] = x[1, 0] + z[0] * math.sin(x[2, 0] + z[1]) #zp[0, 0] = x[0, 0] + z[0, 0] * math.cos(x[2, 0] + z[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp
def calc_LM_Pos(x, z): zp = np.zeros((2, 1)) zp[0, 0] = x[0, 0] + z[0] * math.cos(x[2, 0] + z[1]) zp[1, 0] = x[1, 0] + z[0] * math.sin(x[2, 0] + z[1]) #zp[0, 0] = x[0, 0] + z[0, 0] * math.cos(x[2, 0] + z[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
2d437a4ff3273382edc59920
function
simple
i) mdist.append(y.T @ np.linalg.inv(S) @ y) mdist.append(M_DIST_TH) # new landmark minid = mdist.index(min(mdist)) return minid def calc_innovation(lm, xEst, PEst, z, LMid):
delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] zangle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0] zp = np.array([[math.sqrt(q), pi_2_pi(zangle)]]) y = (z - zp).T y[1] = pi_2_pi(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PEst @ H.T + Cx[0:2, 0:2] return y, S, H
def calc_innovation(lm, xEst, PEst, z, LMid): delta = lm - xEst[0:2] q = (delta.T @ delta)[0, 0] zangle = math.atan2(delta[1, 0], delta[0, 0]) - xEst[2, 0] zp = np.array([[math.sqrt(q), pi_2_pi(zangle)]]) y = (z - zp).T y[1] = pi_2_pi(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PE...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
9aee475d0df6824c8b038ce7
function
simple
.inv(S) xEst = xEst + (K @ y) PEst = (np.eye(len(xEst)) - (K @ H)) @ PEst xEst[2] = pi_2_pi(xEst[2]) return xEst, PEst def calc_input():
v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u
def calc_input(): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
aa13b7b2a8a12c04c9cfee7e
function
simple
(y[1]) H = jacobH(q, delta, xEst, LMid + 1) S = H @ PEst @ H.T + Cx[0:2, 0:2] return y, S, H def jacobH(q, delta, x, i):
sq = math.sqrt(q) G = np.array([[-sq * delta[0, 0], - sq * delta[1, 0], 0, sq * delta[0, 0], sq * delta[1, 0]], [delta[1, 0], - delta[0, 0], - 1.0, - delta[1, 0], delta[0, 0]]]) G = G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nLM)))) F2 = np.hstack((np...
def jacobH(q, delta, x, i): sq = math.sqrt(q) G = np.array([[-sq * delta[0, 0], - sq * delta[1, 0], 0, sq * delta[0, 0], sq * delta[1, 0]], [delta[1, 0], - delta[0, 0], - 1.0, - delta[1, 0], delta[0, 0]]]) G = G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nL...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
ff37468fef6b746d2bcced7a
function
simple
2 DT = 0.1 # time tick [s] SIM_TIME = 50.0 # simulation time [s] MAX_RANGE = 20.0 # maximum observation range M_DIST_TH = 2.0 # Threshold of Mahalanobis distance for data association. STATE_SIZE = 3 # State size [x,y,yaw] LM_SIZE = 2 # LM state size [x,y] show_animation = True def ekf_slam(xEst, PEst, u, z): ...
S = STATE_SIZE xEst[0:S] = motion_model(xEst[0:S], u) G, Fx = jacob_motion(xEst[0:S], u) PEst[0:S, 0:S] = G.T * PEst[0:S, 0:S] * G + Fx.T * Cx * Fx initP = np.eye(2) # Update for iz in range(len(z[:, 0])): # for each observation minid = search_correspond_LM_ID(xEst, PEst, z[iz, 0:2...
def ekf_slam(xEst, PEst, u, z): # Predict S = STATE_SIZE xEst[0:S] = motion_model(xEst[0:S], u) G, Fx = jacob_motion(xEst[0:S], u) PEst[0:S, 0:S] = G.T * PEst[0:S, 0:S] * G + Fx.T * Cx * Fx initP = np.eye(2) # Update for iz in range(len(z[:, 0])): # for each observation minid ...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
a9c1943c9e8e57781f87d45c
function
simple
G / q nLM = calc_n_LM(x) F1 = np.hstack((np.eye(3), np.zeros((3, 2 * nLM)))) F2 = np.hstack((np.zeros((2, 3)), np.zeros((2, 2 * (i - 1))), np.eye(2), np.zeros((2, 2 * nLM - 2 * i)))) F = np.vstack((F1, F2)) H = G @ F return H def pi_2_pi(angle): return (angle + math...
print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [3.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) xTrue = np.zeros((STATE_SIZE...
def main(): print(__file__ + " start!!") time = 0.0 # RFID positions [x, y] RFID = np.array([[10.0, -2.0], [15.0, 10.0], [3.0, 15.0], [-5.0, 20.0]]) # State Vector [x y yaw v]' xEst = np.zeros((STATE_SIZE, 1)) xTrue = np.zeros...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
2f5cc4114b6246fe6779cded
function
simple
([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x def calc_n_LM(x):
n = int((len(x) - STATE_SIZE) / LM_SIZE) return n
def calc_n_LM(x): n = int((len(x) - STATE_SIZE) / LM_SIZE) return n
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
7e507578587551412140e8fa
function
simple
.randn() * Rsim[0, 0], u[1, 0] + np.random.randn() * Rsim[1, 1]]]).T xd = motion_model(xd, ud) return xTrue, z, xd, ud def motion_model(x, u):
F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x
def motion_model(x, u): F = np.array([[1.0, 0, 0], [0, 1.0, 0], [0, 0, 1.0]]) B = np.array([[DT * math.cos(x[2, 0]), 0], [DT * math.sin(x[2, 0]), 0], [0.0, DT]]) x = (F @ x) + (B @ u) return x
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
07c0d37e6455da054ad71740
function
simple
((2, 2 * (i - 1))), np.eye(2), np.zeros((2, 2 * nLM - 2 * i)))) F = np.vstack((F1, F2)) H = G @ F return H def pi_2_pi(angle):
return (angle + math.pi) % (2 * math.pi) - math.pi
def pi_2_pi(angle): return (angle + math.pi) % (2 * math.pi) - math.pi
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
3ed00a84573e319ea00ba306
function
simple
Est xEst[2] = pi_2_pi(xEst[2]) return xEst, PEst def calc_input(): v = 1.0 # [m/s] yawrate = 0.1 # [rad/s] u = np.array([[v, yawrate]]).T return u def observation(xTrue, xd, u, RFID):
xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.sqrt(dx**2 + dy**2) angle = pi_2_pi(math.atan2(dy, dx) - xTrue[2, 0]) if d <= MAX_RA...
def observation(xTrue, xd, u, RFID): xTrue = motion_model(xTrue, u) # add noise to gps x-y z = np.zeros((0, 3)) for i in range(len(RFID[:, 0])): dx = RFID[i, 0] - xTrue[0, 0] dy = RFID[i, 1] - xTrue[1, 0] d = math.sqrt(dx**2 + dy**2) angle = pi_2_pi(math.atan2(dy, dx)...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
02e13c6b8f37c9f3953aaed1
function
simple
0], [0.0, DT]]) x = (F @ x) + (B @ u) return x def calc_n_LM(x): n = int((len(x) - STATE_SIZE) / LM_SIZE) return n def jacob_motion(x, u):
Fx = np.hstack((np.eye(STATE_SIZE), np.zeros( (STATE_SIZE, LM_SIZE * calc_n_LM(x))))) jF = np.array([[0.0, 0.0, -DT * u[0] * math.sin(x[2, 0])], [0.0, 0.0, DT * u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T * jF * Fx return G,...
def jacob_motion(x, u): Fx = np.hstack((np.eye(STATE_SIZE), np.zeros( (STATE_SIZE, LM_SIZE * calc_n_LM(x))))) jF = np.array([[0.0, 0.0, -DT * u[0] * math.sin(x[2, 0])], [0.0, 0.0, DT * u[0] * math.cos(x[2, 0])], [0.0, 0.0, 0.0]]) G = np.eye(STATE_SIZE) + Fx.T...
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
3803e5c82743f67fb1d64573
function
simple
[0, 1]) #zp[1, 0] = x[1, 0] + z[0, 0] * math.sin(x[2, 0] + z[0, 1]) return zp def get_LM_Pos_from_state(x, ind):
lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm
def get_LM_Pos_from_state(x, ind): lm = x[STATE_SIZE + LM_SIZE * ind: STATE_SIZE + LM_SIZE * (ind + 1), :] return lm
takayuki5168/PythonRobotics
SLAM/EKFSLAM/ekf_slam.py
eb8a65f7efebbc0d3caa966f
function
simple
ester=icsr_semester, **kwargs, ) @staticmethod def create_user(**kwargs): default_kwargs = { "username": "default username", } kwargs = {**default_kwargs, **kwargs} return User.objects.create(**kwargs) def login_user(test_cls):
user = ModelFactory.create_user() password = "custom password" user.set_password(password) user.save() group = Group(name="officer") group.save() group.user_set.add(user) group.save() test_cls.client.login(username=user.username, password=password)
def login_user(test_cls): user = ModelFactory.create_user() password = "custom password" user.set_password(password) user.save() group = Group(name="officer") group.save() group.user_set.add(user) group.save() test_cls.client.login(username=user.username, password=password)
jyxzhang/hknweb
hknweb/academics/tests/utils.py
3d158063f17070436ef011fe
function
simple
of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)] def itemize(metrics):
return [m.item() for m in metrics]
def itemize(metrics): return [m.item() for m in metrics]
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
a2d4e7f2b1894cd7f98f15a9
function
simple
_less_precise=True (or better =3), until then using =2 as it works, but this check is less good. pd.testing.assert_frame_equal(csv_df, recorder_df, check_exact=False, check_less_precise=2) @pytest.fixture(scope="module", autouse=True) def cleanup(request):
"""Cleanup the autogenerated file once we are finished.""" def remove_history_csv(): file = "history.csv" if os.path.exists(file): os.remove(file) request.addfinalizer(remove_history_csv)
@pytest.fixture(scope="module", autouse=True) def cleanup(request): """Cleanup the autogenerated file once we are finished.""" def remove_history_csv(): file = "history.csv" if os.path.exists(file): os.remove(file) request.addfinalizer(remove_history_csv)
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
fe4738dc6959880838e4df1d
function
simple
line.split()[:-1]] for line in lines] records = [dict(zip(header, metrics_list)) for metrics_list in floats] df = pd.DataFrame(records, columns=header) df['epoch'] = df['epoch'].astype(int) return df def get_train_losses(learn):
"Returns list of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)]
def get_train_losses(learn): "Returns list of training losses at the end of each training epoch." np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)]
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
9c9846400060f2dac2cc1340
function
simple
)] for i, (loss, val_loss, epoch_metrics) in enumerate(zip( get_train_losses(learn), learn.recorder.val_losses, learn.recorder.metrics), 1)] return pd.DataFrame(records, columns=learn.recorder.names[:-1]) def convert_into_dataframe(buffer):
"Converts data captured from `fastprogress.ConsoleProgressBar` into dataframe." lines = buffer.split('\n') header, *lines = [l.strip() for l in lines if l and not l.startswith('Total')] header = header.split()[:-1] floats = [[float(x) for x in line.split()[:-1]] for line in lines] records = [dic...
def convert_into_dataframe(buffer): "Converts data captured from `fastprogress.ConsoleProgressBar` into dataframe." lines = buffer.split('\n') header, *lines = [l.strip() for l in lines if l and not l.startswith('Total')] header = header.split()[:-1] floats = [[float(x) for x in line.split()[:-1]] f...
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
73eb738aa83d0a6b83c8d65d
function
simple
np_losses = [to_np(l).item() for l in learn.recorder.losses] batch_size = len(learn.data.train_dl) return [batch[-1] for batch in partition(np_losses, batch_size)] def itemize(metrics): return [m.item() for m in metrics] def test_logger():
learn = fake_learner() learn.metrics = [accuracy, error_rate] learn.callback_fns.append(callbacks.CSVLogger) with CaptureStdout() as cs: learn.fit_one_cycle(3) csv_df = learn.csv_logger.read_logged_file() stdout_df = convert_into_dataframe(cs.out) csv_df.drop(columns=['time'], axis=1, inplac...
def test_logger(): learn = fake_learner() learn.metrics = [accuracy, error_rate] learn.callback_fns.append(callbacks.CSVLogger) with CaptureStdout() as cs: learn.fit_one_cycle(3) csv_df = learn.csv_logger.read_logged_file() stdout_df = convert_into_dataframe(cs.out) csv_df.drop(columns=['tim...
jeffrwells/fastai
tests/test_callbacks_csv_logger.py
5a1c9ed79fc82f32da3867af
function
simple
(fake_cmd_from_conftest['_ver_nice']['COMMAND_OUTPUT'], str) assert isinstance(fake_cmd_from_conftest['_ver_nice']['COMMAND_KWARGS'], dict) assert isinstance(fake_cmd_from_conftest['_ver_nice']['COMMAND_RESULT'], dict) def test_validate_documentation_existence():
from moler.util.cmds_events_doc import _validate_documentation_existence fake_cmd = import_module('conftest') test_data = {'_ver_execute': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}} ...
def test_validate_documentation_existence(): from moler.util.cmds_events_doc import _validate_documentation_existence fake_cmd = import_module('conftest') test_data = {'_ver_execute': {'COMMAND_OUTPUT': '', 'COMMAND_KWARGS': {}, 'COMMAND_RESULT': {}}, '_ver_test': {'COMMAND_OUTPUT': '', 'C...
carr-elagheb/moler
test/test_cmds_events_doc.py
f0e782e890944e0cc51c8f01
function
simple
_variant(test_data, '_ver_test2', "COMMAND") assert result1 == ('out1', {1: 1}, {1: 1}) assert result2 == ('out2', {}, {2: 2}) def test_create_command_raise_exception_when_object_takes_no_params(fake_cmd):
from moler.util.cmds_events_doc import _create_command, _buffer_connection with raises(Exception) as exc: _create_command(fake_cmd, _buffer_connection().moler_connection, {}) assert "via FakeCommand() : object() takes no parameters" or "via FakeCommand() : this constructor takes no arguments" in s...
def test_create_command_raise_exception_when_object_takes_no_params(fake_cmd): from moler.util.cmds_events_doc import _create_command, _buffer_connection with raises(Exception) as exc: _create_command(fake_cmd, _buffer_connection().moler_connection, {}) assert "via FakeCommand() : object() takes n...
carr-elagheb/moler
test/test_cmds_events_doc.py
74eaaa4b845518ee463d0f4d
function
simple
_list = [f for root, dirs, files in walk(abs_test_path) for f in files if isfile(join(root, f)) and '__init__' not in f and '.pyc' not in f and f.endswith('.py')] return file_list def _load_obj(func_name):
""" Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name)
def _load_obj(func_name): """ Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name)
carr-elagheb/moler
test/test_cmds_events_doc.py
891919fd8933081d1fad9cbb
function
simple
""" Load instance from module. :param func_name: function name as string :return: object instance :rtype: type """ return getattr(import_module('moler.util.cmds_events_doc'), func_name) # --------------- helper functions --------------- def test_documentation_exists():
from moler.util.cmds_events_doc import check_if_documentation_exists dir_path = path.dirname(path.realpath(__file__)) moler_dir_path = path.dirname(dir_path) cmd_path = path.join(moler_dir_path, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "events") assert check_if_document...
def test_documentation_exists(): from moler.util.cmds_events_doc import check_if_documentation_exists dir_path = path.dirname(path.realpath(__file__)) moler_dir_path = path.dirname(dir_path) cmd_path = path.join(moler_dir_path, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "event...
carr-elagheb/moler
test/test_cmds_events_doc.py
80f670d789556f43ce3926e6
function
simple
@mark.parametrize('func2test,method_param,base_class, expected', [ ('_walk_moler_python_files', cmd_dir_under_test, "COMMAND", True), ('_walk_moler_commands', cmd_dir_under_test, Command, True), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command, True)]) def test_functions_are_generators(func2...
from inspect import isgenerator, isgeneratorfunction func_obj = _load_obj(func_name=func2test) generator_obj = func_obj(method_param, base_class) assert isgeneratorfunction(func_obj) is expected assert isgenerator(generator_obj) is expected
@mark.parametrize('func2test,method_param,base_class, expected', [ ('_walk_moler_python_files', cmd_dir_under_test, "COMMAND", True), ('_walk_moler_commands', cmd_dir_under_test, Command, True), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command, True)]) def test_functions_are_generators(func2...
carr-elagheb/moler
test/test_cmds_events_doc.py
51afb10c37ded1a13c91c137
function
simple
, "moler", "cmd") events_path = path.join(moler_dir_path, "moler", "events") assert check_if_documentation_exists(cmd_path) is True assert check_if_documentation_exists(events_path) is True def test_buffer_connection_returns_threadconnection_with_moler_conn():
from moler.io.raw.memory import ThreadedFifoBuffer from moler.observable_connection import ObservableConnection from moler.util.cmds_events_doc import _buffer_connection buff_conn = _buffer_connection() assert isinstance(buff_conn, ThreadedFifoBuffer) is True assert isinstance(buff_conn.moler_c...
def test_buffer_connection_returns_threadconnection_with_moler_conn(): from moler.io.raw.memory import ThreadedFifoBuffer from moler.observable_connection import ObservableConnection from moler.util.cmds_events_doc import _buffer_connection buff_conn = _buffer_connection() assert isinstance(buff_co...
carr-elagheb/moler
test/test_cmds_events_doc.py
9824e10de59142c4ef4433b5
function
simple
_ver_test2' in result2[1] assert '> has COMMAND_OUTPUT_ver_test3 but no COMMAND_RESULT_ver_test3' in result3[0] assert '> has COMMAND_KWARGS_ver_test3 but no COMMAND_RESULT_ver_test3' in result3[1] def test_get_doc_variant():
from moler.util.cmds_events_doc import _get_doc_variant test_data = {'_ver_test1': {'COMMAND_OUTPUT': 'out1', 'COMMAND_KWARGS': {1: 1}, 'COMMAND_RESULT': {1: 1}}, '_ver_test2': {'COMMAND_OUTPUT': 'out2', 'COMMAND_RESULT': {2: 2}}} result1 = _get_doc_variant(test_data, '_ver_test1', "COMMAN...
def test_get_doc_variant(): from moler.util.cmds_events_doc import _get_doc_variant test_data = {'_ver_test1': {'COMMAND_OUTPUT': 'out1', 'COMMAND_KWARGS': {1: 1}, 'COMMAND_RESULT': {1: 1}}, '_ver_test2': {'COMMAND_OUTPUT': 'out2', 'COMMAND_RESULT': {2: 2}}} result1 = _get_doc_variant(test...
carr-elagheb/moler
test/test_cmds_events_doc.py
b6e6b88e035a4829c17c1b6c
function
simple
) generator_obj = func_obj(method_param, base_class) file_list = _list_in_path(listing_type='allfiles') with raises(StopIteration): for _ in range(len(file_list)): next(generator_obj) def test_walk_moler_nonabstract_commands_raise_exception_when_called(fake_cmd):
from moler.util.cmds_events_doc import _walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler_nonabstract_commands(cmd_dir_under_test, Command))
def test_walk_moler_nonabstract_commands_raise_exception_when_called(fake_cmd): from moler.util.cmds_events_doc import _walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler...
carr-elagheb/moler
test/test_cmds_events_doc.py
5b676c9ddf4dd4d87c532ca7
function
simple
@mark.parametrize('func2test,method_param,base_class', [ ('_walk_moler_python_files', cmd_dir_under_test, Command), ('_walk_moler_commands', cmd_dir_under_test, Command), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command)]) def test_genertors_return_files_without_dunder_init(func2test, method...
func_obj = _load_obj(func_name=func2test) generator_obj = func_obj(method_param, base_class) file_list = _list_in_path(listing_type='allfiles') with raises(StopIteration): for _ in range(len(file_list)): next(generator_obj)
@mark.parametrize('func2test,method_param,base_class', [ ('_walk_moler_python_files', cmd_dir_under_test, Command), ('_walk_moler_commands', cmd_dir_under_test, Command), ('_walk_moler_nonabstract_commands', cmd_dir_under_test, Command)]) def test_genertors_return_files_without_dunder_init(func2test, method...
carr-elagheb/moler
test/test_cmds_events_doc.py
e74b900a7428608c519bec43
function
simple
walk_moler_nonabstract_commands with mock.patch('moler.util.cmds_events_doc._walk_moler_commands', return_value=(None, fake_cmd)): with raises(Exception): next(_walk_moler_nonabstract_commands(cmd_dir_under_test, Command)) def test_retrieve_command_documentation_as_dict():
from moler.util.cmds_events_doc import _retrieve_command_documentation fake_cmd_from_conftest = _retrieve_command_documentation(import_module('conftest'), "COMMAND") assert isinstance(fake_cmd_from_conftest, dict) assert isinstance(fake_cmd_from_conftest['_ver_nice'], dict) assert isinstance(fake_c...
def test_retrieve_command_documentation_as_dict(): from moler.util.cmds_events_doc import _retrieve_command_documentation fake_cmd_from_conftest = _retrieve_command_documentation(import_module('conftest'), "COMMAND") assert isinstance(fake_cmd_from_conftest, dict) assert isinstance(fake_cmd_from_confte...
carr-elagheb/moler
test/test_cmds_events_doc.py
50d134e4f2f18ef85288214d
class
simple
prefix else "", own_keys ) ) def _recursive_check_keys(new_config, old_config, prefix=""): _check_keys(new_config, old_config, prefix) for k, v in new_config.items(): new_prefix = prefix + "/" + k if prefix else k # if isinstance(v, dict): # _recursive_check_ke...
""" This class aims to check whether user config exists if default config system, Mostly, Config is sampled from parameter space in PGDrive Besides, the value type will also be checked, but sometimes the value type is not unique (maybe Union[str, int]). For these <key, value> items, use Config["you...
class Config: """ This class aims to check whether user config exists if default config system, Mostly, Config is sampled from parameter space in PGDrive Besides, the value type will also be checked, but sometimes the value type is not unique (maybe Union[str, int]). For these <key, value> items, u...
decisionforce/pgdrive
pgdrive/utils/config.py
a5fea548b6b15fbb74a43290
class
simple
#!/usr/bin/python3 from __future__ import unicode_literals from adapt.intent import IntentBuilder from mycroft import MycroftSkill, intent_handler import youtube_dl from subprocess import Popen, DEVNULL, STDOUT, CalledProcessError from os import remove class YoutubedlSkill(MycroftSkill):
def __init__(self): super().__init__() self.proc = None self.vid = None self.queue = [] def initialize(self): my_setting = self.settings.get("my_setting") def play_vid(self): if self.proc is not None: self.stop() try: self.pro...
class YoutubedlSkill(MycroftSkill): def __init__(self): super().__init__() self.proc = None self.vid = None self.queue = [] def initialize(self): my_setting = self.settings.get("my_setting") def play_vid(self): if self.proc is not None: self.stop...
bosangeros/mycroft-youtubedl-skill
__init__.py
638ee517e1e6c81d8743daf6
class
simple
_size, self.exp_disk_size) if self.snapshot_count is not None: self.assertEqual(len(image_info.snapshots), self.snapshot_count) def test_qemu_img_info(self): img_info = self._initialize_img_info() if self.garbage_before_snapshot is True: img_info = img_info + ('blah ...
_file_format = [ ('qcow2', dict(file_format='qcow2')), ] _qcow2_cluster_size = [ ('65536', dict(cluster_size='65536', exp_cluster_size=65536)), ] _qcow2_encrypted = [ ('no_encryption', dict(encrypted=None)), ('encrypted', dict(encrypted='yes')), ] _qcow2_ba...
class ImageUtilsQemuTestCase(ImageUtilsRawTestCase): _file_format = [ ('qcow2', dict(file_format='qcow2')), ] _qcow2_cluster_size = [ ('65536', dict(cluster_size='65536', exp_cluster_size=65536)), ] _qcow2_encrypted = [ ('no_encryption', dict(encrypted=None)), ('en...
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
c5da39700ea65cf44a921a7d
class
simple
None: self.assertEqual(image_info.backing_file, self.exp_backing_file) if self.encrypted is not None: self.assertEqual(image_info.encrypted, self.encrypted) ImageUtilsQemuTestCase.generate_scenarios() class ImageUtilsBlankTestCase(test_base.BaseTestCase):...
def test_qemu_img_info_blank(self): example_output = '\n'.join(['image: None', 'file_format: None', 'virtual_size: None', 'disk_size: None', 'cluster_size: None', 'backing_file: None']) image_...
class ImageUtilsBlankTestCase(test_base.BaseTestCase): def test_qemu_img_info_blank(self): example_output = '\n'.join(['image: None', 'file_format: None', 'virtual_size: None', 'disk_size: None', 'cluster_size: None', ...
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
6e4e9977dd1cfc4b1f0b6f27
class
simple
'virtual_size: None', 'disk_size: None', 'cluster_size: None', 'backing_file: None']) image_info = imageutils.QemuImgInfo() self.assertEqual(str(image_info), example_output) self.assertEqual(len(image_info.snapshots), 0) ...
def test_qemu_img_info_json_format(self): img_output = '''{ "virtual-size": 41126400, "filename": "fake_img", "cluster-size": 65536, "format": "qcow2", "actual-size": 13168640 ...
class ImageUtilsJSONTestCase(test_base.BaseTestCase): def test_qemu_img_info_json_format(self): img_output = '''{ "virtual-size": 41126400, "filename": "fake_img", "cluster-size": 65536, "format": "qcow2", ...
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
230cbe79c3ad659dd8dd19b3
class
simple
# Copyright (C) 2012 Yahoo! 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 ...
_image_name = [ ('disk_config', dict(image_name='disk.config')), ] _file_format = [ ('raw', dict(file_format='raw')), ] _virtual_size = [ ('64M', dict(virtual_size='64M', exp_virtual_size=67108864)), ('64M_with_byte_hint', dict(virtual_size='64M...
class ImageUtilsRawTestCase(test_base.BaseTestCase): _image_name = [ ('disk_config', dict(image_name='disk.config')), ] _file_format = [ ('raw', dict(file_format='raw')), ] _virtual_size = [ ('64M', dict(virtual_size='64M', exp_virtual_size=67108864)),...
songhao8080/nova-client
venv/lib/python2.7/site-packages/oslo_utils/tests/test_imageutils.py
7bb0a3913746d20edba9060a
class
simple
except ImportError: HAVE_SSDEEP = False try: import magic except ImportError: pass class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cl...
def __init__(self, event): self.event_id = event['Event']['id'] self.event = event def get_all_ips(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'ip-dst' or a['type'] == 'ip-src'] def get_all_domains(self): return [a['va...
class MispEvent(object): def __init__(self, event): self.event_id = event['Event']['id'] self.event = event def get_all_ips(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'ip-dst' or a['type'] == 'ip-src'] def get_all_domains(se...
vasporig/viper
viper/common/objects.py
e9a0b425aa32da9788154690
class
simple
ms = magic.open(magic.MIME) ms.load() mime_type = ms.file(self.path) except: try: mime = magic.Magic(mime=True) mime_type = mime.from_file(self.path) except: return '' return mime_type class Di...
"""Viper custom dict.""" def __getattr__(self, key): return self.get(key, None) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
class Dictionary(dict): """Viper custom dict.""" def __getattr__(self, key): return self.get(key, None) __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
vasporig/viper
viper/common/objects.py
588076bd2cf31ec44fb8bbad
class
simple
See the file 'LICENSE' for copying permission. import os import hashlib import binascii try: import pydeep HAVE_SSDEEP = True except ImportError: HAVE_SSDEEP = False try: import magic except ImportError: pass class Singleton(type):
_instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]
class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls]
vasporig/viper
viper/common/objects.py
787dc265334e21fed757b7ce
class
simple
'hostname'] def get_all_urls(self): return [a['value'] for a in self.event['Event']['Attribute'] if a['type'] == 'url'] def get_all_hashes(self): event_hashes = [] sample_hashes = [] for a in self.event['Event']['Attribute']: h = None if a['type'] in ('...
def __init__(self, path): self.id = None self.path = path self.name = '' self.size = 0 self.type = '' self.mime = '' self.md5 = '' self.sha1 = '' self.sha256 = '' self.sha512 = '' self.crc32 = '' self.ssdeep = '' ...
class File(object): def __init__(self, path): self.id = None self.path = path self.name = '' self.size = 0 self.type = '' self.mime = '' self.md5 = '' self.sha1 = '' self.sha256 = '' self.sha512 = '' self.crc32 = '' sel...
vasporig/viper
viper/common/objects.py
e907e0ffcba147001684451b
class
simple
and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, dis- # tribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, sub...
""" This is the AWS Data Pipeline API Reference . This guide provides descriptions and samples of the AWS Data Pipeline API. AWS Data Pipeline is a web service that configures and manages a data-driven workflow called a pipeline. AWS Data Pipeline handles the details of scheduling and ens...
class DataPipelineConnection(AWSQueryConnection): """ This is the AWS Data Pipeline API Reference . This guide provides descriptions and samples of the AWS Data Pipeline API. AWS Data Pipeline is a web service that configures and manages a data-driven workflow called a pipeline. AWS Data Pipe...
Rome84/AWS
datapipeline/layer1.py
ff1e2924876f96e62c622f55
class
simple
complex for some models) Attribute: u (Parameter): torch container packaging disentangler tensor u u.leg_type (tuple): a pair of int number indicating the number of in and out bonds of u ((2, 2) for u) """ def __init__(self, chi_in, chi_out, dtype): assert chi_in > 0 and chi_out > 0...
r"""single layer for ternary MERA. Args: chi_in (int): dimension of in (bottom) bond chi_out (int): dimension of out (upper) bond leg_type (tuple): a pair of int number indicating the number of in and out bonds of w (default: (3, 1)) dtype (tensor.dtype): data type (may be comple...
class SimpleTernary(SimpleLayer): r"""single layer for ternary MERA. Args: chi_in (int): dimension of in (bottom) bond chi_out (int): dimension of out (upper) bond leg_type (tuple): a pair of int number indicating the number of in and out bonds of w (default: (3, 1)) dtype (tenso...
xwkgch/IsoTensor
layer/MERAlayer.py
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
33