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
d45631ac45cc69004522b4f3
train
function
def _add_events(hass, events): with session_scope(hass=hass) as session: session.query(Events).delete(synchronize_session=False) for event_type in events: hass.bus.fire(event_type) wait_recording_done(hass) with session_scope(hass=hass) as session: return [ev.to_native() for ev ...
def _add_events(hass, events):
with session_scope(hass=hass) as session: session.query(Events).delete(synchronize_session=False) for event_type in events: hass.bus.fire(event_type) wait_recording_done(hass) with session_scope(hass=hass) as session: return [ev.to_native() for ev in session.query(Events)]
in session.query(States, StateAttributes).outerjoin( StateAttributes, States.attributes_id == StateAttributes.attributes_id ): native_state = state.to_native() native_state.attributes = state_attributes.to_native() states.append(native_state) return state...
64
64
82
9
54
calebvisage/core
tests/components/recorder/test_init.py
Python
_add_events
_add_events
422
430
422
422
6854f9a7e334b3c93394ff280894e49e8b07da87
bigcode/the-stack
train
f03240646bf067b5eb99a138
train
function
async def test_database_lock_without_instance(hass): """Test database lock doesn't fail if instance is not initialized.""" await async_init_recorder_component(hass) hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) instance: Recorder = hass.data[DATA_INSTANCE] with patch.object(instance, "engine", None...
async def test_database_lock_without_instance(hass):
"""Test database lock doesn't fail if instance is not initialized.""" await async_init_recorder_component(hass) hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) instance: Recorder = hass.data[DATA_INSTANCE] with patch.object(instance, "engine", None): try: assert await instance.loc...
instance.queue.put(block_task) with patch.object(recorder, "DB_LOCK_TIMEOUT", 0.1): try: with pytest.raises(TimeoutError): await instance.lock_database() finally: instance.unlock_database() block_task.event.set() async def test_database_lock_witho...
64
64
86
10
54
calebvisage/core
tests/components/recorder/test_init.py
Python
test_database_lock_without_instance
test_database_lock_without_instance
1,386
1,396
1,386
1,386
3378d8b08e28ddac7633af361e0849b6ff72c228
bigcode/the-stack
train
0ed4eb9ede8c548037a5237d
train
function
def test_service_disable_events_not_recording(hass, hass_recorder): """Test that events are not recorded when recorder is disabled using service.""" hass = hass_recorder() assert hass.services.call( DOMAIN, SERVICE_DISABLE, {}, blocking=True, ) event_type = "EVENT_T...
def test_service_disable_events_not_recording(hass, hass_recorder):
"""Test that events are not recorded when recorder is disabled using service.""" hass = hass_recorder() assert hass.services.call( DOMAIN, SERVICE_DISABLE, {}, blocking=True, ) event_type = "EVENT_TEST" events = [] @callback def event_listener(event): ...
run_info = run_information(hass, dt_util.utcnow()) assert isinstance(run_info, RecorderRuns) assert run_info.closed_incorrect is False def test_has_services(hass_recorder): """Test the services exist.""" hass = hass_recorder() assert hass.services.has_service(DOMAIN, SERVICE_DISABLE) assert ...
125
125
419
15
110
calebvisage/core
tests/components/recorder/test_init.py
Python
test_service_disable_events_not_recording
test_service_disable_events_not_recording
1,058
1,119
1,058
1,058
775ef354df0054d2274cfbe522cc09668cecd09b
bigcode/the-stack
train
daad0e34fbfe370abb927bff
train
function
def test_saving_state_and_removing_entity(hass, hass_recorder): """Test saving the state of a removed entity.""" hass = hass_recorder() entity_id = "lock.mine" hass.states.set(entity_id, STATE_LOCKED) hass.states.set(entity_id, STATE_UNLOCKED) hass.states.remove(entity_id) wait_recording_do...
def test_saving_state_and_removing_entity(hass, hass_recorder):
"""Test saving the state of a removed entity.""" hass = hass_recorder() entity_id = "lock.mine" hass.states.set(entity_id, STATE_LOCKED) hass.states.set(entity_id, STATE_UNLOCKED) hass.states.remove(entity_id) wait_recording_done(hass) with session_scope(hass=hass) as session: ...
) assert len(states) == 1 assert _state_empty_context(hass, "test.ok") == states[0] assert _state_empty_context(hass, "test.ok").state == "state2" def test_saving_state_and_removing_entity(hass, hass_recorder):
64
64
179
16
48
calebvisage/core
tests/components/recorder/test_init.py
Python
test_saving_state_and_removing_entity
test_saving_state_and_removing_entity
570
588
570
570
0b8ab517b5f66125bbca904eda9562ba582a7011
bigcode/the-stack
train
1cdf329e12430ef2469fbf65
train
function
async def test_saving_state( hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT ): """Test saving and restoring a state.""" instance = await async_setup_recorder_instance(hass) entity_id = "test.recorder" state = "restoring_from_db" attributes = {"test_attr": 5, "test_at...
async def test_saving_state( hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT ):
"""Test saving and restoring a state.""" instance = await async_setup_recorder_instance(hass) entity_id = "test.recorder" state = "restoring_from_db" attributes = {"test_attr": 5, "test_attr_10": "nice"} hass.states.async_set(entity_id, state, attributes) await async_wait_recording_done(h...
=hass) as session: db_states = list(session.query(States)) assert len(db_states) == 1 assert db_states[0].event_id > 0 async def test_saving_state( hass: HomeAssistant, async_setup_recorder_instance: SetupRecorderInstanceT ):
64
64
203
25
38
calebvisage/core
tests/components/recorder/test_init.py
Python
test_saving_state
test_saving_state
158
181
158
160
d0e42d6fb0b54c53cae1bbe2598a7e40c5de6859
bigcode/the-stack
train
1440d32ffc6891dbf1291425
train
function
def test_service_disable_run_information_recorded(tmpdir): """Test that runs are still recorded when recorder is disabled.""" test_db_file = tmpdir.mkdir("sqlite").join("test_run_info.db") dburl = f"{SQLITE_URL_PREFIX}//{test_db_file}" hass = get_test_home_assistant() setup_component(hass, DOMAIN, ...
def test_service_disable_run_information_recorded(tmpdir):
"""Test that runs are still recorded when recorder is disabled.""" test_db_file = tmpdir.mkdir("sqlite").join("test_run_info.db") dburl = f"{SQLITE_URL_PREFIX}//{test_db_file}" hass = get_test_home_assistant() setup_component(hass, DOMAIN, {DOMAIN: {CONF_DB_URL: dburl}}) hass.start() wait_r...
.states.set("test.two", "off", {}) wait_recording_done(hass) with session_scope(hass=hass) as session: db_states = list(session.query(States)) assert len(db_states) == 1 assert db_states[0].event_id > 0 assert db_states[0].to_native() == _state_empty_context(hass, "test.two") de...
96
96
321
11
85
calebvisage/core
tests/components/recorder/test_init.py
Python
test_service_disable_run_information_recorded
test_service_disable_run_information_recorded
1,156
1,195
1,156
1,156
d85ca5df7d658078768a02f0ffbccec36cefe0ce
bigcode/the-stack
train
236275976bd1d716d637a61b
train
function
def test_saving_state_with_serializable_data(hass_recorder, caplog): """Test saving data that cannot be serialized does not crash.""" hass = hass_recorder() hass.bus.fire("bad_event", {"fail": CannotSerializeMe()}) hass.states.set("test.one", "on", {"fail": CannotSerializeMe()}) wait_recording_done...
def test_saving_state_with_serializable_data(hass_recorder, caplog):
"""Test saving data that cannot be serialized does not crash.""" hass = hass_recorder() hass.bus.fire("bad_event", {"fail": CannotSerializeMe()}) hass.states.set("test.one", "on", {"fail": CannotSerializeMe()}) wait_recording_done(hass) hass.states.set("test.two", "on", {}) wait_recording_d...
is None assert states[1].old_state_id is None assert states[2].old_state_id == states[0].state_id assert states[3].old_state_id == states[1].state_id def test_saving_state_with_serializable_data(hass_recorder, caplog):
66
66
220
17
48
calebvisage/core
tests/components/recorder/test_init.py
Python
test_saving_state_with_serializable_data
test_saving_state_with_serializable_data
993
1,014
993
993
92b540ad09c2f3937ee88d376fa017264d8f2294
bigcode/the-stack
train
8660b4aec5c47e172373f8d2
train
function
@pytest.mark.parametrize("enable_nightly_purge", [True]) def test_auto_purge(hass_recorder): """Test periodic purge scheduling.""" hass = hass_recorder() original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone("Europe/Copenhagen") dt_util.set_default_time_zone(tz) # Purging is sche...
@pytest.mark.parametrize("enable_nightly_purge", [True]) def test_auto_purge(hass_recorder):
"""Test periodic purge scheduling.""" hass = hass_recorder() original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone("Europe/Copenhagen") dt_util.set_default_time_zone(tz) # Purging is scheduled to happen at 4:12am every day. Exercise this behavior by # firing time changed even...
= config["recorder"] return True with patch("homeassistant.components.recorder.async_setup", side_effect=mock_setup): assert await async_setup_component(hass, "history", {}) assert recorder_config is not None # pylint: disable=unsubscriptable-object assert recorder_config["auto_purge"...
170
170
567
23
147
calebvisage/core
tests/components/recorder/test_init.py
Python
test_auto_purge
test_auto_purge
645
700
645
646
98f3d1ff731f2cbd2e1f343a6bf5443a11303aff
bigcode/the-stack
train
165ef3c3f0389ec5d4cc7595
train
function
@pytest.mark.parametrize("enable_nightly_purge", [True]) def test_auto_purge_no_auto_repack_on_not_second_sunday(hass_recorder): """Test periodic purge scheduling does not do a repack unless its the 2nd sunday.""" hass = hass_recorder() original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zon...
@pytest.mark.parametrize("enable_nightly_purge", [True]) def test_auto_purge_no_auto_repack_on_not_second_sunday(hass_recorder):
"""Test periodic purge scheduling does not do a repack unless its the 2nd sunday.""" hass = hass_recorder() original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone("Europe/Copenhagen") dt_util.set_default_time_zone(tz) # Purging is scheduled to happen at 4:12am every day. Exercise ...
test_time + timedelta(days=1) run_tasks_at_time(hass, test_time) assert len(purge_old_data.mock_calls) == 1 args, _ = purge_old_data.call_args_list[0] assert args[2] is False # repack assert len(perodic_db_cleanups.mock_calls) == 1 dt_util.set_default_time_zone(original_tz...
119
119
399
32
87
calebvisage/core
tests/components/recorder/test_init.py
Python
test_auto_purge_no_auto_repack_on_not_second_sunday
test_auto_purge_no_auto_repack_on_not_second_sunday
779
814
779
780
d84de76261b61034dea3a65e648bd93142a2e35a
bigcode/the-stack
train
ba27923f15f8df7c01070e35
train
function
def test_saving_state_include_domain_exclude_entity(hass_recorder): """Test saving and restoring a state.""" hass = hass_recorder( {"exclude": {"entities": "test.recorder"}, "include": {"domains": "test"}} ) states = _add_entities(hass, ["test.recorder", "test2.recorder", "test.ok"]) assert ...
def test_saving_state_include_domain_exclude_entity(hass_recorder):
"""Test saving and restoring a state.""" hass = hass_recorder( {"exclude": {"entities": "test.recorder"}, "include": {"domains": "test"}} ) states = _add_entities(hass, ["test.recorder", "test2.recorder", "test.ok"]) assert len(states) == 1 assert _state_empty_context(hass, "test.ok") ==...
obs": "*._excluded_*"}, } ) states = _add_entities( hass, ["test.recorder", "test2.recorder", "test.excluded_entity"] ) assert len(states) == 3 def test_saving_state_include_domain_exclude_entity(hass_recorder):
64
64
125
15
48
calebvisage/core
tests/components/recorder/test_init.py
Python
test_saving_state_include_domain_exclude_entity
test_saving_state_include_domain_exclude_entity
543
551
543
543
a4a0c49f913874f6c6764e387a2a722e8a33b230
bigcode/the-stack
train
ca6ce79a104531df959d46ee
train
function
def test_compile_missing_statistics(tmpdir): """Test missing statistics are compiled on startup.""" now = dt_util.utcnow().replace(minute=0, second=0, microsecond=0) test_db_file = tmpdir.mkdir("sqlite").join("test_run_info.db") dburl = f"{SQLITE_URL_PREFIX}//{test_db_file}" with patch("homeassista...
def test_compile_missing_statistics(tmpdir):
"""Test missing statistics are compiled on startup.""" now = dt_util.utcnow().replace(minute=0, second=0, microsecond=0) test_db_file = tmpdir.mkdir("sqlite").join("test_run_info.db") dburl = f"{SQLITE_URL_PREFIX}//{test_db_file}" with patch("homeassistant.components.recorder.dt_util.utcnow", retur...
=now): hass = hass_recorder() wait_recording_done(hass) with session_scope(hass=hass) as session: statistics_runs = list(session.query(StatisticsRuns)) assert len(statistics_runs) == 1 last_run = process_timestamp(statistics_runs[0].start) assert...
114
114
380
8
106
calebvisage/core
tests/components/recorder/test_init.py
Python
test_compile_missing_statistics
test_compile_missing_statistics
921
964
921
921
8926d6c1d84acb4e02daaa98b5e3a60d22809921
bigcode/the-stack
train
2d52fea1da48f86575014160
train
function
async def test_database_lock_and_overflow(hass: HomeAssistant, tmp_path): """Test writing events during lock leading to overflow the queue causes the database to unlock.""" # Use file DB, in memory DB cannot do write locks. config = {recorder.CONF_DB_URL: "sqlite:///" + str(tmp_path / "pytest.db")} awai...
async def test_database_lock_and_overflow(hass: HomeAssistant, tmp_path):
"""Test writing events during lock leading to overflow the queue causes the database to unlock.""" # Use file DB, in memory DB cannot do write locks. config = {recorder.CONF_DB_URL: "sqlite:///" + str(tmp_path / "pytest.db")} await async_init_recorder_component(hass, config) await hass.async_block_t...
_type)) assert len(db_events) == 0 assert instance.unlock_database() await task with session_scope(hass=hass) as session: db_events = list(session.query(Events).filter_by(event_type=event_type)) assert len(db_events) == 1 async def test_database_lock_and_overflow(hass: HomeAssistan...
79
79
264
17
61
calebvisage/core
tests/components/recorder/test_init.py
Python
test_database_lock_and_overflow
test_database_lock_and_overflow
1,333
1,359
1,333
1,333
15efa2d4eba57dc9d4e2726fc129d1d482291340
bigcode/the-stack
train
49592b4104ae1d20397463c1
train
function
async def test_database_corruption_while_running(hass, tmpdir, caplog): """Test we can recover from sqlite3 db corruption.""" def _create_tmpdir_for_test_db(): return tmpdir.mkdir("sqlite").join("test.db") test_db_file = await hass.async_add_executor_job(_create_tmpdir_for_test_db) dburl = f"{...
async def test_database_corruption_while_running(hass, tmpdir, caplog):
"""Test we can recover from sqlite3 db corruption.""" def _create_tmpdir_for_test_db(): return tmpdir.mkdir("sqlite").join("test.db") test_db_file = await hass.async_add_executor_job(_create_tmpdir_for_test_db) dburl = f"{SQLITE_URL_PREFIX}//{test_db_file}" assert await async_setup_compon...
() setup_component(hass, DOMAIN, {DOMAIN: {CONF_DB_URL: dburl}}) hass.start() wait_recording_done(hass) with session_scope(hass=hass) as session: db_run_info = list(session.query(RecorderRuns)) assert len(db_run_info) == 2 assert db_run_info[0].start is not None assert d...
156
157
526
18
138
calebvisage/core
tests/components/recorder/test_init.py
Python
test_database_corruption_while_running
test_database_corruption_while_running
1,202
1,261
1,202
1,202
d6bebff609f189b3c0dc717da6d52a453a5a5bdb
bigcode/the-stack
train
a59ceeea14c0cc1b1af8f375
train
function
def test_saving_state_with_commit_interval_zero(hass_recorder): """Test saving a state with a commit interval of zero.""" hass = hass_recorder({"commit_interval": 0}) assert hass.data[DATA_INSTANCE].commit_interval == 0 entity_id = "test.recorder" state = "restoring_from_db" attributes = {"test...
def test_saving_state_with_commit_interval_zero(hass_recorder):
"""Test saving a state with a commit interval of zero.""" hass = hass_recorder({"commit_interval": 0}) assert hass.data[DATA_INSTANCE].commit_interval == 0 entity_id = "test.recorder" state = "restoring_from_db" attributes = {"test_attr": 5, "test_attr_10": "nice"} hass.states.set(entity_i...
event.origin == db_event.origin # Recorder uses SQLite and stores datetimes as integer unix timestamps assert event.time_fired.replace(microsecond=0) == db_event.time_fired.replace( microsecond=0 ) def test_saving_state_with_commit_interval_zero(hass_recorder):
64
64
155
14
50
calebvisage/core
tests/components/recorder/test_init.py
Python
test_saving_state_with_commit_interval_zero
test_saving_state_with_commit_interval_zero
385
401
385
385
f71ce5b8c6e52918af609174d82e9efb4eedd3a3
bigcode/the-stack
train
87909cff5c37b74bdf4e973a
train
function
def test_entity_id_filter(hass_recorder): """Test that entity ID filtering filters string and list.""" hass = hass_recorder( {"include": {"domains": "hello"}, "exclude": {"domains": "hidden_domain"}} ) for idx, data in enumerate( ( {}, {"entity_id": "hello.world"...
def test_entity_id_filter(hass_recorder):
"""Test that entity ID filtering filters string and list.""" hass = hass_recorder( {"include": {"domains": "hello"}, "exclude": {"domains": "hidden_domain"}} ) for idx, data in enumerate( ( {}, {"entity_id": "hello.world"}, {"entity_id": ["hello.world...
event_id > 0 return db_states[0].to_native() state = await hass.async_add_executor_job(_get_last_state) assert state.entity_id == "test.two" assert state.state == "on" hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) await hass.async_block_till_done() hass.stop() def test_entity_id_fi...
83
83
278
10
73
calebvisage/core
tests/components/recorder/test_init.py
Python
test_entity_id_filter
test_entity_id_filter
1,264
1,296
1,264
1,264
d9cad2af31286f26cde6791632cae141732ae967
bigcode/the-stack
train
e6fd750470be3060903df678
train
function
def test_saving_state_include_domains_globs(hass_recorder): """Test saving and restoring a state.""" hass = hass_recorder( {"include": {"domains": "test2", "entity_globs": "*.included_*"}} ) states = _add_entities( hass, ["test.recorder", "test2.recorder", "test3.included_entity"] ) ...
def test_saving_state_include_domains_globs(hass_recorder):
"""Test saving and restoring a state.""" hass = hass_recorder( {"include": {"domains": "test2", "entity_globs": "*.included_*"}} ) states = _add_entities( hass, ["test.recorder", "test2.recorder", "test3.included_entity"] ) assert len(states) == 2 assert _state_empty_context(...
) states = _add_entities(hass, ["test.recorder", "test2.recorder"]) assert len(states) == 1 assert _state_empty_context(hass, "test2.recorder") == states[0] def test_saving_state_include_domains_globs(hass_recorder):
64
64
133
14
50
calebvisage/core
tests/components/recorder/test_init.py
Python
test_saving_state_include_domains_globs
test_saving_state_include_domains_globs
450
460
450
450
1a2c943067b3b3dae5193f20a369a99ce68d5a42
bigcode/the-stack
train
9c0558e7ec320d09763e09c6
train
function
def test_saving_state_with_sqlalchemy_exception(hass, hass_recorder, caplog): """Test saving state when there is an SQLAlchemyError.""" hass = hass_recorder() entity_id = "test.recorder" state = "restoring_from_db" attributes = {"test_attr": 5, "test_attr_10": "nice"} def _throw_if_state_in_se...
def test_saving_state_with_sqlalchemy_exception(hass, hass_recorder, caplog):
"""Test saving state when there is an SQLAlchemyError.""" hass = hass_recorder() entity_id = "test.recorder" state = "restoring_from_db" attributes = {"test_attr": 5, "test_attr_10": "nice"} def _throw_if_state_in_session(*args, **kwargs): for obj in hass.data[DATA_INSTANCE].event_sess...
, state, attributes) wait_recording_done(hass) with session_scope(hass=hass) as session: db_states = list(session.query(States)) assert len(db_states) >= 1 assert "Error executing query" not in caplog.text assert "Error saving events" not in caplog.text def test_saving_state_with_sqlal...
90
90
302
19
70
calebvisage/core
tests/components/recorder/test_init.py
Python
test_saving_state_with_sqlalchemy_exception
test_saving_state_with_sqlalchemy_exception
276
311
276
276
2afdaa76b5a30ae70b333e41f5fd6f77ee03dfe3
bigcode/the-stack
train
fc1de038b5b7fe75a46746d8
train
function
def test_recorder_setup_failure_without_event_listener(hass): """Test recorder setup failure when the event listener is not setup.""" with patch.object(Recorder, "_setup_connection") as setup, patch( "homeassistant.components.recorder.time.sleep" ): setup.side_effect = ImportError("driver no...
def test_recorder_setup_failure_without_event_listener(hass):
"""Test recorder setup failure when the event listener is not setup.""" with patch.object(Recorder, "_setup_connection") as setup, patch( "homeassistant.components.recorder.time.sleep" ): setup.side_effect = ImportError("driver not found") rec = _default_recorder(hass) rec.st...
( "homeassistant.components.recorder.time.sleep" ): setup.side_effect = ImportError("driver not found") rec = _default_recorder(hass) rec.async_initialize() rec.start() rec.join() hass.stop() def test_recorder_setup_failure_without_event_listener(hass):
64
64
88
12
52
calebvisage/core
tests/components/recorder/test_init.py
Python
test_recorder_setup_failure_without_event_listener
test_recorder_setup_failure_without_event_listener
605
615
605
605
7036d3e11234ebc19dd07eaf4e8eba4a3b1688f5
bigcode/the-stack
train
0531656d122a53a8b197a204
train
function
def test_recorder_setup_failure(hass): """Test some exceptions.""" with patch.object(Recorder, "_setup_connection") as setup, patch( "homeassistant.components.recorder.time.sleep" ): setup.side_effect = ImportError("driver not found") rec = _default_recorder(hass) rec.async_i...
def test_recorder_setup_failure(hass):
"""Test some exceptions.""" with patch.object(Recorder, "_setup_connection") as setup, patch( "homeassistant.components.recorder.time.sleep" ): setup.side_effect = ImportError("driver not found") rec = _default_recorder(hass) rec.async_initialize() rec.start() ...
[0].state == STATE_LOCKED assert states[1].entity_id == entity_id assert states[1].state == STATE_UNLOCKED assert states[2].entity_id == entity_id assert states[2].state is None def test_recorder_setup_failure(hass):
64
64
82
9
54
calebvisage/core
tests/components/recorder/test_init.py
Python
test_recorder_setup_failure
test_recorder_setup_failure
591
602
591
591
21f3da63bb2f3cc1b3e732c2e05f847471da108a
bigcode/the-stack
train
35afb3df1dcd0bb4b9572656
train
function
def test_saving_state_with_exception(hass, hass_recorder, caplog): """Test saving and restoring a state.""" hass = hass_recorder() entity_id = "test.recorder" state = "restoring_from_db" attributes = {"test_attr": 5, "test_attr_10": "nice"} def _throw_if_state_in_session(*args, **kwargs): ...
def test_saving_state_with_exception(hass, hass_recorder, caplog):
"""Test saving and restoring a state.""" hass = hass_recorder() entity_id = "test.recorder" state = "restoring_from_db" attributes = {"test_attr": 5, "test_attr_10": "nice"} def _throw_if_state_in_session(*args, **kwargs): for obj in hass.data[DATA_INSTANCE].event_session: ...
hass.states.async_set(entity_id, state, attributes2) await async_wait_recording_done(hass, instance) with session_scope(hass=hass) as session: db_states = list(session.query(States)) assert len(db_states) == 2 assert db_states[0].event_id > 0 def test_saving_state_with_exception(hass,...
86
86
289
17
68
calebvisage/core
tests/components/recorder/test_init.py
Python
test_saving_state_with_exception
test_saving_state_with_exception
238
273
238
238
4c33e2e0cc605a34ed168ea1c2273b7f20c087ad
bigcode/the-stack
train
05cc917c5f76d21537348476
train
function
@pytest.mark.parametrize("enable_nightly_purge", [True]) def test_auto_purge_auto_repack_disabled_on_second_sunday(hass_recorder): """Test periodic purge scheduling does not auto repack on the 2nd sunday if disabled.""" hass = hass_recorder({CONF_AUTO_REPACK: False}) original_tz = dt_util.DEFAULT_TIME_ZONE...
@pytest.mark.parametrize("enable_nightly_purge", [True]) def test_auto_purge_auto_repack_disabled_on_second_sunday(hass_recorder):
"""Test periodic purge scheduling does not auto repack on the 2nd sunday if disabled.""" hass = hass_recorder({CONF_AUTO_REPACK: False}) original_tz = dt_util.DEFAULT_TIME_ZONE tz = dt_util.get_time_zone("Europe/Copenhagen") dt_util.set_default_time_zone(tz) # Purging is scheduled to happen a...
test_time = test_time + timedelta(days=1) run_tasks_at_time(hass, test_time) assert len(purge_old_data.mock_calls) == 1 args, _ = purge_old_data.call_args_list[0] assert args[2] is True # repack assert len(perodic_db_cleanups.mock_calls) == 1 dt_util.set_default_time_zone(...
121
121
405
31
90
calebvisage/core
tests/components/recorder/test_init.py
Python
test_auto_purge_auto_repack_disabled_on_second_sunday
test_auto_purge_auto_repack_disabled_on_second_sunday
741
776
741
742
3ae60aa25428ded1e01e35a871283de2495bc459
bigcode/the-stack
train
d938f19aa28bdcd7208f907a
train
function
async def test_shutdown_closes_connections(hass): """Test shutdown closes connections.""" hass.state = CoreState.not_running await async_init_recorder_component(hass) instance = get_instance(hass) await instance.async_db_ready await hass.async_block_till_done() pool = instance.engine.pool ...
async def test_shutdown_closes_connections(hass):
"""Test shutdown closes connections.""" hass.state = CoreState.not_running await async_init_recorder_component(hass) instance = get_instance(hass) await instance.async_db_ready await hass.async_block_till_done() pool = instance.engine.pool pool.shutdown = Mock() def _ensure_connec...
ill_done() await hass.async_stop() run_info = await hass.async_add_executor_job(run_information_with_session, session) assert run_info.run_id == 1 assert run_info.start is not None assert run_info.end is not None async def test_shutdown_closes_connections(hass):
64
64
142
10
53
calebvisage/core
tests/components/recorder/test_init.py
Python
test_shutdown_closes_connections
test_shutdown_closes_connections
109
130
109
109
4b72710b9a86edd6d2339a5a4491b211f1d4532c
bigcode/the-stack
train
8ffb3907aafc2f3fde7826b4
train
function
def _default_recorder(hass): """Return a recorder with reasonable defaults.""" return Recorder( hass, auto_purge=True, auto_repack=True, keep_days=7, commit_interval=1, uri="sqlite://", db_max_retries=10, db_retry_wait=3, entity_filter=CONF...
def _default_recorder(hass):
"""Return a recorder with reasonable defaults.""" return Recorder( hass, auto_purge=True, auto_repack=True, keep_days=7, commit_interval=1, uri="sqlite://", db_max_retries=10, db_retry_wait=3, entity_filter=CONFIG_SCHEMA({DOMAIN: {}}), ...
_instance, corrupt_db_file, wait_recording_done, ) from .conftest import SetupRecorderInstanceT from tests.common import ( async_fire_time_changed, async_init_recorder_component, fire_time_changed, get_test_home_assistant, ) def _default_recorder(hass):
64
64
95
8
56
calebvisage/core
tests/components/recorder/test_init.py
Python
_default_recorder
_default_recorder
69
83
69
69
88d30e0de237e6870540363ba8e1efba0ddcb346
bigcode/the-stack
train
20d2290c191fe7049eb26bfe
train
function
def test_service_disable_states_not_recording(hass, hass_recorder): """Test that state changes are not recorded when recorder is disabled using service.""" hass = hass_recorder() assert hass.services.call( DOMAIN, SERVICE_DISABLE, {}, blocking=True, ) hass.states.se...
def test_service_disable_states_not_recording(hass, hass_recorder):
"""Test that state changes are not recorded when recorder is disabled using service.""" hass = hass_recorder() assert hass.services.call( DOMAIN, SERVICE_DISABLE, {}, blocking=True, ) hass.states.set("test.one", "on", {}) wait_recording_done(hass) with sess...
_type assert event.data == db_event.data assert event.origin == db_event.origin assert event.time_fired.replace(microsecond=0) == db_event.time_fired.replace( microsecond=0 ) def test_service_disable_states_not_recording(hass, hass_recorder):
64
64
212
15
49
calebvisage/core
tests/components/recorder/test_init.py
Python
test_service_disable_states_not_recording
test_service_disable_states_not_recording
1,122
1,153
1,122
1,122
43361b91cd3f6c5aeae9d09fb296b1e5237aeda7
bigcode/the-stack
train
26ed5aa5d0c2f7ec42a1295a
train
function
def main(argv=None): """script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv parser = E.OptionParser(version="%prog version: $Id: calculate_histogram_2D.py 2782 2009-09-10 11:40:29Z andreas $", usage...
def main(argv=None):
"""script main. parses command line options in sys.argv, unless *argv* is given. """ if argv is None: argv = sys.argv parser = E.OptionParser(version="%prog version: $Id: calculate_histogram_2D.py 2782 2009-09-10 11:40:29Z andreas $", usage=globals()["__doc__"]...
2D histogram. The data is a tab-separated with ``x``, ``y`` in the first two columns. The columns can be changed by the ``-1`` and ``-2`` options. Usage ----- Example:: python calculate_histogram_2D.py --help Type:: python calculate_histogram_2D.py --help for command line help. Command line options -------...
201
201
673
5
195
CGATOxford/cgat
CGAT/scripts/calculate_histogram_2D.py
Python
main
main
49
131
49
49
418a77354d5ce58b8256e3d6496c6cd54f6e70c3
bigcode/the-stack
train
b10179808d3416d8d5eb9c60
train
function
def metric_fn(labels, logits): """Metric function for evaluation.""" predictions = tf.argmax(logits, axis=1) top_1_accuracy = tf.metrics.accuracy(labels, predictions) in_top_5 = tf.cast(tf.nn.in_top_k(logits, labels, 5), tf.float32) top_5_accuracy = tf.metrics.mean(in_top_5) return { 'top_1_accuracy'...
def metric_fn(labels, logits):
"""Metric function for evaluation.""" predictions = tf.argmax(logits, axis=1) top_1_accuracy = tf.metrics.accuracy(labels, predictions) in_top_5 = tf.cast(tf.nn.in_top_k(logits, labels, 5), tf.float32) top_5_accuracy = tf.metrics.mean(in_top_5) return { 'top_1_accuracy': top_1_accuracy, 'top_5_...
express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Model utils.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v1 as tf def metric_fn(labels, logits):
64
64
109
7
56
kiss2u/google-research
l2tl/model_utils.py
Python
metric_fn
metric_fn
25
35
25
25
8ff1d69344191a45db9c8c6b6dfb0691f2fd3fc5
bigcode/the-stack
train
19b57480c792295e3d019cc0
train
function
def update_exponential_moving_average(tensor, momentum, name=None): """Returns an exponential moving average of `tensor`. We will update the moving average every time the returned `tensor` is evaluated. A zero-debias will be applied, so we will return unbiased estimates during the first few training steps. A...
def update_exponential_moving_average(tensor, momentum, name=None):
"""Returns an exponential moving average of `tensor`. We will update the moving average every time the returned `tensor` is evaluated. A zero-debias will be applied, so we will return unbiased estimates during the first few training steps. Args: tensor: A floating point tensor. momentum: A scalar flo...
_5_accuracy, } def get_label(labels, params, num_classes, batch_size=-1): # pylint: disable=unused-argument """Returns the label.""" one_hot_labels = tf.one_hot(tf.cast(labels, tf.int64), num_classes) return one_hot_labels def update_exponential_moving_average(tensor, momentum, name=None):
77
77
258
15
61
kiss2u/google-research
l2tl/model_utils.py
Python
update_exponential_moving_average
update_exponential_moving_average
44
69
44
44
e6ebeba25cda28db287e65eed9c8e0ab106910c2
bigcode/the-stack
train
a4ff24ce0c9ca14fc3ff5d51
train
function
def get_label(labels, params, num_classes, batch_size=-1): # pylint: disable=unused-argument """Returns the label.""" one_hot_labels = tf.one_hot(tf.cast(labels, tf.int64), num_classes) return one_hot_labels
def get_label(labels, params, num_classes, batch_size=-1): # pylint: disable=unused-argument
"""Returns the label.""" one_hot_labels = tf.one_hot(tf.cast(labels, tf.int64), num_classes) return one_hot_labels
_accuracy = tf.metrics.mean(in_top_5) return { 'top_1_accuracy': top_1_accuracy, 'top_5_accuracy': top_5_accuracy, } def get_label(labels, params, num_classes, batch_size=-1): # pylint: disable=unused-argument
64
64
56
25
39
kiss2u/google-research
l2tl/model_utils.py
Python
get_label
get_label
38
41
38
38
9ce7b34f0856f620689724226110056d8d529db3
bigcode/the-stack
train
8a36c10fbee657f37aa95666
train
function
def make_assert_puzzle_announcement(announcement_hash): return [ConditionOpcode.ASSERT_PUZZLE_ANNOUNCEMENT, announcement_hash]
def make_assert_puzzle_announcement(announcement_hash):
return [ConditionOpcode.ASSERT_PUZZLE_ANNOUNCEMENT, announcement_hash]
, time] def make_reserve_fee_condition(fee): return [ConditionOpcode.RESERVE_FEE, fee] def make_assert_coin_announcement(announcement_hash): return [ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT, announcement_hash] def make_assert_puzzle_announcement(announcement_hash):
64
64
32
11
53
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_puzzle_announcement
make_assert_puzzle_announcement
40
41
40
40
42b5647acc35dfac60e1a3f1a4dcd22b3d0188da
bigcode/the-stack
train
c72dfd362b11c970907d665e
train
function
def make_assert_my_puzzlehash(puzzlehash): return [ConditionOpcode.ASSERT_MY_PUZZLEHASH, puzzlehash]
def make_assert_my_puzzlehash(puzzlehash):
return [ConditionOpcode.ASSERT_MY_PUZZLEHASH, puzzlehash]
message] def make_create_puzzle_announcement(message): return [ConditionOpcode.CREATE_PUZZLE_ANNOUNCEMENT, message] def make_assert_my_parent_id(parent_id): return [ConditionOpcode.ASSERT_MY_PARENT_ID, parent_id] def make_assert_my_puzzlehash(puzzlehash):
64
64
29
11
53
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_my_puzzlehash
make_assert_my_puzzlehash
56
57
56
56
d0549715b9c5627d9df793273a3953ee23852be3
bigcode/the-stack
train
d84b6093e8fa80798a8ac9b6
train
function
def make_assert_relative_height_exceeds_condition(block_index): return [ConditionOpcode.ASSERT_HEIGHT_RELATIVE, block_index]
def make_assert_relative_height_exceeds_condition(block_index):
return [ConditionOpcode.ASSERT_HEIGHT_RELATIVE, block_index]
make_assert_my_coin_id_condition(coin_name): return [ConditionOpcode.ASSERT_MY_COIN_ID, coin_name] def make_assert_absolute_height_exceeds_condition(block_index): return [ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, block_index] def make_assert_relative_height_exceeds_condition(block_index):
64
64
26
11
53
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_relative_height_exceeds_condition
make_assert_relative_height_exceeds_condition
20
21
20
20
251d74e25f5b1c53ec891d583f3695e891314a4a
bigcode/the-stack
train
1368ccbd3430b0a3419d7a96
train
function
def make_reserve_fee_condition(fee): return [ConditionOpcode.RESERVE_FEE, fee]
def make_reserve_fee_condition(fee):
return [ConditionOpcode.RESERVE_FEE, fee]
_RELATIVE, block_index] def make_assert_absolute_seconds_exceeds_condition(time): return [ConditionOpcode.ASSERT_SECONDS_ABSOLUTE, time] def make_assert_relative_seconds_exceeds_condition(time): return [ConditionOpcode.ASSERT_SECONDS_RELATIVE, time] def make_reserve_fee_condition(fee):
64
64
21
9
55
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_reserve_fee_condition
make_reserve_fee_condition
32
33
32
32
955e6eec903fd9d9ecf7fa38ad938b10f3e19393
bigcode/the-stack
train
61f65b88b6ee7b30b390d209
train
function
def make_assert_my_parent_id(parent_id): return [ConditionOpcode.ASSERT_MY_PARENT_ID, parent_id]
def make_assert_my_parent_id(parent_id):
return [ConditionOpcode.ASSERT_MY_PARENT_ID, parent_id]
, announcement_hash] def make_create_coin_announcement(message): return [ConditionOpcode.CREATE_COIN_ANNOUNCEMENT, message] def make_create_puzzle_announcement(message): return [ConditionOpcode.CREATE_PUZZLE_ANNOUNCEMENT, message] def make_assert_my_parent_id(parent_id):
64
64
24
9
55
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_my_parent_id
make_assert_my_parent_id
52
53
52
52
630bde81ea95dd649b6d2c7a00c6c1a0094f6726
bigcode/the-stack
train
1c0ec24ff9f93b9eca855f77
train
function
def make_create_coin_announcement(message): return [ConditionOpcode.CREATE_COIN_ANNOUNCEMENT, message]
def make_create_coin_announcement(message):
return [ConditionOpcode.CREATE_COIN_ANNOUNCEMENT, message]
announcement(announcement_hash): return [ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT, announcement_hash] def make_assert_puzzle_announcement(announcement_hash): return [ConditionOpcode.ASSERT_PUZZLE_ANNOUNCEMENT, announcement_hash] def make_create_coin_announcement(message):
64
64
24
8
56
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_create_coin_announcement
make_create_coin_announcement
44
45
44
44
da544e0eb1587549fccbd7ca5e4af5f31387feaa
bigcode/the-stack
train
15b34c47c88fe764c021ee4e
train
function
def make_create_coin_condition(puzzle_hash, amount): return [ConditionOpcode.CREATE_COIN, puzzle_hash, amount]
def make_create_coin_condition(puzzle_hash, amount):
return [ConditionOpcode.CREATE_COIN, puzzle_hash, amount]
from ceres.util.condition_tools import ConditionOpcode def make_create_coin_condition(puzzle_hash, amount):
21
64
25
11
9
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_create_coin_condition
make_create_coin_condition
4
5
4
4
c87af51f362b0d63e067ccb979c727e52f83f6e4
bigcode/the-stack
train
e2f18d733a044c6bdec563c8
train
function
def make_assert_absolute_height_exceeds_condition(block_index): return [ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, block_index]
def make_assert_absolute_height_exceeds_condition(block_index):
return [ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, block_index]
amount] def make_assert_aggsig_condition(pubkey): return [ConditionOpcode.AGG_SIG_UNSAFE, pubkey] def make_assert_my_coin_id_condition(coin_name): return [ConditionOpcode.ASSERT_MY_COIN_ID, coin_name] def make_assert_absolute_height_exceeds_condition(block_index):
64
64
27
11
53
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_absolute_height_exceeds_condition
make_assert_absolute_height_exceeds_condition
16
17
16
16
8ee84a3daf3e6429f6ce8c7dd2f21cb848fd1cb2
bigcode/the-stack
train
6d95adb05ac15421aef8a0f7
train
function
def make_create_puzzle_announcement(message): return [ConditionOpcode.CREATE_PUZZLE_ANNOUNCEMENT, message]
def make_create_puzzle_announcement(message):
return [ConditionOpcode.CREATE_PUZZLE_ANNOUNCEMENT, message]
make_assert_puzzle_announcement(announcement_hash): return [ConditionOpcode.ASSERT_PUZZLE_ANNOUNCEMENT, announcement_hash] def make_create_coin_announcement(message): return [ConditionOpcode.CREATE_COIN_ANNOUNCEMENT, message] def make_create_puzzle_announcement(message):
64
64
27
9
55
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_create_puzzle_announcement
make_create_puzzle_announcement
48
49
48
48
832422ea4f9429dcf75f2c55524993e9dc9401ad
bigcode/the-stack
train
86a601a1d7415b0919f17746
train
function
def make_assert_aggsig_condition(pubkey): return [ConditionOpcode.AGG_SIG_UNSAFE, pubkey]
def make_assert_aggsig_condition(pubkey):
return [ConditionOpcode.AGG_SIG_UNSAFE, pubkey]
from ceres.util.condition_tools import ConditionOpcode def make_create_coin_condition(puzzle_hash, amount): return [ConditionOpcode.CREATE_COIN, puzzle_hash, amount] def make_assert_aggsig_condition(pubkey):
45
64
24
10
35
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_aggsig_condition
make_assert_aggsig_condition
8
9
8
8
ef40268f82cfbc76d233b680017019b93f7584fc
bigcode/the-stack
train
3cb7d3800fd621f4dadf3805
train
function
def make_assert_relative_seconds_exceeds_condition(time): return [ConditionOpcode.ASSERT_SECONDS_RELATIVE, time]
def make_assert_relative_seconds_exceeds_condition(time):
return [ConditionOpcode.ASSERT_SECONDS_RELATIVE, time]
block_index] def make_assert_relative_height_exceeds_condition(block_index): return [ConditionOpcode.ASSERT_HEIGHT_RELATIVE, block_index] def make_assert_absolute_seconds_exceeds_condition(time): return [ConditionOpcode.ASSERT_SECONDS_ABSOLUTE, time] def make_assert_relative_seconds_exceeds_condition(time)...
64
64
24
10
54
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_relative_seconds_exceeds_condition
make_assert_relative_seconds_exceeds_condition
28
29
28
28
03e9eef24125a50c201d7c84deb3294996796ce1
bigcode/the-stack
train
5df240de62f09be400d71d7a
train
function
def make_assert_my_amount(amount): return [ConditionOpcode.ASSERT_MY_AMOUNT, amount]
def make_assert_my_amount(amount):
return [ConditionOpcode.ASSERT_MY_AMOUNT, amount]
EMENT, message] def make_assert_my_parent_id(parent_id): return [ConditionOpcode.ASSERT_MY_PARENT_ID, parent_id] def make_assert_my_puzzlehash(puzzlehash): return [ConditionOpcode.ASSERT_MY_PUZZLEHASH, puzzlehash] def make_assert_my_amount(amount):
64
64
20
7
57
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_my_amount
make_assert_my_amount
60
61
60
60
1b0b19c5389863da660bfd90d2d7c236cf8efda7
bigcode/the-stack
train
1e105e6fa1d99ff6d8fd719a
train
function
def make_assert_my_coin_id_condition(coin_name): return [ConditionOpcode.ASSERT_MY_COIN_ID, coin_name]
def make_assert_my_coin_id_condition(coin_name):
return [ConditionOpcode.ASSERT_MY_COIN_ID, coin_name]
import ConditionOpcode def make_create_coin_condition(puzzle_hash, amount): return [ConditionOpcode.CREATE_COIN, puzzle_hash, amount] def make_assert_aggsig_condition(pubkey): return [ConditionOpcode.AGG_SIG_UNSAFE, pubkey] def make_assert_my_coin_id_condition(coin_name):
64
64
27
11
53
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_my_coin_id_condition
make_assert_my_coin_id_condition
12
13
12
12
917a7f52aaf837f9a38f04c2ed02a4eb5cf176ad
bigcode/the-stack
train
b42074855f01bbfd307ada90
train
function
def make_assert_absolute_seconds_exceeds_condition(time): return [ConditionOpcode.ASSERT_SECONDS_ABSOLUTE, time]
def make_assert_absolute_seconds_exceeds_condition(time):
return [ConditionOpcode.ASSERT_SECONDS_ABSOLUTE, time]
] def make_assert_absolute_height_exceeds_condition(block_index): return [ConditionOpcode.ASSERT_HEIGHT_ABSOLUTE, block_index] def make_assert_relative_height_exceeds_condition(block_index): return [ConditionOpcode.ASSERT_HEIGHT_RELATIVE, block_index] def make_assert_absolute_seconds_exceeds_condition(time)...
64
64
25
10
54
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_absolute_seconds_exceeds_condition
make_assert_absolute_seconds_exceeds_condition
24
25
24
24
aa7be9791472a37a301ed0a9a0453efca15a175d
bigcode/the-stack
train
0ba50875c0c59dd3ae4ebe64
train
function
def make_assert_coin_announcement(announcement_hash): return [ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT, announcement_hash]
def make_assert_coin_announcement(announcement_hash):
return [ConditionOpcode.ASSERT_COIN_ANNOUNCEMENT, announcement_hash]
SSERT_SECONDS_ABSOLUTE, time] def make_assert_relative_seconds_exceeds_condition(time): return [ConditionOpcode.ASSERT_SECONDS_RELATIVE, time] def make_reserve_fee_condition(fee): return [ConditionOpcode.RESERVE_FEE, fee] def make_assert_coin_announcement(announcement_hash):
64
64
29
10
54
duderino999/ceres-combineharvester
ceres/wallet/puzzles/puzzle_utils.py
Python
make_assert_coin_announcement
make_assert_coin_announcement
36
37
36
36
b0034bfcc13c756276faf019121901b1991ea023
bigcode/the-stack
train
c054699cf895fbb7232a8302
train
function
def IsLaptop() -> bool: return sensors_battery() is not None
def IsLaptop() -> bool:
return sensors_battery() is not None
util import sensors_battery from core.messages import services as Messages """ Author : LimerBoy github.com/LimerBoy/BlazeRAT Notes : The file is needed to get geolocation based on BSSID or IP """ # Is laptop? def IsLaptop() -> bool:
64
64
17
7
57
swagkarna/BlazeRAT
BlazeRAT/services/location.py
Python
IsLaptop
IsLaptop
23
24
23
23
f3d3ea2e7a5a7487ee97b1d0b9ae6d3af28b71f3
bigcode/the-stack
train
6aa55ecefa0e37d3324cc843
train
function
def IpApiRequest() -> Union[bool, dict]: # Make request try: response = get("http://www.geoplugin.net/json.gp") except Exception as error: print(error) return False else: json = response.json() if json["geoplugin_status"] == 200 and response.status_code == 200: ...
def IpApiRequest() -> Union[bool, dict]: # Make request
try: response = get("http://www.geoplugin.net/json.gp") except Exception as error: print(error) return False else: json = response.json() if json["geoplugin_status"] == 200 and response.status_code == 200: lat = GetValue(json, "geoplugin_latitude") ...
, "longitude": lon, "range": rang, "address": addr, "text": "Based on BSSID " + bssid } else: return False """ Get location based in IP address """ def IpApiRequest() -> Union[bool, dict]: # Make request
67
67
226
17
50
swagkarna/BlazeRAT
BlazeRAT/services/location.py
Python
IpApiRequest
IpApiRequest
71
94
71
72
98602b2631e2b85a8879ac09e4f84977419a3d9d
bigcode/the-stack
train
edc6f6f0593155748e3a4318
train
function
def SendLocation(message, bot) -> None: chatid = message.chat.id bot.send_chat_action(chatid, "find_location") if IsLaptop(): result = GetResultBSSID(message, bot) if not result: result = GetResultIp(message, bot) else: result = GetResultIp(message, bot) # Send ...
def SendLocation(message, bot) -> None:
chatid = message.chat.id bot.send_chat_action(chatid, "find_location") if IsLaptop(): result = GetResultBSSID(message, bot) if not result: result = GetResultIp(message, bot) else: result = GetResultIp(message, bot) # Send geolocation bot.send_location(chatid...
Log("Location >> Trying get coordinates based on IP address", chatid) result = IpApiRequest() if not result: bot.send_message(chatid, Messages.location_api_request_failed) return False return result """ Send location """ def SendLocation(message, bot) -> None:
64
64
135
10
54
swagkarna/BlazeRAT
BlazeRAT/services/location.py
Python
SendLocation
SendLocation
134
154
134
134
9342c95c56b572a3a18568a509beebc34491c795
bigcode/the-stack
train
757773b5f36133920dde020a
train
function
def GetResultIp(message, bot) -> Union[bool, dict]: chatid = message.chat.id # Log Log("Location >> Trying get coordinates based on IP address", chatid) result = IpApiRequest() if not result: bot.send_message(chatid, Messages.location_api_request_failed) return False return resu...
def GetResultIp(message, bot) -> Union[bool, dict]:
chatid = message.chat.id # Log Log("Location >> Trying get coordinates based on IP address", chatid) result = IpApiRequest() if not result: bot.send_message(chatid, Messages.location_api_request_failed) return False return result
# Get BSSID information result = BssidApiRequest(bssid) if not result: bot.send_message(chatid, Messages.location_api_request_failed) return False return result """ Get location by IP """ def GetResultIp(message, bot) -> Union[bool, dict]:
64
64
76
15
49
swagkarna/BlazeRAT
BlazeRAT/services/location.py
Python
GetResultIp
GetResultIp
122
131
122
122
7fe224560140f8f901554367d2191d75c3ccedd0
bigcode/the-stack
train
d851e4544271b7a8ae1095f7
train
function
def BssidApiRequest(bssid: str) -> Union[bool, dict]: # Make request try: response = get("https://api.mylnikov.org/geolocation/wifi?v=1.2&bssid=" + bssid) except Exception as error: print(error) return False else: # Parse json json = response.json() if jso...
def BssidApiRequest(bssid: str) -> Union[bool, dict]: # Make request
try: response = get("https://api.mylnikov.org/geolocation/wifi?v=1.2&bssid=" + bssid) except Exception as error: print(error) return False else: # Parse json json = response.json() if json["result"] == 200 and response.status_code == 200: lat = Get...
Value(gateways(), "default").values())) except (StopIteration, AttributeError): return False else: return gws[0] """ Get location based on BSSID address """ def BssidApiRequest(bssid: str) -> Union[bool, dict]: # Make request
64
64
197
22
42
swagkarna/BlazeRAT
BlazeRAT/services/location.py
Python
BssidApiRequest
BssidApiRequest
44
68
44
45
835bf518a8469640e957de1464ccede0c68d28a2
bigcode/the-stack
train
9f76238865350b1e73bc57a0
train
function
def GetResultBSSID(message, bot) -> Union[bool, dict]: chatid = message.chat.id # Log Log("Location >> Trying get coordinates based on BSSID address", chatid) # Detect default gateway ip gateway = GetGateway() if not gateway: bot.send_message(chatid, Messages.location_gateway_detection_f...
def GetResultBSSID(message, bot) -> Union[bool, dict]:
chatid = message.chat.id # Log Log("Location >> Trying get coordinates based on BSSID address", chatid) # Detect default gateway ip gateway = GetGateway() if not gateway: bot.send_message(chatid, Messages.location_gateway_detection_failed) return False # Get gateway mac addre...
range": int(rang), "address": addr, "text": "Based on IP " + GetValue(json, "geoplugin_request") } else: return False """ Get location by BSSID """ def GetResultBSSID(message, bot) -> Union[bool, dict]:
64
64
176
16
48
swagkarna/BlazeRAT
BlazeRAT/services/location.py
Python
GetResultBSSID
GetResultBSSID
97
119
97
97
7227162d1f5a951e94898756552fcc5cfc732425
bigcode/the-stack
train
ac7170a89838ba58bfcfb4a1
train
function
def GetGateway() -> Union[bool, str]: try: gws = next(iter(GetValue(gateways(), "default").values())) except (StopIteration, AttributeError): return False else: return gws[0]
def GetGateway() -> Union[bool, str]:
try: gws = next(iter(GetValue(gateways(), "default").values())) except (StopIteration, AttributeError): return False else: return gws[0]
-> bool: return sensors_battery() is not None # Get value def GetValue(data, val) -> str: try: return data[val] except KeyError: return "Unknown" """ Get dafault gateway ip address """ def GetGateway() -> Union[bool, str]:
64
64
54
11
53
swagkarna/BlazeRAT
BlazeRAT/services/location.py
Python
GetGateway
GetGateway
35
41
35
35
f5ab1ddba5e552a8abdecef48341b33795c08f19
bigcode/the-stack
train
be0e808148b3bc0d0b6aef64
train
function
def GetValue(data, val) -> str: try: return data[val] except KeyError: return "Unknown"
def GetValue(data, val) -> str:
try: return data[val] except KeyError: return "Unknown"
imerBoy/BlazeRAT Notes : The file is needed to get geolocation based on BSSID or IP """ # Is laptop? def IsLaptop() -> bool: return sensors_battery() is not None # Get value def GetValue(data, val) -> str:
64
64
28
10
53
swagkarna/BlazeRAT
BlazeRAT/services/location.py
Python
GetValue
GetValue
28
32
28
28
977348b62ea8e0b5fb4628065692b59d778b4aaf
bigcode/the-stack
train
87c8c8082cb8320736a37a8d
train
class
class MdMultiParser(LAMMPSBaseParser): """Parser for LAMMPS MDMulti calculations.""" def __init__(self, node): """Initialize the instance of Lammps MD Parser.""" super(MdMultiParser, self).__init__(node) def parse(self, **kwargs): """Parse the retrieved folder and store results."""...
class MdMultiParser(LAMMPSBaseParser):
"""Parser for LAMMPS MDMulti calculations.""" def __init__(self, node): """Initialize the instance of Lammps MD Parser.""" super(MdMultiParser, self).__init__(node) def parse(self, **kwargs): """Parse the retrieved folder and store results.""" # retrieve resources r...
import io import os import re import traceback from aiida.orm import ArrayData, Dict import numpy as np from aiida_lammps.common.raw_parsers import convert_units, get_units_dict from aiida_lammps.data.trajectory import LammpsTrajectory from aiida_lammps.parsers.lammps.base import LAMMPSBaseParser class MdMultiParser(...
90
252
842
11
78
JPchico/aiida-lammps
aiida_lammps/parsers/lammps/md_multi.py
Python
MdMultiParser
MdMultiParser
14
122
14
14
20556a59522f43653c2d785f0081ea426185c242
bigcode/the-stack
train
88aec789d2ae0bf184746326
train
function
def workers(hook): """ This function defines virtual workers to be used in benchmarking functions. """ # Reset the hook and the local worker syft.local_worker.clear_objects() hook_args.hook_method_args_functions = {} hook_args.hook_method_response_functions = {} hook_args.register_respo...
def workers(hook):
""" This function defines virtual workers to be used in benchmarking functions. """ # Reset the hook and the local worker syft.local_worker.clear_objects() hook_args.hook_method_args_functions = {} hook_args.hook_method_response_functions = {} hook_args.register_response_functions = {} ...
import torch import syft from syft import TorchHook from syft.generic.frameworks.hook import hook_args def hook(): hook = TorchHook(torch) return hook def workers(hook):
45
64
211
5
39
sparkingdark/PySyft
benchmarks/frameworks/torch/mpc/scripts/abstract/workers_initialization.py
Python
workers
workers
12
36
12
12
35fed4bd2b4d8ab2ba2028eb88fa2976f60f4eb4
bigcode/the-stack
train
5208e86b4b03ad7172c41e14
train
function
def hook(): hook = TorchHook(torch) return hook
def hook():
hook = TorchHook(torch) return hook
import torch import syft from syft import TorchHook from syft.generic.frameworks.hook import hook_args def hook():
29
64
14
3
25
sparkingdark/PySyft
benchmarks/frameworks/torch/mpc/scripts/abstract/workers_initialization.py
Python
hook
hook
7
9
7
7
222d446fb14e38866dc011d546732f7b4ca112b7
bigcode/the-stack
train
d3b17073fc9cd8c144e99c34
train
function
@app.route("/scoretest/<int:score>") def passfail(score): return render_template("highscore.html", marks = score)
@app.route("/scoretest/<int:score>") def passfail(score):
return render_template("highscore.html", marks = score)
") def astros(): mydata = requests.get('http://api.open-notify.org/astros.json') isspeople = mydata.json() return render_template("myastros.html", people=isspeople['people']) @app.route("/scoretest/<int:score>") def passfail(score):
64
64
28
15
49
mikerauer/pyapi
jinja2/jinja03.py
Python
passfail
passfail
14
16
14
15
1680b886626abc78ab13acb6f8587d56ca3d7054
bigcode/the-stack
train
ca24352617bce4bbee3d7889
train
function
@app.route("/astros") def astros(): mydata = requests.get('http://api.open-notify.org/astros.json') isspeople = mydata.json() return render_template("myastros.html", people=isspeople['people'])
@app.route("/astros") def astros():
mydata = requests.get('http://api.open-notify.org/astros.json') isspeople = mydata.json() return render_template("myastros.html", people=isspeople['people'])
#!/usr/bin/python3 from flask import Flask, render_template import requests app = Flask(__name__) @app.route("/astros") def astros():
33
64
54
10
23
mikerauer/pyapi
jinja2/jinja03.py
Python
astros
astros
8
12
8
9
27fd184f581811647e51c9343bfbb674dd6f92f9
bigcode/the-stack
train
2b1654ddbf24bf9ddec65060
train
function
def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None): """ Helper function for element-wise operation. The function will perform numpy-like broadcasting if needed and call different functions. Parameters -------- lhs : NDArray or numeric value Left-hand side operand....
def _ufunc_helper(lhs, rhs, fn_array, fn_scalar, lfn_scalar, rfn_scalar=None):
""" Helper function for element-wise operation. The function will perform numpy-like broadcasting if needed and call different functions. Parameters -------- lhs : NDArray or numeric value Left-hand side operand. rhs : NDArray or numeric value Right-hand operand, fn_array ...
ctx = current_context() return _internal._arange(start=start, stop=stop, step=step, repeat=repeat, infer_range=infer_range, dtype=dtype, ctx=str(ctx)) # pylint: enable= no-member, protected-access, too-many-arguments #pylint: disable= too-many-arguments, no-member, protected-access d...
100
100
336
24
75
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_ufunc_helper
_ufunc_helper
2,581
2,625
2,581
2,581
05262de27c9c7fd4afc2241fb6484157445b651a
bigcode/the-stack
train
592a952aef1a16a069e30bf3
train
function
def lesser_equal(lhs, rhs): """Returns the result of element-wise **lesser than or equal to** (<=) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are lesser than equal to rhs, otherwise return 0(false). Equivalent to ``lhs <= rhs`` and ``mx...
def lesser_equal(lhs, rhs):
"""Returns the result of element-wise **lesser than or equal to** (<=) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are lesser than equal to rhs, otherwise return 0(false). Equivalent to ``lhs <= rhs`` and ``mx.nd.broadcast_lesser_equal(l...
dtype=float32) >>> mx.nd.lesser(x, y).asnumpy() array([[ 0., 0., 0.], [ 0., 0., 0.]], dtype=float32) >>> (z < y).asnumpy() array([[ 0., 0.], [ 1., 0.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, r...
168
168
561
7
160
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
lesser_equal
lesser_equal
3,427
3,487
3,427
3,427
ba009c6ded74ecd1492000644c28fcd553595609
bigcode/the-stack
train
539aa44736f36ce697567c2e
train
function
def from_dlpack(dlpack): """Returns a NDArray backed by a dlpack tensor. Parameters ---------- dlpack: PyCapsule (the pointer of DLManagedTensor) input data Returns ------- NDArray a NDArray backed by a dlpack tensor Examples -------- >>> x = mx.nd.ones((2,3)) ...
def from_dlpack(dlpack):
"""Returns a NDArray backed by a dlpack tensor. Parameters ---------- dlpack: PyCapsule (the pointer of DLManagedTensor) input data Returns ------- NDArray a NDArray backed by a dlpack tensor Examples -------- >>> x = mx.nd.ones((2,3)) >>> y = mx.nd.to_dlpa...
_dlpack(w) >>> u += 1 >>> x [[2. 2. 2.] [2. 2. 2.]] <NDArray 2x3 @cpu(0)> """ check_call(_LIB.MXNDArrayWaitToWrite(data.handle)) dlpack = DLPackHandle() check_call(_LIB.MXNDArrayToDLPack(data.handle, ctypes.byref(dlpack))) return ctypes.pythonapi.PyCapsule_New(dlpack, _c_str_dlt...
132
132
442
7
125
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
from_dlpack
from_dlpack
3,985
4,032
3,985
3,985
89c8a3bbd26dee061e03c38c8f2476b16020f31d
bigcode/the-stack
train
03963698cad23b343728cb16
train
function
def waitall(): """Wait for all async operations to finish in MXNet. This function is used for benchmarking only. """ check_call(_LIB.MXNDArrayWaitAll())
def waitall():
"""Wait for all async operations to finish in MXNet. This function is used for benchmarking only. """ check_call(_LIB.MXNDArrayWaitAll())
ctypes.c_int(shared_pid), ctypes.c_int(shared_id), c_array(mx_uint, shape), mx_uint(len(shape)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])), ctypes.byref(hdl))) return hdl def waitall():
64
64
40
4
59
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
waitall
waitall
156
161
156
156
7dfafdee7385aa8dfec75d611301eff8231e354c
bigcode/the-stack
train
1b2d5a561b52b696c1ec2256
train
function
def arange(start, stop=None, step=1.0, repeat=1, infer_range=False, ctx=None, dtype=mx_real_t): """Returns evenly spaced values within a given interval. Values are generated within the half-open interval [`start`, `stop`). In other words, the interval includes `start` but excludes `stop`. The function is ...
def arange(start, stop=None, step=1.0, repeat=1, infer_range=False, ctx=None, dtype=mx_real_t):
"""Returns evenly spaced values within a given interval. Values are generated within the half-open interval [`start`, `stop`). In other words, the interval includes `start` but excludes `stop`. The function is similar to the built-in Python function `range` and to `numpy.arange`, but returns an `ND...
2L) """ axes = list(range(tensor.ndim)) try: axes.pop(source) except IndexError: raise ValueError('Source should verify 0 <= source < tensor.ndim' 'Got %d' % source) try: axes.insert(destination, source) except IndexError: raise ValueError...
157
157
524
31
125
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
arange
arange
2,532
2,576
2,532
2,532
1d371e176b305cb4ba1c73e85fa1a6c05e2f9a6c
bigcode/the-stack
train
8efefb6c341f2dbce5597ef9
train
function
def logical_xor(lhs, rhs): """Returns the result of element-wise **logical xor** comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements or rhs elements are true, otherwise return 0(false). Equivalent to ``bool(lhs) ^ bool(rhs)`` and ``mx.nd.broadca...
def logical_xor(lhs, rhs):
"""Returns the result of element-wise **logical xor** comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements or rhs elements are true, otherwise return 0(false). Equivalent to ``bool(lhs) ^ bool(rhs)`` and ``mx.nd.broadcast_logical_xor(lhs, rhs)``....
1., 1.]], dtype=float32) >>> mx.nd.logical_or(z, y).asnumpy() array([[ 0., 1.], [ 1., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_logical_or, lambda x, y: 1 if x or y else 0, ...
131
131
437
8
122
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
logical_xor
logical_xor
3,610
3,661
3,610
3,610
653d82f905d47d984476988673d51dc0a7d8d574
bigcode/the-stack
train
1b94aebf5e3bfcdbb96f61b5
train
function
def to_dlpack_for_write(data): """Returns a reference view of NDArray that represents as DLManagedTensor until all previous read/write operations on the current array are finished. Parameters ---------- data: NDArray input data. Returns ------- PyCapsule (the pointer of DLMa...
def to_dlpack_for_write(data):
"""Returns a reference view of NDArray that represents as DLManagedTensor until all previous read/write operations on the current array are finished. Parameters ---------- data: NDArray input data. Returns ------- PyCapsule (the pointer of DLManagedTensor) a referenc...
(0)> """ data.wait_to_read() dlpack = DLPackHandle() check_call(_LIB.MXNDArrayToDLPack(data.handle, ctypes.byref(dlpack))) return ctypes.pythonapi.PyCapsule_New(dlpack, _c_str_dltensor, _c_dlpack_deleter) def to_dlpack_for_write(data):
78
78
260
8
70
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
to_dlpack_for_write
to_dlpack_for_write
3,953
3,983
3,953
3,953
d3a1ed5edd4387b6898b689fc8bbe13fdc1305ff
bigcode/the-stack
train
90da9fac806e1246e99b0642
train
function
def zeros(shape, ctx=None, dtype=None, **kwargs): """Returns a new array filled with all zeros, with the given shape and type. Parameters ---------- shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the current d...
def zeros(shape, ctx=None, dtype=None, **kwargs):
"""Returns a new array filled with all zeros, with the given shape and type. Parameters ---------- shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the current default context). dtype : str or numpy.dtype, o...
_rect[3], channels, len(str_img), str_img=str_img) else: return _internal._imdecode(mean, index, clip_rect[0], clip_rect[1], ...
88
88
295
13
75
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
zeros
zeros
3,771
3,804
3,771
3,771
489190c701892ad8f5a6d75d5efc4531da180c3c
bigcode/the-stack
train
4788eda80cc1fcea3924c703
train
function
def _new_empty_handle(): """Returns a new empty handle. Empty handle can be used to hold a result. Returns ------- handle A new empty `NDArray` handle. """ hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateNone(ctypes.byref(hdl))) return hdl
def _new_empty_handle():
"""Returns a new empty handle. Empty handle can be used to hold a result. Returns ------- handle A new empty `NDArray` handle. """ hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateNone(ctypes.byref(hdl))) return hdl
'add': 3 } # pylint: enable= no-member # Return code for dispatching indexing function call _NDARRAY_UNSUPPORTED_INDEXING = -1 _NDARRAY_BASIC_INDEXING = 0 _NDARRAY_ADVANCED_INDEXING = 1 def _new_empty_handle():
64
64
76
6
57
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_new_empty_handle
_new_empty_handle
107
119
107
107
cb8adab463e20120ecdac71f649262b7eeb2a22f
bigcode/the-stack
train
b5df8477428c495702a8fae1
train
function
def equal(lhs, rhs): """Returns the result of element-wise **equal to** (==) comparison operation with broadcasting. For each element in input arrays, return 1(true) if corresponding elements are same, otherwise return 0(false). Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``....
def equal(lhs, rhs):
"""Returns the result of element-wise **equal to** (==) comparison operation with broadcasting. For each element in input arrays, return 1(true) if corresponding elements are same, otherwise return 0(false). Equivalent to ``lhs == rhs`` and ``mx.nd.broadcast_equal(lhs, rhs)``. .. note:: ...
dtype=float32) >>> mx.nd.minimum(x, y).asnumpy() array([[ 0., 0., 0.], [ 1., 1., 1.]], dtype=float32) >>> mx.nd.minimum(z, y).asnumpy() array([[ 0., 0.], [ 0., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( l...
161
161
537
6
154
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
equal
equal
3,104
3,164
3,104
3,104
b4af69d3acf12b2b784bcfb797a343445ea9752d
bigcode/the-stack
train
d161b75efb1168070e66bdb6
train
function
def _get_dim_size(start, stop, step): """Given start, stop, and stop, calculate the number of elements of this slice.""" assert step != 0 if step > 0: assert start < stop dim_size = (stop - start - 1) // step + 1 else: assert stop < start dim_size = (start - stop - 1)...
def _get_dim_size(start, stop, step):
"""Given start, stop, and stop, calculate the number of elements of this slice.""" assert step != 0 if step > 0: assert start < stop dim_size = (stop - start - 1) // step + 1 else: assert stop < start dim_size = (start - stop - 1) // (-step) + 1 return dim_size
and len(ishape) > 0 oshape = list(ishape[1:]) if ishape[0] < len(dshape): oshape.extend(dshape[ishape[0]:]) return tuple(oshape) def _get_dim_size(start, stop, step):
64
64
104
11
53
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_get_dim_size
_get_dim_size
2,342
2,352
2,342
2,342
88f11a97867bb930fbcef13c6c8f1933bdf2aec8
bigcode/the-stack
train
b6ea17f2ffc487c094148af5
train
function
def minimum(lhs, rhs): """Returns element-wise minimum of the input arrays with broadcasting. Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a com...
def minimum(lhs, rhs):
"""Returns element-wise minimum of the input arrays with broadcasting. Equivalent to ``mx.nd.broadcast_minimum(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Paramet...
1., 1.], [ 1., 1., 1.]], dtype=float32) >>> mx.nd.maximum(y, z).asnumpy() array([[ 0., 1.], [ 1., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_maximum, lambda x, y: x i...
138
138
461
6
131
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
minimum
minimum
3,047
3,100
3,047
3,047
ba12130f3bd06834000781089fd677d7e2e0283f
bigcode/the-stack
train
d40f77f8b14a35ca2d786c7e
train
function
def eye(N, M=0, k=0, ctx=None, dtype=None, **kwargs): """Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N: int Number of rows in the output. M: int, optional Number of columns in the output. If 0, defaults to N. k: int, optional I...
def eye(N, M=0, k=0, ctx=None, dtype=None, **kwargs):
"""Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N: int Number of rows in the output. M: int, optional Number of columns in the output. If 0, defaults to N. k: int, optional Index of the diagonal: 0 (the default) refers to the ma...
=float16) """ # pylint: disable= unused-argument if ctx is None: ctx = current_context() dtype = mx_real_t if dtype is None else dtype # pylint: disable= no-member, protected-access return _internal._zeros(shape=shape, ctx=ctx, dtype=dtype, **kwargs) # pylint: enable= no-member, prot...
106
106
356
21
84
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
eye
eye
3,807
3,846
3,807
3,807
0ddcbeec54fec686c9a9efebd2719c5f1ac89baf
bigcode/the-stack
train
8063eaea3300789c49e3498c
train
function
def histogram(a, bins=10, range=None): """Compute the histogram of the input data. Parameters ---------- a : NDArray Input data. The histogram is computed over the flattened array. bins : int or sequence of scalars If bins is an int, it defines the number of equal-width bins in the ...
def histogram(a, bins=10, range=None):
"""Compute the histogram of the input data. Parameters ---------- a : NDArray Input data. The histogram is computed over the flattened array. bins : int or sequence of scalars If bins is an int, it defines the number of equal-width bins in the given range (10, by default). I...
`float32`). Returns ------- NDArray A created array. """ if isinstance(shape, int): shape = (shape, ) if ctx is None: ctx = current_context() if dtype is None: dtype = mx_real_t return NDArray(handle=_new_alloc_handle(shape, ctx, False, dtype)) # pyli...
98
98
329
11
86
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
histogram
histogram
3,878
3,906
3,878
3,878
87ed0e88e7474a44eb576ea4e696c912c3974060
bigcode/the-stack
train
616e060f6c3e6b844d76213e
train
function
def divide(lhs, rhs): """Returns element-wise division of the input arrays with broadcasting. Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcas...
def divide(lhs, rhs):
"""Returns element-wise division of the input arrays with broadcasting. Equivalent to ``lhs / rhs`` and ``mx.nd.broadcast_div(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shap...
).asnumpy() array([[ 0., 0., 0.], [ 1., 1., 1.]], dtype=float32) >>> (z*y).asnumpy() array([[ 0., 0.], [ 0., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_mul, opera...
135
135
450
6
128
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
divide
divide
2,814
2,867
2,814
2,814
8eab0022e9daf5f243060920305fb43ef0ece097
bigcode/the-stack
train
dbde524f0eea158b6b710ac3
train
function
def onehot_encode(indices, out): """One-hot encoding indices into matrix out. .. note:: `onehot_encode` is deprecated. Use `one_hot` instead. """ # pylint: disable= no-member, protected-access return _internal._onehot_encode(indices, out, out=out)
def onehot_encode(indices, out):
"""One-hot encoding indices into matrix out. .. note:: `onehot_encode` is deprecated. Use `one_hot` instead. """ # pylint: disable= no-member, protected-access return _internal._onehot_encode(indices, out, out=out)
!= 1 and a != b: raise ValueError('shape1=%s is not broadcastable to shape2=%s' % (shape1, shape2)) shape[i] = max(a, b) i -= 1 return tuple(shape) def onehot_encode(indices, out):
64
64
67
8
56
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
onehot_encode
onehot_encode
2,376
2,383
2,376
2,376
f80f0b7c6b8324d4bd8899ca9a69a3f4be54d5ab
bigcode/the-stack
train
11333c48db6ae404949c0c78
train
function
def not_equal(lhs, rhs): """Returns the result of element-wise **not equal to** (!=) comparison operation with broadcasting. For each element in input arrays, return 1(true) if corresponding elements are different, otherwise return 0(false). Equivalent to ``lhs != rhs`` and ``mx.nd.broadcast_not_e...
def not_equal(lhs, rhs):
"""Returns the result of element-wise **not equal to** (!=) comparison operation with broadcasting. For each element in input arrays, return 1(true) if corresponding elements are different, otherwise return 0(false). Equivalent to ``lhs != rhs`` and ``mx.nd.broadcast_not_equal(lhs, rhs)``. .....
[ 1., 1., 1.]], dtype=float32) >>> mx.nd.equal(x,y).asnumpy() array([[ 0., 0., 0.], [ 1., 1., 1.]], dtype=float32) >>> (z == y).asnumpy() array([[ 1., 0.], [ 0., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( ...
173
173
579
7
165
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
not_equal
not_equal
3,168
3,231
3,168
3,168
7dfad129bb4cbfe401e5bd99d417343cdee1dd86
bigcode/the-stack
train
0dc652229d945fd54329ef05
train
function
def _get_indexing_dispatch_code(key): """Returns a dispatch code for calling basic or advanced indexing functions.""" if isinstance(key, (NDArray, np.ndarray)): return _NDARRAY_ADVANCED_INDEXING elif isinstance(key, list): # TODO(junwu): Add support for nested lists besides integer list ...
def _get_indexing_dispatch_code(key):
"""Returns a dispatch code for calling basic or advanced indexing functions.""" if isinstance(key, (NDArray, np.ndarray)): return _NDARRAY_ADVANCED_INDEXING elif isinstance(key, list): # TODO(junwu): Add support for nested lists besides integer list for i in key: if not i...
Capsule'> >>> u = mx.nd.from_dlpack(w) >>> u += 1 >>> x [[2. 2. 2.] [2. 2. 2.]] <NDArray 2x3 @cpu(0)> """ return to_dlpack_for_write(self) def _get_indexing_dispatch_code(key):
79
79
264
9
70
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_get_indexing_dispatch_code
_get_indexing_dispatch_code
2,263
2,286
2,263
2,263
c4ef725bff9ef972863d2f1b2dc438b53f3e22f0
bigcode/the-stack
train
19c03a04bb42c5b10340ad41
train
function
def logical_and(lhs, rhs): """Returns the result of element-wise **logical and** comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements and rhs elements are true, otherwise return 0(false). Equivalent to ``lhs and rhs`` and ``mx.nd.broadcast_logica...
def logical_and(lhs, rhs):
"""Returns the result of element-wise **logical and** comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements and rhs elements are true, otherwise return 0(false). Equivalent to ``lhs and rhs`` and ``mx.nd.broadcast_logical_and(lhs, rhs)``. .. ...
([[ 0., 0., 0.], [ 1., 1., 1.]], dtype=float32) >>> (z <= y).asnumpy() array([[ 1., 0.], [ 1., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_lesser_equal, lambda x, y: 1...
152
152
509
7
144
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
logical_and
logical_and
3,490
3,547
3,490
3,490
558e59ec95dd01515c58749240f63b0cf0a8c1cb
bigcode/the-stack
train
7e3568e51b6a2db40120d7c8
train
function
def concatenate(arrays, axis=0, always_copy=True): """DEPRECATED, use ``concat`` instead Parameters ---------- arrays : list of `NDArray` Arrays to be concatenate. They must have identical shape except the first dimension. They also must have the same data type. axis : int T...
def concatenate(arrays, axis=0, always_copy=True):
"""DEPRECATED, use ``concat`` instead Parameters ---------- arrays : list of `NDArray` Arrays to be concatenate. They must have identical shape except the first dimension. They also must have the same data type. axis : int The axis along which to concatenate. always_copy...
], [ 0., 0., 0.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_logical_xor, lambda x, y: 1 if bool(x) ^ bool(y) else 0, _internal._logical_xor_scalar, None) # pylint: enable= n...
140
140
469
13
127
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
concatenate
concatenate
3,671
3,725
3,671
3,671
e2d8708e0c36bf84f420c5faf6c5426d6cf7d7f6
bigcode/the-stack
train
205c218657bd2cda7273bc4f
train
function
def _new_from_shared_mem(shared_pid, shared_id, shape, dtype): hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateFromSharedMem( ctypes.c_int(shared_pid), ctypes.c_int(shared_id), c_array(mx_uint, shape), mx_uint(len(shape)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dt...
def _new_from_shared_mem(shared_pid, shared_id, shape, dtype):
hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateFromSharedMem( ctypes.c_int(shared_pid), ctypes.c_int(shared_id), c_array(mx_uint, shape), mx_uint(len(shape)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])), ctypes.byref(hdl))) return hdl
ctypes.c_int(ctx.device_id), ctypes.c_int(int(delay_alloc)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])), ctypes.byref(hdl))) return hdl def _new_from_shared_mem(shared_pid, shared_id, shape, dtype):
64
64
98
16
47
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_new_from_shared_mem
_new_from_shared_mem
144
153
144
144
e2ba182984a8c45be3c4c74f2f48cfb0da8c98ea
bigcode/the-stack
train
e14831e74d182f59f051ed79
train
function
def _get_index_range(start, stop, length, step=1): """Given start, stop, step and array length, return absolute values of start, stop, and step for generating index range. The returned values have been compensated by adding length if they are less than zero for all the cases but slice(None, None, -1). ...
def _get_index_range(start, stop, length, step=1):
"""Given start, stop, step and array length, return absolute values of start, stop, and step for generating index range. The returned values have been compensated by adding length if they are less than zero for all the cases but slice(None, None, -1). Note that the returned value of stop is not nece...
ING elif isinstance(key, tuple): for idx in key: if isinstance(idx, (NDArray, np.ndarray, list, tuple)): return _NDARRAY_ADVANCED_INDEXING elif not isinstance(idx, (py_slice, integer_types)): raise ValueError("NDArray does not support slicing with key ...
121
121
404
15
105
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_get_index_range
_get_index_range
2,289
2,329
2,289
2,289
55d5133ce41ea1d9c846378c152fd9cb88508492
bigcode/the-stack
train
cb9157dc99b4ba2864500672
train
function
def to_dlpack_for_read(data): """Returns a reference view of NDArray that represents as DLManagedTensor until all previous write operations on the current array are finished. Parameters ---------- data: NDArray input data. Returns ------- PyCapsule (the pointer of DLManagedT...
def to_dlpack_for_read(data):
"""Returns a reference view of NDArray that represents as DLManagedTensor until all previous write operations on the current array are finished. Parameters ---------- data: NDArray input data. Returns ------- PyCapsule (the pointer of DLManagedTensor) a reference vie...
= ctypes.c_void_p( ctypes.pythonapi.PyCapsule_GetPointer(pycapsule, _c_str_dltensor)) check_call(_LIB.MXNDArrayCallDLPackDeleter(ptr)) _c_dlpack_deleter = PyCapsuleDestructor(_dlpack_deleter) def to_dlpack_for_read(data):
72
72
243
8
64
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
to_dlpack_for_read
to_dlpack_for_read
3,922
3,951
3,922
3,922
2ce41734d8bd0d09f9c6331cd1fc33473c28b89e
bigcode/the-stack
train
f6deb6d621626f2f9cad9f12
train
function
def maximum(lhs, rhs): """Returns element-wise maximum of the input arrays with broadcasting. Equivalent to ``mx.nd.broadcast_maximum(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a com...
def maximum(lhs, rhs):
"""Returns element-wise maximum of the input arrays with broadcasting. Equivalent to ``mx.nd.broadcast_maximum(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape. Paramet...
mx.nd.power(x,y).asnumpy() array([[ 2., 2., 2.], [ 4., 4., 4.]], dtype=float32) >>> (z**y).asnumpy() array([[ 1.], [ 4.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( base, exp, op.broadcast_power, ...
138
138
461
6
131
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
maximum
maximum
2,990
3,043
2,990
2,990
7db7fa493dbd6d273b53d63e04662e170666e63b
bigcode/the-stack
train
27e71672ee3cb909ee070945
train
function
def moveaxis(tensor, source, destination): """Moves the `source` axis into the `destination` position while leaving the other axes in their original order Parameters ---------- tensor : mx.nd.array The array which axes should be reordered source : int Original position of the ax...
def moveaxis(tensor, source, destination):
"""Moves the `source` axis into the `destination` position while leaving the other axes in their original order Parameters ---------- tensor : mx.nd.array The array which axes should be reordered source : int Original position of the axes to move. destination : int D...
else dtype if not isinstance(source_array, np.ndarray): try: source_array = np.array(source_array, dtype=dtype) except: raise TypeError('source_array must be array like object') arr = empty(source_array.shape, ctx, dtype) arr[:] = source_array ...
78
78
261
10
67
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
moveaxis
moveaxis
2,493
2,528
2,493
2,493
d431a83ae0fd5b00078d94e093b7a61188aefecc
bigcode/the-stack
train
e0144337c16f181ff35a9545
train
function
def array(source_array, ctx=None, dtype=None): """Creates an array from any object exposing the array interface. Parameters ---------- source_array : array_like An object exposing the array interface, an object whose `__array__` method returns an array, or any (nested) sequence. ctx...
def array(source_array, ctx=None, dtype=None):
"""Creates an array from any object exposing the array interface. Parameters ---------- source_array : array_like An object exposing the array interface, an object whose `__array__` method returns an array, or any (nested) sequence. ctx : Context, optional Device context (de...
>>> mx.nd.full((1, 2), 2.0, dtype='float16').asnumpy() array([[ 2., 2.]], dtype=float16) """ out = empty(shape, ctx, dtype) if out is None else out out[:] = val return out def array(source_array, ctx=None, dtype=None):
78
78
260
11
66
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
array
array
2,460
2,490
2,460
2,460
419daff9d535f9426f038826207e0755b17b7091
bigcode/the-stack
train
52cf0781fa9deb6c98db0667
train
function
def multiply(lhs, rhs): """Returns element-wise product of the input arrays with broadcasting. Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadca...
def multiply(lhs, rhs):
"""Returns element-wise product of the input arrays with broadcasting. Equivalent to ``lhs * rhs`` and ``mx.nd.broadcast_mul(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape...
) >>> mx.nd.subtract(x,y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32) >>> (z-y).asnumpy() array([[ 0., 1.], [-1., 0.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op....
147
147
492
6
140
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
multiply
multiply
2,753
2,810
2,753
2,753
a10de85bf9e57126251369e6fa403d796d1cbfb3
bigcode/the-stack
train
2e8a4d185c241a4bb959e833
train
class
class NDArray(NDArrayBase): """An array object representing a multidimensional, homogeneous array of fixed-size items. """ __slots__ = [] # make numpy functions return NDArray instead of numpy object array __array_priority__ = 1000.0 # Extension type code for TVM function. # See C++ side of...
class NDArray(NDArrayBase):
"""An array object representing a multidimensional, homogeneous array of fixed-size items. """ __slots__ = [] # make numpy functions return NDArray instead of numpy object array __array_priority__ = 1000.0 # Extension type code for TVM function. # See C++ side of definition(kTVMNDArrayTypeC...
('I', shape)), mx_uint(len(shape)), ctypes.c_int(ctx.device_typeid), ctypes.c_int(ctx.device_id), ctypes.c_int(int(delay_alloc)), ctypes.c_int(int(_DTYPE_NP_TO_MX[np.dtype(dtype).type])), ctypes.byref(hdl))) return hdl def _new_from_shared_mem(shared_pid, shared_id,...
256
256
18,717
8
247
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
NDArray
NDArray
170
2,261
170
170
a8ecd607f5cd9998d4b214b2b3a8c1b147c18211
bigcode/the-stack
train
b73874444dd1f43fff8fce7c
train
function
def logical_or(lhs, rhs): """Returns the result of element-wise **logical or** comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements or rhs elements are true, otherwise return 0(false). Equivalent to ``lhs or rhs`` and ``mx.nd.broadcast_logical_or...
def logical_or(lhs, rhs):
"""Returns the result of element-wise **logical or** comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements or rhs elements are true, otherwise return 0(false). Equivalent to ``lhs or rhs`` and ``mx.nd.broadcast_logical_or(lhs, rhs)``. .. note...
() array([[ 0., 0., 0.], [ 1., 1., 1.]], dtype=float32) >>> mx.nd.logical_and(z, y).asnumpy() array([[ 0., 0.], [ 0., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_logical_a...
152
152
509
7
144
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
logical_or
logical_or
3,550
3,607
3,550
3,550
35a6d233c8789fddb35741a054395f40c3095a54
bigcode/the-stack
train
4108077b3db5f829197a238b
train
function
def greater(lhs, rhs): """Returns the result of element-wise **greater than** (>) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are greater than rhs, otherwise return 0(false). Equivalent to ``lhs > rhs`` and ``mx.nd.broadcast_greater(lhs,...
def greater(lhs, rhs):
"""Returns the result of element-wise **greater than** (>) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are greater than rhs, otherwise return 0(false). Equivalent to ``lhs > rhs`` and ``mx.nd.broadcast_greater(lhs, rhs)``. .. note::...
]], dtype=float32) >>> mx.nd.not_equal(x, y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32) >>> (z != y).asnumpy() array([[ 0., 1.], [ 1., 0.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, ...
164
164
547
6
157
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
greater
greater
3,235
3,295
3,235
3,235
e5859bb67ecc958a186f7c3c861e6e3b8820fcf7
bigcode/the-stack
train
045d9812388df1f46b9b9080
train
function
def greater_equal(lhs, rhs): """Returns the result of element-wise **greater than or equal to** (>=) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs, otherwise return 0(false). Equivalent to ``lhs >= rhs`` and `...
def greater_equal(lhs, rhs):
"""Returns the result of element-wise **greater than or equal to** (>=) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are greater than equal to rhs, otherwise return 0(false). Equivalent to ``lhs >= rhs`` and ``mx.nd.broadcast_greater_equa...
=float32) >>> mx.nd.greater(x, y).asnumpy() array([[ 1., 1., 1.], [ 0., 0., 0.]], dtype=float32) >>> (z > y).asnumpy() array([[ 0., 1.], [ 0., 0.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, ...
167
167
559
7
159
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
greater_equal
greater_equal
3,299
3,359
3,299
3,299
388a81fd16819820d0274114f3d732004bc051d5
bigcode/the-stack
train
b125eafcecb6ceafaf8f776e
train
function
def _get_broadcast_shape(shape1, shape2): """Given two shapes that are not identical, find the shape that both input shapes can broadcast to.""" if shape1 == shape2: return shape1 length1 = len(shape1) length2 = len(shape2) if length1 > length2: shape = list(shape1) else: ...
def _get_broadcast_shape(shape1, shape2):
"""Given two shapes that are not identical, find the shape that both input shapes can broadcast to.""" if shape1 == shape2: return shape1 length1 = len(shape1) length2 = len(shape2) if length1 > length2: shape = list(shape1) else: shape = list(shape2) i = max(len...
dim_size = (stop - start - 1) // step + 1 else: assert stop < start dim_size = (start - stop - 1) // (-step) + 1 return dim_size def _get_broadcast_shape(shape1, shape2):
64
64
184
12
51
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_get_broadcast_shape
_get_broadcast_shape
2,355
2,373
2,355
2,355
0676149cd7240d14b319f1da10521d0feb436841
bigcode/the-stack
train
ecb1e27aa4a9a5e5e2b3eb60
train
function
def lesser(lhs, rhs): """Returns the result of element-wise **lesser than** (<) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are less than rhs, otherwise return 0(false). Equivalent to ``lhs < rhs`` and ``mx.nd.broadcast_lesser(lhs, rhs)`...
def lesser(lhs, rhs):
"""Returns the result of element-wise **lesser than** (<) comparison operation with broadcasting. For each element in input arrays, return 1(true) if lhs elements are less than rhs, otherwise return 0(false). Equivalent to ``lhs < rhs`` and ``mx.nd.broadcast_lesser(lhs, rhs)``. .. note:: ...
.nd.greater_equal(x, y).asnumpy() array([[ 1., 1., 1.], [ 1., 1., 1.]], dtype=float32) >>> (z >= y).asnumpy() array([[ 1., 1.], [ 0., 1.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.bro...
164
164
548
6
157
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
lesser
lesser
3,363
3,423
3,363
3,363
8bacf2e0a0d2fb60a4d4a1b45e330c4dd3627c4b
bigcode/the-stack
train
cde7cb621b0a2327bdbc34c3
train
function
def true_divide(lhs, rhs): """This function is similar to :meth:`divide`. """ return divide(lhs, rhs)
def true_divide(lhs, rhs):
"""This function is similar to :meth:`divide`. """ return divide(lhs, rhs)
, rhs, op.broadcast_logical_xor, lambda x, y: 1 if bool(x) ^ bool(y) else 0, _internal._logical_xor_scalar, None) # pylint: enable= no-member, protected-access def true_divide(lhs, rhs):
64
64
29
8
55
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
true_divide
true_divide
3,664
3,668
3,664
3,665
44fc0fa8235a5d364e83485820adcdd299390dee
bigcode/the-stack
train
69b7a5849b2edc08310a0831
train
function
def full(shape, val, ctx=None, dtype=mx_real_t, out=None): """Returns a new array of given shape and type, filled with the given value `val`. Parameters -------- shape : int or tuple of int The shape of the new array. val : scalar Fill value. ctx : Context, optional Devi...
def full(shape, val, ctx=None, dtype=mx_real_t, out=None):
"""Returns a new array of given shape and type, filled with the given value `val`. Parameters -------- shape : int or tuple of int The shape of the new array. val : scalar Fill value. ctx : Context, optional Device context (default is the current default context). dt...
-argument if ctx is None: ctx = current_context() dtype = mx_real_t if dtype is None else dtype # pylint: disable= no-member, protected-access return _internal._ones(shape=shape, ctx=ctx, dtype=dtype, **kwargs) # pylint: enable= no-member, protected-access def full(shape, val, ctx=None, dtyp...
91
91
305
18
72
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
full
full
2,425
2,457
2,425
2,425
1fcf5b9557f04786ef1a635cef19dc6323068773
bigcode/the-stack
train
5126554218b38cac6222026f
train
function
def subtract(lhs, rhs): """Returns element-wise difference of the input arrays with broadcasting. Equivalent to ``lhs - rhs``, ``mx.nd.broadcast_sub(lhs, rhs)`` and ``mx.nd.broadcast_minus(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them ha...
def subtract(lhs, rhs):
"""Returns element-wise difference of the input arrays with broadcasting. Equivalent to ``lhs - rhs``, ``mx.nd.broadcast_sub(lhs, rhs)`` and ``mx.nd.broadcast_minus(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then th...
2.]], dtype=float32) >>> mx.nd.add(x,y).asnumpy() array([[ 1., 1., 1.], [ 2., 2., 2.]], dtype=float32) >>> (z + y).asnumpy() array([[ 0., 1.], [ 1., 2.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, ...
151
151
505
6
144
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
subtract
subtract
2,691
2,749
2,691
2,691
ff9df8bf6d0dbbc87b531e254d8b2ce1d2e11aad
bigcode/the-stack
train
c4519ad640bdf674d7b146ed
train
function
def modulo(lhs, rhs): """Returns element-wise modulo of the input arrays with broadcasting. Equivalent to ``lhs % rhs`` and ``mx.nd.broadcast_mod(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcasta...
def modulo(lhs, rhs):
"""Returns element-wise modulo of the input arrays with broadcasting. Equivalent to ``lhs % rhs`` and ``mx.nd.broadcast_mod(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays are broadcastable to a common shape....
.], [ 3., 3., 3.]], dtype=float32) >>> mx.nd.divide(x,y).asnumpy() array([[ 3., 3., 3.], [ 3., 3., 3.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broadcast_div, operator.truediv, ...
135
135
451
6
128
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
modulo
modulo
2,871
2,924
2,871
2,871
526d58eb6eb7cf9fd405536fde27b6f8daafbf02
bigcode/the-stack
train
a2a1e61c1ca45d16ecda1aa5
train
function
def add(lhs, rhs): """Returns element-wise sum of the input arrays with broadcasting. Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and ``mx.nd.broadcast_plus(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, ...
def add(lhs, rhs):
"""Returns element-wise sum of the input arrays with broadcasting. Equivalent to ``lhs + rhs``, ``mx.nd.broadcast_add(lhs, rhs)`` and ``mx.nd.broadcast_plus(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then the arrays...
NDArray result array """ if isinstance(lhs, numeric_types): if isinstance(rhs, numeric_types): return fn_scalar(lhs, rhs) else: if rfn_scalar is None: # commutative function return lfn_scalar(rhs, float(lhs)) else: ...
151
151
505
6
144
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
add
add
2,629
2,687
2,629
2,629
c110c217aa4fc6617f3e9eec681ef78678b0bfce
bigcode/the-stack
train
580ae6c591c6e7998579f493
train
function
def _get_oshape_of_gather_nd_op(dshape, ishape): """Given data and index shapes, get the output `NDArray` shape. This basically implements the infer shape logic of op gather_nd.""" assert len(dshape) > 0 and len(ishape) > 0 oshape = list(ishape[1:]) if ishape[0] < len(dshape): oshape.extend(...
def _get_oshape_of_gather_nd_op(dshape, ishape):
"""Given data and index shapes, get the output `NDArray` shape. This basically implements the infer shape logic of op gather_nd.""" assert len(dshape) > 0 and len(ishape) > 0 oshape = list(ishape[1:]) if ishape[0] < len(dshape): oshape.extend(dshape[ishape[0]:]) return tuple(oshape)
of %d' % (stop-length, length)) elif stop > length: raise IndexError('Slicing stop %d exceeds limit of %d' % (stop, length)) return start, stop, step def _get_oshape_of_gather_nd_op(dshape, ishape):
64
64
109
17
46
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_get_oshape_of_gather_nd_op
_get_oshape_of_gather_nd_op
2,332
2,339
2,332
2,332
5ebab625b102f6d9b719c61c9be11632013ac85f
bigcode/the-stack
train
ef2741a03a8e0e4608a93e0e
train
function
def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t): """Return a new handle with specified shape and context. Empty handle is only used to hold results. Returns ------- handle A new empty `NDArray` handle. """ hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateEx(...
def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):
"""Return a new handle with specified shape and context. Empty handle is only used to hold results. Returns ------- handle A new empty `NDArray` handle. """ hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateEx( c_array_buf(mx_uint, native_array('I', shape)), ...
handle A new empty `NDArray` handle. """ hdl = NDArrayHandle() check_call(_LIB.MXNDArrayCreateNone(ctypes.byref(hdl))) return hdl def _new_alloc_handle(shape, ctx, delay_alloc, dtype=mx_real_t):
64
64
157
18
45
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_new_alloc_handle
_new_alloc_handle
122
141
122
122
647495f8dc5c39821e69cd454085548d39622c9d
bigcode/the-stack
train
be921bccfc9d058a79a4eac0
train
function
def power(base, exp): """Returns result of first array elements raised to powers from second array, element-wise with broadcasting. Equivalent to ``base ** exp`` and ``mx.nd.broadcast_power(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them h...
def power(base, exp):
"""Returns result of first array elements raised to powers from second array, element-wise with broadcasting. Equivalent to ``base ** exp`` and ``mx.nd.broadcast_power(lhs, rhs)``. .. note:: If the corresponding dimensions of two arrays have the same size or one of them has size 1, then...
y).asnumpy() array([[ 2., 2., 2.], [ 2., 2., 2.]], dtype=float32) >>> mx.nd.modulo(x,y).asnumpy() array([[ 2., 2., 2.], [ 2., 2., 2.]], dtype=float32) """ # pylint: disable= no-member, protected-access return _ufunc_helper( lhs, rhs, op.broad...
152
152
508
6
145
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
power
power
2,928
2,986
2,928
2,928
701240249bf88817a98938505f2312bd04c3230d
bigcode/the-stack
train
241417db979e5525376f4be0
train
function
def empty(shape, ctx=None, dtype=None): """Returns a new array of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the current default co...
def empty(shape, ctx=None, dtype=None):
"""Returns a new array of given shape and type, without initializing entries. Parameters ---------- shape : int or tuple of int The shape of the empty array. ctx : Context, optional An optional device context (default is the current default context). dtype : str or numpy.dtype, ...
None else dtype # pylint: disable= no-member, protected-access return _internal._eye(N=N, M=M, k=k, ctx=ctx, dtype=dtype, **kwargs) # pylint: enable= no-member, protected-access def empty(shape, ctx=None, dtype=None):
64
64
163
10
53
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
empty
empty
3,850
3,874
3,850
3,850
922583ce8b0c95fd7a259a6f4cffbb0b75d4fc3f
bigcode/the-stack
train
21d8da7381b759ab3951df85
train
function
def imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None): """DEPRECATED, use mx.img instead Parameters ---------- str_img : str Binary image data clip_rect : iterable of 4 int Clip decoded image to rectangle (x0, y0, x1, y1). out : NDArray ...
def imdecode(str_img, clip_rect=(0, 0, 0, 0), out=None, index=0, channels=3, mean=None):
"""DEPRECATED, use mx.img instead Parameters ---------- str_img : str Binary image data clip_rect : iterable of 4 int Clip decoded image to rectangle (x0, y0, x1, y1). out : NDArray Output buffer. Can be 3 dimensional (c, h, w) or 4 dimensional (n, c, h, w). index : ...
-member,protected-access _internal._crop_assign(ret, arr, out=ret, begin=tuple(begin), end=tuple(end)) # pylint: enable=no-member,protected-access idx += arr.shape[axis] return ret # pylint: disable=redefined-ou...
98
98
329
34
63
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
imdecode
imdecode
3,729
3,768
3,729
3,729
82538f1776ee6dbab59227cfa7a7b95867aad76c
bigcode/the-stack
train
3188a2c7d6ba639118f174d5
train
function
def _storage_type(handle): storage_type = ctypes.c_int(0) check_call(_LIB.MXNDArrayGetStorageType(handle, ctypes.byref(storage_type))) return storage_type.value
def _storage_type(handle):
storage_type = ctypes.c_int(0) check_call(_LIB.MXNDArrayGetStorageType(handle, ctypes.byref(storage_type))) return storage_type.value
.dtype(dtype).type])), ctypes.byref(hdl))) return hdl def waitall(): """Wait for all async operations to finish in MXNet. This function is used for benchmarking only. """ check_call(_LIB.MXNDArrayWaitAll()) def _storage_type(handle):
64
64
42
6
58
paroda/incubator-mxnet
python/mxnet/ndarray/ndarray.py
Python
_storage_type
_storage_type
164
167
164
164
347c0d6115287af035dc4c2c199d9e9c39c51d0c
bigcode/the-stack
train