code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
182
| url
stringlengths 46
251
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def test_scan_event_result_export_multi(self):
"""
Test scaneventresultexportmulti(self, ids, filetype="csv", dialect="excel")
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
search_results = sfwebui.scaneventresultexportmulti("", "")
self.assertIsInstance(search_results, bytes)
search_results = sfwebui.scaneventresultexportmulti("", "excel")
self.assertIsInstance(search_results, bytes) | Test scaneventresultexportmulti(self, ids, filetype="csv", dialect="excel") | test_scan_event_result_export_multi | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scan_search_result_export(self):
"""
Test scansearchresultexport(self, id, eventType=None, value=None, filetype="csv", dialect="excel")
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
search_results = sfwebui.scansearchresultexport("")
self.assertIsInstance(search_results, bytes)
search_results = sfwebui.scansearchresultexport("", None, None, "excel")
self.assertIsInstance(search_results, bytes) | Test scansearchresultexport(self, id, eventType=None, value=None, filetype="csv", dialect="excel") | test_scan_search_result_export | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scan_export_logs_invalid_scan_id_should_return_string(self):
"""
Test scanexportlogs(self: 'SpiderFootWebUi', id: str, dialect: str = "excel") -> str
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
logs = sfwebui.scanexportlogs(None, "excel")
self.assertIsInstance(logs, str)
self.assertIn("Scan ID not found.", logs) | Test scanexportlogs(self: 'SpiderFootWebUi', id: str, dialect: str = "excel") -> str | test_scan_export_logs_invalid_scan_id_should_return_string | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scan_export_json_multi(self):
"""
Test scanexportjsonmulti(self, ids)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
search_results = sfwebui.scanexportjsonmulti(None)
self.assertIsInstance(search_results, bytes) | Test scanexportjsonmulti(self, ids) | test_scan_export_json_multi | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scan_viz_should_return_a_string(self):
"""
Test scanviz(self, id, gexf="0")
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_viz = sfwebui.scanviz(None, None)
self.assertIsInstance(scan_viz, str) | Test scanviz(self, id, gexf="0") | test_scan_viz_should_return_a_string | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scan_viz_multi_should_return_a_string(self):
"""
Test scanvizmulti(self, ids, gexf="1")
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_viz_multi = sfwebui.scanvizmulti(None, None)
self.assertIsInstance(scan_viz_multi, str) | Test scanvizmulti(self, ids, gexf="1") | test_scan_viz_multi_should_return_a_string | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_rerunscanmulti(self):
"""
Test rerunscanmulti(self, ids)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
rerunscanmulti = sfwebui.rerunscanmulti("example scan instance")
self.assertIsInstance(rerunscanmulti, str) | Test rerunscanmulti(self, ids) | test_rerunscanmulti | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_newscan(self):
"""
Test newscan(self)
"""
self.assertEqual('TBD', 'TBD') | Test newscan(self) | test_newscan | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_clonescan(self):
"""
Test clonescan(self, id)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
clone_scan = sfwebui.clonescan("example scan instance")
self.assertIsInstance(clone_scan, str) | Test clonescan(self, id) | test_clonescan | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_index(self):
"""
Test index(self)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
index = sfwebui.index()
self.assertIsInstance(index, str) | Test index(self) | test_index | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scaninfo(self):
"""
Test scaninfo(self, id)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_info = sfwebui.scaninfo("example scan instance")
self.assertIsInstance(scan_info, str) | Test scaninfo(self, id) | test_scaninfo | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scandelete_invalid_scanid_should_return_an_error(self):
"""
Test scandelete(self, id)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_delete = sfwebui.scandelete("example scan id")
self.assertIsInstance(scan_delete, dict)
self.assertEqual("Scan example scan id does not exist", scan_delete.get('error').get('message')) | Test scandelete(self, id) | test_scandelete_invalid_scanid_should_return_an_error | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_savesettings_invalid_csrf_token_should_return_an_error(self):
"""
Test savesettings(self, allopts, token, configFile=None)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
save_settings = sfwebui.savesettings(None, "invalid token", None)
self.assertIsInstance(save_settings, str)
self.assertIn("Invalid token", save_settings) | Test savesettings(self, allopts, token, configFile=None) | test_savesettings_invalid_csrf_token_should_return_an_error | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_result_set_fp(self):
"""
Test resultsetfp(self, id, resultids, fp)
"""
self.assertEqual('TBD', 'TBD') | Test resultsetfp(self, id, resultids, fp) | test_result_set_fp | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_ping_should_return_list(self):
"""
Test ping(self)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
ping = sfwebui.ping()
self.assertIsInstance(ping, list)
self.assertEqual(ping[0], 'SUCCESS') | Test ping(self) | test_ping_should_return_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_query_should_perform_sql_query(self):
"""
Test query(self, query)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
select = "12345"
query = sfwebui.query(f"SELECT {select}")
self.assertIsInstance(query, list)
self.assertEqual(len(query), 1)
self.assertEqual(str(query[0].get(select)), str(select)) | Test query(self, query) | test_query_should_perform_sql_query | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_start_scan_should_start_a_scan(self):
"""
Test startscan(self, scanname, scantarget, modulelist, typelist, usecase)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
start_scan = sfwebui.startscan('example scan name', 'spiderfoot.net', 'example module list', None, None)
self.assertEqual(start_scan, start_scan)
self.assertEqual('TBD', 'TBD') | Test startscan(self, scanname, scantarget, modulelist, typelist, usecase) | test_start_scan_should_start_a_scan | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_stopscan_invalid_scanid_should_return_an_error(self):
"""
Test stopscan(self, id)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
stop_scan = sfwebui.stopscan("example scan id")
self.assertIsInstance(stop_scan, dict)
self.assertEqual("Scan example scan id does not exist", stop_scan.get('error').get('message')) | Test stopscan(self, id) | test_stopscan_invalid_scanid_should_return_an_error | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scanlog_should_return_a_list(self):
"""
Test scanlog(self, id, limit=None, rowId=None, reverse=None)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_log = sfwebui.scanlog(None, None, None, None)
self.assertIsInstance(scan_log, list)
scan_log = sfwebui.scanlog('', '', '', '')
self.assertIsInstance(scan_log, list) | Test scanlog(self, id, limit=None, rowId=None, reverse=None) | test_scanlog_should_return_a_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scanerrors_should_return_a_list(self):
"""
Test scanerrors(self, id, limit=None)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_errors = sfwebui.scanerrors(None, None)
self.assertIsInstance(scan_errors, list)
scan_errors = sfwebui.scanerrors('', '')
self.assertIsInstance(scan_errors, list) | Test scanerrors(self, id, limit=None) | test_scanerrors_should_return_a_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scanlist_should_return_a_list(self):
"""
Test scanlist(self)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_list = sfwebui.scanlist()
self.assertIsInstance(scan_list, list) | Test scanlist(self) | test_scanlist_should_return_a_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scanstatus_should_return_a_list(self):
"""
Test scanstatus(self, id)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_status = sfwebui.scanstatus("example scan instance")
self.assertIsInstance(scan_status, list) | Test scanstatus(self, id) | test_scanstatus_should_return_a_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scansummary_should_return_a_list(self):
"""
Test scansummary(self, id, by)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_summary = sfwebui.scansummary(None, None)
self.assertIsInstance(scan_summary, list)
scan_summary = sfwebui.scansummary('', '')
self.assertIsInstance(scan_summary, list) | Test scansummary(self, id, by) | test_scansummary_should_return_a_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scaneventresults_should_return_a_list(self):
"""
Test scaneventresults(self, id, eventType, filterfp=False)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_results = sfwebui.scaneventresults(None, None, None)
self.assertIsInstance(scan_results, list)
scan_results = sfwebui.scaneventresults('', '', '')
self.assertIsInstance(scan_results, list) | Test scaneventresults(self, id, eventType, filterfp=False) | test_scaneventresults_should_return_a_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scaneventresultsunique_should_return_a_list(self):
"""
Test scaneventresultsunique(self, id, eventType, filterfp=False)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_results = sfwebui.scaneventresultsunique(None, None, None)
self.assertIsInstance(scan_results, list)
scan_results = sfwebui.scaneventresultsunique('', '', '')
self.assertIsInstance(scan_results, list) | Test scaneventresultsunique(self, id, eventType, filterfp=False) | test_scaneventresultsunique_should_return_a_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_search_should_return_a_list(self):
"""
Test search(self, id=None, eventType=None, value=None)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
search_results = sfwebui.search(None, None, None)
self.assertIsInstance(search_results, list)
search_results = sfwebui.search('', '', '')
self.assertIsInstance(search_results, list) | Test search(self, id=None, eventType=None, value=None) | test_search_should_return_a_list | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scan_history_missing_scanid_should_return_error(self):
"""
Test scanhistory(self, id)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_history = sfwebui.scanhistory(None)
self.assertIsInstance(scan_history, dict)
self.assertEqual("No scan specified", scan_history.get('error').get('message'))
scan_history = sfwebui.scanhistory("example scan id")
self.assertIsInstance(scan_history, list) | Test scanhistory(self, id) | test_scan_history_missing_scanid_should_return_error | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_scan_element_type_discovery_should_return_a_dict(self):
"""
Test scanelementtypediscovery(self, id, eventType)
"""
opts = self.default_options
opts['__modules__'] = dict()
sfwebui = SpiderFootWebUi(self.web_default_options, opts)
scan_element_type_discovery = sfwebui.scanelementtypediscovery(None, None)
self.assertIsInstance(scan_element_type_discovery, dict)
scan_element_type_discovery = sfwebui.scanelementtypediscovery('', '')
self.assertIsInstance(scan_element_type_discovery, dict) | Test scanelementtypediscovery(self, id, eventType) | test_scan_element_type_discovery_should_return_a_dict | python | smicallef/spiderfoot | test/unit/test_spiderfootwebui.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootwebui.py | MIT |
def test_init_argument_start_false_should_create_a_scan_without_starting_the_scan(self):
"""
Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts, start=True)
"""
opts = self.default_options
opts['__modules__'] = dict()
scan_id = str(uuid.uuid4())
module_list = ['sfp__stor_db']
sfscan = SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", "INTERNET_NAME", module_list, opts, start=False)
self.assertIsInstance(sfscan, SpiderFootScanner)
self.assertEqual(sfscan.status, "INITIALIZING") | Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts, start=True) | test_init_argument_start_false_should_create_a_scan_without_starting_the_scan | python | smicallef/spiderfoot | test/unit/test_spiderfootscanner.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootscanner.py | MIT |
def test_init_argument_targetType_of_invalid_type_should_raise_TypeError(self):
"""
Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts)
"""
scan_id = str(uuid.uuid4())
module_list = ['sfp__stor_db']
invalid_types = [None, list(), dict(), int()]
for invalid_type in invalid_types:
with self.subTest(invalid_type=invalid_type):
with self.assertRaises(TypeError):
SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", invalid_type, module_list, self.default_options, start=False) | Test __init__(self, scanName, scanId, scanTarget, targetType, moduleList, globalOpts) | test_init_argument_targetType_of_invalid_type_should_raise_TypeError | python | smicallef/spiderfoot | test/unit/test_spiderfootscanner.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootscanner.py | MIT |
def test__setStatus_argument_status_of_invalid_type_should_raise_TypeError(self):
"""
Test __setStatus(self, status, started=None, ended=None)
"""
opts = self.default_options
opts['__modules__'] = dict()
scan_id = str(uuid.uuid4())
module_list = ['sfp__stor_db']
sfscan = SpiderFootScanner("example scan name", scan_id, "spiderfoot.net", "IP_ADDRESS", module_list, opts, start=False)
invalid_types = [None, list(), dict(), int()]
for invalid_type in invalid_types:
with self.subTest(invalid_type=invalid_type):
with self.assertRaises(TypeError):
sfscan._SpiderFootScanner__setStatus(invalid_type) | Test __setStatus(self, status, started=None, ended=None) | test__setStatus_argument_status_of_invalid_type_should_raise_TypeError | python | smicallef/spiderfoot | test/unit/test_spiderfootscanner.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/test_spiderfootscanner.py | MIT |
def test_init(self):
"""
Test __init__(self)
"""
sfp = SpiderFootPlugin()
self.assertIsInstance(sfp, SpiderFootPlugin) | Test __init__(self) | test_init | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_updateSocket(self):
"""
Test _updateSocket(self, sock)
"""
sfp = SpiderFootPlugin()
sfp._updateSocket(None)
self.assertEqual('TBD', 'TBD') | Test _updateSocket(self, sock) | test_updateSocket | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_clearListeners(self):
"""
Test clearListeners(self)
"""
sfp = SpiderFootPlugin()
sfp.clearListeners()
self.assertEqual('TBD', 'TBD') | Test clearListeners(self) | test_clearListeners | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_setup(self):
"""
Test setup(self, sf, userOpts=dict())
"""
sfp = SpiderFootPlugin()
sfp.setup(None)
sfp.setup(None, None)
self.assertEqual('TBD', 'TBD') | Test setup(self, sf, userOpts=dict()) | test_setup | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_enrichTargetargument_target_should_enrih_target(self):
"""
Test enrichTarget(self, target)
"""
sfp = SpiderFootPlugin()
sfp.enrichTarget(None)
self.assertEqual('TBD', 'TBD') | Test enrichTarget(self, target) | test_enrichTargetargument_target_should_enrih_target | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_setTarget_should_set_a_target(self):
"""
Test setTarget(self, target)
"""
sfp = SpiderFootPlugin()
target = SpiderFootTarget("spiderfoot.net", "INTERNET_NAME")
sfp.setTarget(target)
get_target = sfp.getTarget().targetValue
self.assertIsInstance(get_target, str)
self.assertEqual("spiderfoot.net", get_target) | Test setTarget(self, target) | test_setTarget_should_set_a_target | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_set_dbhargument_dbh_should_set_database_handle(self):
"""
Test setDbh(self, dbh)
"""
sfdb = SpiderFootDb(self.default_options, False)
sfp = SpiderFootPlugin()
sfp.setDbh(sfdb)
self.assertIsInstance(sfp.__sfdb__, SpiderFootDb) | Test setDbh(self, dbh) | test_set_dbhargument_dbh_should_set_database_handle | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_setScanId_argument_id_should_set_a_scan_id(self):
"""
Test setScanId(self, id)
"""
sfp = SpiderFootPlugin()
scan_id = '1234'
sfp.setScanId(scan_id)
get_scan_id = sfp.getScanId()
self.assertIsInstance(get_scan_id, str)
self.assertEqual(scan_id, get_scan_id) | Test setScanId(self, id) | test_setScanId_argument_id_should_set_a_scan_id | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_getScanId_should_return_a_string(self):
"""
Test getScanId(self)
"""
sfp = SpiderFootPlugin()
scan_id = 'example scan id'
sfp.setScanId(scan_id)
get_scan_id = sfp.getScanId()
self.assertIsInstance(get_scan_id, str)
self.assertEqual(scan_id, get_scan_id) | Test getScanId(self) | test_getScanId_should_return_a_string | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_getTarget_should_return_a_string(self):
"""
Test getTarget(self)
"""
sfp = SpiderFootPlugin()
target = SpiderFootTarget("spiderfoot.net", "INTERNET_NAME")
sfp.setTarget(target)
get_target = sfp.getTarget().targetValue
self.assertIsInstance(get_target, str)
self.assertEqual("spiderfoot.net", get_target) | Test getTarget(self) | test_getTarget_should_return_a_string | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_register_listener(self):
"""
Test registerListener(self, listener)
"""
sfp = SpiderFootPlugin()
sfp.registerListener(None)
self.assertEqual('TBD', 'TBD') | Test registerListener(self, listener) | test_register_listener | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_setOutputFilter_should_set_output_filter(self):
"""
Test setOutputFilter(self, types)
"""
sfp = SpiderFootPlugin()
output_filter = "test filter"
sfp.setOutputFilter("test filter")
self.assertEqual(output_filter, sfp.__outputFilter__) | Test setOutputFilter(self, types) | test_setOutputFilter_should_set_output_filter | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_tempStorage_should_return_a_dict(self):
"""
Test tempStorage(self)
"""
sfp = SpiderFootPlugin()
temp_storage = sfp.tempStorage()
self.assertIsInstance(temp_storage, dict) | Test tempStorage(self) | test_tempStorage_should_return_a_dict | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_notifyListeners_should_notify_listener_modules(self):
"""
Test notifyListeners(self, sfEvent)
"""
sfp = SpiderFootPlugin()
sfdb = SpiderFootDb(self.default_options, False)
sfp.setDbh(sfdb)
event_type = 'ROOT'
event_data = 'test data'
module = 'test module'
source_event = None
evt = SpiderFootEvent(event_type, event_data, module, source_event)
sfp.notifyListeners(evt)
self.assertEqual('TBD', 'TBD') | Test notifyListeners(self, sfEvent) | test_notifyListeners_should_notify_listener_modules | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_checkForStop(self):
"""
Test checkForStop(self)
"""
sfp = SpiderFootPlugin()
class DatabaseStub:
def scanInstanceGet(self, scanId):
return [None, None, None, None, None, status]
sfp.__sfdb__ = DatabaseStub()
sfp.__scanId__ = 'example scan id'
# pseudo-parameterized test
scan_statuses = [
(None, False),
("anything", False),
("RUNNING", False),
("ABORT-REQUESTED", True)
]
for status, expectedReturnValue in scan_statuses:
returnValue = sfp.checkForStop()
self.assertEqual(returnValue, expectedReturnValue, status) | Test checkForStop(self) | test_checkForStop | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_watchedEvents_should_return_a_list(self):
"""
Test watchedEvents(self)
"""
sfp = SpiderFootPlugin()
watched_events = sfp.watchedEvents()
self.assertIsInstance(watched_events, list) | Test watchedEvents(self) | test_watchedEvents_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_producedEvents_should_return_a_list(self):
"""
Test producedEvents(self)
"""
sfp = SpiderFootPlugin()
produced_events = sfp.producedEvents()
self.assertIsInstance(produced_events, list) | Test producedEvents(self) | test_producedEvents_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_handleEvent(self):
"""
Test handleEvent(self, sfEvent)
"""
event_type = 'ROOT'
event_data = 'example event data'
module = ''
source_event = ''
evt = SpiderFootEvent(event_type, event_data, module, source_event)
sfp = SpiderFootPlugin()
sfp.handleEvent(evt) | Test handleEvent(self, sfEvent) | test_handleEvent | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_start(self):
"""
Test start(self)
"""
sf = SpiderFoot(self.default_options)
sfp = SpiderFootPlugin()
sfp.sf = sf
sfp.start() | Test start(self) | test_start | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootplugin.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootplugin.py | MIT |
def test_getEquivalents_should_return_a_list(self):
"""
Test _getEquivalents(self, typeName)
"""
target_value = 'example target value'
target_type = 'IP_ADDRESS'
target = SpiderFootTarget(target_value, target_type)
equivalents = target._getEquivalents(target_type)
self.assertEqual(list, type(equivalents)) | Test _getEquivalents(self, typeName) | test_getEquivalents_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfoottarget.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfoottarget.py | MIT |
def test_getNames_should_return_a_list(self):
"""
Test getNames(self)
"""
target_value = 'example target value'
target_type = 'IP_ADDRESS'
target = SpiderFootTarget(target_value, target_type)
names = target.getNames()
self.assertEqual(list, type(names)) | Test getNames(self) | test_getNames_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfoottarget.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfoottarget.py | MIT |
def test_getAddresses_should_return_a_list(self):
"""
Test getAddresses(self)
"""
target_value = 'example target value'
target_type = 'IP_ADDRESS'
target = SpiderFootTarget(target_value, target_type)
addresses = target.getAddresses()
self.assertEqual(list, type(addresses))
target_value = 'example target value'
target_type = 'IPV6_ADDRESS'
target = SpiderFootTarget(target_value, target_type)
addresses = target.getAddresses()
self.assertEqual(list, type(addresses)) | Test getAddresses(self) | test_getAddresses_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfoottarget.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfoottarget.py | MIT |
def test_init_argument_opts_of_invalid_type_should_raise_TypeError(self):
"""
Test __init__(self, opts, init=False)
"""
invalid_types = [None, "", list(), int()]
for invalid_type in invalid_types:
with self.subTest(invalid_type=invalid_type):
with self.assertRaises(TypeError):
SpiderFootDb(invalid_type) | Test __init__(self, opts, init=False) | test_init_argument_opts_of_invalid_type_should_raise_TypeError | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_create_should_create_database_schema(self):
"""
Test create(self)
"""
sfdb = SpiderFootDb(self.default_options, False)
sfdb.create()
self.assertEqual('TBD', 'TBD') | Test create(self) | test_create_should_create_database_schema | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_close_should_close_database_connection(self):
"""
Test close(self)
"""
sfdb = SpiderFootDb(self.default_options, False)
sfdb.close() | Test close(self) | test_close_should_close_database_connection | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_search_should_return_a_list(self):
"""
Test search(self, criteria, filterFp=False)
"""
sfdb = SpiderFootDb(self.default_options, False)
criteria = {
'scan_id': "example scan id",
'type': "example type",
'value': "example value",
'regex': "example regex"
}
search_results = sfdb.search(criteria, False)
self.assertIsInstance(search_results, list)
self.assertFalse(search_results) | Test search(self, criteria, filterFp=False) | test_search_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_eventTypes_should_return_a_list(self):
"""
Test eventTypes(self)
"""
sfdb = SpiderFootDb(self.default_options, False)
event_types = sfdb.eventTypes()
self.assertIsInstance(event_types, list) | Test eventTypes(self) | test_eventTypes_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanLogEvent_should_create_a_scan_log_event(self):
"""
Test scanLogEvent(self, instanceId, classification, message, component=None)
"""
sfdb = SpiderFootDb(self.default_options, False)
sfdb.scanLogEvent("", "", "", None)
self.assertEqual('TBD', 'TBD') | Test scanLogEvent(self, instanceId, classification, message, component=None) | test_scanLogEvent_should_create_a_scan_log_event | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanInstanceCreate_should_create_a_scan_instance(self):
"""
Test scanInstanceCreate(self, instanceId, scanName, scanTarget)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_name = "example scan name"
scan_target = "example scan target"
sfdb.scanInstanceCreate(instance_id, scan_name, scan_target)
self.assertEqual('TBD', 'TBD') | Test scanInstanceCreate(self, instanceId, scanName, scanTarget) | test_scanInstanceCreate_should_create_a_scan_instance | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanInstanceSet(self):
"""
Test scanInstanceSet(self, instanceId, started=None, ended=None, status=None)
"""
sfdb = SpiderFootDb(self.default_options, False)
scan_instance = 'example scan instance'
sfdb.scanInstanceSet(scan_instance, None, None, None)
self.assertEqual('TBD', 'TBD') | Test scanInstanceSet(self, instanceId, started=None, ended=None, status=None) | test_scanInstanceSet | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanInstanceGet_should_return_scan_info(self):
"""
Test scanInstanceGet(self, instanceId)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_name = "example scan name"
scan_target = "example scan target"
sfdb.scanInstanceCreate(instance_id, scan_name, scan_target)
scan_instance_get = sfdb.scanInstanceGet(instance_id)
self.assertEqual(len(scan_instance_get), 6)
self.assertIsInstance(scan_instance_get[0], str)
self.assertEqual(scan_instance_get[0], scan_name)
self.assertIsInstance(scan_instance_get[1], str)
self.assertEqual(scan_instance_get[1], scan_target)
self.assertIsInstance(scan_instance_get[2], float)
self.assertIsInstance(scan_instance_get[3], float)
self.assertIsInstance(scan_instance_get[4], float)
self.assertIsInstance(scan_instance_get[5], str)
self.assertEqual(scan_instance_get[5], 'CREATED') | Test scanInstanceGet(self, instanceId) | test_scanInstanceGet_should_return_scan_info | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanResultSummary_should_return_a_list(self):
"""
Test scanResultSummary(self, instanceId, by="type")
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_results_summary = sfdb.scanResultSummary(instance_id, "type")
self.assertIsInstance(scan_results_summary, list) | Test scanResultSummary(self, instanceId, by="type") | test_scanResultSummary_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanResultEvent_should_return_a_list(self):
"""
Test scanResultEvent(self, instanceId, eventType='ALL', filterFp=False)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_result_event = sfdb.scanResultEvent(instance_id, "", False)
self.assertIsInstance(scan_result_event, list) | Test scanResultEvent(self, instanceId, eventType='ALL', filterFp=False) | test_scanResultEvent_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanResultEventUnique_should_return_a_list(self):
"""
Test scanResultEventUnique(self, instanceId, eventType='ALL', filterFp=False)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_result_event = sfdb.scanResultEventUnique(instance_id, "", False)
self.assertIsInstance(scan_result_event, list) | Test scanResultEventUnique(self, instanceId, eventType='ALL', filterFp=False) | test_scanResultEventUnique_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanLogs_should_return_a_list(self):
"""
Test scanLogs(self, instanceId, limit=None, fromRowId=None, reverse=False)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_logs = sfdb.scanLogs(instance_id, None, None, None)
self.assertIsInstance(scan_logs, list)
self.assertEqual('TBD', 'TBD') | Test scanLogs(self, instanceId, limit=None, fromRowId=None, reverse=False) | test_scanLogs_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanErrors_should_return_a_list(self):
"""
Test scanErrors(self, instanceId, limit=None)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_instance = sfdb.scanErrors(instance_id)
self.assertIsInstance(scan_instance, list) | Test scanErrors(self, instanceId, limit=None) | test_scanErrors_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanInstanceDelete(self):
"""
Test scanInstanceDelete(self, instanceId)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
sfdb.scanInstanceDelete(instance_id)
self.assertEqual('TBD', 'TBD') | Test scanInstanceDelete(self, instanceId) | test_scanInstanceDelete | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanResultsUpdateFP(self):
"""
Test scanResultsUpdateFP(self, instanceId, resultHashes, fpFlag)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_name = "example scan name"
scan_target = "example scan target"
sfdb.scanInstanceCreate(instance_id, scan_name, scan_target)
result_hashes = None
fp_flag = None
sfdb.scanResultsUpdateFP(instance_id, result_hashes, fp_flag)
self.assertEqual('TBD', 'TBD') | Test scanResultsUpdateFP(self, instanceId, resultHashes, fpFlag) | test_scanResultsUpdateFP | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_configSet_should_set_config_opts(self):
"""
Test configSet(self, optMap=dict())
"""
sfdb = SpiderFootDb(self.default_options, False)
opts = dict()
opts['example'] = 'example non-default config opt'
sfdb.configSet(opts)
config = sfdb.configGet()
self.assertIsInstance(config, dict)
self.assertIn('example', config)
self.assertEqual('TBD', 'TBD') | Test configSet(self, optMap=dict()) | test_configSet_should_set_config_opts | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_configGet_should_return_a_dict(self):
"""
Test configGet(self)
"""
sfdb = SpiderFootDb(self.default_options, False)
config = sfdb.configGet()
self.assertIsInstance(config, dict) | Test configGet(self) | test_configGet_should_return_a_dict | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_configClear_should_clear_config(self):
"""
Test configClear(self)
"""
sfdb = SpiderFootDb(self.default_options, False)
opts = dict()
opts['example'] = 'example non-default config opt'
sfdb.configSet(opts)
config = sfdb.configGet()
self.assertIsInstance(config, dict)
self.assertIn('example', config)
sfdb.configClear()
config = sfdb.configGet()
self.assertIsInstance(config, dict)
self.assertNotIn('example', config) | Test configClear(self) | test_configClear_should_clear_config | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanConfigSet_argument_optMap_of_invalid_type_should_raise_TypeError(self):
"""
Test scanConfigSet(self, id, optMap=dict())
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
invalid_types = [None, ""]
for invalid_type in invalid_types:
with self.subTest(invalid_type=invalid_type):
with self.assertRaises(TypeError):
sfdb.scanConfigSet(instance_id, invalid_type) | Test scanConfigSet(self, id, optMap=dict()) | test_scanConfigSet_argument_optMap_of_invalid_type_should_raise_TypeError | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanConfigGet_should_return_a_dict(self):
"""
Test scanConfigGet(self, instanceId)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_config = sfdb.scanConfigGet(instance_id)
self.assertIsInstance(scan_config, dict) | Test scanConfigGet(self, instanceId) | test_scanConfigGet_should_return_a_dict | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanEventStore_should_store_a_scan_event(self):
"""
Test scanEventStore(self, instanceId, sfEvent, truncateSize=0)
"""
sfdb = SpiderFootDb(self.default_options, False)
event_type = 'ROOT'
event_data = 'example data'
module = ''
source_event = ''
event = SpiderFootEvent(event_type, event_data, module, source_event)
instance_id = "example instance id"
sfdb.scanEventStore(instance_id, event) | Test scanEventStore(self, instanceId, sfEvent, truncateSize=0) | test_scanEventStore_should_store_a_scan_event | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanInstanceList_should_return_a_list(self):
"""
Test scanInstanceList(self)
"""
sfdb = SpiderFootDb(self.default_options, False)
scan_instances = sfdb.scanInstanceList()
self.assertIsInstance(scan_instances, list) | Test scanInstanceList(self) | test_scanInstanceList_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanResultHistory_should_return_a_list(self):
"""
Test scanResultHistory(self, instanceId)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_result_history = sfdb.scanResultHistory(instance_id)
self.assertIsInstance(scan_result_history, list) | Test scanResultHistory(self, instanceId) | test_scanResultHistory_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanElementSourcesDirect_should_return_a_list(self):
"""
Test scanElementSourcesDirect(self, instanceId, elementIdList)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
element_id_list = []
scan_element_sources_direct = sfdb.scanElementSourcesDirect(instance_id, element_id_list)
self.assertIsInstance(scan_element_sources_direct, list)
self.assertEqual('TBD', 'TBD') | Test scanElementSourcesDirect(self, instanceId, elementIdList) | test_scanElementSourcesDirect_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanElementChildrenDirect_should_return_a_list(self):
"""
Test scanElementChildrenDirect(self, instanceId, elementIdList)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_element_children_direct = sfdb.scanElementChildrenDirect(instance_id, list())
self.assertIsInstance(scan_element_children_direct, list)
self.assertEqual('TBD', 'TBD') | Test scanElementChildrenDirect(self, instanceId, elementIdList) | test_scanElementChildrenDirect_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanElementSourcesAll_should_return_a_list(self):
"""
Test scanElementSourcesAll(self, instanceId, childData)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
child_data = ["example child", "example child"]
scan_element_sources_all = sfdb.scanElementSourcesAll(instance_id, child_data)
self.assertIsInstance(scan_element_sources_all, list)
self.assertEqual('TBD', 'TBD') | Test scanElementSourcesAll(self, instanceId, childData) | test_scanElementSourcesAll_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_scanElementChildrenAll_should_return_a_list(self):
"""
Test scanElementChildrenAll(self, instanceId, parentIds)
"""
sfdb = SpiderFootDb(self.default_options, False)
instance_id = "example instance id"
scan_element_children_all = sfdb.scanElementChildrenAll(instance_id, list())
self.assertIsInstance(scan_element_children_all, list)
self.assertEqual('TBD', 'TBD') | Test scanElementChildrenAll(self, instanceId, parentIds) | test_scanElementChildrenAll_should_return_a_list | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootdb.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootdb.py | MIT |
def test_threadPool(self):
"""
Test ThreadPool(sfp, threads=10)
"""
threads = 10
def callback(x, *args, **kwargs):
return (x, args, list(kwargs.items())[0])
iterable = ["a", "b", "c"]
args = ("arg1",)
kwargs = {"kwarg1": "kwarg1"}
expectedOutput = [
("a", ("arg1",), ("kwarg1", "kwarg1")),
("b", ("arg1",), ("kwarg1", "kwarg1")),
("c", ("arg1",), ("kwarg1", "kwarg1"))
]
# Example 1: using map()
with SpiderFootThreadPool(threads) as pool:
map_results = sorted(
list(pool.map(
callback,
iterable,
*args,
saveResult=True,
**kwargs
)),
key=lambda x: x[0]
)
self.assertEqual(map_results, expectedOutput)
# Example 2: using submit()
with SpiderFootThreadPool(threads) as pool:
pool.start()
for i in iterable:
pool.submit(callback, *((i,) + args), saveResult=True, **kwargs)
submit_results = sorted(
list(pool.shutdown()["default"]),
key=lambda x: x[0]
)
self.assertEqual(submit_results, expectedOutput)
# Example 3: using both
threads = 1
iterable2 = ["d", "e", "f"]
expectedOutput2 = [
("d", ("arg1",), ("kwarg1", "kwarg1")),
("e", ("arg1",), ("kwarg1", "kwarg1")),
("f", ("arg1",), ("kwarg1", "kwarg1"))
]
pool = SpiderFootThreadPool(threads)
pool.start()
for i in iterable2:
pool.submit(callback, *((i,) + args), taskName="submitTest", saveResult=True, **kwargs)
map_results = sorted(
list(pool.map(
callback,
iterable,
*args,
taskName="mapTest",
saveResult=True,
**kwargs
)),
key=lambda x: x[0]
)
submit_results = sorted(
list(pool.shutdown()["submitTest"]),
key=lambda x: x[0]
)
self.assertEqual(map_results, expectedOutput)
self.assertEqual(submit_results, expectedOutput2) | Test ThreadPool(sfp, threads=10) | test_threadPool | python | smicallef/spiderfoot | test/unit/spiderfoot/test_spiderfootthreadpool.py | https://github.com/smicallef/spiderfoot/blob/master/test/unit/spiderfoot/test_spiderfootthreadpool.py | MIT |
def test_handleEvent_event_data_raw_rir_data_containing_subdomain_should_return_internet_name_event(self):
"""
Test handleEvent(self, event)
"""
sf = SpiderFoot(self.default_options)
module = sfp_dnsresolve()
module.setup(sf, dict())
target_value = 'spiderfoot.net'
target_type = 'INTERNET_NAME'
target = SpiderFootTarget(target_value, target_type)
module.setTarget(target)
def new_notifyListeners(self, event):
expected = 'INTERNET_NAME'
if str(event.eventType) != expected:
raise Exception(f"{event.eventType} != {expected}")
expected = "www.spiderfoot.net"
if str(event.data) != expected:
raise Exception(f"{event.data} != {expected}")
raise Exception("OK")
module.notifyListeners = new_notifyListeners.__get__(module, sfp_dnsresolve)
event_type = 'ROOT'
event_data = 'example data'
event_module = ''
source_event = ''
evt = SpiderFootEvent(event_type, event_data, event_module, source_event)
event_type = 'RAW_RIR_DATA'
event_data = 'example data www.spiderfoot.net example data'
event_module = 'example module'
source_event = evt
evt = SpiderFootEvent(event_type, event_data, event_module, source_event)
with self.assertRaises(Exception) as cm:
module.handleEvent(evt)
self.assertEqual("OK", str(cm.exception)) | Test handleEvent(self, event) | test_handleEvent_event_data_raw_rir_data_containing_subdomain_should_return_internet_name_event | python | smicallef/spiderfoot | test/integration/modules/test_sfp_dnsresolve.py | https://github.com/smicallef/spiderfoot/blob/master/test/integration/modules/test_sfp_dnsresolve.py | MIT |
def display_data(imgData):
sum = 0
'''
显示100个数(若是一个一个绘制将会非常慢,可以将要画的数字整理好,放到一个矩阵中,显示这个矩阵即可)
- 初始化一个二维数组
- 将每行的数据调整成图像的矩阵,放进二维数组
- 显示即可
'''
pad = 1
display_array = -np.ones((pad+10*(20+pad),pad+10*(20+pad)))
for i in range(10):
for j in range(10):
display_array[pad+i*(20+pad):pad+i*(20+pad)+20,pad+j*(20+pad):pad+j*(20+pad)+20] = (imgData[sum,:].reshape(20,20,order="F")) # order=F指定以列优先,在matlab中是这样的,python中需要指定,默认以行
sum += 1
plt.imshow(display_array,cmap='gray') #显示灰度图像
plt.axis('off')
plt.show() | 显示100个数(若是一个一个绘制将会非常慢,可以将要画的数字整理好,放到一个矩阵中,显示这个矩阵即可)
- 初始化一个二维数组
- 将每行的数据调整成图像的矩阵,放进二维数组
- 显示即可 | display_data | python | lawlite19/MachineLearning_Python | LogisticRegression/LogisticRegression_OneVsAll.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/LogisticRegression/LogisticRegression_OneVsAll.py | MIT |
def oneVsAll(X,y,num_labels,Lambda):
# 初始化变量
m,n = X.shape
all_theta = np.zeros((n+1,num_labels)) # 每一列对应相应分类的theta,共10列
X = np.hstack((np.ones((m,1)),X)) # X前补上一列1的偏置bias
class_y = np.zeros((m,num_labels)) # 数据的y对应0-9,需要映射为0/1的关系
initial_theta = np.zeros((n+1,1)) # 初始化一个分类的theta
# 映射y
for i in range(num_labels):
class_y[:,i] = np.int32(y==i).reshape(1,-1) # 注意reshape(1,-1)才可以赋值
#np.savetxt("class_y.csv", class_y[0:600,:], delimiter=',')
'''遍历每个分类,计算对应的theta值'''
for i in range(num_labels):
#optimize.fmin_cg
result = optimize.fmin_bfgs(costFunction, initial_theta, fprime=gradient, args=(X,class_y[:,i],Lambda)) # 调用梯度下降的优化方法
all_theta[:,i] = result.reshape(1,-1) # 放入all_theta中
all_theta = np.transpose(all_theta)
return all_theta | 遍历每个分类,计算对应的theta值 | oneVsAll | python | lawlite19/MachineLearning_Python | LogisticRegression/LogisticRegression_OneVsAll.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/LogisticRegression/LogisticRegression_OneVsAll.py | MIT |
def predict_oneVsAll(all_theta,X):
m = X.shape[0]
num_labels = all_theta.shape[0]
p = np.zeros((m,1))
X = np.hstack((np.ones((m,1)),X)) #在X最前面加一列1
h = sigmoid(np.dot(X,np.transpose(all_theta))) #预测
'''
返回h中每一行最大值所在的列号
- np.max(h, axis=1)返回h中每一行的最大值(是某个数字的最大概率)
- 最后where找到的最大概率所在的列号(列号即是对应的数字)
'''
p = np.array(np.where(h[0,:] == np.max(h, axis=1)[0]))
for i in np.arange(1, m):
t = np.array(np.where(h[i,:] == np.max(h, axis=1)[i]))
p = np.vstack((p,t))
return p | 返回h中每一行最大值所在的列号
- np.max(h, axis=1)返回h中每一行的最大值(是某个数字的最大概率)
- 最后where找到的最大概率所在的列号(列号即是对应的数字) | predict_oneVsAll | python | lawlite19/MachineLearning_Python | LogisticRegression/LogisticRegression_OneVsAll.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/LogisticRegression/LogisticRegression_OneVsAll.py | MIT |
def LogisticRegression():
data = loadtxtAndcsv_data("data2.txt", ",", np.float64)
X = data[:,0:-1]
y = data[:,-1]
plot_data(X,y) # 作图
X = mapFeature(X[:,0],X[:,1]) #映射为多项式
initial_theta = np.zeros((X.shape[1],1))#初始化theta
initial_lambda = 0.1 #初始化正则化系数,一般取0.01,0.1,1.....
J = costFunction(initial_theta,X,y,initial_lambda) #计算一下给定初始化的theta和lambda求出的代价J
print(J) #输出一下计算的值,应该为0.693147
#result = optimize.fmin(costFunction, initial_theta, args=(X,y,initial_lambda)) #直接使用最小化的方法,效果不好
'''调用scipy中的优化算法fmin_bfgs(拟牛顿法Broyden-Fletcher-Goldfarb-Shanno)
- costFunction是自己实现的一个求代价的函数,
- initial_theta表示初始化的值,
- fprime指定costFunction的梯度
- args是其余测参数,以元组的形式传入,最后会将最小化costFunction的theta返回
'''
result = optimize.fmin_bfgs(costFunction, initial_theta, fprime=gradient, args=(X,y,initial_lambda))
p = predict(X, result) #预测
print(u'在训练集上的准确度为%f%%'%np.mean(np.float64(p==y)*100)) # 与真实值比较,p==y返回True,转化为float
X = data[:,0:-1]
y = data[:,-1]
plotDecisionBoundary(result,X,y) #画决策边界 | 调用scipy中的优化算法fmin_bfgs(拟牛顿法Broyden-Fletcher-Goldfarb-Shanno)
- costFunction是自己实现的一个求代价的函数,
- initial_theta表示初始化的值,
- fprime指定costFunction的梯度
- args是其余测参数,以元组的形式传入,最后会将最小化costFunction的theta返回 | LogisticRegression | python | lawlite19/MachineLearning_Python | LogisticRegression/LogisticRegression.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/LogisticRegression/LogisticRegression.py | MIT |
def mapFeature(X1,X2):
degree = 2; # 映射的最高次方
out = np.ones((X1.shape[0],1)) # 映射后的结果数组(取代X)
'''
这里以degree=2为例,映射为1,x1,x2,x1^2,x1,x2,x2^2
'''
for i in np.arange(1,degree+1):
for j in range(i+1):
temp = X1**(i-j)*(X2**j) #矩阵直接乘相当于matlab中的点乘.*
out = np.hstack((out, temp.reshape(-1,1)))
return out | 这里以degree=2为例,映射为1,x1,x2,x1^2,x1,x2,x2^2 | mapFeature | python | lawlite19/MachineLearning_Python | LogisticRegression/LogisticRegression.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/LogisticRegression/LogisticRegression.py | MIT |
def anomalyDetection_example():
'''加载并显示数据'''
data = spio.loadmat('data1.mat')
X = data['X']
plt = display_2d_data(X, 'bx')
plt.title("origin data")
plt.show()
'''多元高斯分布函数,并可视化拟合的边界'''
mu,sigma2 = estimateGaussian(X) # 参数估计(求均值和方差)
#print (mu,sigma2)
p = multivariateGaussian(X,mu,sigma2) # 多元高斯分布函数
#print (p)
visualizeFit(X,mu,sigma2) # 显示图像
'''选择异常点(在交叉验证CV上训练得到最好的epsilon)'''
Xval = data['Xval']
yval = data['yval'] # y=1代表异常
pval = multivariateGaussian(Xval, mu, sigma2) # 计算CV上的概率密度值
epsilon,F1 = selectThreshold(yval,pval) # 选择最优的epsilon临界值
print(u'在CV上得到的最好的epsilon是:%e'%epsilon)
print(u'对应的F1Score值为:%f'%F1)
outliers = np.where(p<epsilon) # 找到小于临界值的异常点,并作图
plt.plot(X[outliers,0],X[outliers,1],'o',markeredgecolor='r',markerfacecolor='w',markersize=10.)
plt = display_2d_data(X, 'bx')
plt.show() | 加载并显示数据 | anomalyDetection_example | python | lawlite19/MachineLearning_Python | AnomalyDetection/AnomalyDetection.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/AnomalyDetection/AnomalyDetection.py | MIT |
def multivariateGaussian(X,mu,Sigma2):
k = len(mu)
if (Sigma2.shape[0]>1):
Sigma2 = np.diag(Sigma2)
'''多元高斯分布函数'''
X = X-mu
argu = (2*np.pi)**(-k/2)*np.linalg.det(Sigma2)**(-0.5)
p = argu*np.exp(-0.5*np.sum(np.dot(X,np.linalg.inv(Sigma2))*X,axis=1)) # axis表示每行
return p | 多元高斯分布函数 | multivariateGaussian | python | lawlite19/MachineLearning_Python | AnomalyDetection/AnomalyDetection.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/AnomalyDetection/AnomalyDetection.py | MIT |
def selectThreshold(yval,pval):
'''初始化所需变量'''
bestEpsilon = 0.
bestF1 = 0.
F1 = 0.
step = (np.max(pval)-np.min(pval))/1000
'''计算'''
for epsilon in np.arange(np.min(pval),np.max(pval),step):
cvPrecision = pval<epsilon
tp = np.sum((cvPrecision == 1) & (yval == 1).ravel()).astype(float) # sum求和是int型的,需要转为float
fp = np.sum((cvPrecision == 1) & (yval == 0).ravel()).astype(float)
fn = np.sum((cvPrecision == 0) & (yval == 1).ravel()).astype(float)
precision = tp/(tp+fp) # 精准度
recision = tp/(tp+fn) # 召回率
F1 = (2*precision*recision)/(precision+recision) # F1Score计算公式
if F1 > bestF1: # 修改最优的F1 Score
bestF1 = F1
bestEpsilon = epsilon
return bestEpsilon,bestF1 | 初始化所需变量 | selectThreshold | python | lawlite19/MachineLearning_Python | AnomalyDetection/AnomalyDetection.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/AnomalyDetection/AnomalyDetection.py | MIT |
def SVM():
'''data1——线性分类'''
data1 = spio.loadmat('data1.mat')
X = data1['X']
y = data1['y']
y = np.ravel(y)
plot_data(X, y)
model = svm.SVC(C=1.0, kernel='linear').fit(X, y) # 指定核函数为线性核函数
plot_decisionBoundary(X, y, model) # 画决策边界
'''data2——非线性分类'''
data2 = spio.loadmat('data2.mat')
X = data2['X']
y = data2['y']
y = np.ravel(y)
plt = plot_data(X, y)
plt.show()
model = svm.SVC(gamma=100).fit(X, y) # gamma为核函数的系数,值越大拟合的越好
plot_decisionBoundary(X, y, model, class_='notLinear') # 画决策边界 | data1——线性分类 | SVM | python | lawlite19/MachineLearning_Python | SVM/SVM_scikit-learn.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/SVM/SVM_scikit-learn.py | MIT |
def PCA_2d_example():
'''加载数据并作图'''
data = spio.loadmat('data.mat')
X = data['X']
plt = plot_data_2d(X,'bo')
plt.axis('square')
plt.title('original data')
plt.show()
'''归一化数据并作图'''
scaler = StandardScaler()
scaler.fit(X)
x_train = scaler.transform(X)
plot_data_2d(x_train, 'bo')
plt.axis('square')
plt.title('scaler data')
plt.show()
'''拟合数据'''
K=1 # 要降的维度
model = pca.PCA(n_components=K).fit(x_train) # 拟合数据,n_components定义要降的维度
Z = model.transform(x_train) # transform就会执行降维操作
'''数据恢复并作图'''
Ureduce = model.components_ # 得到降维用的Ureduce
x_rec = np.dot(Z,Ureduce) # 数据恢复
plot_data_2d(x_rec,'bo')
plt.plot()
plt.axis('square')
plt.title('recover data')
plt.show() | 加载数据并作图 | PCA_2d_example | python | lawlite19/MachineLearning_Python | PCA/PCA_scikit-learn.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/PCA/PCA_scikit-learn.py | MIT |
def PCA_face_example():
'''加载数据并显示'''
image_data = spio.loadmat('data_faces.mat')
X = image_data['X']
display_imageData(X[0:100,:]) # 显示100个最初图像
'''归一化数据'''
scaler = StandardScaler()
scaler.fit(X)
x_train = scaler.transform(X)
'''拟合模型'''
K=100
model = pca.PCA(n_components=K).fit(x_train)
Z = model.transform(x_train)
Ureduce = model.components_
display_imageData(Ureduce[0:36,:]) # 可视化部分U数据
x_rec = np.dot(Z,Ureduce)
display_imageData(x_rec[0:100,:]) # 显示恢复的数据 | 加载数据并显示 | PCA_face_example | python | lawlite19/MachineLearning_Python | PCA/PCA_scikit-learn.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/PCA/PCA_scikit-learn.py | MIT |
def display_imageData(imgData):
sum = 0
'''
显示100个数(若是一个一个绘制将会非常慢,可以将要画的图片整理好,放到一个矩阵中,显示这个矩阵即可)
- 初始化一个二维数组
- 将每行的数据调整成图像的矩阵,放进二维数组
- 显示即可
'''
m,n = imgData.shape
width = np.int32(np.round(np.sqrt(n)))
height = np.int32(n/width);
rows_count = np.int32(np.floor(np.sqrt(m)))
cols_count = np.int32(np.ceil(m/rows_count))
pad = 1
display_array = -np.ones((pad+rows_count*(height+pad),pad+cols_count*(width+pad)))
for i in range(rows_count):
for j in range(cols_count):
max_val = np.max(np.abs(imgData[sum,:]))
display_array[pad+i*(height+pad):pad+i*(height+pad)+height,pad+j*(width+pad):pad+j*(width+pad)+width] = imgData[sum,:].reshape(height,width,order="F")/max_val # order=F指定以列优先,在matlab中是这样的,python中需要指定,默认以行
sum += 1
plt.imshow(display_array,cmap='gray') #显示灰度图像
plt.axis('off')
plt.show() | 显示100个数(若是一个一个绘制将会非常慢,可以将要画的图片整理好,放到一个矩阵中,显示这个矩阵即可)
- 初始化一个二维数组
- 将每行的数据调整成图像的矩阵,放进二维数组
- 显示即可 | display_imageData | python | lawlite19/MachineLearning_Python | PCA/PCA_scikit-learn.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/PCA/PCA_scikit-learn.py | MIT |
def PCA_2D():
data_2d = spio.loadmat("data.mat")
X = data_2d['X']
m = X.shape[0]
plt = plot_data_2d(X,'bo') # 显示二维的数据
plt.show()
X_copy = X.copy()
X_norm,mu,sigma = featureNormalize(X_copy) # 归一化数据
#plot_data_2d(X_norm) # 显示归一化后的数据
#plt.show()
Sigma = np.dot(np.transpose(X_norm),X_norm)/m # 求Sigma
U,S,V = np.linalg.svd(Sigma) # 求Sigma的奇异值分解
plt = plot_data_2d(X,'bo') # 显示原本数据
drawline(plt, mu, mu+S[0]*(U[:,0]), 'r-') # 线,为投影的方向
plt.axis('square')
plt.show()
K = 1 # 定义降维多少维(本来是2维的,这里降维1维)
'''投影之后数据(降维之后)'''
Z = projectData(X_norm,U,K) # 投影
'''恢复数据'''
X_rec = recoverData(Z,U,K) # 恢复
'''作图-----原数据与恢复的数据'''
plt = plot_data_2d(X_norm,'bo')
plot_data_2d(X_rec,'ro')
for i in range(X_norm.shape[0]):
drawline(plt, X_norm[i,:], X_rec[i,:], '--k')
plt.axis('square')
plt.show() | 投影之后数据(降维之后) | PCA_2D | python | lawlite19/MachineLearning_Python | PCA/PCA.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/PCA/PCA.py | MIT |
def featureNormalize(X):
'''(每一个数据-当前列的均值)/当前列的标准差'''
n = X.shape[1]
mu = np.zeros((1,n));
sigma = np.zeros((1,n))
mu = np.mean(X,axis=0) # axis=0表示列
sigma = np.std(X,axis=0)
for i in range(n):
X[:,i] = (X[:,i]-mu[i])/sigma[i]
return X,mu,sigma | (每一个数据-当前列的均值)/当前列的标准差 | featureNormalize | python | lawlite19/MachineLearning_Python | PCA/PCA.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/PCA/PCA.py | MIT |
def KMeans():
'''二维数据聚类过程演示'''
print(u'聚类过程展示...\n')
data = spio.loadmat("data.mat")
X = data['X']
K = 3 # 总类数
initial_centroids = np.array([[3,3],[6,2],[8,5]]) # 初始化类中心
max_iters = 10
runKMeans(X,initial_centroids,max_iters,True) # 执行K-Means聚类算法
'''
图片压缩
'''
print(u'K-Means压缩图片\n')
img_data = misc.imread("bird.png") # 读取图片像素数据
img_data = img_data/255.0 # 像素值映射到0-1
img_size = img_data.shape
X = img_data.reshape(img_size[0]*img_size[1],3) # 调整为N*3的矩阵,N是所有像素点个数
K = 16
max_iters = 5
initial_centroids = kMeansInitCentroids(X,K)
centroids,idx = runKMeans(X, initial_centroids, max_iters, False)
print(u'\nK-Means运行结束\n')
print(u'\n压缩图片...\n')
idx = findClosestCentroids(X, centroids)
X_recovered = centroids[idx,:]
X_recovered = X_recovered.reshape(img_size[0],img_size[1],3)
print(u'绘制图片...\n')
plt.subplot(1,2,1)
plt.imshow(img_data)
plt.title(u"原先图片",fontproperties=font)
plt.subplot(1,2,2)
plt.imshow(X_recovered)
plt.title(u"压缩图像",fontproperties=font)
plt.show()
print(u'运行结束!') | 二维数据聚类过程演示 | KMeans | python | lawlite19/MachineLearning_Python | K-Means/K-Menas.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/K-Means/K-Menas.py | MIT |
def findClosestCentroids(X,initial_centroids):
m = X.shape[0] # 数据条数
K = initial_centroids.shape[0] # 类的总数
dis = np.zeros((m,K)) # 存储计算每个点分别到K个类的距离
idx = np.zeros((m,1)) # 要返回的每条数据属于哪个类
'''计算每个点到每个类中心的距离'''
for i in range(m):
for j in range(K):
dis[i,j] = np.dot((X[i,:]-initial_centroids[j,:]).reshape(1,-1),(X[i,:]-initial_centroids[j,:]).reshape(-1,1))
'''返回dis每一行的最小值对应的列号,即为对应的类别
- np.min(dis, axis=1)返回每一行的最小值
- np.where(dis == np.min(dis, axis=1).reshape(-1,1)) 返回对应最小值的坐标
- 注意:可能最小值对应的坐标有多个,where都会找出来,所以返回时返回前m个需要的即可(因为对于多个最小值,属于哪个类别都可以)
'''
dummy,idx = np.where(dis == np.min(dis, axis=1).reshape(-1,1))
return idx[0:dis.shape[0]] # 注意截取一下 | 计算每个点到每个类中心的距离 | findClosestCentroids | python | lawlite19/MachineLearning_Python | K-Means/K-Menas.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/K-Means/K-Menas.py | MIT |
def neuralNetwork(input_layer_size,hidden_layer_size,out_put_layer):
data_img = loadmat_data("data_digits.mat")
X = data_img['X']
y = data_img['y']
'''scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)'''
m,n = X.shape
"""digits = datasets.load_digits()
X = digits.data
y = digits.target
m,n = X.shape
scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X)"""
## 随机显示几行数据
rand_indices = [t for t in [np.random.randint(x-x, m) for x in range(100)]] # 生成100个0-m的随机数
display_data(X[rand_indices,:]) # 显示100个数字
#nn_params = np.vstack((Theta1.reshape(-1,1),Theta2.reshape(-1,1)))
Lambda = 1
initial_Theta1 = randInitializeWeights(input_layer_size,hidden_layer_size);
initial_Theta2 = randInitializeWeights(hidden_layer_size,out_put_layer)
initial_nn_params = np.vstack((initial_Theta1.reshape(-1,1),initial_Theta2.reshape(-1,1))) #展开theta
#np.savetxt("testTheta.csv",initial_nn_params,delimiter=",")
start = time.time()
result = optimize.fmin_cg(nnCostFunction, initial_nn_params, fprime=nnGradient, args=(input_layer_size,hidden_layer_size,out_put_layer,X,y,Lambda), maxiter=100)
print (u'执行时间:',time.time()-start)
print (result)
'''可视化 Theta1'''
length = result.shape[0]
Theta1 = result[0:hidden_layer_size*(input_layer_size+1)].reshape(hidden_layer_size,input_layer_size+1)
Theta2 = result[hidden_layer_size*(input_layer_size+1):length].reshape(out_put_layer,hidden_layer_size+1)
display_data(Theta1[:,1:length])
display_data(Theta2[:,1:length])
'''预测'''
p = predict(Theta1,Theta2,X)
print (u"预测准确度为:%f%%"%np.mean(np.float64(p == y.reshape(-1,1))*100))
res = np.hstack((p,y.reshape(-1,1)))
np.savetxt("predict.csv", res, delimiter=',') | scaler = StandardScaler()
scaler.fit(X)
X = scaler.transform(X) | neuralNetwork | python | lawlite19/MachineLearning_Python | NeuralNetwok/NeuralNetwork.py | https://github.com/lawlite19/MachineLearning_Python/blob/master/NeuralNetwok/NeuralNetwork.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.