uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2ec85cb9ed62089e4d61aacf | train | function | def test_record_update(app_static, app_live):
"""Update one record value and validate the updated data returned in the
response."""
time.sleep(SLEEP_TIME)
record = dict(app_live.get(OBJ)[0])
update_value = "0.00" if record[UPDATE_KEY] != "0.00" else "1.00"
data = {"id": record["id"], UPDATE_KEY:... | def test_record_update(app_static, app_live):
| """Update one record value and validate the updated data returned in the
response."""
time.sleep(SLEEP_TIME)
record = dict(app_live.get(OBJ)[0])
update_value = "0.00" if record[UPDATE_KEY] != "0.00" else "1.00"
data = {"id": record["id"], UPDATE_KEY: update_value}
record_updated = app_live.r... | assert record1["id"] == record2["id"]
time.sleep(SLEEP_TIME)
# delete
response = app_live.record(method="delete", data={"id": record2["id"]}, obj=OBJ,)
assert response["delete"]
def test_record_update(app_static, app_live):
| 63 | 64 | 120 | 10 | 53 | gabcoyne/knackpy | tests/test_app.py | Python | test_record_update | test_record_update | 235 | 243 | 235 | 235 | aca6809b9c1fc50cc7906354c8ed04580ea57c3f | bigcode/the-stack | train |
1be2dad3a8600b7466d95e9a | train | function | def test_get_view_by_key_live(app_live):
assert app_live.get("view_11")
| def test_get_view_by_key_live(app_live):
| assert app_live.get("view_11")
| test_object_get_by_key_static(app_static):
assert app_static.get(OBJ)
def test_get_object_by_key_live(app_live):
assert app_live.get(OBJ)
def test_view_by_key_static(app_static):
assert app_static.get("view_11")
def test_get_view_by_key_live(app_live):
| 64 | 64 | 20 | 10 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_view_by_key_live | test_get_view_by_key_live | 102 | 103 | 102 | 102 | ce9d4f18df7b03d3ebc514f2d367ec2ce2527c48 | bigcode/the-stack | train |
43dd042bc231e534ba93060b | train | function | def test_get_records_by_object_name(app_static):
assert app_static.get("orders")
| def test_get_records_by_object_name(app_static):
| assert app_static.get("orders")
| _live.get(OBJ, filters=FILTERS)
assert len(records) == 1
def test_get_view_records_with_filters(app_live):
records = app_live.get("view_11", filters=FILTERS)
assert len(records) == 1
def test_get_records_by_object_name(app_static):
| 64 | 64 | 18 | 10 | 53 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_records_by_object_name | test_get_records_by_object_name | 139 | 140 | 139 | 139 | f6399269413516eb5a53c7248239a371a6a81dc5 | bigcode/the-stack | train |
16639cc8099dfdf85d0d6993 | train | function | def test_update_record_state_update(app_static):
record_id = app_static.get(OBJ)[0]["id"]
fake_data = {"id": record_id}
app_static._update_record_state(fake_data, OBJ, "update")
assert (
len(
[
record
for record in app_static.data[OBJ]
... | def test_update_record_state_update(app_static):
| record_id = app_static.get(OBJ)[0]["id"]
fake_data = {"id": record_id}
app_static._update_record_state(fake_data, OBJ, "update")
assert (
len(
[
record
for record in app_static.data[OBJ]
if record["id"] == fake_data["id"]
]
... | records = list(app_static.get(OBJ))
fake_data = app_static.data.get(OBJ)[0]
app_static._update_record_state(fake_data, OBJ, "create")
assert len(app_static.get(OBJ)) == len(records) + 1
def test_update_record_state_update(app_static):
| 64 | 64 | 92 | 9 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_update_record_state_update | test_update_record_state_update | 263 | 276 | 263 | 263 | 0ceac91df60d0cb8415f8d073b4e01c5bf71e3c4 | bigcode/the-stack | train |
a79258b7a273247268737f79 | train | function | @pytest.fixture
def app_data():
with open("tests/_metadata.json", "r") as fin:
metadata = json.loads(fin.read())
with open("tests/_all_fields.json", "r") as fin:
data = json.loads(fin.read())
data = data["records"]
return {"data": data, "metadata": metadata}
| @pytest.fixture
def app_data():
| with open("tests/_metadata.json", "r") as fin:
metadata = json.loads(fin.read())
with open("tests/_all_fields.json", "r") as fin:
data = json.loads(fin.read())
data = data["records"]
return {"data": data, "metadata": metadata}
| ": OBJ,
"file_field": "field_17",
"image_field": "field_18",
}
# we're trying to randomize sleep time across three+ concurrent tests of this package
# via github workflows
SLEEP_TIME = random.random() * 3
@pytest.fixture
def app_data():
| 64 | 64 | 73 | 7 | 56 | gabcoyne/knackpy | tests/test_app.py | Python | app_data | app_data | 39 | 48 | 39 | 40 | e11c53a8f4b1e0c14ea3b5b28b81394d51ca83fd | bigcode/the-stack | train |
e2052efe27f0d06709b972ef | train | function | def test_update_record_state_create(app_static):
records = list(app_static.get(OBJ))
fake_data = app_static.data.get(OBJ)[0]
app_static._update_record_state(fake_data, OBJ, "create")
assert len(app_static.get(OBJ)) == len(records) + 1
| def test_update_record_state_create(app_static):
| records = list(app_static.get(OBJ))
fake_data = app_static.data.get(OBJ)[0]
app_static._update_record_state(fake_data, OBJ, "create")
assert len(app_static.get(OBJ)) == len(records) + 1
| _live.record(method="create", data={}, obj=OBJ)
assert new_record
time.sleep(SLEEP_TIME)
response = app_live.record(method="delete", data={"id": new_record["id"]}, obj=OBJ,)
assert response["delete"]
def test_update_record_state_create(app_static):
| 63 | 64 | 64 | 9 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_update_record_state_create | test_update_record_state_create | 256 | 260 | 256 | 256 | f9e2db69eafa3521c0a9694b43ed451320b98c9c | bigcode/the-stack | train |
bb5620974d73211ba15cd54c | train | function | def test_over_the_wire_construction_with_slug(app_live):
assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY, slug="atd")
| def test_over_the_wire_construction_with_slug(app_live):
| assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY, slug="atd")
| , not side-loaded)
return knackpy.app.App(app_id=APP_ID, api_key=API_KEY)
def test_basic_over_the_wire_construction(app_live):
assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY)
def test_over_the_wire_construction_with_slug(app_live):
| 64 | 64 | 35 | 12 | 52 | gabcoyne/knackpy | tests/test_app.py | Python | test_over_the_wire_construction_with_slug | test_over_the_wire_construction_with_slug | 73 | 74 | 73 | 73 | f07c99637d88618985c6deeee4def7b8d8406a9d | bigcode/the-stack | train |
ad77028482922d60953cea15 | train | function | def test_constructor_fail_missing_app_id(app_static):
with pytest.raises(TypeError):
knackpy.app.App()
| def test_constructor_fail_missing_app_id(app_static):
| with pytest.raises(TypeError):
knackpy.app.App()
| (app_live):
assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY, slug="atd")
def test_basic_static_app_construction(app_static):
assert app_static
def test_app_repr(app_static):
assert repr(app_static)
def test_constructor_fail_missing_app_id(app_static):
| 64 | 64 | 23 | 10 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_constructor_fail_missing_app_id | test_constructor_fail_missing_app_id | 85 | 87 | 85 | 85 | 7f63638a6afcc5f5439d1f29b2c191229e182338 | bigcode/the-stack | train |
d9199491ca3599cf50bad077 | train | function | def test_view_by_key_static(app_static):
assert app_static.get("view_11")
| def test_view_by_key_static(app_static):
| assert app_static.get("view_11")
| _missing_app_id(app_static):
with pytest.raises(TypeError):
knackpy.app.App()
def test_object_get_by_key_static(app_static):
assert app_static.get(OBJ)
def test_get_object_by_key_live(app_live):
assert app_live.get(OBJ)
def test_view_by_key_static(app_static):
| 64 | 64 | 19 | 9 | 55 | gabcoyne/knackpy | tests/test_app.py | Python | test_view_by_key_static | test_view_by_key_static | 98 | 99 | 98 | 98 | b4e2e3b371e229ad4b067167b0457b48b0023453 | bigcode/the-stack | train |
d75d90cfcfd5aea8514f8c97 | train | function | def test_app_repr(app_static):
assert repr(app_static)
| def test_app_repr(app_static):
| assert repr(app_static)
| , api_key=API_KEY)
def test_over_the_wire_construction_with_slug(app_live):
assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY, slug="atd")
def test_basic_static_app_construction(app_static):
assert app_static
def test_app_repr(app_static):
| 64 | 64 | 13 | 7 | 56 | gabcoyne/knackpy | tests/test_app.py | Python | test_app_repr | test_app_repr | 81 | 82 | 81 | 81 | 948ac9a86f94267b152c0d7baf3a2a24e84802d9 | bigcode/the-stack | train |
bbb0defd431a2512ebb03741 | train | function | def test_update_record_state_delete(app_static):
record_id = app_static.get(OBJ)[0]["id"]
fake_data = {"delete": True}
app_static._update_record_state(fake_data, OBJ, "delete", record_id=record_id)
assert (
len([record for record in app_static.records[OBJ] if record["id"] == record_id])
... | def test_update_record_state_delete(app_static):
| record_id = app_static.get(OBJ)[0]["id"]
fake_data = {"delete": True}
app_static._update_record_state(fake_data, OBJ, "delete", record_id=record_id)
assert (
len([record for record in app_static.records[OBJ] if record["id"] == record_id])
== 0
)
| update_record_state(fake_data, OBJ, "update")
assert (
len(
[
record
for record in app_static.data[OBJ]
if record["id"] == fake_data["id"]
]
)
== 1
)
def test_update_record_state_delete(app_static):
| 64 | 64 | 85 | 9 | 55 | gabcoyne/knackpy | tests/test_app.py | Python | test_update_record_state_delete | test_update_record_state_delete | 279 | 286 | 279 | 279 | bee34460799f46362acff2f330385666ddbc6ca5 | bigcode/the-stack | train |
c126d4bfc61e4c08eb52df04 | train | function | def test_get_view_records_with_filters(app_live):
records = app_live.get("view_11", filters=FILTERS)
assert len(records) == 1
| def test_get_view_records_with_filters(app_live):
| records = app_live.get("view_11", filters=FILTERS)
assert len(records) == 1
| .HTTPError):
app_static.api_key = None
app_static.get(OBJ, refresh=True)
def test_get_object_records_with_filters(app_live):
records = app_live.get(OBJ, filters=FILTERS)
assert len(records) == 1
def test_get_view_records_with_filters(app_live):
| 64 | 64 | 35 | 10 | 53 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_view_records_with_filters | test_get_view_records_with_filters | 134 | 136 | 134 | 134 | 037647957082d05a3dad50fa01c5592489e56077 | bigcode/the-stack | train |
60fb1dcc465bad6063f0a8cd | train | function | def test_invalid_tzinfo(app_data):
with pytest.raises(ValueError):
assert knackpy.app.App(
app_id=app_data["metadata"]["application"]["id"],
metadata=app_data["metadata"],
tzinfo="Austin, Texas",
)
| def test_invalid_tzinfo(app_data):
| with pytest.raises(ValueError):
assert knackpy.app.App(
app_id=app_data["metadata"]["application"]["id"],
metadata=app_data["metadata"],
tzinfo="Austin, Texas",
)
| _fields_test"), types.GeneratorType)
def test_valid_tzinfo(app_data):
assert knackpy.app.App(
app_id=app_data["metadata"]["application"]["id"],
metadata=app_data["metadata"],
tzinfo="US/Eastern",
)
def test_invalid_tzinfo(app_data):
| 64 | 64 | 54 | 9 | 55 | gabcoyne/knackpy | tests/test_app.py | Python | test_invalid_tzinfo | test_invalid_tzinfo | 180 | 186 | 180 | 180 | bf05975d1925a1243a4e60c3c092db25b01e40e1 | bigcode/the-stack | train |
9cf6c9dfa67fd8dc411ed99f | train | function | def test_get_obj_records_no_api_key_get(app_static):
with pytest.raises(requests.exceptions.HTTPError):
app_static.api_key = None
app_static.get(OBJ, refresh=True)
| def test_get_obj_records_no_api_key_get(app_static):
| with pytest.raises(requests.exceptions.HTTPError):
app_static.api_key = None
app_static.get(OBJ, refresh=True)
| _generate_records_is_generator(app_static):
assert isinstance(app_static.get(OBJ, generate=True), types.GeneratorType)
def test_generate_records(app_static):
assert len([record for record in app_static.get(OBJ, generate=True)]) > 0
def test_get_obj_records_no_api_key_get(app_static):
| 64 | 64 | 40 | 12 | 51 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_obj_records_no_api_key_get | test_get_obj_records_no_api_key_get | 123 | 126 | 123 | 123 | 55ae7d0b0e359ebbf5b42658f4ae1b6b9768fdd2 | bigcode/the-stack | train |
8755795f28b3444ccc372ff1 | train | function | def test_get_by_key_refresh(app_live):
records = app_live.get(OBJ, refresh=True)
assert records
| def test_get_by_key_refresh(app_live):
| records = app_live.get(OBJ, refresh=True)
assert records
| _by_key_static(app_static):
assert app_static.get("view_11")
def test_get_view_by_key_live(app_live):
assert app_live.get("view_11")
def test_get_view_by_name(app_live):
assert app_live.get("view_11")
def test_get_by_key_refresh(app_live):
| 64 | 64 | 25 | 9 | 55 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_by_key_refresh | test_get_by_key_refresh | 110 | 112 | 110 | 110 | b5bb722b6a9362d8e48870351e140b68fffe8aca | bigcode/the-stack | train |
aeeb330540b0ba036af00dbb | train | function | def test_valid_tzinfo(app_data):
assert knackpy.app.App(
app_id=app_data["metadata"]["application"]["id"],
metadata=app_data["metadata"],
tzinfo="US/Eastern",
)
| def test_valid_tzinfo(app_data):
| assert knackpy.app.App(
app_id=app_data["metadata"]["application"]["id"],
metadata=app_data["metadata"],
tzinfo="US/Eastern",
)
| " container name exists in our app as both an object
# and as a view. so trying to query by that name results in a KeyError.
with pytest.raises(ValueError):
assert isinstance(app_static.get("all_fields_test"), types.GeneratorType)
def test_valid_tzinfo(app_data):
| 64 | 64 | 47 | 9 | 55 | gabcoyne/knackpy | tests/test_app.py | Python | test_valid_tzinfo | test_valid_tzinfo | 172 | 177 | 172 | 172 | e57d08de18cd18c14ba136c7f36ac88ebe0ed3b8 | bigcode/the-stack | train |
1bbf1d8c9d62d554cfab7577 | train | function | def test_object_get_by_key_static(app_static):
assert app_static.get(OBJ)
| def test_object_get_by_key_static(app_static):
| assert app_static.get(OBJ)
| atd")
def test_basic_static_app_construction(app_static):
assert app_static
def test_app_repr(app_static):
assert repr(app_static)
def test_constructor_fail_missing_app_id(app_static):
with pytest.raises(TypeError):
knackpy.app.App()
def test_object_get_by_key_static(app_static):
| 64 | 64 | 18 | 10 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_object_get_by_key_static | test_object_get_by_key_static | 90 | 91 | 90 | 90 | a8318761faf8a6ceafbf00895928a64f9cd77fc9 | bigcode/the-stack | train |
53844fa3672c10389e141f8a | train | function | def test_get_view_by_name(app_live):
assert app_live.get("view_11")
| def test_get_view_by_name(app_live):
| assert app_live.get("view_11")
| _get_object_by_key_live(app_live):
assert app_live.get(OBJ)
def test_view_by_key_static(app_static):
assert app_static.get("view_11")
def test_get_view_by_key_live(app_live):
assert app_live.get("view_11")
def test_get_view_by_name(app_live):
| 64 | 64 | 19 | 9 | 55 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_view_by_name | test_get_view_by_name | 106 | 107 | 106 | 106 | 6d835a40bdfbe88a291d7eaf5e61672426a1ea4e | bigcode/the-stack | train |
ec4e6d5d00ee4e236b20eb2d | train | function | def test_get_records_by_view_name(app_static):
assert app_static.get("all fields")
| def test_get_records_by_view_name(app_static):
| assert app_static.get("all fields")
|
def test_get_view_records_with_filters(app_live):
records = app_live.get("view_11", filters=FILTERS)
assert len(records) == 1
def test_get_records_by_object_name(app_static):
assert app_static.get("orders")
def test_get_records_by_view_name(app_static):
| 64 | 64 | 19 | 10 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_records_by_view_name | test_get_records_by_view_name | 143 | 144 | 143 | 143 | 1c0cbc0d2b3149d3229c3141079198a06587ed0d | bigcode/the-stack | train |
ddaa04e54e6eb6fa88cc0225 | train | function | def test_downloads(app_live, tmpdir):
app_live.download(
container="object_3", field="file", out_dir=tmpdir, label_keys=["field_125"]
)
assert True
| def test_downloads(app_live, tmpdir):
| app_live.download(
container="object_3", field="file", out_dir=tmpdir, label_keys=["field_125"]
)
assert True
| def test_info(app_static):
assert isinstance(app_static.info(), dict)
def test_csv(app_static, tmpdir):
app_static.to_csv("object_3", out_dir=tmpdir)
assert os.path.exists(tmpdir / "object_3.csv")
def test_downloads(app_live, tmpdir):
| 64 | 64 | 45 | 10 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_downloads | test_downloads | 198 | 202 | 198 | 198 | 223128665943ada99eef9cc9955ee479bd160416 | bigcode/the-stack | train |
e84c61430b84ae5c0b8e9acd | train | function | def test_get_object_records_with_filters(app_live):
records = app_live.get(OBJ, filters=FILTERS)
assert len(records) == 1
| def test_get_object_records_with_filters(app_live):
| records = app_live.get(OBJ, filters=FILTERS)
assert len(records) == 1
| in app_static.get(OBJ, generate=True)]) > 0
def test_get_obj_records_no_api_key_get(app_static):
with pytest.raises(requests.exceptions.HTTPError):
app_static.api_key = None
app_static.get(OBJ, refresh=True)
def test_get_object_records_with_filters(app_live):
| 64 | 64 | 33 | 10 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_object_records_with_filters | test_get_object_records_with_filters | 129 | 131 | 129 | 129 | bc238e3d60d66b788e1047168b7b69b17ec43d8f | bigcode/the-stack | train |
fc1e8ec168b35652a54f9561 | train | function | def test_record_create_delete(app_live):
# yes, two tests in one :/
time.sleep(SLEEP_TIME)
new_record = app_live.record(method="create", data={}, obj=OBJ)
assert new_record
time.sleep(SLEEP_TIME)
response = app_live.record(method="delete", data={"id": new_record["id"]}, obj=OBJ,)
assert resp... | def test_record_create_delete(app_live):
# yes, two tests in one :/
| time.sleep(SLEEP_TIME)
new_record = app_live.record(method="create", data={}, obj=OBJ)
assert new_record
time.sleep(SLEEP_TIME)
response = app_live.record(method="delete", data={"id": new_record["id"]}, obj=OBJ,)
assert response["delete"]
| data = {"id": record["id"], UPDATE_KEY: update_value}
record_updated = app_live.record(method="update", data=data, obj=OBJ)
assert record_updated[UPDATE_KEY] == update_value
def test_record_create_delete(app_live):
# yes, two tests in one :/
| 64 | 64 | 84 | 18 | 45 | gabcoyne/knackpy | tests/test_app.py | Python | test_record_create_delete | test_record_create_delete | 246 | 253 | 246 | 247 | 2de1e4c1371fd23f61c177bd8db9ce4743633d25 | bigcode/the-stack | train |
0861089625f4e29c527103fe | train | function | def test_get_object_by_key_live(app_live):
assert app_live.get(OBJ)
| def test_get_object_by_key_live(app_live):
| assert app_live.get(OBJ)
| def test_app_repr(app_static):
assert repr(app_static)
def test_constructor_fail_missing_app_id(app_static):
with pytest.raises(TypeError):
knackpy.app.App()
def test_object_get_by_key_static(app_static):
assert app_static.get(OBJ)
def test_get_object_by_key_live(app_live):
| 64 | 64 | 18 | 10 | 54 | gabcoyne/knackpy | tests/test_app.py | Python | test_get_object_by_key_live | test_get_object_by_key_live | 94 | 95 | 94 | 94 | dcda678f4209be101bbcd8cfecaf6b1b5b919068 | bigcode/the-stack | train |
c24c8a3f57cd8963c6720958 | train | function | def test_csv(app_static, tmpdir):
app_static.to_csv("object_3", out_dir=tmpdir)
assert os.path.exists(tmpdir / "object_3.csv")
| def test_csv(app_static, tmpdir):
| app_static.to_csv("object_3", out_dir=tmpdir)
assert os.path.exists(tmpdir / "object_3.csv")
| Error):
assert knackpy.app.App(
app_id=app_data["metadata"]["application"]["id"],
metadata=app_data["metadata"],
tzinfo="Austin, Texas",
)
def test_info(app_static):
assert isinstance(app_static.info(), dict)
def test_csv(app_static, tmpdir):
| 64 | 64 | 39 | 9 | 55 | gabcoyne/knackpy | tests/test_app.py | Python | test_csv | test_csv | 193 | 195 | 193 | 193 | a85717979eab5af61c0eeea735e23bc52d8701eb | bigcode/the-stack | train |
aba9de83894b008d47bb252e | train | function | def test_upload_image_create_update_delete_record(app_live):
"""
Yes, this is three tests in one. Create a record with a new image. Update the
record with another image (ok, well, technically the same image), delete that
record.
"""
path = UPLOAD_CONFIG["path"]
field = UPLOAD_CONFIG["image_f... | def test_upload_image_create_update_delete_record(app_live):
| """
Yes, this is three tests in one. Create a record with a new image. Update the
record with another image (ok, well, technically the same image), delete that
record.
"""
path = UPLOAD_CONFIG["path"]
field = UPLOAD_CONFIG["image_field"]
obj = UPLOAD_CONFIG["obj"]
# create
record... | .path.exists(tmpdir / "object_3.csv")
def test_downloads(app_live, tmpdir):
app_live.download(
container="object_3", field="file", out_dir=tmpdir, label_keys=["field_125"]
)
assert True
def test_upload_image_create_update_delete_record(app_live):
| 67 | 67 | 225 | 11 | 55 | gabcoyne/knackpy | tests/test_app.py | Python | test_upload_image_create_update_delete_record | test_upload_image_create_update_delete_record | 205 | 232 | 205 | 205 | 559bddd0a0853af6814a7f0c48451f9e70b34b64 | bigcode/the-stack | train |
a547a245510fc2d29c201736 | train | function | @pytest.fixture
def app_live():
# testing on live app (as in over-the-wire data fetch, not side-loaded)
return knackpy.app.App(app_id=APP_ID, api_key=API_KEY)
| @pytest.fixture
def app_live():
# testing on live app (as in over-the-wire data fetch, not side-loaded)
| return knackpy.app.App(app_id=APP_ID, api_key=API_KEY)
| "],
api_key=API_KEY,
metadata=app_data["metadata"],
)
knackpy_app.data = {OBJ: app_data["data"]}
return knackpy_app
@pytest.fixture
def app_live():
# testing on live app (as in over-the-wire data fetch, not side-loaded)
| 64 | 64 | 44 | 26 | 37 | gabcoyne/knackpy | tests/test_app.py | Python | app_live | app_live | 63 | 66 | 63 | 65 | 10b0ed3ee35a37b74605a0f26bf9248d7fa11e05 | bigcode/the-stack | train |
520d7003c13a5035ffe05cff | train | function | def test_no_key_or_name_param_fail(app_static):
# the API allows you to use App.reords() (without any key or view name) if only
# one container has been retrieved. in this case, we side-load additional data
# such that the app is holding data for two containers, and so the user must
# specifiy the conta... | def test_no_key_or_name_param_fail(app_static):
# the API allows you to use App.reords() (without any key or view name) if only
# one container has been retrieved. in this case, we side-load additional data
# such that the app is holding data for two containers, and so the user must
# specifiy the conta... | data = app_static.data["object_3"]
app_static.data["fake_data_holder"] = data
with pytest.raises(TypeError):
assert app_static.get()
| def test_no_key_or_name_param_fail(app_static):
# the API allows you to use App.reords() (without any key or view name) if only
# one container has been retrieved. in this case, we side-load additional data
# such that the app is holding data for two containers, and so the user must
# specifiy the conta... | 81 | 64 | 117 | 81 | 0 | gabcoyne/knackpy | tests/test_app.py | Python | test_no_key_or_name_param_fail | test_no_key_or_name_param_fail | 154 | 162 | 154 | 158 | cdafc18d4298f82ec4a34e119fb949979ad8d3b2 | bigcode/the-stack | train |
f90d4a62002098c140fca266 | train | function | @pytest.fixture
def app_static(app_data):
# app with side-loaded metadata and records
knackpy_app = knackpy.app.App(
app_id=app_data["metadata"]["application"]["id"],
api_key=API_KEY,
metadata=app_data["metadata"],
)
knackpy_app.data = {OBJ: app_data["data"]}
return knackpy_a... | @pytest.fixture
def app_static(app_data):
# app with side-loaded metadata and records
| knackpy_app = knackpy.app.App(
app_id=app_data["metadata"]["application"]["id"],
api_key=API_KEY,
metadata=app_data["metadata"],
)
knackpy_app.data = {OBJ: app_data["data"]}
return knackpy_app
| .read())
with open("tests/_all_fields.json", "r") as fin:
data = json.loads(fin.read())
data = data["records"]
return {"data": data, "metadata": metadata}
@pytest.fixture
def app_static(app_data):
# app with side-loaded metadata and records
| 64 | 64 | 79 | 19 | 45 | gabcoyne/knackpy | tests/test_app.py | Python | app_static | app_static | 51 | 60 | 51 | 53 | c40d7390d8fa615c907e3d44500e2e9676b656b3 | bigcode/the-stack | train |
7a65b4e0b93912ed6c645e5a | train | function | def factorial_memoization(n):
"""Memoization implementation of factorial: O(n) runtime, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[0] = 1
def factorial_memoization_helper(k):
if d[k] == 0:
d[k] = k * factorial_memoization_helper(k - 1)
return d[k]... | def factorial_memoization(n):
| """Memoization implementation of factorial: O(n) runtime, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[0] = 1
def factorial_memoization_helper(k):
if d[k] == 0:
d[k] = k * factorial_memoization_helper(k - 1)
return d[k]
return factorial_memoiza... | have base case of d[1] = 1 and compute d[n] from there, looping from i = 2
for i in range(1, n + 1):
d[i] = i * d[i - 1]
return d[n]
def factorial_memoization(n):
| 64 | 64 | 106 | 7 | 57 | ChamiLamelas/Learning_DP | common_recursion.py | Python | factorial_memoization | factorial_memoization | 26 | 36 | 26 | 26 | d74b0eab93a58137b4a3bf6e595a0e67969722e7 | bigcode/the-stack | train |
83578827ed7658c7ea2b63bd | train | function | def different_ways_tabulation(n):
"""Tabulation implementation of different ways, O(n) time and O(n) space pre-allocated"""
# build array such that d[i] = # ways to write i as sum of 1s, 3s, and 4s
d = [0] * (n + 1)
# d allows us to define D0 = 1 as above, but we cannot represent Dn = 0 for negative n... | def different_ways_tabulation(n):
| """Tabulation implementation of different ways, O(n) time and O(n) space pre-allocated"""
# build array such that d[i] = # ways to write i as sum of 1s, 3s, and 4s
d = [0] * (n + 1)
# d allows us to define D0 = 1 as above, but we cannot represent Dn = 0 for negative n in d, thus we need different
... | It is ok to have them sum to 0 because
that just means n = xk (there is no requirement that k be anymore than 1) ==> base cases are D0 = 1, Dn = 0 for n < 0
"""
def different_ways_rec(n):
"""Recursive implementation of different ways, O(3^n) time and O(n) space maximum"""
if n < 0:
return 0
if n ... | 146 | 146 | 487 | 8 | 138 | ChamiLamelas/Learning_DP | common_recursion.py | Python | different_ways_tabulation | different_ways_tabulation | 128 | 152 | 128 | 128 | 469e8cc1cdcc348eb95a1a7043f11fa01a937127 | bigcode/the-stack | train |
aa109d59f579b133ecf2d766 | train | function | def fibonacci_rec(n):
"""Recursive implementation of fibonacci. O(2^n) runtime, O(n) max stack frames"""
if n <= 2:
return 1
return fibonacci_rec(n - 1) + fibonacci_rec(n - 2)
| def fibonacci_rec(n):
| """Recursive implementation of fibonacci. O(2^n) runtime, O(n) max stack frames"""
if n <= 2:
return 1
return fibonacci_rec(n - 1) + fibonacci_rec(n - 2)
| (1, n + 1):
prod *= i
return prod
"""
Fibonacci sequence: f(n) = 1 for n = 1, 2 and f(n) = f(n-1) + f(n-2) for n > 2
"""
def fibonacci_rec(n):
| 64 | 64 | 56 | 5 | 59 | ChamiLamelas/Learning_DP | common_recursion.py | Python | fibonacci_rec | fibonacci_rec | 52 | 56 | 52 | 52 | d10f85961617b4953f834a524975c510aff7cd97 | bigcode/the-stack | train |
f3ba43b80d09e2040b428e37 | train | function | def different_ways_memoization(n):
"""Memoization implementation of different ways, O(n) time, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[0] = 1
def different_ways_memoization_helper(k):
if k < 0:
return 0
if d[k] == 0:
d[k] = differen... | def different_ways_memoization(n):
| """Memoization implementation of different ways, O(n) time, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[0] = 1
def different_ways_memoization_helper(k):
if k < 0:
return 0
if d[k] == 0:
d[k] = different_ways_memoization_helper(k - 1) + ... | for 4 <= i <= n with our recursive step
for i in range(4, n + 1):
d[i] = d[i - 1] + d[i - 3] + d[i - 4]
return d[n]
def different_ways_memoization(n):
| 64 | 64 | 153 | 9 | 55 | ChamiLamelas/Learning_DP | common_recursion.py | Python | different_ways_memoization | different_ways_memoization | 155 | 168 | 155 | 155 | 5c40b50971667b0ca25dc173bf9a26b65a9f4baa | bigcode/the-stack | train |
6f6b7f80d93b012bcacb4e30 | train | function | def different_ways_rec(n):
"""Recursive implementation of different ways, O(3^n) time and O(n) space maximum"""
if n < 0:
return 0
if n == 0:
return 1
return different_ways_rec(n - 1) + different_ways_rec(n - 3) + different_ways_rec(n - 4)
| def different_ways_rec(n):
| """Recursive implementation of different ways, O(3^n) time and O(n) space maximum"""
if n < 0:
return 0
if n == 0:
return 1
return different_ways_rec(n - 1) + different_ways_rec(n - 3) + different_ways_rec(n - 4)
| negative number. It is ok to have them sum to 0 because
that just means n = xk (there is no requirement that k be anymore than 1) ==> base cases are D0 = 1, Dn = 0 for n < 0
"""
def different_ways_rec(n):
| 64 | 64 | 84 | 7 | 57 | ChamiLamelas/Learning_DP | common_recursion.py | Python | different_ways_rec | different_ways_rec | 119 | 125 | 119 | 119 | 5d7da9dceb1860c1d42b28337619e21d8ac00d7b | bigcode/the-stack | train |
252f9ee5eb1a5161347b9fd1 | train | function | def fibonacci_iter(n):
"""Iterative implementation of fibonacci. O(n) runtime, O(1) space"""
if n <= 2:
return 1
prev_prev_term = 1 # f(k-2)
prev_term = 1 # f(k-1)
for k in range(3, n + 1):
tmp = prev_term
# f(k) = f(k-1) + f(k-2) => f(k) at current term becomes f(k-1) at ... | def fibonacci_iter(n):
| """Iterative implementation of fibonacci. O(n) runtime, O(1) space"""
if n <= 2:
return 1
prev_prev_term = 1 # f(k-2)
prev_term = 1 # f(k-1)
for k in range(3, n + 1):
tmp = prev_term
# f(k) = f(k-1) + f(k-2) => f(k) at current term becomes f(k-1) at next term
prev_... | n + 1)
d[1] = 1
d[2] = 1
for i in range(3, n + 1):
d[i] = d[i - 1] + d[i - 2]
return d[n]
def fibonacci_iter(n):
| 64 | 64 | 156 | 5 | 59 | ChamiLamelas/Learning_DP | common_recursion.py | Python | fibonacci_iter | fibonacci_iter | 83 | 96 | 83 | 83 | de1872e32678c6050e726ee5e23a4d3e74bc7540 | bigcode/the-stack | train |
ee5828006983b5ac03681860 | train | function | def fibonacci_memoization(n):
"""Memoization implementation of fibonacci. O(n) runtime, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[1] = 1
d[2] = 1
def fibonacci_memoization_helper(k):
if d[k] == 0:
d[k] = fibonacci_memoization_helper(k - 1) + fibonacc... | def fibonacci_memoization(n):
| """Memoization implementation of fibonacci. O(n) runtime, O(n) max stack frames, O(n) pre-allocated space"""
d = [0] * (n + 1)
d[1] = 1
d[2] = 1
def fibonacci_memoization_helper(k):
if d[k] == 0:
d[k] = fibonacci_memoization_helper(k - 1) + fibonacci_memoization_helper(k - 2)
... | """
def fibonacci_rec(n):
"""Recursive implementation of fibonacci. O(2^n) runtime, O(n) max stack frames"""
if n <= 2:
return 1
return fibonacci_rec(n - 1) + fibonacci_rec(n - 2)
def fibonacci_memoization(n):
| 64 | 64 | 124 | 7 | 57 | ChamiLamelas/Learning_DP | common_recursion.py | Python | fibonacci_memoization | fibonacci_memoization | 59 | 70 | 59 | 59 | a98eba9cf30c3a7c09443af8c3c1cf2012789de3 | bigcode/the-stack | train |
b2e0413515c20f86b5757f1b | train | function | def factorial_rec(n):
"""Recursive implementation of factorial: O(n) runtime, O(n) max stack frames"""
if n == 0:
return 1
return n * factorial_rec(n - 1)
| def factorial_rec(n):
| """Recursive implementation of factorial: O(n) runtime, O(n) max stack frames"""
if n == 0:
return 1
return n * factorial_rec(n - 1)
| """
Derivation for factorial:
n! = n * (n-1) * .... * 1, by definition 0! = 1
recurrence: n! = n * (n-1)! assuming n > 0
"""
def factorial_rec(n):
| 56 | 64 | 47 | 5 | 51 | ChamiLamelas/Learning_DP | common_recursion.py | Python | factorial_rec | factorial_rec | 9 | 13 | 9 | 9 | 64c2fc005adf59a20ef3c0265d82594d61d7490a | bigcode/the-stack | train |
de551df8e38ba7fadea4b68b | train | function | def factorial_iter(n):
"""Iterative implementation of factorial: O(n) runtime, O(n) space"""
prod = 1
for i in range(1, n + 1):
prod *= i
return prod
| def factorial_iter(n):
| """Iterative implementation of factorial: O(n) runtime, O(n) space"""
prod = 1
for i in range(1, n + 1):
prod *= i
return prod
| )
d[0] = 1
def factorial_memoization_helper(k):
if d[k] == 0:
d[k] = k * factorial_memoization_helper(k - 1)
return d[k]
return factorial_memoization_helper(n)
def factorial_iter(n):
| 64 | 64 | 51 | 5 | 59 | ChamiLamelas/Learning_DP | common_recursion.py | Python | factorial_iter | factorial_iter | 39 | 44 | 39 | 39 | 11bafef5f8a4030d601bbe058b6302751136fc27 | bigcode/the-stack | train |
348a1f1fcae41dd58f232b4a | train | function | def fibonacci_tabulation(n):
"""DP implementation of fibonacci. O(n) runtime, O(n) space"""
d = [0] * (n + 1)
d[1] = 1
d[2] = 1
for i in range(3, n + 1):
d[i] = d[i - 1] + d[i - 2]
return d[n]
| def fibonacci_tabulation(n):
| """DP implementation of fibonacci. O(n) runtime, O(n) space"""
d = [0] * (n + 1)
d[1] = 1
d[2] = 1
for i in range(3, n + 1):
d[i] = d[i - 1] + d[i - 2]
return d[n]
| def fibonacci_memoization_helper(k):
if d[k] == 0:
d[k] = fibonacci_memoization_helper(k - 1) + fibonacci_memoization_helper(k - 2)
return d[k]
return fibonacci_memoization_helper(n)
def fibonacci_tabulation(n):
| 64 | 64 | 90 | 6 | 58 | ChamiLamelas/Learning_DP | common_recursion.py | Python | fibonacci_tabulation | fibonacci_tabulation | 73 | 80 | 73 | 73 | 2207b5ec6cdcdb27457e4edb9f6246a96c5d925b | bigcode/the-stack | train |
904ac266380427b10bae0897 | train | function | def factorial_tabulation(n):
"""Tabulation implementation of factorial: O(n) runtime, O(n) space"""
d = [0] * (n + 1)
d[0] = 1
# could alternatively have base case of d[1] = 1 and compute d[n] from there, looping from i = 2
for i in range(1, n + 1):
d[i] = i * d[i - 1]
return d[n]
| def factorial_tabulation(n):
| """Tabulation implementation of factorial: O(n) runtime, O(n) space"""
d = [0] * (n + 1)
d[0] = 1
# could alternatively have base case of d[1] = 1 and compute d[n] from there, looping from i = 2
for i in range(1, n + 1):
d[i] = i * d[i - 1]
return d[n]
| n-1)! assuming n > 0
"""
def factorial_rec(n):
"""Recursive implementation of factorial: O(n) runtime, O(n) max stack frames"""
if n == 0:
return 1
return n * factorial_rec(n - 1)
def factorial_tabulation(n):
| 64 | 64 | 107 | 6 | 58 | ChamiLamelas/Learning_DP | common_recursion.py | Python | factorial_tabulation | factorial_tabulation | 16 | 23 | 16 | 16 | 9064e3401a1d30e3c9ff8bf0665fe0aade41bdaa | bigcode/the-stack | train |
e065b1d935706f18b5f85c26 | train | function | def update_Q_table(state, action, reward, state_prime, alpha, gamma):
qsa = np.max(Q_table[state_prime])
Q_table[state][action] += alpha * (reward + gamma * qsa - Q_table[state][action])
| def update_Q_table(state, action, reward, state_prime, alpha, gamma):
| qsa = np.max(Q_table[state_prime])
Q_table[state][action] += alpha * (reward + gamma * qsa - Q_table[state][action])
| 3')
alpha = 0.4
gamma = 0.85
epslion = 0.05
episodes = 2000
Q_table = np.zeros((env.observation_space.n, env.action_space.n))
def update_Q_table(state, action, reward, state_prime, alpha, gamma):
| 64 | 64 | 52 | 17 | 47 | RayshineRen/Reinforement-Learning-from-Scratch | Q_Learning/Taxi-v3.py | Python | update_Q_table | update_Q_table | 15 | 17 | 15 | 15 | c4ae746e41297adbdab5c12b6d0df6c9e697d83f | bigcode/the-stack | train |
da3bf8e9ddaf1a676807c5ac | train | function | def OutPolicy(env, Q_table):
policy = []
for state in range(env.observation_space.n):
action = np.argmax(Q_table[state])
policy.append(action)
return policy
| def OutPolicy(env, Q_table):
| policy = []
for state in range(env.observation_space.n):
action = np.argmax(Q_table[state])
policy.append(action)
return policy
| reward + gamma * qsa - Q_table[state][action])
def epslion_greedy(state, epslion):
if random.uniform(0, 1) < epslion:
return env.action_space.sample()
else:
return np.argmax(Q_table[state])
def OutPolicy(env, Q_table):
| 64 | 64 | 41 | 8 | 56 | RayshineRen/Reinforement-Learning-from-Scratch | Q_Learning/Taxi-v3.py | Python | OutPolicy | OutPolicy | 25 | 30 | 25 | 25 | 165df7fe800c603180d4a8f4444edc0c0ad0986a | bigcode/the-stack | train |
e0fed26c7a254fd902a96751 | train | function | def evaluatePolicy(env, policy):
obs = env.reset()
env.render()
while True:
obs, reward, done, _ = env.step(int(policy[obs]))
env.render()
if done:
break
| def evaluatePolicy(env, policy):
| obs = env.reset()
env.render()
while True:
obs, reward, done, _ = env.step(int(policy[obs]))
env.render()
if done:
break
| env.action_space.sample()
else:
return np.argmax(Q_table[state])
def OutPolicy(env, Q_table):
policy = []
for state in range(env.observation_space.n):
action = np.argmax(Q_table[state])
policy.append(action)
return policy
def evaluatePolicy(env, policy):
| 64 | 64 | 48 | 7 | 56 | RayshineRen/Reinforement-Learning-from-Scratch | Q_Learning/Taxi-v3.py | Python | evaluatePolicy | evaluatePolicy | 32 | 39 | 32 | 32 | 00a68dbba81a7708e293f0b78674aa5eb242d6e0 | bigcode/the-stack | train |
01d354fd59e7df4ff2831723 | train | function | def epslion_greedy(state, epslion):
if random.uniform(0, 1) < epslion:
return env.action_space.sample()
else:
return np.argmax(Q_table[state])
| def epslion_greedy(state, epslion):
| if random.uniform(0, 1) < epslion:
return env.action_space.sample()
else:
return np.argmax(Q_table[state])
| ))
def update_Q_table(state, action, reward, state_prime, alpha, gamma):
qsa = np.max(Q_table[state_prime])
Q_table[state][action] += alpha * (reward + gamma * qsa - Q_table[state][action])
def epslion_greedy(state, epslion):
| 64 | 64 | 43 | 11 | 53 | RayshineRen/Reinforement-Learning-from-Scratch | Q_Learning/Taxi-v3.py | Python | epslion_greedy | epslion_greedy | 19 | 23 | 19 | 19 | ce85fdaabfb9089efb7fe5919fc9574beaeb8efb | bigcode/the-stack | train |
1c418f73a6f61d7b0f41ac08 | train | class | class ProbClassPredDistrWidget(Widget):
def __init__(self, title:str, dataset:str='reference'):
super().__init__()
self.title = title
self.dataset = dataset #reference or current
def analyzers(self):
return [ProbClassificationPerformanceAnalyzer]
def get_info(self) -> Ba... | class ProbClassPredDistrWidget(Widget):
| def __init__(self, title:str, dataset:str='reference'):
super().__init__()
self.title = title
self.dataset = dataset #reference or current
def analyzers(self):
return [ProbClassificationPerformanceAnalyzer]
def get_info(self) -> BaseWidgetInfo:
if self.dataset ==... | #!/usr/bin/env python
# coding: utf-8
import json
import pandas as pd
import numpy as np
from sklearn import metrics, preprocessing
from pandas.api.types import is_numeric_dtype
import plotly.graph_objs as go
import plotly.figure_factory as ff
from evidently.analyzers.prob_classification_performance_analyzer impor... | 126 | 184 | 614 | 9 | 117 | QAtestinc/evidently | evidently/widgets/prob_class_pred_distr_widget.py | Python | ProbClassPredDistrWidget | ProbClassPredDistrWidget | 23 | 114 | 23 | 23 | 811748c3588579029f89374872ac7ab00761c861 | bigcode/the-stack | train |
039dc5e3ace3fc6028c9f657 | train | function | def printMany():
bar_len = 50
lines = [0, 5, 10, 15, 20, 25, -30, -35, -40, -45]
num_lines = len(lines)
while(1):
printHitmanBarMany(lines, bar_len)
for i in range(num_lines):
lines[i] += 1
if(lines[i] >= bar_len): #if the line index is at the max, set it to nega... | def printMany():
| bar_len = 50
lines = [0, 5, 10, 15, 20, 25, -30, -35, -40, -45]
num_lines = len(lines)
while(1):
printHitmanBarMany(lines, bar_len)
for i in range(num_lines):
lines[i] += 1
if(lines[i] >= bar_len): #if the line index is at the max, set it to negative indicating i... | Index] = '█'
if lineIndex < 0:
bar[-lineIndex] = '|'
bar_str = ""
for x in bar:
bar_str += x
print(bar_str, end = "\r")
time.sleep(0.025)
def printMany():
| 64 | 64 | 123 | 4 | 60 | deruitda/terminal-loaders | python/hitman-loader.py | Python | printMany | printMany | 19 | 29 | 19 | 19 | 4005ee74c8d7de885a684e1606dcb2b26ae9ff06 | bigcode/the-stack | train |
dc157eb518c3bde143a6b94f | train | function | def printHitmanBarMany(lines, len):
bar = [' '] * len
for lineIndex in lines:
if lineIndex > 0:
bar[lineIndex] = '█'
if lineIndex < 0:
bar[-lineIndex] = '|'
bar_str = ""
for x in bar:
bar_str += x
print(bar_str, end = "\r")
time.sle... | def printHitmanBarMany(lines, len):
| bar = [' '] * len
for lineIndex in lines:
if lineIndex > 0:
bar[lineIndex] = '█'
if lineIndex < 0:
bar[-lineIndex] = '|'
bar_str = ""
for x in bar:
bar_str += x
print(bar_str, end = "\r")
time.sleep(0.025)
| import time
def printHitmanBarMany(lines, len):
| 13 | 64 | 97 | 10 | 2 | deruitda/terminal-loaders | python/hitman-loader.py | Python | printHitmanBarMany | printHitmanBarMany | 3 | 17 | 3 | 3 | 79e81f9c1ad5fb8c215c8cfa81d0ed26ecb4c613 | bigcode/the-stack | train |
ef1a709adf496b1c9e27e8e7 | train | function | def printHitmanBar(pos, len, line):
start = (' ' * pos)
end = (' ' * (len - pos - 1))
bar = "\t|" + start + line + end + '|'
print(bar, end = "\r")
time.sleep(0.05)
| def printHitmanBar(pos, len, line):
| start = (' ' * pos)
end = (' ' * (len - pos - 1))
bar = "\t|" + start + line + end + '|'
print(bar, end = "\r")
time.sleep(0.05)
| ):
lines[i] += 1
if(lines[i] >= bar_len): #if the line index is at the max, set it to negative indicating it's moving backwards
lines[i] = -(bar_len - 1)
printMany()
def printHitmanBar(pos, len, line):
| 64 | 64 | 65 | 11 | 53 | deruitda/terminal-loaders | python/hitman-loader.py | Python | printHitmanBar | printHitmanBar | 35 | 41 | 35 | 35 | 4e225ca2a0b2410a4e30d1feba26ed6fe12df8ea | bigcode/the-stack | train |
8ddd4e89cb56acaba5162ac7 | train | function | def printSingle():
pos = 0
len = 20
while(1):
printHitmanBar(pos, len, '█')
pos += 1
if pos >= len:
while(pos > 0):
pos -= 1
printHitmanBar(pos, len, '|')
| def printSingle():
| pos = 0
len = 20
while(1):
printHitmanBar(pos, len, '█')
pos += 1
if pos >= len:
while(pos > 0):
pos -= 1
printHitmanBar(pos, len, '|')
| (pos, len, line):
start = (' ' * pos)
end = (' ' * (len - pos - 1))
bar = "\t|" + start + line + end + '|'
print(bar, end = "\r")
time.sleep(0.05)
def printSingle():
| 64 | 64 | 69 | 4 | 60 | deruitda/terminal-loaders | python/hitman-loader.py | Python | printSingle | printSingle | 43 | 53 | 43 | 43 | 7c0d060bbcb3902d816db8595fe5e4707edadf67 | bigcode/the-stack | train |
7a0ac55a89401f9caa659391 | train | function | @functools.lru_cache(maxsize=1)
def has_amazon() -> bool:
"""
Check if an instance is running on AWS EC2
"""
if amazon_public_address():
return True
else:
return False
| @functools.lru_cache(maxsize=1)
def has_amazon() -> bool:
| """
Check if an instance is running on AWS EC2
"""
if amazon_public_address():
return True
else:
return False
| ().strip()
return None
except Exception as error:
return None
@functools.lru_cache(maxsize=1)
def private_address() -> str:
assert False, f"TODO"
@functools.lru_cache(maxsize=1)
def has_amazon() -> bool:
| 64 | 64 | 53 | 20 | 44 | Andrei-Pozolotin/nspawn | src/main/nspawn/tool/network.py | Python | has_amazon | has_amazon | 72 | 80 | 72 | 73 | 4f829c40fee57e03735b39eb02f21177fc321418 | bigcode/the-stack | train |
c221064027fe27cd1837b822 | train | function | @functools.lru_cache(maxsize=1)
def public_address() -> str:
"""
Discover public internet address
"""
check_timeout = float(CONFIG['network']['check_timeout'])
check_host_list = CONFIG.get_list('network', 'check_host_list')
try:
for check_url in check_host_list:
with urllib.r... | @functools.lru_cache(maxsize=1)
def public_address() -> str:
| """
Discover public internet address
"""
check_timeout = float(CONFIG['network']['check_timeout'])
check_host_list = CONFIG.get_list('network', 'check_host_list')
try:
for check_url in check_host_list:
with urllib.request.urlopen(
url=check_url, timeout=check_... | functools.lru_cache(maxsize=1)
def has_internet() -> bool:
"""
Verify public internet access
"""
if public_address():
return True
else:
return False
@functools.lru_cache(maxsize=1)
def public_address() -> str:
| 64 | 64 | 114 | 19 | 44 | Andrei-Pozolotin/nspawn | src/main/nspawn/tool/network.py | Python | public_address | public_address | 49 | 64 | 49 | 50 | 2708817ae7a1205a8bf311feaa772a3120cf6f75 | bigcode/the-stack | train |
c47ebb1d4ced4ba59c427175 | train | function | @functools.lru_cache(maxsize=1)
def private_address() -> str:
assert False, f"TODO"
| @functools.lru_cache(maxsize=1)
def private_address() -> str:
| assert False, f"TODO"
| with urllib.request.urlopen(
url=check_url, timeout=check_timeout,
) as response:
return response.read().decode().strip()
return None
except Exception as error:
return None
@functools.lru_cache(maxsize=1)
def private_address() -> str:
| 64 | 64 | 27 | 19 | 44 | Andrei-Pozolotin/nspawn | src/main/nspawn/tool/network.py | Python | private_address | private_address | 67 | 69 | 67 | 68 | 387f318b7880b7210d8034e7303a3818b9a2e4bd | bigcode/the-stack | train |
1e0914fb19b02f937f5296c6 | train | function | @functools.lru_cache(maxsize=1)
def interface_list() -> List[str]:
"""
Discover available host interfaces
"""
cmd_ip = system_command('ip')
command = f"{cmd_ip} -o addr show up primary scope global".split()
result = SUDO.execute_unit(command)
result.assert_return()
line_list = result.std... | @functools.lru_cache(maxsize=1)
def interface_list() -> List[str]:
| """
Discover available host interfaces
"""
cmd_ip = system_command('ip')
command = f"{cmd_ip} -o addr show up primary scope global".split()
result = SUDO.execute_unit(command)
result.assert_return()
line_list = result.stdout.splitlines()
pattern = re.compile(r"^\d+[:]\s+(\S+)\s+(.+)$... | import re
import functools
import urllib.request
from typing import List
from nspawn import CONFIG
from nspawn.wrapper.sudo import SUDO
from nspawn.wrapper.base import system_command
@functools.lru_cache(maxsize=1)
def interface_list() -> List[str]:
| 60 | 64 | 135 | 20 | 39 | Andrei-Pozolotin/nspawn | src/main/nspawn/tool/network.py | Python | interface_list | interface_list | 11 | 24 | 11 | 12 | 3c571e70e499f08163c652888bf3ec3c1a0bbef2 | bigcode/the-stack | train |
66b08336dc60b096e7a04851 | train | function | @functools.lru_cache(maxsize=1)
def amazon_public_address() -> str:
"""
Obtain public address when running on AWS EC2
"""
check_url = 'http://169.254.169.254/latest/meta-data/public-ipv4'
check_timeout = float(CONFIG['network']['check_timeout'])
try:
with urllib.request.urlopen(
... | @functools.lru_cache(maxsize=1)
def amazon_public_address() -> str:
| """
Obtain public address when running on AWS EC2
"""
check_url = 'http://169.254.169.254/latest/meta-data/public-ipv4'
check_timeout = float(CONFIG['network']['check_timeout'])
try:
with urllib.request.urlopen(
url=check_url, timeout=check_timeout,
) as response:
... | =1)
def has_amazon() -> bool:
"""
Check if an instance is running on AWS EC2
"""
if amazon_public_address():
return True
else:
return False
@functools.lru_cache(maxsize=1)
def amazon_public_address() -> str:
| 64 | 64 | 113 | 20 | 43 | Andrei-Pozolotin/nspawn | src/main/nspawn/tool/network.py | Python | amazon_public_address | amazon_public_address | 83 | 96 | 83 | 84 | da196807a29326b309e0b02f450f3d6b9a7bdc52 | bigcode/the-stack | train |
3de14aafd0466745b5bc85c6 | train | function | @functools.lru_cache(maxsize=1)
def select_interface() -> str:
"""
"""
face_list = interface_list()
if face_list:
return face_list[0]
else:
raise RuntimeError("Failed to select network interface")
| @functools.lru_cache(maxsize=1)
def select_interface() -> str:
| """
"""
face_list = interface_list()
if face_list:
return face_list[0]
else:
raise RuntimeError("Failed to select network interface")
| +[:]\s+(\S+)\s+(.+)$")
select = lambda line: pattern.search(line).group(1)
face_list = list(map(select, line_list))
return face_list
@functools.lru_cache(maxsize=1)
def select_interface() -> str:
| 64 | 64 | 56 | 19 | 44 | Andrei-Pozolotin/nspawn | src/main/nspawn/tool/network.py | Python | select_interface | select_interface | 27 | 35 | 27 | 28 | 0c57d78fb21cf90b6e7e1a87bf4a6920160fed95 | bigcode/the-stack | train |
58286b8388e2e4e61eca25c3 | train | function | @functools.lru_cache(maxsize=1)
def has_internet() -> bool:
"""
Verify public internet access
"""
if public_address():
return True
else:
return False
| @functools.lru_cache(maxsize=1)
def has_internet() -> bool:
| """
Verify public internet access
"""
if public_address():
return True
else:
return False
| def select_interface() -> str:
"""
"""
face_list = interface_list()
if face_list:
return face_list[0]
else:
raise RuntimeError("Failed to select network interface")
@functools.lru_cache(maxsize=1)
def has_internet() -> bool:
| 64 | 64 | 46 | 20 | 44 | Andrei-Pozolotin/nspawn | src/main/nspawn/tool/network.py | Python | has_internet | has_internet | 38 | 46 | 38 | 39 | 77eb5f0ec68df924c982902429c6911cfb4f857b | bigcode/the-stack | train |
597c8711dca861b74d76f8f2 | train | class | class PCA(_BasePCA):
"""Principal component analysis (PCA)
Linear dimensionality reduction using Singular Value Decomposition of the
data to project it to a lower dimensional space.
It uses the "tsqr" algorithm from Benson et. al. (2013). See the References
for more.
Read more in the :ref:`Us... | class PCA(_BasePCA):
| """Principal component analysis (PCA)
Linear dimensionality reduction using Singular Value Decomposition of the
data to project it to a lower dimensional space.
It uses the "tsqr" algorithm from Benson et. al. (2013). See the References
for more.
Read more in the :ref:`User Guide <PCA>`.
... | import dask.array as da
import numpy as np
import scipy.sparse as sp
from dask import compute
from sklearn.decomposition.base import _BasePCA
from sklearn.utils.extmath import fast_logdet
from sklearn.utils.validation import check_is_fitted, check_random_state
from ..utils import svd_flip
class PCA(_BasePCA):
| 75 | 256 | 3,615 | 7 | 67 | souravsingh/dask-ml | dask_ml/decomposition/pca.py | Python | PCA | PCA | 12 | 453 | 12 | 12 | 40420a10bc19c49a88baa5500e9fe0e41b924854 | bigcode/the-stack | train |
6fe0190bf52b70a3529e9aed | train | function | def getDocumentsForNer(claim,predictor):
results = predictor.predict(sentence=claim)
f = open('NER.txt','w')
for word, tag in zip(results["words"], results["tags"]):
f.write(word+'\t'+tag+'\n')
f.write('\n')
f.close()
l =[]
s = ''
a = []
for line in open('NER.txt','r'): #ch... | def getDocumentsForNer(claim,predictor):
| results = predictor.predict(sentence=claim)
f = open('NER.txt','w')
for word, tag in zip(results["words"], results["tags"]):
f.write(word+'\t'+tag+'\n')
f.write('\n')
f.close()
l =[]
s = ''
a = []
for line in open('NER.txt','r'): #change files names based on dev /test
... | ('has')[0])
if 'is' in claim and 'actor' in claim:
l.append(claim.split('is')[0]+' '+'actor')
if 'is' in claim and 'actress' in claim:
l.append(claim.split('is')[0]+' '+'actress')
if 'features' in claim:
l.append(claim.split('features')[0])
return l
def getDocumentsForNer(claim,... | 100 | 100 | 334 | 12 | 87 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | getDocumentsForNer | getDocumentsForNer | 163 | 207 | 163 | 163 | 689733abbe1034e7942dca8761d69a88c47051ad | bigcode/the-stack | train |
298abcb12d27584b8c0b3d20 | train | function | def getDocsForClaim(claim,google_config,predictor,ranker):
try:
docs_google = getDocumentsForClaimFromGoogle(claim,google_config)
except Exception:
docs_google = []
try:
docs_ner = getDocumentsForNer(claim,predictor)
except Exception:
docs_google = []
try:
doc... | def getDocsForClaim(claim,google_config,predictor,ranker):
| try:
docs_google = getDocumentsForClaimFromGoogle(claim,google_config)
except Exception:
docs_google = []
try:
docs_ner = getDocumentsForNer(claim,predictor)
except Exception:
docs_google = []
try:
docs_dep_parse = getDocumentsFromDepParse(claim)
except Ex... | x.replace(')','-RRB-')
x = x.replace(':','-COLON-')
rec.append(x)
rec = list(set(rec))
return rec
def getDocsFromTFIDF(claim, ranker, k=10):
doc_names, doc_scores = ranker.closest_docs(claim, k)
pages = list(zip(doc_names, doc_scores))
return pages
def getDocsForClaim(clai... | 102 | 102 | 340 | 17 | 84 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | getDocsForClaim | getDocsForClaim | 215 | 252 | 215 | 215 | aea61c661cea3b0c631bd75b0a97c31531779d83 | bigcode/the-stack | train |
944523120f225d9996da19a8 | train | function | def google_search(search_term, api_key, cse_id, **kwargs):
service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
if 'items' in res:
return res['items']
else:
return []
| def google_search(search_term, api_key, cse_id, **kwargs):
| service = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
if 'items' in res:
return res['items']
else:
return []
| return 'GoogleConfig(api_key={}, cse_id={}, site={}, num={}, max_docs={}'.format(self.api_key,
self.cse_id,
self.site,
... | 63 | 64 | 77 | 16 | 47 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | google_search | google_search | 39 | 45 | 39 | 39 | 198740b28bc313125efb3871f111853feda30bf0 | bigcode/the-stack | train |
3269e9a018eb5c35c1d1f30c | train | function | def addHeuristics(l,claim):
if 'film' in claim.split() or '(film)' in claim.split() or 'film)' in claim.split():
if 'is' in claim.split():
l.append(claim.split('is')[0]+' '+'film')
if 'was' in claim.split():
l.append(claim.split('was')[0]+' '+'film')
if 'in the film' ... | def addHeuristics(l,claim):
| if 'film' in claim.split() or '(film)' in claim.split() or 'film)' in claim.split():
if 'is' in claim.split():
l.append(claim.split('is')[0]+' '+'film')
if 'was' in claim.split():
l.append(claim.split('was')[0]+' '+'film')
if 'in the film' in claim:
l.appe... | .pos_tag(claim)
s = ''
for w,p in zip(claim,pos):
if p[1][0]=='V' and w.islower():
s = s[:-1]
break
s = s+ w + ' '
if s:
entity = wikipedia.search(s,1)
else:
entity = []
if len(entity)>0:
x = entity[0]
x = x.replace(' ','_')
... | 152 | 153 | 512 | 9 | 143 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | addHeuristics | addHeuristics | 118 | 161 | 118 | 118 | d70976a3bdc4916d28a287ce6fba6d2a9c8e1a3a | bigcode/the-stack | train |
82c7756275acb61b7e0dce65 | train | function | def getDocsFromTFIDF(claim, ranker, k=10):
doc_names, doc_scores = ranker.closest_docs(claim, k)
pages = list(zip(doc_names, doc_scores))
return pages
| def getDocsFromTFIDF(claim, ranker, k=10):
| doc_names, doc_scores = ranker.closest_docs(claim, k)
pages = list(zip(doc_names, doc_scores))
return pages
| ('(','-LRB-')
x = x.replace(')','-RRB-')
x = x.replace(':','-COLON-')
rec.append(x)
rec = list(set(rec))
return rec
def getDocsFromTFIDF(claim, ranker, k=10):
| 64 | 64 | 48 | 17 | 46 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | getDocsFromTFIDF | getDocsFromTFIDF | 209 | 213 | 209 | 209 | 4ad8760a75d7389983ba8824d3b23f47dd2fd69c | bigcode/the-stack | train |
fd84f73e6d7a24f79ab22369 | train | function | def getDocsBatch(file,google_config,predictor,ranker):
for line in open(file):
line = json.loads(line.strip())
line.update(getDocsForClaim(line['claim'],google_config,predictor,ranker))
yield line
| def getDocsBatch(file,google_config,predictor,ranker):
| for line in open(file):
line = json.loads(line.strip())
line.update(getDocsForClaim(line['claim'],google_config,predictor,ranker))
yield line
| = []
for d in data:
claim = d['claim']
docs = getDocsForClaim(claim,google_config,predictor,ranker)
d.update(docs)
a.append(d)
return a
def getDocsBatch(file,google_config,predictor,ranker):
| 64 | 64 | 54 | 15 | 48 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | getDocsBatch | getDocsBatch | 268 | 272 | 268 | 268 | 951073501b0e6ba74ea6ae44404da777beb142fc | bigcode/the-stack | train |
9619c2bf3d372ff71f79fb91 | train | function | def getDocsSingle(data,google_config,predictor,ranker):
if str(type(data))=="<class 'dict'>":
return getDocsForClaim(data['claim'],google_config,predictor,ranker)
if str(type(data))=="<class 'list'>":
print('here')
a = []
for d in data:
claim = d['claim']
... | def getDocsSingle(data,google_config,predictor,ranker):
| if str(type(data))=="<class 'dict'>":
return getDocsForClaim(data['claim'],google_config,predictor,ranker)
if str(type(data))=="<class 'list'>":
print('here')
a = []
for d in data:
claim = d['claim']
docs = getDocsForClaim(claim,google_config,predictor,ran... | ] for d in docs ]
return dict(predicted_pages=docs, predicted_google=docs_google,
predicted_ner=docs_ner, predicted_dep_parse=docs_dep_parse,
predicted_tfidf=docs_tfidf)
def getDocsSingle(data,google_config,predictor,ranker):
| 64 | 64 | 116 | 15 | 49 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | getDocsSingle | getDocsSingle | 254 | 265 | 254 | 254 | 894bb83ccc05af4a7ffc90e9785b753a4a818023 | bigcode/the-stack | train |
ad19c62c4c978d9972cd8e2d | train | function | def getDocumentsFromConstituentParse(claim, predictor):
results = predictor.predict(sentence=claim)
nodes = [results['hierplane_tree']['root']]
candidates = []
while len(nodes):
node = nodes.pop(0)
if node['nodeType'] == 'NP':
#print(node)
candidates.append(node[... | def getDocumentsFromConstituentParse(claim, predictor):
| results = predictor.predict(sentence=claim)
nodes = [results['hierplane_tree']['root']]
candidates = []
while len(nodes):
node = nodes.pop(0)
if node['nodeType'] == 'NP':
#print(node)
candidates.append(node['word'])
if 'children' in node:
node... | ')
b = b.replace('%26','&')
b = b.replace('%27',"'")
b = b.replace('%22','"')
b = b.replace('%3F','?')
res.append(b)
return res
def getDocumentsFromConstituentParse(claim, predictor):
| 64 | 64 | 177 | 13 | 50 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | getDocumentsFromConstituentParse | getDocumentsFromConstituentParse | 69 | 92 | 69 | 69 | 9dd5e2a61eb2b5e94bb8ab375061dced47cd62ed | bigcode/the-stack | train |
c5987efa17a7133a6588eea9 | train | class | class GoogleConfig:
def __init__(self, api_key=None, cse_id=None, site='wikipedia', num=5, max_docs=2):
if 'API_KEY' in os.environ:
api_key = os.environ['API_KEY']
if 'SEARCH_ID' in os.environ:
cse_id = os.environ['SEARCH_ID']
assert(api_key is not None and cse_id is ... | class GoogleConfig:
| def __init__(self, api_key=None, cse_id=None, site='wikipedia', num=5, max_docs=2):
if 'API_KEY' in os.environ:
api_key = os.environ['API_KEY']
if 'SEARCH_ID' in os.environ:
cse_id = os.environ['SEARCH_ID']
assert(api_key is not None and cse_id is not None)
... | from time import sleep
from googleapiclient.discovery import build #google-api-python-client
import pprint
import nltk
import wikipedia
import ast
import unicodedata
from allennlp.service.predictors import Predictor
import time
import logging
logger = logging.getLogger(__name__)
class GoogleConfig:
| 64 | 64 | 184 | 4 | 60 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | GoogleConfig | GoogleConfig | 18 | 37 | 18 | 18 | 415d70b66861641e7bb2eb7790709ea5bf40bc93 | bigcode/the-stack | train |
f69191ae468ba7b7fcbf2ddb | train | function | def getDocumentsFromDepParse(claim):
claim = nltk.word_tokenize(claim)
pos = nltk.pos_tag(claim)
s = ''
for w,p in zip(claim,pos):
if p[1][0]=='V' and w.islower():
s = s[:-1]
break
s = s+ w + ' '
if s:
entity = wikipedia.search(s,1)
else:
e... | def getDocumentsFromDepParse(claim):
| claim = nltk.word_tokenize(claim)
pos = nltk.pos_tag(claim)
s = ''
for w,p in zip(claim,pos):
if p[1][0]=='V' and w.islower():
s = s[:-1]
break
s = s+ w + ' '
if s:
entity = wikipedia.search(s,1)
else:
entity = []
if len(entity)>0:
... | ]
x = x.replace(' ','_')
x = x.replace('(','-LRB-')
x = x.replace(')','-RRB-')
x = x.replace(':','-COLON-')
entities.append(x)
return entities
def getDocumentsFromDepParse(claim):
| 64 | 64 | 166 | 9 | 54 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | getDocumentsFromDepParse | getDocumentsFromDepParse | 94 | 115 | 94 | 94 | e272cac10d0c3998f38d4e3f0c13c26689daa9a1 | bigcode/the-stack | train |
cf674af9865d95084911d1e9 | train | function | def getDocumentsForClaimFromGoogle(claim, google_config):
results = google_search(google_config.site+' '+claim, google_config.api_key,
google_config.cse_id, num=google_config.num)
logger.info(google_config)
res = []
c = 0
for result in results:
logger.info(res... | def getDocumentsForClaimFromGoogle(claim, google_config):
| results = google_search(google_config.site+' '+claim, google_config.api_key,
google_config.cse_id, num=google_config.num)
logger.info(google_config)
res = []
c = 0
for result in results:
logger.info(result['formattedUrl'])
#if 'https://en.wikipedia.org/wik... | = build("customsearch", "v1", developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
if 'items' in res:
return res['items']
else:
return []
def getDocumentsForClaimFromGoogle(claim, google_config):
| 73 | 73 | 244 | 14 | 59 | zahrahosseini99/fever2-columbia | src/doc/getDocuments.py | Python | getDocumentsForClaimFromGoogle | getDocumentsForClaimFromGoogle | 47 | 67 | 47 | 47 | 38714d839b17aedf52b5a0d85cd320517a421bcb | bigcode/the-stack | train |
fb6f7a0958bbba5c397e2c71 | train | function | @task(ignore_result=True)
def delete_unreferenced_expressions():
"""删除未被引用的expression"""
iam.delete_unreferenced_expressions()
| @task(ignore_result=True)
def delete_unreferenced_expressions():
| """删除未被引用的expression"""
iam.delete_unreferenced_expressions()
| _scopes.append(role_scope)
# 批量更新分级管理员授权范围
if len(updated_role_scopes) > 0:
RoleScope.objects.bulk_update(updated_role_scopes, fields=["content"], batch_size=10)
@task(ignore_result=True)
def delete_unreferenced_expressions():
| 64 | 64 | 32 | 14 | 50 | Chace-wang/bk-iam-saas | saas/backend/apps/policy/tasks.py | Python | delete_unreferenced_expressions | delete_unreferenced_expressions | 181 | 184 | 181 | 182 | 74c0d4e04e48979bc72282acd3846a968699aa2b | bigcode/the-stack | train |
57dda5645c74f1f67f4c626c | train | class | class ModelChangeEventTypeEnum(ChoicesEnum, LowerStrEnum):
ActionPolicyDeleted = "action_policy_deleted"
ActionDeleted = "action_deleted"
| class ModelChangeEventTypeEnum(ChoicesEnum, LowerStrEnum):
| ActionPolicyDeleted = "action_policy_deleted"
ActionDeleted = "action_deleted"
| import RoleScopeType
from backend.util.enum import ChoicesEnum
from backend.util.json import json_dumps
logger = logging.getLogger("celery")
# TODO: [重构]单独的ModelChangeEvent的Service和Biz模块
class ModelChangeEventTypeEnum(ChoicesEnum, LowerStrEnum):
| 64 | 64 | 32 | 14 | 49 | Chace-wang/bk-iam-saas | saas/backend/apps/policy/tasks.py | Python | ModelChangeEventTypeEnum | ModelChangeEventTypeEnum | 32 | 34 | 32 | 32 | 8bcf09e1467d8b95e91e5cf4e14d275da1d2d77e | bigcode/the-stack | train |
c1aa6807ec51948da9fd36c3 | train | class | class ModelChangeEventStatusEnum(ChoicesEnum, LowerStrEnum):
Pending = auto()
Finished = auto()
| class ModelChangeEventStatusEnum(ChoicesEnum, LowerStrEnum):
| Pending = auto()
Finished = auto()
| TODO: [重构]单独的ModelChangeEvent的Service和Biz模块
class ModelChangeEventTypeEnum(ChoicesEnum, LowerStrEnum):
ActionPolicyDeleted = "action_policy_deleted"
ActionDeleted = "action_deleted"
class ModelChangeEventStatusEnum(ChoicesEnum, LowerStrEnum):
| 64 | 64 | 24 | 14 | 50 | Chace-wang/bk-iam-saas | saas/backend/apps/policy/tasks.py | Python | ModelChangeEventStatusEnum | ModelChangeEventStatusEnum | 37 | 39 | 37 | 37 | 70f2d59fe057cc671e2733c046ae8d910bed385f | bigcode/the-stack | train |
fcd043a423ec829171dcb4c3 | train | function | @task(ignore_result=True)
def execute_model_change_event():
"""作为后台模型事件的异步任务消费者,目前包括删除Action的相关策略,删除Action权限模型"""
# 1. 查询模型变更事件
events = iam.list_model_change_event(ModelChangeEventStatusEnum.Pending.value)
if len(events) == 0:
return
# 2. 遍历每个事件,执行对应任务
# 记录失败事件
failed_events = set(... | @task(ignore_result=True)
def execute_model_change_event():
| """作为后台模型事件的异步任务消费者,目前包括删除Action的相关策略,删除Action权限模型"""
# 1. 查询模型变更事件
events = iam.list_model_change_event(ModelChangeEventStatusEnum.Pending.value)
if len(events) == 0:
return
# 2. 遍历每个事件,执行对应任务
# 记录失败事件
failed_events = set()
for event in events:
event_type, system_id, ac... | ery")
# TODO: [重构]单独的ModelChangeEvent的Service和Biz模块
class ModelChangeEventTypeEnum(ChoicesEnum, LowerStrEnum):
ActionPolicyDeleted = "action_policy_deleted"
ActionDeleted = "action_deleted"
class ModelChangeEventStatusEnum(ChoicesEnum, LowerStrEnum):
Pending = auto()
Finished = auto()
# TODO: [重构]... | 123 | 123 | 411 | 12 | 110 | Chace-wang/bk-iam-saas | saas/backend/apps/policy/tasks.py | Python | execute_model_change_event | execute_model_change_event | 43 | 83 | 43 | 44 | 0fc42cc6306a00f4ee7eeba833c3aa0b61ec53ab | bigcode/the-stack | train |
5a976caf72269d30bfcb7917 | train | function | def delete_action_policies(system_id: str, action_id: str):
"""删除某个操作的所有策略"""
# 1. 用户或用户组自定义权限删除
Policy.objects.filter(system_id=system_id, action_id=action_id).delete()
# 2. 权限模板:变更权限模板里的action_ids及其授权的数据
_delete_action_from_perm_template(system_id, action_id)
# 3. 调用后台根据action_id删除Policy的API... | def delete_action_policies(system_id: str, action_id: str):
| """删除某个操作的所有策略"""
# 1. 用户或用户组自定义权限删除
Policy.objects.filter(system_id=system_id, action_id=action_id).delete()
# 2. 权限模板:变更权限模板里的action_ids及其授权的数据
_delete_action_from_perm_template(system_id, action_id)
# 3. 调用后台根据action_id删除Policy的API, 实际测试在150万策略里删除10万+策略,大概需要3秒多
iam.delete_action_policie... | 事件状态
iam.update_model_change_event(event["pk"], ModelChangeEventStatusEnum.Finished.value)
except Exception:
logger.exception(f"execute model change event fail! event={event}")
# 记录失败事件
failed_events.add((event_type, system_id, action_id))
def delete_action_polici... | 77 | 77 | 257 | 15 | 62 | Chace-wang/bk-iam-saas | saas/backend/apps/policy/tasks.py | Python | delete_action_policies | delete_action_policies | 86 | 106 | 86 | 86 | 603bb6c940d4e6b8b3a872a452834458d7c8487c | bigcode/the-stack | train |
706d4f9920df9baec8197fd3 | train | function | def _delete_action_from_perm_template(system_id: str, action_id: str):
"""从权限模板里移除Action,同时包括权限模板的授权"""
# 1 变更权限模板
perm_templates = PermTemplate.objects.filter(system_id=system_id)
modified_perm_template_ids = []
updated_perm_templates = []
for pt in perm_templates:
action_ids = pt.actio... | def _delete_action_from_perm_template(system_id: str, action_id: str):
| """从权限模板里移除Action,同时包括权限模板的授权"""
# 1 变更权限模板
perm_templates = PermTemplate.objects.filter(system_id=system_id)
modified_perm_template_ids = []
updated_perm_templates = []
for pt in perm_templates:
action_ids = pt.action_ids
# 要删除的Action不在权限模板里,则忽略
if action_id not in actio... | listconfig
AuthAPIAllowListConfig.objects.filter(
type=AuthorizationAPIEnum.AUTHORIZATION_INSTANCE.value, system_id=system_id, object_id=action_id
).delete()
def delete_action(system_id: str, action_id: str):
"""删除Action权限模型"""
iam.delete_action(system_id, action_id)
# TODO: [重构]_delete_acti... | 115 | 115 | 386 | 17 | 97 | Chace-wang/bk-iam-saas | saas/backend/apps/policy/tasks.py | Python | _delete_action_from_perm_template | _delete_action_from_perm_template | 115 | 151 | 115 | 115 | 0d25c46226c2e7e48044e5fb0ec17c8826bf2845 | bigcode/the-stack | train |
0bd2d04b0042b15ff6273a63 | train | function | def delete_action(system_id: str, action_id: str):
"""删除Action权限模型"""
iam.delete_action(system_id, action_id)
| def delete_action(system_id: str, action_id: str):
| """删除Action权限模型"""
iam.delete_action(system_id, action_id)
| 6. API白名单授权:authorization_authapiallowlistconfig
AuthAPIAllowListConfig.objects.filter(
type=AuthorizationAPIEnum.AUTHORIZATION_INSTANCE.value, system_id=system_id, object_id=action_id
).delete()
def delete_action(system_id: str, action_id: str):
| 64 | 64 | 30 | 13 | 51 | Chace-wang/bk-iam-saas | saas/backend/apps/policy/tasks.py | Python | delete_action | delete_action | 109 | 111 | 109 | 109 | 587baaa3e762775201da3a3f6b4b402fda964b30 | bigcode/the-stack | train |
e0f840ffc7e9e0c780495869 | train | function | def _delete_action_from_role_scope(system_id: str, action_id: str):
"""从分级管理员的授权范围里删除操作"""
role_scopes = RoleScope.objects.filter(type=RoleScopeType.AUTHORIZATION.value)
updated_role_scopes = []
for role_scope in role_scopes:
content = json.loads(role_scope.content)
is_updated = False
... | def _delete_action_from_role_scope(system_id: str, action_id: str):
| """从分级管理员的授权范围里删除操作"""
role_scopes = RoleScope.objects.filter(type=RoleScopeType.AUTHORIZATION.value)
updated_role_scopes = []
for role_scope in role_scopes:
content = json.loads(role_scope.content)
is_updated = False
for scope in content:
if scope["system_id"] != sys... |
updated_perm_template_policy_authorizeds.append(ptpa)
if len(updated_perm_template_policy_authorizeds) > 0:
PermTemplatePolicyAuthorized.objects.bulk_update(
updated_perm_template_policy_authorizeds, fields=["_data"], batch_size=20
)
def _delete_action_from_r... | 75 | 75 | 253 | 17 | 58 | Chace-wang/bk-iam-saas | saas/backend/apps/policy/tasks.py | Python | _delete_action_from_role_scope | _delete_action_from_role_scope | 154 | 178 | 154 | 154 | 6285e4b53cc73082891ce923c8b3549e6eb1e6a2 | bigcode/the-stack | train |
17a00dd6ba4f995a03723c32 | train | class | class MMOCR:
def __init__(self,
det='PANet_IC15',
det_config='',
det_ckpt='',
recog='SEG',
recog_config='',
recog_ckpt='',
kie='',
kie_config='',
kie_ckpt='',
... | class MMOCR:
| def __init__(self,
det='PANet_IC15',
det_config='',
det_ckpt='',
recog='SEG',
recog_config='',
recog_ckpt='',
kie='',
kie_config='',
kie_ckpt='',
... | '
)
parser.add_argument(
'--imshow',
action='store_true',
help='Whether show image with OpenCV.')
parser.add_argument(
'--print-result',
action='store_true',
help='Prints the recognised text')
parser.add_argument(
'--merge', action='store_true', he... | 256 | 256 | 5,068 | 4 | 251 | NceBoy/mmocr | mmocr/utils/ocr.py | Python | MMOCR | MMOCR | 164 | 704 | 164 | 165 | 2eb92150ed158514e72e072d2c4f5fe04a8a27c4 | bigcode/the-stack | train |
5a1edc69f7f0a8241e22b1aa | train | function | def parse_args():
parser = ArgumentParser()
parser.add_argument(
'img', type=str, help='Input image file or folder path.')
parser.add_argument(
'--output',
type=str,
default='',
help='Output file/folder name for visualization')
parser.add_argument(
'--det'... | def parse_args():
| parser = ArgumentParser()
parser.add_argument(
'img', type=str, help='Input image file or folder path.')
parser.add_argument(
'--output',
type=str,
default='',
help='Output file/folder name for visualization')
parser.add_argument(
'--det',
type=str... | #!/usr/bin/env python
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import os
import warnings
from argparse import ArgumentParser, Namespace
from pathlib import Path
import mmcv
import numpy as np
import torch
from mmcv.image.misc import tensor2imgs
from mmcv.runner import load_checkpoint
from mmcv.utils... | 188 | 256 | 947 | 4 | 183 | NceBoy/mmocr | mmocr/utils/ocr.py | Python | parse_args | parse_args | 28 | 161 | 28 | 28 | ae30fec6a75c52d8d329615e4b3eaaf83415719a | bigcode/the-stack | train |
de448fd5eb3635e48fd8ef91 | train | function | def main():
args = parse_args()
ocr = MMOCR(**vars(args))
ocr.readtext(**vars(args))
| def main():
| args = parse_args()
ocr = MMOCR(**vars(args))
ocr.readtext(**vars(args))
| Path(args.export)
args.export = [
str(export_path / f'out_{x}.{args.export_format}')
for x in args.filenames
]
else:
args.export = [None] * num_res
return args
# Create an inference pipeline with parsed arguments
def main():
| 64 | 64 | 28 | 3 | 60 | NceBoy/mmocr | mmocr/utils/ocr.py | Python | main | main | 708 | 711 | 708 | 708 | 6b3a0c3330480784558ef4f6ab071b76667e7eea | bigcode/the-stack | train |
e52ee0e60ccb6e634d8c5f8d | train | class | class ManageUserView(generics.RetrieveUpdateAPIView):
"""Manage the authenticated user"""
serializer_class = serializers.UserSerializer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get_object(self):
return self.reques... | class ManageUserView(generics.RetrieveUpdateAPIView):
| """Manage the authenticated user"""
serializer_class = serializers.UserSerializer
authentication_classes = (authentication.TokenAuthentication,)
permission_classes = (permissions.IsAuthenticated,)
def get_object(self):
return self.request.user
| the system"""
serializer_class = serializers.UserSerializer
class CreateTokenView(ObtainAuthToken):
"""Create a new auth token for the user"""
serializer_class = serializers.AuthTokenSerializer
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
class ManageUserView(generics.RetrieveUpdateAPIVie... | 64 | 64 | 58 | 12 | 51 | pydevsp/recipe_app_API | app/user/views.py | Python | ManageUserView | ManageUserView | 19 | 26 | 19 | 19 | ba055e78b5f2e7d8edea1ac61eefc51a7eddb8b6 | bigcode/the-stack | train |
d3c50a29c3bad3c3e601c3ae | train | class | class CreateTokenView(ObtainAuthToken):
"""Create a new auth token for the user"""
serializer_class = serializers.AuthTokenSerializer
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
| class CreateTokenView(ObtainAuthToken):
| """Create a new auth token for the user"""
serializer_class = serializers.AuthTokenSerializer
renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES
|
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from . import serializers
class CreateUserView(generics.CreateAPIView):
"""Create a new user in the system"""
serializer_class = serializers.UserSerializer
class CreateTokenView(ObtainAuthToken):
| 64 | 64 | 41 | 10 | 53 | pydevsp/recipe_app_API | app/user/views.py | Python | CreateTokenView | CreateTokenView | 13 | 16 | 13 | 13 | aebefd4aa7c517fc6bca2c3d1b952efd103c7126 | bigcode/the-stack | train |
4b7f1861be24eeef3e345b77 | train | class | class CreateUserView(generics.CreateAPIView):
"""Create a new user in the system"""
serializer_class = serializers.UserSerializer
| class CreateUserView(generics.CreateAPIView):
| """Create a new user in the system"""
serializer_class = serializers.UserSerializer
| from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from . import serializers
class CreateUserView(generics.CreateAPIView):
| 46 | 64 | 28 | 10 | 35 | pydevsp/recipe_app_API | app/user/views.py | Python | CreateUserView | CreateUserView | 8 | 10 | 8 | 8 | 914895f40204b48f6778c47188a0fe09bb8019d7 | bigcode/the-stack | train |
7871c85723a6ece65dba538c | train | class | class CitationStyleList(JSONAPIBaseView, generics.ListAPIView, ODMFilterMixin):
'''List of standard citation styles available for rendering citations. *Read-only*
##Note
**This API endpoint is under active development, and is subject to change in the future**
##Citation Attributes
name ... | class CitationStyleList(JSONAPIBaseView, generics.ListAPIView, ODMFilterMixin):
| '''List of standard citation styles available for rendering citations. *Read-only*
##Note
**This API endpoint is under active development, and is subject to change in the future**
##Citation Attributes
name type description
=================================... | get_object_or_error
from api.base.views import JSONAPIBaseView
from api.citations.serializers import CitationSerializer
from framework.auth.oauth_scopes import CoreScopes
from rest_framework import permissions as drf_permissions
from rest_framework import generics
from osf.models.citation import CitationStyle
class Ci... | 80 | 80 | 269 | 18 | 61 | hmoco/osf.io | api/citations/views.py | Python | CitationStyleList | CitationStyleList | 13 | 48 | 13 | 13 | ad5197de205291e37f04dc923c4b1d5851f7e86a | bigcode/the-stack | train |
4ba2ddc3f48ad3e41981425a | train | class | class CitationStyleDetail(JSONAPIBaseView, generics.RetrieveAPIView):
'''Detail for a citation style *Read-only*
##Note
**This API endpoint is under active development, and is subject to change in the future**
##Citation Attributes
name type description
===========... | class CitationStyleDetail(JSONAPIBaseView, generics.RetrieveAPIView):
| '''Detail for a citation style *Read-only*
##Note
**This API endpoint is under active development, and is subject to change in the future**
##Citation Attributes
name type description
=========================================================================
dat... | SizePagination
view_category = 'citations'
view_name = 'citation-list'
# overrides ListAPIView
def get_default_odm_query(self):
return
def get_queryset(self):
return CitationStyle.find(self.get_query_from_request())
class CitationStyleDetail(JSONAPIBaseView, generics.RetrieveAPIVie... | 69 | 69 | 232 | 15 | 54 | hmoco/osf.io | api/citations/views.py | Python | CitationStyleDetail | CitationStyleDetail | 50 | 80 | 50 | 50 | 3dd0e866fbbd6178958022e19111a9aa0f378084 | bigcode/the-stack | train |
84e3204a90e4a6001297ff65 | train | function | def get_notebook_name():
log_path = '/opt/ml/metadata/resource-metadata.json'
with open(log_path, 'r') as logs:
_logs = json.load(logs)
return _logs['ResourceName']
| def get_notebook_name():
| log_path = '/opt/ml/metadata/resource-metadata.json'
with open(log_path, 'r') as logs:
_logs = json.load(logs)
return _logs['ResourceName']
| if (datetime.now() - last_activity).total_seconds() > time:
print('Notebook is idle. Last activity time = ', last_activity)
return True
else:
print('Notebook is not idle. Last activity time = ', last_activity)
return False
def get_notebook_name():
| 64 | 64 | 49 | 6 | 57 | nguyen102/service-workbench-on-aws | main/solution/post-deployment/config/environment-files/offline-packages/sagemaker/autostop.py | Python | get_notebook_name | get_notebook_name | 81 | 85 | 81 | 81 | 04a3065e070c3f841f938e70afa5c18c923bda1e | bigcode/the-stack | train |
889da777c47e99f2ea220421 | train | function | def is_idle(last_activity):
last_activity = datetime.strptime(last_activity,"%Y-%m-%dT%H:%M:%S.%fz")
if (datetime.now() - last_activity).total_seconds() > time:
print('Notebook is idle. Last activity time = ', last_activity)
return True
else:
print('Notebook is not idle. Last activit... | def is_idle(last_activity):
| last_activity = datetime.strptime(last_activity,"%Y-%m-%dT%H:%M:%S.%fz")
if (datetime.now() - last_activity).total_seconds() > time:
print('Notebook is idle. Last activity time = ', last_activity)
return True
else:
print('Notebook is not idle. Last activity time = ', last_activity)
... |
except getopt.GetoptError:
print(usageInfo)
exit(1)
# Missing configuration notification
missingConfiguration = False
if not time:
print("Missing '-t' or '--time'")
missingConfiguration = True
if missingConfiguration:
exit(2)
def is_idle(last_activity):
| 64 | 64 | 88 | 6 | 58 | nguyen102/service-workbench-on-aws | main/solution/post-deployment/config/environment-files/offline-packages/sagemaker/autostop.py | Python | is_idle | is_idle | 71 | 78 | 71 | 71 | 75823791ace6f38799dd80d737b764f00710458b | bigcode/the-stack | train |
1d00e3bdfaea8e8d8f8f4596 | train | function | def fitnessFunction(chromosome):
"""
Given a "chromosome", this function must determine its fitness score
The fitness score should be a floating point value. If the fitness is zero or smaller
then the chromosome will not be allowed to "reproduce"
"""
#you can access the attributes of a chrom... | def fitnessFunction(chromosome):
| """
Given a "chromosome", this function must determine its fitness score
The fitness score should be a floating point value. If the fitness is zero or smaller
then the chromosome will not be allowed to "reproduce"
"""
#you can access the attributes of a chromosome using square brackets
#... | import math
from pyvolution.EvolutionManager import *
from pyvolution.GeneLibrary import *
"""
This example attempts to find a solution to the following system of equations:
a + b + c + d - 17 = 0
a^2 + b^2 - 5 = 0
sin(a) + c - d - 20 = 0
"""
def fitnessFunction(chromosome):
| 84 | 90 | 301 | 7 | 77 | littley/pyvolution | examples/EquationSolver_advanced.py | Python | fitnessFunction | fitnessFunction | 15 | 41 | 15 | 15 | 23e1e37a35f156a3d99a53c402e001a56485100e | bigcode/the-stack | train |
e17777330cabc8cc030650a8 | train | function | @webhook_view("HelloSign")
@has_request_variables
def api_hellosign_webhook(
request: HttpRequest,
user_profile: UserProfile,
payload: Dict[str, Dict[str, Any]] = REQ(whence="json", converter=orjson.loads),
) -> HttpResponse:
if "signature_request" in payload:
body = get_message_body(payload)
... | @webhook_view("HelloSign")
@has_request_variables
def api_hellosign_webhook(
request: HttpRequest,
user_profile: UserProfile,
payload: Dict[str, Dict[str, Any]] = REQ(whence="json", converter=orjson.loads),
) -> HttpResponse:
| if "signature_request" in payload:
body = get_message_body(payload)
topic = payload["signature_request"]["title"]
check_send_webhook_message(request, user_profile, topic, body)
return json_success({"msg": "Hello API Event Received"})
| @webhook_view("HelloSign")
@has_request_variables
def api_hellosign_webhook(
request: HttpRequest,
user_profile: UserProfile,
payload: Dict[str, Dict[str, Any]] = REQ(whence="json", converter=orjson.loads),
) -> HttpResponse:
| 66 | 64 | 121 | 66 | 0 | TylerPham2000/zulip | zerver/webhooks/hellosign/view.py | Python | api_hellosign_webhook | api_hellosign_webhook | 57 | 69 | 57 | 63 | c95563684351bd85a1f476388b48a7fabe48f895 | bigcode/the-stack | train |
96d8fe486a0f09adab655a6e | train | function | def get_message_body(payload: Dict[str, Dict[str, Any]]) -> str:
contract_title = payload["signature_request"]["title"]
recipients: Dict[str, List[str]] = {}
signatures = payload["signature_request"]["signatures"]
for signature in signatures:
recipients.setdefault(signature["status_code"], [])
... | def get_message_body(payload: Dict[str, Dict[str, Any]]) -> str:
| contract_title = payload["signature_request"]["title"]
recipients: Dict[str, List[str]] = {}
signatures = payload["signature_request"]["signatures"]
for signature in signatures:
recipients.setdefault(signature["status_code"], [])
recipients[signature["status_code"]].append(signature["si... | _SIGNATURE = "is awaiting the signature of {awaiting_recipients}"
WAS_JUST_SIGNED_BY = "was just signed by {signed_recipients}"
BODY = "The `{contract_title}` document {actions}."
def get_message_body(payload: Dict[str, Dict[str, Any]]) -> str:
| 64 | 64 | 208 | 17 | 47 | TylerPham2000/zulip | zerver/webhooks/hellosign/view.py | Python | get_message_body | get_message_body | 17 | 42 | 17 | 17 | 954ac4ed101bac9c22159a46d45ee7f12676a1c4 | bigcode/the-stack | train |
667a153673918df17ba0f838 | train | function | def get_recipients_text(recipients: List[str]) -> str:
recipients_text = ""
if len(recipients) == 1:
recipients_text = "{}".format(*recipients)
else:
for recipient in recipients[:-1]:
recipients_text += f"{recipient}, "
recipients_text += f"and {recipients[-1]}"
retu... | def get_recipients_text(recipients: List[str]) -> str:
| recipients_text = ""
if len(recipients) == 1:
recipients_text = "{}".format(*recipients)
else:
for recipient in recipients[:-1]:
recipients_text += f"{recipient}, "
recipients_text += f"and {recipients[-1]}"
return recipients_text
| )
if recipients_text:
recipients_text = f"{recipients_text}, and {text}"
else:
recipients_text = text
return BODY.format(contract_title=contract_title, actions=recipients_text).strip()
def get_recipients_text(recipients: List[str]) -> str:
| 64 | 64 | 82 | 16 | 48 | TylerPham2000/zulip | zerver/webhooks/hellosign/view.py | Python | get_recipients_text | get_recipients_text | 45 | 54 | 45 | 45 | 5e775d2e425bb568ea37451c1ead9992602e2054 | bigcode/the-stack | train |
b6586ad6b6277e9d2619cc95 | train | function | def get_extra_data(obj_class):
extra_data = tuple()
# Get the SCHEMA items to add to the fingerprint
# if we are looking at a notification
if issubclass(obj_class, notification.NotificationPayloadBase):
schema_data = collections.OrderedDict(
sorted(obj_class.SCHEMA.items()))
... | def get_extra_data(obj_class):
| extra_data = tuple()
# Get the SCHEMA items to add to the fingerprint
# if we are looking at a notification
if issubclass(obj_class, notification.NotificationPayloadBase):
schema_data = collections.OrderedDict(
sorted(obj_class.SCHEMA.items()))
extra_data += (schema_data,)
... | es(extra_data_func=get_extra_data)
TestNotificationPayload.SCHEMA['field_3'] = ('source_field',
'field_3')
new_hash = checker.get_hashes(extra_data_func=get_extra_data)
self.assertNotEqual(old_hash, new_hash)
def get_extra_data(obj_class):
| 64 | 64 | 81 | 7 | 57 | sapcc/nova | nova/tests/unit/notifications/objects/test_notification.py | Python | get_extra_data | get_extra_data | 462 | 473 | 462 | 462 | dd13b06d9c486a2add9d2efdf58de5fe37b713c9 | bigcode/the-stack | train |
59f24376f33337da2c3e80fc | train | class | class TestNotificationObjectVersions(test.NoDBTestCase):
def setUp(self):
super(TestNotificationObjectVersions, self).setUp()
base.NovaObjectRegistry.register_notification_objects()
def test_versions(self):
checker = fixture.ObjectVersionChecker(
test_objects.get_nova_object... | class TestNotificationObjectVersions(test.NoDBTestCase):
| def setUp(self):
super(TestNotificationObjectVersions, self).setUp()
base.NovaObjectRegistry.register_notification_objects()
def test_versions(self):
checker = fixture.ObjectVersionChecker(
test_objects.get_nova_objects())
notification_object_data.update(test_objects... | ServiceStatusNotification': '1.0-a73147b93b520ff0061865849d3dfa56',
'ServiceStatusPayload': '1.1-7b6856bd879db7f3ecbcd0ca9f35f92f',
'VMWareLiveMigrateData': '1.1-13e17ad269e942ef13a8af7f5e402da7',
}
class TestNotificationObjectVersions(test.NoDBTestCase):
| 104 | 104 | 349 | 11 | 93 | sapcc/nova | nova/tests/unit/notifications/objects/test_notification.py | Python | TestNotificationObjectVersions | TestNotificationObjectVersions | 419 | 459 | 419 | 419 | 512a2e488f77bdd9b374dca4219ae1b59e15dcd3 | bigcode/the-stack | train |
674fee7f7ec872ddadb12d84 | train | class | class TestNotificationBase(test.NoDBTestCase):
@base.NovaObjectRegistry.register_if(False)
class TestObject(base.NovaObject):
VERSION = '1.0'
fields = {
'field_1': fields.StringField(),
'field_2': fields.IntegerField(),
'not_important_field': fields.IntegerFi... | class TestNotificationBase(test.NoDBTestCase):
@base.NovaObjectRegistry.register_if(False)
| class TestObject(base.NovaObject):
VERSION = '1.0'
fields = {
'field_1': fields.StringField(),
'field_2': fields.IntegerField(),
'not_important_field': fields.IntegerField(),
'lazy_field': fields.IntegerField()
}
def obj_load_attr(self... | # All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | 235 | 256 | 2,528 | 21 | 213 | sapcc/nova | nova/tests/unit/notifications/objects/test_notification.py | Python | TestNotificationBase | TestNotificationBase | 30 | 365 | 30 | 32 | 00a17a595615cf0fda078d32130e4ec1499bd519 | bigcode/the-stack | train |
ad466a12b99400809a304a30 | train | function | def is_norm(modules):
"""Check if is one of the norms."""
if isinstance(modules, (_BatchNorm, )):
return True
return False
| def is_norm(modules):
| """Check if is one of the norms."""
if isinstance(modules, (_BatchNorm, )):
return True
return False
| import pytest
import torch
from torch.nn.modules.batchnorm import _BatchNorm
from mmpose.models.backbones import LiteHRNet
from mmpose.models.backbones.litehrnet import LiteHRModule
from mmpose.models.backbones.resnet import Bottleneck
def is_norm(modules):
| 64 | 64 | 36 | 6 | 57 | nightfuryyy/mmpose | tests/test_backbones/test_litehrnet.py | Python | is_norm | is_norm | 11 | 15 | 11 | 11 | 6292048dbac8263189cf38bccb37b15e6b5a3f41 | bigcode/the-stack | train |
bcac7d648cbc6f6da86041c4 | train | function | def test_litehrmodule():
# Test LiteHRModule forward
block = LiteHRModule(
num_branches=1,
num_blocks=1,
in_channels=[
40,
],
reduce_ratio=8,
module_type='LITE')
x = torch.randn(2, 40, 56, 56)
x_out = block([[x]])
assert x_out[0][0].shape ... | def test_litehrmodule():
# Test LiteHRModule forward
| block = LiteHRModule(
num_branches=1,
num_blocks=1,
in_channels=[
40,
],
reduce_ratio=8,
module_type='LITE')
x = torch.randn(2, 40, 56, 56)
x_out = block([[x]])
assert x_out[0][0].shape == torch.Size([2, 40, 56, 56])
block = LiteHRModule(... | ules.weight.data,
torch.zeros_like(modules.weight.data))
if hasattr(modules, 'bias'):
bias_zero = torch.equal(modules.bias.data,
torch.zeros_like(modules.bias.data))
else:
bias_zero = True
return weight_zero and bias_zero
def tes... | 74 | 74 | 248 | 15 | 58 | nightfuryyy/mmpose | tests/test_backbones/test_litehrnet.py | Python | test_litehrmodule | test_litehrmodule | 31 | 67 | 31 | 32 | a465ba06c13a3d9f9261731f02fbe8a251d7a412 | bigcode/the-stack | train |
20cac8d8a478e737f1922cb0 | train | function | def test_litehrnet_backbone():
extra = dict(
stem=dict(stem_channels=32, out_channels=32, expand_ratio=1),
num_stages=3,
stages_spec=dict(
num_modules=(2, 4, 2),
num_branches=(2, 3, 4),
num_blocks=(2, 2, 2),
module_type=('LITE', 'LITE', 'LITE')... | def test_litehrnet_backbone():
| extra = dict(
stem=dict(stem_channels=32, out_channels=32, expand_ratio=1),
num_stages=3,
stages_spec=dict(
num_modules=(2, 4, 2),
num_branches=(2, 3, 4),
num_blocks=(2, 2, 2),
module_type=('LITE', 'LITE', 'LITE'),
with_fuse=(True, ... | ='LITE')
x = torch.randn(2, 40, 56, 56)
x_out = block([[x]])
assert x_out[0][0].shape == torch.Size([2, 40, 56, 56])
block = LiteHRModule(
num_branches=1,
num_blocks=1,
in_channels=[
40,
],
reduce_ratio=8,
module_type='NAIVE')
x = torch.... | 203 | 203 | 679 | 9 | 194 | nightfuryyy/mmpose | tests/test_backbones/test_litehrnet.py | Python | test_litehrnet_backbone | test_litehrnet_backbone | 70 | 143 | 70 | 70 | 710d7c4ef4130c70e19b809c238b5559444031fb | bigcode/the-stack | train |
ef3cae06417b86e06949de23 | train | function | def all_zeros(modules):
"""Check if the weight(and bias) is all zero."""
weight_zero = torch.equal(modules.weight.data,
torch.zeros_like(modules.weight.data))
if hasattr(modules, 'bias'):
bias_zero = torch.equal(modules.bias.data,
torch.z... | def all_zeros(modules):
| """Check if the weight(and bias) is all zero."""
weight_zero = torch.equal(modules.weight.data,
torch.zeros_like(modules.weight.data))
if hasattr(modules, 'bias'):
bias_zero = torch.equal(modules.bias.data,
torch.zeros_like(modules.bias.d... | itehrnet import LiteHRModule
from mmpose.models.backbones.resnet import Bottleneck
def is_norm(modules):
"""Check if is one of the norms."""
if isinstance(modules, (_BatchNorm, )):
return True
return False
def all_zeros(modules):
| 64 | 64 | 86 | 7 | 56 | nightfuryyy/mmpose | tests/test_backbones/test_litehrnet.py | Python | all_zeros | all_zeros | 18 | 28 | 18 | 18 | 41f5521fa2c3cf689ac324c2eafe720876333b1f | bigcode/the-stack | train |
6fa87b592840e4b12f3dea3d | train | class | class Appr(object):
# Based on paper and largely on https://github.com/dai-dao/pathnet-pytorch and https://github.com/kimhc6028/pathnet-pytorch
#Paper name "PathNet: Evolution Channels Gradient Descent in Super Neural Networks"
def __init__(self,model,nepochs=100,sbatch=64,lr=0.05,lr_min=1e-4,lr_factor=3,lr... | class Appr(object):
# Based on paper and largely on https://github.com/dai-dao/pathnet-pytorch and https://github.com/kimhc6028/pathnet-pytorch
#Paper name "PathNet: Evolution Channels Gradient Descent in Super Neural Networks"
| def __init__(self,model,nepochs=100,sbatch=64,lr=0.05,lr_min=1e-4,lr_factor=3,lr_patience=5,clipgrad=1000,generations=20,args=None):
self.model=model
self.initial_model=deepcopy(model)
#architecture hyperparams (must be the same as alexnet_pathnet)
self.N = self.model.N # from pap... | import sys,time
import numpy as np
import torch
import random
import utils
from copy import deepcopy
class Appr(object):
# Based on paper and largely on https://github.com/dai-dao/pathnet-pytorch and https://github.com/kimhc6028/pathnet-pytorch
#Paper name "PathNet: Evolution Channels Gradient Descent in Super... | 81 | 256 | 1,835 | 58 | 22 | dionis/ABSA-DeepMultidomain | approaches/pathnet.py | Python | Appr | Appr | 9 | 210 | 9 | 11 | 6132b358104253dc9786614069512d959ef67ad5 | bigcode/the-stack | train |
7912afde40526f14f154b821 | train | class | @test_util.test_all_tf_execution_regimes
class SmoothSeasonalTest(test_util.TestCase, _StsTestHarness):
def _build_sts(self, observed_time_series=None):
return SmoothSeasonal(period=42,
frequency_multipliers=[1, 2, 4],
observed_time_series=observed_time_series)... | @test_util.test_all_tf_execution_regimes
class SmoothSeasonalTest(test_util.TestCase, _StsTestHarness):
| def _build_sts(self, observed_time_series=None):
return SmoothSeasonal(period=42,
frequency_multipliers=[1, 2, 4],
observed_time_series=observed_time_series)
| _util.TestCase, _StsTestHarness):
def _build_sts(self, observed_time_series=None):
return SemiLocalLinearTrend(observed_time_series=observed_time_series)
@test_util.test_all_tf_execution_regimes
class SmoothSeasonalTest(test_util.TestCase, _StsTestHarness):
| 64 | 64 | 71 | 25 | 39 | fearghus-moloco/probability | tensorflow_probability/python/sts/structural_time_series_test.py | Python | SmoothSeasonalTest | SmoothSeasonalTest | 453 | 459 | 453 | 455 | 69a8ab59dc57ee0550f2bf4a23413983d5bdefbc | bigcode/the-stack | train |
957fd18415656712b57b3486 | train | class | @test_util.test_all_tf_execution_regimes
class SeasonalWithMultipleStepsAndNoiseTest(test_util.TestCase,
_StsTestHarness):
def _build_sts(self, observed_time_series=None):
day_of_week = tfp.sts.Seasonal(num_seasons=7,
num_steps_per_se... | @test_util.test_all_tf_execution_regimes
class SeasonalWithMultipleStepsAndNoiseTest(test_util.TestCase,
_StsTestHarness):
| def _build_sts(self, observed_time_series=None):
day_of_week = tfp.sts.Seasonal(num_seasons=7,
num_steps_per_season=24,
allow_drift=False,
observed_time_series=observed_time_series,
... | return Seasonal(num_seasons=7,
num_steps_per_season=1,
observed_time_series=observed_time_series,
constrain_mean_effect_to_zero=True)
@test_util.test_all_tf_execution_regimes
class SeasonalWithMultipleStepsAndNoiseTest(test_util.TestCase,
... | 64 | 64 | 116 | 29 | 35 | fearghus-moloco/probability | tensorflow_probability/python/sts/structural_time_series_test.py | Python | SeasonalWithMultipleStepsAndNoiseTest | SeasonalWithMultipleStepsAndNoiseTest | 432 | 443 | 432 | 435 | a70146d9b336c0b8601cef721210de344d808ace | bigcode/the-stack | train |
bcf1c2de8e93ea020d84fc33 | train | class | class _StructuralTimeSeriesTests(object):
def test_broadcast_batch_shapes(self):
batch_shape = [3, 1, 4]
partial_batch_shape = [2, 1]
expected_broadcast_batch_shape = [3, 2, 4]
# Build a model where parameters have different batch shapes.
partial_batch_loc = self._build_placeholder(
np.... | class _StructuralTimeSeriesTests(object):
| def test_broadcast_batch_shapes(self):
batch_shape = [3, 1, 4]
partial_batch_shape = [2, 1]
expected_broadcast_batch_shape = [3, 2, 4]
# Build a model where parameters have different batch shapes.
partial_batch_loc = self._build_placeholder(
np.random.randn(*partial_batch_shape))
ful... | 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 tensorflow_probability.python.sts.structur... | 256 | 256 | 1,103 | 8 | 247 | fearghus-moloco/probability | tensorflow_probability/python/sts/structural_time_series_test.py | Python | _StructuralTimeSeriesTests | _StructuralTimeSeriesTests | 41 | 148 | 41 | 42 | e6e7237a47f64044ada148a2161e49646ee5dcb1 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.