content stringlengths 0 1.55M |
|---|
<import_stmt>rebase<import_stmt>partition<line_sep> |
<import_stmt>angr<line_sep>######################################
# accept (but not really)
######################################
<class_stmt>accept(angr.SimProcedure)#pylint:disable=arguments-differ
<block_start><def_stmt>run self sockfd addr addrlen<block_start>conc_addrlen=self.state.mem[addrlen].int.concrete<line_sep>addr_data=self.state.solver.BVS('accept_addr' conc_addrlen<times>8 key=('api' 'accept' 'addr'))<line_sep>self.state.memory.store(addr addr_data)<line_sep>ident='unknown'<if_stmt><not>sockfd.symbolic<block_start>sockfd=self.state.solver.eval(sockfd)<if_stmt>sockfd<in>self.state.posix.fd<block_start>simsockfd=self.state.posix.fd[sockfd]<for_stmt>potential_ident self.state.posix.sockets<block_start><if_stmt>self.state.posix.sockets[potential_ident][0]<is>simsockfd.read_storage<and>self.state.posix.sockets[potential_ident][1]<is>simsockfd.write_storage<block_start>ident=potential_ident<line_sep><break><block_end><block_end><block_end><block_end>ident_counters=dict(self.state.globals.get('accept_idents' {}))<line_sep>ident_counters[ident]=ident_counters.get(ident 0)+1<line_sep>self.state.globals['accept_idents']=ident_counters<line_sep>fd=self.state.posix.open_socket(('accept' ident ident_counters[ident]))<line_sep><return>fd<block_end><block_end> |
<import_stmt>panel<as>pn<def_stmt>test_alert <block_start>my_alert=pn.pane.Alert("foo" alert_type="primary")<line_sep>my_button=pn.widgets.Button(name="Toggle")<def_stmt>toggle event<block_start><if_stmt>my_alert.alert_type<eq>"primary"<block_start>my_alert.alert_type<eq>"success"<block_end><else_stmt><block_start>my_alert.alert_type="primary"<block_end>my_alert.object=my_alert.alert_type<block_end>my_button.on_click(toggle)<line_sep>pn.Row(my_alert my_button).show()<block_end>test_alert()<line_sep> |
<import_stmt>pytest<line_sep>@pytest.fixture(autouse=<true>)<def_stmt>encrypted_settings_mock mocker<block_start>mocker.patch('confidant.settings.encrypted_settings.secret_string' {})<line_sep>mocker.patch('confidant.settings.encrypted_settings.decrypted_secrets' {'SESSION_SECRET':'TEST_KEY'} )<block_end> |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# MIT License for more details.
"""Score model optimum finder."""<import_stmt>random<import_from_stmt>collections OrderedDict<import_from_stmt>typing Set<class_stmt>ModelOptim()<block_start>"""Score model optimum finder class."""<def_stmt>__init__ self space<block_start>self.space=space<block_end><def_stmt>get_random_index self excludes:Set[int]<arrow>int<block_start>"""Return random categorical index from search space."""<line_sep>index=random.randint(0 self.space.categorical_size()-1)<while_stmt>index<in>excludes<block_start>index=random.randint(0 self.space.categorical_size()-1)<block_end><return>index<block_end><def_stmt>get_random_params self excludes:Set[int]<arrow>OrderedDict<block_start>"""Return random categorical parameters from search space."""<line_sep><return>self.space.get_categorical_params(self.get_random_index(excludes))<block_end><def_stmt>get_optimums self model size excludes<block_start>"""Return optimums in score model."""<line_sep><raise>NotImplementedError<block_end><block_end> |
<try_stmt><block_start><import_from_stmt>. generic<as>g<block_end><except_stmt>BaseException<block_start><import_stmt>generic<as>g<block_end><class_stmt>AdjacencyTest(g.unittest.TestCase)<block_start><def_stmt>test_radius self<block_start><for_stmt>radius [0.1 1.0 3.1459 29.20]<block_start>m=g.trimesh.creation.cylinder(radius=radius height=radius<times>10)<line_sep># remove the cylinder cap
signs=(g.np.sign(m.vertices[: 2])<l>0)[m.faces]<line_sep>not_cap=~g.np.logical_or(signs.all(axis=1) ~signs.any(axis=1))<line_sep>m.update_faces(not_cap)<line_sep># compare the calculated radius
radii=m.face_adjacency_radius<line_sep>radii=radii[g.np.isfinite(radii)]<assert_stmt>g.np.allclose(radii radius atol=radius/100)<block_end><block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>g.trimesh.util.attach_to_log()<line_sep>g.unittest.main()<block_end> |
# -*- coding: utf-8 -*-
<import_from_future_stmt> unicode_literals<import_stmt>sys<import_stmt>pytest<import_from_stmt>clastic.contrib.obj_browser create_app<line_sep>_IS_PYPY='__pypy__'<in>sys.builtin_module_names<line_sep>@pytest.mark.skipif(_IS_PYPY reason='pypy gc cannot support obj browsing')<def_stmt>test_flaw_basic <block_start>app=create_app()<line_sep>cl=app.get_local_client()<line_sep>resp=cl.get('/')<assert_stmt>resp.status_code<eq>302# take me to the default
resp=cl.get('/' follow_redirects=<true>)<assert_stmt>resp.status_code<eq>200# default should be sys
<assert_stmt>'modules'<in>resp.get_data(<true>)<block_end> |
<import_stmt>datetime<import_stmt>io<import_stmt>json<import_stmt>zipfile<import_from_stmt>pathlib Path<import_stmt>pyrsistent<import_stmt>pytest<import_stmt>yaml<import_from_stmt>aiohttp web<import_from_stmt>openapi_core.shortcuts create_spec<import_from_stmt>yarl URL<import_from_stmt>rororo BaseSettings get_openapi_context get_openapi_schema get_openapi_spec openapi_context OperationTableDef setup_openapi setup_settings_from_environ <import_from_stmt>rororo.annotations DictStrAny<import_from_stmt>rororo.openapi get_validated_data<import_from_stmt>rororo.openapi.exceptions ConfigurationError OperationError validation_error_context ValidationError <line_sep>ROOT_PATH=Path(__file__).parent<line_sep>INVALID_OPENAPI_JSON_PATH=ROOT_PATH/"invalid-openapi.json"<line_sep>INVALID_OPENAPI_YAML_PATH=ROOT_PATH/"invalid-openapi.yaml"<line_sep>OPENAPI_JSON_PATH=ROOT_PATH/"openapi.json"<line_sep>OPENAPI_YAML_PATH=ROOT_PATH/"openapi.yaml"<line_sep>TEST_NESTED_OBJECT={"uid":"6fccda1b-0873-4c8a-bceb-a2acfe5851da" "type":"nested-object" "data":{"data_item":{"key":"value1" "any_data":{}} "data_items":[{"key":"value2" "any_data":{"two":2}} {"key":"value3" "any_data":{"three":3}} ] "str_items":["1" "2" "3"] } "any_data":{"key1":"value1" "key2":"value2" "list":[1 2 3]} }<line_sep>operations=OperationTableDef()<line_sep>invalid_operations=OperationTableDef()<def_stmt>custom_json_loader content:bytes<arrow>DictStrAny<block_start><return>json.load(io.BytesIO(content))<block_end><def_stmt>custom_yaml_loader content:bytes<arrow>DictStrAny<block_start><return>yaml.load(content Loader=yaml.SafeLoader)<block_end>@invalid_operations.register("does-not-exist")<async_keyword><def_stmt>does_not_exist request:web.Request<arrow>web.Response<block_start><return>web.Response(text="Hello, world!")<block_end>@operations.register("create-post")<async_keyword><def_stmt>create_post request:web.Request<arrow>web.Response<block_start>data=get_validated_data(request)<line_sep>published_at:datetime.datetime=data["published_at"]<with_stmt>validation_error_context("body" "published_at")<block_start><if_stmt>published_at.tzinfo<is><none><block_start><raise>ValidationError(message="Invalid value")<block_end><block_end><return>web.json_response({**data "id":1 "published_at":data["published_at"].isoformat()} status=201 )<block_end>@operations.register<async_keyword><def_stmt>hello_world request:web.Request<arrow>web.Response<block_start><with_stmt>openapi_context(request)<as>context<block_start>name=context.parameters.query.get("name")<or>"world"<line_sep>email=context.parameters.query.get("email")<or>"<EMAIL>"<line_sep><return>web.json_response({"message":f"Hello, {name}!" "email":email})<block_end><block_end>@operations.register<async_keyword><def_stmt>retrieve_any_object_from_request_body request:web.Request <arrow>web.Response<block_start><return>web.json_response(pyrsistent.thaw(get_validated_data(request)))<block_end>@operations.register<async_keyword><def_stmt>retrieve_array_from_request_body request:web.Request <arrow>web.Response<block_start><with_stmt>openapi_context(request)<as>context<block_start><return>web.json_response(pyrsistent.thaw(context.data))<block_end><block_end>@operations.register<async_keyword><def_stmt>retrieve_empty request:web.Request<arrow>web.Response<block_start>context=get_openapi_context(request)<line_sep><return>web.Response(status=204 headers={"X-API-Key":context.security.get("apiKey")<or>""})<block_end>@operations.register<async_keyword><def_stmt>retrieve_invalid_response request:web.Request<arrow>web.Response<block_start><return>web.json_response({})<block_end>@operations.register<async_keyword><def_stmt>retrieve_post request:web.Request<arrow>web.Response<block_start>context=get_openapi_context(request)<line_sep><return>web.json_response({"id":context.parameters.path["post_id"] "title":"The Post"})<block_end>@operations.register<async_keyword><def_stmt>retrieve_nested_object_from_request_body request:web.Request <arrow>web.Response<block_start><with_stmt>openapi_context(request)<as>context<block_start>data=pyrsistent.thaw(context.data)<line_sep>data["uid"]=str(data["uid"])<line_sep><return>web.json_response(data headers={"X-Data-Type":str(type(context.data)) "X-Data-Data-Data-Items-Type":str(type(context.data["data"]["data_items"])) "X-Data-Data-Str-Items-Type":str(type(context.data["data"]["str_items"])) "X-Data-UID-Type":str(type(context.data["uid"])) } )<block_end><block_end>@operations.register<async_keyword><def_stmt>retrieve_zip request:web.Request<arrow>web.Response<block_start>output=io.BytesIO()<with_stmt>zipfile.ZipFile(output "w")<as>handler<block_start>handler.writestr("hello.txt" "Hello, world!")<block_end>output.seek(0)<line_sep><return>web.Response(body=output content_type="application/zip" headers={"Content-Disposition":"attachment; filename=hello.zip"} )<block_end>@operations.register<async_keyword><def_stmt>upload_image request:web.Request<arrow>web.Response<block_start><return>web.Response(body=get_openapi_context(request).data content_type=request.content_type status=201 )<block_end>@operations.register<async_keyword><def_stmt>upload_text request:web.Request<arrow>web.Response<block_start><return>web.Response(text=get_openapi_context(request).data content_type=request.content_type status=201 )<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_any_object_request_body aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url=URL("/api/"))<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.post("/api/any-object" json=TEST_NESTED_OBJECT)<assert_stmt>response.status<eq>200<assert_stmt><await>response.json()<eq>TEST_NESTED_OBJECT<block_end>@pytest.mark.parametrize("data, expected_status, expected_response" (({} 422 {"detail":[{"loc":["body"] "message":"[] is too short"}]} ) ([] 422 {"detail":[{"loc":["body"] "message":"[] is too short"}]} ) ([""] 422 {"detail":[{"loc":["body" 0] "message":"'' is too short"}]} ) (["Hello" "world!"] 200 ["Hello" "world!"]) ) )<async_keyword><def_stmt>test_array_request_body aiohttp_client data expected_status expected_response<block_start>app=setup_openapi(web.Application() OPENAPI_YAML_PATH operations server_url=URL("/api") )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.post("/api/array" json=data)<assert_stmt>response.status<eq>expected_status<assert_stmt><await>response.json()<eq>expected_response<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_create_post_201 aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api/")<line_sep>published_at="2020-04-01T12:00:00+02:00"<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.post("/api/create-post" json={"title":"Post" "slug":"post" "content":"Post Content" "published_at":published_at } )<assert_stmt>response.status<eq>201<assert_stmt><await>response.json()<eq>{"id":1 "title":"Post" "slug":"post" "content":"Post Content" "published_at":published_at }<block_end>@pytest.mark.parametrize("schema_path, invalid_data, expected_detail" ((OPENAPI_JSON_PATH {} [{"loc":["body" "title"] "message":"Field required"} {"loc":["body" "slug"] "message":"Field required"} {"loc":["body" "content"] "message":"Field required"} {"loc":["body" "published_at"] "message":"Field required"} ] ) (OPENAPI_YAML_PATH {"title":"Title"} [{"loc":["body" "slug"] "message":"Field required"} {"loc":["body" "content"] "message":"Field required"} {"loc":["body" "published_at"] "message":"Field required"} ] ) (OPENAPI_JSON_PATH {"title":"Title" "slug":"slug"} [{"loc":["body" "content"] "message":"Field required"} {"loc":["body" "published_at"] "message":"Field required"} ] ) (OPENAPI_YAML_PATH {"title":"Title" "slug":"slug" "content":"Content"} [{"loc":["body" "published_at"] "message":"Field required"}] ) ) )<async_keyword><def_stmt>test_create_post_422 aiohttp_client schema_path invalid_data expected_detail<block_start>app=setup_openapi(web.Application() schema_path operations server_url=URL("/dev-api") )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.post("/dev-api/create-post" json=invalid_data)<assert_stmt>response.status<eq>422<assert_stmt>(<await>response.json())["detail"]<eq>expected_detail<block_end>@pytest.mark.parametrize("schema_path, schema_loader" ((OPENAPI_JSON_PATH custom_json_loader) (OPENAPI_YAML_PATH custom_yaml_loader) ) )<def_stmt>test_custom_schema_loader schema_path schema_loader<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api/" schema_loader=schema_loader )<assert_stmt>isinstance(get_openapi_schema(app) dict)<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_email_format aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api/")<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/hello" params={"email":"<EMAIL>"})<assert_stmt>response.status<eq>200<assert_stmt>(<await>response.json())["email"]<eq>"<EMAIL>"<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_invalid_parameter_format aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api/")<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/posts/not-an-integer")<assert_stmt>response.status<eq>422<assert_stmt><await>response.json()<eq>{"detail":[{"loc":["parameters" "post_id"] "message":"'not-an-integer' is not a type of 'integer'" }]}<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_invalid_parameter_value aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api/")<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/posts/0")<assert_stmt>response.status<eq>422<assert_stmt><await>response.json()<eq>{"detail":[{"loc":["parameters" "post_id"] "message":"0 is less than the minimum of 1" }]}<block_end><def_stmt>test_get_openapi_schema_no_schema <block_start><with_stmt>pytest.raises(ConfigurationError)<block_start>get_openapi_schema(web.Application())<block_end><block_end><def_stmt>test_get_openapi_spec_no_spec <block_start><with_stmt>pytest.raises(ConfigurationError)<block_start>get_openapi_spec(web.Application())<block_end><block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_multiple_request_errors aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api/")<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/hello?name=&email=")<assert_stmt>response.status<eq>422<assert_stmt><await>response.json()<eq>{"detail":[{"loc":["parameters" "name"] "message":"Empty parameter value" } {"loc":["parameters" "email"] "message":"Empty parameter value" } ]}<block_end>@pytest.mark.parametrize("schema_path, query_string, expected_message" ((OPENAPI_JSON_PATH <none> "Hello, world!") (OPENAPI_JSON_PATH "?name=Name" "Hello, Name!") (str(OPENAPI_JSON_PATH) <none> "Hello, world!") (str(OPENAPI_JSON_PATH) "?name=Name" "Hello, Name!") (OPENAPI_YAML_PATH <none> "Hello, world!") (OPENAPI_YAML_PATH "?name=Name" "Hello, Name!") (str(OPENAPI_YAML_PATH) <none> "Hello, world!") (str(OPENAPI_YAML_PATH) "?name=Name" "Hello, Name!") ) )<async_keyword><def_stmt>test_openapi aiohttp_client schema_path query_string expected_message<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api")<line_sep>client=<await>aiohttp_client(app)<line_sep>url="/api/hello"<line_sep>response=<await>client.get(f"{url}{query_string}"<if>query_string<is><not><none><else>url)<assert_stmt>response.status<eq>200<assert_stmt>(<await>response.json())["message"]<eq>expected_message<block_end>@pytest.mark.parametrize("is_enabled" (<false> <true>))<async_keyword><def_stmt>test_openapi_validate_response aiohttp_client is_enabled<block_start>app=web.Application()<line_sep>setup_openapi(app OPENAPI_YAML_PATH operations server_url="/api" is_validate_response=is_enabled )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/hello")<assert_stmt>response.status<eq>200<assert_stmt><await>response.json()<eq>{"message":"Hello, world!" "email":"<EMAIL>" }<block_end>@pytest.mark.parametrize("has_openapi_schema_handler, url, expected_status" ((<true> "/api/openapi.json" 200) (<false> "/api/openapi.yaml" 404) (<true> "/api/openapi.yaml" 200) (<false> "/api/openapi.yaml" 404) (<true> "/api/openapi.txt" 500) (<false> "/api/openapi.txt" 404) ) )<async_keyword><def_stmt>test_openapi_schema_handler aiohttp_client has_openapi_schema_handler url expected_status<block_start>app=web.Application()<line_sep>setup_openapi(app OPENAPI_YAML_PATH operations server_url=URL("/api") has_openapi_schema_handler=has_openapi_schema_handler )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get(url)<assert_stmt>response.status<eq>expected_status<block_end>@pytest.mark.parametrize("schema_path, headers, expected" ((OPENAPI_JSON_PATH {} "") (OPENAPI_JSON_PATH {"X-API-Key":"apiKey"} "apiKey") (OPENAPI_YAML_PATH {} "") (OPENAPI_YAML_PATH {"X-API-Key":"apiKey"} "apiKey") ) )<async_keyword><def_stmt>test_optional_security_scheme aiohttp_client schema_path headers expected<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api/")<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/empty" headers=headers)<assert_stmt>response.status<eq>204<assert_stmt>response.headers["X-API-Key"]<eq>expected<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_request_body_nested_object aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api/")<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.post("/api/nested-object" json=TEST_NESTED_OBJECT)<assert_stmt>response.status<eq>200<assert_stmt>response.headers["X-Data-Type"]<eq>"<class 'pyrsistent._pmap.PMap'>"<assert_stmt>(response.headers["X-Data-Data-Data-Items-Type"]<eq>"<class 'pvectorc.PVector'>")<assert_stmt>(response.headers["X-Data-Data-Str-Items-Type"]<eq>"<class 'pvectorc.PVector'>")<assert_stmt>response.headers["X-Data-UID-Type"]<eq>"<class 'uuid.UUID'>"<assert_stmt><await>response.json()<eq>TEST_NESTED_OBJECT<block_end>@pytest.mark.parametrize("schema_path, loader" ((OPENAPI_JSON_PATH custom_json_loader) (OPENAPI_YAML_PATH custom_yaml_loader) ) )<async_keyword><def_stmt>test_setup_openapi_schema_and_spec aiohttp_client schema_path loader<block_start>schema=loader(schema_path.read_bytes())<line_sep>spec=create_spec(schema)<line_sep>app=setup_openapi(web.Application() operations schema=schema spec=spec server_url="/api/" )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/hello")<assert_stmt>response.status<eq>200<assert_stmt><await>response.json()<eq>{"message":"Hello, world!" "email":"<EMAIL>" }<block_end>@pytest.mark.parametrize("schema_path, loader" ((OPENAPI_JSON_PATH custom_json_loader) (OPENAPI_YAML_PATH custom_yaml_loader) ) )<async_keyword><def_stmt>test_setup_openapi_schema_and_path_ignore_invalid_schema_path aiohttp_client schema_path loader<block_start>schema=loader(schema_path.read_bytes())<line_sep>spec=create_spec(schema)<line_sep>setup_openapi(web.Application() INVALID_OPENAPI_JSON_PATH operations schema=schema spec=spec server_url="/api/" )<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<def_stmt>test_setup_openapi_invalid_operation schema_path<block_start><with_stmt>pytest.raises(OperationError)<block_start>setup_openapi(web.Application() schema_path invalid_operations server_url="/api" )<block_end><block_end><def_stmt>test_setup_openapi_invalid_path <block_start><with_stmt>pytest.raises(ConfigurationError)<block_start>setup_openapi(web.Application() ROOT_PATH/"does-not-exist.yaml" operations)<block_end><block_end><def_stmt>test_setup_openapi_invalid_file <block_start><with_stmt>pytest.raises(ConfigurationError)<block_start>setup_openapi(web.Application() ROOT_PATH/"settings.py" operations)<block_end><block_end>@pytest.mark.parametrize("schema_path" (INVALID_OPENAPI_JSON_PATH INVALID_OPENAPI_YAML_PATH))<def_stmt>test_setup_openapi_invalid_spec schema_path<block_start><with_stmt>pytest.raises(ConfigurationError)<block_start>setup_openapi(web.Application() schema_path operations)<block_end><block_end>@pytest.mark.parametrize("schema_path, level, url, expected_status" ((OPENAPI_JSON_PATH "test" "/api/hello" 200) (OPENAPI_JSON_PATH "test" "/dev-api/hello" 404) (OPENAPI_YAML_PATH "test" "/api/hello" 200) (OPENAPI_YAML_PATH "test" "/dev-api/hello" 404) (OPENAPI_JSON_PATH "dev" "/api/hello" 404) (OPENAPI_JSON_PATH "dev" "/dev-api/hello" 200) (OPENAPI_YAML_PATH "dev" "/api/hello" 404) (OPENAPI_YAML_PATH "dev" "/dev-api/hello" 200) ) )<async_keyword><def_stmt>test_setup_openapi_server_url_from_settings monkeypatch aiohttp_client schema_path level url expected_status<block_start>monkeypatch.setenv("LEVEL" level)<line_sep>app=setup_openapi(setup_settings_from_environ(web.Application() BaseSettings) schema_path operations )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get(url)<assert_stmt>response.status<eq>expected_status<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<def_stmt>test_setup_openapi_server_url_invalid_level monkeypatch schema_path<block_start>monkeypatch.setenv("LEVEL" "prod")<with_stmt>pytest.raises(ConfigurationError)<block_start>setup_openapi(setup_settings_from_environ(web.Application() BaseSettings) schema_path operations )<block_end><block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<def_stmt>test_setup_openapi_server_url_does_not_set schema_path<block_start><with_stmt>pytest.raises(ConfigurationError)<block_start>setup_openapi(web.Application() schema_path operations)<block_end><block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_upload_image aiohttp_client schema_path<block_start>blank_png=(Path(__file__).parent/"data"/"blank.png").read_bytes()<line_sep>app=setup_openapi(web.Application() schema_path operations server_url="/api")<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.post("/api/upload-image" data=blank_png headers={"Content-Type":"image/png"} )<assert_stmt>response.status<eq>201<assert_stmt><await>response.read()<eq>blank_png<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_upload_text aiohttp_client schema_path<block_start>text="Hello, world! And other things..."<line_sep>app=setup_openapi(web.Application() schema_path operations server_url="/api")<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.post("/api/upload-text" data=text.encode("utf-8") headers={"Content-Type":"text/plain"} )<assert_stmt>response.status<eq>201<assert_stmt><await>response.text()<eq>text<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_validate_binary_response aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api" is_validate_response=<true> )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/download.zip")<assert_stmt>response.status<eq>200<assert_stmt>response.content_type<eq>"application/zip"<line_sep>content=io.BytesIO(<await>response.read())<with_stmt>zipfile.ZipFile(content)<as>handler<block_start><with_stmt>handler.open("hello.txt")<as>item<block_start><assert_stmt>item.read()<eq>b"Hello, world!"<block_end><block_end><block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_validate_empty_response aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api" is_validate_response=<true> )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/empty")<assert_stmt>response.status<eq>204<block_end>@pytest.mark.parametrize("schema_path, is_validate_response, expected_status" ((OPENAPI_JSON_PATH <false> 200) (OPENAPI_JSON_PATH <true> 422) (OPENAPI_YAML_PATH <false> 200) (OPENAPI_JSON_PATH <true> 422) ) )<async_keyword><def_stmt>test_validate_response aiohttp_client schema_path is_validate_response expected_status<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api" is_validate_response=is_validate_response )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/invalid-response")<assert_stmt>response.status<eq>expected_status<block_end>@pytest.mark.parametrize("schema_path" (OPENAPI_JSON_PATH OPENAPI_YAML_PATH))<async_keyword><def_stmt>test_validate_response_error aiohttp_client schema_path<block_start>app=setup_openapi(web.Application() schema_path operations server_url="/api" is_validate_response=<true> )<line_sep>client=<await>aiohttp_client(app)<line_sep>response=<await>client.get("/api/invalid-response")<assert_stmt>response.status<eq>422<assert_stmt><await>response.json()<eq>{"detail":[{"loc":["response" "uid"] "message":"Field required"} {"loc":["response" "type"] "message":"Field required"} {"loc":["response" "data"] "message":"Field required"} {"loc":["response" "any_data"] "message":"Field required"} ]}<block_end> |
# Copyright 2019 TerraPower, 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.
"""
Inconel600
"""<import_stmt>numpy<import_from_stmt>armi.utils.units getTc<import_from_stmt>armi.materials.material Material<class_stmt>Inconel600(Material)<block_start>name="Inconel600"<line_sep>references={"mass fractions":"http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf" "density":"http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf" "thermalConductivity":"http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf" "specific heat":"http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf" "linear expansion percent":"http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf" "linear expansion":"http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf" }<def_stmt>__init__ self<block_start>Material.__init__(self)<line_sep>self.p.refTempK=294.15<line_sep>self.p.refDens=8.47<block_end># g/cc
# Only density measurement presented in the reference.
# Presumed to be performed at 21C since this was the reference temperature for linear expansion measurements.
<def_stmt>setDefaultMassFracs self<block_start>massFracs={"NI":0.7541 "CR":0.1550 "FE":0.0800 "C":0.0008 "MN55":0.0050 "S":0.0001 "SI":0.0025 "CU":0.0025 }<for_stmt>element,massFrac massFracs.items()<block_start>self.setMassFrac(element massFrac)<block_end><block_end><def_stmt>polyfitThermalConductivity self power=2<block_start>r"""
Calculates the coefficients of a polynomial fit for thermalConductivity.
Based on data from http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf
Fits a polynomial to the data set and returns the coefficients.
Parameters
----------
power : int, optional
power of the polynomial fit equation
Returns
-------
list of length 'power' containing the polynomial fit coefficients for thermal conductivity.
"""<line_sep>Tc=[20.0 100.0 200.0 300.0 400.0 500.0 600.0 700.0 800.0]<line_sep>k=[14.9 15.9 17.3 19.0 20.5 22.1 23.9 25.7 27.5]<line_sep><return>numpy.polyfit(numpy.array(Tc) numpy.array(k) power).tolist()<block_end><def_stmt>thermalConductivity self Tk=<none> Tc=<none><block_start>r"""
Returns the thermal conductivity of Inconel600.
Parameters
----------
Tk : float, optional
temperature in (K)
Tc : float, optional
Temperature in (C)
Returns
-------
thermalCond : float
thermal conductivity in W/m/C
"""<line_sep>Tc=getTc(Tc Tk)<line_sep>self.checkTempRange(20.0 800.0 Tc "thermal conductivity")<line_sep>thermalCond=3.4938e-6<times>Tc<power>2+1.3403e-2<times>Tc+14.572<line_sep><return>thermalCond<block_end># W/m-C
<def_stmt>polyfitHeatCapacity self power=2<block_start>r"""
Calculates the coefficients of a polynomial fit for heatCapacity.
Based on data from http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf
Fits a polynomial to the data set and returns the coefficients.
Parameters
----------
power : int, optional
power of the polynomial fit equation
Returns
-------
list of length 'power' containing the polynomial fit coefficients for heat capacity.
"""<line_sep>Tc=[20.0 100.0 200.0 300.0 400.0 500.0 600.0 700.0 800.0 900.0]<line_sep>cp=[444.0 465.0 486.0 502.0 519.0 536.0 578.0 595.0 611.0 628.0]<line_sep><return>numpy.polyfit(numpy.array(Tc) numpy.array(cp) power).tolist()<block_end><def_stmt>heatCapacity self Tk=<none> Tc=<none><block_start>r"""
Returns the specific heat capacity of Inconel600.
Parameters
----------
Tk : float, optional
Temperature in Kelvin.
Tc : float, optional
Temperature in degrees Celsius.
Returns
-------
heatCapacity : float
heat capacity in J/kg/C
"""<line_sep>Tc=getTc(Tc Tk)<line_sep>self.checkTempRange(20 900 Tc "heat capacity")<line_sep>heatCapacity=7.4021e-6<times>Tc<power>2+0.20573<times>Tc+441.3<line_sep><return>heatCapacity<block_end># J/kg-C
<def_stmt>polyfitLinearExpansionPercent self power=2<block_start>r"""
Calculates the coefficients of a polynomial fit for linearExpansionPercent.
Based on data from http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf
Uses mean CTE values to find percent thermal strain values. Fits a polynomial
to the data set and returns the coefficients.
Parameters
----------
power : int, optional
power of the polynomial fit equation
Returns
-------
list of length 'power' containing the polynomial fit coefficients for linearExpansionPercent
"""<line_sep>refTempC=getTc(<none> Tk=self.p.refTempK)<line_sep>Tc=[100.0 200.0 300.0 400.0 500.0 600.0 700.0 800.0 900.0]<line_sep>alpha_mean=[1.33e-05 1.38e-05 1.42e-05 1.45e-05 1.49e-05 1.53e-05 1.58e-05 1.61e-05 1.64e-05 ]<line_sep>linExpPercent=[0.0]<for_stmt>i,alpha enumerate(alpha_mean)<block_start>linExpPercentVal=100.0<times>alpha<times>(Tc[i]-refTempC)<line_sep>linExpPercent.append(linExpPercentVal)<block_end>Tc.insert(0 refTempC)<line_sep><return>numpy.polyfit(numpy.array(Tc) numpy.array(linExpPercent) power).tolist()<block_end><def_stmt>linearExpansionPercent self Tk=<none> Tc=<none><block_start>r"""
Returns percent linear expansion of Inconel600.
Parameters
----------
Tk : float
temperature in (K)
Tc : float
Temperature in (C)
Returns
-------
linExpPercent in %-m/m/C
"""<line_sep>Tc=getTc(Tc Tk)<line_sep>self.checkTempRange(21.0 900.0 Tc "linear expansion percent")<line_sep>linExpPercent=3.722e-7<times>Tc<power>2+1.303e-3<times>Tc-2.863e-2<line_sep><return>linExpPercent<block_end><def_stmt>linearExpansion self Tk=<none> Tc=<none><block_start>r"""
From http://www.specialmetals.com/documents/Inconel%20alloy%20600.pdf
Using the correlation for linearExpansionPercent, the 2nd order polynomial is divided by 100 to convert
from percent strain to strain, then differentiated with respect to temperature to find the correlation
for instantaneous linear expansion.
i.e. for a linearExpansionPercent correlation of a*Tc**2 + b*Tc + c, the linearExpansion correlation is 2*a/100*Tc + b/100
2*(3.722e-7/100.0)*Tc + 1.303e-3/100.0
Parameters
----------
Tk : float
temperature in (K)
Tc : float
Temperature in (C)
Returns
-------
linExp in m/m/C
"""<line_sep>Tc=getTc(Tc Tk)<line_sep>self.checkTempRange(21.0 900.0 Tc "linear expansion")<line_sep>linExp=7.444e-9<times>Tc+1.303e-5<line_sep><return>linExp<block_end><block_end> |
<import_from_future_stmt> absolute_import<line_sep># flake8: noqa
# import apis into api package
<import_from_stmt>hubspot.crm.products.api.associations_api AssociationsApi<import_from_stmt>hubspot.crm.products.api.basic_api BasicApi<import_from_stmt>hubspot.crm.products.api.batch_api BatchApi<import_from_stmt>hubspot.crm.products.api.search_api SearchApi<line_sep> |
"""The store routes
"""<line_sep># Django Library
<import_from_stmt>django.urls path<line_sep># Localfolder Library
<import_from_stmt>..views.product_category_uom ProductCategoryUOMCreateView ProductCategoryUOMDeleteView ProductCategoryUOMDetailView ProductCategoryUOMListView ProductCategoryUOMUpdateView <line_sep>app_name='PyProductCategoryUOM'<line_sep>urlpatterns=[path('' ProductCategoryUOMListView.as_view() name='list') path('add/' ProductCategoryUOMCreateView.as_view() name='add') path('int:pk>/' ProductCategoryUOMDetailView.as_view() name='product-category-uom-detail') path('<int:pk>/update' ProductCategoryUOMUpdateView.as_view() name='update') path('<int:pk>/delete/' ProductCategoryUOMDeleteView.as_view() name='delete') ]<line_sep> |
"""
A statement function set holds a set of statement functions that can be used in statements.
"""<class_stmt>BaseStatementFuncSet(object)<block_start>"""
A statement function set holds a set of statement functions that can be used in statements.
"""<def_stmt>__init__ self<block_start>self.funcs={}<line_sep>self.at_creation()<block_end><def_stmt>at_creation self<block_start>"""
Load statement functions here.
"""<line_sep><pass><block_end><def_stmt>add self func_cls<block_start>"""
Add a statement function's class.
Args:
func_cls: statement function's class
Returns:
None
"""<line_sep># save an instance of the function class
self.funcs[func_cls.key]=func_cls<block_end><def_stmt>get_func_class self key<block_start>"""
Get statement function's class.
Args:
key: statement function's key.
Returns:
function's class
"""<if_stmt>key<in>self.funcs<block_start><return>self.funcs[key]<block_end><else_stmt><block_start><return><none><block_end><block_end><block_end> |
<import_from_stmt>tagger.data.dataset get_dataset<import_from_stmt>tagger.data.vocab load_vocabulary lookup<import_from_stmt>tagger.data.embedding load_glove_embedding<line_sep> |
<import_stmt>torch<import_from_stmt>torch nn<import_stmt>pdb os<import_from_stmt>shapely.geometry *<import_from_stmt>maskrcnn_benchmark.structures.boxlist_ops cat_boxlist<import_stmt>time<import_stmt>matplotlib.pyplot<as>plt<import_stmt>numpy<as>np<import_from_stmt>scipy.signal argrelextrema<import_stmt>random<import_stmt>string<line_sep>all_types=[[1 2 3 4] [1 2 4 3] [1 3 2 4] [1 3 4 2] [1 4 2 3] [1 4 3 2] [2 1 3 4] [2 1 4 3] [2 3 1 4] [2 3 4 1] [2 4 1 3] [2 4 3 1] [3 1 2 4] [3 1 4 2] [3 2 1 4] [3 2 4 1] [3 4 1 2] [3 4 2 1] [4 1 2 3] [4 1 3 2] [4 2 1 3] [4 2 3 1] [4 3 1 2] [4 3 2 1]]<class_stmt>kePostProcessor(nn.Module)<block_start><def_stmt>__init__ self keer=<none> cfg=<none><block_start>super(kePostProcessor self).__init__()<line_sep>self.keer=keer<line_sep>self.cfg=cfg<block_end><def_stmt>forward self ft_x ft_y mty boxes<block_start>ke_prob_x=ft_x<line_sep>ke_prob_y=ft_y<line_sep>mty_prob=mty<line_sep>boxes_per_image=[box.bbox.size(0)<for>box boxes]<line_sep>ke_prob_x=ke_prob_x.split(boxes_per_image dim=0)<line_sep>ke_prob_y=ke_prob_y.split(boxes_per_image dim=0)<line_sep>mty_prob=mty_prob.split(boxes_per_image dim=0)<line_sep>results=[]<for_stmt>prob_x,prob_y,prob_mty,box zip(ke_prob_x ke_prob_y mty_prob boxes)<block_start>bbox=BoxList(box.bbox box.size mode='xyxy')<for_stmt>field box.fields()<block_start>bbox.add_field(field box.get_field(field))<block_end><if_stmt>self.keer<block_start>prob_x,rescores_x=self.keer(prob_x box)<line_sep>prob_y,rescores_y=self.keer(prob_y box)<line_sep>rescores=(rescores_x+rescores_y)<times>0.5<block_end><if_stmt>self.cfg.MODEL.ROI_KE_HEAD.RESCORING<block_start>bbox.add_field('scores' rescores)<block_end>prob=torch.cat((prob_x prob_y) dim=-2)<line_sep>prob=prob[<ellipsis> :1]<line_sep>prob=textKES(prob box.size)<line_sep>bbox.add_field('ke' prob)<line_sep>bbox.add_field('mty' prob_mty)<line_sep>results.append(bbox)<block_end><return>results<block_end><block_end># TODO remove and use only the keer
<import_stmt>numpy<as>np<import_stmt>cv2<def_stmt>scores_to_probs scores<block_start>"""Transforms CxHxW of scores to probabilities spatially."""<line_sep>channels=scores.shape[0]<for_stmt>c range(channels)<block_start>temp=scores[c : :]<line_sep>max_score=temp.max()<line_sep>temp=np.exp(temp-max_score)/np.sum(np.exp(temp-max_score))<line_sep>scores[c : :]=temp<block_end><return>scores<block_end><def_stmt>kes_decode kes# BDN decode
<block_start><for_stmt>ix,i enumerate(kes)<block_start>mnd=i[0 0]<line_sep>nkes=i.shape[1]-2<line_sep>kes[ix][0 1:5]=kes[ix][0 1:5]<times>2-mnd<block_end><return>kes<block_end><def_stmt>heatmaps_to_kes maps rois scores cfg<block_start>"""Extract predicted ke locations from heatmaps. Output has shape
(#rois, 4, #kes) with the 4 rows corresponding to (x, y, logit, prob)
for each ke.
"""<line_sep># This function converts a discrete image coordinate in a HEATMAP_SIZE x
# HEATMAP_SIZE image to a continuous ke coordinate. We maintain
# consistency with kes_to_heatmap_labels by using the conversion from
# Heckbert 1990: c = d + 0.5, where d is a discrete coordinate and c is a
# continuous coordinate.
offset_x=rois[: 0]<line_sep>offset_y=rois[: 1]<line_sep>widths=rois[: 2]-rois[: 0]<line_sep>heights=rois[: 3]-rois[: 1]<line_sep>widths=np.maximum(widths 1)<line_sep>heights=np.maximum(heights 1)<line_sep>widths_ceil=np.ceil(widths)<line_sep>heights_ceil=np.ceil(heights)<line_sep>resol=cfg.MODEL.ROI_KE_HEAD.RESOLUTION# cfg.mo... 56
<if_stmt>maps.shape[-2:]<eq>(1 resol)<block_start>xory_mode=0# x mode
<block_end><elif_stmt>maps.shape[-2:]<eq>(resol 1)<block_start>xory_mode=1# y mode
<block_end><else_stmt><block_start><assert_stmt>(0) 'invalid mode.'<block_end># print("maps", maps.shape, maps[0,0], maps[0,1])
# NCHW to NHWC for use with OpenCV
maps=np.transpose(maps [0 2 3 1])<line_sep>min_size=0# cfg
num_kes=int(cfg.MODEL.ROI_KE_HEAD.NUM_KES/2)+2<line_sep>d_preds=np.zeros((len(rois) 2 num_kes) dtype=np.float32)<line_sep>d_scores=np.zeros(scores.shape dtype=np.float32)<assert_stmt>(len(rois)<eq>maps.shape[0]) 'shape mismatch {}, {}, {}, {}'.format(str(len(rois)) str(rois.shape) str(maps.shape[0]) str(maps.shape))<line_sep>normal=0<line_sep>innormal=0<for_stmt>i range(len(rois))<block_start><if_stmt>min_size<g>0<block_start>roi_map_width=int(np.maximum(widths_ceil[i] min_size))<line_sep>roi_map_height=int(np.maximum(heights_ceil[i] min_size))<block_end><else_stmt><block_start>roi_map_width=widths_ceil[i]<line_sep>roi_map_height=heights_ceil[i]<block_end>width_correction=widths[i]/roi_map_width<line_sep>height_correction=heights[i]/roi_map_height<line_sep>np.set_printoptions(suppress=<true>)<line_sep># print(i, "stop", maps.shape, np.around(maps[i][0, :, :], decimals=2))
<if_stmt><not>xory_mode<block_start>roi_map=cv2.resize(maps[i] (roi_map_width 1) interpolation=cv2.INTER_CUBIC)<block_end><else_stmt><block_start>roi_map=cv2.resize(maps[i] (1 roi_map_height) interpolation=cv2.INTER_CUBIC)<block_end># print(roi_map.shape, np.around(roi_map[0, :, :], decimals=2))
# Bring back to CHW
roi_map=np.transpose(roi_map [2 0 1])<line_sep>roi_map_probs=scores_to_probs(roi_map.copy())<line_sep># kescore visulize.
map_vis=np.transpose(maps[i] [2 0 1])<line_sep>map_vis=scores_to_probs(map_vis.copy())<line_sep>sum_score=[]<if_stmt>cfg.MODEL.ROI_KE_HEAD.RESCORING<block_start><for_stmt>k range(num_kes)<block_start><if_stmt>map_vis[k].shape[0]<eq>1<block_start>x=np.arange(0 len(map_vis[k][0]) 1)<line_sep>y=map_vis[k][0]<block_end><else_stmt><block_start>x=np.arange(0 len(map_vis[k][: 0]) 1)<line_sep>y=map_vis[k][: 0]<block_end>top=y.max()<line_sep>atop=y.argmax()<line_sep># lf2&1
lf2=max(atop-2 0)<line_sep>lf1=max(atop-1 0)<line_sep>rt2=min(atop+2 55)<line_sep>rt1=min(atop+1 55)<line_sep>sum_score.append(top+y[lf2]+y[lf1]+y[rt1]+y[rt2])<line_sep>kes_score_mean=sum(sum_score)<times>1.0/len(sum_score)<line_sep>gama=cfg.MODEL.ROI_KE_HEAD.RESCORING_GAMA<line_sep>final_score=(scores[i]<times>(2.0-gama)+gama<times>kes_score_mean)<times>0.5<line_sep># rescore
d_scores[i]=final_score<block_end><block_end><else_stmt><block_start>d_scores[i]=scores[i]<block_end>w=roi_map.shape[2]<for_stmt>k range(num_kes)<block_start>pos=roi_map[k : :].argmax()<line_sep>x_int=pos%w<line_sep>y_int=(pos-x_int)<floordiv>w<assert_stmt>(roi_map_probs[k y_int x_int]<eq>roi_map_probs[k : :].max())<line_sep>x=(x_int+0.5)<times>width_correction<line_sep>y=(y_int+0.5)<times>height_correction<if_stmt><not>xory_mode<block_start>d_preds[i 0 k]=x+offset_x[i]<line_sep>d_preds[i 1 k]=roi_map_probs[k y_int x_int]<block_end><else_stmt><block_start>d_preds[i 0 k]=y+offset_y[i]<line_sep>d_preds[i 1 k]=roi_map_probs[k y_int x_int]<block_end><block_end><block_end>out_kes_d=kes_decode(d_preds)<line_sep><return>np.transpose(out_kes_d [0 2 1]) d_scores<block_end><import_from_stmt>maskrcnn_benchmark.structures.bounding_box BoxList<import_from_stmt>maskrcnn_benchmark.structures.ke textKES<class_stmt>KEer(object)<block_start>"""
Projects a set of masks in an image on the locations
specified by the bounding boxes
"""<def_stmt>__init__ self padding=0 cfg=<none><block_start>self.padding=padding<line_sep>self.cfg=cfg<block_end><def_stmt>compute_flow_field_cpu self boxes<block_start>im_w,im_h=boxes.size<line_sep>boxes_data=boxes.bbox<line_sep>num_boxes=len(boxes_data)<line_sep>device=boxes_data.device<line_sep>TO_REMOVE=1<line_sep>boxes_data=boxes_data.int()<line_sep>box_widths=boxes_data[: 2]-boxes_data[: 0]+TO_REMOVE<line_sep>box_heights=boxes_data[: 3]-boxes_data[: 1]+TO_REMOVE<line_sep>box_widths.clamp_(min=1)<line_sep>box_heights.clamp_(min=1)<line_sep>boxes_data=boxes_data.tolist()<line_sep>box_widths=box_widths.tolist()<line_sep>box_heights=box_heights.tolist()<line_sep>flow_field=torch.full((num_boxes im_h im_w 2) -2)<line_sep># TODO maybe optimize to make it GPU-friendly with advanced indexing
# or dedicated kernel
<for_stmt>i range(num_boxes)<block_start>w=box_widths[i]<line_sep>h=box_heights[i]<if_stmt>w<l>2<or>h<l>2<block_start><continue><block_end>x=torch.linspace(-1 1 w)<line_sep>y=torch.linspace(-1 1 h)<line_sep># meshogrid
x=x[<none> :].expand(h w)<line_sep>y=y[: <none>].expand(h w)<line_sep>b=boxes_data[i]<line_sep>x_0=max(b[0] 0)<line_sep>x_1=min(b[2]+0 im_w)<line_sep>y_0=max(b[1] 0)<line_sep>y_1=min(b[3]+0 im_h)<line_sep>flow_field[i y_0:y_1 x_0:x_1 0]=x[(y_0-b[1]):(y_1-b[1]) (x_0-b[0]):(x_1-b[0])]<line_sep>flow_field[i y_0:y_1 x_0:x_1 1]=y[(y_0-b[1]):(y_1-b[1]) (x_0-b[0]):(x_1-b[0])]<block_end><return>flow_field.to(device)<block_end><def_stmt>compute_flow_field self boxes<block_start><return>self.compute_flow_field_cpu(boxes)<block_end># TODO make it work better for batches
<def_stmt>forward_single_image self masks boxes<block_start>boxes=boxes.convert('xyxy')<if_stmt>self.padding<block_start>boxes=BoxList(boxes.bbox.clone() boxes.size boxes.mode)<line_sep>masks,scale=expand_masks(masks self.padding)<line_sep>boxes.bbox=expand_boxes(boxes.bbox scale)<block_end>flow_field=self.compute_flow_field(boxes)<line_sep>result=torch.nn.functional.grid_sample(masks flow_field)<line_sep><return>result<block_end><def_stmt>to_points self masks<block_start>height,width=masks.shape[-2:]<line_sep>m=masks.view(masks.shape[:2]+(-1 ))<line_sep>scores,pos=m.max(-1)<line_sep>x_int=pos%width<line_sep>y_int=(pos-x_int)<floordiv>width<line_sep>result=torch.stack([x_int.float() y_int.float() torch.ones_like(x_int dtype=torch.float32)] dim=2)<line_sep><return>result<block_end><def_stmt>__call__ self masks boxes# TODO do this properly
<block_start><if_stmt>isinstance(boxes BoxList)<block_start>boxes=[boxes]<block_end><if_stmt>isinstance(masks list)<block_start>masks=torch.stack(masks dim=0)<assert_stmt>(len(masks.size())<eq>4)<block_end>scores=boxes[0].get_field("scores")<line_sep>result,rescores=heatmaps_to_kes(masks.detach().cpu().numpy() boxes[0].bbox.cpu().numpy() scores.cpu().numpy() self.cfg)<line_sep><return>torch.from_numpy(result).to(masks.device) torch.from_numpy(rescores).to(masks.device)<block_end><block_end><def_stmt>make_roi_ke_post_processor cfg<block_start><if_stmt>cfg.MODEL.ROI_KE_HEAD.POSTPROCESS_KES<block_start>keer=KEer(padding=0 cfg=cfg)<block_end><else_stmt><block_start>keer=<none><block_end>ke_post_processor=kePostProcessor(keer cfg)<line_sep><return>ke_post_processor<block_end> |
<class_stmt>SubmissionStatus(object)<block_start>SUBMITTED=-4<line_sep>WAITING=-3<line_sep>JUDGING=-2<line_sep>WRONG_ANSWER=-1<line_sep>ACCEPTED=0<line_sep>TIME_LIMIT_EXCEEDED=1<line_sep>IDLENESS_LIMIT_EXCEEDED=2<line_sep>MEMORY_LIMIT_EXCEEDED=3<line_sep>RUNTIME_ERROR=4<line_sep>SYSTEM_ERROR=5<line_sep>COMPILE_ERROR=6<line_sep>SCORED=7<line_sep>REJECTED=10<line_sep>JUDGE_ERROR=11<line_sep>PRETEST_PASSED=12<line_sep>@staticmethod<def_stmt>is_judged status<block_start><return>status<ge>SubmissionStatus.WRONG_ANSWER<block_end>@staticmethod<def_stmt>is_penalty status<block_start><return>SubmissionStatus.is_judged(status)<and>status<ne>SubmissionStatus.COMPILE_ERROR<block_end>@staticmethod<def_stmt>is_accepted status<block_start><return>status<eq>SubmissionStatus.ACCEPTED<or>status<eq>SubmissionStatus.PRETEST_PASSED<block_end>@staticmethod<def_stmt>is_scored status<block_start><return>status<eq>SubmissionStatus.SCORED<block_end><block_end>STATUS_CHOICE=((-4 'Submitted') (-3 'In queue') (-2 'Running') (-1 'Wrong answer') (0 'Accepted') (1 'Time limit exceeded') (2 'Idleness limit exceeded') (3 'Memory limit exceeded') (4 'Runtime error') (5 'Denial of judgement') (6 'Compilation error') (7 'Partial score') (10 'Rejected') (11 'Checker error') (12 'Pretest passed') )<line_sep> |
# Copyright 2017, Red Hat
#
# 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_stmt>os<import_stmt>shutil<import_stmt>tempfile<import_from_stmt>unittest TestCase<import_from_stmt>repoxplorer.index.yamlbackend YAMLBackend<class_stmt>TestYAMLBackend(TestCase)<block_start><def_stmt>setUp self<block_start><pass><block_end><def_stmt>tearDown self<block_start><if_stmt>os.path.isdir(self.db)<block_start>shutil.rmtree(self.db)<block_end><block_end><def_stmt>create_db self files<block_start>self.db=tempfile.mkdtemp()<for_stmt>filename,content files.items()<block_start>open(os.path.join(self.db filename) 'w+').write(content)<block_end><block_end><def_stmt>test_yamlbackend_load self<block_start>f1="""
---
key: value
"""<line_sep>f2="""
---
key2: value2
"""<line_sep>files={'f1.yaml':f1 'f2.yaml':f2}<line_sep>self.create_db(files)<line_sep>backend=YAMLBackend(db_path=self.db)<line_sep>backend.load_db()<line_sep>default_data,data=backend.get_data()<line_sep>self.assertEqual(default_data <none>)<line_sep>self.assertEqual(len(data) 2)<block_end><def_stmt>test_yamlbackend_load_with_default self<block_start>f1="""
---
key: value
"""<line_sep>f2="""
---
key2: value2
"""<line_sep>files={'default.yaml':f1 'f2.yaml':f2}<line_sep>self.create_db(files)<line_sep>backend=YAMLBackend(db_path=self.db db_default_file=os.path.join(self.db 'default.yaml'))<line_sep>backend.load_db()<line_sep>default_data,data=backend.get_data()<line_sep>self.assertDictEqual(default_data {'key':'value'})<line_sep>self.assertEqual(len(data) 1)<line_sep>self.assertDictEqual(data[0] {'key2':'value2'})<block_end><block_end> |
<import_stmt>tkinter<as>tk<class_stmt>ScrolledFrame(tk.Frame)<block_start><def_stmt>__init__ self parent vertical=<true> horizontal=<false><block_start>super().__init__(parent)<line_sep># canvas for inner frame
self._canvas=tk.Canvas(self)<line_sep>self._canvas.grid(row=0 column=0 sticky='news')# changed
# create right scrollbar and connect to canvas Y
self._vertical_bar=tk.Scrollbar(self orient='vertical' command=self._canvas.yview)<if_stmt>vertical<block_start>self._vertical_bar.grid(row=0 column=1 sticky='ns')<block_end>self._canvas.configure(yscrollcommand=self._vertical_bar.set)<line_sep># create bottom scrollbar and connect to canvas X
self._horizontal_bar=tk.Scrollbar(self orient='horizontal' command=self._canvas.xview)<if_stmt>horizontal<block_start>self._horizontal_bar.grid(row=1 column=0 sticky='we')<block_end>self._canvas.configure(xscrollcommand=self._horizontal_bar.set)<line_sep># inner frame for widgets
self.inner=tk.Frame(self._canvas)<line_sep>self._window=self._canvas.create_window((0 0) window=self.inner anchor='nw')<line_sep># autoresize inner frame
self.columnconfigure(0 weight=1)# changed
self.rowconfigure(0 weight=1)# changed
# resize when configure changed
self.inner.bind('<Configure>' self.resize)<line_sep># resize inner frame to canvas size
self.resize_width=<false><line_sep>self.resize_height=<false><line_sep>self._canvas.bind('<Configure>' self.inner_resize)<block_end><def_stmt>resize self event=<none><block_start>self._canvas.configure(scrollregion=self._canvas.bbox('all'))<block_end><def_stmt>inner_resize self event# resize inner frame to canvas size
<block_start><if_stmt>self.resize_width<block_start>self._canvas.itemconfig(self._window width=event.width)<block_end><if_stmt>self.resize_height<block_start>self._canvas.itemconfig(self._window height=event.height)<block_end><block_end><block_end> |
<import_from_stmt>rest_framework.exceptions ValidationError<import_from_stmt>django.utils.translation ugettext_lazy<as>_<import_from_stmt>openbook_circles.models Circle<def_stmt>circle_id_exists circle_id<block_start>count=Circle.objects.filter(id=circle_id).count()<if_stmt>count<eq>0<block_start><raise>ValidationError(_('The circle does not exist.') )<block_end><block_end> |
<import_from_stmt>.version __version__<import_from_stmt>dtreeviz.classifiers clfviz<line_sep> |
<import_stmt>numpy<as>np<import_stmt>skimage<import_stmt>skimage.io<import_stmt>scipy.io<as>sio<import_stmt>skimage.transform<import_stmt>sys<line_sep>np.random.seed(0)<line_sep>VGG_MEAN=[103.939 116.779 123.68]<def_stmt>read_mat path<block_start><return>np.load(path)<block_end><def_stmt>write_mat path m<block_start>np.save(path m)<block_end><def_stmt>read_ids path<block_start><return>[line.rstrip('\n')<for>line open(path)]<block_end><class_stmt>Batch_Feeder<block_start><def_stmt>__init__ self dataset indices train batchSize padWidth=<none> padHeight=<none> flip=<false> keepEmpty=<true><block_start>self._epochs_completed=0<line_sep>self._index_in_epoch=0<line_sep>self._dataset=dataset<line_sep>self._indices=indices<line_sep>self._train=train<line_sep>self._batchSize=batchSize<line_sep>self._padWidth=padWidth<line_sep>self._padHeight=padHeight<line_sep>self._flip=flip<line_sep>self._keepEmpty=keepEmpty<block_end><def_stmt>set_paths self idList=<none> imageDir=<none> gtDir=<none> ssDir=<none><block_start>self._paths=[]<if_stmt>self._train<block_start><for_stmt>id idList<block_start>self._paths.append([id imageDir+'/'+id+'_leftImg8bit.png' gtDir+'/'+id+'_unified_GT.mat' ssDir+'/'+id+'_unified_ss.mat'])<block_end>self.shuffle()<block_end><else_stmt><block_start><for_stmt>id idList<block_start>self._paths.append([id imageDir+'/'+id+'_leftImg8bit.png' ssDir+'/'+id+'_unified_ss.mat'])<block_end><block_end>self._numData=len(self._paths)<if_stmt>self._numData<l>self._batchSize<block_start>self._batchSize=self._numData<block_end><block_end><def_stmt>shuffle self<block_start>np.random.shuffle(self._paths)<block_end><def_stmt>next_batch self<block_start>idBatch=[]<line_sep>imageBatch=[]<line_sep>gtBatch=[]<line_sep>ssBatch=[]<line_sep>ssMaskBatch=[]<line_sep>weightBatch=[]<if_stmt>self._train<block_start><while_stmt>(len(idBatch)<l>self._batchSize)<block_start>ss=(sio.loadmat(self._paths[self._index_in_epoch][3])['mask']).astype(float)<line_sep>ssMask=ss<line_sep>ss=np.sum(ss[: : self._indices] 2)<line_sep>background=np.zeros(ssMask.shape[0:2]+(1 ))<line_sep>ssMask=np.concatenate((ssMask[: : [1 2 3 4]] background ssMask[: : [0 5 6 7]]) axis=-1)<line_sep>ssMask=np.argmax(ssMask axis=-1)<line_sep>ssMask=ssMask.astype(float)<line_sep>ssMask=(ssMask-4)<times>32# centered at 0, with 0 being background, spaced 32 apart for classes
<if_stmt>ss.sum()<g>0<or>self._keepEmpty<block_start>idBatch.append(self._paths[self._index_in_epoch][0])<line_sep>image=(self.image_scaling(skimage.io.imread(self._paths[self._index_in_epoch][1]))).astype(float)<line_sep>gt=(sio.loadmat(self._paths[self._index_in_epoch][2])['dir_map']).astype(float)<line_sep>weight=(sio.loadmat(self._paths[self._index_in_epoch][2])['weight_map']).astype(float)<line_sep>imageBatch.append(self.pad(image))<line_sep>gtBatch.append(self.pad(gt))<line_sep>weightBatch.append(self.pad(weight))<line_sep>ssBatch.append(self.pad(ss))<line_sep>ssMaskBatch.append(self.pad(ssMask))<block_end><else_stmt><block_start><pass><line_sep># raw_input("skipping " + self._paths[self._index_in_epoch][0])
<block_end>self._index_in_epoch<augadd>1<if_stmt>self._index_in_epoch<eq>self._numData<block_start>self._index_in_epoch=0<line_sep>self.shuffle()<block_end><block_end>imageBatch=np.array(imageBatch)<line_sep>gtBatch=np.array(gtBatch)<line_sep>ssBatch=np.array(ssBatch)<line_sep>ssMaskBatch=np.array(ssMaskBatch)<line_sep>weightBatch=np.array(weightBatch)<if_stmt>self._flip<and>np.random.uniform()<g>0.5<block_start><for_stmt>i range(len(imageBatch))<block_start><for_stmt>j range(3)<block_start>imageBatch[i : : j]=np.fliplr(imageBatch[i : : j])<block_end>weightBatch[i]=np.fliplr(weightBatch[i])<line_sep>ssBatch[i]=np.fliplr(ssBatch[i])<line_sep>ssMaskBatch[i]=np.fliplr(ssMaskBatch[i])<for_stmt>j range(2)<block_start>gtBatch[i : : j]=np.fliplr(gtBatch[i : : j])<block_end>gtBatch[i : : 0]=-1<times>gtBatch[i : : 0]<block_end><block_end><return>imageBatch gtBatch weightBatch ssBatch ssMaskBatch idBatch<block_end><else_stmt><block_start><for_stmt>example self._paths[self._index_in_epoch:min(self._index_in_epoch+self._batchSize self._numData)]<block_start>imageBatch.append(self.pad((self.image_scaling(skimage.io.imread(example[1]))).astype(float)))<line_sep>idBatch.append(example[0])<line_sep>ss=(sio.loadmat(example[2])['mask']).astype(float)<line_sep>ssMask=ss<line_sep>ss=np.sum(ss[: : self._indices] 2)<line_sep>background=np.zeros(ssMask.shape[0:2]+(1 ))<line_sep>ssMask=np.concatenate((ssMask[: : [1 2 3 4]] background ssMask[: : [0 5 6 7]]) axis=-1)<line_sep>ssMask=np.argmax(ssMask axis=-1)<line_sep>ssMask=ssMask.astype(float)<line_sep>ssMask=(ssMask-4)<times>32# centered at 0, with 0 being background, spaced 32 apart for classes
ssBatch.append(self.pad(ss))<line_sep>ssMaskBatch.append(self.pad(ssMask))<block_end>imageBatch=np.array(imageBatch)<line_sep>ssBatch=np.array(ssBatch)<line_sep>ssMaskBatch=np.array(ssMaskBatch)<line_sep>self._index_in_epoch<augadd>self._batchSize<line_sep><return>imageBatch ssBatch ssMaskBatch idBatch<block_end><block_end><def_stmt>total_samples self<block_start><return>self._numData<block_end><def_stmt>image_scaling self rgb_in<block_start><if_stmt>rgb_in.dtype<eq>np.float32<block_start>rgb_in=rgb_in<times>255<block_end><elif_stmt>rgb_in.dtype<eq>np.uint8<block_start>rgb_in=rgb_in.astype(np.float32)<block_end># VGG16 was trained using opencv which reads images as BGR, but skimage reads images as RGB
rgb_out=np.zeros(rgb_in.shape).astype(np.float32)<line_sep>rgb_out[: : 0]=rgb_in[: : 2]-VGG_MEAN[2]<line_sep>rgb_out[: : 1]=rgb_in[: : 1]-VGG_MEAN[1]<line_sep>rgb_out[: : 2]=rgb_in[: : 0]-VGG_MEAN[0]<line_sep><return>rgb_out<block_end><def_stmt>pad self data<block_start><if_stmt>self._padHeight<and>self._padWidth<block_start><if_stmt>data.ndim<eq>3<block_start>npad=((0 self._padHeight-data.shape[0]) (0 self._padWidth-data.shape[1]) (0 0))<block_end><elif_stmt>data.ndim<eq>2<block_start>npad=((0 self._padHeight-data.shape[0]) (0 self._padWidth-data.shape[1]))<block_end>padData=np.pad(data npad mode='constant' constant_values=0)<block_end><else_stmt><block_start>padData=data<block_end><return>padData<block_end><block_end> |
# ===================================
# Import the libraries
# ===================================
<import_stmt>numpy<as>np<import_from_stmt>matplotlib pylab<as>plt<import_stmt>imaging<import_stmt>utility<import_stmt>os sys<line_sep># ===================================
# Which stages to run
# ===================================
do_add_noise=<false><line_sep>do_black_level_correction=<true><line_sep>do_lens_shading_correction=<true><line_sep>do_bad_pixel_correction=<true><line_sep>do_channel_gain_white_balance=<true><line_sep>do_bayer_denoise=<false><line_sep>do_demosaic=<true><line_sep>do_demosaic_artifact_reduction=<true><line_sep>do_color_correction=<true><line_sep>do_gamma=<true><line_sep>do_chromatic_aberration_correction=<true><line_sep>do_tone_mapping=<true><line_sep>do_memory_color_enhancement=<true><line_sep>do_noise_reduction=<true><line_sep>do_sharpening=<true><line_sep>do_distortion_correction=<false><line_sep># ===================================
# Remove all the .png files
os.system("rm images/*.png")<line_sep># ===================================
# ===================================
# raw image and set up the metadata
# ===================================
# uncomment the image_name to run it via pipeline
image_name="DSC_1339_768x512_rggb"# image content: Rose rggb
# image_name = "DSC_1339_768x512_gbrg" # image content: Rose gbrg
# image_name = "DSC_1339_768x512_grbg" # image content: Rose grbg
# image_name = "DSC_1339_768x512_bggr" # image content: Rose bggr
# image_name = "DSC_1320_2048x2048_rggb" # image content: Potrait
# image_name = "DSC_1372_6032x4032_rggb" # image content: Downtown San Jose
# image_name = "DSC_1372_12096x6032_rgb_out_demosaic" # image content: Downtown San Jose after demosaic
# read the raw image
temp=np.fromfile("images/"+image_name+".raw" dtype="uint16" sep="")<if_stmt>(image_name<eq>"DSC_1339_768x512_rggb")<block_start>temp=temp.reshape([512 768])<line_sep>raw=imaging.ImageInfo("1339_768x512_rggb" temp)<line_sep>raw.set_color_space("raw")<line_sep>raw.set_bayer_pattern("rggb")<line_sep>raw.set_channel_gain((1.94921875 1.0 1.0 1.34375))# Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)<line_sep>raw.set_black_level((600 600 600 600))<line_sep>raw.set_white_level((15520 15520 15520 15520))<line_sep># the ColorMatrix2 found from the metadata
raw.set_color_matrix([[.9020 -.2890 -.0715] [-.4535 1.2436 .2348] [-.0934 .1919 .7086]])<line_sep>data=raw.data<block_end><elif_stmt>(image_name<eq>"DSC_1339_768x512_gbrg")<block_start>temp=temp.reshape([512 768])<line_sep>raw=imaging.ImageInfo("1339_768x512_gbrg" temp)<line_sep>raw.set_color_space("raw")<line_sep>raw.set_bayer_pattern("gbrg")<line_sep>raw.set_channel_gain((1.0 1.34375 1.94921875 1.0))# Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)<line_sep>raw.set_black_level((600 600 600 600))<line_sep>raw.set_white_level((15520 15520 15520 15520))<line_sep># the ColorMatrix2 found from the metadata
raw.set_color_matrix([[.9020 -.2890 -.0715] [-.4535 1.2436 .2348] [-.0934 .1919 .7086]])<line_sep>data=raw.data<block_end><elif_stmt>(image_name<eq>"DSC_1339_768x512_grbg")<block_start>temp=temp.reshape([512 768])<line_sep>raw=imaging.ImageInfo("1339_768x512_grbg" temp)<line_sep>raw.set_color_space("raw")<line_sep>raw.set_bayer_pattern("grbg")<line_sep>raw.set_channel_gain((1.0 1.94921875 1.34375 1.0))# Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)<line_sep>raw.set_black_level((600 600 600 600))<line_sep>raw.set_white_level((15520 15520 15520 15520))<line_sep># the ColorMatrix2 found from the metadata
raw.set_color_matrix([[.9020 -.2890 -.0715] [-.4535 1.2436 .2348] [-.0934 .1919 .7086]])<line_sep>data=raw.data<block_end><elif_stmt>(image_name<eq>"DSC_1339_768x512_bggr")<block_start>temp=temp.reshape([512 768])<line_sep>raw=imaging.ImageInfo("1339_768x512_bggr" temp)<line_sep>raw.set_color_space("raw")<line_sep>raw.set_bayer_pattern("bggr")<line_sep>raw.set_channel_gain((1.34375 1.0 1.0 1.94921875 ))# Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)<line_sep>raw.set_black_level((600 600 600 600))<line_sep>raw.set_white_level((15520 15520 15520 15520))<line_sep># the ColorMatrix2 found from the metadata
raw.set_color_matrix([[.9020 -.2890 -.0715] [-.4535 1.2436 .2348] [-.0934 .1919 .7086]])<line_sep>data=raw.data<block_end><elif_stmt>(image_name<eq>"DSC_1320_2048x2048_rggb")<block_start>temp=temp.reshape([2048 2048])<line_sep>raw=imaging.ImageInfo("1320_2048x2048_rggb" temp)<line_sep>raw.set_color_space("raw")<line_sep>raw.set_bayer_pattern("rggb")<line_sep>raw.set_channel_gain((1.94921875 1.0 1.0 1.34375))# Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)<line_sep>raw.set_black_level((600 600 600 600))<line_sep>raw.set_white_level((15520 15520 15520 15520))<line_sep># the ColotMatrix2 found from the metadata
raw.set_color_matrix([[.9020 -.2890 -.0715] [-.4535 1.2436 .2348] [-.0934 .1919 .7086]])<line_sep>data=raw.data<block_end><elif_stmt>(image_name<eq>"DSC_1372_6032x4032_rggb")<block_start>temp=temp.reshape([4032 6032])<line_sep>raw=imaging.ImageInfo("DSC_1372_6032x4032_rggb" temp)<line_sep>raw.set_color_space("raw")<line_sep>raw.set_bayer_pattern("rggb")<line_sep>raw.set_channel_gain((1.94921875 1.0 1.0 1.34375))# Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)<line_sep>raw.set_black_level((600 600 600 600))<line_sep>raw.set_white_level((15520 15520 15520 15520))<line_sep># the ColotMatrix2 found from the metadata
raw.set_color_matrix([[.9020 -.2890 -.0715] [-.4535 1.2436 .2348] [-.0934 .1919 .7086]])<line_sep>data=raw.data<block_end><elif_stmt>(image_name<eq>"DSC_1372_12096x6032_rgb_out_demosaic")<block_start>temp=temp.reshape([12096 6032])<line_sep>temp=np.float32(temp)<line_sep>data=np.empty((4032 6032 3) dtype=np.float32)<line_sep>data[: : 0]=temp[0:4032 :]<line_sep>data[: : 1]=temp[4032:2<times>4032 :]<line_sep>data[: : 2]=temp[2<times>4032:3<times>4032 :]<line_sep>raw=imaging.ImageInfo("DSC_1372_12096x6032_rgb_out_demosaic" data)<line_sep>raw.set_color_space("raw")<line_sep>raw.set_bayer_pattern("rggb")<line_sep>raw.set_channel_gain((1.94921875 1.0 1.0 1.34375))# Please shuffle the values
# depending on bayer_pattern
raw.set_bit_depth(14)<line_sep>raw.set_black_level((600 600 600 600))<line_sep>raw.set_white_level((15520 15520 15520 15520))<line_sep># the ColotMatrix2 found from the metadata
raw.set_color_matrix([[.9020 -.2890 -.0715] [-.4535 1.2436 .2348] [-.0934 .1919 .7086]])<block_end><else_stmt><block_start>print("Warning! image_name not recognized.")<block_end># ===================================
# Add noise
# ===================================
<if_stmt>do_add_noise<block_start>noise_mean=0<line_sep>noise_standard_deviation=100<line_sep>seed=100<line_sep>clip_range=[600 65535]<line_sep>data=utility.synthetic_image_generate(raw.get_width() raw.get_height()).create_noisy_image(data noise_mean noise_standard_deviation seed clip_range)<block_end><else_stmt><block_start><pass><block_end># ===================================
# Black level correction
# ===================================
<if_stmt>do_black_level_correction<block_start>data=imaging.black_level_correction(data raw.get_black_level() raw.get_white_level() [0 2<power>raw.get_bit_depth()-1])<line_sep>utility.imsave(data "images/"+image_name+"_out_black_level_correction.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Lens shading correction
# ===================================
<if_stmt>do_lens_shading_correction# normally dark_current_image and flat_field_image are
# captured in the image quality lab using flat field chart
# here we are synthetically generating thouse two images
<block_start>dark_current_image,flat_field_image=utility.synthetic_image_generate(raw.get_width() raw.get_height()).create_lens_shading_correction_images(0 65535 40000)<line_sep># save the dark_current_image and flat_field_image for viewing
utility.imsave(dark_current_image "images/"+image_name+"_dark_current_image.png" "uint16")<line_sep>utility.imsave(flat_field_image "images/"+image_name+"_flat_field_image.png" "uint16")<line_sep>data=imaging.lens_shading_correction(data).flat_field_compensation(dark_current_image flat_field_image)<line_sep># data = lsc.approximate_mathematical_compensation([0.01759, -28.37, -13.36])
utility.imsave(data "images/"+image_name+"_out_lens_shading_correction.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Bad pixel correction
# ===================================
<if_stmt>do_bad_pixel_correction<block_start>neighborhood_size=3<line_sep>data=imaging.bad_pixel_correction(data neighborhood_size)<line_sep>utility.imsave(data "images/"+image_name+"_out_bad_pixel_correction.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Channel gain for white balance
# ===================================
<if_stmt>do_channel_gain_white_balance<block_start>data=imaging.channel_gain_white_balance(data raw.get_channel_gain())<line_sep>utility.imsave(data "images/"+image_name+"_out_channel_gain_white_balance.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Bayer denoising
# ===================================
<if_stmt>do_bayer_denoise# bayer denoising parameters
<block_start>neighborhood_size=5<line_sep>initial_noise_level=65535<times>10/100<line_sep>hvs_min=1000<line_sep>hvs_max=2000<line_sep>clip_range=[0 65535]<line_sep>threshold_red_blue=1300<line_sep># data is the denoised output, ignoring the second output
data,_=imaging.bayer_denoising(data).utilize_hvs_behavior(raw.get_bayer_pattern() initial_noise_level hvs_min hvs_max threshold_red_blue clip_range)<line_sep>utility.imsave(data "images/"+image_name+"_out_bayer_denoising.png" "uint16")<line_sep># utility.imsave(np.clip(texture_degree_debug*65535, 0, 65535), "images/" + image_name + "_out_texture_degree_debug.png", "uint16")
<block_end><else_stmt><block_start><pass><block_end># ===================================
# Demosacing
# ===================================
<if_stmt>do_demosaic#data = imaging.demosaic(data, raw.get_bayer_pattern()).mhc(False)
<block_start>data=imaging.demosaic(data raw.get_bayer_pattern()).directionally_weighted_gradient_based_interpolation()<line_sep>utility.imsave(data "images/"+image_name+"_out_demosaic.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Demosaic artifact reduction
# ===================================
<if_stmt>do_demosaic_artifact_reduction<block_start>data=imaging.demosaic(data).post_process_local_color_ratio(0.80<times>65535)<line_sep>utility.imsave(data "images/"+image_name+"_out_local_color_ratio.png" "uint16")<line_sep>edge_detection_kernel_size=5<line_sep>edge_threshold=0.05<line_sep># first output is main output, second output is edge_location is a debug output
data,_=imaging.demosaic(data).post_process_median_filter(edge_detection_kernel_size edge_threshold)<line_sep>utility.imsave(data "images/"+image_name+"_out_median_filter.png" "uint16")<line_sep># utility.imsave(edge_location*65535, "images/" + image_name + "_edge_location.png", "uint16")
<block_end><else_stmt><block_start><pass><block_end># ===================================
# Color correction
# ===================================
<if_stmt>do_color_correction<block_start>data=imaging.color_correction(data raw.get_color_matrix()).apply_cmatrix()<line_sep>utility.imsave(data "images/"+image_name+"_out_color_correction.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Gamma
# ===================================
<if_stmt>do_gamma# brightening
<block_start>data=imaging.nonlinearity(data "brightening").luma_adjustment(80.)<line_sep># gamma by value
#data = imaging.nonlinearity(data, "gamma").by_value(1/2.2, [0, 65535])
# gamma by table
# data = imaging.nonlinearity(data, "gamma").by_table("tables/gamma_2.4.txt", "gamma", [0, 65535])
# gamma by value
data=imaging.nonlinearity(data "gamma").by_equation(-0.9 -8.0 [0 65535])<line_sep>utility.imsave(data "images/"+image_name+"_out_gamma.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Chromatic aberration correction
# ===================================
<if_stmt>do_chromatic_aberration_correction<block_start>nsr_threshold=90.<line_sep>cr_threshold=6425./2<line_sep>data=imaging.chromatic_aberration_correction(data).purple_fringe_removal(nsr_threshold cr_threshold)<line_sep>utility.imsave(data "images/"+image_name+"_out_purple_fringe_removal.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Tone mapping
# ===================================
<if_stmt>do_tone_mapping<block_start>data=imaging.tone_mapping(data).nonlinear_masking(1.0)<line_sep>utility.imsave(data "images/"+image_name+"_out_tone_mapping_nl_masking.png" "uint16")<line_sep># data = imaging.tone_mapping(data).dynamic_range_compression("normal", [-25., 260.], [0, 65535])
# utility.imsave(data, "images/" + image_name + "_out_tone_mapping_drc.png", "uint16")
<block_end><else_stmt><block_start><pass><block_end># ===================================
# Memory color enhancement
# ===================================
<if_stmt>do_memory_color_enhancement# target_hue = [30., -115., 100.]
# hue_preference = [45., -90., 130.]
# hue_sigma = [20., 10., 5.]
# is_both_side = [True, False, False]
# multiplier = [0.6, 0.6, 0.6]
# chroma_preference = [25., 17., 30.]
# chroma_sigma = [10., 10., 5.]
<block_start>target_hue=[30. -125. 100.]<line_sep>hue_preference=[20. -118. 130.]<line_sep>hue_sigma=[20. 10. 5.]<line_sep>is_both_side=[<true> <false> <false>]<line_sep>multiplier=[0.6 0.6 0.6]<line_sep>chroma_preference=[25. 14. 30.]<line_sep>chroma_sigma=[10. 10. 5.]<line_sep>data=imaging.memory_color_enhancement(data).by_hue_squeeze(target_hue hue_preference hue_sigma is_both_side multiplier chroma_preference chroma_sigma)<line_sep>utility.imsave(data "images/"+image_name+"_out_memory_color_enhancement.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Noise reduction
# ===================================
<if_stmt>do_noise_reduction# sigma filter parameters
<block_start>neighborhood_size=7<line_sep>sigma=[1000 500 500]<line_sep>data=imaging.noise_reduction(data).sigma_filter(neighborhood_size sigma)<line_sep>utility.imsave(data "images/"+image_name+"_out_noise_reduction.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Sharpening
# ===================================
<if_stmt>do_sharpening<block_start>data=imaging.sharpening(data).unsharp_masking()<line_sep>utility.imsave(data "images/"+image_name+"_out_sharpening.png" "uint16")<block_end><else_stmt><block_start><pass><block_end># ===================================
# Distortion correction
# ===================================
<if_stmt>do_distortion_correction<block_start>correction_type="barrel-1"<line_sep>strength=0.5<line_sep>zoom_type="fit"<line_sep>clip_range=[0 65535]<line_sep>data=imaging.distortion_correction(data).empirical_correction(correction_type strength zoom_type clip_range)<line_sep>utility.imsave(data "images/"+image_name+"_out_distortion_correction.png" "uint16")<block_end><else_stmt><block_start><pass><block_end> |
# -*- coding: utf-8 -*-
'''
Description: the feed fetcher
Copyright (c) 2013—2016 <NAME>
Portions are copyright (c) 2013 <NAME>
License: MIT (see LICENSE for details)
'''<import_stmt>sys os re time urlparse<import_from_stmt>datetime datetime<import_from_stmt>peewee IntegrityError<import_stmt>feedparser<import_stmt>requests<import_from_stmt>requests.exceptions *<import_from_stmt>webob.exc *<import_from_stmt>coldsweat *<import_from_stmt>plugins trigger_event<import_from_stmt>models *<import_from_stmt>utilities *<import_from_stmt>translators *<import_stmt>markup<import_stmt>filters<line_sep>__all__=['Fetcher' 'fetch_url']<line_sep>FETCH_ICONS_DELTA=30# Days
<class_stmt>Fetcher(object)<block_start>'''
Fetch a single given feed
'''<def_stmt>__init__ self feed# Save timestamp for current fetch operation
<block_start>self.instant=datetime.utcnow()<line_sep># Extract netloc
_,self.netloc,_,_,_=urlparse.urlsplit(feed.self_link)<line_sep>self.feed=feed<block_end><def_stmt>handle_500 self response<block_start>'''
Internal server error
'''<line_sep>self.feed.error_count<augadd>1<line_sep>self.feed.last_status=response.status_code<line_sep>logger.warn(u"%s has caused an error on server, skipped"%self.netloc)<line_sep><raise>HTTPInternalServerError<block_end><def_stmt>handle_403 self response<block_start>'''
Forbidden
'''<line_sep>self.feed.error_count<augadd>1<line_sep>self.feed.last_status=response.status_code<line_sep>logger.warn(u"%s access was denied, skipped"%self.netloc)<line_sep><raise>HTTPForbidden<block_end><def_stmt>handle_404 self response<block_start>'''
Not Found
'''<line_sep>self.feed.error_count<augadd>1<line_sep>self.feed.last_status=response.status_code<line_sep>logger.warn(u"%s has been not found, skipped"%self.netloc)<line_sep><raise>HTTPNotFound<block_end><def_stmt>handle_410 self response<block_start>'''
Gone
'''<line_sep>self.feed.is_enabled=<false><line_sep>self.feed.error_count<augadd>1<line_sep>self.feed.last_status=response.status_code<line_sep>logger.warn(u"%s is gone, disabled"%self.netloc)<line_sep>self._synthesize_entry('Feed has been removed from the origin server.')<line_sep><raise>HTTPGone<block_end><def_stmt>handle_304 self response<block_start>'''
Not modified
'''<line_sep>logger.debug(u"%s hasn't been modified, skipped"%self.netloc)<line_sep>self.feed.last_status=response.status_code<line_sep><raise>HTTPNotModified<block_end><def_stmt>handle_301 self response<block_start>'''
Moved permanently
'''<line_sep>self_link=response.url<try_stmt><block_start>Feed.get(self_link=self_link)<block_end><except_stmt>Feed.DoesNotExist<block_start>self.feed.self_link=self_link<line_sep>self.feed.last_status=response.status_code<line_sep>logger.info(u"%s has changed its location, updated to %s"%(self.netloc self_link))<block_end><else_stmt><block_start>self.feed.is_enabled=<false><line_sep>self.feed.last_status=DuplicatedFeedError.code<line_sep>self.feed.error_count<augadd>1<line_sep>self._synthesize_entry('Feed has a duplicated web address.')<line_sep>logger.warn(u"new %s location %s is duplicated, disabled"%(self.netloc self_link))<line_sep><raise>DuplicatedFeedError<block_end><block_end><def_stmt>handle_200 self response<block_start>'''
OK plus redirects
'''<line_sep>self.feed.etag=response.headers.get('ETag' <none>)<line_sep># Save final status code discarding redirects
self.feed.last_status=response.status_code<block_end>handle_307=handle_200# Alias
handle_302=handle_200# Alias
<def_stmt>update_feed self<block_start>logger.debug(u"updating %s"%self.netloc)<line_sep># Check freshness
<for_stmt>value [self.feed.last_checked_on self.feed.last_updated_on]<block_start><if_stmt><not>value<block_start><continue><block_end># No datetime.timedelta since we need to
# deal with large seconds values
delta=datetime_as_epoch(self.instant)-datetime_as_epoch(value)<if_stmt>delta<l>config.fetcher.min_interval<block_start>logger.debug(u"%s is below minimun fetch interval, skipped"%self.netloc)<line_sep><return><block_end><block_end><try_stmt><block_start>response=fetch_url(self.feed.self_link timeout=config.fetcher.timeout etag=self.feed.etag modified_since=self.feed.last_updated_on)<block_end><except_stmt>RequestException# Record any network error as 'Service Unavailable'
<block_start>self.feed.last_status=HTTPServiceUnavailable.code<line_sep>self.feed.error_count<augadd>1<line_sep>logger.warn(u"a network error occured while fetching %s, skipped"%self.netloc)<line_sep>self.check_feed_health()<line_sep>self.feed.save()<line_sep><return><block_end>self.feed.last_checked_on=self.instant<line_sep># Check if we got a redirect first
<if_stmt>response.history<block_start>status=response.history[0].status_code<block_end><else_stmt><block_start>status=response.status_code<block_end><try_stmt><block_start>handler=getattr(self 'handle_%d'%status <none>)<if_stmt>handler<block_start>logger.debug(u"got status %s from server"%status)<line_sep>handler(response)<block_end><else_stmt><block_start>self.feed.last_status=status<line_sep>logger.warn(u"%s replied with unhandled status %d, aborted"%(self.netloc status))<line_sep><return><block_end>self._parse_feed(response.text)<line_sep>self._fetch_icon()<block_end><except_stmt>HTTPNotModified<block_start><pass># Nothing to do
<block_end><except_stmt>(HTTPError DuplicatedFeedError)<block_start>self.check_feed_health()<block_end><finally_stmt><block_start>self.feed.save()<block_end><block_end><def_stmt>check_feed_health self<block_start><if_stmt>config.fetcher.max_errors<and>self.feed.error_count<g>config.fetcher.max_errors<block_start>self._synthesize_entry('Feed has accumulated too many errors (last was %s).'%filters.status_title(self.feed.last_status))<line_sep>logger.warn(u"%s has accomulated too many errors, disabled"%self.netloc)<line_sep>self.feed.is_enabled=<false><block_end><return><block_end><def_stmt>update_feed_with_data self data<block_start>self._parse_feed(data)<line_sep>self.feed.save()<block_end><def_stmt>_parse_feed self data<block_start>soup=feedparser.parse(data)<line_sep># Got parsing error?
<if_stmt>hasattr(soup 'bozo')<and>soup.bozo<block_start>logger.debug(u"%s caused a parser error (%s), tried to parse it anyway"%(self.netloc soup.bozo_exception))<block_end>ft=FeedTranslator(soup.feed)<line_sep>self.feed.last_updated_on=ft.get_timestamp(self.instant)<line_sep>self.feed.alternate_link=ft.get_alternate_link()<line_sep>self.feed.title=self.feed.title<or>ft.get_title()# Do not set again if already set
#entries = []
feed_author=ft.get_author()<for_stmt>entry_dict soup.entries<block_start>t=EntryTranslator(entry_dict)<line_sep>link=t.get_link()<line_sep>guid=t.get_guid(default=link)<if_stmt><not>guid<block_start>logger.warn(u'could not find GUID for entry from %s, skipped'%self.netloc)<line_sep><continue><block_end>timestamp=t.get_timestamp(self.instant)<line_sep>content_type,content=t.get_content(('text/plain' ''))<line_sep># Skip ancient entries
<if_stmt>config.fetcher.max_history<and>(self.instant-timestamp).days<g>config.fetcher.max_history<block_start>logger.debug(u"entry %s from %s is over maximum history, skipped"%(guid self.netloc))<line_sep><continue><block_end><try_stmt># If entry is already in database with same hashed GUID, skip it
<block_start>Entry.get(guid_hash=make_sha1_hash(guid))<line_sep>logger.debug(u"duplicated entry %s, skipped"%guid)<line_sep><continue><block_end><except_stmt>Entry.DoesNotExist<block_start><pass><block_end>entry=Entry(feed=self.feed guid=guid link=link title=t.get_title(default='Untitled') author=t.get_author()<or>feed_author content=content content_type=content_type last_updated_on=timestamp)<line_sep># At this point we are pretty sure we doesn't have the entry
# already in the database so alert plugins and save data
trigger_event('entry_parsed' entry entry_dict)<line_sep>entry.save()<line_sep>#@@TODO: entries.append(entry)
logger.debug(u"parsed entry %s from %s"%(guid self.netloc))<block_end>#return entries
<block_end><def_stmt>_fetch_icon self<block_start><if_stmt><not>self.feed.icon<or><not>self.feed.icon_last_updated_on<or>(self.instant-self.feed.icon_last_updated_on).days<g>FETCH_ICONS_DELTA# Prefer alternate_link if available since self_link could
# point to Feed Burner or similar services
<block_start>self.feed.icon=self._google_favicon_fetcher(self.feed.alternate_link<or>self.feed.self_link)<line_sep>self.feed.icon_last_updated_on=self.instant<line_sep>logger.debug(u"fetched favicon %s..."%(self.feed.icon[:70]))<block_end><block_end><def_stmt>_google_favicon_fetcher self url<block_start>'''
Fetch a site favicon via Google service
'''<line_sep>endpoint="http://www.google.com/s2/favicons?domain=%s"%urlparse.urlsplit(url).hostname<try_stmt><block_start>response=fetch_url(endpoint)<block_end><except_stmt>RequestException exc<block_start>logger.warn(u"could not fetch favicon for %s (%s)"%(url exc))<line_sep><return>Feed.DEFAULT_ICON<block_end><return>make_data_uri(response.headers['Content-Type'] response.content)<block_end><def_stmt>add_synthesized_entry self title content_type content<block_start>'''
Create an HTML entry for this feed
'''<line_sep># Since we don't know the mechanism the feed used to build a GUID for its entries
# synthesize an tag URI from the link and a random string. This makes
# entries internally generated by Coldsweat reasonably globally unique
guid=ENTRY_TAG_URI%make_sha1_hash(self.feed.self_link+make_nonce())<line_sep>entry=Entry(feed=self.feed guid=guid title=title author='Coldsweat' content=content content_type=content_type last_updated_on=self.instant)<line_sep>entry.save()<line_sep>logger.debug(u"synthesized entry %s"%guid)<line_sep><return>entry<block_end><def_stmt>_synthesize_entry self reason<block_start>title=u'This feed has been disabled'<line_sep>content=render_template(os.path.join(template_dir '_entry_feed_disabled.html') {'reason':reason})<line_sep><return>self.add_synthesized_entry(title 'text/html' content)<block_end><block_end><def_stmt>fetch_url url timeout=10 etag=<none> modified_since=<none><block_start>'''
Fecth a given URL optionally issuing a 'Conditional GET' request
'''<line_sep>request_headers={'User-Agent':USER_AGENT}<line_sep># Conditional GET headers
<if_stmt>etag<and>modified_since<block_start>logger.debug(u"fetching %s with a conditional GET (%s %s)"%(url etag format_http_datetime(modified_since)))<line_sep>request_headers['If-None-Match']=etag<line_sep>request_headers['If-Modified-Since']=format_http_datetime(modified_since)<block_end><try_stmt><block_start>response=requests.get(url timeout=timeout headers=request_headers)<block_end><except_stmt>RequestException exc<block_start>logger.debug(u"tried to fetch %s but got %s"%(url exc.__class__.__name__))<line_sep><raise>exc<block_end><return>response<block_end># ------------------------------------------------------
# Custom error codes 9xx & exceptions
# ------------------------------------------------------
<class_stmt>DuplicatedFeedError(Exception)<block_start>code=900<line_sep>title='Duplicated feed'<line_sep>explanation='Feed address matches another already present in the database.'<block_end># Update WebOb status codes map
<for_stmt>klass (DuplicatedFeedError )<block_start>status_map[klass.code]=klass<block_end> |
# Leo colorizer control file for velocity mode.
# This file is in the public domain.
# Properties for velocity mode.
properties={"commentEnd":"*#" "commentStart":"#*" "lineComment":"##" }<line_sep># Attributes dict for velocity_main ruleset.
velocity_main_attributes_dict={"default":"null" "digit_re":"" "escape":"" "highlight_digits":"true" "ignore_case":"true" "no_word_sep":"" }<line_sep># Attributes dict for velocity_velocity ruleset.
velocity_velocity_attributes_dict={"default":"null" "digit_re":"" "escape":"" "highlight_digits":"true" "ignore_case":"true" "no_word_sep":"" }<line_sep># Attributes dict for velocity_javascript ruleset.
velocity_javascript_attributes_dict={"default":"MARKUP" "digit_re":"" "escape":"" "highlight_digits":"true" "ignore_case":"true" "no_word_sep":"" }<line_sep># Attributes dict for velocity_javascript2 ruleset.
velocity_javascript2_attributes_dict={"default":"MARKUP" "digit_re":"(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)" "escape":"\\" "highlight_digits":"true" "ignore_case":"false" "no_word_sep":"" }<line_sep># Attributes dict for velocity_back_to_html ruleset.
velocity_back_to_html_attributes_dict={"default":"MARKUP" "digit_re":"(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)" "escape":"\\" "highlight_digits":"true" "ignore_case":"false" "no_word_sep":"" }<line_sep># Attributes dict for velocity_css ruleset.
velocity_css_attributes_dict={"default":"MARKUP" "digit_re":"(0x[[:xdigit:]]+[lL]?|[[:digit:]]+(e[[:digit:]]*)?[lLdDfF]?)" "escape":"\\" "highlight_digits":"true" "ignore_case":"false" "no_word_sep":"" }<line_sep># Attributes dict for velocity_css2 ruleset.
velocity_css2_attributes_dict={"default":"MARKUP" "digit_re":"[[:digit:]]+(pt|pc|in|mm|cm|em|ex|px|ms|s|%)" "escape":"\\" "highlight_digits":"true" "ignore_case":"true" "no_word_sep":"-_" }<line_sep># Dictionary of attributes dictionaries for velocity mode.
attributesDictDict={"velocity_back_to_html":velocity_back_to_html_attributes_dict "velocity_css":velocity_css_attributes_dict "velocity_css2":velocity_css2_attributes_dict "velocity_javascript":velocity_javascript_attributes_dict "velocity_javascript2":velocity_javascript2_attributes_dict "velocity_main":velocity_main_attributes_dict "velocity_velocity":velocity_velocity_attributes_dict }<line_sep># Keywords dict for velocity_main ruleset.
velocity_main_keywords_dict={}<line_sep># Keywords dict for velocity_velocity ruleset.
velocity_velocity_keywords_dict={"#else":"keyword1" "#elseif":"keyword1" "#end":"keyword1" "#foreach":"keyword1" "#if":"keyword1" "#include":"keyword1" "#macro":"keyword1" "#parse":"keyword1" "#set":"keyword1" "#stop":"keyword1" }<line_sep># Keywords dict for velocity_javascript ruleset.
velocity_javascript_keywords_dict={}<line_sep># Keywords dict for velocity_javascript2 ruleset.
velocity_javascript2_keywords_dict={}<line_sep># Keywords dict for velocity_back_to_html ruleset.
velocity_back_to_html_keywords_dict={}<line_sep># Keywords dict for velocity_css ruleset.
velocity_css_keywords_dict={}<line_sep># Keywords dict for velocity_css2 ruleset.
velocity_css2_keywords_dict={}<line_sep># Dictionary of keywords dictionaries for velocity mode.
keywordsDictDict={"velocity_back_to_html":velocity_back_to_html_keywords_dict "velocity_css":velocity_css_keywords_dict "velocity_css2":velocity_css2_keywords_dict "velocity_javascript":velocity_javascript_keywords_dict "velocity_javascript2":velocity_javascript2_keywords_dict "velocity_main":velocity_main_keywords_dict "velocity_velocity":velocity_velocity_keywords_dict }<line_sep># Rules for velocity_main ruleset.
<def_stmt>velocity_rule0 colorer s i<block_start><return>colorer.match_span(s i kind="comment1" begin="<!--" end="-->" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="" exclude_match=<false> no_escape=<false> no_line_break=<false> no_word_break=<false>)<block_end><def_stmt>velocity_rule1 colorer s i<block_start><return>colorer.match_span(s i kind="markup" begin="<SCRIPT" end="</SCRIPT>" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="velocity::javascript" exclude_match=<false> no_escape=<false> no_line_break=<false> no_word_break=<false>)<block_end><def_stmt>velocity_rule2 colorer s i<block_start><return>colorer.match_span(s i kind="markup" begin="<STYLE" end="</STYLE>" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="velocity::css" exclude_match=<false> no_escape=<false> no_line_break=<false> no_word_break=<false>)<block_end><def_stmt>velocity_rule3 colorer s i<block_start><return>colorer.match_span(s i kind="keyword2" begin="<!" end=">" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="xml::dtd-tags" exclude_match=<false> no_escape=<false> no_line_break=<false> no_word_break=<false>)<block_end><def_stmt>velocity_rule4 colorer s i<block_start><return>colorer.match_span(s i kind="markup" begin="<" end=">" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="html::tags" exclude_match=<false> no_escape=<false> no_line_break=<false> no_word_break=<false>)<block_end><def_stmt>velocity_rule5 colorer s i<block_start><return>colorer.match_span(s i kind="literal2" begin="&" end=";" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="" exclude_match=<false> no_escape=<false> no_line_break=<false> no_word_break=<true>)<block_end># Rules dict for velocity_main ruleset.
rulesDict1={"&":[velocity_rule5 ] "<":[velocity_rule0 velocity_rule1 velocity_rule2 velocity_rule3 velocity_rule4 ] }<line_sep># Rules for velocity_velocity ruleset.
<def_stmt>velocity_rule6 colorer s i<block_start><return>colorer.match_span(s i kind="comment2" begin="#*" end="*#" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="" exclude_match=<false> no_escape=<false> no_line_break=<false> no_word_break=<false>)<block_end><def_stmt>velocity_rule7 colorer s i<block_start><return>colorer.match_eol_span(s i kind="comment3" seq="##" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="" exclude_match=<false>)<block_end><def_stmt>velocity_rule8 colorer s i<block_start><return>colorer.match_span(s i kind="keyword3" begin="${" end="}" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="" exclude_match=<false> no_escape=<false> no_line_break=<true> no_word_break=<false>)<block_end><def_stmt>velocity_rule9 colorer s i<block_start><return>colorer.match_mark_following(s i kind="keyword3" pattern="$!" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> exclude_match=<false>)<block_end><def_stmt>velocity_rule10 colorer s i<block_start><return>colorer.match_mark_following(s i kind="keyword3" pattern="$" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> exclude_match=<false>)<block_end><def_stmt>velocity_rule11 colorer s i<block_start><return>colorer.match_keywords(s i)<block_end># Rules dict for velocity_velocity ruleset.
rulesDict2={"#":[velocity_rule6 velocity_rule7 velocity_rule11 ] "$":[velocity_rule8 velocity_rule9 velocity_rule10 ] "0":[velocity_rule11 ] "1":[velocity_rule11 ] "2":[velocity_rule11 ] "3":[velocity_rule11 ] "4":[velocity_rule11 ] "5":[velocity_rule11 ] "6":[velocity_rule11 ] "7":[velocity_rule11 ] "8":[velocity_rule11 ] "9":[velocity_rule11 ] "@":[velocity_rule11 ] "A":[velocity_rule11 ] "B":[velocity_rule11 ] "C":[velocity_rule11 ] "D":[velocity_rule11 ] "E":[velocity_rule11 ] "F":[velocity_rule11 ] "G":[velocity_rule11 ] "H":[velocity_rule11 ] "I":[velocity_rule11 ] "J":[velocity_rule11 ] "K":[velocity_rule11 ] "L":[velocity_rule11 ] "M":[velocity_rule11 ] "N":[velocity_rule11 ] "O":[velocity_rule11 ] "P":[velocity_rule11 ] "Q":[velocity_rule11 ] "R":[velocity_rule11 ] "S":[velocity_rule11 ] "T":[velocity_rule11 ] "U":[velocity_rule11 ] "V":[velocity_rule11 ] "W":[velocity_rule11 ] "X":[velocity_rule11 ] "Y":[velocity_rule11 ] "Z":[velocity_rule11 ] "a":[velocity_rule11 ] "b":[velocity_rule11 ] "c":[velocity_rule11 ] "d":[velocity_rule11 ] "e":[velocity_rule11 ] "f":[velocity_rule11 ] "g":[velocity_rule11 ] "h":[velocity_rule11 ] "i":[velocity_rule11 ] "j":[velocity_rule11 ] "k":[velocity_rule11 ] "l":[velocity_rule11 ] "m":[velocity_rule11 ] "n":[velocity_rule11 ] "o":[velocity_rule11 ] "p":[velocity_rule11 ] "q":[velocity_rule11 ] "r":[velocity_rule11 ] "s":[velocity_rule11 ] "t":[velocity_rule11 ] "u":[velocity_rule11 ] "v":[velocity_rule11 ] "w":[velocity_rule11 ] "x":[velocity_rule11 ] "y":[velocity_rule11 ] "z":[velocity_rule11 ] }<line_sep># Rules for velocity_javascript ruleset.
<def_stmt>velocity_rule12 colorer s i<block_start><return>colorer.match_seq(s i kind="markup" seq=">" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="velocity::javascript2")<block_end><def_stmt>velocity_rule13 colorer s i<block_start><return>colorer.match_seq(s i kind="markup" seq="SRC=" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="velocity::back_to_html")<block_end># Rules dict for velocity_javascript ruleset.
rulesDict3={">":[velocity_rule12 ] "S":[velocity_rule13 ] }<line_sep># Rules for velocity_javascript2 ruleset.
# Rules dict for velocity_javascript2 ruleset.
rulesDict4={}<line_sep># Rules for velocity_back_to_html ruleset.
<def_stmt>velocity_rule14 colorer s i<block_start><return>colorer.match_seq(s i kind="markup" seq=">" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="velocity::main")<block_end># Rules dict for velocity_back_to_html ruleset.
rulesDict5={">":[velocity_rule14 ] }<line_sep># Rules for velocity_css ruleset.
<def_stmt>velocity_rule15 colorer s i<block_start><return>colorer.match_seq(s i kind="markup" seq=">" at_line_start=<false> at_whitespace_end=<false> at_word_start=<false> delegate="velocity::css2")<block_end># Rules dict for velocity_css ruleset.
rulesDict6={">":[velocity_rule15 ] }<line_sep># Rules for velocity_css2 ruleset.
# Rules dict for velocity_css2 ruleset.
rulesDict7={}<line_sep># x.rulesDictDict for velocity mode.
rulesDictDict={"velocity_back_to_html":rulesDict5 "velocity_css":rulesDict6 "velocity_css2":rulesDict7 "velocity_javascript":rulesDict3 "velocity_javascript2":rulesDict4 "velocity_main":rulesDict1 "velocity_velocity":rulesDict2 }<line_sep># Import dict for velocity mode.
importDict={"velocity_css2":["velocity_css2::velocity" "css::main" ] "velocity_javascript2":["velocity_javascript2::velocity" "javascript::main" ] "velocity_main":["velocity_main::velocity" ] }<line_sep> |
__author__="<EMAIL>"<line_sep>"""
Tagging BAM files with phasing info
"""<import_stmt>pysam<import_from_stmt>csv DictReader<def_stmt>main read_bam hap_info output_bam celltype_file=<none><block_start>d={}<line_sep>celltype_info={}<line_sep>#for r in DictReader(open('phased.partial.cleaned.hap_info.txt'),delimiter=','):
<for_stmt>r DictReader(open(hap_info) delimiter=',')<block_start>d[r['id']]=r['hap_postclean']<block_end><if_stmt>celltype_file<is><not><none><block_start><for_stmt>r DictReader(open(celltype_file) delimiter=',')<block_start><if_stmt>r['id']<in>d<block_start>celltype_info[r['id']]=r['Celltype'].replace(' ' '_').replace(':' '_')<block_end><block_end><block_end>reader=pysam.AlignmentFile(read_bam 'rb' check_sq=<false>)<line_sep>f2=pysam.AlignmentFile(output_bam 'wb' header=reader.header)<for_stmt>r reader<block_start>d2=r.to_dict()<if_stmt>r.qname<in>d<block_start>d2['tags'].append('RG:Z:'+str(d[r.qname]))<if_stmt>r.qname<in>celltype_info<block_start>d2['tags'].append('XC:Z:'+str(celltype_info[r.qname]))<block_end><block_end><else_stmt><block_start>d2['tags'].append('RG:Z:NA')<block_end>x=pysam.AlignedSegment.from_dict(d2 r.header)<line_sep>f2.write(x)<block_end>f2.close()<block_end><if_stmt>__name__<eq>"__main__"<block_start><import_from_stmt>argparse ArgumentParser<line_sep>parser=ArgumentParser("Tagging BAM files with phasing info")<line_sep>parser.add_argument("read_bam" help="Aligned BAM file that be tagged")<line_sep>parser.add_argument("hap_info" help="Comma-delimited hap info CSV, must have column 'id' and 'hap_postclean'")<line_sep>parser.add_argument("output_bam" help="Output tagged BAM filename")<line_sep>parser.add_argument("--celltype" default=<none> help="[Optional] Comma-delimited celltype info CSV, must have column 'id' and 'Celltype'")<line_sep>args=parser.parse_args()<line_sep>main(args.read_bam args.hap_info args.output_bam args.celltype)<block_end> |
<import_from_stmt>collections namedtuple<import_from_stmt>turtle fd heading lt pd position pu rt setheading setposition# pylint: disable=no-name-in-module
<import_from_stmt>pudzu.utils weighted_choice<class_stmt>LSystem<block_start>Rule=namedtuple("Rule" "predecessor successor weight" defaults=(1.0 ))<def_stmt>__init__ self axiom rules angle=4<block_start>self.axiom=axiom<line_sep>self.angle=360/angle<line_sep>self.rules={}<line_sep>self.weights={}<for_stmt>rule rules<block_start>pr=self.Rule(*rule)<line_sep>self.rules.setdefault(pr.predecessor []).append(pr.successor)<line_sep>self.weights.setdefault(pr.predecessor []).append(pr.weight)<block_end><block_end><def_stmt>expand self iterations<block_start>state=self.axiom<for_stmt>_ range(iterations)<block_start>state="".join([weighted_choice(self.rules.get(c [c]) self.weights.get(c [1]))<for>c state])<block_end><return>state<block_end><def_stmt>plot self screen iterations size reset=<true> tracer=(0 0)<block_start><if_stmt>reset<block_start>screen.clearscreen()<block_end>screen.tracer(*tracer)<line_sep>stack=[]<for_stmt>c self.expand(iterations)<block_start><if_stmt>c<eq>"F"<block_start>fd(size)<block_end><elif_stmt>c<eq>"G"<block_start>pu()<line_sep>fd(size)<line_sep>pd()<block_end><elif_stmt>c<eq>"+"<block_start>rt(self.angle)<block_end><elif_stmt>c<eq>"-"<block_start>lt(self.angle)<block_end><elif_stmt>c<eq>"["<block_start>stack.append((position() heading()))<block_end><elif_stmt>c<eq>"]"<block_start>p,h=stack.pop()<line_sep>pu()<line_sep>setposition(p)<line_sep>setheading(h)<line_sep>pd()<block_end><block_end>screen.update()<block_end><block_end>Koch=LSystem("F--F--F" [("F" "F+F--F+F")] 6)<line_sep>Dragon=LSystem("FX" [("F" "") ("Y" "+FX--FY+") ("X" "-FX++FY-")] 8)<line_sep>Plant07=LSystem("Z" [("Z" "ZFX[+Z][-Z]") ("X" "X[-FFF][+FFF]FX")] 14)<line_sep>Plant08=LSystem("SLFFF" [("S" "[+++Z][---Z]TS") ("Z" "+H[-Z]L") ("H" "-Z[+H]L") ("T" "TL") ("L" "[-FFF][+FFF]F")] 20)<line_sep>Sierpinski=LSystem("AF" [("A" "BF+AF+BF") ("B" "AF-BF-AF") ("F" "")] 6)<line_sep>Barnsley=LSystem("X" [("X" "F+[[X]-X]-F[-FX]+X") ("F" "FF")] 14.4)<line_sep>RandomWalk=LSystem("F" [("F" "FF") ("F" "F+F") ("F" "F++F") ("F" "F-F")] 4)<line_sep> |
<import_stmt>torch<import_from_stmt>torch nn<as>nn<import_from_stmt>torch.nn functional<as>F<import_from_stmt>torch.autograd Variable<import_from_stmt>model.tensorized_layers.graphsage BatchedGraphSAGE<class_stmt>DiffPoolAssignment(nn.Module)<block_start><def_stmt>__init__ self nfeat nnext<block_start>super().__init__()<line_sep>self.assign_mat=BatchedGraphSAGE(nfeat nnext use_bn=<true>)<block_end><def_stmt>forward self x adj log=<false><block_start>s_l_init=self.assign_mat(x adj)<line_sep>s_l=F.softmax(s_l_init dim=-1)<line_sep><return>s_l<block_end><block_end> |
# Time: O(1)
# Space: O(n)
<import_from_stmt>random randint<class_stmt>RandomizedSet(object)<block_start><def_stmt>__init__ self<block_start>"""
Initialize your data structure here.
"""<line_sep>self.__set=[]<line_sep>self.__used={}<block_end><def_stmt>insert self val<block_start>"""
Inserts a value to the set. Returns true if the set did not already contain the specified element.
:type val: int
:rtype: bool
"""<if_stmt>val<in>self.__used<block_start><return><false><block_end>self.__set<augadd>val <line_sep>self.__used[val]=len(self.__set)-1<line_sep><return><true><block_end><def_stmt>remove self val<block_start>"""
Removes a value from the set. Returns true if the set contained the specified element.
:type val: int
:rtype: bool
"""<if_stmt>val<not><in>self.__used<block_start><return><false><block_end>self.__used[self.__set[-1]]=self.__used[val]<line_sep>self.__set[self.__used[val]],self.__set[-1]=self.__set[-1] self.__set[self.__used[val]]<line_sep>self.__used.pop(val)<line_sep>self.__set.pop()<line_sep><return><true><block_end><def_stmt>getRandom self<block_start>"""
Get a random element from the set.
:rtype: int
"""<line_sep><return>self.__set[randint(0 len(self.__set)-1)]<block_end><block_end> |
"""
Multiple Servers linked via broadcaster example.
To run this example.
- 0. Setup a broadcast medium and pass its configuration to the endpoint (e.g. postgres on 'postgres://localhost:5432/' )
- 1. run this script for the servers (as many instances as you'd like) - use the PORT env-variable to run them on different ports
- 2. once the servers are up, run notifier_client_test.py and connect to one of them
- 3. send get request to one server on: '/trigger'
- 4. See that the client recives the event -no matter which server you connected it to, or which server got the initial trigger to publish
"""<import_stmt>sys<import_stmt>os<line_sep>sys.path.append(os.path.abspath(os.path.join(os.path.basename(__file__) "..")))<import_from_stmt>fastapi_websocket_pubsub PubSubEndpoint<import_stmt>asyncio<import_stmt>os<import_from_stmt>starlette.websockets WebSocket<import_stmt>uvicorn<import_from_stmt>fastapi FastAPI<import_from_stmt>fastapi.routing APIRouter<line_sep>PORT=int(os.environ.get("PORT")<or>"8000")<line_sep>app=FastAPI()<line_sep>router=APIRouter()<line_sep>endpoint=PubSubEndpoint(broadcaster="postgres://localhost:5432/")<line_sep>@router.websocket("/pubsub")<async_keyword><def_stmt>websocket_rpc_endpoint websocket:WebSocket<block_start><async_keyword><with_stmt>endpoint.broadcaster<block_start><await>endpoint.main_loop(websocket)<block_end><block_end>app.include_router(router)<async_keyword><def_stmt>events <block_start><await>asyncio.sleep(1)<line_sep><await>endpoint.publish(["guns" "germs"])<line_sep><await>asyncio.sleep(1)<line_sep><await>endpoint.publish(["germs"])<line_sep><await>asyncio.sleep(1)<line_sep><await>endpoint.publish(["steel"])<block_end>@app.get("/trigger")<async_keyword><def_stmt>trigger_events <block_start>asyncio.create_task(events())<block_end>uvicorn.run(app host="0.0.0.0" port=PORT)<line_sep> |
<import_stmt>matplotlib.pyplot<as>plt<import_stmt>numpy<as>np<def_stmt>plot_convolution f g<block_start>fig,(ax1 ax2 ax3)=plt.subplots(3 1)<line_sep>ax1.set_yticklabels([])<line_sep>ax1.set_xticklabels([])<line_sep>ax1.plot(f color='blue' label='f')<line_sep>ax1.legend()<line_sep>ax2.set_yticklabels([])<line_sep>ax2.set_xticklabels([])<line_sep>ax2.plot(g color='red' label='g')<line_sep>ax2.legend()<line_sep>filtered=np.convolve(f g "same")/sum(g)<line_sep>ax3.set_yticklabels([])<line_sep>ax3.set_xticklabels([])<line_sep>ax3.plot(filtered color='green' label='f * g')<line_sep>ax3.legend()<line_sep>plt.show()<block_end><def_stmt>plot_convolution_step_by_step f g<block_start>fig,(ax1 ax2 ax3 ax4 ax5)=plt.subplots(5 1)<line_sep>ax1.set_yticklabels([])<line_sep>ax1.set_xticklabels([])<line_sep>ax1.plot(f color='blue' label='f')<line_sep>ax1.plot(np.roll(g -10000) color='red' label='g')<line_sep>ax2.set_yticklabels([])<line_sep>ax2.set_xticklabels([])<line_sep>ax2.plot(f color='blue' label='f')<line_sep>ax2.plot(np.roll(g -5000) color='red' label='g')<line_sep>ax3.set_yticklabels([])<line_sep>ax3.set_xticklabels([])<line_sep>ax3.plot(f color='blue' label='f')<line_sep>ax3.plot(g color='red' label='g')<line_sep>ax4.set_yticklabels([])<line_sep>ax4.set_xticklabels([])<line_sep>ax4.plot(f color='blue' label='f')<line_sep>ax4.plot(np.roll(g 5000) color='red' label='g')<line_sep>ax5.set_yticklabels([])<line_sep>ax5.set_xticklabels([])<line_sep>ax5.plot(f color='blue' label='f')<line_sep>ax5.plot(np.roll(g 10000) color='red' label='g')<line_sep>plt.show()<block_end>signal=np.zeros(30000)<line_sep>signal[10000:20000]=1<line_sep>kernel=np.zeros(30000)<line_sep>kernel[10000:20000]=np.linspace(1 0 10000)<line_sep>plot_convolution(signal kernel)<line_sep>plot_convolution_step_by_step(signal kernel)<line_sep> |
<import_from_future_stmt> print_function<import_from_stmt>amd.rali.plugin.tf RALIIterator<import_from_stmt>amd.rali.pipeline Pipeline<import_stmt>amd.rali.ops<as>ops<import_stmt>amd.rali.types<as>types<import_stmt>sys<import_stmt>tensorflow.compat.v1<as>tf<line_sep>tf.disable_v2_behavior()<import_stmt>numpy<as>np<line_sep>############################### HYPER PARAMETERS FOR TRAINING ###############################
learning_rate=0.001<line_sep>image_size=28<line_sep># Network Parameters
n_hidden_1=256# 1st layer number of neurons
n_hidden_2=256# 2nd layer number of neurons
num_input=784# MNIST data input (img shape: 28*28)
num_classes=10# MNIST total classes (0-9 digits)
############################### HYPER PARAMETERS FOR TRAINING ###############################
<def_stmt>get_label_one_hot label_ndArray<block_start>one_hot_vector_list=[]<for_stmt>label label_ndArray<block_start>one_hot_vector=np.zeros(num_classes)<line_sep>np.put(one_hot_vector label-1 1)<line_sep>one_hot_vector_list.append(one_hot_vector)<block_end><return>one_hot_vector_list<block_end># Create model
weights={'h1':tf.Variable(tf.random_normal([num_input n_hidden_1])) 'h2':tf.Variable(tf.random_normal([n_hidden_1 n_hidden_2])) 'out':tf.Variable(tf.random_normal([n_hidden_2 num_classes]))}<line_sep>biases={'b1':tf.Variable(tf.random_normal([n_hidden_1])) 'b2':tf.Variable(tf.random_normal([n_hidden_2])) 'out':tf.Variable(tf.random_normal([num_classes]))}<def_stmt>neural_net x# Hidden fully connected layer with 256 neurons
<block_start>layer_1=tf.add(tf.matmul(x weights['h1']) biases['b1'])<line_sep># Hidden fully connected layer with 256 neurons
layer_1=tf.nn.relu(layer_1)<line_sep>layer_2=tf.add(tf.matmul(layer_1 weights['h2']) biases['b2'])<line_sep>layer_2=tf.nn.relu(layer_2)<line_sep># Output fully connected layer with a neuron for each class
out_layer=tf.matmul(layer_2 weights['out'])+biases['out']<line_sep><return>out_layer<block_end>#helper function not used in training
<def_stmt>decode tfrecord_serialized<block_start>tfrecord_features=tf.parse_single_example(tfrecord_serialized features={'image/height':tf.FixedLenFeature([] tf.int64) 'image/width':tf.FixedLenFeature([] tf.int64) 'image/class/label':tf.FixedLenFeature([] tf.int64) 'image/raw':tf.FixedLenFeature([] tf.string) } name='features')<line_sep>image=tf.decode_raw(tfrecord_features['image/raw'] tf.float32)<line_sep>image.set_shape([784])<line_sep>label=tf.cast(tfrecord_features['image/class/label'] tf.int32)<line_sep># image_batch, label_batch = tf.train.batch([image, label], batch_size=bs)
<return>image label<block_end>#RALI pipeline
<class_stmt>HybridPipe(Pipeline)<block_start><def_stmt>__init__ self feature_key_map tfrecordreader_type batch_size num_threads device_id data_dir crop rali_cpu=<true><block_start>super(HybridPipe self).__init__(batch_size num_threads device_id seed=12+device_id rali_cpu=rali_cpu)<line_sep>self.input=ops.TFRecordReader(path=data_dir index_path="" reader_type=tfrecordreader_type user_feature_key_map=feature_key_map features={'image/encoded':tf.FixedLenFeature(() tf.string "") 'image/class/label':tf.FixedLenFeature([1] tf.int64 -1) 'image/filename':tf.FixedLenFeature(() tf.string "")} )<line_sep>rali_device='cpu'<if>rali_cpu<else>'gpu'<line_sep>decoder_device='cpu'<if>rali_cpu<else>'mixed'<line_sep>self.decode=ops.ImageDecoderRaw(user_feature_key_map=feature_key_map device=decoder_device output_type=types.RGB)<line_sep>#self.res = ops.Resize(device=rali_device, resize_x=crop[0], resize_y=crop[1])
self.cmnp=ops.CropMirrorNormalize(device="cpu" output_dtype=types.FLOAT output_layout=types.NCHW crop=(crop crop) image_type=types.GRAY mean=[0 0 0] std=[255 255 255] mirror=0)<line_sep>self.coin=ops.CoinFlip(probability=0.5)<line_sep>print('rali "{0}" variant'.format(rali_device))<block_end><def_stmt>define_graph self<block_start>inputs=self.input(name="Reader")<line_sep>images=inputs["image/encoded"]<line_sep>labels=inputs["image/class/label"]<line_sep>images=self.decode(images)<line_sep>#rng = self.coin()
output=self.cmnp(images)<line_sep><return>[output labels]<block_end><block_end># compute accuracy
<def_stmt>compute_accuracy predictions labels<block_start>correct_predictions=tf.equal(tf.argmax(predictions 1) tf.argmax(labels 1))<line_sep>accuracy=tf.reduce_mean(tf.cast(correct_predictions tf.float32))<line_sep><return>accuracy<block_end><def_stmt>train_mnist_rali data_path _rali_cpu batch_size# setup keep_prob
<block_start>input_X=tf.placeholder('float32' shape=(batch_size 784))<line_sep>labels=tf.placeholder('float32' shape=(batch_size 10))<line_sep>logits=neural_net(input_X)<line_sep>cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=labels logits=logits) name="loss")<line_sep>optimizer=tf.train.AdamOptimizer().minimize(cost)<line_sep>train_prediction=tf.nn.softmax(logits)<line_sep>accuracy=compute_accuracy(train_prediction labels)<line_sep>#correct_label = tf.argmax(labels, 1)
num_epochs=10<line_sep>crop_size=28<line_sep>TFRecordReaderType=0<line_sep>featureKeyMap={'image/encoded':'image_raw' 'image/class/label':'label' 'image/filename':''}<line_sep>trainPipe=HybridPipe(feature_key_map=featureKeyMap tfrecordreader_type=TFRecordReaderType batch_size=batch_size num_threads=1 device_id=0 data_dir=data_path+"/train" crop=crop_size rali_cpu=_rali_cpu)<line_sep>valPipe=HybridPipe(feature_key_map=featureKeyMap tfrecordreader_type=TFRecordReaderType batch_size=batch_size num_threads=1 device_id=0 data_dir=data_path+"/val" crop=crop_size rali_cpu=_rali_cpu)<line_sep>trainPipe.build()<line_sep>valPipe.build()<line_sep>trainIterator=RALIIterator(trainPipe)<line_sep>valIterator=RALIIterator(valPipe)<with_stmt>tf.Session()<as>sess<block_start>sess.run(tf.initialize_all_variables())<for_stmt>epoch range(num_epochs)<block_start>print('\n\n----------------------------Training Model for Epoch: ' epoch "-----------------------------------------------")<line_sep>epoch_loss=0<line_sep>train_accuracy=0<for_stmt>i,(image_train label_train) enumerate(trainIterator 0)<block_start>image_train_res=image_train.reshape(batch_size 784)<line_sep>train_label_one_hot_list=get_label_one_hot(label_train)<line_sep>_,c,tacc=sess.run([optimizer cost accuracy] feed_dict={input_X:image_train_res labels:train_label_one_hot_list})<line_sep>epoch_loss<augadd>c<line_sep>train_accuracy<augadd>tacc<block_end>print('Epoch' epoch 'completed out of' num_epochs 'loss:' epoch_loss 'accuracy:' (train_accuracy<times>100)/i 'count :' i)<line_sep>#run evaluation for every epoch
mean_acc=0<line_sep>print("\n\n----------------------------Evaluating Model ---------------------------------------------------------------")<for_stmt>j,(val_image_ndArray val_label_ndArray) enumerate(valIterator 0)#val_image_ndArray_transposed = np.transpose(val_image_ndArray, [0, 2, 3, 1])
<block_start>val_image_ndArray_res=val_image_ndArray.reshape(batch_size 784)<line_sep>val_label_one_hot_list=get_label_one_hot(val_label_ndArray)<line_sep>val_accuracy=sess.run(accuracy #[optimizer, accuracy, prediction, correct_label, correct_pred],
feed_dict={input_X:val_image_ndArray_res labels:val_label_one_hot_list})<line_sep>mean_acc<augadd>val_accuracy<line_sep>#mean_loss = mean_loss + val_loss
#num_correct_predicate = 0
#for predicate in correct_predicate:
# if predicate == True:
# num_correct_predicate += 1
#print ("Step :: %s\tTarget :: %s\tPrediction :: %s\tCorrect Predictions :: %s/%s\tValidation Loss :: %.2f\tValidation Accuracy :: %.2f%%\t" % (j, val_target, val_prediction, num_correct_predicate, len(correct_predicate), val_loss, (val_accuracy * 100)))
<block_end>mean_acc=(mean_acc<times>100)/j<line_sep>#mean_loss = (mean_loss * 100)/ j
print("\nSUMMARY:\nMean Accuracy :: %.2f%% count: %d"%(mean_acc j))<block_end><block_end><block_end><def_stmt>main <block_start><if_stmt>len(sys.argv)<l>4<block_start>print('Please pass mnistTFRecord_dir cpu/gpu batch_size')<line_sep>exit(0)<block_end>image_path=sys.argv[1]<if_stmt>(sys.argv[2]<eq>"cpu")<block_start>_rali_cpu=<true><block_end><else_stmt><block_start>_rali_cpu=<false><block_end>bs=int(sys.argv[3])<line_sep>train_mnist_rali(image_path _rali_cpu bs)<block_end><if_stmt>__name__<eq>'__main__'<block_start>main()<block_end> |
<import_stmt>json<import_stmt>os.path<import_from_stmt>unittest.mock patch<import_from_stmt>twisted.trial unittest<import_from_stmt>scripts.casefold_db calculate_lookup_hash update_global_associations update_local_associations <import_from_stmt>sydent.util json_decoder<import_from_stmt>sydent.util.emailutils sendEmail<import_from_stmt>tests.utils make_sydent<class_stmt>MigrationTestCase(unittest.TestCase)<block_start><def_stmt>create_signedassoc self medium address mxid ts not_before not_after<block_start><return>{"medium":medium "address":address "mxid":mxid "ts":ts "not_before":not_before "not_after":not_after }<block_end><def_stmt>setUp self# Create a new sydent
<block_start>config={"general":{"templates.path":os.path.join(os.path.dirname(os.path.dirname(__file__)) "res") } "crypto":{"ed25519.signingkey":"<KEY>"} }<line_sep>self.sydent=make_sydent(test_config=config)<line_sep># create some local associations
associations=[]<for_stmt>i range(10)<block_start>address="<EMAIL>"%i<line_sep>associations.append({"medium":"email" "address":address "lookup_hash":calculate_lookup_hash(self.sydent address) "mxid":"@bob%d:example.com"%i "ts":(i<times>10000) "not_before":0 "not_after":99999999999 })<block_end># create some casefold-conflicting associations
<for_stmt>i range(5)<block_start>address="<EMAIL>"%i<line_sep>associations.append({"medium":"email" "address":address "lookup_hash":calculate_lookup_hash(self.sydent address) "mxid":"@otherbob%d:example.com"%i "ts":(i<times>10000) "not_before":0 "not_after":99999999999 })<block_end># add all associations to db
cur=self.sydent.db.cursor()<line_sep>cur.executemany("INSERT INTO local_threepid_associations "<concat>"(medium, address, lookup_hash, mxid, ts, notBefore, notAfter) "<concat>"VALUES (?, ?, ?, ?, ?, ?, ?)" [(assoc["medium"] assoc["address"] assoc["lookup_hash"] assoc["mxid"] assoc["ts"] assoc["not_before"] assoc["not_after"] )<for>assoc associations] )<line_sep>self.sydent.db.commit()<line_sep># create some global associations
associations=[]<line_sep>originServer=self.sydent.config.general.server_name<for_stmt>i range(10)<block_start>address="<EMAIL>"%i<line_sep>mxid="@bob%d:example.com"%i<line_sep>ts=10000<times>i<line_sep>associations.append({"medium":"email" "address":address "lookup_hash":calculate_lookup_hash(self.sydent address) "mxid":mxid "ts":ts "not_before":0 "not_after":99999999999 "originServer":originServer "originId":i "sgAssoc":json.dumps(self.create_signedassoc("email" address mxid ts 0 99999999999)) })<block_end># create some casefold-conflicting associations
<for_stmt>i range(5)<block_start>address="<EMAIL>"%i<line_sep>mxid="@BOB%d:example.com"%i<line_sep>ts=10000<times>i<line_sep>associations.append({"medium":"email" "address":address "lookup_hash":calculate_lookup_hash(self.sydent address) "mxid":mxid "ts":ts+1 "not_before":0 "not_after":99999999999 "originServer":originServer "originId":i+10 "sgAssoc":json.dumps(self.create_signedassoc("email" address mxid ts 0 99999999999)) })<block_end># add all associations to db
cur=self.sydent.db.cursor()<line_sep>cur.executemany("INSERT INTO global_threepid_associations "<concat>"(medium, address, lookup_hash, mxid, ts, notBefore, notAfter, originServer, originId, sgAssoc) "<concat>"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" [(assoc["medium"] assoc["address"] assoc["lookup_hash"] assoc["mxid"] assoc["ts"] assoc["not_before"] assoc["not_after"] assoc["originServer"] assoc["originId"] assoc["sgAssoc"] )<for>assoc associations] )<line_sep>self.sydent.db.commit()<block_end><def_stmt>test_migration_email self<block_start><with_stmt>patch("sydent.util.emailutils.smtplib")<as>smtplib# self.sydent.config.email.template is deprecated
<block_start><if_stmt>self.sydent.config.email.template<is><none><block_start>templateFile=self.sydent.get_branded_template(<none> "migration_template.eml" )<block_end><else_stmt><block_start>templateFile=self.sydent.config.email.template<block_end>sendEmail(self.sydent templateFile "<EMAIL>" {"mxid":"@bob:example.com" "subject_header_value":"MatrixID Deletion" } )<line_sep>smtp=smtplib.SMTP.return_value<line_sep>email_contents=smtp.sendmail.call_args[0][2].decode("utf-8")<line_sep>self.assertIn("In the past" email_contents)<line_sep># test email was sent
smtp.sendmail.assert_called()<block_end><block_end><def_stmt>test_local_db_migration self<block_start><with_stmt>patch("sydent.util.emailutils.smtplib")<as>smtplib<block_start>update_local_associations(self.sydent self.sydent.db send_email=<true> dry_run=<false> test=<true> )<block_end># test 5 emails were sent
smtp=smtplib.SMTP.return_value<line_sep>self.assertEqual(smtp.sendmail.call_count 5)<line_sep># don't send emails to people who weren't affected
self.assertNotIn(smtp.sendmail.call_args_list ["<EMAIL>" "<EMAIL>" "<EMAIL>" "<EMAIL>" "<EMAIL>" ] )<line_sep># make sure someone who is affected gets email
self.assertIn("<EMAIL>" smtp.sendmail.call_args_list[0][0])<line_sep>cur=self.sydent.db.cursor()<line_sep>res=cur.execute("SELECT * FROM local_threepid_associations")<line_sep>db_state=res.fetchall()<line_sep># five addresses should have been deleted
self.assertEqual(len(db_state) 10)<line_sep># iterate through db and make sure all addresses are casefolded and hash matches casefolded address
<for_stmt>row db_state<block_start>casefolded=row[2].casefold()<line_sep>self.assertEqual(row[2] casefolded)<line_sep>self.assertEqual(calculate_lookup_hash(self.sydent row[2]) calculate_lookup_hash(self.sydent casefolded) )<block_end><block_end><def_stmt>test_global_db_migration self<block_start>update_global_associations(self.sydent self.sydent.db dry_run=<false> )<line_sep>cur=self.sydent.db.cursor()<line_sep>res=cur.execute("SELECT * FROM global_threepid_associations")<line_sep>db_state=res.fetchall()<line_sep># five addresses should have been deleted
self.assertEqual(len(db_state) 10)<line_sep># iterate through db and make sure all addresses are casefolded and hash matches casefolded address
# and make sure the casefolded address matches the address in sgAssoc
<for_stmt>row db_state<block_start>casefolded=row[2].casefold()<line_sep>self.assertEqual(row[2] casefolded)<line_sep>self.assertEqual(calculate_lookup_hash(self.sydent row[2]) calculate_lookup_hash(self.sydent casefolded) )<line_sep>sgassoc=json_decoder.decode(row[9])<line_sep>self.assertEqual(row[2] sgassoc["address"])<block_end><block_end><def_stmt>test_local_no_email_does_not_send_email self<block_start><with_stmt>patch("sydent.util.emailutils.smtplib")<as>smtplib<block_start>update_local_associations(self.sydent self.sydent.db send_email=<false> dry_run=<false> test=<true> )<line_sep>smtp=smtplib.SMTP.return_value<line_sep># test no emails were sent
self.assertEqual(smtp.sendmail.call_count 0)<block_end><block_end><def_stmt>test_dry_run_does_nothing self# reset DB
<block_start>self.setUp()<line_sep>cur=self.sydent.db.cursor()<line_sep># grab a snapshot of global table before running script
res1=cur.execute("SELECT mxid FROM global_threepid_associations")<line_sep>list1=res1.fetchall()<with_stmt>patch("sydent.util.emailutils.smtplib")<as>smtplib<block_start>update_global_associations(self.sydent self.sydent.db dry_run=<true> )<block_end># test no emails were sent
smtp=smtplib.SMTP.return_value<line_sep>self.assertEqual(smtp.sendmail.call_count 0)<line_sep>res2=cur.execute("SELECT mxid FROM global_threepid_associations")<line_sep>list2=res2.fetchall()<line_sep>self.assertEqual(list1 list2)<line_sep># grab a snapshot of local table db before running script
res3=cur.execute("SELECT mxid FROM local_threepid_associations")<line_sep>list3=res3.fetchall()<with_stmt>patch("sydent.util.emailutils.smtplib")<as>smtplib<block_start>update_local_associations(self.sydent self.sydent.db send_email=<true> dry_run=<true> test=<true> )<block_end># test no emails were sent
smtp=smtplib.SMTP.return_value<line_sep>self.assertEqual(smtp.sendmail.call_count 0)<line_sep>res4=cur.execute("SELECT mxid FROM local_threepid_associations")<line_sep>list4=res4.fetchall()<line_sep>self.assertEqual(list3 list4)<block_end><block_end> |
<import_stmt>sys<import_stmt>soundcard<import_stmt>numpy<import_stmt>pytest<line_sep>skip_if_not_linux=pytest.mark.skipif(sys.platform<ne>'linux' reason='Only implemented for PulseAudio so far')<line_sep>ones=numpy.ones(1024)<line_sep>signal=numpy.concatenate([[ones] [-ones]]).T<def_stmt>test_speakers <block_start><for_stmt>speaker soundcard.all_speakers()<block_start><assert_stmt>isinstance(speaker.name str)<assert_stmt>hasattr(speaker 'id')<assert_stmt>isinstance(speaker.channels int)<assert_stmt>speaker.channels<g>0<block_end><block_end><def_stmt>test_microphones <block_start><for_stmt>microphone soundcard.all_microphones()<block_start><assert_stmt>isinstance(microphone.name str)<assert_stmt>hasattr(microphone 'id')<assert_stmt>isinstance(microphone.channels int)<assert_stmt>microphone.channels<g>0<block_end><block_end><def_stmt>test_default_playback <block_start>soundcard.default_speaker().play(signal 44100 channels=2)<block_end><def_stmt>test_default_record <block_start>recording=soundcard.default_microphone().record(1024 44100)<assert_stmt>len(recording<eq>1024)<block_end><def_stmt>test_default_blockless_record <block_start>recording=soundcard.default_microphone().record(<none> 44100)<block_end>@skip_if_not_linux<def_stmt>test_name # The default is the application name, so when run from pytest,
# it’s “pytest” or “_jb_pytest_runner.py” or so.
<block_start><assert_stmt>'pytest'<in>soundcard.get_name()<line_sep>soundcard.set_name('testapp')<assert_stmt>soundcard.get_name()<eq>'testapp'<block_end>@skip_if_not_linux@pytest.mark.parametrize("argv,progname" [(["./script.py"] "script.py") # chmod +x script.py; ./script.py
(["path/to/script.py"] "script.py") # python path/to/script.py or
# python -m path.to.script
(["module/__main__.py"] "module") # python -m module
(["-m" "module.submodule"] "module.submodule") # rare unresolved case
(["-c" "import soundcard; soundcard.foo()"] "import soundcard; soundcard.fo...") ])<def_stmt>test_infer_name monkeypatch argv progname<block_start>infer=soundcard.pulseaudio._PulseAudio._infer_program_name<line_sep>monkeypatch.setattr(sys "argv" argv)<assert_stmt>infer()<eq>progname<block_end>@pytest.fixture<def_stmt>loopback_speaker <block_start><import_stmt>sys<if_stmt>sys.platform<eq>'win32'# must install https://www.vb-audio.com/Cable/index.htm
<block_start><return>soundcard.get_speaker('Cable')<block_end><elif_stmt>sys.platform<eq>'darwin'# must install soundflower
<block_start><return>soundcard.get_speaker('Soundflower64')<block_end><elif_stmt>sys.platform<eq>'linux'# pacmd load-module module-null-sink channels=6 rate=48000
<block_start><return>soundcard.get_speaker('Null')<block_end><else_stmt><block_start><raise>RuntimeError('Unknown platform {}'.format(sys.platform))<block_end><block_end>@pytest.fixture<def_stmt>loopback_player loopback_speaker<block_start><with_stmt>loopback_speaker.player(48000 channels=2 blocksize=512)<as>player<block_start><yield>player<block_end><block_end>@pytest.fixture<def_stmt>loopback_microphone <block_start><if_stmt>sys.platform<eq>'win32'# must install https://www.vb-audio.com/Cable/index.htm
<block_start><return>soundcard.get_microphone('Cable')<block_end><elif_stmt>sys.platform<eq>'darwin'# must install soundflower
<block_start><return>soundcard.get_microphone('Soundflower64')<block_end><elif_stmt>sys.platform<eq>'linux'<block_start><return>soundcard.get_microphone('Null' include_loopback=<true>)<block_end><else_stmt><block_start><raise>RuntimeError('Unknown platform {}'.format(sys.platform))<block_end><block_end>@pytest.fixture<def_stmt>loopback_recorder loopback_microphone<block_start><with_stmt>loopback_microphone.recorder(48000 channels=2 blocksize=512)<as>recorder<block_start><yield>recorder<block_end><block_end><def_stmt>test_loopback_playback loopback_player loopback_recorder<block_start>loopback_player.play(signal)<line_sep>recording=loopback_recorder.record(1024<times>10)<assert_stmt>recording.shape[1]<eq>2<line_sep>left,right=recording.T<assert_stmt>left.mean()<g>0<assert_stmt>right.mean()<l>0<assert_stmt>(left<g>0.5).sum()<eq>len(signal)<assert_stmt>(right<l>-0.5).sum()<eq>len(signal)<block_end><def_stmt>test_loopback_reverse_recorder_channelmap loopback_player loopback_microphone<block_start><with_stmt>loopback_microphone.recorder(48000 channels=[1 0] blocksize=512)<as>loopback_recorder<block_start>loopback_player.play(signal)<line_sep>recording=loopback_recorder.record(1024<times>12)<block_end><assert_stmt>recording.shape[1]<eq>2<line_sep>left,right=recording.T<assert_stmt>right.mean()<g>0<assert_stmt>left.mean()<l>0<assert_stmt>(right<g>0.5).sum()<eq>len(signal)<assert_stmt>(left<l>-0.5).sum()<eq>len(signal)<block_end><def_stmt>test_loopback_reverse_player_channelmap loopback_speaker loopback_recorder<block_start><with_stmt>loopback_speaker.player(48000 channels=[1 0] blocksize=512)<as>loopback_player<block_start>loopback_player.play(signal)<line_sep>recording=loopback_recorder.record(1024<times>12)<block_end><assert_stmt>recording.shape[1]<eq>2<line_sep>left,right=recording.T<assert_stmt>right.mean()<g>0<assert_stmt>left.mean()<l>0<assert_stmt>(right<g>0.5).sum()<eq>len(signal)<assert_stmt>(left<l>-0.5).sum()<eq>len(signal)<block_end><def_stmt>test_loopback_mono_player_channelmap loopback_speaker loopback_recorder<block_start><with_stmt>loopback_speaker.player(48000 channels=[0] blocksize=512)<as>loopback_player<block_start>loopback_player.play(signal[: 0])<line_sep>recording=loopback_recorder.record(1024<times>12)<block_end><assert_stmt>recording.shape[1]<eq>2<line_sep>left,right=recording.T<assert_stmt>left.mean()<g>0<if_stmt>sys.platform<eq>'linux'# unmapped channels on linux are filled with the mean of other channels
<block_start><assert_stmt>right.mean()<l>left.mean()<block_end><else_stmt><block_start><assert_stmt>abs(right.mean())<l>0.01# something like zero
<block_end><assert_stmt>(left<g>0.5).sum()<eq>len(signal)<block_end><def_stmt>test_loopback_mono_recorder_channelmap loopback_player loopback_microphone<block_start><with_stmt>loopback_microphone.recorder(48000 channels=[0] blocksize=512)<as>loopback_recorder<block_start>loopback_player.play(signal)<line_sep>recording=loopback_recorder.record(1024<times>12)<block_end><assert_stmt>len(recording.shape)<eq>1<or>recording.shape[1]<eq>1<assert_stmt>recording.mean()<g>0<assert_stmt>(recording<g>0.5).sum()<eq>len(signal)<block_end><def_stmt>test_loopback_multichannel_channelmap loopback_speaker loopback_microphone<block_start><with_stmt>loopback_speaker.player(48000 channels=[2 0] blocksize=512)<as>loopback_player<block_start><with_stmt>loopback_microphone.recorder(48000 channels=[2 0] blocksize=512)<as>loopback_recorder<block_start>loopback_player.play(signal)<line_sep>recording=loopback_recorder.record(1024<times>12)<block_end><block_end><assert_stmt>len(recording.shape)<eq>2<line_sep>left,right=recording.T<assert_stmt>left.mean()<g>0<assert_stmt>right.mean()<l>0<assert_stmt>(left<g>0.5).sum()<eq>len(signal)<assert_stmt>(right<l>-0.5).sum()<eq>len(signal)<block_end> |
"""added anomaly config to kpi
Revision ID: c0e8d68e84fa
Revises: <PASSWORD>
Create Date: 2021-09-02 09:08:21.174195
"""<import_from_stmt>alembic op<import_stmt>sqlalchemy<as>sa<line_sep># revision identifiers, used by Alembic.
revision='c0e8d68e84fa'<line_sep>down_revision='<PASSWORD>0d4ab3bc9'<line_sep>branch_labels=<none><line_sep>depends_on=<none><def_stmt>upgrade # ### commands auto generated by Alembic - please adjust! ###
<block_start>op.add_column('kpi' sa.Column('anomaly_params' sa.JSON() nullable=<true>))<line_sep>op.add_column('kpi' sa.Column('anomaly_frequency' sa.String(length=80) nullable=<true>))<line_sep># ### end Alembic commands ###
<block_end><def_stmt>downgrade # ### commands auto generated by Alembic - please adjust! ###
<block_start>op.drop_column('kpi' 'anomaly_frequency')<line_sep>op.drop_column('kpi' 'anomaly_params')<line_sep># ### end Alembic commands ###
<block_end> |
<import_stmt>numpy<as>np<import_from_stmt>hls4ml.model.types CompressedType NamedType ExponentType FixedPrecisionType IntegerPrecisionType XnorPrecisionType ExponentPrecisionType TensorVariable PackedType WeightVariable<line_sep>#region Precision types
<class_stmt>PrecisionDefinition(object)<block_start><def_stmt>definition_cpp self<block_start><raise>NotImplementedError<block_end><block_end><class_stmt>APIntegerPrecisionDefinition(PrecisionDefinition)<block_start><def_stmt>definition_cpp self<block_start>typestring='ap_{signed}int<{width}>'.format(signed='u'<if><not>self.signed<else>'' width=self.width)<line_sep><return>typestring<block_end><block_end><class_stmt>APFixedPrecisionDefinition(PrecisionDefinition)<block_start><def_stmt>_rounding_mode_cpp self mode<block_start><if_stmt>mode<is><not><none><block_start><return>'AP_'+str(mode)<block_end><block_end><def_stmt>_saturation_mode_cpp self mode<block_start><if_stmt>mode<is><not><none><block_start><return>'AP_'+str(mode)<block_end><block_end><def_stmt>definition_cpp self<block_start>args=[self.width self.integer self._rounding_mode_cpp(self.rounding_mode) self._saturation_mode_cpp(self.saturation_mode) self.saturation_bits]<line_sep>args=','.join([str(arg)<for>arg args<if>arg<is><not><none>])<line_sep>typestring='ap_{signed}fixed<{args}>'.format(signed='u'<if><not>self.signed<else>'' args=args)<line_sep><return>typestring<block_end><block_end><class_stmt>ACIntegerPrecisionDefinition(PrecisionDefinition)<block_start><def_stmt>definition_cpp self<block_start>typestring='ac_int<{width}, {signed}>'.format(width=self.width signed=str(self.signed).lower())<line_sep><return>typestring<block_end><block_end><class_stmt>ACFixedPrecisionDefinition(PrecisionDefinition)<block_start><def_stmt>_rounding_mode_cpp self mode<block_start><if_stmt>mode<is><not><none><block_start><return>'AC_'+str(mode)<block_end><block_end><def_stmt>_saturation_mode_cpp self mode<block_start><if_stmt>mode<is><not><none><block_start><return>'AC_'+str(mode)<block_end><block_end><def_stmt>definition_cpp self<block_start>args=[self.width self.integer str(self.signed).lower() self._rounding_mode_cpp(self.rounding_mode) self._saturation_mode_cpp(self.saturation_mode) self.saturation_bits]<line_sep>args=','.join([str(arg)<for>arg args<if>arg<is><not><none>])<line_sep>typestring='ac_fixed<{args}>'.format(args=args)<line_sep><return>typestring<block_end><block_end><class_stmt>PrecisionConverter(object)<block_start><def_stmt>convert self precision_type<block_start><raise>NotImplementedError<block_end><block_end><class_stmt>FixedPrecisionConverter(PrecisionConverter)<block_start><def_stmt>__init__ self type_map prefix<block_start>self.type_map=type_map<line_sep>self.prefix=prefix<block_end><def_stmt>convert self precision_type<block_start>type_cls=type(precision_type)<line_sep>type_cls_name=type_cls.__name__<line_sep># If the type is already converted, do nothing
<if_stmt>type_cls_name.startswith(self.prefix)<block_start><return>precision_type<block_end>definition_cls=self.type_map.get(type_cls <none>)<if_stmt>definition_cls<is><not><none><block_start>precision_type.__class__=type(self.prefix+type_cls_name (type_cls definition_cls) {})<line_sep><return>precision_type<block_end><else_stmt><block_start><raise>Exception('Cannot convert precision type to {}: {}'.format(self.prefix precision_type.__class__.__name__))<block_end><block_end><block_end><class_stmt>APTypeConverter(FixedPrecisionConverter)<block_start><def_stmt>__init__ self<block_start>super().__init__(type_map={FixedPrecisionType:APFixedPrecisionDefinition IntegerPrecisionType:APIntegerPrecisionDefinition ExponentPrecisionType:APIntegerPrecisionDefinition XnorPrecisionType:APIntegerPrecisionDefinition } prefix='AP')<block_end><block_end><class_stmt>ACTypeConverter(FixedPrecisionConverter)<block_start><def_stmt>__init__ self<block_start>super().__init__(type_map={FixedPrecisionType:ACFixedPrecisionDefinition IntegerPrecisionType:ACIntegerPrecisionDefinition ExponentPrecisionType:ACIntegerPrecisionDefinition XnorPrecisionType:ACIntegerPrecisionDefinition } prefix='AC')<block_end><block_end>#endregion
#region Data types
<class_stmt>TypeDefinition(object)<block_start><def_stmt>definition_cpp self<block_start><raise>NotImplementedError<block_end><block_end><class_stmt>TypePrecisionConverter(object)<block_start><def_stmt>convert_precision self precision_converter<block_start>self.precision=precision_converter.convert(self.precision)<block_end><block_end><class_stmt>NamedTypeConverter(TypeDefinition TypePrecisionConverter)<block_start><def_stmt>definition_cpp self<block_start><return>'typedef {precision} {name};\n'.format(name=self.name precision=self.precision.definition_cpp())<block_end><block_end><class_stmt>CompressedTypeConverter(TypeDefinition TypePrecisionConverter)<block_start><def_stmt>definition_cpp self<block_start>cpp_fmt=('typedef struct {name} {{'<concat>'{index} row_index;'<concat>'{index} col_index;'<concat>'{precision} weight; }} {name};\n')<line_sep><return>cpp_fmt.format(name=self.name index=self.index_precision precision=self.precision.definition_cpp())<block_end><def_stmt>convert_precision self precision_converter<block_start>super().convert_precision(precision_converter)<line_sep>self.index_precision=precision_converter.convert(self.index_precision)<block_end><block_end><class_stmt>ExponentTypeConverter(TypeDefinition TypePrecisionConverter)<block_start><def_stmt>definition_cpp self<block_start>cpp_fmt=('typedef struct {name} {{'<concat>'{sign} sign;'<concat>'{precision} weight; }} {name};\n')<line_sep><return>cpp_fmt.format(name=self.name precision=self.precision.definition_cpp() sign=self.sign.definition_cpp())<block_end><def_stmt>convert_precision self precision_converter<block_start>super().convert_precision(precision_converter)<line_sep>self.sign=precision_converter.convert(self.sign)<block_end><block_end><class_stmt>PackedTypeConverter(TypeDefinition TypePrecisionConverter)<block_start><def_stmt>definition_cpp self<block_start>n_elem_expr='/'<if>self.unpack<else>'*'<line_sep><return>'typedef nnet::array<{precision}, {n_elem}> {name};\n'.format(name=self.name precision=self.precision.definition_cpp() n_elem=str(self.n_elem)+n_elem_expr+str(self.n_pack))<block_end><block_end><class_stmt>HLSTypeConverter(object)<block_start><def_stmt>__init__ self precision_converter<block_start>self.precision_converter=precision_converter<line_sep>self.type_map={NamedType:NamedTypeConverter CompressedType:CompressedTypeConverter ExponentType:ExponentTypeConverter PackedType:PackedTypeConverter }<block_end><def_stmt>convert self atype<block_start>type_cls=type(atype)<line_sep>type_cls_name=type_cls.__name__<line_sep># If the type is already converted, do nothing
<if_stmt>type_cls_name.startswith('HLS')<block_start><return>atype<block_end>conversion_cls=self.type_map.get(type_cls <none>)<if_stmt>conversion_cls<is><not><none><block_start>atype.__class__=type('HLS'+type_cls_name (type_cls conversion_cls) {})<line_sep>atype.convert_precision(self.precision_converter)<line_sep><return>atype<block_end><else_stmt><block_start><raise>Exception('Cannot convert type: {}'.format(atype.__class__.__name__))<block_end><block_end><block_end>#endregion
#region Variables
<class_stmt>VariableDefinition(object)<block_start><def_stmt>definition_cpp self name_suffix='' as_reference=<false><block_start><raise>NotImplementedError<block_end><block_end>#region ArrayVariable
<class_stmt>VivadoArrayVariableDefinition(VariableDefinition)<block_start><def_stmt>definition_cpp self name_suffix='' as_reference=<false><block_start><return>'{type} {name}{suffix}[{shape}]'.format(type=self.type.name name=self.cppname suffix=name_suffix shape=self.size_cpp())<block_end><block_end><class_stmt>QuartusArrayVariableDefinition(VariableDefinition)<block_start><def_stmt>definition_cpp self name_suffix='' as_reference=<false><block_start><return>'{type} {name}{suffix}[{shape}] {pragma}'.format(type=self.type.name name=self.cppname suffix=name_suffix shape=self.size_cpp() pragma=self.pragma)<block_end><block_end><class_stmt>ArrayVariableConverter(object)<block_start><def_stmt>__init__ self type_converter prefix definition_cls<block_start>self.type_converter=type_converter<line_sep>self.prefix=prefix<line_sep>self.definition_cls=definition_cls<block_end><def_stmt>convert self tensor_var pragma='partition'<block_start><if_stmt>isinstance(tensor_var self.definition_cls)# Already converted
<block_start><return>tensor_var<block_end>tensor_var.pragma=pragma<line_sep>tensor_var.type=self.type_converter.convert(tensor_var.type)<line_sep>tensor_var.__class__=type(self.prefix+'ArrayVariable' (type(tensor_var) self.definition_cls) {})<line_sep><return>tensor_var<block_end><block_end><class_stmt>VivadoArrayVariableConverter(ArrayVariableConverter)<block_start><def_stmt>__init__ self type_converter<block_start>super().__init__(type_converter=type_converter prefix='Vivado' definition_cls=VivadoArrayVariableDefinition)<block_end><block_end><class_stmt>QuartusArrayVariableConverter(ArrayVariableConverter)<block_start><def_stmt>__init__ self type_converter<block_start>super().__init__(type_converter=type_converter prefix='Quartus' definition_cls=QuartusArrayVariableDefinition)<block_end><block_end>#endregion
#region StructMemberVariable
<class_stmt>QuartusStructMemberVariableDefinition(VariableDefinition)<block_start><def_stmt>definition_cpp self name_suffix='' as_reference=<false><block_start><return>'{type} {name}{suffix}[{shape}]'.format(type=self.type.name name=self.member_name suffix=name_suffix shape=self.size_cpp())<block_end><block_end><class_stmt>StructMemberVariableConverter(object)<block_start><def_stmt>__init__ self type_converter prefix definition_cls<block_start>self.type_converter=type_converter<line_sep>self.prefix=prefix<line_sep>self.definition_cls=definition_cls<block_end><def_stmt>convert self tensor_var pragma='partition' struct_name=<none><block_start><if_stmt>isinstance(tensor_var self.definition_cls)# Already converted
<block_start><return>tensor_var<block_end>tensor_var.pragma=pragma<line_sep>tensor_var.type=self.type_converter.convert(tensor_var.type)<assert_stmt>struct_name<is><not><none> 'struct_name must be provided when creating a StructMemberVariable'<line_sep>tensor_var.struct_name=str(struct_name)<line_sep>tensor_var.member_name=tensor_var.name<line_sep>tensor_var.name=tensor_var.struct_name+'.'+tensor_var.member_name<line_sep>tensor_var.__class__=type(self.prefix+'StructMemberVariable' (type(tensor_var) self.definition_cls) {})<line_sep><return>tensor_var<block_end><block_end><class_stmt>QuartusStructMemberVariableConverter(StructMemberVariableConverter)<block_start><def_stmt>__init__ self type_converter<block_start>super().__init__(type_converter=type_converter prefix='Quartus' definition_cls=QuartusStructMemberVariableDefinition)<block_end><block_end>#endregion
#region StreamVariable
<class_stmt>VivadoStreamVariableDefinition(VariableDefinition)<block_start><def_stmt>definition_cpp self name_suffix='' as_reference=<false><block_start><if_stmt>as_reference# Function parameter
<block_start><return>'hls::stream<{type}> &{name}{suffix}'.format(type=self.type.name name=self.cppname suffix=name_suffix)<block_end><else_stmt># Declaration
<block_start><return>'hls::stream<{type}> {name}{suffix}("{name}")'.format(type=self.type.name name=self.cppname suffix=name_suffix)<block_end><block_end><block_end><class_stmt>StreamVariableConverter(object)<block_start><def_stmt>__init__ self type_converter prefix definition_cls<block_start>self.type_converter=type_converter<line_sep>self.prefix=prefix<line_sep>self.definition_cls=definition_cls<block_end><def_stmt>convert self tensor_var n_pack=1 depth=0<block_start><if_stmt>isinstance(tensor_var self.definition_cls)# Already converted
<block_start><return>tensor_var<block_end><if_stmt>depth<eq>0<block_start>depth=np.prod(tensor_var.shape)<floordiv>tensor_var.shape[-1]<block_end>tensor_var.pragma=('stream' depth)<line_sep>tensor_var.type=self.type_converter.convert(PackedType(tensor_var.type.name tensor_var.type.precision tensor_var.shape[-1] n_pack))<line_sep>tensor_var.__class__=type(self.prefix+'StreamVariable' (type(tensor_var) self.definition_cls) {})<line_sep><return>tensor_var<block_end><block_end><class_stmt>VivadoStreamVariableConverter(StreamVariableConverter)<block_start><def_stmt>__init__ self type_converter<block_start>super().__init__(type_converter=type_converter prefix='Vivado' definition_cls=VivadoStreamVariableDefinition)<block_end><block_end>#endregion
#region InplaceVariable
<class_stmt>InplaceVariableConverter(object)<block_start><def_stmt>__init__ self type_converter prefix<block_start>self.type_converter=type_converter<line_sep>self.prefix=prefix<block_end><def_stmt>convert self tensor_var io_type<block_start><if_stmt>tensor_var.__class__.__name__.startswith(self.prefix)# Already converted
<block_start><return>tensor_var<block_end><if_stmt>io_type<eq>'io_stream'<block_start>tensor_var.type=self.type_converter.convert(PackedType(tensor_var.type.name tensor_var.type.precision tensor_var.shape[-1] n_pack=1))<block_end><else_stmt><block_start>tensor_var.type=self.type_converter.convert(tensor_var.type)<block_end>tensor_var.__class__=type(self.prefix+'InplaceVariable' (type(tensor_var) ) {})<line_sep><return>tensor_var<block_end><block_end><class_stmt>VivadoInplaceVariableConverter(InplaceVariableConverter)<block_start><def_stmt>__init__ self type_converter<block_start>super().__init__(type_converter=type_converter prefix='Vivado')<block_end><block_end><class_stmt>QuartusInplaceVariableConverter(InplaceVariableConverter)<block_start><def_stmt>__init__ self type_converter<block_start>super().__init__(type_converter=type_converter prefix='Quartus')<block_end><block_end>#endregion
#region WeightsVariable
<class_stmt>StaticWeightVariableDefinition(VariableDefinition)<block_start><def_stmt>definition_cpp self name_suffix='' as_reference=<false><block_start><return>'{type} {name}[{size}]'.format(type=self.type.name name=self.cppname size=self.data_length)<block_end><block_end><class_stmt>StaticWeightVariableConverter(object)<block_start><def_stmt>__init__ self type_converter<block_start>self.type_converter=type_converter<block_end><def_stmt>convert self weight_var<block_start><if_stmt>isinstance(weight_var StaticWeightVariableDefinition)# Already converted
<block_start><return>weight_var<block_end>weight_var.weight_class=weight_var.__class__.__name__<line_sep>weight_var.storage='register'<line_sep>weight_var.type=self.type_converter.convert(weight_var.type)<line_sep>weight_var.__class__=type('StaticWeightVariable' (type(weight_var) StaticWeightVariableDefinition) {})<line_sep><return>weight_var<block_end><block_end><class_stmt>BramWeightVariableConverter(object)<block_start>@classmethod<def_stmt>convert cls weight_var<block_start>weight_var.storage='bram'<line_sep><return>weight_var<block_end><block_end>#endregion
#endregion
|
<import_from_stmt>pycoin.networks.bitcoinish create_bitcoinish_network<line_sep>network=create_bitcoinish_network(network_name="Monacoin" symbol="MONA" subnet_name="mainnet" wif_prefix_hex="b0" sec_prefix="MONASEC:" address_prefix_hex="32" pay_to_script_prefix_hex="37" bip32_prv_prefix_hex="0488ade4" bip32_pub_prefix_hex="0488b21e" bech32_hrp="mona" magic_header_hex="fbc0b6db" default_port=9401 dns_bootstrap=["dnsseed.monacoin.org"])<line_sep> |
<import_stmt>torch<import_stmt>torch.nn.functional<as>F<import_from_stmt>torch.autograd Variable<import_stmt>numpy<as>np<class_stmt>LabelSmoothingCrossEntropy(torch.nn.Module)<block_start><def_stmt>__init__ self<block_start>super(LabelSmoothingCrossEntropy self).__init__()<block_end><def_stmt>forward self x target smoothing=0.1<block_start>confidence=1.-smoothing<line_sep>logprobs=F.log_softmax(x dim=-1)<line_sep>nll_loss=-logprobs.gather(dim=-1 index=target.unsqueeze(1))<line_sep>nll_loss=nll_loss.squeeze(1)<line_sep>smooth_loss=-logprobs.mean(dim=-1)<line_sep>loss=confidence<times>nll_loss+smoothing<times>smooth_loss<line_sep><return>loss.mean()<block_end><block_end><class_stmt>ConfidenceLabelSmoothingCrossEntropy(torch.nn.Module)<block_start><def_stmt>__init__ self<block_start>super(ConfidenceLabelSmoothingCrossEntropy self).__init__()<line_sep># self.confidence = [0.7425, 0.9325, 0.965, 0.5395, 0.86025, 0.754, 0.66475, 0.618, 0.7925, 0.6525, 0.5415,
# 0.5705, 0.6525, 0.59625, 0.6145, 0.62125, 0.7755, 0.866, 0.83425, 0.64125, 0.986, 0.82225,
# 0.70525, 0.5625, 0.5145, 0.5275, 0.57775, 0.918, 0.9175, 0.69575, 0.6555, 0.867, 0.945,
# 0.5155, 0.593, 0.976, 0.963, 0.591, 0.749, 0.5575, 0.52625, 0.6125, 0.83725, 0.97225,
# 0.93725, 0.6415, 0.61225, 0.584, 0.69175, 0.60825, 0.63575, 0.756, 0.61375, 0.53575]
self.confidence=[0.713 0.953 0.947 0.514 0.933 0.725 0.6025 0.5855 0.821 0.6175 0.547 0.5605 0.7 0.609 0.5785 0.638 0.8005 0.824 0.834 0.5155 0.9775 0.8615 0.6305 0.549 0.517 0.5915 0.5285 0.923 0.855 0.751 0.675 0.773 0.9805 0.53 0.5255 0.9685 0.9535 0.5515 0.8795 0.497 0.529 0.5335 0.8645 0.9595 0.9245 0.5265 0.452 0.6415 0.696 0.617 0.683 0.7255 0.5995 0.5815 0.772 0.912 0.983 0.565 0.7875 0.783 0.727 0.6505 0.764 0.6875 0.536 0.5805 0.605 0.5835 0.6505 0.6045 0.7505 0.908 0.8345 0.767 0.9945 0.783 0.78 0.576 0.512 0.4635 0.627 0.913 0.98 0.6405 0.636 0.961 0.9095 0.501 0.6605 0.9835 0.9725 0.6305 0.6185 0.618 0.5235 0.6915 0.81 0.985 0.95 0.7565 0.7725 0.5265 0.6875 0.5995 0.5885 0.7865 0.628 0.49 0.985 0.95 0.7565 0.7725 0.5265 0.6875 0.5995 0.5885 0.7865 0.628 0.49]<block_end><def_stmt>forward self x target sid<block_start>confidencemat=torch.zeros_like(target dtype=torch.float32)<for_stmt>i range(len(target))<block_start>confidencemat[i]=self.confidence[sid[i]]<block_end>smoothing=1-confidencemat<line_sep>logprobs=F.log_softmax(x dim=-1)<line_sep>nll_loss=-logprobs.gather(dim=-1 index=target.unsqueeze(1))<line_sep>nll_loss=nll_loss.squeeze(1)<line_sep>smooth_loss=-logprobs.mean(dim=-1)<line_sep>loss=torch.mul(confidencemat nll_loss)+torch.mul(smoothing smooth_loss)<line_sep><return>loss.mean()<block_end><block_end><class_stmt>CroppedLoss<block_start><def_stmt>__init__ self loss_function<block_start>self.loss_function=loss_function<block_end><def_stmt>__call__ self preds targets<block_start>avg_preds=torch.mean(preds dim=2)<line_sep>avg_preds=avg_preds.squeeze(dim=1)<line_sep><return>self.loss_function(avg_preds targets)<block_end><block_end><def_stmt>train_crop log_interval model device train_loader optimizer scheduler cuda gpuidx epoch=1<block_start>criterion=torch.nn.NLLLoss()<line_sep>lossfn=CroppedLoss(criterion)<line_sep>model.train()<for_stmt>batch_idx,datas enumerate(train_loader)<block_start>data,target=datas[0].to(device) datas[1].to(device dtype=torch.int64)<line_sep>optimizer.zero_grad()<line_sep>output=model(data)<line_sep>output=model.embedding_net(data)<line_sep>loss=lossfn(output target)<line_sep>loss.backward()<line_sep>optimizer.step()<if_stmt>batch_idx%log_interval<eq>0<block_start>print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch batch_idx<times>len(data) len(train_loader.dataset) 100.<times>batch_idx/len(train_loader) loss.item()))<block_end><block_end>scheduler.step()<block_end><def_stmt>eval_crop model device test_loader<block_start>model.eval()<line_sep>test_loss=[]<line_sep>correct=[]<with_stmt>torch.no_grad()<block_start><for_stmt>datas test_loader<block_start>data,target=datas[0].to(device) datas[1].to(device dtype=torch.int64)<line_sep>outputs=[]<for_stmt>i range(2)<block_start>outputs.append(model(data[: : : i<times>125:i<times>125+1000]))<block_end>result=torch.cat([outputs[0] outputs[1][: : model.out_size-125:model.out_size]] dim=2)<line_sep>y_preds_per_trial=result.mean(dim=2)<line_sep>test_loss.append(F.nll_loss(y_preds_per_trial target reduction='sum').item())# sum up batch loss
pred=y_preds_per_trial.argmax(dim=1 keepdim=<true>)# get the index of the max log-probability
correct.append(pred.eq(target.view_as(pred)).sum().item())<block_end><block_end>loss=sum(test_loss)/len(test_loader.dataset)<line_sep># print('{:.0f}'.format(100. * correct / len(test_loader.dataset)))
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)'.format(loss sum(correct) len(test_loader.dataset) 100.<times>sum(correct)/len(test_loader.dataset)))<line_sep><return>loss 100.<times>sum(correct)/len(test_loader.dataset)<block_end><class_stmt>MAE_loss(torch.nn.Module)<block_start><def_stmt>__init__ self device<block_start>super(MAE_loss self).__init__()<line_sep>self.device=device<line_sep>self.loss_function=torch.nn.L1Loss()<block_end><def_stmt>__call__ self preds targets<block_start>y_onehot=torch.FloatTensor(targets.size(0) 2).to(self.device)<line_sep>y_onehot.zero_()<line_sep>y_onehot.scatter_(1 targets.unsqueeze(1) 1)<line_sep><return>self.loss_function(preds y_onehot)<block_end><block_end><class_stmt>MAE_loss(torch.nn.Module)<block_start><def_stmt>__init__ self device<block_start>super(MAE_loss self).__init__()<line_sep>self.device=device<line_sep>self.loss_function=torch.nn.L1Loss()<block_end><def_stmt>__call__ self preds targets<block_start>y_onehot=torch.FloatTensor(targets.size(0) 2).to(self.device)<line_sep>y_onehot.zero_()<line_sep>y_onehot.scatter_(1 targets.unsqueeze(1) 1)<line_sep><return>self.loss_function(preds y_onehot)<block_end><block_end><import_stmt>utils<import_stmt>time<def_stmt>train log_interval model device train_loader optimizer scheduler cuda gpuidx epoch<block_start>losses=utils.AverageMeter('Loss' ':.4e')<if_stmt>isinstance(model torch.nn.DataParallel)<block_start>lossfn=model.module.criterion<block_end><else_stmt><block_start>lossfn=model.criterion<line_sep># lossfn = LabelSmoothingCrossEntropy()
# lossfn = ConfidenceLabelSmoothingCrossEntropy()
<block_end>correct=[]<line_sep>start=time.time()<line_sep>model.train()<line_sep>t_data=[]<line_sep>t_model=[]<line_sep>t3=time.time()<for_stmt>batch_idx,datas enumerate(train_loader)<block_start>data,target=datas[0].to(device) datas[1].to(device dtype=torch.int64)<line_sep>t2=time.time()<line_sep>t_data.append(t2-t3)<line_sep># print(t2)
optimizer.zero_grad()<line_sep>output=model(data.unsqueeze(dim=1))<line_sep>pred=F.log_softmax(output dim=1).argmax(dim=1 keepdim=<true>)# get the index of the max log-probability
correct.append(pred.eq(target.view_as(pred)).sum().item())<line_sep>loss=lossfn(output target)<line_sep>loss.backward()<line_sep>optimizer.step()<line_sep>losses.update(loss.item() data.size(0))<if_stmt>batch_idx%log_interval<eq>0<block_start>print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch batch_idx<times>len(data) len(train_loader.dataset) 100.<times>batch_idx/len(train_loader) loss.item()))<block_end>t3=time.time()<line_sep>t_model.append(t3-t2)<block_end>print("time :" time.time()-start)<line_sep>print(f"t_data : {sum(t_data)} , t_model : {sum(t_model)}")<line_sep>print(f'Train set: Accuracy: {sum(correct)}/{len(train_loader.dataset)} ({100.<times>sum(correct)/len(train_loader.dataset):.4f}%)')<block_end><def_stmt>train_mtl log_interval model device train_loader optimizer scheduler cuda gpuidx epoch<block_start>losses=utils.AverageMeter('Loss' ':.4e')<if_stmt>isinstance(model torch.nn.DataParallel)<block_start>lossfn=model.module.criterion<block_end><else_stmt><block_start>lossfn=model.criterion<line_sep># lossfn = LabelSmoothingCrossEntropy()
# lossfn = ConfidenceLabelSmoothingCrossEntropy()
<block_end>correct=[]<line_sep>start=time.time()<line_sep>model.train()<line_sep>t_data=[]<line_sep>t_model=[]<line_sep>t3=time.time()<for_stmt>batch_idx,datas enumerate(train_loader)<block_start>data,target,subjid=datas[0].to(device) datas[1].to(device dtype=torch.int64) datas[2].to(device dtype=torch.int64)<line_sep>t2=time.time()<line_sep>t_data.append(t2-t3)<line_sep># print(t2)
optimizer.zero_grad()<line_sep>output=model(data.unsqueeze(dim=1))<line_sep>pred=F.log_softmax(output dim=1).argmax(dim=1 keepdim=<true>)# get the index of the max log-probability
correct.append(pred.eq(target.view_as(pred)).sum().item())<line_sep>loss=lossfn(output 2<times>subjid+target)<line_sep>loss.backward()<line_sep>optimizer.step()<line_sep>losses.update(loss.item() data.size(0))<if_stmt>batch_idx%log_interval<eq>0<block_start>print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch batch_idx<times>len(data) len(train_loader.dataset) 100.<times>batch_idx/len(train_loader) loss.item()))<block_end>t3=time.time()<line_sep>t_model.append(t3-t2)<block_end>print("time :" time.time()-start)<line_sep>print(f"t_data : {sum(t_data)} , t_model : {sum(t_model)}")<line_sep>print(f'Train set: Accuracy: {sum(correct)}/{len(train_loader.dataset)} ({100.<times>sum(correct)/len(train_loader.dataset):.4f}%)')<block_end><def_stmt>train_gpu log_interval model device train_loader optimizer scheduler cuda gpuidx epoch=1<block_start>losses=utils.AverageMeter('Loss' ':.4e')<if_stmt>isinstance(model torch.nn.DataParallel)<block_start>lossfn=model.module.criterion<block_end><else_stmt><block_start>lossfn=model.criterion<block_end>correct=[]<import_stmt>time<line_sep>start=time.time()<line_sep>model.train()<line_sep>t_data=[]<line_sep>t_model=[]<line_sep>t3=time.time()<for_stmt>batch_idx,datas enumerate(train_loader)<block_start>data,target=datas[0] datas[1]<line_sep>t2=time.time()<line_sep>t_data.append(t2-t3)<line_sep>optimizer.zero_grad()<line_sep>output=model(data.unsqueeze(dim=1))<line_sep>pred=F.log_softmax(output dim=1).argmax(dim=1 keepdim=<true>)# get the index of the max log-probability
correct.append(pred.eq(target.view_as(pred)).sum().item())<line_sep>loss=lossfn(output target)<line_sep>loss.backward()<line_sep>optimizer.step()<line_sep>losses.update(loss.item() data.size(0))<if_stmt>batch_idx%log_interval<eq>0<block_start>print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format(epoch batch_idx<times>len(data) len(train_loader.dataset) 100.<times>batch_idx/len(train_loader) loss.item()))<block_end>t3=time.time()<line_sep>t_model.append(t3-t2)<block_end>print("time :" time.time()-start)<line_sep>print(f"t_data : {sum(t_data)} , t_model : {sum(t_model)}")<line_sep>scheduler.step(losses.avg)<line_sep>print(f'Train set: Accuracy: {sum(correct)}/{len(train_loader.dataset)} ({100.<times>sum(correct)/len(train_loader.dataset):.4f}%)')<block_end><def_stmt>eval model device test_loader<block_start>model.eval()<line_sep>test_loss=[]<line_sep>correct=[]<with_stmt>torch.no_grad()<block_start><for_stmt>datas test_loader<block_start>data,target=datas[0].to(device) datas[1].to(device dtype=torch.int64)<line_sep>output=model(data.unsqueeze(dim=1))<line_sep>test_loss.append(F.cross_entropy(output target reduction='sum').item())# sum up batch loss
pred=F.log_softmax(output dim=1).argmax(dim=1 keepdim=<true>)# get the index of the max log-probability
correct.append(pred.eq(target.view_as(pred)).sum().item())<block_end><block_end>loss=sum(test_loss)/len(test_loader.dataset)<line_sep># print('{:.0f}'.format(100. * correct / len(test_loader.dataset)))
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)'.format(loss sum(correct) len(test_loader.dataset) 100.<times>sum(correct)/len(test_loader.dataset)))<line_sep><return>loss 100.<times>sum(correct)/len(test_loader.dataset)<block_end><import_from_stmt>sklearn.metrics roc_curve<import_from_stmt>sklearn.metrics auc<def_stmt>eval_cali model device test_loader<block_start>model.eval()<line_sep>test_loss=[]<line_sep>correct=[]<with_stmt>torch.no_grad()<block_start><for_stmt>datas test_loader<block_start>data,target=datas[0].to(device) datas[1].to(device dtype=torch.int64)<line_sep>output=model(data.unsqueeze(dim=1))<line_sep>test_loss.append(F.cross_entropy(output target reduction='sum').item())# sum up batch loss
pred=F.softmax(output dim=1)<line_sep>fpr,tpr,thresholds=roc_curve(target.cpu() pred.cpu()[: 0])<line_sep>AUC=auc(fpr tpr)<line_sep>correct.append(AUC)<block_end><block_end>loss=sum(test_loss)/len(test_loader.dataset)<line_sep># print('{:.0f}'.format(100. * correct / len(test_loader.dataset)))
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)'.format(loss sum(correct) len(test_loader.dataset) 100.<times>sum(correct)/len(test_loader.dataset)))<line_sep><return>loss 100.<times>sum(correct)/len(test_loader.dataset)<block_end><def_stmt>vote output target topk=(1 )<block_start>""" Computes the precision@k for the specified values of k """<line_sep>maxk=max(topk)<line_sep>batch_size=target.size(0)<line_sep>output=F.log_softmax(output dim=1)<line_sep>_,pred=output.topk(maxk 1 <true> <true>)<line_sep># pred = pred.t()
# one-hot case
<if_stmt>target.ndimension()<g>1<block_start>target=target.max(1)[1]<block_end>modevalue=torch.mode(pred%2)[0]<line_sep><return>modevalue<block_end><def_stmt>eval_mtl model device test_loader<block_start>model.eval()<line_sep>test_loss=[]<line_sep>correct=[]<with_stmt>torch.no_grad()<block_start><for_stmt>datas test_loader<block_start>data,target,subjid=datas[0].to(device) datas[1].to(device dtype=torch.int64) datas[2].to(device dtype=torch.int64)<line_sep>output=model(data.unsqueeze(dim=1))<line_sep>pred=vote(output subjid<times>2+target (1 5))<line_sep>test_loss.append(F.cross_entropy(output subjid<times>2+target reduction='sum').item())# sum up batch loss
# pred_0 = F.log_softmax(output, dim=1).argmax(dim=1, keepdim=True) # get the index of the max log-probability
# pred = pred_0%2
correct.append(pred.eq(target.view_as(pred)).sum().item())<block_end><block_end>loss=sum(test_loss)/len(test_loader.dataset)<line_sep># print('{:.0f}'.format(100. * correct / len(test_loader.dataset)))
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)'.format(loss sum(correct) len(test_loader.dataset) 100.<times>sum(correct)/len(test_loader.dataset)))<line_sep><return>loss 100.<times>sum(correct)/len(test_loader.dataset)<block_end><def_stmt>eval_ensemble models device test_loader<block_start><for_stmt>model models<block_start>model.eval()<block_end>test_loss=[]<line_sep>correct=[]<with_stmt>torch.no_grad()<block_start><for_stmt>datas test_loader<block_start>data,target=datas[0].to(device) datas[1].to(device dtype=torch.int64)<line_sep>output=[]<for_stmt>model models<block_start>output.append(model(data.unsqueeze(dim=1)).unsqueeze(dim=2))<block_end>temp=torch.cat(output dim=2)<line_sep>temp2=temp.mean(dim=2)<line_sep>test_loss.append(F.cross_entropy(temp2 target reduction='sum').item())# sum up batch loss
pred=F.log_softmax(temp2 dim=1).argmax(dim=1 keepdim=<true>)# get the index of the max log-probability
correct.append(pred.eq(target.view_as(pred)).sum().item())<block_end><block_end>loss=sum(test_loss)/len(test_loader.dataset)<line_sep># print('{:.0f}'.format(100. * correct / len(test_loader.dataset)))
print('Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.4f}%)'.format(loss sum(correct) len(test_loader.dataset) 100.<times>sum(correct)/len(test_loader.dataset)))<line_sep><return>loss 100.<times>sum(correct)/len(test_loader.dataset)<block_end> |
<import_from_stmt>datetime datetime<import_from_stmt>enum Enum<import_from_stmt>typing Any List Optional<import_from_stmt>xbox.webapi.common.models CamelCaseModel PascalCaseModel<class_stmt>TitleFields(str Enum)<block_start>SERVICE_CONFIG_ID="scid"<line_sep>ACHIEVEMENT="achievement"<line_sep>STATS="stats"<line_sep>GAME_PASS="gamepass"<line_sep>IMAGE="image"<line_sep>DETAIL="detail"<line_sep>FRIENDS_WHO_PLAYED="friendswhoplayed"<line_sep>ALTERNATE_TITLE_ID="alternateTitleId"<block_end><class_stmt>Achievement(CamelCaseModel)<block_start>current_achievements:int<line_sep>total_achievements:int<line_sep>current_gamerscore:int<line_sep>total_gamerscore:int<line_sep>progress_percentage:float<line_sep>source_version:int<block_end><class_stmt>Stats(CamelCaseModel)<block_start>source_version:int<block_end><class_stmt>GamePass(CamelCaseModel)<block_start>is_game_pass:bool<block_end><class_stmt>Image(CamelCaseModel)<block_start>url:str<line_sep>type:str<block_end><class_stmt>TitleHistory(CamelCaseModel)<block_start>last_time_played:datetime<line_sep>visible:bool<line_sep>can_hide:bool<block_end><class_stmt>Attribute(CamelCaseModel)<block_start>applicable_platforms:Optional[List[str]]<line_sep>maximum:Optional[int]<line_sep>minimum:Optional[int]<line_sep>name:str<block_end><class_stmt>Availability(PascalCaseModel)<block_start>actions:List[str]<line_sep>availability_id:str<line_sep>platforms:List[str]<line_sep>sku_id:str<block_end><class_stmt>Detail(CamelCaseModel)<block_start>attributes:List[Attribute]<line_sep>availabilities:List[Availability]<line_sep>capabilities:List[str]<line_sep>description:str<line_sep>developer_name:str<line_sep>genres:Optional[List[str]]<line_sep>publisher_name:str<line_sep>min_age:int<line_sep>release_date:Optional[datetime]<line_sep>short_description:Optional[str]<line_sep>vui_display_name:Optional[str]<line_sep>xbox_live_gold_required:bool<block_end><class_stmt>Title(CamelCaseModel)<block_start>title_id:str<line_sep>pfn:Optional[str]<line_sep>bing_id:Optional[str]<line_sep>service_config_id:Optional[str]<line_sep>windows_phone_product_id:Optional[str]<line_sep>name:str<line_sep>type:str<line_sep>devices:List[str]<line_sep>display_image:str<line_sep>media_item_type:str<line_sep>modern_title_id:Optional[str]<line_sep>is_bundle:bool<line_sep>achievement:Optional[Achievement]<line_sep>stats:Optional[Stats]<line_sep>game_pass:Optional[GamePass]<line_sep>images:Optional[List[Image]]<line_sep>title_history:Optional[TitleHistory]<line_sep>detail:Optional[Detail]<line_sep>friends_who_played:Any<line_sep>alternate_title_ids:Any<line_sep>content_boards:Any<line_sep>xbox_live_tier:Optional[str]<line_sep>is_streamable:Optional[bool]<block_end><class_stmt>TitleHubResponse(CamelCaseModel)<block_start>xuid:Optional[str]<line_sep>titles:List[Title]<block_end> |
<import_stmt>numpy<as>np<import_stmt>scipy<import_from_stmt>sklearn.model_selection train_test_split<line_sep>files=['../data/combined_data_1.txt' '../data/combined_data_2.txt' '../data/combined_data_3.txt' '../data/combined_data_4.txt' ]<if_stmt>__name__<eq>'__main__'<block_start>coo_row=[]<line_sep>coo_col=[]<line_sep>coo_val=[]<for_stmt>file_name files<block_start>print('processing {0}'.format(file_name))<with_stmt>open(file_name "r")<as>f<block_start>movie=-1<for_stmt>line f<block_start><if_stmt>line.endswith(':\n')<block_start>movie=int(line[:-2])-1<line_sep><continue><block_end><assert_stmt>movie<ge>0<line_sep>splitted=line.split(',')<line_sep>user=int(splitted[0])<line_sep>rating=float(splitted[1])<line_sep>coo_row.append(user)<line_sep>coo_col.append(movie)<line_sep>coo_val.append(rating)<block_end><block_end><block_end>print('transformation...')<line_sep>coo_col=np.array(coo_col)<line_sep>user,indices=np.unique(coo_row return_inverse=<true>)<line_sep>coo_val=np.array(coo_val).astype(np.float32)<line_sep>coo_matrix=scipy.sparse.coo_matrix((coo_val (indices coo_col)))<line_sep>shape=coo_matrix.shape<line_sep>print(shape)<line_sep>train_row,test_row,train_col,test_col,train_data,test_data=train_test_split(coo_matrix.row coo_matrix.col coo_matrix.data test_size=0.2 random_state=42)<line_sep>train=scipy.sparse.coo_matrix((train_data (train_row train_col)) shape=shape)<line_sep>test=scipy.sparse.coo_matrix((test_data (test_row test_col)) shape=shape)<line_sep>scipy.sparse.save_npz('../data/netflix_train.npz' train)<line_sep>scipy.sparse.save_npz('../data/netflix_test.npz' test)<line_sep>np.savez_compressed('../data/netflix_.npz' user)<block_end> |
<import_from_stmt>.abc ABCTokenGenerator Token<import_from_stmt>.consistent ConsistentTokenGenerator<import_from_stmt>.single SingleTokenGenerator<import_from_stmt>.util get_token_generator<line_sep> |
<import_from_stmt>AppKit *<import_from_stmt>PyObjCTools.TestSupport *<class_stmt>TestNSDockTile(TestCase)<block_start><def_stmt>testMethods self<block_start>self.assertResultIsBOOL(NSDockTile.showsApplicationBadge)<line_sep>self.assertArgIsBOOL(NSDockTile.setShowsApplicationBadge_ 0)<block_end><def_stmt>testConstants self<block_start>self.assertEqual(NSAppKitVersionNumberWithDockTilePlugInSupport 1001.0)<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>main()<block_end> |
# Generated by Django 2.2.16 on 2020-12-15 07:18
<import_from_stmt>django.conf settings<import_from_stmt>django.db migrations models<import_stmt>django.db.models.deletion<class_stmt>Migration(migrations.Migration)<block_start>initial=<true><line_sep>dependencies=[('sqlorders' '0001_initial') migrations.swappable_dependency(settings.AUTH_USER_MODEL) ]<line_sep>operations=[migrations.CreateModel(name='DbQuerySchemas' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键ID')) ('schema' models.CharField(default='' max_length=64 verbose_name='库名')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='创建时间')) ('updated_at' models.DateTimeField(auto_now=<true> verbose_name='更新时间')) ('cid' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlorders.DbConfig' verbose_name='数据库')) ] options={'verbose_name':'DB查询库' 'verbose_name_plural':'DB查询库' 'db_table':'yasql_sqlquery_schemas' 'default_permissions':() 'unique_together':{('cid' 'schema')} } ) migrations.CreateModel(name='DbQueryTables' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键ID')) ('table' models.CharField(default='' max_length=128 verbose_name='表名')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='创建时间')) ('updated_at' models.DateTimeField(auto_now=<true> verbose_name='更新时间')) ('schema' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQuerySchemas' verbose_name='库名')) ] options={'verbose_name':'DB查询表' 'verbose_name_plural':'DB查询表' 'db_table':'yasql_sqlquery_tables' 'default_permissions':() } ) migrations.CreateModel(name='DbQueryUserPrivs' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键ID')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='创建时间')) ('updated_at' models.DateTimeField(auto_now=<true> verbose_name='更新时间')) ('schemas' models.ManyToManyField(to='sqlquery.DbQuerySchemas' verbose_name='允许访问的库')) ('user' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to=settings.AUTH_USER_MODEL verbose_name='用户')) ] options={'verbose_name':'DB查询用户权限' 'verbose_name_plural':'DB查询用户权限' 'db_table':'yasql_sqlquery_user_privileges' 'default_permissions':() } ) migrations.CreateModel(name='DbQueryUserDenyTables' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键ID')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='创建时间')) ('updated_at' models.DateTimeField(auto_now=<true> verbose_name='更新时间')) ('tables' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQueryTables' verbose_name='表')) ('user_privs' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQueryUserPrivs' verbose_name='权限')) ] options={'verbose_name':'禁止用户访问的表' 'verbose_name_plural':'禁止用户访问的表' 'db_table':'yasql_sqlquery_user_deny_tables' 'default_permissions':() } ) migrations.CreateModel(name='DbQueryUserAllowedTables' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键ID')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='创建时间')) ('updated_at' models.DateTimeField(auto_now=<true> verbose_name='更新时间')) ('tables' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQueryTables' verbose_name='表')) ('user_privs' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQueryUserPrivs' verbose_name='权限')) ] options={'verbose_name':'允许用户访问的表' 'verbose_name_plural':'允许用户访问的表' 'db_table':'yasql_sqlquery_user_allowed_tables' 'default_permissions':() } ) migrations.CreateModel(name='DbQueryLog' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键id')) ('username' models.CharField(max_length=64 verbose_name='用户名')) ('host' models.CharField(max_length=256 verbose_name='目标数据库地址')) ('schema' models.CharField(default='' max_length=128 verbose_name='目标数据库')) ('tables' models.CharField(default='' max_length=200 verbose_name='目标表名')) ('query_sql' models.TextField(default='' verbose_name='查询SQL')) ('query_consume_time' models.FloatField(default=0.0 verbose_name='查询耗时,单位s')) ('query_status' models.CharField(default='' max_length=2048 verbose_name='查询是否成功或失败的原因')) ('affected_rows' models.IntegerField(default=0 verbose_name='影响影响行数')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='查询时间')) ] options={'verbose_name':'DB查询日志' 'verbose_name_plural':'DB查询日志' 'db_table':'yasql_sqlquery_log' 'default_permissions':() 'index_together':{('tables' ) ('schema' ) ('username' )} } ) migrations.CreateModel(name='DbQueryGroupPrivs' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键ID')) ('group' models.CharField(default='' max_length=128 verbose_name='组名')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='创建时间')) ('updated_at' models.DateTimeField(auto_now=<true> verbose_name='更新时间')) ('schemas' models.ManyToManyField(to='sqlquery.DbQuerySchemas' verbose_name='允许访问的库')) ('user' models.ManyToManyField(to=settings.AUTH_USER_MODEL verbose_name='用户')) ] options={'verbose_name':'DB查询组权限' 'verbose_name_plural':'DB查询组权限' 'db_table':'yasql_sqlquery_group_privileges' 'default_permissions':() } ) migrations.CreateModel(name='DbQueryGroupDenyTables' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键ID')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='创建时间')) ('updated_at' models.DateTimeField(auto_now=<true> verbose_name='更新时间')) ('group_privs' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQueryGroupPrivs' verbose_name='权限')) ('tables' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQueryTables' verbose_name='表')) ] options={'verbose_name':'禁止组访问的表' 'verbose_name_plural':'禁止组访问的表' 'db_table':'yasql_sqlquery_group_deny_tables' 'default_permissions':() } ) migrations.CreateModel(name='DbQueryGroupAllowedTables' fields=[('id' models.AutoField(primary_key=<true> serialize=<false> verbose_name='主键ID')) ('created_at' models.DateTimeField(auto_now_add=<true> verbose_name='创建时间')) ('updated_at' models.DateTimeField(auto_now=<true> verbose_name='更新时间')) ('group_privs' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQueryGroupPrivs' verbose_name='权限')) ('tables' models.ForeignKey(blank=<true> null=<true> on_delete=django.db.models.deletion.SET_NULL to='sqlquery.DbQueryTables' verbose_name='表')) ] options={'verbose_name':'允许组访问的表' 'verbose_name_plural':'允许组访问的表' 'db_table':'yasql_sqlquery_group_allowed_tables' 'default_permissions':() } ) ]<block_end> |
<import_stmt>glob<line_sep>"""
this script is fixing errors found in the data, after processing
"""<line_sep># final fixes for known errors
<for_stmt>filepath glob.glob('output/*.json')# Read in the file
<block_start><with_stmt>open(filepath 'r')<as>file<block_start>filedata=file.read()<block_end># AIDA has a wrong URL for the Dallas Airport
wrong='http://en.wikipedia.org/wiki/Dallas/Dallas%2FFort%20Worth%20International%20Airport'<line_sep>correct='http://en.wikipedia.org/wiki/Dallas%2FFort%20Worth%20International%20Airport'<line_sep># Replace the target string
filedata=filedata.replace(wrong correct)<line_sep># Write the file out again
<with_stmt>open(filepath 'w')<as>file<block_start>file.write(filedata)<block_end><block_end> |
"""
Module description:
"""<line_sep>__version__='0.3.1'<line_sep>__author__='<NAME>, <NAME>'<line_sep>__email__='<EMAIL>, <EMAIL>'<import_stmt>tensorflow<as>tf<import_stmt>numpy<as>np<import_stmt>random<class_stmt>Sampler()<block_start><def_stmt>__init__ self indexed_ratings=<none> m=<none> num_users=<none> num_items=<none> transactions=<none> batch_size=512 random_seed=42<block_start>np.random.seed(random_seed)<line_sep>random.seed(random_seed)<line_sep>self._UIDICT={u:list(set(indexed_ratings[u]))<for>u indexed_ratings}<line_sep>self._POS=list({(u i 1)<for>u,items self._UIDICT.items()<for>i items})<line_sep>self._POS=random.sample(self._POS len(self._POS))<line_sep>self._M=m<line_sep>self._NUM_USERS=num_users<line_sep>self._NUM_ITEMS=num_items<line_sep>self._transactions=transactions<line_sep>self._batch_size=batch_size<block_end><def_stmt>_full_generator self<block_start>r_int=np.random.randint<line_sep>n_items=self._NUM_ITEMS<line_sep>ui_dict=self._UIDICT<line_sep>neg=set()<for_stmt>u,i,_ self._POS<block_start>ui=ui_dict[u]<for_stmt>_ range(self._M)<block_start>j=r_int(n_items)<while_stmt>j<in>ui<block_start>j=r_int(n_items)<block_end>neg.add((u j 0))<block_end><block_end>samples=self._POS[:]<line_sep>samples.extend(list(neg))<line_sep>samples=random.sample(samples len(samples))<line_sep># u, i, b = map(np.array, zip(*samples))
# yield u,i,b
<for_stmt>start range(0 len(samples) self._batch_size)<block_start>u,i,b=map(np.array zip(*samples[start:min(start+self._batch_size len(samples))]))<line_sep><yield>u i b<block_end><block_end><def_stmt>step self batch_size:int<block_start>r_int=np.random.randint<line_sep>n_items=self._NUM_ITEMS<line_sep>ui_dict=self._UIDICT<line_sep>pos={(u i 1)<for>u,items ui_dict.items()<for>i items}<line_sep>neg=set()<for_stmt>u,i,_ pos<block_start>ui=ui_dict[u]<for_stmt>_ range(self._M)<block_start>j=r_int(n_items)<while_stmt>j<in>ui<block_start>j=r_int(n_items)<block_end>neg.add((u j 0))<block_end><block_end>samples=list(pos)<line_sep>samples.extend(list(neg))<line_sep>samples=random.sample(samples len(samples))<for_stmt>start range(0 len(samples) batch_size)<block_start>u,i,b=map(np.array zip(*samples[start:min(start+batch_size len(samples))]))<line_sep><yield>u i b<block_end><block_end><def_stmt>create_tf_dataset self<block_start>data=tf.data.Dataset.from_generator(generator=self._full_generator output_types=(np.int64 np.int64 np.int64) )<line_sep># data = data.unbatch().batch(batch_size=self._batch_size)
data=data.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)<line_sep><return>data<block_end><block_end> |
<import_from_stmt>.checks is_toeplitz_matrix is_super_symmetric is_toeplitz_tensor<line_sep>__all__=["is_toeplitz_matrix" "is_super_symmetric" "is_toeplitz_tensor" ]<line_sep> |
# Copyright 2021 <NAME> <EMAIL>
#
# 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.
"""
Knapsack problem in OR-tools CP-SAT Solver.
Simple knapsack problem.
This is a port of my old CP model knapsack_cp.py
This model was created by <NAME> (<EMAIL>)
Also see my other OR-tools models: http://www.hakank.org/or_tools/
"""<import_from_future_stmt> print_function<import_from_stmt>ortools.sat.python cp_model<as>cp<import_stmt>math sys<import_from_stmt>cp_sat_utils knapsack<def_stmt>main values weights n<block_start>model=cp.CpModel()<line_sep>#
# data
#
print("values:" values)<line_sep>print("weights:" weights)<line_sep>print("n:" n)<line_sep>print()<line_sep># declare variables
#
# constraints
#
x,z,w=knapsack(model values weights n)<line_sep># objective
model.Maximize(z)<line_sep>#
# solution and search
#
solver=cp.CpSolver()<line_sep>status=solver.Solve(model)<if_stmt>status<eq>cp.OPTIMAL<block_start>print("x:" [solver.Value(x[i])<for>i range(len(values))])<line_sep>print("z:" solver.Value(z))<line_sep>print("w:" solver.Value(w))<line_sep>print()<block_end>print("NumConflicts:" solver.NumConflicts())<line_sep>print("NumBranches:" solver.NumBranches())<line_sep>print("WallTime:" solver.WallTime())<block_end>values=[15 100 90 60 40 15 10 1 12 12 100]<line_sep>weights=[2 20 20 30 40 30 60 10 21 12 2]<line_sep>n=102<if_stmt>__name__<eq>"__main__"<block_start>main(values weights n)<block_end> |
<import_stmt>FWCore.ParameterSet.Config<as>cms<import_from_stmt>L1TriggerConfig.L1ScalesProducers.l1CaloScales_cfi *<line_sep>emrcdsrc=cms.ESSource("EmptyESSource" recordName=cms.string('L1EmEtScaleRcd') iovIsRunNotTime=cms.bool(<true>) firstValid=cms.vuint32(1))<line_sep>jetrcdsrc=cms.ESSource("EmptyESSource" recordName=cms.string('L1JetEtScaleRcd') iovIsRunNotTime=cms.bool(<true>) firstValid=cms.vuint32(1))<line_sep>htmrcdsrc=cms.ESSource("EmptyESSource" recordName=cms.string('L1HtMissScaleRcd') iovIsRunNotTime=cms.bool(<true>) firstValid=cms.vuint32(1))<line_sep>hfrrcdsrc=cms.ESSource("EmptyESSource" recordName=cms.string('L1HfRingEtScaleRcd') iovIsRunNotTime=cms.bool(<true>) firstValid=cms.vuint32(1))<line_sep> |
"""
@Author : <NAME>
"""<line_sep># full assembly of the sub-parts to form the complete net
<import_stmt>numpy<as>np<import_from_stmt>unet_parts *<class_stmt>UNet(nn.Module)<block_start><def_stmt>__init__ self n_channels n_classes<block_start>super(UNet self).__init__()<line_sep>self.inc=inconv(n_channels 64)<line_sep>self.down1=down(64 128)<line_sep>self.down2=down(128 256)<line_sep>self.down3=down(256 512)<line_sep>self.down4=down(512 512)<line_sep>self.up1=up(1024 256)<line_sep>self.up2=up(512 128)<line_sep>self.up3=up(256 64)<line_sep>self.up4=up(128 64)<line_sep>self.outc=outconv(64 n_classes)<block_end><def_stmt>forward self x<block_start>x1=self.inc(x)<line_sep>x2=self.down1(x1)<line_sep>x3=self.down2(x2)<line_sep>x4=self.down3(x3)<line_sep>x5=self.down4(x4)<line_sep>x4_=self.up1(x5 x4)<line_sep>x3_=self.up2(x4_ x3)<line_sep>x2_=self.up3(x3_ x2)<line_sep>x1_=self.up4(x2_ x1)<line_sep>x_=self.outc(x1_)<line_sep>print('x1 ' x1.shape)<line_sep>print('x2 ' x2.shape)<line_sep>print('x3 ' x3.shape)<line_sep>print('x4 ' x4.shape)<line_sep>print('x5 ' x5.shape)<line_sep>print('x4_' x4_.shape)<line_sep>print('x3_' x3_.shape)<line_sep>print('x2_' x2_.shape)<line_sep>print('x1_' x1_.shape)<line_sep>print('x_ ' x_.shape)<line_sep><return>x<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>model=UNet(n_channels=3 n_classes=1)<line_sep># import numpy as np
dummy_batch_data=np.zeros((2 3 224 224) dtype=np.float32)<line_sep>dummy_batch_data=torch.from_numpy(dummy_batch_data)<line_sep>Pred=model(dummy_batch_data)<line_sep>print(Pred.shape)<block_end> |
<import_stmt>numbers<import_stmt>xnmt.tensor_tools<as>tt<import_stmt>xnmt.modelparts.decoders<as>decoders<import_stmt>xnmt.transducers.recurrent<as>recurrent<import_stmt>xnmt.transducers.base<as>transducers_base<import_stmt>xnmt.expression_seqs<as>expr_seq<import_stmt>xnmt.vocabs<as>vocabs<class_stmt>SimultaneousState(decoders.AutoRegressiveDecoderState)<block_start>"""
The read/write state used to determine the state of the SimultaneousTranslator.
"""<def_stmt>__init__ self model encoder_state:recurrent.UniLSTMState context_state:decoders.AutoRegressiveDecoderState output_embed:tt.Tensor to_read:int=0 to_write:int=0 prev_written_word:numbers.Integral=<none> reset_attender:bool=<true><block_start>super().__init__(<none> <none>)<line_sep>self.model=model<line_sep>self.encoder_state=encoder_state<line_sep>self.context_state=context_state<line_sep>self.output_embed=output_embed<line_sep>self.has_been_read=to_read<line_sep>self.has_been_written=to_write<line_sep>self.prev_written_word=prev_written_word<line_sep>self.reset_attender=reset_attender<block_end><def_stmt>read self src<block_start>src_embed=self.model.src_embedder.embed(src[self.has_been_read])<line_sep>next_encoder_state=self.encoder_state.add_input(src_embed)<line_sep><return>SimultaneousState(self.model next_encoder_state self.context_state self.output_embed self.has_been_read+1 self.has_been_written self.prev_written_word <true>)<block_end><def_stmt>calc_context self src_encoding# Generating h_t based on RNN(h_{t-1}, embed(e_{t-1}))
<block_start><if_stmt>self.prev_written_word<is><none><block_start>final_transducer_state=[transducers_base.FinalTransducerState(h c)<for>h,c zip(self.encoder_state.h() self.encoder_state.c())]<line_sep>context_state=self.model.decoder.initial_state(final_transducer_state vocabs.Vocab.SS)<block_end><else_stmt><block_start>context_state=self.model.decoder.add_input(self.context_state self.prev_written_word)<block_end># Reset attender if there is a read action
reset_attender=self.reset_attender<if_stmt>reset_attender<block_start>self.model.attender.init_sent(expr_seq.ExpressionSequence(expr_list=src_encoding))<line_sep>reset_attender=<false><block_end># Calc context for decoding
context_state.context=self.model.attender.calc_context(context_state.rnn_state.output())<line_sep><return>SimultaneousState(self.model self.encoder_state context_state self.output_embed self.has_been_read self.has_been_written self.prev_written_word reset_attender)<block_end><def_stmt>write self next_word<block_start><return>SimultaneousState(self.model self.encoder_state self.context_state self.model.decoder.embedder.embed(next_word) self.has_been_read self.has_been_written+1 next_word self.reset_attender)<block_end># These states are used for decoding
<def_stmt>as_vector self<block_start><return>self.context_state.as_vector()<block_end>@property<def_stmt>rnn_state self<block_start><return>self.context_state.rnn_state<block_end>@property<def_stmt>context self<block_start><return>self.context_state.context<block_end>@context.setter<def_stmt>context self value<block_start>self.context_state.context=value<block_end><block_end> |
"""Define tests for the Luftdaten component."""<line_sep> |
# Copyright 2021, The TensorFlow Federated 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.
"""Helpers for converting Python data representations for CPP bindings."""<import_stmt>collections<import_from_stmt>typing Mapping<import_from_stmt>tensorflow_federated.python.core.impl.types placements<def_stmt>convert_cardinalities_dict_to_string_keyed cardinalities:Mapping[placements.PlacementLiteral int]<arrow>Mapping[str int]<block_start>"""Ensures incoming cardinalities dict is formatted correctly."""<if_stmt><not>isinstance(cardinalities collections.abc.Mapping)<block_start><raise>TypeError('`cardinalities` must be a `Mapping`. Received a type: '<concat>f'{type(cardinalities)}.')<block_end>uri_cardinalities={}<for_stmt>placement,cardinality cardinalities.items()<block_start><if_stmt><not>isinstance(placement placements.PlacementLiteral)<block_start><raise>TypeError('`cardinalities` must be a `Mapping` with '<concat>'`PlacementLiteral` (e.g. `tff.CLIENTS`) keys. '<concat>f'Received a key of type: {type(placement)}.')<block_end><if_stmt><not>isinstance(cardinality int)<block_start><raise>TypeError('`cardinalities` must be a `Mapping` with `int` values. '<concat>f'Received a value of type: {type(cardinality)} for '<concat>f'placement {placement}.')<block_end>uri_cardinalities[placement.uri]=cardinality<block_end><return>uri_cardinalities<block_end> |
# -------------------------------------------------------------------------------
# Copyright IBM Corp. 2017
#
# 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_from_stmt>pixiedust.display.display *<import_from_stmt>pixiedust.display addDisplayRunListener<line_sep>#add a display Run Listener
addDisplayRunListener(<lambda>entity options:onNewDisplayRun(entity options))<line_sep>activesStreamingEntities={}<def_stmt>onNewDisplayRun entity options<block_start><if_stmt>"cell_id"<in>options<and>"showchrome"<in>options<block_start><if_stmt>options["cell_id"]<in>activesStreamingEntities<block_start><del_stmt>activesStreamingEntities[options["cell_id"]]<block_end><block_end><block_end><class_stmt>StreamingDisplay(Display)<block_start><def_stmt>__init__ self options entity dataHandler=<none><block_start>super(StreamingDisplay self).__init__(options entity dataHandler)<line_sep>self.windowSize=100<block_end><block_end> |
# MIT License
# Copyright (c) 2018-2019 <NAME>, <NAME>, <NAME>, <NAME>
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# 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.
<import_stmt>rhino3dm<as>r3d<import_from_stmt>. utils<import_from_stmt>mathutils Vector<line_sep>CONVERT={}<def_stmt>import_null rcurve bcurve scale<block_start>print("Failed to convert type" type(rcurve))<line_sep><return><none><block_end><def_stmt>import_line rcurve bcurve scale<block_start>fr=rcurve.Line.From<line_sep>to=rcurve.Line.To<line_sep>line=bcurve.splines.new('POLY')<line_sep>line.points.add(1)<line_sep>line.points[0].co=(fr.X<times>scale fr.Y<times>scale fr.Z<times>scale 1)<line_sep>line.points[1].co=(to.X<times>scale to.Y<times>scale to.Z<times>scale 1)<line_sep><return>line<block_end>CONVERT[r3d.LineCurve]=import_line<def_stmt>import_polyline rcurve bcurve scale<block_start>N=rcurve.PointCount<line_sep>polyline=bcurve.splines.new('POLY')<line_sep>polyline.use_cyclic_u=rcurve.IsClosed<if_stmt>rcurve.IsClosed<block_start>N<augsub>1<block_end>polyline.points.add(N-1)<for_stmt>i range(0 N)<block_start>rpt=rcurve.Point(i)<line_sep>polyline.points[i].co=(rpt.X<times>scale rpt.Y<times>scale rpt.Z<times>scale 1)<block_end><return>polyline<block_end>CONVERT[r3d.PolylineCurve]=import_polyline<def_stmt>import_nurbs_curve rcurve bcurve scale<block_start>N=len(rcurve.Points)<line_sep>nurbs=bcurve.splines.new('NURBS')<line_sep>nurbs.use_cyclic_u=rcurve.IsClosed<line_sep>nurbs.points.add(N-1)<for_stmt>i range(0 N)<block_start>rpt=rcurve.Points[i]<line_sep>nurbs.points[i].co=(rpt.X<times>scale rpt.Y<times>scale rpt.Z<times>scale rpt.W<times>scale)<block_end>#nurbs.use_bezier_u = True
nurbs.use_endpoint_u=<true><line_sep>nurbs.order_u=rcurve.Order<line_sep><return>nurbs<block_end>CONVERT[r3d.NurbsCurve]=import_nurbs_curve<def_stmt>import_arc rcurve bcurve scale<block_start>spt=Vector((rcurve.Arc.StartPoint.X rcurve.Arc.StartPoint.Y rcurve.Arc.StartPoint.Z))<times>scale<line_sep>ept=Vector((rcurve.Arc.EndPoint.X rcurve.Arc.EndPoint.Y rcurve.Arc.EndPoint.Z))<times>scale<line_sep>cpt=Vector((rcurve.Arc.Center.X rcurve.Arc.Center.Y rcurve.Arc.Center.Z))<times>scale<line_sep>r1=spt-cpt<line_sep>r2=ept-cpt<line_sep>r1.normalize()<line_sep>r2.normalize()<line_sep>d=rcurve.Arc.Length<times>scale<line_sep>normal=r1.cross(r2)<line_sep>t1=normal.cross(r1)<line_sep>t2=normal.cross(r2)<line_sep>'''
Temporary arc
'''<line_sep>arc=bcurve.splines.new('NURBS')<line_sep>arc.use_cyclic_u=<false><line_sep>arc.points.add(3)<line_sep>arc.points[0].co=(spt.x spt.y spt.z 1)<line_sep>sspt=spt+t1<times>d<times>0.33<line_sep>arc.points[1].co=(sspt.x sspt.y sspt.z 1)<line_sep>eept=ept-t2<times>d<times>0.33<line_sep>arc.points[2].co=(eept.x eept.y eept.z 1)<line_sep>arc.points[3].co=(ept.x ept.y ept.z 1)<line_sep>'''
print("ARC")
print(" StartPoint:", rcurve.Arc.StartPoint)
print(" EndPoint:", rcurve.Arc.EndPoint)
print(" Center:", rcurve.Arc.Center)
print(" Radius:", rcurve.Radius)
'''<line_sep>arc.use_endpoint_u=<true><line_sep>arc.order_u=3<line_sep><return>arc<block_end>CONVERT[r3d.ArcCurve]=import_arc<def_stmt>import_polycurve rcurve bcurve scale<block_start><for_stmt>seg range(rcurve.SegmentCount)<block_start>segcurve=rcurve.SegmentCurve(seg)<if_stmt>type(segcurve)<in>CONVERT.keys()<block_start>CONVERT[type(segcurve)](segcurve bcurve scale)<block_end><block_end><block_end>CONVERT[r3d.PolyCurve]=import_polycurve<def_stmt>import_curve context ob name scale options<block_start>og=ob.Geometry<line_sep>oa=ob.Attributes<line_sep>curve_data=context.blend_data.curves.new(name type="CURVE")<if_stmt>type(og)<in>CONVERT.keys()<block_start>curve_data.dimensions='3D'<line_sep>curve_data.resolution_u=2<line_sep>CONVERT[type(og)](og curve_data scale)<block_end><return>curve_data<block_end> |
# Copyright 2004-2015, <NAME>, Inc.
# Copyright 2017-Present Facebook, Inc.
<import_from_stmt>ng NailgunConnection NailgunException<line_sep> |
### DO NOT REMOVE THIS
<import_from_stmt>typing List<class_stmt>ListNode<block_start><def_stmt>__init__ self val=0 next=<none><block_start>self.val=val<line_sep>self.next=next<block_end><block_end>### DO NOT REMOVE THIS
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
<class_stmt>Solution<block_start><def_stmt>addTwoNumbers self l1:ListNode l2:ListNode<arrow>ListNode<block_start>a1=0<line_sep>a2=0<line_sep>current=l1<line_sep>i=0<while_stmt>current<block_start>a1<augadd>current.val<times>(10<power>i)<line_sep>current=current.next<line_sep>i<augadd>1<block_end>j=0<line_sep>current=l2<while_stmt>current<block_start>a2<augadd>current.val<times>(10<power>j)<line_sep>current=current.next<line_sep>j<augadd>1<block_end>result=a1+a2<line_sep>link=ListNode(0)<line_sep>current=link<if_stmt>result<eq>0<block_start><return>link<block_end><while_stmt>result<g>0<block_start>current.next=ListNode(result%10)<line_sep>result=result<floordiv>10<line_sep>current=current.next<block_end><return>link.next<block_end><block_end> |
"Code used to generate data for experiments with synthetic data"<import_stmt>math<import_stmt>typing<as>ty<import_stmt>numba<import_stmt>numpy<as>np<import_stmt>torch<import_stmt>torch.nn<as>nn<import_from_stmt>numba.experimental jitclass<import_from_stmt>tqdm.auto tqdm<class_stmt>MLP(nn.Module)<block_start><def_stmt>__init__ self * d_in:int d_layers:ty.List[int] d_out:int bias:bool=<true> <arrow><none><block_start>super().__init__()<line_sep>self.layers=nn.ModuleList([nn.Linear(d_layers[i-1]<if>i<else>d_in x bias=bias)<for>i,x enumerate(d_layers)])<line_sep>self.head=nn.Linear(d_layers[-1]<if>d_layers<else>d_in d_out)<def_stmt>init_weights m<block_start><if_stmt>isinstance(m nn.Linear)<block_start>torch.nn.init.kaiming_normal_(m.weight mode='fan_in')<if_stmt>m.bias<is><not><none><block_start>fan_in,_=torch.nn.init._calculate_fan_in_and_fan_out(m.weight)<line_sep>bound=1/math.sqrt(fan_in)<line_sep>torch.nn.init.uniform_(m.bias -bound bound)<block_end><block_end><block_end>self.apply(init_weights)<block_end><def_stmt>forward self x:torch.Tensor<arrow>torch.Tensor<block_start><for_stmt>layer self.layers<block_start>x=layer(x)<line_sep>x=torch.relu(x)<block_end>x=self.head(x)<line_sep>x=x.squeeze(-1)<line_sep><return>x<block_end><block_end>@jitclass(spec=[('left_children' numba.int64[:]) ('right_children' numba.int64[:]) ('feature' numba.int64[:]) ('threshold' numba.float32[:]) ('value' numba.float32[:]) ('is_leaf' numba.int64[:]) ])<class_stmt>Tree<block_start>"Randomly initialized decision tree"<def_stmt>__init__ self n_features n_nodes max_depth<block_start><assert_stmt>(2<power>np.arange(max_depth+1)).sum()<ge>n_nodes "Too much nodes"<line_sep>self.left_children=np.ones(n_nodes dtype=np.int64)<times>-1<line_sep>self.right_children=np.ones(n_nodes dtype=np.int64)<times>-1<line_sep>self.feature=np.random.randint(0 n_features (n_nodes ))<line_sep>self.threshold=np.random.randn(n_nodes).astype(np.float32)<line_sep>self.value=np.random.randn(n_nodes).astype(np.float32)<line_sep>depth=np.zeros(n_nodes dtype=np.int64)<line_sep># Root is 0
self.is_leaf=np.zeros(n_nodes dtype=np.int64)<line_sep>self.is_leaf[0]=1<line_sep># Keep adding nodes while we can (new node must have 2 children)
<while_stmt><true><block_start>idx=np.flatnonzero(self.is_leaf)[np.random.choice(self.is_leaf.sum())]<if_stmt>depth[idx]<l>max_depth<block_start>unused=np.flatnonzero((self.left_children<eq>-1)&(self.right_children<eq>-1)&~self.is_leaf)<if_stmt>len(unused)<l>2<block_start><break><block_end>lr_child=unused[np.random.permutation(unused.shape[0])[:2]]<line_sep>self.is_leaf[lr_child]=1<line_sep>self.is_leaf[lr_child]=1<line_sep>depth[lr_child]=depth[idx]+1<line_sep>self.left_children[idx]=lr_child[0]<line_sep>self.right_children[idx]=lr_child[1]<line_sep>self.is_leaf[idx]=0<block_end><block_end><block_end><def_stmt>apply self x<block_start>y=np.zeros(x.shape[0])<for_stmt>i range(x.shape[0])<block_start>idx=0<while_stmt><not>self.is_leaf[idx]<block_start><if_stmt>x[i self.feature[idx]]<l>self.threshold[idx]<block_start>idx=self.left_children[idx]<block_end><else_stmt><block_start>idx=self.right_children[idx]<block_end><block_end>y[i]=self.value[idx]<block_end><return>y<block_end><block_end><class_stmt>TreeEnsemble<block_start>"Combine multiple trees"<def_stmt>__init__ self * n_trees n_features n_nodes max_depth<block_start>self.trees=[Tree(n_features=n_features n_nodes=n_nodes max_depth=max_depth)<for>_ range(n_trees)]<block_end><def_stmt>apply self x<block_start><return>np.mean([t.apply(x)<for>t tqdm(self.trees)] axis=0)<block_end><block_end> |
<import_from_stmt>stix2 Filter<import_from_stmt>itertools chain<import_stmt>copy<import_from_stmt>mitreattack.navlayers.exporters.matrix_gen MatrixGen<import_from_stmt>mitreattack.navlayers.core.exceptions BadInput typeChecker<import_from_stmt>mitreattack.navlayers.core.layer Layer<import_from_stmt>mitreattack.navlayers.generators.gen_helpers remove_revoked_depreciated get_attack_id build_data_strings<class_stmt>UnableToFindStixObject(Exception)<block_start><pass><block_end><class_stmt>StixObjectIsNotValid(Exception)<block_start><pass><block_end><class_stmt>UsageLayerGenerator<block_start>"""Generates a Layer that shows techniques mapped to an input group, software or mitigation"""<def_stmt>__init__ self source domain='enterprise' resource=<none><block_start>"""
Initialize the Generator
:param source: Which source to use for data (local, taxii [server], or [remote] ATT&CK Workbench)
:param domain: Which matrix to use during generation
:param resource: string path to local STIX data (local) or url of workbench to reach out to (remote)
"""<line_sep>self.matrix_handle=MatrixGen(source resource)<line_sep>self.domain=domain<try_stmt><block_start>self.source_handle=self.matrix_handle.collections[domain]<block_end><except_stmt>KeyError<block_start>print(f"[UsageGenerator] - unable to load collection {domain} (current source = {source}).")<line_sep><raise>BadInput<block_end>self.full_matrix=self.matrix_handle.get_matrix(self.domain)<line_sep>self.sources=self.source_handle.query([Filter('type' '=' 'x-mitre-data-source')])<line_sep>self.components=self.source_handle.query([Filter('type' '=' 'x-mitre-data-component')])<line_sep>self.source_mapping=build_data_strings(self.sources self.components)<block_end><def_stmt>get_stix_object self match<block_start>"""
Retrieve the stix object for a given string
:param match: The string to match on - can be a name, alias, or ATT&CK ID
:return: the corresponding stix object
"""<line_sep>filts=[[Filter('name' '=' match)] [Filter(match 'in' 'aliases')] [Filter(match 'in' 'x_mitre_aliases')] [Filter('external_references.external_id' '=' match)] [Filter('id' '=' match)]# Support data component type objects from sum generator
]<line_sep>data=list(chain.from_iterable(self.source_handle.query(f)<for>f filts))<line_sep>data=remove_revoked_depreciated(data)<if_stmt>len(data)<block_start><if_stmt>len(data)<g>1<block_start>print(f"[Usage Generator] - WARNING! Multiple matches found for {match}: [{data}]. Selecting the first "<concat>f"one as default.")<block_end><return>data[0]<block_end><raise>UnableToFindStixObject<block_end><def_stmt>get_matrix_data self match_pattern<block_start>"""
Retrieve a list of attack-pattern (technique) objects that map to a group, software or mitigation.
:param match_pattern: Name, associated group/software (alias), or ATT&CK ID.
Techniques mapped to the object matching this pattern are returned.```
"""<line_sep>obj=self.get_stix_object(match_pattern)<if_stmt>obj['type']<eq>'course-of-action'<block_start>verb='mitigates'<block_end><elif_stmt>obj['type']<eq>'x-mitre-data-component'<or>obj['type']<eq>'x-mitre-data-source'<block_start>verb='detects'<block_end><else_stmt><block_start>verb='uses'<block_end>related=self.source_handle.relationships(obj['id'] verb source_only=<true>)<line_sep>out=self.source_handle.query([Filter('type' '=' 'attack-pattern') Filter('id' 'in' [r.target_ref<for>r related])])<line_sep><return>remove_revoked_depreciated(out) obj<block_end><def_stmt>generate_technique_data self raw_matches<block_start>"""
Generate technique list of dictionary objects (dictionary form of technique listing for a layer)
:param raw_matches: matching attack-pattern objects
:return: list of dictionary objects for every technique: score=0 if not in raw_matches, 1 otherwise,
description in comments
"""<line_sep>shortlist=[]<for_stmt>match raw_matches<block_start>xid=''<line_sep>xphase=''<for_stmt>ref match.external_references<block_start><if_stmt>ref.source_name<eq>'mitre-attack'<block_start>xid=ref.external_id<block_end><block_end><for_stmt>phase match.kill_chain_phases<block_start><if_stmt>phase.kill_chain_name<eq>'mitre-attack'<block_start>xphase=phase.phase_name<block_end><block_end>shortlist.append((xid xphase match.description))<block_end>full_matrix_listing=copy.deepcopy(self.full_matrix)<line_sep>construct=list()<for_stmt>tactic full_matrix_listing<block_start><for_stmt>tech tactic.techniques<block_start>construct.append(dict(techniqueID=tech.id score=0 tactic=self.matrix_handle.convert(tactic.tactic.name)))<block_end><for_stmt>tech_key tactic.subtechniques<block_start><for_stmt>subtech tactic.subtechniques[tech_key]<block_start>construct.append(dict(techniqueID=subtech.id score=0 tactic=self.matrix_handle.convert(tactic.tactic.name)))<block_end><block_end><block_end><for_stmt>entry shortlist<block_start><for_stmt>tac construct<block_start><if_stmt>entry[0]<eq>tac['techniqueID']<and>(entry[1]<eq>''<or>entry[1]<eq>tac['tactic'])<block_start>tac['score']=1<line_sep>tac['comment']=entry[2]<block_end><block_end><block_end><return>construct<block_end><def_stmt>generate_layer self match<block_start>"""
Generate a layer
:param match: the pattern to match
:return: layer object with annotated techniques
"""<line_sep>typeChecker(type(self).__name__ match str "match")<line_sep>raw_data,matched_obj=self.get_matrix_data(match)<if_stmt>matched_obj['type']<not><in>["course-of-action" 'tool' 'malware' 'intrusion-set' 'x-mitre-data-source' 'x-mitre-data-component']<block_start>print(f"Warning: The input match {match} corresponds with an ATT&CK Technique, which is not supported. "<concat>f"Please provide a group, software, or mitigation instead.")<line_sep><raise>StixObjectIsNotValid<block_end>a_id=get_attack_id(matched_obj)<line_sep>processed_listing=self.generate_technique_data(raw_data)<line_sep>raw_layer=dict(name=f"{matched_obj['name']} ({matched_obj['id']})" domain=self.domain+'-attack')<line_sep>raw_layer['techniques']=processed_listing<line_sep>output_layer=Layer(raw_layer)<if_stmt>matched_obj['type']<ne>'x-mitre-data-component'<block_start>name=matched_obj['name']<block_end><else_stmt><block_start>name=self.source_mapping[matched_obj['id']]<block_end>output_layer.description=f"{self.domain.capitalize()<if>len(self.domain)<g>3<else>self.domain.upper()} "<concat>f"techniques used by {name}, ATT&CK {matched_obj['type']} {a_id}"<line_sep><return>output_layer<block_end><block_end> |
GUIDs={"ASROCK_ACPIS4_DXE_GUID":[69196166 45078 18382 175 197 34 105 237 212 173 100] "ASROCK_USBRT_GUID":[82487969 10657 4567 136 56 0 80 4 115 212 235] "ASROCK_RAID_SETUP_GUID":[152494882 14144 12750 173 98 189 23 44 236 202 54] "ASROCK_RAID_LOADER_GUID":[164506669 19843 17592 151 208 16 133 235 84 144 184] "ASROCK_SIOSLPSMI_GUID":[204970154 53806 19926 140 180 60 156 251 29 134 211] "ASROCK_PLEDDXE_GUID":[260599413 12329 20175 182 148 34 137 77 63 33 67] "ASROCK_A_DEFAULT_DXE_GUID":[303480106 49246 19565 145 231 235 142 55 173 59 122] "ASROCK_USER_DEF_SETUP_DXE_GUID":[321832763 48422 20415 177 147 138 203 80 239 189 137] "ASROCK_WAKEUP_CTRL_SMM_GUID":[460234064 4836 19285 129 217 26 191 236 89 212 252] "ASROCK_AMI_AGESA_DXE_GUID":[503020538 49038 19729 151 102 47 176 208 68 35 16] "ASROCK_HDD_READY_SMI_GUID":[560462180 29336 19087 154 42 191 228 152 214 0 168] "ASROCK_MOUSE_DRIVER_GUID":[719032155 51156 20094 190 42 35 99 77 246 104 161] "ASROCK_IDESMM_GUID":[829100592 1280 17810 140 9 234 186 15 182 176 127] "ASROCK_BFGSMI_GUID":[978522445 22131 19929 181 179 203 114 195 71 102 155] "ASROCK_ASRLOGODXE_GUID":[1033880909 6629 19152 185 134 2 214 135 215 96 229] "ASROCK_ASM104_X_DXE_GUID":[1080004582 21011 19333 184 33 151 183 122 255 121 91] "ASROCK_HDAUDIO_SMI_GUID":[1254707048 58961 19256 161 216 45 93 239 250 15 96] "ASROCK_SM_BUS_DXE_GUID":[1265110573 3427 20322 185 48 122 233 149 185 179 163] "ASROCK_USBINT13_GUID":[1275096281 6586 17943 132 131 96 145 148 161 172 252] "ASROCK_SLP_SUPPORT_GUID":[1279872597 22601 21314 69 84 84 69 82 33 33 33] "ASROCK_PATA_CONTROLLER_GUID":[1334921163 38702 20316 184 105 160 33 130 201 217 60] "ASROCK_SATA_CONTROLLER_GUID":[1359869601 46785 18760 174 231 89 242 32 248 152 189] "ASROCK_ACPIS4_SMM_GUID":[1368992111 10248 19194 148 196 153 246 176 108 135 30] "ASROCK_POST_REPORT_GUID":[1413923475 13211 18381 183 25 88 93 227 148 8 204] "ASROCK_CLOCK_GEN_DXE_GUID":[1447053695 25694 17937 185 21 230 130 200 189 71 131] "ASROCK_UHCD_GUID":[1477302528 14429 4567 136 58 0 80 4 115 212 235] "ASROCK_LEGACY_REGION_GUID":[1495543256 59343 18809 182 14 166 6 126 42 24 95] "ASROCK_SLEEP_SMI_GUID":[1654193688 54767 17079 187 12 41 83 40 63 87 4] "ASROCK_CMOS_MANAGER_SMM_GUID":[1751762355 44173 18803 139 55 227 84 219 243 74 221] "ASROCK_AMD_AGESA_DXE_DRIVER_GUID":[1766895615 28387 4573 173 139 8 0 32 12 154 102] "ASROCK_RE_FLASH_GUID":[1893836824 3041 17481 191 212 158 246 140 127 2 168] "ASROCK_LEGACY_INTERRUPT_GUID":[1911362257 9483 17147 140 23 16 220 250 119 23 1] "ASROCK_SMM_CHILD_DISPATCHER_GUID":[1966485705 64229 18345 187 191 136 214 33 205 114 130] "ASROCK_BFGDXE_GUID":[1988600983 65358 18687 188 170 103 219 246 92 66 209] "ASROCK_IFLASHSETUP_GUID":[2011543064 9746 19496 188 223 162 177 77 138 62 254] "ASROCK_S4_SLEEPDELAY_GUID":[2075935011 23902 19484 149 209 48 235 164 135 1 202] "ASROCK_HDD_READY_DXE_GUID":[2179248970 9868 20428 142 57 28 29 62 111 110 105] "ASROCK_RTLANDXE_GUID":[2332955475 13708 20015 147 69 238 191 29 171 152 155] "ASROCK_AMD_SB900_DXE_GUID":[2333274783 28981 20139 175 218 5 18 247 75 101 234] "ASROCK_SB900_SMBUS_LIGHT_GUID":[2551896525 34437 19115 175 218 5 18 247 75 101 234] "ASROCK_AAFTBL_SMI_GUID":[2667102838 46054 19161 143 231 199 79 113 196 114 72] "ASROCK_NVRAMID_GUID":[2708185858 25876 17031 190 227 98 35 183 222 44 33] "ASROCK_IDE_SECURITY_GUID":[2847342799 414 19851 163 167 136 225 234 1 105 158] "ASROCK_ASM1061_DXE_GUID":[2848876245 27959 17694 169 191 245 143 122 11 60 194] "ASROCK_ASM104_X_SMI_GUID":[2904508538 47702 18652 142 170 232 251 234 116 184 242] "ASROCK_RTLANSMI_GUID":[3005543067 24215 19449 180 224 81 37 193 246 5 213] "ASROCK_GEC_UPDATE_SMI_GUID":[3092850716 5882 17832 146 1 28 56 48 169 115 189] "ASROCK_APMOFF_GUID":[3146872289 16021 19326 135 80 157 106 163 78 183 246] "ASROCK_SMIFLASH_GUID":[3157425597 47490 20309 159 121 5 106 215 233 135 197] "ASROCK_RAID_X64_GUID":[3295196034 17744 18697 173 87 36 150 20 27 63 74] "ASROCK_AMD_SB900_SMM_GUID":[3351810409 6722 20062 179 75 230 131 6 113 201 166] "ASROCK_FIREWIRE_GUID":[3367390790 38937 17835 135 93 9 223 218 109 139 27] "ASROCK_IDE_SMART_GUID":[3581707566 32927 17871 163 119 215 123 192 203 120 238] "ASROCK_SB_INTERFACE_DXE_GUID":[3622218689 38683 17947 181 228 60 55 102 38 122 217] "ASROCK_AMD_SB900_SMM_DISPATCHER_GUID":[3748899802 31298 20062 179 75 230 131 6 113 201 166] "ASROCK_AMDCPU_DXE_GUID":[3786566962 16719 18139 154 238 66 0 119 243 93 190] "ASROCK_SMBIOS_DMIEDIT_GUID":[3802613560 35124 18677 132 18 153 233 72 200 220 27] "ASROCK_SECURITY_SELECT_DXE_GUID":[3832130086 37480 20144 160 135 221 76 238 55 64 75] "ASROCK_FILE_EXPLORER_LITE_GUID":[3875982164 33976 16573 131 47 127 178 213 203 135 179] "ASROCK_PLEDSMM_GUID":[3911953940 15869 19568 159 230 56 153 243 108 120 70] "ASROCK_CPU_SMBIOS_DRIVER_GUID":[3930959592 43089 19103 171 244 183 159 162 82 130 145] "ASROCK_AAFTBL_DXE_GUID":[4279363330 35107 18380 173 48 217 224 226 64 221 16] }<line_sep> |
# coding=utf-8
# Copyright 2021 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 tf3d.utils.projections."""<import_stmt>numpy<as>np<import_stmt>tensorflow<as>tf<import_from_stmt>tf3d.utils projections<class_stmt>ProjectionsTest(tf.test.TestCase)<block_start><def_stmt>_get_transformation_matrices self# pylint: disable=bad-whitespace
<block_start>rotate_world_to_camera=tf.constant([[2.34773703e-04 -9.99944150e-01 -1.05634779e-02] [1.04494076e-02 1.05653536e-02 -9.99889553e-01] [9.99945402e-01 1.24365382e-04 1.04513029e-02]] dtype=tf.float32)<line_sep>translate_world_to_camera=tf.constant([0.05705245 -0.07546672 -0.26938692] dtype=tf.float32)<line_sep>tr_camera_to_image=tf.constant([[721.53771973 0. 609.55932617] [0. 721.53771973 172.85400391] [0. 0. 1.]] dtype=tf.float32)<line_sep># pylint: enable=bad-whitespace
<return>(rotate_world_to_camera translate_world_to_camera tr_camera_to_image)<block_end><def_stmt>test_to_camera_frame self<block_start>num_points=1000<line_sep>original_wf_points=tf.random.uniform((num_points 3) minval=-10.0 maxval=10.0)<line_sep>(rotate_world_to_camera translate_world_to_camera _)=self._get_transformation_matrices()<line_sep>cf_points=projections.to_camera_frame(original_wf_points rotate_world_to_camera translate_world_to_camera)<line_sep>computed_wf_points=projections.to_world_frame(cf_points rotate_world_to_camera translate_world_to_camera)<line_sep>self.assertAllClose(original_wf_points.numpy() computed_wf_points.numpy())<line_sep>self.assertEqual(original_wf_points.shape (num_points 3))<line_sep>self.assertEqual(cf_points.shape (num_points 3))<line_sep>self.assertEqual(computed_wf_points.shape (num_points 3))<block_end><def_stmt>test_to_image_frame self<block_start>height=375<line_sep>width=1242<line_sep>cf_points=tf.convert_to_tensor([[0.0 0.0 10.0] [0.0 0.2 12.0] [0.0 -0.2 20.0] [1.0 0.0 20.0] [-1.0 0.0 20.0] [0 0 -10] [-1 1 -20]] dtype=tf.float32)<line_sep>_,_,camera_intrinsics=self._get_transformation_matrices()<line_sep>image_points,within_image=projections.to_image_frame(cf_points height width camera_intrinsics)<line_sep>np_image_points=image_points.numpy()<line_sep>np_within_image=within_image.numpy()<line_sep>self.assertEqual(np_within_image.sum() 5)<line_sep>self.assertTrue((np_image_points[np_within_image]<ge>0).all())<line_sep>self.assertTrue((np_image_points[np_within_image 0]<l>width).all())<line_sep>self.assertTrue((np_image_points[np_within_image 1]<l>height).all())<block_end><def_stmt>test_image_frame_to_camera_frame self<block_start>num_points=10<line_sep>height,width=480 640<line_sep>image_frame=tf.concat([tf.random.uniform([num_points 1] minval=0.0 maxval=width dtype=tf.float32) tf.random.uniform([num_points 1] minval=0.0 maxval=height dtype=tf.float32)] axis=1)<line_sep>camera_intrinsics=tf.constant([[500 0. 320.] [0. 500. 120.] [0. 0. 1.]] dtype=tf.float32)<line_sep>camera_frame=projections.image_frame_to_camera_frame(image_frame=image_frame camera_intrinsics=camera_intrinsics)<line_sep>self.assertEqual(camera_frame.shape (num_points 3))<block_end><def_stmt>_test_create_image_from_rank1_values_unbatched self use_sparse_tensor<block_start>image_height,image_width=(240 320)<line_sep>xx=tf.random.uniform((10 ) minval=0 maxval=image_width dtype=tf.int32)<line_sep>yy=tf.random.uniform((10 ) minval=0 maxval=image_height dtype=tf.int32)<line_sep>pixel_locations=tf.stack([yy xx] axis=1)<line_sep>pixel_values=tf.ones((tf.shape(pixel_locations)[0] ) dtype=tf.float32)<line_sep>created_image=projections.create_image_from_point_values_unbatched(pixel_locations=pixel_locations pixel_values=pixel_values image_height=image_height image_width=image_width default_value=255 use_sparse_tensor=use_sparse_tensor)<line_sep>self.assertAllClose(pixel_values.numpy() np.ones((10 ) dtype=np.uint8))<line_sep>np_expected_image=np.full((image_height image_width 1) 255 np.uint8)<line_sep>np_yy=pixel_locations.numpy()[: 0]<line_sep>np_xx=pixel_locations.numpy()[: 1]<line_sep>np_expected_image[np_yy np_xx Ellipsis]=[1]<line_sep>self.assertAllClose(created_image.numpy() np_expected_image)<block_end><def_stmt>_test_create_image_from_rank1_values self use_sparse_tensor<block_start>image_height,image_width=(240 320)<line_sep>xx=tf.random.uniform((4 10) minval=0 maxval=image_width dtype=tf.int32)<line_sep>yy=tf.random.uniform((4 10) minval=0 maxval=image_height dtype=tf.int32)<line_sep>pixel_locations=tf.stack([yy xx] axis=2)<line_sep>pixel_values=tf.random.uniform([4 10 3] minval=-2.0 maxval=2.0 dtype=tf.float32)<line_sep>num_valid_points=tf.constant([10 3 5 7] dtype=tf.int32)<line_sep>created_image=projections.create_image_from_point_values(pixel_locations=pixel_locations pixel_values=pixel_values num_valid_points=num_valid_points image_height=image_height image_width=image_width default_value=255.0 use_sparse_tensor=use_sparse_tensor)<line_sep>self.assertAllEqual(created_image.shape np.array([4 240 320 3]))<block_end><def_stmt>_test_create_image_from_rank2_values_unbatched self use_sparse_tensor<block_start>image_height,image_width=(240 320)<line_sep>xx=tf.random.uniform((10 ) minval=0 maxval=image_width dtype=tf.int32)<line_sep>yy=tf.random.uniform((10 ) minval=0 maxval=image_height dtype=tf.int32)<line_sep>pixel_locations=tf.stack([yy xx] axis=1)<line_sep>pixel_values=tf.random.uniform((10 3) minval=0 maxval=255 dtype=tf.float32)<line_sep>created_image=projections.create_image_from_point_values_unbatched(pixel_locations=pixel_locations pixel_values=pixel_values image_height=image_height image_width=image_width default_value=0 use_sparse_tensor=use_sparse_tensor)<line_sep>self.assertEqual(created_image.shape (image_height image_width 3))<line_sep>np_pixel_locations=pixel_locations.numpy().round().astype(np.int32)<line_sep>np_yy=np_pixel_locations[: 0]<line_sep>np_xx=np_pixel_locations[: 1]<line_sep>self.assertAllClose(created_image.numpy()[np_yy np_xx] pixel_values.numpy() atol=1e-3)<block_end><def_stmt>test_create_image_rank1_unbatched_sparse self<block_start>self._test_create_image_from_rank1_values_unbatched(use_sparse_tensor=<true>)<block_end><def_stmt>test_create_image_rank1_unbatched_scatter self<block_start>self._test_create_image_from_rank1_values_unbatched(use_sparse_tensor=<false>)<block_end><def_stmt>test_create_image_rank1_sparse self<block_start>self._test_create_image_from_rank1_values(use_sparse_tensor=<true>)<block_end><def_stmt>test_create_image_rank1_scatter self<block_start>self._test_create_image_from_rank1_values(use_sparse_tensor=<false>)<block_end><def_stmt>test_create_image_rank2_unbatched_sparse self<block_start>self._test_create_image_from_rank2_values_unbatched(use_sparse_tensor=<true>)<block_end><def_stmt>test_create_image_rank2_unbatched_scatter self<block_start>self._test_create_image_from_rank2_values_unbatched(use_sparse_tensor=<false>)<block_end><def_stmt>_test_move_image_values_to_points self use_sparse_tensor<block_start>image_values=tf.constant([[[1.0 2.0] [3.0 4.0]] [[5.0 6.0] [7.0 8.0]] [[9.0 10.0] [11.0 12.0]]] dtype=tf.float32)<line_sep>image_point_indices=tf.constant([[[1] [-1]] [[6] [-1]] [[0] [3]]] dtype=tf.int32)<line_sep>num_points=10<line_sep>point_values=projections.move_image_values_to_points(image_values=image_values image_point_indices=image_point_indices num_points=num_points default_value=-1.0 use_sparse_tensor=use_sparse_tensor)<line_sep>expected_point_values=tf.constant([[9.0 10.0] [1.0 2.0] [-1.0 -1.0] [11.0 12.0] [-1.0 -1.0] [-1.0 -1.0] [5.0 6.0] [-1.0 -1.0] [-1.0 -1.0] [-1.0 -1.0]] dtype=tf.float32)<line_sep>self.assertAllClose(point_values.numpy() expected_point_values.numpy())<block_end><def_stmt>test_move_image_values_to_points_sparse self<block_start>self._test_move_image_values_to_points(use_sparse_tensor=<true>)<block_end><def_stmt>test_move_image_values_to_points_scatter self<block_start>self._test_move_image_values_to_points(use_sparse_tensor=<false>)<block_end><def_stmt>test_update_pixel_locations_given_deformed_meshgrid self<block_start>pixel_locations=tf.constant([[0 1] [1 1] [2 0] [2 2] [0 2] [0 1] [1 1] [3 3]] dtype=tf.int32)<line_sep>meshgrid_y=tf.constant([[1 1 1 1 1] [2 2 2 2 2] [3 3 3 3 3] [4 4 4 4 4]])<line_sep>meshgrid_x=tf.constant([[1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5] [1 2 3 4 5]])<line_sep>meshgrid_yx=tf.stack([meshgrid_y meshgrid_x] axis=2)<line_sep>deformed_meshgrid_y=tf.constant([[-1 3 2 2] [-1 -1 3 2] [1 -1 2 -1]])<line_sep>deformed_meshgrid_x=tf.constant([[2 -2 2 -1] [-1 3 2 3] [2 -1 3 -1]])<line_sep>deformed_meshgrid_yx=tf.stack([deformed_meshgrid_y deformed_meshgrid_x] axis=2)<line_sep>updated_pixel_locations=(projections.update_pixel_locations_given_deformed_meshgrid(pixel_locations=pixel_locations original_meshgrid=meshgrid_yx deformed_meshgrid=deformed_meshgrid_yx))<line_sep>expected_updated_pixel_locations=tf.constant([[2 0] [0 2] [-1 -1] [-1 -1] [-1 -1] [2 0] [0 2] [-1 -1]] dtype=tf.int32)<line_sep>self.assertAllEqual(updated_pixel_locations.numpy() expected_updated_pixel_locations.numpy())<block_end><def_stmt>test_project_points_with_depth_visibility_check self<block_start>point_positions=tf.constant([[-1.0 -1.0 1.0] [-1.0 1.0 1.0] [1.0 -1.0 1.0] [1.0 1.0 1.0]] dtype=tf.float32)<line_sep>camera_intrinsics=tf.constant([[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]] dtype=tf.float32)<line_sep>camera_rotation_matrix=tf.constant([[1.0 0.0 0.0] [0.0 1.0 0.0] [0.0 0.0 1.0]] dtype=tf.float32)<line_sep>camera_translation=tf.constant([5.0 5.0 0.0] dtype=tf.float32)<line_sep>image_width=10<line_sep>image_height=10<line_sep>depth_image_00=tf.ones([5 5 1] dtype=tf.float32)<times>1.0<line_sep>depth_image_01=tf.ones([5 5 1] dtype=tf.float32)<times>2.0<line_sep>depth_image_10=tf.ones([5 5 1] dtype=tf.float32)<times>1.0<line_sep>depth_image_11=tf.ones([5 5 1] dtype=tf.float32)<times>4.0<line_sep>depth_image=tf.concat([tf.concat([depth_image_00 depth_image_01] axis=1) tf.concat([depth_image_10 depth_image_11] axis=1)] axis=0)<line_sep>depth_threshold=0.1<line_sep>(points_in_image_frame visibility)=projections.project_points_with_depth_visibility_check(point_positions=point_positions camera_intrinsics=camera_intrinsics camera_rotation_matrix=camera_rotation_matrix camera_translation=camera_translation image_width=image_width image_height=image_height depth_image=depth_image depth_intrinsics=camera_intrinsics depth_threshold=depth_threshold)<line_sep>self.assertAllEqual(visibility.numpy().astype(np.int32) np.array([1 1 0 0]))<line_sep>self.assertAllEqual(points_in_image_frame.numpy() np.array([[4 4] [4 6] [6 4] [6 6]]))<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>tf.test.main()<block_end> |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
An example of reading a line at a time from standard input
without blocking the reactor.
"""<import_from_stmt>os linesep<import_from_stmt>twisted.internet stdio<import_from_stmt>twisted.protocols basic<class_stmt>Echo(basic.LineReceiver)<block_start>delimiter=linesep.encode("ascii")<def_stmt>connectionMade self<block_start>self.transport.write(b">>> ")<block_end><def_stmt>lineReceived self line<block_start>self.sendLine(b"Echo: "+line)<line_sep>self.transport.write(b">>> ")<block_end><block_end><def_stmt>main <block_start>stdio.StandardIO(Echo())<import_from_stmt>twisted.internet reactor<line_sep>reactor.run()<block_end><if_stmt>__name__<eq>"__main__"<block_start>main()<block_end> |
<import_stmt>networkx<as>nx<class_stmt>Hierarchy<block_start><def_stmt>__init__ self tree column<block_start>self.tree=tree<line_sep>self.column=column<block_end><def_stmt>_leaves_below self node<block_start>leaves=sum(([vv<for>vv v<if>self.tree.out_degree(vv)<eq>0]<for>k,v nx.dfs_successors(self.tree node).items()) [])<line_sep><return>sorted(leaves)<or>[node]<block_end><def_stmt>__call__ self *nodes<block_start>"""Return process IDs below the given nodes in the tree"""<line_sep>s=set()<for_stmt>node nodes<block_start><if_stmt>self.tree.in_degree(node)<eq>0<block_start><return><none># all
<block_end>s.update(self._leaves_below(node))<block_end><if_stmt>len(s)<eq>1<block_start>query='{} == "{}"'.format(self.column s.pop())<block_end><else_stmt><block_start>query='{} in {}'.format(self.column repr(sorted(s)))<block_end><return>query<block_end><block_end> |
# The start of a win32gui generic demo.
# Feel free to contribute more demos back ;-)
<import_stmt>win32gui win32con win32api<import_stmt>time math random<def_stmt>_MyCallback hwnd extra<block_start>hwnds,classes=extra<line_sep>hwnds.append(hwnd)<line_sep>classes[win32gui.GetClassName(hwnd)]=1<block_end><def_stmt>TestEnumWindows <block_start>windows=[]<line_sep>classes={}<line_sep>win32gui.EnumWindows(_MyCallback (windows classes))<line_sep>print("Enumerated a total of %d windows with %d classes"%(len(windows) len(classes)))<if_stmt>"tooltips_class32"<not><in>classes<block_start>print("Hrmmmm - I'm very surprised to not find a 'tooltips_class32' class.")<block_end><block_end><def_stmt>OnPaint_1 hwnd msg wp lp<block_start>dc,ps=win32gui.BeginPaint(hwnd)<line_sep>win32gui.SetGraphicsMode(dc win32con.GM_ADVANCED)<line_sep>br=win32gui.CreateSolidBrush(win32api.RGB(255 0 0))<line_sep>win32gui.SelectObject(dc br)<line_sep>angle=win32gui.GetWindowLong(hwnd win32con.GWL_USERDATA)<line_sep>win32gui.SetWindowLong(hwnd win32con.GWL_USERDATA angle+2)<line_sep>r_angle=angle<times>(math.pi/180)<line_sep>win32gui.SetWorldTransform(dc {"M11":math.cos(r_angle) "M12":math.sin(r_angle) "M21":math.sin(r_angle)<times>-1 "M22":math.cos(r_angle) "Dx":250 "Dy":250 } )<line_sep>win32gui.MoveToEx(dc 250 250)<line_sep>win32gui.BeginPath(dc)<line_sep>win32gui.Pie(dc 10 70 200 200 350 350 75 10)<line_sep>win32gui.Chord(dc 200 200 850 0 350 350 75 10)<line_sep>win32gui.LineTo(dc 300 300)<line_sep>win32gui.LineTo(dc 100 20)<line_sep>win32gui.LineTo(dc 20 100)<line_sep>win32gui.LineTo(dc 400 0)<line_sep>win32gui.LineTo(dc 0 400)<line_sep>win32gui.EndPath(dc)<line_sep>win32gui.StrokeAndFillPath(dc)<line_sep>win32gui.EndPaint(hwnd ps)<line_sep><return>0<block_end>wndproc_1={win32con.WM_PAINT:OnPaint_1}<def_stmt>OnPaint_2 hwnd msg wp lp<block_start>dc,ps=win32gui.BeginPaint(hwnd)<line_sep>win32gui.SetGraphicsMode(dc win32con.GM_ADVANCED)<line_sep>l,t,r,b=win32gui.GetClientRect(hwnd)<for_stmt>x range(25)<block_start>vertices=({"x":int(random.random()<times>r) "y":int(random.random()<times>b) "Red":int(random.random()<times>0xFF00) "Green":0 "Blue":0 "Alpha":0 } {"x":int(random.random()<times>r) "y":int(random.random()<times>b) "Red":0 "Green":int(random.random()<times>0xFF00) "Blue":0 "Alpha":0 } {"x":int(random.random()<times>r) "y":int(random.random()<times>b) "Red":0 "Green":0 "Blue":int(random.random()<times>0xFF00) "Alpha":0 } )<line_sep>mesh=((0 1 2) )<line_sep>win32gui.GradientFill(dc vertices mesh win32con.GRADIENT_FILL_TRIANGLE)<block_end>win32gui.EndPaint(hwnd ps)<line_sep><return>0<block_end>wndproc_2={win32con.WM_PAINT:OnPaint_2}<def_stmt>TestSetWorldTransform <block_start>wc=win32gui.WNDCLASS()<line_sep>wc.lpszClassName="test_win32gui_1"<line_sep>wc.style=win32con.CS_GLOBALCLASS|win32con.CS_VREDRAW|win32con.CS_HREDRAW<line_sep>wc.hbrBackground=win32con.COLOR_WINDOW+1<line_sep>wc.lpfnWndProc=wndproc_1<line_sep>class_atom=win32gui.RegisterClass(wc)<line_sep>hwnd=win32gui.CreateWindow(wc.lpszClassName "Spin the Lobster!" win32con.WS_CAPTION|win32con.WS_VISIBLE 100 100 900 900 0 0 0 <none> )<for_stmt>x range(500)<block_start>win32gui.InvalidateRect(hwnd <none> <true>)<line_sep>win32gui.PumpWaitingMessages()<line_sep>time.sleep(0.01)<block_end>win32gui.DestroyWindow(hwnd)<line_sep>win32gui.UnregisterClass(wc.lpszClassName <none>)<block_end><def_stmt>TestGradientFill <block_start>wc=win32gui.WNDCLASS()<line_sep>wc.lpszClassName="test_win32gui_2"<line_sep>wc.style=win32con.CS_GLOBALCLASS|win32con.CS_VREDRAW|win32con.CS_HREDRAW<line_sep>wc.hbrBackground=win32con.COLOR_WINDOW+1<line_sep>wc.lpfnWndProc=wndproc_2<line_sep>class_atom=win32gui.RegisterClass(wc)<line_sep>hwnd=win32gui.CreateWindowEx(0 class_atom "Kaleidoscope" win32con.WS_CAPTION|win32con.WS_VISIBLE|win32con.WS_THICKFRAME|win32con.WS_SYSMENU 100 100 900 900 0 0 0 <none> )<line_sep>s=win32gui.GetWindowLong(hwnd win32con.GWL_EXSTYLE)<line_sep>win32gui.SetWindowLong(hwnd win32con.GWL_EXSTYLE s|win32con.WS_EX_LAYERED)<line_sep>win32gui.SetLayeredWindowAttributes(hwnd 0 175 win32con.LWA_ALPHA)<for_stmt>x range(30)<block_start>win32gui.InvalidateRect(hwnd <none> <true>)<line_sep>win32gui.PumpWaitingMessages()<line_sep>time.sleep(0.3)<block_end>win32gui.DestroyWindow(hwnd)<line_sep>win32gui.UnregisterClass(class_atom <none>)<block_end>print("Enumerating all windows...")<line_sep>TestEnumWindows()<line_sep>print("Testing drawing functions ...")<line_sep>TestSetWorldTransform()<line_sep>TestGradientFill()<line_sep>print("All tests done!")<line_sep> |
<import_stmt>orderedset<def_stmt>find_cycle nodes successors<block_start>path=orderedset.orderedset()<line_sep>visited=set()<def_stmt>visit node# If the node is already in the current path, we have found a cycle.
<block_start><if_stmt><not>path.add(node)<block_start><return>(path node)<block_end># If we have otherwise already visited this node, we don't need to visit
# it again.
<if_stmt>node<in>visited<block_start>item=path.pop()<assert_stmt>item<eq>node<line_sep><return><block_end>visited.add(node)<line_sep># Otherwise, visit all the successors.
<for_stmt>succ successors(node)<block_start>cycle=visit(succ)<if_stmt>cycle<is><not><none><block_start><return>cycle<block_end><block_end>item=path.pop()<assert_stmt>item<eq>node<line_sep><return><none><block_end><for_stmt>node nodes<block_start>cycle=visit(node)<if_stmt>cycle<is><not><none><block_start><return>cycle<block_end><else_stmt><block_start><assert_stmt><not>path.items<block_end><block_end><return><none><block_end> |
<import_from_stmt>. test_trianglemesh<import_from_stmt>. test_voxelgrid<line_sep> |
<import_stmt>unittest<import_from_stmt>securityheaders.checkers.hsts HSTSMaxAgeZeroChecker<class_stmt>HSTSMaxAgeZeroCheckerTest(unittest.TestCase)<block_start><def_stmt>setUp self<block_start>self.x=HSTSMaxAgeZeroChecker()<block_end><def_stmt>test_checkNoHSTS self<block_start>nox=dict()<line_sep>nox['test']='value'<line_sep>self.assertEqual(self.x.check(nox) [])<block_end><def_stmt>test_checkNone self<block_start>nonex=<none><line_sep>self.assertEqual(self.x.check(nonex) [])<block_end><def_stmt>test_checkNoneHSTS self<block_start>hasx=dict()<line_sep>hasx['strict-transport-security']=<none><line_sep>self.assertEqual(self.x.check(hasx) [])<block_end><def_stmt>test_ValidHSTS self<block_start>hasx4=dict()<line_sep>hasx4['strict-transport-security']="max-age=31536000; includeSubDomains"<line_sep>result=self.x.check(hasx4)<line_sep>self.assertEqual(self.x.check(hasx4) [])<block_end><def_stmt>test_ZeroMaxAge self<block_start>hasx5=dict()<line_sep>hasx5['strict-transport-security']="max-age=0; includeSubDomains"<line_sep>result=self.x.check(hasx5)<line_sep>self.assertIsNotNone(result)<line_sep>self.assertEqual(len(result) 1)<block_end><block_end><if_stmt>__name__<eq>'__main__'<block_start>unittest.main()<block_end> |
#
# Copyright (c) 2021 salesforce.com, inc.
# All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
# For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
#
"""
Classic ARIMA (AutoRegressive Integrated Moving Average) forecasting model,
adapted for anomaly detection.
"""<import_from_stmt>merlion.models.anomaly.forecast_based.base ForecastingDetectorBase<import_from_stmt>merlion.models.anomaly.base DetectorConfig<import_from_stmt>merlion.models.forecast.arima ArimaConfig Arima<import_from_stmt>merlion.post_process.threshold AggregateAlarms<class_stmt>ArimaDetectorConfig(ArimaConfig DetectorConfig)<block_start>_default_threshold=AggregateAlarms(alm_threshold=2.5)<block_end><class_stmt>ArimaDetector(ForecastingDetectorBase Arima)<block_start>config_class=ArimaDetectorConfig<block_end> |
<import_from_stmt>typing Callable AsyncGenerator Generator<import_stmt>asyncio<import_stmt>httpx<import_stmt>pytest<import_from_stmt>asgi_lifespan LifespanManager<import_from_stmt>fastapi FastAPI<import_from_stmt>fastapi.testclient TestClient<line_sep>TestClientGenerator=Callable[[FastAPI] AsyncGenerator[httpx.AsyncClient <none>]]<line_sep>@pytest.fixture(scope="session")<def_stmt>event_loop <block_start>loop=asyncio.get_event_loop()<line_sep><yield>loop<line_sep>loop.close()<block_end>@pytest.fixture<async_keyword><def_stmt>client request:pytest.FixtureRequest <arrow>AsyncGenerator[httpx.AsyncClient <none>]<block_start>marker=request.node.get_closest_marker("fastapi")<if_stmt>marker<is><none><block_start><raise>ValueError("client fixture: the marker fastapi must be provided")<block_end><try_stmt><block_start>app=marker.kwargs["app"]<block_end><except_stmt>KeyError<block_start><raise>ValueError("client fixture: keyword argument app must be provided in the marker")<block_end><if_stmt><not>isinstance(app FastAPI)<block_start><raise>ValueError("client fixture: app must be a FastAPI instance")<block_end>dependency_overrides=marker.kwargs.get("dependency_overrides")<if_stmt>dependency_overrides<block_start><if_stmt><not>isinstance(dependency_overrides dict)<block_start><raise>ValueError("client fixture: dependency_overrides must be a dictionary")<block_end>app.dependency_overrides=dependency_overrides<block_end>run_lifespan_events=marker.kwargs.get("run_lifespan_events" <true>)<if_stmt><not>isinstance(run_lifespan_events bool)<block_start><raise>ValueError("client fixture: run_lifespan_events must be a bool")<block_end>test_client_generator=httpx.AsyncClient(app=app base_url="http://app.io")<if_stmt>run_lifespan_events<block_start><async_keyword><with_stmt>LifespanManager(app)<block_start><async_keyword><with_stmt>test_client_generator<as>test_client<block_start><yield>test_client<block_end><block_end><block_end><else_stmt><block_start><async_keyword><with_stmt>test_client_generator<as>test_client<block_start><yield>test_client<block_end><block_end><block_end>@pytest.fixture<def_stmt>websocket_client request:pytest.FixtureRequest event_loop:asyncio.AbstractEventLoop <arrow>Generator[TestClient <none> <none>]<block_start>asyncio.set_event_loop(event_loop)<line_sep>marker=request.node.get_closest_marker("fastapi")<if_stmt>marker<is><none><block_start><raise>ValueError("client fixture: the marker fastapi must be provided")<block_end><try_stmt><block_start>app=marker.kwargs["app"]<block_end><except_stmt>KeyError<block_start><raise>ValueError("client fixture: keyword argument app must be provided in the marker")<block_end><if_stmt><not>isinstance(app FastAPI)<block_start><raise>ValueError("client fixture: app must be a FastAPI instance")<block_end>dependency_overrides=marker.kwargs.get("dependency_overrides")<if_stmt>dependency_overrides<block_start><if_stmt><not>isinstance(dependency_overrides dict)<block_start><raise>ValueError("client fixture: dependency_overrides must be a dictionary")<block_end>app.dependency_overrides=dependency_overrides<block_end><with_stmt>TestClient(app)<as>test_client<block_start><yield>test_client<block_end><block_end> |
<import_from_stmt>opendatatools.common RestAgent md5<import_from_stmt>progressbar ProgressBar<import_stmt>json<import_stmt>pandas<as>pd<import_stmt>io<import_stmt>hashlib<import_stmt>time<line_sep>index_map={'Barclay_Hedge_Fund_Index':'ghsndx' 'Convertible_Arbitrage_Index':'ghsca' 'Distressed_Securities_Index':'ghsds' 'Emerging_Markets_Index':'ghsem' 'Equity_Long_Bias_Index':'ghselb' 'Equity_Long_Short_Index':'ghsels' 'Equity_Market_Neutral_Index':'ghsemn' 'European_Equities_Index':'ghsee' 'Event_Driven_Index':'ghsed' 'Fixed_Income_Arbitrage_Index':'ghsfia' 'Fund_of_Funds_Index':'ghsfof' 'Global_Macro_Index':'ghsmc' 'Healthcare_&_Biotechnology_Index':'ghsbio' 'Merger_Arbitrage_Index':'ghsma' 'Multi_Strategy_Index':'ghsms' 'Pacific_Rim_Equities_Index':'ghspre' 'Technology_Index':'ghstec' }<class_stmt>SimuAgent(RestAgent)<block_start><def_stmt>__init__ self<block_start>RestAgent.__init__(self)<line_sep>self.user_info=<none><line_sep>self.df_fundlist=<none><line_sep>self.cookies=<none><block_end><def_stmt>login self username password<block_start>url='https://passport.simuwang.com/index.php?m=Passport&c=auth&a=login&type=login&name=%s&pass=%s&reme=1&rn=1'%(username password)<line_sep>self.add_headers({'Referer':'https://dc.simuwang.com/'})<line_sep>response=self.do_request(url)<if_stmt>response<is><none><block_start><return><none> '登录失败'<block_end>jsonobj=json.loads(response)<line_sep>suc=jsonobj['suc']<line_sep>msg=jsonobj['msg']<if_stmt>suc<ne>1<block_start><return><none> msg<block_end>self.cookies=self.get_cookies()<line_sep>self.user_info=jsonobj['data']<line_sep><return>self.user_info msg<block_end><def_stmt>prepare_cookies self url<block_start>response=self.do_request(url <none>)<if_stmt>response<is><not><none><block_start>cookies=self.get_cookies()<line_sep><return>cookies<block_end><else_stmt><block_start><return><none><block_end><block_end><def_stmt>_get_rz_token self time<block_start>mk=time<times>158995555893<line_sep>mtoken=md5(md5(str(mk)))+'.'+str(time)<line_sep><return>mtoken<block_end><def_stmt>_get_fund_list_page self page_no<block_start>url='https://dc.simuwang.com/ranking/get?page=%s&condition=fund_type:1,6,4,3,8,2;ret:9;rating_year:1;istiered:0;company_type:1;sort_name:profit_col2;sort_asc:desc;keyword:'%page_no<line_sep>response=self.do_request(url)<if_stmt>response<is><none><block_start><return><none> '获取数据失败' <none><block_end>jsonobj=json.loads(response)<line_sep>code=jsonobj['code']<line_sep>msg=jsonobj['msg']<if_stmt>code<ne>1000<block_start><return><none> msg <none><block_end>df=pd.DataFrame(jsonobj['data'])<line_sep>pageinfo=jsonobj['pager']<line_sep><return>df '' pageinfo<block_end><def_stmt>load_data self<block_start>page_no=1<line_sep>df_list=[]<line_sep>df,msg,pageinfo=self._get_fund_list_page(page_no)<if_stmt>df<is><none><block_start><return><none> msg<block_end>df_list.append(df)<line_sep>page_count=pageinfo['pagecount']<line_sep>process_bar=ProgressBar().start(max_value=page_count)<line_sep>page_no=page_no+1<while_stmt>page_no<le>page_count<block_start>df,msg,pageinfo=self._get_fund_list_page(page_no)<if_stmt>df<is><none><block_start><return><none> msg<block_end>df_list.append(df)<line_sep>process_bar.update(page_no)<line_sep>page_no=page_no+1<block_end>self.df_fundlist=pd.concat(df_list)<line_sep><return>self.df_fundlist ''<block_end><def_stmt>get_fund_list self<block_start><if_stmt>self.df_fundlist<is><none><block_start><return><none> '请先加载数据 load_data'<block_end><return>self.df_fundlist ''<block_end><def_stmt>_get_sign self url params<block_start>str=url<for_stmt>k,v params.items()<block_start>str=str+k+params[k]<block_end>sha1=hashlib.sha1()<line_sep>sha1.update(str.encode('utf8'))<line_sep>sign=sha1.hexdigest()<line_sep><return>sign<block_end><def_stmt>_get_token self fund_id<block_start>sign=self._get_sign('https://dc.simuwang.com/Api/getToken' {'id':fund_id})<line_sep>url='https://dc.simuwang.com/Api/getToken?id=%s&sign=%s'%(fund_id sign)<line_sep>self.add_headers({'Referer':'https://dc.simuwang.com/'})<line_sep>response=self.do_request(url)<if_stmt>response<is><none><block_start><return><none> '获取数据失败'<block_end>jsonobj=json.loads(response)<line_sep>code=jsonobj['code']<line_sep>msg=jsonobj['message']<if_stmt>code<ne>1000<block_start><return>code msg<block_end>self.cookies.update(self.get_cookies())<line_sep>salt=jsonobj['data']<line_sep>muid=self.user_info['userid']<line_sep>#str = 'id%smuid%spage%s%s' % (fund_id, muid, page_no, salt)
str='%s%s'%(fund_id salt)<line_sep>sha1=hashlib.sha1()<line_sep>sha1.update(str.encode('utf8'))<line_sep>token=sha1.hexdigest()<line_sep><return>token ''<block_end><def_stmt>_get_fund_nav_page self fund_id page_no<block_start>muid=self.user_info['userid']<line_sep>token,msg=self._get_token(fund_id)<if_stmt>token<is><none><block_start><return><none> '获取token失败: '+msg ''<block_end>url='https://dc.simuwang.com/fund/getNavList.html'<line_sep>self.add_headers({'Referer':'https://dc.simuwang.com/product/%s.html'%fund_id})<line_sep>data={'id':fund_id 'muid':muid 'page':str(page_no) 'token':token }<line_sep>response=self.do_request(url param=data cookies=self.cookies encoding="utf8")<if_stmt>response<is><none><block_start><return><none> '获取数据失败' ''<block_end>jsonobj=json.loads(response)<line_sep>code=jsonobj['code']<line_sep>msg=jsonobj['msg']<if_stmt>code<ne>1000<block_start><return>code msg ''<block_end>df=pd.DataFrame(jsonobj['data'])<line_sep>pageinfo=jsonobj['pager']<line_sep><return>df '' pageinfo<block_end><def_stmt>_bit_encrypt self str key<block_start>cryText=''<line_sep>keyLen=len(key)<line_sep>strLen=len(str)<for_stmt>i range(strLen)<block_start>k=i%keyLen<line_sep>cryText=cryText+chr(ord(str[i])-k)<block_end><return>cryText<block_end><def_stmt>_bit_encrypt2 self str key<block_start>cryText=''<line_sep>keyLen=len(key)<line_sep>strLen=len(str)<for_stmt>i range(strLen)<block_start>k=i%keyLen<line_sep>cryText=cryText+chr(ord(str[i])^ord(key[k]))<block_end><return>cryText<block_end><def_stmt>_decrypt_data self str func key# return self._bit_encrypt(str, 'cd0a8bee4c6b2f8a91ad5538dde2eb34')
# return self._bit_encrypt(str, '937ab03370497f2b4e8d0599ad25c44c')
# return self._bit_encrypt(str, '083975ce19392492bbccff21a52f1ace')
<block_start><return>func(str key)<block_end><def_stmt>_get_decrypt_info self fund_id<block_start>url='https://dc.simuwang.com/product/%s.html'%fund_id<line_sep>response=self.do_request(url param=<none> cookies=self.cookies encoding="utf8")<if_stmt>response<is><none><block_start><return><none> '获取数据失败' ''<block_end><if_stmt>"String.fromCharCode(str.charCodeAt(i) - k)"<in>response<block_start>decrypt_func=self._bit_encrypt<block_end><else_stmt><block_start>decrypt_func=self._bit_encrypt2<block_end><if_stmt>response.find("return xOrEncrypt(str, ")<g>0<block_start>tag="return xOrEncrypt(str, "<block_end><else_stmt><block_start>tag="return bitEncrypt(str, "<block_end>pos=response.index(tag)+len(tag)+1<line_sep>key=response[pos:pos+32]<line_sep><return>decrypt_func key<block_end><def_stmt>get_fund_nav self fund_id time_elapse=0<block_start><if_stmt>self.user_info<is><none><block_start><return><none> '请先登录'<block_end>page_no=1<line_sep>df_list=[]<line_sep>df,msg,pageinfo=self._get_fund_nav_page(fund_id page_no)<if_stmt>df<is><none><block_start><return><none> msg<block_end>df_list.append(df)<line_sep>page_count=pageinfo['pagecount']<line_sep>page_no=page_no+1<while_stmt>page_no<le>page_count<block_start>try_times=1<while_stmt>try_times<le>3<block_start>df,msg,pageinfo=self._get_fund_nav_page(fund_id page_no)<if_stmt>df<is><none><block_start><if_stmt>try_times<g>3<block_start><return><none> msg<block_end><else_stmt><block_start>try_times=try_times+1<line_sep><continue><block_end><block_end><else_stmt><block_start>df_list.append(df)<line_sep><break><block_end><block_end>page_no=page_no+1<if_stmt>time_elapse<g>0<block_start>time.sleep(time_elapse)<block_end><block_end>df_nav=pd.concat(df_list)<line_sep>df_nav.drop('c' axis=1 inplace=<true>)<line_sep>df_nav.rename(columns={'d':'date' 'n':'nav' 'cn':'accu_nav' 'cnw':'accu_nav_w'} inplace=<true>)<line_sep># 这个网站搞了太多的小坑
func,key=self._get_decrypt_info(fund_id)<line_sep>df_nav['nav']=df_nav['nav'].apply(<lambda>x:self._decrypt_data(x func key))<line_sep>df_nav['accu_nav']=df_nav['accu_nav'].apply(<lambda>x:self._decrypt_data(x func key))<line_sep>df_nav['accu_nav_w']=df_nav['accu_nav_w'].apply(<lambda>x:self._decrypt_data(x func key))<line_sep>#df_nav['nav'] = df_nav['nav'] - df_nav.index * 0.01 - 0.01
#df_nav['accu_nav'] = df_nav['accu_nav'].apply(lambda x: float(x) - 0.01)
#df_nav['accu_nav_w'] = df_nav['accu_nav_w'].apply(lambda x: float(x) - 0.02)
<return>df_nav ''<block_end><block_end><class_stmt>BarclayAgent(RestAgent)<block_start><def_stmt>__init__ self<block_start>RestAgent.__init__(self)<line_sep>self.add_headers({'Referer':'https://www.barclayhedge.com/research/indices/ghs/Equity_Long_Short_Index.html'})<line_sep>self.add_headers({'Content - Type':'application / x - www - form - urlencoded'})<block_end><def_stmt>get_data self index<block_start>prog_cod=index_map[index]<line_sep>url="https://www.barclayhedge.com/cgi-bin/barclay_stats/ghsndx.cgi"<line_sep>param={'dump':'excel' 'prog_cod':prog_cod }<line_sep>response=self.do_request(url param=param method='POST' type='binary')<if_stmt>response<is><not><none><block_start>excel=pd.ExcelFile(io.BytesIO(response))<line_sep>df=excel.parse('Sheet1').dropna(how='all').copy().reset_index().drop(0)<line_sep>df.columns=['year' 'Jan' 'Feb' 'Mar' 'Apr' 'May' 'Jun' 'Jul' 'Aug' 'Sep' 'Oct' 'Nov' 'Dec' 'YTD']<line_sep>df=df.set_index('year')<line_sep><return>df ''<block_end><return><none> "获取数据失败"<block_end><block_end> |
<import_stmt>networkx<as>nx<import_stmt>matplotlib.pyplot<as>plt<import_from_stmt>nxviz GeoPlot<line_sep>G=nx.read_gpickle("divvy.pkl")<line_sep>print(list(G.nodes(data=<true>))[0])<line_sep>G_new=G.copy()<for_stmt>n1,n2,d G.edges(data=<true>)<block_start><if_stmt>d["count"]<l>200<block_start>G_new.remove_edge(n1 n2)<block_end><block_end>g=GeoPlot(G_new node_lat="latitude" node_lon="longitude" node_color="dpcapacity" node_size=0.005 )<line_sep>g.draw()<line_sep>plt.show()<line_sep> |
"""
Example usage:
python -m smalst.experiments.smal_shape --zebra_dir='smalst/zebra_no_toys_wtex_1000_0' --num_epochs=100000 --save_epoch_freq=20 --name=smal_net_600 --save_training_imgs=True --num_images=20000 --do_validation=True
"""<import_from_future_stmt> absolute_import<import_from_future_stmt> division<import_from_future_stmt> print_function<import_from_stmt>absl app<import_from_stmt>absl flags<import_stmt>os.path<as>osp<import_stmt>numpy<as>np<import_stmt>torch<import_stmt>torchvision<import_from_stmt>torch.autograd Variable<import_stmt>scipy.io<as>sio<import_stmt>scipy<import_stmt>scipy.misc<import_from_stmt>collections OrderedDict<import_stmt>pickle<as>pkl<import_from_stmt>..data zebra<as>zebra_data<import_from_stmt>..utils visutil<import_from_stmt>..utils smal_vis<import_from_stmt>..utils image<as>image_utils<import_from_stmt>..nnutils train_utils<import_from_stmt>..nnutils loss_utils<import_from_stmt>..nnutils smal_mesh_net<import_from_stmt>..nnutils.nmr NeuralRenderer<import_from_stmt>..nnutils geom_utils<line_sep>flags.DEFINE_string('dataset' 'zebra' 'zebra')<line_sep># Weights:
flags.DEFINE_float('kp_loss_wt' 10. 'keypoint loss weight')<line_sep>flags.DEFINE_float('kp_2D_loss_wt' 10. 'loss weight for the 2D keypoints predicted by the network')<line_sep>flags.DEFINE_float('mask_loss_wt' 30. 'mask loss weight')<line_sep>flags.DEFINE_float('cam_loss_wt' 10000. 'weights to camera loss')<line_sep>flags.DEFINE_float('deform_reg_wt' 100. 'reg to deformation')<line_sep>flags.DEFINE_float('triangle_reg_wt' 100. 'weights to triangle smoothness prior')<line_sep>flags.DEFINE_float('vert2kp_loss_wt' .16 'reg to vertex assignment')<line_sep>flags.DEFINE_float('tex_loss_wt' 10. 'weights to tex loss')<line_sep>flags.DEFINE_boolean('grad_v_in_tex_loss' <false> '')<line_sep>flags.DEFINE_boolean('use_keypoints' <true> 'use keypoints loss')<line_sep>flags.DEFINE_boolean('use_mask' <true> 'use mask loss')<line_sep>flags.DEFINE_boolean('use_shape_reg' <false> 'use shape regularizers')<line_sep>flags.DEFINE_float('tex_map_loss_wt' 10. 'weights to tex map loss')<line_sep>flags.DEFINE_float('tex_dt_loss_wt' .5 'weights to tex dt loss')<line_sep>flags.DEFINE_float('mod_trans_loss_wt' 4000. 'weights for model translation loss')<line_sep>flags.DEFINE_float('mod_pose_loss_wt' 200000. 'weights for model pose loss')<line_sep>flags.DEFINE_float('betas_reg_wt' 100000. 'weights for betas prior loss')<line_sep>flags.DEFINE_float('delta_v_loss_wt' 100000. 'weights for model delta_v')<line_sep>flags.DEFINE_float('occ_loss_wt' 100. 'weights for occlusion loss')<line_sep>flags.DEFINE_boolean('infer_vert2kp' <false> 'estimate keypoints on the 3D model instead of using predefined values.')<line_sep>flags.DEFINE_boolean('no_delta_v' <false> 'set predicted deformations to zero')<line_sep>flags.DEFINE_boolean('use_gtpose' <false> 'if true uses gt pose for projection, but trans still gets trained.')<line_sep>flags.DEFINE_boolean('use_gttrans' <false> 'if true uses gt trans for projection, but pose still gets trained.')<line_sep>flags.DEFINE_boolean('use_gtcam' <false> 'if true uses gt cam for projection, but cam still gets trained.')<line_sep>flags.DEFINE_boolean('use_gtbetas' <false> 'if true uses gt betas for projection, but betas still gets trained.')<line_sep>flags.DEFINE_boolean('use_gtdeltav' <false> '')<line_sep>flags.DEFINE_boolean('use_gttexture' <false> '')<line_sep>flags.DEFINE_boolean('use_camera_loss' <true> 'if train with gt camera')<line_sep>flags.DEFINE_boolean('random_bkg' <false> 'if using a random background rather than black in the pred image')<line_sep>flags.DEFINE_boolean('use_perceptual_loss' <true> '')<line_sep>flags.DEFINE_boolean('uv_flow' <true> '')<line_sep>flags.DEFINE_float('uv_flow_loss_wt' 100000. 'weights for uv_flow loss')<line_sep>flags.DEFINE_boolean('use_pose_geodesic_loss' <true> '')<line_sep>flags.DEFINE_boolean('use_loss_on_whole_image' <false> 'if compose the predicted animal with the image background')<line_sep>flags.DEFINE_boolean('use_tex_dt' <true> 'if use loss (4) in the birds paper')<line_sep>flags.DEFINE_boolean('white_balance_for_texture_map' <false> '')<line_sep>flags.DEFINE_boolean('use_img_as_background' <false> 'if to use the input image as background for the optimization')<line_sep>flags.DEFINE_boolean('use_gtmask_for_background' <false> 'if to use the input image as background for the optimization')<line_sep>flags.DEFINE_boolean('use_per_image_rgb_bg' <false> 'if to compute per-imag rgb colors for background in optimization')<line_sep>opts=flags.FLAGS<line_sep>curr_path=osp.dirname(osp.abspath(__file__))<line_sep>cache_path=osp.join(curr_path '..' 'cachedir')<class_stmt>ShapeTrainer(train_utils.Trainer)<block_start><def_stmt>define_model self<block_start>opts=self.opts<line_sep>self.symmetric=opts.symmetric<line_sep>img_size=(opts.img_size opts.img_size)<line_sep>texture_mask_path='smalst/'+opts.dataset+'_data/texture_maps/my_smpl_00781_4_all_template_w_tex_uv_001_mask_small.png'<line_sep>self.texture_map_mask=torch.Tensor(scipy.misc.imread(texture_mask_path)/255.0).cuda(device=opts.gpu_id)<line_sep>tex_masks=<none><line_sep>data_path='smalst/smpl_models/my_smpl_data_00781_4_all.pkl'<line_sep>data=pkl.load(open(data_path))<line_sep>pca_var=data['eigenvalues'][:opts.num_betas]<line_sep>self.betas_prec=torch.Tensor(pca_var).cuda(device=opts.gpu_id).expand(opts.batch_size opts.num_betas)<line_sep>self.model=smal_mesh_net.MeshNet(img_size opts nz_feat=opts.nz_feat num_kps=opts.num_kps tex_masks=tex_masks)<if_stmt>opts.num_pretrain_epochs<g>0<block_start>self.load_network(self.model 'pred' opts.num_pretrain_epochs)<block_end>self.model=self.model.cuda(device=opts.gpu_id)<if_stmt><not>opts.infer_vert2kp<block_start>self.vert2kp=torch.Tensor(pkl.load(open('smalst/'+opts.dataset+'_data/verts2kp.pkl'))).cuda(device=opts.gpu_id)<block_end># Data structures to use for triangle priors.
edges2verts=self.model.edges2verts<line_sep># B x E x 4
edges2verts=np.tile(np.expand_dims(edges2verts 0) (opts.batch_size 1 1))<line_sep>self.edges2verts=Variable(torch.LongTensor(edges2verts).cuda(device=opts.gpu_id) requires_grad=<false>)<line_sep># For renderering.
faces=self.model.faces.view(1 -1 3)<line_sep>self.faces=faces.repeat(opts.batch_size 1 1)<line_sep>self.renderer=NeuralRenderer(opts.img_size opts.projection_type opts.norm_f opts.norm_z opts.norm_f0)<if_stmt>opts.texture<block_start>self.tex_renderer=NeuralRenderer(opts.img_size opts.projection_type opts.norm_f opts.norm_z opts.norm_f0)<line_sep># Only use ambient light for tex renderer
<if_stmt>opts.use_directional_light<block_start>self.tex_renderer.directional_light_only()<block_end><else_stmt><block_start>self.tex_renderer.ambient_light_only()<block_end><block_end># For visualization
self.vis_rend=smal_vis.VisRenderer(opts.img_size faces.data.cpu().numpy() opts.projection_type opts.norm_f opts.norm_z opts.norm_f0)<line_sep>self.background_imgs=<none><line_sep><return><block_end><def_stmt>init_dataset self<block_start>opts=self.opts<if_stmt>opts.dataset<eq>'zebra'<block_start>self.data_module=zebra_data<block_end><else_stmt><block_start>print('Unknown dataset %d!'%opts.dataset)<block_end>self.dataloader=self.data_module.data_loader(opts)<line_sep>self.resnet_transform=torchvision.transforms.Normalize(mean=[0.485 0.456 0.406] std=[0.229 0.224 0.225])<block_end><def_stmt>define_criterion self<block_start><if_stmt>opts.use_keypoints<block_start>self.projection_loss=loss_utils.kp_l2_loss<block_end><if_stmt>opts.use_mask<block_start>self.mask_loss_fn=loss_utils.mask_loss<block_end><if_stmt>opts.infer_vert2kp<block_start>self.entropy_loss=loss_utils.entropy_loss<block_end><if_stmt>self.opts.use_camera_loss<block_start>self.camera_loss=loss_utils.camera_loss<block_end><if_stmt>opts.use_smal_betas<block_start>self.betas_loss_fn=loss_utils.betas_loss<block_end>self.delta_v_loss_fn=loss_utils.delta_v_loss<if_stmt>self.opts.texture<block_start><if_stmt>self.opts.use_perceptual_loss<block_start><if_stmt><false><block_start>self.texture_loss=loss_utils.MSE_texture_loss<block_end><else_stmt><block_start>self.texture_loss=loss_utils.PerceptualTextureLoss()<block_end><block_end><else_stmt><block_start>self.texture_loss=loss_utils.texture_loss<block_end>self.texture_dt_loss_fn=loss_utils.texture_dt_loss<if_stmt>opts.texture_map<block_start>self.texture_map_loss=loss_utils.texture_map_loss<block_end><if_stmt>opts.uv_flow<block_start>self.uv_flow_loss=loss_utils.uv_flow_loss<block_end><block_end>self.model_trans_loss_fn=loss_utils.model_trans_loss<line_sep>self.model_pose_loss_fn=loss_utils.model_pose_loss<block_end><def_stmt>set_optimization_input self<block_start>opts=self.opts<line_sep>cams=np.zeros((self.scale_pred.shape[0] 3))<line_sep>cams[: 0]=self.scale_pred.data<line_sep>cams[: 1:]=128<line_sep>self.cams=Variable(torch.FloatTensor(cams).cuda(device=opts.gpu_id) requires_grad=<false>)<line_sep>self.model_trans=Variable(self.trans_pred.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><def_stmt>set_optimization_variables self<block_start>'''
Sets as optimization variables those obtained as prediction from the network
'''<line_sep>opts=self.opts<line_sep>cams=np.zeros((self.scale_pred.shape[0] 3))<line_sep>cams[: 0]=self.scale_pred.data<line_sep>cams[: 1:]=128<line_sep># Prediction is gt
self.cams=Variable(torch.FloatTensor(cams).cuda(device=opts.gpu_id) requires_grad=<false>)<line_sep>self.model_pose=Variable(self.pose_pred.cuda(device=opts.gpu_id) requires_grad=<false>)<line_sep>self.model_trans=Variable(self.trans_pred.cuda(device=opts.gpu_id) requires_grad=<false>)<line_sep>self.delta_v=Variable(self.delta_v.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><def_stmt>set_input self batch<block_start>opts=self.opts<line_sep># Image with annotations.
input_img_tensor=batch['img'].type(torch.FloatTensor)<for_stmt>b range(input_img_tensor.size(0))<block_start>input_img_tensor[b]=self.resnet_transform(input_img_tensor[b])<block_end>img_tensor=batch['img'].type(torch.FloatTensor)<line_sep>self.input_imgs=Variable(input_img_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<line_sep>self.imgs=Variable(img_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<line_sep>#if opts.use_mask and 'mask' in batch.keys():
<if_stmt>'mask'<in>batch.keys()<block_start>mask_tensor=batch['mask'].type(torch.FloatTensor)<line_sep>self.masks=Variable(mask_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><else_stmt><block_start>self.masks=<none><block_end><if_stmt>opts.use_keypoints<and>'kp'<in>batch.keys()<block_start>kp_tensor=batch['kp'].type(torch.FloatTensor)<line_sep>self.kps=Variable(kp_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><else_stmt><block_start>self.kps=<none><block_end>self.img_paths=batch['img_path']<if_stmt>'camera_params'<in>batch.keys()<block_start>cam_tensor=batch['camera_params'].type(torch.FloatTensor)<if_stmt>opts.use_norm_f_and_z<block_start>cam_tensor[: 0]=(cam_tensor[: 0]-opts.norm_f0)/opts.norm_f<block_end>self.cams=Variable(cam_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><else_stmt><block_start>self.cams=<none><line_sep>cam_c_tensor=batch['camera_params_c'].type(torch.FloatTensor)<line_sep>self.cams_center=Variable(cam_c_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><if_stmt>'model_trans'<in>batch.keys()<block_start>model_trans_tensor=batch['model_trans'].type(torch.FloatTensor)<if_stmt>opts.use_norm_f_and_z<block_start>model_trans_tensor[: 2]=model_trans_tensor[: 2]-opts.norm_z+1.<block_end>self.model_trans=Variable(model_trans_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><if_stmt>'model_pose'<in>batch.keys()<block_start>model_pose_tensor=batch['model_pose'].type(torch.FloatTensor)<line_sep>self.model_pose=Variable(model_pose_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><else_stmt><block_start>self.model_trans=<none><line_sep>self.model_pose=<none><block_end><if_stmt>'model_betas'<in>batch.keys()<block_start>model_betas_tensor=batch['model_betas'][: :self.opts.num_betas].type(torch.FloatTensor)<line_sep>self.model_betas=Variable(model_betas_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><else_stmt><block_start>self.model_betas=<none><block_end><if_stmt>'model_delta_v'<in>batch.keys()<block_start>model_delta_v_tensor=batch['model_delta_v'].type(torch.FloatTensor)<line_sep>self.model_delta_v=Variable(model_delta_v_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><else_stmt><block_start>self.model_delta_v=<none><block_end><if_stmt>opts.texture_map<block_start><assert_stmt>('texture_map'<in>batch.keys())<line_sep>texture_map_tensor=batch['texture_map'].type(torch.FloatTensor)<line_sep>self.texture_map=Variable(texture_map_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><else_stmt><block_start>self.texture_map=<none><block_end><if_stmt>'uv_flow'<in>batch.keys()<block_start>uv_flow_tensor=batch['uv_flow'].type(torch.FloatTensor).permute(0 3 1 2)<line_sep>self.uv_flow_gt=Variable(uv_flow_tensor.cuda(device=opts.gpu_id) requires_grad=<false>)<block_end><else_stmt><block_start>self.uv_flow_gt=<none><block_end># Compute barrier distance transform.
#if opts.use_mask and self.masks is not None:
<if_stmt>self.masks<is><not><none><block_start>mask_dts=np.stack([image_utils.compute_dt_barrier(m)<for>m batch['mask']])<line_sep>dt_tensor=torch.FloatTensor(mask_dts).cuda(device=opts.gpu_id)<line_sep># B x 1 x N x N
self.dts_barrier=Variable(dt_tensor requires_grad=<false>).unsqueeze(1)<block_end><block_end><def_stmt>forward self opts_scale=<none> opts_pose=<none> opts_trans=<none> opts_delta_v=<none><block_start>opts=self.opts<if_stmt>opts.use_double_input<block_start>masks=self.input_imgs<times>self.masks<block_end><else_stmt><block_start>masks=<none><block_end><if_stmt>opts.texture<block_start>pred_codes,self.textures=self.model.forward(self.input_imgs masks)<block_end><else_stmt><block_start>pred_codes=self.model.forward(self.input_imgs masks)<block_end>self.delta_v,self.scale_pred,self.trans_pred,self.pose_pred,self.betas_pred,self.kp_2D_pred=pred_codes<if_stmt>opts.fix_trans<block_start>self.trans_pred[: 2]=self.model_trans[: 2]<block_end><if_stmt>opts.use_gttrans<block_start>print('Using gt trans')<line_sep>self.trans_pred=self.model_trans<block_end><if_stmt>opts.use_gtpose<block_start>print('Using gt pose')<line_sep>self.pose_pred=self.model_pose<block_end><if_stmt>opts.use_gtcam<block_start>print('Using gt cam')<line_sep>self.scale_pred=self.cams[: 0 <none>]<block_end><if_stmt>opts.use_gtbetas<block_start>print('Using gt betas')<line_sep>self.betas_pred=self.model_betas<block_end><if_stmt>opts.use_gtdeltav<block_start>print('Using gt delta_v')<line_sep>self.delta_v=self.model_delta_v<block_end><if_stmt>self.cams<is><not><none># The camera center does not change; here we predicting flength
<block_start>self.cam_pred=torch.cat([self.scale_pred self.cams[: 1:]] 1)<block_end><else_stmt><block_start>self.cam_pred=torch.cat([self.scale_pred self.cams_center] 1)<block_end><if_stmt>opts.only_mean_sym<block_start>del_v=self.delta_v<block_end><else_stmt><block_start>del_v=self.model.symmetrize(self.delta_v)<block_end><if_stmt>opts.no_delta_v<block_start>del_v[:]=0<block_end><if_stmt>opts.use_smal_pose<block_start>self.pred_v=self.model.get_smal_verts(self.pose_pred self.betas_pred self.trans_pred del_v)<block_end><else_stmt># TODO
<block_start>self.mean_shape=self.model.get_mean_shape()<line_sep>self.pred_v=self.mean_shape+del_v+self.trans_pred<block_end># Compute keypoints.
<if_stmt>opts.infer_vert2kp<block_start>self.vert2kp=torch.nn.functional.softmax(self.model.vert2kp dim=1)<block_end>self.kp_verts=torch.matmul(self.vert2kp self.pred_v)<line_sep># Set projection camera
proj_cam=self.cam_pred<line_sep># Project keypoints
<if_stmt>opts.use_keypoints<block_start>self.kp_pred=self.renderer.project_points(self.kp_verts proj_cam)<block_end># Render mask.
self.mask_pred=self.renderer.forward(self.pred_v self.faces proj_cam)<if_stmt>opts.texture<block_start>self.texture_flow=self.textures<line_sep>self.textures=geom_utils.sample_textures(self.texture_flow self.imgs)<line_sep>tex_size=self.textures.size(2)<line_sep>self.textures=self.textures.unsqueeze(4).repeat(1 1 1 1 tex_size 1)<if_stmt>opts.use_gttexture<block_start>idx=0<import_from_stmt>..utils.obj2nmr obj2nmr_uvmap<line_sep>uv_map=obj2nmr_uvmap(self.model.ft self.model.vt tex_size=tex_size)<line_sep>uv_img=self.texture_map[idx : : :]<line_sep>uv_img=uv_img.permute(1 2 0)<line_sep>texture_t=sample_texture(uv_map uv_img)<line_sep>self.textures[0 : : : : :]=texture_t[0 : : : : :]<block_end><if_stmt>opts.grad_v_in_tex_loss<block_start>self.texture_pred=self.tex_renderer.forward(self.pred_v self.faces proj_cam.detach() textures=self.textures)<block_end><else_stmt><block_start>self.texture_pred=self.tex_renderer.forward(self.pred_v.detach() self.faces proj_cam.detach() textures=self.textures)<block_end><block_end><else_stmt><block_start>self.textures=<none><if_stmt>opts.save_training_imgs<and>opts.use_mask<and>self.masks<is><not><none><block_start>T=255<times>self.mask_pred.cpu().detach().numpy()[0 : :]<line_sep>scipy.misc.imsave(opts.name+'_mask_pred.png' T)<line_sep>T=255<times>self.masks.cpu().detach().numpy()[0 : : :]<line_sep>T=np.transpose(T (1 2 0))[: : 0]<line_sep>scipy.misc.imsave(opts.name+'_mask_gt.png' T)<block_end><block_end># Compute losses for this instance.
<if_stmt>self.opts.use_keypoints<and>self.kps<is><not><none><block_start>self.kp_loss=self.projection_loss(self.kp_pred self.kps)<block_end><if_stmt>self.opts.use_mask<and>self.masks<is><not><none><block_start>self.mask_loss=self.mask_loss_fn(self.mask_pred self.masks[: 0 : :])<block_end><if_stmt>self.opts.use_camera_loss<and>self.cams<is><not><none><block_start>self.cam_loss=self.camera_loss(self.cam_pred self.cams 0 self.opts.use_norm_f_and_z)<block_end><if_stmt>self.model_trans<is><not><none><block_start>self.mod_trans_loss=self.model_trans_loss_fn(self.trans_pred self.model_trans)<block_end><if_stmt>self.model_pose<is><not><none><block_start>self.mod_pose_loss=self.model_pose_loss_fn(self.pose_pred self.model_pose self.opts)<block_end><if_stmt>opts.texture<block_start><if_stmt>opts.use_loss_on_whole_image<block_start><if_stmt>self.background_imgs<is><none><block_start>print("SETTING BACKGROUND MODEL")<line_sep>self.background_imgs=np.zeros(self.imgs.shape)<line_sep>fg_mask=self.mask_pred.detach().cpu().numpy()<line_sep>I=self.imgs.detach().cpu().numpy()<line_sep>bg_mask=np.abs(fg_mask-1)<line_sep>rgb=np.zeros((3))<line_sep>n=np.sum(bg_mask)<for_stmt>c range(3)<block_start>I[: c : :]=I[: c : :]<times>bg_mask<line_sep>rgb[c]=np.sum(I[0 c : :])/n<block_end><if_stmt>self.background_model_top<is><not><none><block_start>N=128<for_stmt>c range(3)<block_start>self.background_imgs[: c :N :]=self.background_model_top[c]<line_sep>self.background_imgs[: c N: :]=self.background_model_bottom[c]<block_end><block_end><else_stmt># This is what we use for optimization
<block_start><if_stmt>opts.use_per_image_rgb_bg<block_start>self.background_imgs[: 0 : :]=rgb[0]<line_sep>self.background_imgs[: 1 : :]=rgb[1]<line_sep>self.background_imgs[: 2 : :]=rgb[2]<block_end><else_stmt><block_start>self.background_imgs[: 0 : :]=.6964<line_sep>self.background_imgs[: 1 : :]=.5806<line_sep>self.background_imgs[: 2 : :]=.4780<block_end># Verification experiment: replace with image
<if_stmt>opts.use_img_as_background<block_start>self.background_imgs[: 0 : :]=self.imgs.data[: 0 : :]<line_sep>self.background_imgs[: 1 : :]=self.imgs.data[: 1 : :]<line_sep>self.background_imgs[: 2 : :]=self.imgs.data[: 2 : :]<block_end><block_end>self.background_imgs=torch.Tensor(self.background_imgs).cuda(device=opts.gpu_id)<block_end><block_end><if_stmt>self.masks<is><not><none><block_start><if_stmt>opts.use_loss_on_whole_image<block_start>self.tex_loss=self.texture_loss(self.texture_pred self.imgs self.mask_pred <none> self.background_imgs)<block_end><else_stmt><block_start>self.tex_loss=self.texture_loss(self.texture_pred self.imgs self.mask_pred self.masks[: 0 : :])<block_end><if_stmt>opts.use_tex_dt<block_start>self.tex_dt_loss=self.texture_dt_loss_fn(self.texture_flow self.dts_barrier[: : : : 0])<block_end><block_end><else_stmt><block_start><if_stmt>opts.use_loss_on_whole_image<block_start>self.tex_loss=self.texture_loss(self.texture_pred self.imgs self.mask_pred <none> self.background_imgs)<block_end><else_stmt><block_start>self.tex_loss=self.texture_loss(self.texture_pred self.imgs self.mask_pred <none>)<block_end><block_end><if_stmt>opts.texture_map<and>self.texture_map<is><not><none><block_start>uv_flows=self.model.texture_predictor.uvimage_pred<line_sep>uv_flows=uv_flows.permute(0 2 3 1)<line_sep>uv_images=torch.nn.functional.grid_sample(self.imgs uv_flows)<line_sep>self.tex_map_loss=self.texture_map_loss(uv_images self.texture_map self.texture_map_mask self.opts)<block_end><if_stmt>opts.uv_flow<and>self.uv_flow_gt<is><not><none><block_start>uv_flows=self.model.texture_predictor.uvimage_pred<line_sep>self.uv_f_loss=self.uv_flow_loss(uv_flows self.uv_flow_gt)<block_end><block_end># Priors:
<if_stmt>opts.infer_vert2kp<block_start>self.vert2kp_loss=self.entropy_loss(self.vert2kp)<block_end><if_stmt>opts.use_smal_betas<block_start>self.betas_loss=self.betas_loss_fn(self.betas_pred self.model_betas self.betas_prec)<block_end><if_stmt>self.model_delta_v<is><not><none><block_start>self.delta_v_loss=self.delta_v_loss_fn(self.delta_v self.model_delta_v)<block_end># Finally sum up the loss.
# Instance loss:
<if_stmt>opts.use_keypoints<and>self.kps<is><not><none><block_start>self.total_loss=opts.kp_loss_wt<times>self.kp_loss<if_stmt>opts.use_mask<and>self.masks<is><not><none><block_start>self.total_loss<augadd>opts.mask_loss_wt<times>self.mask_loss<block_end><block_end><else_stmt><block_start><if_stmt>opts.use_mask<and>self.masks<is><not><none><block_start>self.total_loss=opts.mask_loss_wt<times>self.mask_loss<block_end><else_stmt><block_start>self.total_loss=0<block_end><block_end><if_stmt><not>opts.use_gtcam<and>self.opts.use_camera_loss<and>self.cams<is><not><none><block_start>self.total_loss<augadd>opts.cam_loss_wt<times>self.cam_loss<block_end><if_stmt>opts.texture<block_start>self.total_loss<augadd>opts.tex_loss_wt<times>self.tex_loss<block_end><if_stmt>opts.texture_map<and>self.texture_map<is><not><none><block_start>self.total_loss<augadd>opts.tex_map_loss_wt<times>self.tex_map_loss<block_end><if_stmt>opts.uv_flow<and>self.uv_flow_gt<is><not><none><block_start>self.total_loss<augadd>opts.uv_flow_loss_wt<times>self.uv_f_loss<block_end><if_stmt>self.model_trans<is><not><none><block_start><if_stmt><not>opts.use_gttrans<block_start>self.total_loss<augadd>opts.mod_trans_loss_wt<times>self.mod_trans_loss<block_end><block_end><if_stmt>self.model_pose<is><not><none><block_start><if_stmt><not>opts.use_gtpose<block_start>self.total_loss<augadd>opts.mod_pose_loss_wt<times>self.mod_pose_loss<block_end><block_end><if_stmt>self.model_delta_v<is><not><none><block_start>self.total_loss<augadd>opts.delta_v_loss_wt<times>self.delta_v_loss<block_end># Priors:
<if_stmt>opts.infer_vert2kp<block_start>self.total_loss<augadd>opts.vert2kp_loss_wt<times>self.vert2kp_loss<block_end><if_stmt>opts.use_smal_betas<block_start>self.total_loss<augadd>opts.betas_reg_wt<times>self.betas_loss<block_end><if_stmt>opts.texture<and>self.masks<is><not><none><and>opts.use_tex_dt<block_start>self.total_loss<augadd>opts.tex_dt_loss_wt<times>self.tex_dt_loss<block_end><block_end><def_stmt>get_current_visuals self<block_start>vis_dict={}<try_stmt><block_start>mask_concat=torch.cat([self.masks[: 0 : :] self.mask_pred] 2)<block_end><except_stmt><block_start><import_stmt>pdb<line_sep>pdb.set_trace()<block_end><if_stmt>self.opts.texture# B x 2 x H x W
<block_start>uv_flows=self.model.texture_predictor.uvimage_pred<line_sep># B x H x W x 2
uv_flows=uv_flows.permute(0 2 3 1)<line_sep>uv_images=torch.nn.functional.grid_sample(self.imgs uv_flows)<block_end>num_show=min(2 self.opts.batch_size)<line_sep>show_uv_imgs=[]<line_sep>show_uv_flows=[]<for_stmt>i range(num_show)<block_start>input_img=smal_vis.kp2im(self.kps[i].data self.imgs[i].data)<line_sep>pred_kp_img=smal_vis.kp2im(self.kp_pred[i].data self.imgs[i].data)<line_sep>masks=smal_vis.tensor2mask(mask_concat[i].data)<if_stmt>self.opts.texture<block_start>texture_here=self.textures[i]<block_end><else_stmt><block_start>texture_here=<none><block_end>rend_predcam=self.vis_rend(self.pred_v[i] self.cam_pred[i] texture=texture_here)<line_sep># Render from front & back:
rend_frontal=self.vis_rend.diff_vp(self.pred_v[i] self.cam_pred[i] texture=texture_here kp_verts=self.kp_verts[i])<line_sep>rend_top=self.vis_rend.diff_vp(self.pred_v[i] self.cam_pred[i] axis=[0 1 0] texture=texture_here kp_verts=self.kp_verts[i])<line_sep>diff_rends=np.hstack((rend_frontal rend_top))<if_stmt>self.opts.texture<block_start>uv_img=smal_vis.tensor2im(uv_images[i].data)<line_sep>show_uv_imgs.append(uv_img)<line_sep>uv_flow=smal_vis.visflow(uv_flows[i].data)<line_sep>show_uv_flows.append(uv_flow)<line_sep>tex_img=smal_vis.tensor2im(self.texture_pred[i].data)<line_sep>imgs=np.hstack((input_img pred_kp_img tex_img))<block_end><else_stmt><block_start>imgs=np.hstack((input_img pred_kp_img))<block_end>rend_gtcam=self.vis_rend(self.pred_v[i] self.cams[i] texture=texture_here)<line_sep>rends=np.hstack((diff_rends rend_predcam rend_gtcam))<line_sep>vis_dict['%d'%i]=np.hstack((imgs rends masks))<line_sep>vis_dict['masked_img %d'%i]=smal_vis.tensor2im((self.imgs[i]<times>self.masks[i]).data)<block_end><if_stmt>self.opts.texture<block_start>vis_dict['uv_images']=np.hstack(show_uv_imgs)<line_sep>vis_dict['uv_flow_vis']=np.hstack(show_uv_flows)<block_end><return>vis_dict<block_end><def_stmt>get_current_points self<block_start><return>{'mean_shape':visutil.tensor2verts(self.mean_shape.data) 'verts':visutil.tensor2verts(self.pred_v.data) }<block_end><def_stmt>get_current_scalars self<block_start>sc_dict=OrderedDict([('smoothed_total_loss' self.smoothed_total_loss) ('total_loss' self.total_loss.item()) ])<if_stmt>self.opts.use_smal_betas<block_start>sc_dict['betas_reg']=self.betas_loss.item()<block_end><if_stmt>self.opts.use_mask<and>self.masks<is><not><none><block_start>sc_dict['mask_loss']=self.mask_loss.item()<block_end><if_stmt>self.opts.use_keypoints<and>self.kps<is><not><none><block_start>sc_dict['kp_loss']=self.kp_loss.item()<block_end><if_stmt>self.opts.use_camera_loss<and>self.cams<is><not><none><block_start>sc_dict['cam_loss']=self.cam_loss.item()<block_end><if_stmt>self.opts.texture<block_start>sc_dict['tex_loss']=self.tex_loss.item()<block_end><if_stmt>self.opts.texture_map<and>self.opts.use_tex_dt<and>self.masks<is><not><none><block_start>sc_dict['tex_dt_loss']=self.tex_dt_loss.item()<block_end><if_stmt>self.opts.uv_flow<and>self.uv_flow_gt<is><not><none><block_start>sc_dict['uv_flow_loss']=self.uv_f_loss.item()<block_end><if_stmt>self.opts.texture_map<and>self.texture_map<is><not><none><block_start>sc_dict['tex_map_loss']=self.tex_map_loss.item()<block_end><if_stmt>self.model_trans<is><not><none><block_start>sc_dict['model_trans_loss']=self.mod_trans_loss.item()<block_end><if_stmt>self.model_pose<is><not><none><block_start>sc_dict['model_pose_loss']=self.mod_pose_loss.item()<block_end><if_stmt>opts.infer_vert2kp<block_start>sc_dict['vert2kp_loss']=self.vert2kp_loss.item()<block_end><if_stmt>self.model_delta_v<is><not><none><block_start>sc_dict['model_delta_v_loss']=self.delta_v_loss.item()<block_end><return>sc_dict<block_end><block_end><def_stmt>main _<block_start>torch.manual_seed(0)<line_sep>np.random.seed(0)<line_sep>trainer=ShapeTrainer(opts)<line_sep>trainer.init_training()<line_sep>trainer.train()<block_end><if_stmt>__name__<eq>'__main__'<block_start>app.run(main)<block_end> |
<class_stmt>_Manager(type)<block_start>""" Singletone for cProfile manager """<line_sep>_inst={}<def_stmt>__call__ cls *args **kwargs<block_start><if_stmt>cls<not><in>cls._inst<block_start>cls._inst[cls]=super(_Manager cls).__call__(*args **kwargs)<block_end><return>cls._inst[cls]<block_end><block_end><class_stmt>ProfileManager(metaclass=_Manager)<block_start><def_stmt>__init__ self<block_start>self._profiles=list()<block_end><def_stmt>clear self<block_start>self._profiles.clear()<block_end><def_stmt>add self profile<block_start>self._profiles.append(profile)<block_end><def_stmt>profiles self<block_start><return>self._profiles<block_end>@property<def_stmt>count self<block_start><return>len(self._profiles)<block_end><block_end> |
<import_stmt>sys<import_stmt>os<line_sep>base_dir=os.path.join(os.path.dirname(os.path.abspath(__file__)) '../../')<line_sep>sys.path.append(base_dir)<line_sep>sys.path.append(os.path.join(base_dir 'rl'))<import_stmt>numpy<as>np<import_stmt>argparse<import_stmt>torch<import_stmt>torch.nn<as>nn<import_stmt>torch.nn.functional<as>F<import_stmt>torch.optim<as>optim<import_stmt>gym<line_sep>gym.logger.set_level(40)<import_stmt>environments<import_from_stmt>rl.train.evaluation render render_full<import_from_stmt>rl.train.arguments get_parser<import_from_stmt>a2c_ppo_acktr algo utils<import_from_stmt>a2c_ppo_acktr.envs make_vec_envs make_env<import_from_stmt>a2c_ppo_acktr.model Policy<line_sep>parser=get_parser()<line_sep>parser.add_argument('--model-path' type=str required=<true>)<line_sep>args=parser.parse_args()<if_stmt><not>os.path.isfile(args.model_path)<block_start>print_error('Model file does not exist')<block_end>torch.manual_seed(0)<line_sep>torch.set_num_threads(1)<line_sep>device=torch.device('cpu')<line_sep>render_env=gym.make(args.env_name args=args)<line_sep>render_env.seed(0)<line_sep>envs=make_vec_envs(args.env_name 0 4 0.995 <none> device <false> args=args)<line_sep>actor_critic=Policy(envs.observation_space.shape envs.action_space base_kwargs={'recurrent':<false>})<line_sep>actor_critic.to(device)<line_sep>ob_rms=utils.get_vec_normalize(envs).ob_rms<line_sep>actor_critic,ob_rms=torch.load(args.model_path)<line_sep>actor_critic.eval()<line_sep>envs.close()<line_sep>render_full(render_env actor_critic ob_rms deterministic=<true> repeat=<true>)<line_sep> |
<import_from_stmt>.kfold PurgedKFold CPKFold generate_signals<import_from_stmt>.score cv_score<import_from_stmt>.pipeline Pipeline<import_from_stmt>.hyper clf_hyper_fit<import_from_stmt>.distribution LogUniformGen log_uniform<import_from_stmt>.utils evaluate<line_sep> |
<import_stmt>json<import_stmt>os<import_from_stmt>eg config<import_from_stmt>eg substitute<import_from_stmt>eg util<import_from_stmt>mock Mock<import_from_stmt>mock patch<line_sep>PATH_UNSQUEEZED_FILE=os.path.join('test' 'assets' 'pwd_unsqueezed.md')<line_sep>PATH_SQUEEZED_FILE=os.path.join('test' 'assets' 'pwd_squeezed.md')<def_stmt>_create_config examples_dir=<none> custom_dir=<none> color_config=<none> use_color=<true> pager_cmd=<none> editor_cmd=<none> squeeze=<false> subs=<none><block_start>"""
Create a config.Config object with default values for expediency in
testing.
"""<line_sep><return>config.Config(examples_dir=examples_dir custom_dir=custom_dir color_config=color_config use_color=use_color pager_cmd=pager_cmd editor_cmd=editor_cmd squeeze=squeeze subs=subs)<block_end>@patch('os.walk')<def_stmt>test_get_file_paths_for_program_with_single mock_walk<block_start>program='cp'<line_sep>examples_dir='/Users/tyrion'<line_sep>program_file=program+util.EXAMPLE_FILE_SUFFIX<line_sep>expected=['/Users/tyrion/cp.md']<line_sep>mock_walk.return_value=[[examples_dir [] [program_file 'cp.txt' 'other_file.md']] ]<line_sep>actual=util.get_file_paths_for_program(program examples_dir)<assert_stmt>actual<eq>expected<line_sep>mock_walk.assert_called_once_with(examples_dir)<block_end>@patch('os.walk')<def_stmt>test_get_file_paths_for_program_with_nested mock_walk<block_start>program='cp'<line_sep>examples_dir='/Users/tyrion'<line_sep>program_file='cp.md'<line_sep>mock_walk.return_value=[[examples_dir ['dirA' 'dirB'] [program_file 'cp.txt' 'other_file.md'] ] [examples_dir+'/dirA' ['dirA-child'] [program_file 'bad.md'] ] [examples_dir+'/dirA/dirA-child' [] ['bad.md' program_file 'wtf.md'] ] [examples_dir+'/dirB' [] ['foo.md' program_file] ] ]<line_sep>expected=['/Users/tyrion/cp.md' '/Users/tyrion/dirA/cp.md' '/Users/tyrion/dirA/dirA-child/cp.md' '/Users/tyrion/dirB/cp.md' ]<line_sep>actual=util.get_file_paths_for_program(program examples_dir)<assert_stmt>actual<eq>expected<line_sep>mock_walk.assert_called_once_with(examples_dir)<block_end>@patch('os.walk')<def_stmt>test_get_file_paths_for_program_with_none mock_walk<block_start>expected=[]<line_sep>mock_walk.return_value=[]<line_sep>actual=util.get_file_paths_for_program('cp' '/Users/tyrion')<assert_stmt>actual<eq>expected<line_sep>mock_walk.assert_called_once_with('/Users/tyrion')<block_end>@patch('os.walk')<def_stmt>test_get_file_paths_for_program_with_no_dir mock_walk<block_start><assert_stmt>util.get_file_paths_for_program('cp' <none>)<eq>[]<block_end>@patch('eg.util.page_string')@patch('eg.util.get_formatted_contents')@patch('eg.util.get_contents_from_files')@patch('eg.util.get_resolved_program')<def_stmt>test_handle_program_no_entries mock_resolve_program mock_get_contents mock_format mock_page_string <block_start>"""
We should do the right thing if there are no entries for a given program.
"""<line_sep>program='cp'<line_sep>test_config=_create_config()<line_sep>mock_resolve_program.return_value=program<line_sep>util.handle_program(program test_config)<line_sep>mock_resolve_program.assert_called_once_with(program test_config)<line_sep># We should have aborted and not called any of the
# other methods.
<assert_stmt>mock_get_contents.call_count<eq>0<assert_stmt>mock_format.call_count<eq>0<assert_stmt>mock_page_string.call_count<eq>0<block_end>@patch('eg.util.get_resolved_program')@patch('eg.util.get_contents_from_files')@patch('eg.util.get_file_paths_for_program')@patch('eg.util.get_formatted_contents')@patch('eg.util.page_string')<def_stmt>test_handle_program_finds_paths_and_calls_open_pager_no_alias mock_page mock_format mock_get_paths mock_get_contents mock_resolve <block_start>"""
If there are entries for the program, handle_program needs to get the
paths, get the contents, format the contents, and page the resulting
string.
"""<line_sep>program='mv'<line_sep>examples_dir='test-eg-dir'<line_sep>custom_dir='test-custom-dir'<line_sep>color_config=<none><line_sep>use_color=<false><line_sep>pager_cmd='foo bar'<line_sep>squeeze=<false><line_sep>subs=['foo' 'bar']<line_sep>file_contents='I am the contents of mv.md.'<line_sep>formatted_contents='and I am the formatted contents of mv.md.'<line_sep>test_config=_create_config(examples_dir=examples_dir custom_dir=custom_dir color_config=color_config use_color=use_color pager_cmd=pager_cmd squeeze=squeeze subs=subs)<line_sep>default_paths=['test-eg-dir/mv.md' 'test-eg-dir/foo/mv.md']<line_sep>custom_paths=['test-custom-dir/mv.md' 'test-custom-dir/bar.md']<def_stmt>return_correct_path *args **kwargs<block_start>program_param=args[0]<line_sep>dir_param=args[1]<if_stmt>program_param<ne>program<block_start><raise>NameError('expected '+program+', got '+program_param)<block_end><if_stmt>dir_param<eq>examples_dir<block_start><return>default_paths<block_end><elif_stmt>dir_param<eq>custom_dir<block_start><return>custom_paths<block_end><else_stmt><block_start><raise>NameError('got '+dir_param+', expected '+examples_dir+' or '+custom_dir)<block_end><block_end>mock_format.return_value=formatted_contents<line_sep>mock_get_paths.side_effect=return_correct_path<line_sep>mock_get_contents.return_value=file_contents<line_sep>mock_resolve.return_value=program<line_sep>util.handle_program(program test_config)<line_sep>mock_resolve.assert_called_once_with(program test_config)<line_sep>mock_get_paths.assert_any_call(program examples_dir)<line_sep>mock_get_paths.assert_any_call(program custom_dir )<line_sep>mock_get_contents.assert_called_once_with(custom_paths[0] custom_paths[1] default_paths[0] default_paths[1] )<line_sep>mock_format.assert_called_once_with(file_contents use_color=test_config.use_color color_config=test_config.color_config squeeze=test_config.squeeze subs=test_config.subs)<line_sep>mock_page.assert_called_once_with(formatted_contents test_config.pager_cmd)<block_end>@patch('eg.util.get_resolved_program')@patch('eg.util.get_contents_from_files')@patch('eg.util.get_file_paths_for_program')@patch('eg.util.get_formatted_contents')@patch('eg.util.page_string')<def_stmt>test_handle_program_finds_paths_and_calls_open_pager_with_alias mock_page mock_format mock_get_paths mock_get_contents mock_resolve <block_start>"""
If there are entries for the program, handle_program needs to get the
paths, get the contents, format the contents, and page the resulting
string.
"""<line_sep>alias_for_program='link'<line_sep>resolved_program='ln'<line_sep>examples_dir='test-eg-dir'<line_sep>custom_dir='test-custom-dir'<line_sep>color_config=<none><line_sep>use_color=<false><line_sep>pager_cmd='foo bar'<line_sep>squeeze=<false><line_sep>subs=['foo' 'bar']<line_sep>file_contents='I am the contents of ln.md.'<line_sep>formatted_contents='and I am the formatted contents of ln.md.'<line_sep>test_config=_create_config(examples_dir=examples_dir custom_dir=custom_dir color_config=color_config use_color=use_color pager_cmd=pager_cmd squeeze=squeeze subs=subs)<line_sep>default_paths=['test-eg-dir/ln.md']<line_sep>custom_paths=['test-custom-dir/ln.md']<def_stmt>return_correct_path *args **kwargs<block_start>program_param=args[0]<line_sep>dir_param=args[1]<if_stmt>program_param<ne>resolved_program<block_start><raise>NameError('expected '+resolved_program+', got '+program_param)<block_end><if_stmt>dir_param<eq>examples_dir<block_start><return>default_paths<block_end><elif_stmt>dir_param<eq>custom_dir<block_start><return>custom_paths<block_end><else_stmt><block_start><raise>NameError('got '+dir_param+', expected '+examples_dir+' or '+custom_dir)<block_end><block_end>mock_format.return_value=formatted_contents<line_sep>mock_get_paths.side_effect=return_correct_path<line_sep>mock_get_contents.return_value=file_contents<line_sep>mock_resolve.return_value=resolved_program<line_sep>util.handle_program(alias_for_program test_config)<line_sep>mock_resolve.assert_called_once_with(alias_for_program test_config)<line_sep>mock_get_paths.assert_any_call(resolved_program examples_dir)<line_sep>mock_get_paths.assert_any_call(resolved_program custom_dir )<line_sep>mock_get_contents.assert_called_once_with(custom_paths[0] default_paths[0])<line_sep>mock_format.assert_called_once_with(file_contents use_color=test_config.use_color color_config=test_config.color_config squeeze=test_config.squeeze subs=test_config.subs)<line_sep>mock_page.assert_called_once_with(formatted_contents test_config.pager_cmd)<block_end><def_stmt>test_get_list_of_all_supported_commands tmpdir<block_start>dir_example=tmpdir.mkdir('examples')<line_sep>dir_custom=tmpdir.mkdir('custom')<line_sep>config=_create_config(examples_dir=str(dir_example) custom_dir=str(dir_custom) )<line_sep>expected=['a-only-default' 'b-both *' 'c-only-custom +' 'd-only-custom-nested +' 'e-only-default-nested' 'f-default-custom-nested' 'g-both-different-levels *' 't-a-only-default-alias -> a-only-default' 'u-b-both-alias -> b-both *' 'v-c-only-custom-alias -> c-only-custom +']<line_sep>aliases={'t-a-only-default-alias':'a-only-default' 'u-b-both-alias':'b-both' 'v-c-only-custom-alias':'c-only-custom'}<line_sep># Make the directory structure we expect.
dir_example_nested=dir_example.mkdir('default-nested')<line_sep>dir_custom_nested=dir_custom.mkdir('custom-nested')<line_sep>dir_example.join('a-only-default.md').write('foo')<line_sep>dir_example.join('b-both.md').write('foo')<line_sep>dir_custom.join('b-both.md').write('foo')<line_sep>dir_custom.join('c-only-custom.md').write('foo')<line_sep>dir_custom_nested.join('d-only-custom-nested.md').write('foo')<line_sep>dir_example_nested.join('e-only-default-nested.md').write('foo')<line_sep>dir_example_nested.join('f-default-custom-nested.md').write('foo')<line_sep>dir_example.join('g-both-different-levels.md').write('foo')<line_sep>dir_custom_nested.join('g-both-different-levels.md').write('foo')<line_sep># Use the 'with' context manager rather than the @decorator, because the
# tmpdir fixture doesn't play nice with the decorator.
<with_stmt>patch('eg.util.get_alias_dict')<as>mock_get_alias<block_start>mock_get_alias.return_value=aliases<line_sep>actual=util.get_list_of_all_supported_commands(config)<assert_stmt>actual<eq>expected<line_sep>mock_get_alias.assert_called_once_with(config)<block_end><block_end><def_stmt>test_list_supported_programs_fails_gracefully_if_no_dirs <block_start>test_config=_create_config()<line_sep>actual=util.get_list_of_all_supported_commands(test_config)<line_sep>target=[]<assert_stmt>actual<eq>target<block_end><def_stmt>test_calls_pipepager_if_not_less <block_start>"""
We're special casing less a bit, as it is the default value, so if a custom
command has been set that is NOT less, we should call pipepager straight
away.
"""<line_sep>_helper_assert_about_pager('page me plz' 'cat' <false>)<block_end><def_stmt>test_calls_fallback_pager_if_none <block_start>"""
If pager_cmd is None, we should just use the fallback pager.
"""<line_sep>_helper_assert_about_pager('page me plz' <none> <true>)<block_end><def_stmt>test_calls_pipepager_if_less <block_start>"""
We should call pipepager if we ask to use less and less is installed on the
machine.
"""<line_sep>_helper_assert_about_pager('a fancy value to page' 'less -R' <false>)<block_end><def_stmt>test_calls_fallback_if_cmd_is_flag_string <block_start>"""
We are using a flag string to indicate if we should use the fallback pager.
"""<line_sep>_helper_assert_about_pager('page via fallback' util.FLAG_FALLBACK <true>)<block_end>@patch('pydoc.pager')@patch('pydoc.pipepager')<def_stmt>_helper_assert_about_pager str_to_page pager_cmd use_fallback pipepager default_pager <block_start>"""
Help with asserting about pager.
str_to_page: what you're paging
pager_cmd: the string you're passing to pipepager (or None)
use_default: false if we should actually use pydoc.pipepager, true if we
instead are going to fallback to pydoc.pager
"""<line_sep>util.page_string(str_to_page pager_cmd)<if_stmt>use_fallback<block_start>default_pager.assert_called_once_with(str_to_page)<assert_stmt>pipepager.call_count<eq>0<block_end><else_stmt><block_start><assert_stmt>default_pager.call_count<eq>0<line_sep>pipepager.assert_called_once_with(str_to_page cmd=pager_cmd)<block_end><block_end>@patch('eg.util.pydoc.pipepager' side_effect=KeyboardInterrupt)<def_stmt>test_page_string_excepts_keyboard_interrupt_if_not_less pipepager_mock<block_start>"""
Do not fail when user hits ctrl-c while in pager.
"""<try_stmt><block_start>util.page_string('page me plz' 'cat')<block_end><except_stmt>KeyboardInterrupt<block_start><raise>AssertionError('Should not have got this far')<block_end>pipepager_mock.assert_called_once_with('page me plz' cmd='cat')<block_end>@patch('eg.util.pydoc.pager' side_effect=KeyboardInterrupt)<def_stmt>test_page_string_excepts_keyboard_interrupt_if_none pager_mock<block_start>"""
Do not fail when user hits ctrl-c while in pipepager.
"""<try_stmt><block_start>util.page_string('page me plz' <none>)<block_end><except_stmt>KeyboardInterrupt<block_start><raise>AssertionError('Should not have got this far')<block_end>pager_mock.assert_called_once_with('page me plz')<block_end><def_stmt>test_get_contents_from_files_handles_none <block_start>"""
Empty string if no files.
"""<line_sep>_helper_assert_file_contents([] '')<block_end><def_stmt>test_get_contents_from_files_handles_one <block_start>file_infos=[{'path':'test/path' 'contents':'contents of file'}]<line_sep>combined_contents='contents of file'<line_sep>_helper_assert_file_contents(file_infos combined_contents)<block_end><def_stmt>test_get_contents_from_files_handles_multiple <block_start>file_infos=[{'path':'path/1' 'contents':'foo\n'} {'path':'path/2/foo' 'contents':'bar\n'} {'path':'another/path' 'contents':'baz'}]<line_sep>combined_contents='foo\nbar\nbaz'<line_sep>_helper_assert_file_contents(file_infos combined_contents)<block_end>@patch('eg.util._get_contents_of_file')<def_stmt>_helper_assert_file_contents file_infos target_contents get_contents_mock <block_start>"""
Helper method to assert things about the get_contents_from_files method.
Does not actually hit the disk.
file_infos: array of { path, contents } dicts representing files. Array so
that we can assert proper order calling
target_contents: the final combined contents that should be returned by the
get_contents_from_files method.
"""<line_sep># This method will be used by the mock framework to return the right file
# contents based on the file name.
<def_stmt>return_file_contents *args **kwargs<block_start><for_stmt>file_info file_infos<block_start><if_stmt>file_info['path']<eq>args[0]<block_start><return>file_info['contents']<block_end><block_end><raise>TypeError('did not find path in test obj')<block_end>get_contents_mock.side_effect=return_file_contents<line_sep>paths=[el['path']<for>el file_infos]<line_sep>actual=util.get_contents_from_files(*paths)<assert_stmt>actual<eq>target_contents<block_end>@patch('eg.util.get_colorized_contents')@patch('eg.util.get_squeezed_contents')@patch('eg.util.get_substituted_contents')<def_stmt>_helper_assert_formatted_contents starting_contents use_color color_config squeeze subs colorized_contents squeezed_contents subbed_contents formatted_result sub_method squeeze_method color_method <block_start>"""
Helper method to assist in asserting things about the
get_formatted_contents method.
starting_contents: the starting string that we are working with
use_color: True if we should use color
color_config: the color config to be passed to get_colorized_contents
squeeze: True if we should squeeze
subs: the list of Substitutions that we should pass to
get_substituted_contents
colored_contents: the result of get_colorized_contents
squeezed_contents: the result of get_squeezed_contents
subbed_contents: the result of subbed_contents
formatted_result: the final, formatted string that should be returned
"""<line_sep>sub_method.return_value=subbed_contents<line_sep>squeeze_method.return_value=squeezed_contents<line_sep>color_method.return_value=colorized_contents<line_sep>actual=util.get_formatted_contents(starting_contents use_color color_config squeeze subs)<line_sep># We'll update the contents as they get formatted to make sure
# we pass the right thing to the various methods.
contents_thus_far=starting_contents<if_stmt>use_color<block_start>color_method.assert_called_once_with(contents_thus_far color_config)<line_sep>contents_thus_far=colorized_contents<block_end><else_stmt><block_start><assert_stmt>color_method.call_count<eq>0<block_end><if_stmt>squeeze<block_start>squeeze_method.assert_called_once_with(contents_thus_far)<line_sep>contents_thus_far=squeezed_contents<block_end><else_stmt><block_start><assert_stmt>squeeze_method.call_count<eq>0<block_end><if_stmt>subs<block_start>sub_method.assert_called_once_with(contents_thus_far subs)<line_sep>contents_thus_far=subbed_contents<block_end><else_stmt><block_start><assert_stmt>sub_method.call_count<eq>0<block_end><assert_stmt>actual<eq>formatted_result<block_end><def_stmt>test_get_formatted_contents_does_not_format_methods_if_all_falsey <block_start>"""
We should invoke none of the formatter methods if the flags are false and
subs is not truthy.
"""<line_sep>starting_contents='this is where we start'<line_sep>_helper_assert_formatted_contents(starting_contents <false> 'some color config' <false> <none> 'this was colored' 'this was squeezed' 'these contents were subbed' starting_contents)<block_end><def_stmt>test_get_formatted_contents_calls_colorize_if_use_color <block_start>"""
Colorize the contents if use_color = True.
"""<line_sep>starting_contents='this is where we start'<line_sep>colorized_contents='COLORIZED: this is where we start'<line_sep>_helper_assert_formatted_contents(starting_contents <true> 'some color config' <false> <none> colorized_contents 'this was squeezed' 'these contents were subbed' colorized_contents)<block_end><def_stmt>test_get_formatted_contents_squeezes <block_start>"""If squeeze, we need to squeeze."""<line_sep>starting_contents='this is where we start'<line_sep>squeezed_contents='this is the result of a squeezing'<line_sep>_helper_assert_formatted_contents(starting_contents <false> 'some color config' <true> <none> 'this was colored' squeezed_contents 'these contents were subbed' squeezed_contents)<block_end><def_stmt>test_get_formatted_contents_subsitutes <block_start>"""If subs is truthy, get_substituted contents should be called."""<line_sep>starting_contents='this is where we start'<line_sep>subbed_contents='substituted like a teacher'<line_sep>_helper_assert_formatted_contents(starting_contents <false> 'some color config' <false> ['truthy' 'list'] 'this was colored' 'this was squeezed' subbed_contents subbed_contents)<block_end><def_stmt>test_perform_all_formatting <block_start>"""
When use_color, squeeze, and subs are all truthy, all the formatting
should be applied in that order.
"""<line_sep>starting_contents='the starting point for grand formatting'<line_sep>subbed_contents='subbed is the last thing called so should be the result'<line_sep>_helper_assert_formatted_contents(starting_contents <true> 'some color config' <true> ['truthy' 'list'] 'this was colored' 'this was squeezed' subbed_contents subbed_contents)<block_end><def_stmt>_get_file_as_string path<block_start>"""Get the contents of the file as a string."""<with_stmt>open(path 'r')<as>f<block_start>data=f.read()<block_end><return>data<block_end><def_stmt>test_get_squeezed_contents_correctly_squeezes <block_start>"""
Our squeeze method should follow our convention, which is to remove the
blank line between a description and an example, to keep two blank lines
between sections, and otherwise have only single blank lines.
"""<line_sep>unsqueezed=_get_file_as_string(PATH_UNSQUEEZED_FILE)<line_sep># the target squeezed output is a reference implementation in
# pwd_squeezed.md.
target=_get_file_as_string(PATH_SQUEEZED_FILE)<line_sep>actual=util.get_squeezed_contents(unsqueezed)<assert_stmt>actual<eq>target<block_end><def_stmt>test_get_substituted_contents_handles_empty_subs <block_start>"""Nothing should be formatted if there are no substitutions."""<line_sep>raw_contents='this should not be subbed'<line_sep>actual=util.get_substituted_contents(raw_contents [])<assert_stmt>actual<eq>raw_contents<block_end><def_stmt>test_get_substituted_contents_substitutes_calls_correct_methods <block_start>"""
The get_substituted_contents method calls things in the correct order.
"""<line_sep>sub_one=Mock(auto_spec=substitute.Substitution)<line_sep>sub_one_result='result of sub one'<line_sep>sub_one.apply_and_get_result.return_value=sub_one_result<line_sep>sub_two=Mock(auto_spec=substitute.Substitution)<line_sep>sub_two_result='result of sub two'<line_sep>sub_two.apply_and_get_result.return_value=sub_two_result<line_sep>starting_contents='the string we should be substituting into'<line_sep>target=sub_two_result<line_sep>subs=[sub_one sub_two]<line_sep>actual=util.get_substituted_contents(starting_contents subs)<line_sep>sub_one.apply_and_get_result.assert_called_once_with(starting_contents)<line_sep>sub_two.apply_and_get_result.assert_called_once_with(sub_one_result)<assert_stmt>actual<eq>target<block_end><def_stmt>test_get_substituted_contents_substitutes_correctly <block_start>"""
Basic test to make sure Substitutions can get applied correctly.
"""<line_sep>sub_one=substitute.Substitution('foo' 'bar' <false>)<line_sep>sub_two=substitute.Substitution('bar\n\n' 'baz\n' <true>)<line_sep>start='foo\n\n something else\n\n bar\n\n'<line_sep>target='baz\n something else\n\n baz\n'<line_sep>subs=[sub_one sub_two]<line_sep>actual=util.get_substituted_contents(start subs)<assert_stmt>actual<eq>target<block_end>@patch('eg.color.EgColorizer')<def_stmt>test_get_colorized_contents_calls_methods patched_colorizer_class<block_start>"""
We should call the correct methods on the EgColorizer objects when we color
a file.
"""<line_sep>raw_contents='these are uncolored contents'<line_sep>colored_contents='COLORED: '+raw_contents<line_sep>color_config='some color config'<line_sep># The actual instance created by these calls is stored at return_value.
colorizer_instance=patched_colorizer_class.return_value<line_sep>colorizer_instance.colorize_text.return_value=colored_contents<line_sep>actual=util.get_colorized_contents(raw_contents color_config)<assert_stmt>actual<eq>colored_contents<line_sep>colorizer_instance.colorize_text.assert_called_once_with(raw_contents)<block_end>@patch('eg.util.get_alias_dict')<def_stmt>_helper_assert_get_resolved_program program resolved_program config_obj alias_dict mock_dict <block_start>"""
program: the program to resolved for as an alias
resolved_program: the result of the resolution.
config_obj: the config_obj to use toe resolve the alias path
alias_dict: the dict of aliases to be returned
"""<line_sep>mock_dict.return_value=alias_dict<line_sep>actual=util.get_resolved_program(program config_obj)<assert_stmt>actual<eq>resolved_program<line_sep>mock_dict.assert_called_once_with(config_obj)<block_end><def_stmt>test_get_resolved_program_no_alias <block_start>"""
A program that is not an alias should return itself.
"""<line_sep>alias_dict={'link':'ln' 'nc':'netcat'}<line_sep>config_obj='a config'<line_sep>_helper_assert_get_resolved_program('link' 'ln' config_obj alias_dict)<block_end><def_stmt>test_get_resolved_program_is_alias <block_start>"""
A program that is an alias should return the resolved value.
"""<line_sep>alias_dict={'link':'ln' 'nc':'netcat'}<line_sep>config_obj='some new config'<line_sep>_helper_assert_get_resolved_program('cp' 'cp' config_obj alias_dict)<block_end><def_stmt>test_get_alias_dict_returns_contents_of_correct_file <block_start>"""
get_alias_dict should read data from the file at the default path.
"""<line_sep>alias_dict={'link':'ln' 'nc':'netcat'}<line_sep>config_obj=_create_config(examples_dir='path/to/examples/dir' )<line_sep>alias_file_path='path/to/alias/file'<line_sep>alias_dict_str=json.dumps(alias_dict)<line_sep>_helper_assert_get_alias_dict(alias_dict_str alias_dict config_obj alias_file_path <true>)<block_end><def_stmt>test_get_alias_dict_fails_gracefully_if_not_file <block_start>"""
Since users can specify a directory for examples that might not contain the
aliases file, we want to fail gracefully if the file doesn't exist.
"""<line_sep>contents_of_alias_dict_file='should never be reached'<line_sep>config_obj=_create_config(examples_dir='path/to/examples/dir' )<line_sep>alias_file_path='path/to/the/alias/file'<line_sep>_helper_assert_get_alias_dict(contents_of_alias_dict_file {} config_obj alias_file_path <false>)<block_end>@patch('eg.util._get_contents_of_file')@patch('eg.util._get_alias_file_path')@patch('os.path.isfile')<def_stmt>_helper_assert_get_alias_dict contents_of_alias_dict_file target_alias_dict config_obj alias_file_path alias_file_path_is_file mock_is_file mock_get_alias_file_path mock_get_contents <block_start>"""
contents_of_alias_dict_file: the string contents of the file storing the
dictionary of aliases
target_alias_dict: the target result of get_alias_dict
config_obj: the Config object
alias_file_path: the path to be returned by _get_alias_file_path
alias_file_path_is_file: True if the alias path is a file, else False
"""<line_sep>mock_is_file.return_value=alias_file_path_is_file<line_sep>mock_get_alias_file_path.return_value=alias_file_path<line_sep>mock_get_contents.return_value=contents_of_alias_dict_file<line_sep>actual=util.get_alias_dict(config_obj)<assert_stmt>actual<eq>target_alias_dict<line_sep>mock_get_alias_file_path.assert_called_once_with(config_obj)<line_sep>mock_is_file.assert_called_once_with(alias_file_path)<if_stmt>alias_file_path_is_file<block_start>mock_get_contents.assert_called_once_with(alias_file_path)<block_end><else_stmt><block_start><assert_stmt>mock_get_contents.call_count<eq>0<block_end><block_end>@patch('os.path.join')<def_stmt>test_get_alias_file_path mock_join<block_start>"""
_get_alias_file_path should just join the example dir and the alias file
name, to make sure we look in the right place for the file.
"""<line_sep>config_obj=_create_config(examples_dir='handy/dandy/examples/dir' )<line_sep>join_result='joined path'<line_sep>mock_join.return_value=join_result<line_sep>actual=util._get_alias_file_path(config_obj)<assert_stmt>actual<eq>join_result<line_sep>mock_join.assert_called_once_with(config_obj.examples_dir util.ALIAS_FILE_NAME)<block_end><def_stmt>test_is_example_file_true_if_has_suffix <block_start>"""
Should be true if ends in EXAMPLE_FILE_SUFFIX.
"""<line_sep>file_name='find.md'<line_sep>actual=util._is_example_file(file_name)<assert_stmt>actual<eq><true><block_end><def_stmt>test_is_example_file_true_if_not_suffix <block_start>"""
Should be false if the file does not end in EXAMPLE_FILE_SUFFIX.
"""<line_sep>file_name='aliases.json'<line_sep>actual=util._is_example_file(file_name)<assert_stmt>actual<eq><false><block_end><def_stmt>test_can_parse_alias_file <block_start>"""
Make sure aliases.json file can be parsed.
This is to make sure an edit doesn't accidentally corrupt it.
"""<line_sep># We'll have to hardcode this.
alias_file_path=os.path.join(config.DEFAULT_EXAMPLES_DIR util.ALIAS_FILE_NAME)<line_sep>alias_file_contents=util._get_contents_of_file(alias_file_path)<line_sep>alias_dict=json.loads(alias_file_contents)<line_sep># We'll check that link goes to ln, as we know that one will be present.
<assert_stmt>alias_dict['link']<eq>'ln'<block_end>@patch('os.path.exists')@patch('eg.util._inform_cannot_edit_no_custom_dir')@patch('eg.util.get_resolved_program')@patch('eg.util.get_file_paths_for_program')@patch('subprocess.call')<def_stmt>test_edit_custom_examples_correct_with_custom_dir mock_call mock_get_paths mock_get_program mock_inform mock_exists <block_start>"""
We should resolve aliases, get the custom file path, and call subprocess.
"""<line_sep>program='du'<line_sep>resolved_program='alias for du'<line_sep>config=_create_config(custom_dir='path/to/custom' editor_cmd='nano')<line_sep>paths=['path/to/custom/du.md' 'foo.md']<line_sep>mock_get_program.return_value=resolved_program<line_sep>mock_get_paths.return_value=paths<line_sep>mock_exists.return_value=<true><line_sep>util.edit_custom_examples(program config)<line_sep>mock_get_program.assert_called_once_with(program config)<line_sep>mock_get_paths.assert_called_once_with(resolved_program config.custom_dir)<line_sep>mock_call.assert_called_once_with([config.editor_cmd paths[0]])<assert_stmt>mock_inform.call_count<eq>0<block_end>@patch('os.path.exists')@patch('eg.util._inform_cannot_edit_no_custom_dir')@patch('eg.util.get_resolved_program')@patch('eg.util.get_file_paths_for_program')@patch('subprocess.call')<def_stmt>test_edit_custom_examples_creates_file_if_none_exist mock_call mock_get_paths mock_get_program mock_inform mock_exists <block_start>program='du'<line_sep>resolved_program='alias-for-du'<line_sep>config=_create_config(custom_dir='path/to/custom' editor_cmd='nano')<line_sep>paths=[]<line_sep>mock_get_program.return_value=resolved_program<line_sep>mock_get_paths.return_value=paths<line_sep>mock_exists.return_value=<true><line_sep>util.edit_custom_examples(program config)<line_sep>mock_get_program.assert_called_once_with(program config)<line_sep>mock_get_paths.assert_called_once_with(resolved_program config.custom_dir)<line_sep>mock_call.assert_called_once_with([config.editor_cmd 'path/to/custom/alias-for-du.md'])<assert_stmt>mock_inform.call_count<eq>0<block_end>@patch('os.path.exists')@patch('eg.util._inform_cannot_edit_no_custom_dir')@patch('eg.util.get_resolved_program')@patch('eg.util.get_file_paths_for_program')@patch('subprocess.call')<def_stmt>test_edit_custom_examples_informs_if_no_custom_dir mock_call mock_get_paths mock_get_program mock_inform mock_exists <block_start>"""
We should inform the user if they are trying to edit with no custom dir.
This should be true if it is not set and if the path does not exist.
"""<line_sep>program='awk'<line_sep># First with no custom dir set.
config=_create_config(editor_cmd='vi -e')<line_sep>mock_exists.return_value=<true><line_sep>util.edit_custom_examples(program config)<assert_stmt>mock_inform.call_count<eq>1<line_sep># And now with it set but a nonexistent path.
config=_create_config(custom_dir='/path/to/custom' editor_cmd='vi -e')<line_sep>mock_exists.return_value=<false><line_sep>util.edit_custom_examples(program config)<assert_stmt>mock_inform.call_count<eq>2<assert_stmt>mock_call.call_count<eq>0<assert_stmt>mock_get_paths.call_count<eq>0<assert_stmt>mock_get_program.call_count<eq>0<block_end> |
<import_from_stmt>sage.misc.lazy_import lazy_import<line_sep>lazy_import('sage.symbolic.expression' 'PynacConstant' deprecation=32386)<line_sep> |
<import_stmt>FWCore.ParameterSet.Config<as>cms<line_sep>BtagPerformanceESProducer_TTBARWPBTAGCSVL=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGCSVL') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGCSVLtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGCSVLwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGCSVM=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGCSVM') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGCSVMtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGCSVMwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGCSVT=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGCSVT') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGCSVTtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGCSVTwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJPL=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJPL') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJPLtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJPLwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJPM=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJPM') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJPMtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJPMwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJPT=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJPT') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJPTtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJPTwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJBPL=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJBPL') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJBPLtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJBPLwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJBPM=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJBPM') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJBPMtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJBPMwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJBPT=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJBPT') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJBPTtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJBPTwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJBPL=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJBPL') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJBPLtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJBPLwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJBPM=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJBPM') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJBPMtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJBPMwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGJBPT=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGJBPT') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGJBPTtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGJBPTwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGSSVHEM=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGSSVHEM') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGSSVHEMtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGSSVHEMwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGSSVHET=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGSSVHET') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGSSVHETtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGSSVHETwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGSSVHPT=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGSSVHPT') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGSSVHPTtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGSSVHPTwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGTCHEL=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGTCHEL') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGTCHELtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGTCHELwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGTCHEM=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGTCHEM') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGTCHEMtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGTCHEMwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGTCHET=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGTCHET') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGTCHETtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGTCHETwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGTCHPL=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGTCHPL') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGTCHPLtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGTCHPLwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGTCHPM=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGTCHPM') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGTCHPMtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGTCHPMwp_v8_offline'))<line_sep>BtagPerformanceESProducer_TTBARWPBTAGTCHPT=cms.ESProducer("BtagPerformanceESProducer" # this is what it makes available
ComponentName=cms.string('TTBARWPBTAGTCHPT') # this is where it gets the payload from
PayloadName=cms.string('BTagTTBARWPBTAGTCHPTtable_v8_offline') WorkingPointName=cms.string('BTagTTBARWPBTAGTCHPTwp_v8_offline'))<line_sep> |
#
# Copyright (c) 2020 <NAME>.
#
# 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_stmt>sys<import_stmt>ast<import_stmt>os<import_stmt>importlib<import_stmt>copy<import_from_stmt>pycg utils<def_stmt>get_custom_loader ig_obj<block_start>"""
Closure which returns a custom loader
that modifies an ImportManager object
"""<class_stmt>CustomLoader(importlib.abc.SourceLoader)<block_start><def_stmt>__init__ self fullname path<block_start>self.fullname=fullname<line_sep>self.path=path<line_sep>ig_obj.create_edge(self.fullname)<if_stmt><not>ig_obj.get_node(self.fullname)<block_start>ig_obj.create_node(self.fullname)<line_sep>ig_obj.set_filepath(self.fullname self.path)<block_end><block_end><def_stmt>get_filename self fullname<block_start><return>self.path<block_end><def_stmt>get_data self filename<block_start><return>""<block_end><block_end><return>CustomLoader<block_end><class_stmt>ImportManager(object)<block_start><def_stmt>__init__ self<block_start>self.import_graph=dict()<line_sep>self.current_module=""<line_sep>self.input_file=""<line_sep>self.mod_dir=<none><line_sep>self.old_path_hooks=<none><line_sep>self.old_path=<none><block_end><def_stmt>set_pkg self input_pkg<block_start>self.mod_dir=input_pkg<block_end><def_stmt>get_mod_dir self<block_start><return>self.mod_dir<block_end><def_stmt>get_node self name<block_start><if_stmt>name<in>self.import_graph<block_start><return>self.import_graph[name]<block_end><block_end><def_stmt>create_node self name<block_start><if_stmt><not>name<or><not>isinstance(name str)<block_start><raise>ImportManagerError("Invalid node name")<block_end><if_stmt>self.get_node(name)<block_start><raise>ImportManagerError("Can't create a node a second time")<block_end>self.import_graph[name]={"filename":"" "imports":set()}<line_sep><return>self.import_graph[name]<block_end><def_stmt>create_edge self dest<block_start><if_stmt><not>dest<or><not>isinstance(dest str)<block_start><raise>ImportManagerError("Invalid node name")<block_end>node=self.get_node(self._get_module_path())<if_stmt><not>node<block_start><raise>ImportManagerError("Can't add edge to a non existing node")<block_end>node["imports"].add(dest)<block_end><def_stmt>_clear_caches self<block_start>importlib.invalidate_caches()<line_sep>sys.path_importer_cache.clear()<line_sep># TODO: maybe not do that since it empties the whole cache
<for_stmt>name self.import_graph<block_start><if_stmt>name<in>sys.modules<block_start><del_stmt>sys.modules[name]<block_end><block_end><block_end><def_stmt>_get_module_path self<block_start><return>self.current_module<block_end><def_stmt>set_current_mod self name fname<block_start>self.current_module=name<line_sep>self.input_file=os.path.abspath(fname)<block_end><def_stmt>get_filepath self modname<block_start><if_stmt>modname<in>self.import_graph<block_start><return>self.import_graph[modname]["filename"]<block_end><block_end><def_stmt>set_filepath self node_name filename<block_start><if_stmt><not>filename<or><not>isinstance(filename str)<block_start><raise>ImportManagerError("Invalid node name")<block_end>node=self.get_node(node_name)<if_stmt><not>node<block_start><raise>ImportManagerError("Node does not exist")<block_end>node["filename"]=os.path.abspath(filename)<block_end><def_stmt>get_imports self modname<block_start><if_stmt><not>modname<in>self.import_graph<block_start><return>[]<block_end><return>self.import_graph[modname]["imports"]<block_end><def_stmt>_is_init_file self<block_start><return>self.input_file.endswith("__init__.py")<block_end><def_stmt>_handle_import_level self name level# add a dot for each level
<block_start>package=self._get_module_path().split(".")<if_stmt>level<g>len(package)<block_start><raise>ImportError("Attempting import beyond top level package")<block_end>mod_name=("."<times>level)+name<line_sep># When an __init__ file is analyzed, then the module name doesn't contain
# the __init__ part in it, so special care must be taken for levels.
<if_stmt>self._is_init_file()<and>level<ge>1<block_start><if_stmt>level<ne>1<block_start>level<augsub>1<line_sep>package=package[:-level]<block_end><block_end><else_stmt><block_start>package=package[:-level]<block_end><return>mod_name ".".join(package)<block_end><def_stmt>_do_import self mod_name package<block_start><if_stmt>mod_name<in>sys.modules<block_start>self.create_edge(mod_name)<line_sep><return>sys.modules[mod_name]<block_end><return>importlib.import_module(mod_name package=package)<block_end><def_stmt>handle_import self name level# We currently don't support builtin modules because they're frozen.
# Add an edge and continue.
# TODO: identify a way to include frozen modules
<block_start>root=name.split(".")[0]<if_stmt>root<in>sys.builtin_module_names<block_start>self.create_edge(root)<line_sep><return><block_end># Import the module
<try_stmt><block_start>mod_name,package=self._handle_import_level(name level)<block_end><except_stmt>ImportError<block_start><return><block_end>parent=".".join(mod_name.split(".")[:-1])<line_sep>parent_name=".".join(name.split(".")[:-1])<line_sep>combos=[(mod_name package) (parent package) (utils.join_ns(package name) "") (utils.join_ns(package parent_name) "")]<line_sep>mod=<none><for_stmt>mn,pkg combos<block_start><try_stmt><block_start>mod=self._do_import(mn pkg)<line_sep><break><block_end><except_stmt><block_start><continue><block_end><block_end><if_stmt><not>mod<block_start><return><block_end><if_stmt><not>hasattr(mod "__file__")<or><not>mod.__file__<block_start><return><block_end><if_stmt>self.mod_dir<not><in>mod.__file__<block_start><return><block_end>fname=mod.__file__<if_stmt>fname.endswith("__init__.py")<block_start>fname=os.path.split(fname)[0]<block_end><return>utils.to_mod_name(os.path.relpath(fname self.mod_dir))<block_end><def_stmt>get_import_graph self<block_start><return>self.import_graph<block_end><def_stmt>install_hooks self<block_start>loader=get_custom_loader(self)<line_sep>self.old_path_hooks=copy.deepcopy(sys.path_hooks)<line_sep>self.old_path=copy.deepcopy(sys.path)<line_sep>loader_details=loader importlib.machinery.all_suffixes()<line_sep>sys.path_hooks.insert(0 importlib.machinery.FileFinder.path_hook(loader_details))<line_sep>sys.path.insert(0 os.path.abspath(self.mod_dir))<line_sep>self._clear_caches()<block_end><def_stmt>remove_hooks self<block_start>sys.path_hooks=self.old_path_hooks<line_sep>sys.path=self.old_path<line_sep>self._clear_caches()<block_end><block_end><class_stmt>ImportManagerError(Exception)<block_start><pass><block_end> |
# Generated by Django 2.2.7 on 2019-11-15 21:48
<import_from_stmt>django.db migrations models<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[('products' '0005_ClickMeeetingRoomURL') ]<line_sep>operations=[migrations.AddField(model_name='course' name='full_name' field=models.CharField(default='' help_text='Билет на мастер-класс о TDD или «запись курсов кройки и шитья»' max_length=255 verbose_name='Full name for letters') preserve_default=<false> ) migrations.AddField(model_name='record' name='full_name' field=models.CharField(default='' help_text='«Запись мастер-класса о TDD»' max_length=255 verbose_name='Full name for letters') preserve_default=<false> ) migrations.AlterField(model_name='course' name='name_genitive' field=models.CharField(help_text='«мастер-класса о TDD». К примеру для записей.' max_length=255 verbose_name='Genitive name') ) migrations.AlterField(model_name='course' name='name_receipt' field=models.CharField(help_text='«посещение мастер-класса по TDD» или «Доступ к записи курсов кройки и шитья»' max_length=255 verbose_name='Name for receipts') ) migrations.AlterField(model_name='record' name='name_receipt' field=models.CharField(help_text='«Доступ к записи курсов кройки и шитья»' max_length=255 verbose_name='Name for receipts') ) ]<block_end> |
# -*- coding: utf-8 -*-
<import_stmt>requests<import_stmt>os<import_from_stmt>lxml etree<try_stmt><block_start><import_from_stmt>urlparse urlparse<block_end><except_stmt>ImportError<block_start><import_from_stmt>urllib.parse urlparse<block_end><try_stmt><block_start><import_from_stmt>.xmlns strip_xmlns<import_from_stmt>.service Service<import_from_stmt>.embedded_device EmbeddedDevice<import_from_stmt>.instance_singleton InstanceSingleton<block_end><except_stmt>ImportError<block_start><import_from_stmt>xmlns strip_xmlns<import_from_stmt>service Service<import_from_stmt>embedded_device EmbeddedDevice<import_from_stmt>instance_singleton InstanceSingleton<block_end><class_stmt>UPNPObject(object)<block_start><def_stmt>__init__ self ip locations dump=''<block_start>self.ip_address=ip<line_sep>self._devices={}<line_sep>self._services={}<for_stmt>location locations<block_start>parsed_url=urlparse(location)<line_sep>url=parsed_url.scheme+'://'+parsed_url.netloc<line_sep>response=requests.get(location)<line_sep>content=response.content.decode('utf-8')<if_stmt>dump<block_start>path=location<if_stmt>path.startswith('/')<block_start>path=path[1:]<block_end><if_stmt>'/'<in>path<block_start>path,file_name=path.rsplit('/' 1)<line_sep>path=os.path.join(dump path)<block_end><else_stmt><block_start>file_name=path<line_sep>path=dump<block_end><if_stmt><not>os.path.exists(path)<block_start>os.makedirs(path)<block_end><if_stmt><not>file_name.endswith('.xml')<block_start>file_name<augadd>'.xml'<block_end><with_stmt>open(os.path.join(path file_name) 'w')<as>f<block_start>f.write(content)<block_end><block_end><try_stmt><block_start>root=etree.fromstring(content)<block_end><except_stmt>etree.XMLSyntaxError<block_start><continue><block_end>root=strip_xmlns(root)<line_sep>node=root.find('device')<line_sep>services=node.find('serviceList')<if_stmt>services<is><none><block_start>services=[]<block_end>devices=node.find('deviceList')<if_stmt>devices<is><none><block_start>devices=[]<block_end><for_stmt>service services<block_start>scpdurl=service.find('SCPDURL').text.replace(url '')<line_sep>control_url=service.find('controlURL').text<if_stmt>control_url<is><none><block_start><if_stmt>scpdurl.endswith('.xml')<block_start>control_url=scpdurl.rsplit('/' 1)[0]<if_stmt>control_url<eq>scpdurl<block_start>control_url=''<block_end><block_end><else_stmt><block_start>control_url=scpdurl<block_end><block_end><else_stmt><block_start>control_url=control_url.replace(url '')<block_end>service_id=service.find('serviceId').text<line_sep>service_type=service.find('serviceType').text<line_sep>service=Service(self url scpdurl service_type control_url node dump=dump)<line_sep>name=service_id.split(':')[-1]<line_sep>service.__name__=name<line_sep>self._services[name]=service<block_end><for_stmt>device devices<block_start>device=EmbeddedDevice(url node=device parent=self dump=dump)<line_sep>self._devices[device.__name__]=device<block_end><block_end><block_end><def_stmt>__getattr__ self item<block_start><if_stmt>item<in>self.__dict__<block_start><return>self.__dict__[item]<block_end><if_stmt>item<in>self._devices<block_start><return>self._devices[item]<block_end><if_stmt>item<in>self._services<block_start><return>self._services[item]<block_end><if_stmt>item<in>self.__class__.__dict__<block_start><if_stmt>hasattr(self.__class__.__dict__[item] 'fget')<block_start><return>self.__class__.__dict__[item].fget(self)<block_end><block_end><raise>AttributeError(item)<block_end>@property<def_stmt>as_dict self<block_start>res=dict(services=list(service.as_dict<for>service self.services) devices=list(device.as_dict<for>device self.devices))<line_sep><return>res<block_end>@property<def_stmt>access_point self<block_start><return>self.__class__.__name__<block_end>@property<def_stmt>services self<block_start><return>list(self._services.values())[:]<block_end>@property<def_stmt>devices self<block_start><return>list(self._devices.values())[:]<block_end><def_stmt>__str__ self<block_start>output='\n\n'+str(self.__name__)+'\n'<line_sep>output<augadd>'IP Address: '+self.ip_address+'\n'<line_sep>output<augadd>'==============================================\n'<if_stmt>self.services<block_start>output<augadd>'Services:\n'<for_stmt>cls self.services<block_start>output<augadd>cls.__str__(indent=' ').rstrip()+'\n'<block_end><block_end><else_stmt><block_start>output<augadd>'Services: None\n'<block_end><if_stmt>self.devices<block_start>output<augadd>'Devices:\n'<for_stmt>cls self.devices<block_start>output<augadd>cls.__str__(indent=' ').rstrip()+'\n'<block_end><block_end><else_stmt><block_start>output<augadd>'Devices: None\n'<block_end><return>output<block_end><block_end> |
# Copyright 2019 HTCondor Team, Computer Sciences Department,
# University of Wisconsin-Madison, WI.
#
# 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_stmt>logging<import_stmt>textwrap<import_from_stmt>pathlib Path<line_sep>logger=logging.getLogger(__name__)<line_sep>logger.setLevel(logging.DEBUG)<line_sep># TODO: does this way of doing permissions work on Windows?
<def_stmt>write_file path:Path text:str permissions:int=0o777<arrow>Path<block_start>"""
Write the given ``text`` to a new file at the given ``path``, stomping
anything that might exist there.
Parameters
----------
path
The path to write to.
text
The text to write.
permissions
The permissions to give the file.
Returns
-------
path : pathlib.Path
The path the file was written to (as an absolute path).
"""<line_sep>path=Path(path).absolute()<line_sep>path.parent.mkdir(parents=<true> exist_ok=<true>)<line_sep>path.write_text(textwrap.dedent(text))<line_sep>path.chmod(permissions)<line_sep><return>path<block_end> |
<import_stmt>abc<import_stmt>enum<import_from_stmt>magma.common deprecated<import_from_stmt>magma.compatibility IntegerTypes StringTypes<import_from_stmt>magma.ref AnonRef NamedRef TempNamedRef DefnRef InstRef<import_from_stmt>magma.protocol_type magma_value<import_from_stmt>magma.wire wire<class_stmt>Direction(enum.Enum)<block_start>In=0<line_sep>Out=1<line_sep>InOut=2<line_sep>Undirected=3<block_end><class_stmt>Type(object)<block_start><def_stmt>__init__ self name=<none><block_start><if_stmt>name<is><none><block_start>name=AnonRef()<block_end><elif_stmt>isinstance(name str)<block_start>name=TempNamedRef(name=name value=self)<block_end>self.name=name<block_end>__hash__=object.__hash__<def_stmt>__repr__ self<block_start><if_stmt>self.name.anon()<block_start><return>f"{type(self)}()"<block_end>has_name=(isinstance(self.name NamedRef)<and><not>isinstance(self.name (InstRef DefnRef)))<if_stmt>has_name<block_start><return>f"{type(self)}(name=\"{repr(self.name)}\")"<block_end><return>repr(self.name)<block_end><def_stmt>__str__ self<block_start><if_stmt>self.name.anon()# Anon names aren't very useful, so just return a repr instead so
# it's easier to find the value
<block_start><return>repr(self)<block_end><return>str(self.name)<block_end># An instance has an anon name.
<def_stmt>anon self<block_start><return>self.name.anon()<block_end># Abstract method to be implemented by subclasses.
@classmethod<def_stmt>is_oriented cls direction<block_start><raise>NotImplementedError()<block_end>@classmethod<def_stmt>is_clock cls<block_start><raise>NotImplementedError()<block_end>@classmethod<def_stmt>is_input cls<block_start><return>cls.is_oriented(Direction.In)<block_end>@classmethod<def_stmt>is_output cls<block_start><return>cls.is_oriented(Direction.Out)<block_end>@classmethod<def_stmt>is_inout cls<block_start><return>cls.is_oriented(Direction.InOut)<block_end>@classmethod@deprecated<def_stmt>isoriented cls direction<block_start><return>cls.is_oriented(direction)<block_end>@classmethod@deprecated<def_stmt>isinput cls<block_start><return>cls.is_input()<block_end>@classmethod@deprecated<def_stmt>isoutput cls<block_start><return>cls.is_output()<block_end>@classmethod@deprecated<def_stmt>isinout cls<block_start><return>cls.is_inout()<block_end>@property<def_stmt>debug_name self<block_start>defn_str=""<line_sep>inst_str=""<if_stmt>isinstance(self.name DefnRef)<block_start>defn_str=str(self.name.defn.name)+"."<block_end><elif_stmt>isinstance(self.name InstRef)<block_start>inst_str=str(self.name.inst.name)+"."<line_sep>defn_str=str(self.name.inst.defn.name)+"."<block_end><return>f"{defn_str}{inst_str}{str(self)}"<block_end><def_stmt>__le__ self other<block_start><if_stmt>self.is_output()<block_start><raise>TypeError(f"Cannot use <= to assign to output: "<concat>f"{self.debug_name} (trying to assign "<concat>f"{other.debug_name})")<block_end>wire(other self)<block_end><def_stmt>__imatmul__ self other<block_start>other=magma_value(other)<if_stmt>self.is_output()<block_start><raise>TypeError(f"Cannot use @= to assign to output: {self} "<concat>f"(trying to assign {other})")<block_end>wire(other self)<line_sep><return>self<block_end>@abc.abstractmethod<def_stmt>unused self# Mark value is unused by calling unused on the underlying magma
# elements. For example, m.Bit is wired up to a coreir term primitive A
# general m.Array and m.Tuple will recursively call `unused` on its
# members.
<block_start><raise>NotImplementedError()<block_end>@abc.abstractmethod<def_stmt>undriven self# Mark value is undriven by calling undriven on the underlying magma
# elements. For example, m.Bit is wired up to a coreir undriven
# primitive A general m.Array and m.Tuple will recursively call
# `undriven` on its members.
<block_start><raise>NotImplementedError()<block_end><def_stmt>is_driven_anon_temporary self<block_start>"""
Returns true if this is an anonymous temporary value (not an output)
that is driven
"""<line_sep><return>self.name.anon()<and><not>self.is_output()<and>self.driven()<block_end><block_end><class_stmt>Kind(type)# Subclasses only need to implement one of these methods.
<block_start><def_stmt>__eq__ cls rhs<block_start><return>cls<is>rhs<block_end>__hash__=type.__hash__<def_stmt>__repr__ cls<block_start><return>cls.__name__<block_end><def_stmt>__str__ cls<block_start><return>cls.__name__<block_end>@abc.abstractmethod<def_stmt>qualify cls direction<block_start><raise>NotImplementedError()<block_end><def_stmt>flip cls<block_start><if_stmt>cls.direction<eq>Direction.In<block_start><return>cls[Direction.Out]<block_end><if_stmt>cls.direction<eq>Direction.Out<block_start><return>cls[Direction.In]<block_end># Flip of inout is inout, and flip of undirected is undirected.
<return>cls<block_end>@property<def_stmt>undirected_t cls<block_start><return>cls.qualify(Direction.Undirected)<block_end>@property<def_stmt>is_directed cls<block_start><return>cls<is><not>cls.qualify(Direction.Undirected)<block_end><block_end><def_stmt>In T<block_start><return>T.qualify(Direction.In)<block_end><def_stmt>Out T<block_start><return>T.qualify(Direction.Out)<block_end><def_stmt>InOut T<block_start><return>T.qualify(Direction.InOut)<block_end><def_stmt>Flip T<block_start><return>T.flip()<block_end> |
<import_from_stmt>unittest SkipTest<import_from_stmt>collections OrderedDict<import_stmt>numpy<as>np<import_from_stmt>holoviews Store<import_from_stmt>holoviews.element RGB Image<import_from_stmt>holoviews.element.comparison ComparisonTestCase<try_stmt><block_start><import_stmt>xarray<as>xr<block_end><except_stmt><block_start><raise>SkipTest('XArray not available')<block_end><else_stmt><block_start><import_stmt>hvplot.xarray<block_end># noqa
<class_stmt>TestGridPlots(ComparisonTestCase)<block_start><def_stmt>setUp self<block_start>coords=OrderedDict([('band' [1 2 3]) ('y' [0 1]) ('x' [0 1])])<line_sep>self.da_rgb=xr.DataArray(np.arange(12).reshape((3 2 2)) coords ['band' 'y' 'x'])<line_sep>coords=OrderedDict([('time' [0 1]) ('band' [1 2 3]) ('y' [0 1]) ('x' [0 1])])<line_sep>self.da_rgb_by_time=xr.DataArray(np.arange(24).reshape((2 3 2 2)) coords ['time' 'band' 'y' 'x'])<line_sep>coords=OrderedDict([('time' [0 1]) ('lat' [0 1]) ('lon' [0 1])])<line_sep>self.da_img_by_time=xr.DataArray(np.arange(8).reshape((2 2 2)) coords ['time' 'lat' 'lon']).assign_coords(lat1=xr.DataArray([2 3] dims=['lat']))<line_sep>self.xarr_with_attrs=xr.DataArray(np.random.rand(10 10) coords=[('x' range(10)) ('y' range(10))] dims=['y' 'x'] attrs={'long_name':'luminosity' 'units':'lm'})<line_sep>self.xarr_with_attrs.x.attrs['long_name']='Declination'<line_sep>self.xarr_with_attrs.y.attrs['long_name']='Right Ascension'<line_sep>self.xds_with_attrs=xr.Dataset({'light':self.xarr_with_attrs})<line_sep>self.da_img=xr.DataArray(np.arange(-2 2).reshape((2 2)) name='foo')<line_sep>self.big_img=xr.DataArray(np.arange(-1e6 1e6).reshape(1000 2000))<line_sep>self.ds=xr.Dataset({'temp':(('lon' 'lat') 15+8<times>np.random.randn(2 2)) 'precip':(('lon' 'lat') 10<times>np.random.rand(2 2))} coords={'lon':[-99.83 -99.32] 'lat':[42.25 42.21]})<line_sep>xs=np.linspace(0 10 5)<line_sep>lon=xs<times>xs[np.newaxis :].T<line_sep>lat=xs+xs[: np.newaxis]<line_sep>coords={'lon':(('ny' 'nx') lon) 'lat':(('ny' 'nx') lat) 'time':[1 2 3] 'samples':('nsamples' [0 1 2 3])}<line_sep>self.ds_unindexed=xr.DataArray(np.random.rand(5 5 3 4) coords=coords dims=('nx' 'ny' 'time' 'nsamples'))<block_end><def_stmt>test_rgb_dataarray_no_args self<block_start>rgb=self.da_rgb.hvplot()<line_sep>self.assertEqual(rgb RGB(([0 1] [0 1])+tuple(self.da_rgb.values)))<block_end><def_stmt>test_rgb_dataarray_explicit_args self<block_start>rgb=self.da_rgb.hvplot('x' 'y')<line_sep>self.assertEqual(rgb RGB(([0 1] [0 1])+tuple(self.da_rgb.values)))<block_end><def_stmt>test_rgb_dataarray_explicit_args_and_kind self<block_start>rgb=self.da_rgb.hvplot.rgb('x' 'y')<line_sep>self.assertEqual(rgb RGB(([0 1] [0 1])+tuple(self.da_rgb.values)))<block_end><def_stmt>test_rgb_dataset self<block_start>rgb=self.da_rgb.to_dataset(name='z').hvplot.rgb()<line_sep>self.assertEqual(rgb RGB(([0 1] [0 1])+tuple(self.da_rgb.values)))<block_end><def_stmt>test_rgb_dataset_explicit_z self<block_start>rgb=self.da_rgb.to_dataset(name='z').hvplot.rgb(z='z')<line_sep>self.assertEqual(rgb RGB(([0 1] [0 1])+tuple(self.da_rgb.values)))<block_end><def_stmt>test_rgb_dataarray_groupby_explicit self<block_start>rgb=self.da_rgb_by_time.hvplot.rgb('x' 'y' groupby='time')<line_sep>self.assertEqual(rgb[0] RGB(([0 1] [0 1])+tuple(self.da_rgb_by_time.values[0])))<line_sep>self.assertEqual(rgb[1] RGB(([0 1] [0 1])+tuple(self.da_rgb_by_time.values[1])))<block_end><def_stmt>test_rgb_dataarray_groupby_infer self<block_start>rgb=self.da_rgb_by_time.hvplot.rgb('x' 'y' bands='band')<line_sep>self.assertEqual(rgb[0] RGB(([0 1] [0 1])+tuple(self.da_rgb_by_time.values[0])))<line_sep>self.assertEqual(rgb[1] RGB(([0 1] [0 1])+tuple(self.da_rgb_by_time.values[1])))<block_end><def_stmt>test_img_dataarray_infers_correct_other_dims self<block_start>img=self.da_img_by_time[0].hvplot()<line_sep>self.assertEqual(img Image(self.da_img_by_time[0] ['lon' 'lat'] ['value']))<block_end><def_stmt>test_img_dataarray_groupby_infers_correct_other_dims self<block_start>img=self.da_img_by_time.hvplot(groupby='time')<line_sep>self.assertEqual(img[0] Image(self.da_img_by_time[0] ['lon' 'lat'] ['value']))<line_sep>self.assertEqual(img[1] Image(self.da_img_by_time[1] ['lon' 'lat'] ['value']))<block_end><def_stmt>test_line_infer_dimension_params_from_xarray_attrs self<block_start>hmap=self.xarr_with_attrs.hvplot.line(groupby='x' dynamic=<false>)<line_sep>self.assertEqual(hmap.kdims[0].label 'Declination')<line_sep>self.assertEqual(hmap.last.kdims[0].label 'Right Ascension')<line_sep>self.assertEqual(hmap.last.vdims[0].label 'luminosity')<line_sep>self.assertEqual(hmap.last.vdims[0].unit 'lm')<block_end><def_stmt>test_img_infer_dimension_params_from_xarray_attrs self<block_start>img=self.xarr_with_attrs.hvplot.image(clim=(0 2))<line_sep>self.assertEqual(img.kdims[0].label 'Declination')<line_sep>self.assertEqual(img.kdims[1].label 'Right Ascension')<line_sep>self.assertEqual(img.vdims[0].label 'luminosity')<line_sep>self.assertEqual(img.vdims[0].unit 'lm')<line_sep>self.assertEqual(img.vdims[0].range (0 2))<block_end><def_stmt>test_table_infer_dimension_params_from_xarray_ds_attrs self<block_start>table=self.xds_with_attrs.hvplot.dataset()<line_sep>self.assertEqual(table.kdims[0].label 'Declination')<line_sep>self.assertEqual(table.kdims[1].label 'Right Ascension')<line_sep>self.assertEqual(table.vdims[0].label 'luminosity')<line_sep>self.assertEqual(table.vdims[0].unit 'lm')<block_end><def_stmt>test_points_infer_dimension_params_from_xarray_attrs self<block_start>points=self.xarr_with_attrs.hvplot.points(c='value' clim=(0 2))<line_sep>self.assertEqual(points.kdims[0].label 'Declination')<line_sep>self.assertEqual(points.kdims[1].label 'Right Ascension')<line_sep>self.assertEqual(points.vdims[0].label 'luminosity')<line_sep>self.assertEqual(points.vdims[0].unit 'lm')<line_sep>self.assertEqual(points.vdims[0].range (0 2))<block_end><def_stmt>test_dataset_infer_dimension_params_from_xarray_attrs self<block_start>ds=self.xarr_with_attrs.hvplot.dataset()<line_sep>self.assertEqual(ds.kdims[0].label 'Declination')<line_sep>self.assertEqual(ds.kdims[1].label 'Right Ascension')<line_sep>self.assertEqual(ds.vdims[0].label 'luminosity')<line_sep>self.assertEqual(ds.vdims[0].unit 'lm')<block_end><def_stmt>test_table_infer_dimension_params_from_xarray_attrs self<block_start>table=self.xarr_with_attrs.hvplot.dataset()<line_sep>self.assertEqual(table.kdims[0].label 'Declination')<line_sep>self.assertEqual(table.kdims[1].label 'Right Ascension')<line_sep>self.assertEqual(table.vdims[0].label 'luminosity')<line_sep>self.assertEqual(table.vdims[0].unit 'lm')<block_end><def_stmt>test_symmetric_img_deduces_symmetric self<block_start>plot=self.da_img.hvplot.image()<line_sep>plot_opts=Store.lookup_options('bokeh' plot 'plot')<line_sep>self.assertEqual(plot_opts.kwargs.get('symmetric') <true>)<line_sep>style_opts=Store.lookup_options('bokeh' plot 'style')<line_sep>self.assertEqual(style_opts.kwargs['cmap'] 'coolwarm')<block_end><def_stmt>test_symmetric_img_with_symmetric_set_to_false self<block_start>plot=self.da_img.hvplot.image(symmetric=<false>)<line_sep>plot_opts=Store.lookup_options('bokeh' plot 'plot')<line_sep>self.assertEqual(plot_opts.kwargs.get('symmetric') <false>)<line_sep>style_opts=Store.lookup_options('bokeh' plot 'style')<line_sep>self.assertEqual(style_opts.kwargs['cmap'] 'kbc_r')<block_end><def_stmt>test_symmetric_img_with_cmap_set self<block_start>plot=self.da_img.hvplot.image(cmap='fire')<line_sep>plot_opts=Store.lookup_options('bokeh' plot 'plot')<line_sep>self.assertEqual(plot_opts.kwargs.get('symmetric') <true>)<line_sep>style_opts=Store.lookup_options('bokeh' plot 'style')<line_sep>self.assertEqual(style_opts.kwargs['cmap'] 'fire')<block_end><def_stmt>test_symmetric_with_big_img_sets_symmetric_to_false_without_calculating self<block_start>plot=self.big_img.hvplot.image()<line_sep>plot_opts=Store.lookup_options('bokeh' plot 'plot')<line_sep>self.assertEqual(plot_opts.kwargs.get('symmetric') <false>)<line_sep>style_opts=Store.lookup_options('bokeh' plot 'style')<line_sep>self.assertEqual(style_opts.kwargs['cmap'] 'kbc_r')<block_end><def_stmt>test_symmetric_with_big_img_and_check_symmetric_max_calculates_symmetric self<block_start>plot=self.big_img.hvplot.image(check_symmetric_max=int(1e7))<line_sep>plot_opts=Store.lookup_options('bokeh' plot 'plot')<line_sep>self.assertEqual(plot_opts.kwargs.get('symmetric') <true>)<line_sep>style_opts=Store.lookup_options('bokeh' plot 'style')<line_sep>self.assertEqual(style_opts.kwargs['cmap'] 'coolwarm')<block_end><def_stmt>test_multiple_zs self<block_start>plot=self.ds.hvplot(x='lat' y='lon' z=['temp' 'precip'] dynamic=<false>)<assert_stmt>'temp'<in>plot.keys()<assert_stmt>'precip'<in>plot.keys()<assert_stmt>plot['temp'].kdims<eq>['lat' 'lon']<assert_stmt>plot['precip'].kdims<eq>['lat' 'lon']<block_end><def_stmt>test_unindexed_quadmesh self<block_start>plot=self.ds_unindexed.hvplot.quadmesh(x='lon' y='lat')<assert_stmt>len(plot.kdims)<eq>2<assert_stmt>plot.kdims[0].name<eq>'time'<assert_stmt>plot.kdims[1].name<eq>'nsamples'<line_sep>p=plot[1 0]<assert_stmt>len(p.kdims)<eq>2<assert_stmt>p.kdims[0].name<eq>'lon'<assert_stmt>p.kdims[1].name<eq>'lat'<block_end><block_end> |
<def_stmt>_impl _ctx<block_start><pass><block_end>bad_attrs=rule(implementation=_impl attrs={"1234isntvalid":attr.int()})<line_sep> |
<import_stmt>redis<line_sep>redis_client=redis.StrictRedis(host="127.0.0.1" port=6379)<line_sep>input("")<line_sep> |
<import_stmt>pytest<import_stmt>numpy<as>np<import_from_stmt>csgo.analytics.distance bombsite_distance point_distance polygon_area area_distance <import_from_stmt>csgo.analytics.coords Encoder<class_stmt>TestCSGOAnalytics<block_start>"""Class to test CSGO analytics"""<def_stmt>test_bombsite_distance self<block_start>"""Test bombsite distance function."""<assert_stmt>bombsite_distance([0 0 0])<eq>35<assert_stmt>bombsite_distance([0 0 0] bombsite="B")<eq>38<assert_stmt>bombsite_distance([0 0 0] bombsite="A" map="de_inferno")<eq>30<block_end><def_stmt>test_point_distance self<block_start>"""Test point distance function"""<assert_stmt>point_distance([0 0] [1 1] type="euclidean")<eq>1.4142135623730951<assert_stmt>point_distance([0 0] [1 1] type="manhattan")<eq>2<assert_stmt>point_distance([0 0] [1 1] type="canberra")<eq>2.0<assert_stmt>point_distance([-1 5] [2 1] type="cosine")<eq>0.7368825942078912<assert_stmt>point_distance([0 0 0] [100 100 100])<eq>4<assert_stmt>point_distance([0 0 0] [100 100 100] map="de_vertigo")<eq>1<block_end><def_stmt>test_polygon_area self<block_start>"""Test polygon area function"""<assert_stmt>polygon_area([0 1 2] [0 1 0])<eq>1.0<block_end><def_stmt>test_bombsite_invalid_map self<block_start>"""
Test bombsite function with an invalid map.
"""<with_stmt>pytest.raises(ValueError)<block_start>bombsite_distance([0 0 0] map="dust2")<block_end><block_end><def_stmt>test_point_invalid_map self<block_start>"""
Test point distance function with an invalid map.
"""<with_stmt>pytest.raises(ValueError)<block_start>point_distance([0 0 0] [1 1 1] map="dust2")<block_end><block_end><def_stmt>test_area_invalid_map self<block_start>"""
Test area distance function with an invalid map.
"""<with_stmt>pytest.raises(ValueError)<block_start>area_distance(26 42 map="dust2")<block_end><block_end><def_stmt>test_area_dist self<block_start>"""
Tests that area distance returns correct value.
"""<assert_stmt>area_distance(26 42 map="de_mirage")<eq>26<block_end><def_stmt>test_place_encode self<block_start>"""
Tests that place encoding works for correct values
"""<line_sep>e=Encoder()<assert_stmt>np.sum(e.encode("place" "TSpawn"))<eq>1<assert_stmt>np.sum(e.encode("place" "TSpawnnn"))<eq>0<assert_stmt>np.sum(e.encode("map" "de_dust2"))<eq>1<assert_stmt>np.sum(e.encode("map" "de_dust0"))<eq>0<block_end><block_end> |
<import_stmt>collections<import_stmt>pandas<as>pd<import_stmt>warnings<import_from_stmt>typing Union Optional List Dict Tuple<import_from_stmt>autogluon.core.constants MULTICLASS BINARY REGRESSION<import_from_stmt>.constants NULL CATEGORICAL NUMERICAL TEXT<line_sep>#TODO, This file may later be merged with the infer type logic in tabular.
<def_stmt>is_categorical_column data:pd.Series valid_data:pd.Series threshold:int=<none> ratio:Optional[float]=<none> oov_ratio_threshold:Optional[float]=<none> is_label:bool=<false><arrow>bool<block_start>"""Check whether the column is a categorical column.
If the number of unique elements in the column is smaller than
min(#Total Sample * ratio, threshold),
it will be treated as a categorical column.
Parameters
----------
data
The column data
valid_data
Additional validation data
threshold
The threshold for detecting categorical column
ratio
The ratio detecting categorical column
oov_ratio_threshold
The out-of-vocabulary ratio between training and validation.
This is used to determine if the column is a categorical column.
Usually, a categorical column can tolerate a small OOV ratio
is_label
Whether the column is a label column.
Returns
-------
is_categorical
Whether the column is a categorical column
"""<if_stmt>data.dtype.name<eq>'category'<block_start><return><true><block_end><else_stmt><block_start><if_stmt>threshold<is><none><block_start><if_stmt>is_label<block_start>threshold=100<line_sep>oov_ratio_threshold=0<line_sep>ratio=0.1<block_end><else_stmt><block_start>threshold=20<line_sep>oov_ratio_threshold=0<line_sep>ratio=0.1<block_end><block_end>threshold=min(int(len(data)<times>ratio) threshold)<line_sep>data_value_counts=data.value_counts(dropna=<false>)<line_sep>key_set=set(data_value_counts.keys())<if_stmt>len(data_value_counts)<l>threshold<block_start>valid_value_counts=valid_data.value_counts(dropna=<false>)<line_sep>total_valid_num=len(valid_data)<line_sep>oov_num=0<for_stmt>k,v zip(valid_value_counts.keys() valid_value_counts.values)<block_start><if_stmt>k<not><in>key_set<block_start>oov_num<augadd>v<block_end><block_end><if_stmt>is_label<and>oov_num<ne>0<block_start><return><false><block_end><if_stmt>oov_num/total_valid_num<g>oov_ratio_threshold<block_start><return><false><block_end><return><true><block_end><return><false><block_end><block_end><def_stmt>is_numerical_column data:pd.Series valid_data:Optional[pd.Series]=<none><block_start>"""Try to identify if a column is a numerical column.
We adopted a very simple rule to verify if the column is a numerical column.
Parameters
----------
data
The training data series
valid_data
The validation data series
Returns
-------
is_numerical
Whether the column is a numerical column
"""<try_stmt><block_start>numerical_data=pd.to_numeric(data)<if_stmt>valid_data<is><not><none><block_start>numerical_valid_data=pd.to_numeric(valid_data)<block_end><return><true><block_end><except_stmt><block_start><return><false><block_end><block_end><def_stmt>infer_column_problem_types train_df:pd.DataFrame valid_df:pd.DataFrame label_columns:Union[str List[str]] problem_type:Optional[str]=<none> provided_column_types:Optional[Dict]=<none><arrow>Tuple[collections.OrderedDict str]<block_start>"""Infer the column types of the data frame + the problem type
Parameters
----------
train_df
The training Pandas DataFrame
valid_df
The validation Pandas DataFrame
label_columns
The chosen label column names
problem_type
The type of the problem
provided_column_types
Additional dictionary that you can use to specify the columns types that you know.
{'col_name': TYPE}
Returns
-------
column_types
Dictionary of column types
If the column does not contain any useful information, we will filter the column with
type = NULL
problem_type
The inferred problem type
"""<if_stmt>isinstance(label_columns str)<block_start>label_columns=[label_columns]<block_end><elif_stmt>isinstance(label_columns (list tuple))<block_start><pass><block_end><else_stmt><block_start><raise>NotImplementedError(f'label_columns is not supported. label_columns={label_columns}.')<block_end>label_set=set(label_columns)<assert_stmt>len(label_set)<eq>1 'Currently, only a single label column is supported.'<line_sep>column_types=collections.OrderedDict()<line_sep># Process all feature columns
<for_stmt>col_name train_df.columns<block_start>is_label=col_name<in>label_set<if_stmt>provided_column_types<is><not><none><and>col_name<in>provided_column_types<block_start>column_types[col_name]=provided_column_types[col_name]<line_sep><continue><block_end><if_stmt>is_label<block_start>num_train_missing=train_df[col_name].isnull().sum()<line_sep>num_valid_missing=valid_df[col_name].isnull().sum()<if_stmt>num_train_missing<g>0<block_start><raise>ValueError(f'Label column "{col_name}" contains missing values in the '<concat>f'training data frame. You may want to filter your data because '<concat>f'missing label is currently not supported.')<block_end><if_stmt>num_valid_missing<g>0<block_start><raise>ValueError(f'Label column "{col_name}" contains missing values in the '<concat>f'validation data frame. You may want to filter your data because '<concat>f'missing label is currently not supported.')<block_end><if_stmt>problem_type<eq>MULTICLASS<or>problem_type<eq>BINARY<block_start>column_types[col_name]=CATEGORICAL<line_sep><continue><block_end><elif_stmt>problem_type<eq>REGRESSION<block_start>column_types[col_name]=NUMERICAL<line_sep><continue><block_end><block_end># Identify columns that provide no information
idx=train_df[col_name].first_valid_index()<if_stmt>idx<is><none><or>len(train_df[col_name].unique())<eq>1# No valid index, thus, we will just ignore the column
<block_start><if_stmt><not>is_label<block_start>column_types[col_name]=NULL<block_end><else_stmt><block_start>warnings.warn(f'Label column "{col_name}" contains only one label. You may want'<concat>f' to check your dataset again.')<block_end><block_end># Use the following way for type inference
# 1) Inference categorical column
# 2) Inference numerical column
# 3) All the other columns are treated as text column
<if_stmt>is_categorical_column(train_df[col_name] valid_df[col_name] is_label=is_label)<block_start>column_types[col_name]=CATEGORICAL<block_end><elif_stmt>is_numerical_column(train_df[col_name] valid_df[col_name])<block_start>column_types[col_name]=NUMERICAL<block_end><else_stmt><block_start>column_types[col_name]=TEXT<block_end><block_end>problem_type=infer_problem_type(column_types label_columns[0] train_df problem_type)<line_sep><return>column_types problem_type<block_end><def_stmt>printable_column_type_string column_types<block_start>ret='Column Types:\n'<for_stmt>col_name,col_type column_types.items()<block_start>ret<augadd>f' - "{col_name}": {col_type}\n'<block_end><return>ret<block_end><def_stmt>infer_problem_type column_types label_column data_df provided_problem_type=<none><block_start>"""Inference the type of the problem based on type of the column and
the training data.
Also, it will try to check the correctness of the column types and the provided problem_type.
Parameters
----------
column_types
Type of the columns
label_column
The label column
data_df
The dataframe
provided_problem_type
The provided problem type
Returns
-------
problem_type
Type of the problem
"""<if_stmt>provided_problem_type<is><not><none><block_start><if_stmt>provided_problem_type<eq>MULTICLASS<or>provided_problem_type<eq>BINARY<block_start>err_msg=f'Provided problem type is "{provided_problem_type}" while the number of '<concat>f'unique value in the label column is {len(data_df[label_column].unique())}'<if_stmt>provided_problem_type<eq>BINARY<and>len(data_df[label_column].unique())<ne>2<block_start><raise>AssertionError(err_msg)<block_end><elif_stmt>provided_problem_type<eq>MULTICLASS<and>len(data_df[label_column].unique())<le>2<block_start><raise>AssertionError(err_msg)<block_end><block_end><return>provided_problem_type<block_end><else_stmt><block_start><if_stmt>column_types[label_column]<eq>CATEGORICAL<block_start><if_stmt>len(data_df[label_column].value_counts())<eq>2<block_start><return>BINARY<block_end><else_stmt><block_start><return>MULTICLASS<block_end><block_end><elif_stmt>column_types[label_column]<eq>NUMERICAL<block_start><return>REGRESSION<block_end><else_stmt><block_start><raise>ValueError(f'The label column "{label_column}" has type'<concat>f' "{column_types[label_column]}" and is supported yet.')<block_end><block_end><block_end> |
<import_stmt>subprocess<import_stmt>os<def_stmt>download_task_model task<block_start>m_path=os.path.join('/home/ubuntu/s3' "model_log_final" task "logs/model.permanent-ckpt")<line_sep>dirs,fname=os.path.split(m_path)<line_sep>dst_dir=dirs.replace('/home/ubuntu/s3' "s3://taskonomy-unpacked-oregon")<line_sep>tmp_path="/home/ubuntu/temp/{}".format(task)<line_sep>subprocess.call('mkdir -p {}'.format(tmp_path) shell=<true>)<line_sep>tmp_fname=os.path.join(tmp_path fname)<line_sep>aws_cp_command="aws s3 cp {}.data-00000-of-00001 {}".format(os.path.join(dst_dir fname) tmp_path)<line_sep>subprocess.call(aws_cp_command shell=<true>)<line_sep>aws_cp_command="aws s3 cp {}.meta {}".format(os.path.join(dst_dir fname) tmp_path)<line_sep>subprocess.call(aws_cp_command shell=<true>)<line_sep>aws_cp_command="aws s3 cp {}.index {}".format(os.path.join(dst_dir fname) tmp_path)<line_sep>subprocess.call(aws_cp_command shell=<true>)<block_end>list_of_tasks='autoencoder curvature denoise edge2d edge3d \
keypoint2d keypoint3d colorization jigsaw \
reshade rgb2depth rgb2mist rgb2sfnorm \
room_layout segment25d segment2d vanishing_point_well_defined \
segmentsemantic_rb class_1000 class_places impainting_whole'<line_sep>list_of_tasks='impainting_whole'<line_sep>list_of_tasks=list_of_tasks.split()<for_stmt>t list_of_tasks<block_start>download_task_model(t)<block_end> |
<import_from_stmt>resotocore.db.async_arangodb AsyncArangoDB<import_from_stmt>resotocore.db.entitydb EntityDb EventEntityDb ArangoEntityDb<import_from_stmt>resotocore.task.task_description Job<line_sep>JobDb=EntityDb[Job]<line_sep>EventJobDb=EventEntityDb[Job]<def_stmt>job_db db:AsyncArangoDB collection:str<arrow>ArangoEntityDb[Job]<block_start><return>ArangoEntityDb(db collection Job <lambda>k:k.id)<block_end> |
# Generated by Django 2.0.2 on 2018-02-09 23:15
<import_from_stmt>django.db migrations models<import_stmt>django.db.models.deletion<class_stmt>Migration(migrations.Migration)<block_start>dependencies=[("auth" "0009_alter_user_last_name_max_length") ("todo" "0003_assignee_optional") ]<line_sep>operations=[migrations.CreateModel(name="TaskList" fields=[("id" models.AutoField(auto_created=<true> primary_key=<true> serialize=<false> verbose_name="ID") ) ("name" models.CharField(max_length=60)) ("slug" models.SlugField(default="")) ("group" models.ForeignKey(on_delete=django.db.models.deletion.CASCADE to="auth.Group") ) ] options={"verbose_name_plural":"Lists" "ordering":["name"]} ) migrations.AlterUniqueTogether(name="list" unique_together=set()) migrations.RemoveField(model_name="list" name="group") migrations.RemoveField(model_name="item" name="list") migrations.DeleteModel(name="List") migrations.AddField(model_name="item" name="task_list" field=models.ForeignKey(null=<true> on_delete=django.db.models.deletion.CASCADE to="todo.TaskList") ) migrations.AlterUniqueTogether(name="tasklist" unique_together={("group" "slug")}) ]<block_end> |
<import_from_stmt>flask_restful marshal abort Resource<import_from_stmt>app.models Schedule2<import_from_stmt>app.apiv2.decorators permission_sudo<import_from_stmt>app.apiv2.marshal tasking_schedule_fields<class_stmt>MobiusTaskApi(Resource)<block_start>method_decorators=[permission_sudo]<def_stmt>get self schedule_id<block_start>""" Peek at a schedule """<line_sep>s=Schedule2.query.get_or_404(schedule_id)<line_sep><return>marshal(s tasking_schedule_fields)<block_end><def_stmt>delete self schedule_id<block_start>""" Mark a task as done """<line_sep>s=Schedule2.query.get_or_404(schedule_id)<if_stmt>s.state<ne>"mobius-processing"<block_start>abort(400)<block_end>s.transition_to_published()<line_sep><return>"{}" 204<block_end><block_end> |
# -*- coding: utf-8 -*-
<import_from_future_stmt> unicode_literals absolute_import division print_function <import_from_stmt>._compat string_types<import_from_stmt>.util get_resource_path read_file<line_sep># 模板文件
# is_buildin == True时为内建模板文件,在脚本源码目录下寻找
<class_stmt>TemplateFile(object)<block_start><def_stmt>__init__ self path is_buildin=<false><block_start>self.tpl_file=get_resource_path(path)<if>is_buildin<else>path<block_end><def_stmt>__str__ self<block_start><return>read_file(self.tpl_file fail_msg='读取自定义模板文件{path}失败')<block_end><block_end>PAC=TemplateFile('res/tpl-pac.js' <true>)<line_sep>PAC_MIN=TemplateFile('res/tpl-pac.min.js' <true>)<line_sep>PAC_PRECISE=TemplateFile('res/tpl-pac-precise.js' <true>)<line_sep>PAC_PRECISE_MIN=TemplateFile('res/tpl-pac-precise.min.js' <true>)<line_sep>WINGY=TemplateFile('res/tpl-wingy.yaml' <true>)<line_sep>DNSMASQ='''
#! __GENPAC__
__DNSMASQ__
#! Generated: __GENERATED__
#! GFWList: __GFWLIST_DETAIL__
'''<line_sep>SS_ACL='''
#! __GENPAC__
[bypass_all]
[proxy_list]
__GFWED_RULES__
#! Generated: __GENERATED__
#! GFWList: __GFWLIST_DETAIL__
'''<line_sep>POTATSO='''
#! __GENPAC__
[RULESET.gfwed]
name = "GFWed rules"
rules = [
__GFWED_RULES__
]
[RULESET.direct]
name = "Direct rules"
rules = [
__DIRECT_RULES__
]
#! Generated: __GENERATED__
#! GFWList: __GFWLIST_DETAIL__
'''<line_sep># 去除文本模板的前后换行符
<for_stmt>name dir()<block_start><if_stmt>name.isupper()<and>isinstance(vars()[name] string_types)<block_start>vars()[name]=vars()[name].strip('\n')<block_end><block_end> |
# Copyright 2019 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""
Function:
Test mindinsight.datavisual.data_transform.data_loader.
Usage:
pytest tests/ut/datavisual
"""<import_stmt>os<import_stmt>shutil<import_stmt>tempfile<import_stmt>pytest<import_from_stmt>mindinsight.datavisual.common.exceptions SummaryLogPathInvalid<import_from_stmt>mindinsight.datavisual.data_transform data_loader<import_from_stmt>mindinsight.datavisual.data_transform.data_loader DataLoader<import_from_stmt>..mock MockLogger<class_stmt>TestDataLoader<block_start>"""Test data_loader."""<line_sep>@classmethod<def_stmt>setup_class cls<block_start>data_loader.logger=MockLogger<block_end><def_stmt>setup_method self<block_start>self._summary_dir=tempfile.mkdtemp()<if_stmt>os.path.exists(self._summary_dir)<block_start>shutil.rmtree(self._summary_dir)<block_end>os.mkdir(self._summary_dir)<block_end><def_stmt>teardown_method self<block_start><if_stmt>os.path.exists(self._summary_dir)<block_start>shutil.rmtree(self._summary_dir)<block_end><block_end><def_stmt>_generate_files self dir_path file_list<block_start><for_stmt>file_name file_list<block_start><with_stmt>open(os.path.join(dir_path file_name) 'w')<block_start><pass><block_end><block_end><block_end><def_stmt>test_load_with_not_file_list self<block_start>"""Test loading method with empty file list."""<line_sep>loader=DataLoader(self._summary_dir)<with_stmt>pytest.raises(SummaryLogPathInvalid)<block_start>loader.load()<block_end><assert_stmt>'No valid files can be loaded'<in>str(MockLogger.log_msg['warning'])<block_end><def_stmt>test_load_with_invalid_file_list self<block_start>"""Test loading method with valid path and invalid file_list."""<line_sep>file_list=['summary.abc01' 'summary.abc02']<line_sep>self._generate_files(self._summary_dir file_list)<line_sep>loader=DataLoader(self._summary_dir)<with_stmt>pytest.raises(SummaryLogPathInvalid)<block_start>loader.load()<block_end><assert_stmt>'No valid files can be loaded'<in>str(MockLogger.log_msg['warning'])<block_end><def_stmt>test_load_success self<block_start>"""Test loading method with valid path and file_list."""<line_sep>dir_path=tempfile.NamedTemporaryFile().name<if_stmt><not>os.path.exists(dir_path)<block_start>os.mkdir(dir_path)<block_end>file_list=['summary.001' 'summary.002']<line_sep>self._generate_files(dir_path file_list)<line_sep>dataloader=DataLoader(dir_path)<line_sep>dataloader.load()<assert_stmt>dataloader._loader<is><not><none><line_sep>shutil.rmtree(dir_path)<block_end><block_end> |
<import_stmt>pytest<import_from_stmt>django.conf settings<import_from_stmt>django.test Client<import_from_stmt>tests.factories TeamFactory TeamMemberFactory<import_from_stmt>tests.utils assert_viewname_redirect assert_viewname_status get_view_for_user validate_admin_or_participant_view validate_open_view <def_stmt>validate_owner_or_admin_view * two_challenge_set client:Client **kwargs<block_start>"""
Assert that a view is only accessible to administrators or participants
of that particular challenge.
"""<line_sep># No user
assert_viewname_redirect(redirect_url=settings.LOGIN_URL challenge=two_challenge_set.challenge_set_1.challenge client=client **kwargs )<line_sep>tests=[(403 two_challenge_set.challenge_set_1.non_participant) (200 two_challenge_set.challenge_set_1.participant) (403 two_challenge_set.challenge_set_1.participant1) (200 two_challenge_set.challenge_set_1.creator) (200 two_challenge_set.challenge_set_1.admin) (403 two_challenge_set.challenge_set_2.non_participant) (403 two_challenge_set.challenge_set_2.participant) (403 two_challenge_set.challenge_set_2.participant1) (403 two_challenge_set.challenge_set_2.creator) (403 two_challenge_set.challenge_set_2.admin) (200 two_challenge_set.admin12) (403 two_challenge_set.participant12) (200 two_challenge_set.admin1participant2) ]<for_stmt>test tests<block_start>assert_viewname_status(code=test[0] challenge=two_challenge_set.challenge_set_1.challenge client=client user=test[1] **kwargs )<block_end><block_end><def_stmt>validate_member_owner_or_admin_view * two_challenge_set client:Client **kwargs<block_start>"""
Assert that a view is only accessible to administrators or participants
of that particular challenge.
"""<line_sep># No user
assert_viewname_redirect(redirect_url=settings.LOGIN_URL challenge=two_challenge_set.challenge_set_1.challenge client=client **kwargs )<line_sep>tests=[(403 two_challenge_set.challenge_set_1.non_participant) (200 two_challenge_set.challenge_set_1.participant) (200 two_challenge_set.challenge_set_1.participant1) (200 two_challenge_set.challenge_set_1.creator) (200 two_challenge_set.challenge_set_1.admin) (403 two_challenge_set.challenge_set_2.non_participant) (403 two_challenge_set.challenge_set_2.participant) (403 two_challenge_set.challenge_set_2.participant1) (403 two_challenge_set.challenge_set_2.creator) (403 two_challenge_set.challenge_set_2.admin) (200 two_challenge_set.admin12) (403 two_challenge_set.participant12) (200 two_challenge_set.admin1participant2) ]<for_stmt>test tests<block_start>assert_viewname_status(code=test[0] challenge=two_challenge_set.challenge_set_1.challenge client=client user=test[1] **kwargs )<block_end><block_end>@pytest.mark.django_db@pytest.mark.parametrize("view" ["teams:list" "teams:create" "teams:member-create"])<def_stmt>test_admin_or_participant_permissions client two_challenge_sets view<block_start>team=TeamFactory(challenge=two_challenge_sets.challenge_set_1.challenge owner=two_challenge_sets.challenge_set_1.participant )<if_stmt>view<in>("teams:detail" "teams:member-create")<block_start>pk=team.pk<block_end><else_stmt><block_start>pk=<none><block_end>validate_admin_or_participant_view(viewname=view reverse_kwargs={"pk":pk} two_challenge_set=two_challenge_sets client=client )<block_end>@pytest.mark.django_db<def_stmt>test_open_views client challenge_set<block_start>team=TeamFactory(challenge=challenge_set.challenge owner=challenge_set.participant)<line_sep>validate_open_view(viewname="teams:detail" reverse_kwargs={"pk":team.pk} challenge_set=challenge_set client=client )<block_end>@pytest.mark.django_db@pytest.mark.parametrize("view" ["teams:update" "teams:delete"])<def_stmt>test_team_update_delete_permissions client two_challenge_sets view<block_start>team=TeamFactory(challenge=two_challenge_sets.challenge_set_1.challenge owner=two_challenge_sets.challenge_set_1.participant )<line_sep>TeamFactory(challenge=two_challenge_sets.challenge_set_1.challenge owner=two_challenge_sets.challenge_set_1.participant1 )<line_sep>validate_owner_or_admin_view(viewname=view reverse_kwargs={"pk":team.pk} two_challenge_set=two_challenge_sets client=client )<block_end>@pytest.mark.django_db<def_stmt>test_team_member_delete_permissions client two_challenge_sets<block_start>team=TeamFactory(challenge=two_challenge_sets.challenge_set_1.challenge owner=two_challenge_sets.challenge_set_1.participant )<line_sep>team_member=TeamMemberFactory(team=team user=two_challenge_sets.challenge_set_1.participant1)<line_sep>validate_member_owner_or_admin_view(viewname="teams:member-delete" reverse_kwargs={"pk":team_member.pk} two_challenge_set=two_challenge_sets client=client )<block_end>@pytest.mark.django_db@pytest.mark.parametrize("team_name" ["test_team_name"])<def_stmt>test_team_creation client two_challenge_sets team_name<block_start>response=get_view_for_user(viewname="teams:create" challenge=two_challenge_sets.challenge_set_1.challenge client=client method=client.post user=two_challenge_sets.challenge_set_1.participant data={"name":team_name} )<assert_stmt>response.status_code<eq>302<line_sep>response=get_view_for_user(url=response.url client=client user=two_challenge_sets.challenge_set_1.participant )<assert_stmt>response.status_code<eq>200<assert_stmt>team_name<in>response.rendered_content.lower()<block_end>@pytest.mark.django_db<def_stmt>test_team_member_addition client two_challenge_sets<block_start>team=TeamFactory(challenge=two_challenge_sets.challenge_set_1.challenge owner=two_challenge_sets.challenge_set_1.participant )<assert_stmt>two_challenge_sets.challenge_set_1.participant<in>team.get_members()<assert_stmt>(two_challenge_sets.challenge_set_1.participant1<not><in>team.get_members())<line_sep># Participant1 requests to join team
response=get_view_for_user(viewname="teams:member-create" challenge=two_challenge_sets.challenge_set_1.challenge client=client method=client.post user=two_challenge_sets.challenge_set_1.participant1 reverse_kwargs={"pk":team.pk} )<assert_stmt>(two_challenge_sets.challenge_set_1.participant1<in>team.get_members())<assert_stmt>response.status_code<eq>302<block_end>@pytest.mark.django_db<def_stmt>test_unique_membership client two_challenge_sets<block_start>team=TeamFactory(challenge=two_challenge_sets.challenge_set_1.challenge owner=two_challenge_sets.challenge_set_1.participant )<line_sep>team1=TeamFactory(challenge=two_challenge_sets.challenge_set_1.challenge owner=two_challenge_sets.challenge_set_1.participant1 )<line_sep># Try to create a new team, should be denied
response=get_view_for_user(viewname="teams:create" challenge=two_challenge_sets.challenge_set_1.challenge client=client method=client.post user=two_challenge_sets.challenge_set_1.participant data={"name":"thisteamshouldnotbecreated"} )<assert_stmt>response.status_code<eq>200<assert_stmt>("You are already a member of another team for this challenge"<in>response.rendered_content)<line_sep># Participant1 requests to join team, should be denied
response=get_view_for_user(viewname="teams:member-create" challenge=two_challenge_sets.challenge_set_1.challenge client=client method=client.post user=two_challenge_sets.challenge_set_1.participant1 reverse_kwargs={"pk":team.pk} )<assert_stmt>response.status_code<eq>200<assert_stmt>("You are already a member of another team for this challenge"<in>response.rendered_content)<line_sep># participant12 should be able to create a team in their challenge and join
# another team
response=get_view_for_user(viewname="teams:create" challenge=two_challenge_sets.challenge_set_2.challenge client=client method=client.post user=two_challenge_sets.participant12 data={"name":"thisteamshouldbecreated"} )<assert_stmt>response.status_code<eq>302<line_sep>response=get_view_for_user(viewname="teams:member-create" challenge=two_challenge_sets.challenge_set_1.challenge client=client method=client.post user=two_challenge_sets.participant12 reverse_kwargs={"pk":team.pk} )<assert_stmt>response.status_code<eq>302<assert_stmt>two_challenge_sets.participant12<in>team.get_members()<line_sep>response=get_view_for_user(viewname="teams:member-create" challenge=two_challenge_sets.challenge_set_1.challenge client=client method=client.post user=two_challenge_sets.participant12 reverse_kwargs={"pk":team1.pk} )<assert_stmt>response.status_code<eq>200<assert_stmt>("You are already a member of another team for this challenge"<in>response.rendered_content)<block_end> |
<import_stmt>unittest<import_from_stmt>programy.clients.events.console.config ConsoleConfiguration<import_from_stmt>programy.config.brain.dynamic BrainDynamicsConfiguration<import_from_stmt>programy.config.file.yaml_file YamlConfigurationFile<class_stmt>BrainDynamicsConfigurationTests(unittest.TestCase)<block_start><def_stmt>test_with_data self<block_start>yaml=YamlConfigurationFile()<line_sep>self.assertIsNotNone(yaml)<line_sep>yaml.load_from_text("""
brain:
dynamic:
variables:
gettime: programy.dynamic.variables.datetime.GetTime
sets:
number: programy.dynamic.sets.numeric.IsNumeric
roman: programy.dynamic.sets.roman.IsRomanNumeral
maps:
romantodec: programy.dynamic.maps.roman.MapRomanToDecimal
dectoroman: programy.dynamic.maps.roman.MapDecimalToRoman
""" ConsoleConfiguration() ".")<line_sep>brain_config=yaml.get_section("brain")<line_sep>dynamic_config=BrainDynamicsConfiguration()<line_sep>dynamic_config.load_config_section(yaml brain_config ".")<line_sep>self.assertEquals({'GETTIME':'programy.dynamic.variables.datetime.GetTime'} dynamic_config.dynamic_vars)<line_sep>self.assertEquals({'NUMBER':'programy.dynamic.sets.numeric.IsNumeric' 'ROMAN':'programy.dynamic.sets.roman.IsRomanNumeral'} dynamic_config.dynamic_sets)<line_sep>self.assertEquals({'ROMANTODEC':'programy.dynamic.maps.roman.MapRomanToDecimal' 'DECTOROMAN':'programy.dynamic.maps.roman.MapDecimalToRoman'} dynamic_config.dynamic_maps)<block_end><def_stmt>test_with_missing_vars_sets_maps self<block_start>yaml=YamlConfigurationFile()<line_sep>self.assertIsNotNone(yaml)<line_sep>yaml.load_from_text("""
brain:
dynamic:
""" ConsoleConfiguration() ".")<line_sep>brain_config=yaml.get_section("brain")<line_sep>dynamic_config=BrainDynamicsConfiguration()<line_sep>dynamic_config.load_config_section(yaml brain_config ".")<line_sep>self.assertEquals({} dynamic_config.dynamic_vars)<line_sep>self.assertEquals({} dynamic_config.dynamic_sets)<line_sep>self.assertEquals({} dynamic_config.dynamic_maps)<block_end><def_stmt>test_with_missing_vars_sets_maps2 self<block_start>yaml=YamlConfigurationFile()<line_sep>self.assertIsNotNone(yaml)<line_sep>yaml.load_from_text("""
brain:
dynamic:
something: else
""" ConsoleConfiguration() ".")<line_sep>brain_config=yaml.get_section("brain")<line_sep>dynamic_config=BrainDynamicsConfiguration()<line_sep>dynamic_config.load_config_section(yaml brain_config ".")<line_sep>self.assertEquals({} dynamic_config.dynamic_vars)<line_sep>self.assertEquals({} dynamic_config.dynamic_sets)<line_sep>self.assertEquals({} dynamic_config.dynamic_maps)<block_end><def_stmt>test_without_data self<block_start>yaml=YamlConfigurationFile()<line_sep>self.assertIsNotNone(yaml)<line_sep>yaml.load_from_text("""
brain:
dynamic:
""" ConsoleConfiguration() ".")<line_sep>brain_config=yaml.get_section("brain")<line_sep>dynamic_config=BrainDynamicsConfiguration()<line_sep>dynamic_config.load_config_section(yaml brain_config ".")<line_sep>self.assertEquals({} dynamic_config.dynamic_vars)<line_sep>self.assertEquals({} dynamic_config.dynamic_sets)<line_sep>self.assertEquals({} dynamic_config.dynamic_maps)<block_end><def_stmt>test_with_no_data self<block_start>yaml=YamlConfigurationFile()<line_sep>self.assertIsNotNone(yaml)<line_sep>yaml.load_from_text("""
brain:
""" ConsoleConfiguration() ".")<line_sep>brain_config=yaml.get_section("brain")<line_sep>dynamic_config=BrainDynamicsConfiguration()<line_sep>dynamic_config.load_config_section(yaml brain_config ".")<line_sep>self.assertEquals({} dynamic_config.dynamic_vars)<line_sep>self.assertEquals({} dynamic_config.dynamic_sets)<line_sep>self.assertEquals({} dynamic_config.dynamic_maps)<block_end><def_stmt>test_to_yaml_defaults self<block_start>yaml={}<line_sep>dynamic_config=BrainDynamicsConfiguration()<line_sep>dynamic_config.to_yaml(yaml defaults=<true>)<line_sep>self.assertEquals({'GETTIME':'programy.dynamic.variables.datetime.GetTime'} yaml['variables'])<line_sep>self.assertEquals({'NUMBER':'programy.dynamic.sets.numeric.IsNumeric' 'ROMAN':'programy.dynamic.sets.roman.IsRomanNumeral' 'STOPWORD':'programy.dynamic.sets.stopword.IsStopWord' 'SYNSETS':'programy.dynamic.sets.synsets.IsSynset'} yaml['sets'])<line_sep>self.assertEquals({'ROMANTODDEC':'programy.dynamic.maps.roman.MapRomanToDecimal' 'DECTOROMAN':'programy.dynamic.maps.roman.MapDecimalToRoman' 'LEMMATIZE':'programy.dynamic.maps.lemmatize.LemmatizeMap' 'STEMMER':'programy.dynamic.maps.stemmer.StemmerMap'} yaml['maps'])<block_end><def_stmt>test_to_yaml_no_defaults self<block_start>yaml=YamlConfigurationFile()<line_sep>self.assertIsNotNone(yaml)<line_sep>yaml.load_from_text("""
brain:
dynamic:
variables:
gettime: programy.dynamic.variables.datetime.GetTime
sets:
number: programy.dynamic.sets.numeric.IsNumeric
roman: programy.dynamic.sets.roman.IsRomanNumeral
maps:
romantodec: programy.dynamic.maps.roman.MapRomanToDecimal
dectoroman: programy.dynamic.maps.roman.MapDecimalToRoman
""" ConsoleConfiguration() ".")<line_sep>brain_config=yaml.get_section("brain")<line_sep>dynamic_config=BrainDynamicsConfiguration()<line_sep>dynamic_config.load_config_section(yaml brain_config ".")<line_sep>data={}<line_sep>dynamic_config.to_yaml(data defaults=<false>)<line_sep>self.assertEquals({'GETTIME':'programy.dynamic.variables.datetime.GetTime'} data['variables'])<line_sep>self.assertEquals({'NUMBER':'programy.dynamic.sets.numeric.IsNumeric' 'ROMAN':'programy.dynamic.sets.roman.IsRomanNumeral'} data['sets'])<line_sep>self.assertEquals({'ROMANTODEC':'programy.dynamic.maps.roman.MapRomanToDecimal' 'DECTOROMAN':'programy.dynamic.maps.roman.MapDecimalToRoman'} data['maps'])<block_end><def_stmt>test_to_yaml_no_defaults_no_data self<block_start>yaml={}<line_sep>dynamic_config=BrainDynamicsConfiguration()<line_sep>dynamic_config.to_yaml(yaml defaults=<false>)<line_sep>self.assertEquals({} yaml['variables'])<line_sep>self.assertEquals({} yaml['sets'])<line_sep>self.assertEquals({} yaml['maps'])<block_end><def_stmt>test_defaults self<block_start>dynamic_config=BrainDynamicsConfiguration()<line_sep>data={}<line_sep>dynamic_config.to_yaml(data <true>)<line_sep>BrainDynamicsConfigurationTests.assert_defaults(self data)<block_end>@staticmethod<def_stmt>assert_defaults test data<block_start>test.assertTrue('sets'<in>data)<line_sep>test.assertEqual(data['sets']['NUMBER'] 'programy.dynamic.sets.numeric.IsNumeric')<line_sep>test.assertEqual(data['sets']['ROMAN'] 'programy.dynamic.sets.roman.IsRomanNumeral')<line_sep>test.assertEqual(data['sets']['STOPWORD'] 'programy.dynamic.sets.stopword.IsStopWord')<line_sep>test.assertEqual(data['sets']['SYNSETS'] 'programy.dynamic.sets.synsets.IsSynset')<line_sep>test.assertTrue('maps'<in>data)<line_sep>test.assertEqual(data['maps']['ROMANTODDEC'] 'programy.dynamic.maps.roman.MapRomanToDecimal')<line_sep>test.assertEqual(data['maps']['DECTOROMAN'] 'programy.dynamic.maps.roman.MapDecimalToRoman')<line_sep>test.assertEqual(data['maps']['LEMMATIZE'] 'programy.dynamic.maps.lemmatize.LemmatizeMap')<line_sep>test.assertEqual(data['maps']['STEMMER'] 'programy.dynamic.maps.stemmer.StemmerMap')<line_sep>test.assertTrue('variables'<in>data)<line_sep>test.assertEqual(data['variables']['GETTIME'] 'programy.dynamic.variables.datetime.GetTime')<block_end><block_end> |
<import_from_stmt>django.db.models Manager<import_from_stmt>permissions.models ORGANISATION_PERMISSION_TYPE<class_stmt>OrganisationPermissionManager(Manager)<block_start><def_stmt>get_queryset self<block_start><return>super().get_queryset().filter(type=ORGANISATION_PERMISSION_TYPE)<block_end><block_end> |
<import_from_stmt>collections defaultdict<import_from_stmt>dataclasses dataclass<import_from_stmt>typing Dict List Optional<import_stmt>numpy<as>np<import_stmt>numpy.typing<as>npt<import_from_stmt>nuplan.common.actor_state.agent Agent<import_from_stmt>nuplan.common.actor_state.ego_state EgoState<import_from_stmt>nuplan.common.actor_state.vehicle_parameters get_pacifica_parameters<import_from_stmt>nuplan.common.geometry.compute signed_lateral_distance signed_longitudinal_distance<import_from_stmt>nuplan.planning.metrics.evaluation_metrics.base.metric_base MetricBase<import_from_stmt>nuplan.planning.metrics.metric_result MetricStatistics MetricStatisticsType Statistic TimeSeries<import_from_stmt>nuplan.planning.scenario_builder.abstract_scenario AbstractScenario<import_from_stmt>nuplan.planning.simulation.history.simulation_history SimulationHistory<import_from_stmt>nuplan.planning.simulation.observation.observation_type DetectionsTracks<line_sep>@dataclass<class_stmt>EgoAgentPair<block_start>"""Class to pair ego and agent."""<line_sep>ego_state:EgoState# Ego state
agent:Agent<block_end># Agent
@dataclass<class_stmt>EgoToAgentDistances<block_start>"""
Class to keep track of the history of projected distances from ego to an agent.
It also contains the length of the agent.
"""<line_sep>agent_lengths:List[float]# A list of Length of agents [m]
longitudinal_distances:List[float]# Longitudinal distance from ego to the agent [m]
lateral_distances:List[float]<block_end># Lateral distance from ego to the agent [m]
<class_stmt>ClearanceFromStaticAgentsStatistics(MetricBase)<block_start>"""Metric on clearance while passing static vehicles."""<def_stmt>__init__ self name:str category:str lateral_distance_threshold:float<arrow><none><block_start>"""
Initializes the ClearanceFromStaticAgentsStatistics class
:param name: Metric name
:param category: Metric category
:param lateral_distance_threshold: Agents laterally further away than this threshold are not considered.
"""<line_sep>super().__init__(name=name category=category)<line_sep>self._lateral_distance_threshold=lateral_distance_threshold<line_sep>self._ego_half_length=get_pacifica_parameters().half_length<block_end><def_stmt>compute_score self scenario:AbstractScenario metric_statistics:Dict[str Statistic] time_series:Optional[TimeSeries]=<none> <arrow>float<block_start>"""Inherited, see superclass."""<line_sep># TODO: Define the metric score
<return>0.0<block_end><def_stmt>compute self history:SimulationHistory scenario:AbstractScenario<arrow>List[MetricStatistics]<block_start>"""
Returns the estimated metric
:param history: History from a simulation engine
:param scenario: Scenario running this metric
:return the estimated metric.
"""<line_sep># Compute projected distances
agents_distances=self._extract_agent_projected_distances(history)<line_sep>clearances_during_passing=self._extract_passing_clearances(agents_distances)<if_stmt><not>clearances_during_passing<block_start><return>[]<block_end>statistics={MetricStatisticsType.MAX:Statistic(name='max_clearance_overtaking_static_agent' unit='meters' value=np.amax(clearances_during_passing)) MetricStatisticsType.MIN:Statistic(name='min_clearance_overtaking_static_agent' unit='meters' value=np.amin(clearances_during_passing)) MetricStatisticsType.P90:Statistic(name='p90_clearance_overtaking_static_agent' unit='meters' value=np.percentile(np.abs(clearances_during_passing) 90) ) }<line_sep>results=self._construct_metric_results(metric_statistics=statistics time_series=<none> scenario=scenario)<line_sep><return>results<block_end># type: ignore
<def_stmt>get_overtake_start_idx self longitudinal_dist:List[float] idx_overtake:int critical_dist_abs:float<arrow>int<block_start>"""
Finds the index of the element which represents the start of the overtake
:param longitudinal_dist: longitudinal distances
:param idx_overtake: index of the distance closest to zero
:param critical_dist_abs: critical distance which represent start of overtake
:return index of the start of overtake.
"""<line_sep>offset=self._get_overtake_edge(longitudinal_dist[idx_overtake::-1] critical_dist_abs)<line_sep><return>idx_overtake-offset<if>offset<is><not><none><else>0<block_end><def_stmt>get_overtake_end_idx self longitudinal_dist:List[float] idx_overtake:int critical_dist_abs:float<arrow>int<block_start>"""
Finds the index of the element which represents the end of the overtake
:param longitudinal_dist: longitudinal distances
:param idx_overtake: index of the distance closest to zero
:param critical_dist_abs: critical distance which represent end of overtake
:return index of the end of overtake.
"""<line_sep>offset=self._get_overtake_edge(longitudinal_dist[idx_overtake:] critical_dist_abs)<line_sep><return>idx_overtake+offset<if>offset<is><not><none><else>-1<block_end>@staticmethod<def_stmt>_get_overtake_edge distances:List[float] critical_distance:float<arrow>Optional[int]<block_start>"""
Finds the index of the first element which exceeds the given amount in a list
:param distances: list of distances
:param critical_distance: threshold distance
:return index of the first element exceeding the given amount, None if it doesn't happen.
"""<for_stmt>idx_start,d enumerate(distances)<block_start><if_stmt>abs(d)<g>critical_distance<block_start><return>idx_start<block_end><block_end><return><none><block_end><def_stmt>_extract_agent_projected_distances self history:SimulationHistory<arrow>Dict[str EgoToAgentDistances]<block_start>"""
Computes the projected distances, for inactive agents only
:param history: The history of the scenario
:return A dict containing the projected distances to each inactive track in the entire scenario.
"""<line_sep>agents_distances:Dict[str EgoToAgentDistances]={}<line_sep>inactive_agents_scenario=self._get_inactive_agents_scenario(history)<for_stmt>track_token,ego_agent_pairs inactive_agents_scenario.items()<block_start>lateral_dist=[signed_lateral_distance(ego_agent_pair.ego_state.rear_axle ego_agent_pair.agent.box.geometry)<for>ego_agent_pair ego_agent_pairs]<line_sep>longitudinal_dist=[signed_longitudinal_distance(ego_agent_pair.ego_state.rear_axle ego_agent_pair.agent.box.geometry)<for>ego_agent_pair ego_agent_pairs]<line_sep>lengths=[ego_agent_pair.agent.box.length<for>ego_agent_pair ego_agent_pairs]<line_sep>agents_distances[track_token]=EgoToAgentDistances(agent_lengths=lengths longitudinal_distances=longitudinal_dist lateral_distances=lateral_dist)<block_end><return>agents_distances<block_end><def_stmt>_extract_passing_clearances self agents_distances:Dict[str EgoToAgentDistances]<arrow>List[float]<block_start>"""
Extracts the portion of projected distances relative to the passing of every agent and saves them to a list
:param agents_distances: The projected distances to each inactive agent
:return A list containing the lateral clearance of all inactive agents while ego is passing them.
"""<line_sep>clearances_during_overtake=[]<for_stmt>distances agents_distances.values()<block_start>max_longitudinal_dist=max(distances.longitudinal_distances)<line_sep>idx_max=distances.longitudinal_distances.index(max_longitudinal_dist)<line_sep>min_longitudinal_dist=min(distances.longitudinal_distances)<line_sep>idx_min=distances.longitudinal_distances.index(min_longitudinal_dist)<if_stmt>max_longitudinal_dist<g>0<g>min_longitudinal_dist<and>idx_max<l>idx_min<block_start>overtake_idx=int(np.argmin(np.abs(distances.longitudinal_distances)))<if_stmt>abs(distances.lateral_distances[overtake_idx])<l>self._lateral_distance_threshold<block_start>threshold=self._ego_half_length+distances.agent_lengths[overtake_idx]/2.0<line_sep>start_idx=self.get_overtake_start_idx(distances.longitudinal_distances int(overtake_idx) threshold)<line_sep>end_idx=self.get_overtake_end_idx(distances.longitudinal_distances int(overtake_idx) threshold)<line_sep>clearances_during_overtake.extend(np.abs(distances.lateral_distances[start_idx:end_idx+1]))<block_end><block_end><block_end><return>clearances_during_overtake<block_end>@staticmethod<def_stmt>_get_inactive_agents_scenario history:SimulationHistory<arrow>Dict[str List[EgoAgentPair]]<block_start>"""
Get a set of agents which are inactive for the full length of the scenario
An inactive agents in this context is an agent that for the entire scenario never moves
:param history: The history from the scenario
:return A dict of inactive tracks and their ego poses with agents.
"""<line_sep># Collect a series of agents to their tracks
agent_tracks=defaultdict(list)<for_stmt>sample history.data<block_start>ego_state=sample.ego_state<if_stmt><not>isinstance(sample.observation DetectionsTracks)<block_start><continue><block_end><for_stmt>tracked_object sample.observation.tracked_objects.get_agents()<block_start>agent_tracks[tracked_object.track_token].append(EgoAgentPair(ego_state=ego_state agent=tracked_object))<block_end><block_end>inactive_track_agents=defaultdict(list)<for_stmt>track_token,ego_agent_pairs agent_tracks.items()<block_start>velocities:npt.NDArray[np.float64]=np.asarray([ego_agent_pair.agent.velocity.magnitude()<for>ego_agent_pair ego_agent_pairs])<line_sep>inactive_status=np.isclose(velocities 0.0)<line_sep># Must all inactive
<if_stmt>np.sum(inactive_status)<ne>len(velocities)<block_start><continue><block_end>inactive_track_agents[track_token]=ego_agent_pairs<block_end><return>inactive_track_agents<block_end><block_end> |
<def_stmt>_copy_cmd ctx file_list target_dir<block_start>dest_list=[]<if_stmt>file_list<eq><none><or>len(file_list)<eq>0<block_start><return>dest_list<block_end>shell_content=""<line_sep>batch_file_name="%s-copy-files.bat"%(ctx.label.name)<line_sep>bat=ctx.actions.declare_file(batch_file_name)<line_sep>src_file_list=[]<for_stmt>(src_file relative_dest_file) file_list<block_start>src_file_list.append(src_file)<line_sep>dest_file=ctx.actions.declare_file("{}/{}".format(target_dir relative_dest_file))<line_sep>dest_list.append(dest_file)<line_sep>shell_content<augadd>"@copy /Y \"%s\" \"%s\" >NUL\n"%(src_file.path.replace("/" "\\") dest_file.path.replace("/" "\\") )<block_end>ctx.actions.write(output=bat content=shell_content is_executable=<true> )<line_sep>ctx.actions.run(inputs=src_file_list tools=[bat] outputs=dest_list executable="cmd.exe" arguments=["/C" bat.path.replace("/" "\\")] mnemonic="CopyFile" progress_message="Copying files" use_default_shell_env=<true> )<line_sep><return>dest_list<block_end><def_stmt>_copy_bash ctx src_list target_dir<block_start>dest_list=[]<for_stmt>(src_file relative_dest_file) src_list<block_start>dest_file=ctx.actions.declare_file("{}/{}".format(target_dir relative_dest_file))<line_sep>dest_list.append(dest_file)<line_sep>ctx.actions.run_shell(tools=[src_file] outputs=[dest_file] command="cp -f \"$1\" \"$2\"" arguments=[src_file.path dest_file.path] mnemonic="CopyFile" progress_message="Copying files" use_default_shell_env=<true> )<block_end><return>dest_list<block_end><def_stmt>copy_files ctx file_list base_dest_directory is_windows<block_start>dest_list=[]<if_stmt>is_windows<block_start>dest_list=_copy_cmd(ctx file_list base_dest_directory)<block_end><else_stmt><block_start>dest_list=_copy_bash(ctx file_list base_dest_directory)<block_end><return>dest_list<block_end> |
<class_stmt>Enum(object)<block_start>@classmethod<def_stmt>parse cls value<block_start>options=cls.options()<line_sep>result=[]<for_stmt>k,v options.items()<block_start><if_stmt>type(v)<is><not>int<or>v<eq>0<block_start><continue><block_end><if_stmt>value<eq>0<or>(value&v)<eq>v<block_start>result.append(v)<block_end><block_end><return>result<block_end>@classmethod<def_stmt>options cls<block_start>result={}<for_stmt>key dir(cls)<block_start><if_stmt>key.startswith('_')<block_start><continue><block_end>result[key]=getattr(cls key)<block_end><return>result<block_end><block_end><class_stmt>Media(Enum)<block_start>All=0<line_sep>Movies=1<line_sep>Shows=2<line_sep>Seasons=4<line_sep>Episodes=8<line_sep>Lists=16<line_sep>__map__=<none><line_sep>@classmethod<def_stmt>get cls key<block_start><if_stmt>cls.__map__<is><none><block_start>cls.__map__={Media.Movies:'movies' Media.Shows:'shows' Media.Seasons:'seasons' Media.Episodes:'episodes' Media.Lists:'lists'}<block_end><return>cls.__map__.get(key)<block_end><block_end><class_stmt>Data(Enum)<block_start>All=0<line_sep>Collection=1<line_sep>Playback=2<line_sep>Ratings=4<line_sep>Watched=8<line_sep>Watchlist=16<line_sep># Lists
Liked=32<line_sep>Personal=64<line_sep>__attributes__=<none><line_sep>__map__=<none><line_sep>@classmethod<def_stmt>initialize cls<block_start><if_stmt>cls.__attributes__<block_start><return><block_end>cls.__attributes__={Data.Collection:{'interface':'sync/collection' 'timestamp':'collected_at'} Data.Playback:{'interface':'sync/playback' 'timestamp':'paused_at'} Data.Ratings:{'interface':'sync/ratings' 'timestamp':'rated_at'} Data.Watched:{'interface':'sync/watched' 'timestamp':'watched_at'} Data.Watchlist:{'interface':'sync/watchlist' 'timestamp':'watchlisted_at'} # Lists
Data.Liked:{'interface':'users/likes' 'timestamp':'updated_at'} Data.Personal:{'interface':'users/*/lists' 'timestamp':'updated_at'}}<block_end>@classmethod<def_stmt>get cls key<block_start><if_stmt>cls.__map__<is><none><block_start>cls.__map__={Data.Collection:'collection' Data.Playback:'playback' Data.Ratings:'ratings' Data.Watched:'watched' Data.Watchlist:'watchlist' # Lists
Data.Liked:'liked' Data.Personal:'personal'}<block_end><return>cls.__map__.get(key)<block_end>@classmethod<def_stmt>get_interface cls key<block_start><return>cls.get_attribute(key 'interface')<block_end>@classmethod<def_stmt>get_timestamp_key cls key<block_start><return>cls.get_attribute(key 'timestamp')<block_end>@classmethod<def_stmt>get_attribute cls key attribute<block_start>cls.initialize()<line_sep>attributes=cls.__attributes__.get(key)<if_stmt><not>attributes<block_start><return><none><block_end><return>attributes.get(attribute)<block_end><block_end> |
"""
Res2Net for ImageNet-1K, implemented in Gluon.
Original paper: 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
"""<line_sep>__all__=['Res2Net' 'res2net50_w14_s8' 'res2net50_w26_s8']<import_stmt>os<import_from_stmt>mxnet cpu<import_from_stmt>mxnet.gluon nn HybridBlock<import_from_stmt>mxnet.gluon.contrib.nn Identity<import_from_stmt>.common conv1x1 conv3x3 conv1x1_block<import_from_stmt>.resnet ResInitBlock<import_from_stmt>.preresnet PreResActivation<class_stmt>HierarchicalConcurrent(nn.HybridSequential)<block_start>"""
A container for hierarchical concatenation of blocks with parameters.
Parameters:
----------
axis : int, default 1
The axis on which to concatenate the outputs.
multi_input : bool, default False
Whether input is multiple.
"""<def_stmt>__init__ self axis=1 multi_input=<false> **kwargs<block_start>super(HierarchicalConcurrent self).__init__(**kwargs)<line_sep>self.axis=axis<line_sep>self.multi_input=multi_input<block_end><def_stmt>hybrid_forward self F x<block_start>out=[]<line_sep>y_prev=<none><if_stmt>self.multi_input<block_start>xs=F.split(x axis=self.axis num_outputs=len(self._children.values()))<block_end><for_stmt>i,block enumerate(self._children.values())<block_start><if_stmt>self.multi_input<block_start>y=block(xs[i])<block_end><else_stmt><block_start>y=block(x)<block_end><if_stmt>y_prev<is><not><none><block_start>y=y+y_prev<block_end>out.append(y)<line_sep>y_prev=y<block_end>out=F.concat(*out dim=self.axis)<line_sep><return>out<block_end><block_end><class_stmt>Res2NetUnit(HybridBlock)<block_start>"""
Res2Net unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
strides : int or tuple/list of 2 int
Strides of the branch convolution layers.
width : int
Width of filters.
scale : int
Number of scale.
bn_use_global_stats : bool
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
"""<def_stmt>__init__ self in_channels out_channels strides width scale bn_use_global_stats **kwargs<block_start>super(Res2NetUnit self).__init__(**kwargs)<line_sep>self.scale=scale<line_sep>downsample=(strides<ne>1)<line_sep>self.resize_identity=(in_channels<ne>out_channels)<or>downsample<line_sep>mid_channels=width<times>scale<line_sep>brn_channels=width<with_stmt>self.name_scope()<block_start>self.reduce_conv=conv1x1_block(in_channels=in_channels out_channels=mid_channels bn_use_global_stats=bn_use_global_stats)<line_sep>self.branches=HierarchicalConcurrent(axis=1 multi_input=<true> prefix="")<if_stmt>downsample<block_start>self.branches.add(conv1x1(in_channels=brn_channels out_channels=brn_channels strides=strides))<block_end><else_stmt><block_start>self.branches.add(Identity())<block_end><for_stmt>i range(scale-1)<block_start>self.branches.add(conv3x3(in_channels=brn_channels out_channels=brn_channels strides=strides))<block_end>self.preactiv=PreResActivation(in_channels=mid_channels)<line_sep>self.merge_conv=conv1x1_block(in_channels=mid_channels out_channels=out_channels bn_use_global_stats=bn_use_global_stats activation=<none>)<if_stmt>self.resize_identity<block_start>self.identity_conv=conv1x1_block(in_channels=in_channels out_channels=out_channels strides=strides bn_use_global_stats=bn_use_global_stats activation=<none>)<block_end>self.activ=nn.Activation("relu")<block_end><block_end><def_stmt>hybrid_forward self F x<block_start><if_stmt>self.resize_identity<block_start>identity=self.identity_conv(x)<block_end><else_stmt><block_start>identity=x<block_end>y=self.reduce_conv(x)<line_sep>y=self.branches(y)<line_sep>y=self.preactiv(y)<line_sep>y=self.merge_conv(y)<line_sep>y=y+identity<line_sep>y=self.activ(y)<line_sep><return>y<block_end><block_end><class_stmt>Res2Net(HybridBlock)<block_start>"""
Res2Net model from 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
width : int
Width of filters.
scale : int
Number of scale.
bn_use_global_stats : bool, default False
Whether global moving statistics is used instead of local batch-norm for BatchNorm layers.
Useful for fine-tuning.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
classes : int, default 1000
Number of classification classes.
"""<def_stmt>__init__ self channels init_block_channels width scale bn_use_global_stats=<false> in_channels=3 in_size=(224 224) classes=1000 **kwargs<block_start>super(Res2Net self).__init__(**kwargs)<line_sep>self.in_size=in_size<line_sep>self.classes=classes<with_stmt>self.name_scope()<block_start>self.features=nn.HybridSequential(prefix="")<line_sep>self.features.add(ResInitBlock(in_channels=in_channels out_channels=init_block_channels bn_use_global_stats=bn_use_global_stats))<line_sep>in_channels=init_block_channels<for_stmt>i,channels_per_stage enumerate(channels)<block_start>stage=nn.HybridSequential(prefix="stage{}_".format(i+1))<with_stmt>stage.name_scope()<block_start><for_stmt>j,out_channels enumerate(channels_per_stage)<block_start>strides=2<if>(j<eq>0)<and>(i<ne>0)<else>1<line_sep>stage.add(Res2NetUnit(in_channels=in_channels out_channels=out_channels strides=strides width=width scale=scale bn_use_global_stats=bn_use_global_stats))<line_sep>in_channels=out_channels<block_end><block_end>self.features.add(stage)<block_end>self.features.add(nn.AvgPool2D(pool_size=7 strides=1))<line_sep>self.output=nn.HybridSequential(prefix="")<line_sep>self.output.add(nn.Flatten())<line_sep>self.output.add(nn.Dense(units=classes in_units=in_channels))<block_end><block_end><def_stmt>hybrid_forward self F x<block_start>x=self.features(x)<line_sep>x=self.output(x)<line_sep><return>x<block_end><block_end><def_stmt>get_res2net blocks width scale model_name=<none> pretrained=<false> ctx=cpu() root=os.path.join("~" ".mxnet" "models") **kwargs<block_start>"""
Create Res2Net model with specific parameters.
Parameters:
----------
blocks : int
Number of blocks.
width : int
Width of filters.
scale : int
Number of scale.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""<line_sep>bottleneck=<true><if_stmt>blocks<eq>50<block_start>layers=[3 4 6 3]<block_end><elif_stmt>blocks<eq>101<block_start>layers=[3 4 23 3]<block_end><elif_stmt>blocks<eq>152<block_start>layers=[3 8 36 3]<block_end><else_stmt><block_start><raise>ValueError("Unsupported Res2Net with number of blocks: {}".format(blocks))<block_end><assert_stmt>(sum(layers)<times>3+2<eq>blocks)<line_sep>init_block_channels=64<line_sep>channels_per_layers=[64 128 256 512]<if_stmt>bottleneck<block_start>bottleneck_factor=4<line_sep>channels_per_layers=[ci<times>bottleneck_factor<for>ci channels_per_layers]<block_end>channels=[[ci]<times>li<for>(ci li) zip(channels_per_layers layers)]<line_sep>net=Res2Net(channels=channels init_block_channels=init_block_channels width=width scale=scale **kwargs)<if_stmt>pretrained<block_start><if_stmt>(model_name<is><none>)<or>(<not>model_name)<block_start><raise>ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")<block_end><import_from_stmt>.model_store get_model_file<line_sep>net.load_parameters(filename=get_model_file(model_name=model_name local_model_store_dir_path=root) ctx=ctx)<block_end><return>net<block_end><def_stmt>res2net50_w14_s8 **kwargs<block_start>"""
Res2Net-50 (14wx8s) model from 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""<line_sep><return>get_res2net(blocks=50 width=14 scale=8 model_name="res2net50_w14_s8" **kwargs)<block_end><def_stmt>res2net50_w26_s8 **kwargs<block_start>"""
Res2Net-50 (26wx8s) model from 'Res2Net: A New Multi-scale Backbone Architecture,' https://arxiv.org/abs/1904.01169.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, default '~/.mxnet/models'
Location for keeping the model parameters.
"""<line_sep><return>get_res2net(blocks=50 width=26 scale=8 model_name="res2net50_w14_s8" **kwargs)<block_end><def_stmt>_test <block_start><import_stmt>numpy<as>np<import_stmt>mxnet<as>mx<line_sep>pretrained=<false><line_sep>models=[res2net50_w14_s8 res2net50_w26_s8 ]<for_stmt>model models<block_start>net=model(pretrained=pretrained)<line_sep>ctx=mx.cpu()<if_stmt><not>pretrained<block_start>net.initialize(ctx=ctx)<block_end># net.hybridize()
net_params=net.collect_params()<line_sep>weight_count=0<for_stmt>param net_params.values()<block_start><if_stmt>(param.shape<is><none>)<or>(<not>param._differentiable)<block_start><continue><block_end>weight_count<augadd>np.prod(param.shape)<block_end>print("m={}, {}".format(model.__name__ weight_count))<assert_stmt>(model<ne>res2net50_w14_s8<or>weight_count<eq>8231732)<assert_stmt>(model<ne>res2net50_w26_s8<or>weight_count<eq>11432660)<line_sep>x=mx.nd.zeros((1 3 224 224) ctx=ctx)<line_sep>y=net(x)<assert_stmt>(y.shape<eq>(1 1000))<block_end><block_end><if_stmt>__name__<eq>"__main__"<block_start>_test()<block_end> |
<import_from_stmt>detectors.detectsecrets DetectSecrets<import_from_stmt>detectors.gitsecrets GitSecrets<import_from_stmt>detectors.trufflehog TruffleHog<line_sep># TODO: Turn this into a registry to match the notifiers pattern?
AvailableDetectors={'detect-secrets':DetectSecrets 'git-secrets':GitSecrets 'trufflehog':TruffleHog}<line_sep> |
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/SpecimenDefinition
Release: R4
Version: 4.0.1
Build ID: 9346c8cc45
Last updated: 2019-11-01T09:29:23.356+11:00
"""<import_from_stmt>pydantic.validators bytes_validator# noqa: F401
<import_from_stmt>.. fhirtypes# noqa: F401
<import_from_stmt>.. specimendefinition<def_stmt>impl_specimendefinition_1 inst<block_start><assert_stmt>inst.id<eq>"2364"<assert_stmt>inst.meta.tag[0].code<eq>"HTEST"<assert_stmt>inst.meta.tag[0].display<eq>"test health data"<assert_stmt>(inst.meta.tag[0].system<eq>"http://terminology.hl7.org/CodeSystem/v3-ActReason")<assert_stmt>inst.patientPreparation[0].text<eq>"12 hour fasting"<assert_stmt>inst.patientPreparation[1].coding[0].code<eq>"263678003"<assert_stmt>inst.patientPreparation[1].coding[0].display<eq>"At rest"<assert_stmt>inst.patientPreparation[1].coding[0].system<eq>"http://snomed.info/sct"<assert_stmt>inst.text.status<eq>"generated"<assert_stmt>inst.timeAspect<eq>"preferrably morning time"<assert_stmt>inst.typeCollected.coding[0].code<eq>"122555007"<assert_stmt>inst.typeCollected.coding[0].display<eq>"Venous blood specimen"<assert_stmt>inst.typeCollected.coding[0].system<eq>"http://snomed.info/sct"<assert_stmt>inst.typeTested[0].container.cap.coding[0].code<eq>"yellow"<assert_stmt>inst.typeTested[0].container.cap.coding[0].display<eq>"yellow cap"<assert_stmt>(inst.typeTested[0].container.cap.coding[0].system<eq>"urn:iso:std:iso:6710:2017")<assert_stmt>inst.typeTested[0].container.material.coding[0].code<eq>"61088005"<assert_stmt>inst.typeTested[0].container.material.coding[0].display<eq>"plastic"<assert_stmt>(inst.typeTested[0].container.material.coding[0].system<eq>"http://snomed.info/sct")<assert_stmt>inst.typeTested[0].container.minimumVolumeQuantity.code<eq>"mL"<assert_stmt>(inst.typeTested[0].container.minimumVolumeQuantity.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[0].container.minimumVolumeQuantity.unit<eq>"ml"<assert_stmt>float(inst.typeTested[0].container.minimumVolumeQuantity.value)<eq>float(2)<assert_stmt>inst.typeTested[0].container.type.coding[0].code<eq>"702281005"<assert_stmt>inst.typeTested[0].container.type.coding[0].display<eq>("Evacuated blood collection tube, thrombin/clot activator/gel"<concat>" separator")<assert_stmt>(inst.typeTested[0].container.type.coding[0].system<eq>"http://snomed.info/sct")<assert_stmt>inst.typeTested[0].handling[0].maxDuration.code<eq>"min"<assert_stmt>(inst.typeTested[0].handling[0].maxDuration.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[0].handling[0].maxDuration.unit<eq>"minute"<assert_stmt>float(inst.typeTested[0].handling[0].maxDuration.value)<eq>float(60)<assert_stmt>(inst.typeTested[0].handling[0].temperatureQualifier.text<eq>"Ambient temperature")<assert_stmt>inst.typeTested[0].handling[0].temperatureRange.high.code<eq>"Cel"<assert_stmt>(inst.typeTested[0].handling[0].temperatureRange.high.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[0].handling[0].temperatureRange.high.unit<eq>"°C"<assert_stmt>float(inst.typeTested[0].handling[0].temperatureRange.high.value)<eq>float(25)<assert_stmt>inst.typeTested[0].handling[0].temperatureRange.low.code<eq>"Cel"<assert_stmt>(inst.typeTested[0].handling[0].temperatureRange.low.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[0].handling[0].temperatureRange.low.unit<eq>"°C"<assert_stmt>float(inst.typeTested[0].handling[0].temperatureRange.low.value)<eq>float(15)<assert_stmt>inst.typeTested[0].handling[1].maxDuration.code<eq>"h"<assert_stmt>(inst.typeTested[0].handling[1].maxDuration.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[0].handling[1].maxDuration.unit<eq>"hour"<assert_stmt>float(inst.typeTested[0].handling[1].maxDuration.value)<eq>float(8)<assert_stmt>(inst.typeTested[0].handling[1].temperatureQualifier.text<eq>"Refrigerated temperature")<assert_stmt>inst.typeTested[0].handling[1].temperatureRange.high.code<eq>"Cel"<assert_stmt>(inst.typeTested[0].handling[1].temperatureRange.high.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[0].handling[1].temperatureRange.high.unit<eq>"°C"<assert_stmt>float(inst.typeTested[0].handling[1].temperatureRange.high.value)<eq>float(8)<assert_stmt>inst.typeTested[0].handling[1].temperatureRange.low.code<eq>"Cel"<assert_stmt>(inst.typeTested[0].handling[1].temperatureRange.low.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[0].handling[1].temperatureRange.low.unit<eq>"°C"<assert_stmt>float(inst.typeTested[0].handling[1].temperatureRange.low.value)<eq>float(2)<assert_stmt>inst.typeTested[0].preference<eq>"preferred"<assert_stmt>inst.typeTested[0].type.coding[0].code<eq>"119364003"<assert_stmt>inst.typeTested[0].type.coding[0].display<eq>"Serum specimen"<assert_stmt>inst.typeTested[0].type.coding[0].system<eq>"http://snomed.info/sct"<assert_stmt>inst.typeTested[1].container.cap.coding[0].code<eq>"green"<assert_stmt>inst.typeTested[1].container.cap.coding[0].display<eq>"green cap"<assert_stmt>(inst.typeTested[1].container.cap.coding[0].system<eq>"urn:iso:std:iso:6710:2017")<assert_stmt>inst.typeTested[1].container.material.coding[0].code<eq>"32039001"<assert_stmt>inst.typeTested[1].container.material.coding[0].display<eq>"glass"<assert_stmt>(inst.typeTested[1].container.material.coding[0].system<eq>"http://snomed.info/sct")<assert_stmt>inst.typeTested[1].container.minimumVolumeQuantity.code<eq>"mL"<assert_stmt>(inst.typeTested[1].container.minimumVolumeQuantity.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[1].container.minimumVolumeQuantity.unit<eq>"ml"<assert_stmt>float(inst.typeTested[1].container.minimumVolumeQuantity.value)<eq>float(2)<assert_stmt>inst.typeTested[1].container.type.coding[0].code<eq>"767390000"<assert_stmt>inst.typeTested[1].container.type.coding[0].display<eq>("Evacuated blood collection tube with heparin lithium and gel"<concat>" separator")<assert_stmt>(inst.typeTested[1].container.type.coding[0].system<eq>"http://snomed.info/sct")<assert_stmt>inst.typeTested[1].handling[0].maxDuration.code<eq>"min"<assert_stmt>(inst.typeTested[1].handling[0].maxDuration.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[1].handling[0].maxDuration.unit<eq>"minute"<assert_stmt>float(inst.typeTested[1].handling[0].maxDuration.value)<eq>float(60)<assert_stmt>(inst.typeTested[1].handling[0].temperatureQualifier.text<eq>"Ambient temperature")<assert_stmt>inst.typeTested[1].handling[0].temperatureRange.high.code<eq>"Cel"<assert_stmt>(inst.typeTested[1].handling[0].temperatureRange.high.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[1].handling[0].temperatureRange.high.unit<eq>"°C"<assert_stmt>float(inst.typeTested[1].handling[0].temperatureRange.high.value)<eq>float(25)<assert_stmt>inst.typeTested[1].handling[0].temperatureRange.low.code<eq>"Cel"<assert_stmt>(inst.typeTested[1].handling[0].temperatureRange.low.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[1].handling[0].temperatureRange.low.unit<eq>"°C"<assert_stmt>float(inst.typeTested[1].handling[0].temperatureRange.low.value)<eq>float(15)<assert_stmt>inst.typeTested[1].handling[1].maxDuration.code<eq>"h"<assert_stmt>(inst.typeTested[1].handling[1].maxDuration.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[1].handling[1].maxDuration.unit<eq>"hour"<assert_stmt>float(inst.typeTested[1].handling[1].maxDuration.value)<eq>float(8)<assert_stmt>(inst.typeTested[1].handling[1].temperatureQualifier.text<eq>"Refrigerated temperature")<assert_stmt>inst.typeTested[1].handling[1].temperatureRange.high.code<eq>"Cel"<assert_stmt>(inst.typeTested[1].handling[1].temperatureRange.high.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[1].handling[1].temperatureRange.high.unit<eq>"°C"<assert_stmt>float(inst.typeTested[1].handling[1].temperatureRange.high.value)<eq>float(8)<assert_stmt>inst.typeTested[1].handling[1].temperatureRange.low.code<eq>"Cel"<assert_stmt>(inst.typeTested[1].handling[1].temperatureRange.low.system<eq>"http://unitsofmeasure.org")<assert_stmt>inst.typeTested[1].handling[1].temperatureRange.low.unit<eq>"°C"<assert_stmt>float(inst.typeTested[1].handling[1].temperatureRange.low.value)<eq>float(2)<assert_stmt>inst.typeTested[1].preference<eq>"alternate"<assert_stmt>inst.typeTested[1].rejectionCriterion[0].coding[0].code<eq>"insufficient"<assert_stmt>(inst.typeTested[1].rejectionCriterion[0].coding[0].display<eq>"insufficient specimen volume")<assert_stmt>(inst.typeTested[1].rejectionCriterion[0].coding[0].system<eq>"http://terminology.hl7.org/CodeSystem/rejection-criteria")<assert_stmt>inst.typeTested[1].rejectionCriterion[1].coding[0].code<eq>"hemolized"<assert_stmt>(inst.typeTested[1].rejectionCriterion[1].coding[0].display<eq>"hemolized specimen")<assert_stmt>(inst.typeTested[1].rejectionCriterion[1].coding[0].system<eq>"http://terminology.hl7.org/CodeSystem/rejection-criteria")<assert_stmt>inst.typeTested[1].type.coding[0].code<eq>"119361006"<assert_stmt>inst.typeTested[1].type.coding[0].display<eq>"Plasma specimen"<assert_stmt>inst.typeTested[1].type.coding[0].system<eq>"http://snomed.info/sct"<block_end><def_stmt>test_specimendefinition_1 base_settings<block_start>"""No. 1 tests collection for SpecimenDefinition.
Test File: specimendefinition-example-serum-plasma.json
"""<line_sep>filename=(base_settings["unittest_data_dir"]/"specimendefinition-example-serum-plasma.json")<line_sep>inst=specimendefinition.SpecimenDefinition.parse_file(filename content_type="application/json" encoding="utf-8")<assert_stmt>"SpecimenDefinition"<eq>inst.resource_type<line_sep>impl_specimendefinition_1(inst)<line_sep># testing reverse by generating data from itself and create again.
data=inst.dict()<assert_stmt>"SpecimenDefinition"<eq>data["resourceType"]<line_sep>inst2=specimendefinition.SpecimenDefinition(**data)<line_sep>impl_specimendefinition_1(inst2)<block_end> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.