本文整理汇总了Python中contextlib2.ExitStack方法的典型用法代码示例。如果您正苦于以下问题:Python contextlib2.ExitStack方法的具体用法?Python contextlib2.ExitStack怎么用?Python contextlib2.ExitStack使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类contextlib2
的用法示例。
在下文中一共展示了contextlib2.ExitStack方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: on_draw
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def on_draw():
window.clear()
with ExitStack() as stack:
for shader in [rc.resources.shadow_shader, rc.default_shader]:
with shader, rc.default_states, light, rc.default_camera:
if shader == rc.resources.shadow_shader:
stack.enter_context(fbo_shadow)
window.clear()
else:
stack.close()
for x, y in it.product([-2, -1, 0, 1, 2], [-2, -1, 0, 1, 2]):
monkey.position.x = x
monkey.position.y = y
monkey.drawmode = rc.GL_POINTS if x % 2 and y % 2 else rc.GL_TRIANGLES
monkey.uniforms['diffuse'][0] = (x + 1) / 4.
monkey.uniforms['diffuse'][1:] = (y + 1) / 4.
monkey.scale.z = np.linalg.norm((x, y)) / 10. + .03
monkey.draw()
plane.draw()
fps_display.draw()
示例2: setup_remotes
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def setup_remotes(remote_metadata_list, pyro_port, pyro_key):
"""
:param remote_metadata_list: list of dictionaries, each containing:
"script" - python script to run
"name" - name used to register with Pyro nameserver
"gpu_id" - GPU ID to run on
"""
with NameServerSP(key=pyro_key, port=pyro_port) as _:
with contextlib2.ExitStack() as stack:
for metadata in remote_metadata_list:
stack.enter_context(remoteSP(metadata['script'],
key=pyro_key,
name=metadata['name'],
port=pyro_port,
gpu_id=metadata['gpu_id']))
print 'sleeping extra...'
time.sleep(20) #TODO: why do I need this now?
print 'assuming everything is ready to use now' # This is a bad assumption. Can we check this?
yield
示例3: patch
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def patch(option, *patches, **kwargs):
negate = kwargs.get('negate', False)
@pytest.yield_fixture(autouse=True, scope='session')
def patch_conditionally(request):
condition = bool(request.config.getoption(option))
if negate:
condition = not condition
if condition:
with contextlib.ExitStack() as exit_stack:
for patch in patches:
exit_stack.enter_context(patch)
yield
else:
yield
return patch_conditionally
示例4: main
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def main(_):
record_files = list_records(FLAGS.path_to_records)
logging.debug(
"Number of records to be processed: {}".format(len(record_files)))
next_example = read_records(record_files, shuffle=FLAGS.shuffle)
# To maximize file I/O throughout, split the training data into pieces.
with contextlib2.ExitStack() as tf_record_close_stack:
output_records = tf_record_creation_util.open_sharded_output_tfrecords(
tf_record_close_stack, FLAGS.output_file, FLAGS.num_shards)
with tf.Session() as sess:
index = 0
while True:
try:
serialized_example = sess.run(next_example)
index += 1
output_shard_index = index % FLAGS.num_shards
output_records[output_shard_index].write(
serialized_example)
logging.debug("Samples processed: {}".format(index))
except tf.errors.OutOfRangeError:
break
示例5: test_show_csv
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_show_csv():
import dtale
csv_path = "/../".join([os.path.dirname(__file__), "data/test_df.csv"])
with mock.patch("dtale.app.show", mock.Mock()):
dtale.show_csv(path=csv_path)
with open(csv_path, "r") as f:
csv_txt = f.read()
with ExitStack() as stack:
stack.enter_context(mock.patch("dtale.app.show", mock.Mock()))
class MockRequest(object):
def __init__(self):
self.content = csv_txt.encode() if PY3 else csv_txt
self.status_code = 200
stack.enter_context(
mock.patch("requests.get", mock.Mock(return_value=MockRequest()))
)
dtale.show_csv(path="http://test-csv")
dtale.show_csv(path="http://test-csv", proxy="http://test-proxy")
示例6: test_delete_col
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_delete_col():
from dtale.views import build_dtypes_state
df = pd.DataFrame([dict(a=1, b=2, c=3)])
with app.test_client() as c:
with ExitStack() as stack:
data = {c.port: df}
stack.enter_context(mock.patch("dtale.global_state.DATA", data))
settings = {c.port: {"locked": ["a"]}}
stack.enter_context(mock.patch("dtale.global_state.SETTINGS", settings))
dtypes = {c.port: build_dtypes_state(df)}
stack.enter_context(mock.patch("dtale.global_state.DTYPES", dtypes))
c.get("/dtale/delete-col/{}/a".format(c.port))
assert "a" not in data[c.port].columns
assert (
next((dt for dt in dtypes[c.port] if dt["name"] == "a"), None) is None
)
assert len(settings[c.port]["locked"]) == 0
resp = c.get("/dtale/delete-col/-1/d")
assert "error" in json.loads(resp.data)
示例7: test_update_visibility
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_update_visibility(unittest):
from dtale.views import build_dtypes_state
df = pd.DataFrame([dict(a=1, b=2, c=3)])
with app.test_client() as c:
dtypes = {c.port: build_dtypes_state(df)}
with ExitStack() as stack:
stack.enter_context(mock.patch("dtale.global_state.DATA", {c.port: df}))
stack.enter_context(mock.patch("dtale.global_state.DTYPES", dtypes))
c.post(
"/dtale/update-visibility/{}".format(c.port),
data=dict(visibility=json.dumps({"a": True, "b": True, "c": False})),
)
unittest.assertEqual(
[True, True, False], [col["visible"] for col in dtypes[c.port]]
)
c.post("/dtale/update-visibility/{}".format(c.port), data=dict(toggle="c"))
unittest.assertEqual(
[True, True, True], [col["visible"] for col in dtypes[c.port]]
)
resp = c.post("/dtale/update-visibility/-1", data=dict(toggle="foo"))
assert "error" in json.loads(resp.data)
示例8: test_302
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_302():
import dtale.views as views
df = pd.DataFrame([1, 2, 3])
df, _ = views.format_data(df)
with app.test_client() as c:
with ExitStack() as stack:
stack.enter_context(mock.patch("dtale.global_state.DATA", {c.port: df}))
stack.enter_context(
mock.patch(
"dtale.global_state.DTYPES", {c.port: views.build_dtypes_state(df)}
)
)
for path in [
"/",
"/dtale",
"/dtale/main",
"/dtale/iframe",
"/dtale/popup/test",
"/favicon.ico",
]:
response = c.get(path)
assert (
response.status_code == 302
), "{} should return 302 response".format(path)
示例9: test_convert
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_convert():
from dtale.views import startup
from tests.dtale.test_replacements import replacements_data
with app.test_client() as c:
with ExitStack() as stack:
data, dtypes, datasets, dataset_dim, settings = {}, {}, {}, {}, {}
stack.enter_context(mock.patch("dtale.global_state.DATA", data))
stack.enter_context(mock.patch("dtale.global_state.DTYPES", dtypes))
stack.enter_context(mock.patch("dtale.global_state.DATASETS", datasets))
stack.enter_context(
mock.patch("dtale.global_state.DATASET_DIM", dataset_dim)
)
stack.enter_context(mock.patch("dtale.global_state.SETTINGS", settings))
startup(URL, data=replacements_data(), data_id=c.port)
resp = c.get(
"/dtale/to-xarray/{}".format(c.port),
query_string=dict(index=json.dumps(["a"])),
)
assert resp.status_code == 200
assert c.port in datasets
assert settings[c.port]["locked"] == ["a"]
示例10: test_spaces
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_spaces(unittest):
df = replacements_data()
data_id, replacement_type = "1", "spaces"
with ExitStack() as stack:
stack.enter_context(mock.patch("dtale.global_state.DATA", {data_id: df}))
builder = ColumnReplacement(data_id, "b", replacement_type, {})
verify_builder(
builder,
lambda col: unittest.assertEqual(list(col.values), ["", np.nan, " - "]),
)
builder = ColumnReplacement(data_id, "b", replacement_type, {"value": "blah"})
verify_builder(
builder,
lambda col: unittest.assertEqual(list(col.values), ["", "blah", " - "]),
)
示例11: test_build_startup_url_and_app_root
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_build_startup_url_and_app_root():
from dtale.app import build_startup_url_and_app_root
with ExitStack() as stack:
stack.enter_context(mock.patch("dtale.app.JUPYTER_SERVER_PROXY", True))
stack.enter_context(mock.patch("dtale.app.ACTIVE_PORT", 40000))
stack.enter_context(mock.patch("dtale.app.ACTIVE_HOST", "localhost"))
url, app_root = build_startup_url_and_app_root()
assert url == "/user/{}/proxy/40000".format(getpass.getuser())
assert app_root == "/user/{}/proxy/40000".format(getpass.getuser())
url, app_root = build_startup_url_and_app_root("/test_route/")
assert url == "/test_route/40000"
assert app_root == "/test_route/40000"
with ExitStack() as stack:
stack.enter_context(mock.patch("dtale.app.JUPYTER_SERVER_PROXY", False))
stack.enter_context(mock.patch("dtale.app.ACTIVE_PORT", 40000))
stack.enter_context(mock.patch("dtale.app.ACTIVE_HOST", "localhost"))
url, app_root = build_startup_url_and_app_root()
assert url == "http://localhost:40000"
assert app_root is None
url, app_root = build_startup_url_and_app_root("/test_route/")
assert url == "http:/localhost:40000/test_route/"
assert app_root == "/test_route/"
示例12: test_query_changes
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_query_changes():
import dtale.views as views
df = pd.DataFrame(dict(a=[1, 2, 3], b=[4, 5, 6], c=[7, 8, 9]))
with app.test_client() as c:
with ExitStack() as stack:
df, _ = views.format_data(df)
stack.enter_context(mock.patch("dtale.global_state.DATA", {c.port: df}))
pathname = path_builder(c.port)
params = {
"output": "..query-data.data...query-input.style...query-input.title..",
"changedPropIds": ["query-input.value"],
"inputs": [{"id": "query-input", "property": "value", "value": "d"}],
"state": [pathname, {"id": "query-data", "property": "data"}],
}
response = c.post("/charts/_dash-update-component", json=params)
resp_data = response.get_json()["response"]
assert resp_data["query-data"]["data"] is None
assert resp_data["query-input"]["title"] == "name 'd' is not defined"
params["inputs"][0]["value"] = "a == 1"
response = c.post("/charts/_dash-update-component", json=params)
resp_data = response.get_json()["response"]
assert resp_data["query-data"]["data"] == "a == 1"
示例13: test_sharded_tfrecord_writes
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def test_sharded_tfrecord_writes(self):
with contextlib2.ExitStack() as tf_record_close_stack:
output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords(
tf_record_close_stack,
os.path.join(tf.test.get_temp_dir(), 'test.tfrec'), 10)
for idx in range(10):
output_tfrecords[idx].write('test_{}'.format(idx))
for idx in range(10):
tf_record_path = '{}-{:05d}-of-00010'.format(
os.path.join(tf.test.get_temp_dir(), 'test.tfrec'), idx)
records = list(tf.python_io.tf_record_iterator(tf_record_path))
self.assertAllEqual(records, ['test_{}'.format(idx)])
示例14: setUp
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def setUp(self):
self.fixtures = ExitStack()
self.addCleanup(self.fixtures.close)
self.site_dir = self.fixtures.enter_context(tempdir())
示例15: setUp
# 需要导入模块: import contextlib2 [as 别名]
# 或者: from contextlib2 import ExitStack [as 别名]
def setUp(self):
# Find the path to the example-*.whl so we can add it to the front of
# sys.path, where we'll then try to find the metadata thereof.
self.resources = ExitStack()
self.addCleanup(self.resources.close)
wheel = self.resources.enter_context(
path(self.root, 'example-21.12-py3-none-any.whl'))
sys.path.insert(0, str(wheel))
self.resources.callback(sys.path.pop, 0)