hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
qsc_code_num_words_quality_signal
int64
qsc_code_num_chars_quality_signal
float64
qsc_code_mean_word_length_quality_signal
float64
qsc_code_frac_words_unique_quality_signal
float64
qsc_code_frac_chars_top_2grams_quality_signal
float64
qsc_code_frac_chars_top_3grams_quality_signal
float64
qsc_code_frac_chars_top_4grams_quality_signal
float64
qsc_code_frac_chars_dupe_5grams_quality_signal
float64
qsc_code_frac_chars_dupe_6grams_quality_signal
float64
qsc_code_frac_chars_dupe_7grams_quality_signal
float64
qsc_code_frac_chars_dupe_8grams_quality_signal
float64
qsc_code_frac_chars_dupe_9grams_quality_signal
float64
qsc_code_frac_chars_dupe_10grams_quality_signal
float64
qsc_code_frac_chars_replacement_symbols_quality_signal
float64
qsc_code_frac_chars_digital_quality_signal
float64
qsc_code_frac_chars_whitespace_quality_signal
float64
qsc_code_size_file_byte_quality_signal
float64
qsc_code_num_lines_quality_signal
float64
qsc_code_num_chars_line_max_quality_signal
float64
qsc_code_num_chars_line_mean_quality_signal
float64
qsc_code_frac_chars_alphabet_quality_signal
float64
qsc_code_frac_chars_comments_quality_signal
float64
qsc_code_cate_xml_start_quality_signal
float64
qsc_code_frac_lines_dupe_lines_quality_signal
float64
qsc_code_cate_autogen_quality_signal
float64
qsc_code_frac_lines_long_string_quality_signal
float64
qsc_code_frac_chars_string_length_quality_signal
float64
qsc_code_frac_chars_long_word_length_quality_signal
float64
qsc_code_frac_lines_string_concat_quality_signal
float64
qsc_code_cate_encoded_data_quality_signal
float64
qsc_code_frac_chars_hex_words_quality_signal
float64
qsc_code_frac_lines_prompt_comments_quality_signal
float64
qsc_code_frac_lines_assert_quality_signal
float64
qsc_codepython_cate_ast_quality_signal
float64
qsc_codepython_frac_lines_func_ratio_quality_signal
float64
qsc_codepython_cate_var_zero_quality_signal
bool
qsc_codepython_frac_lines_pass_quality_signal
float64
qsc_codepython_frac_lines_import_quality_signal
float64
qsc_codepython_frac_lines_simplefunc_quality_signal
float64
qsc_codepython_score_lines_no_logic_quality_signal
float64
qsc_codepython_frac_lines_print_quality_signal
float64
qsc_code_num_words
int64
qsc_code_num_chars
int64
qsc_code_mean_word_length
int64
qsc_code_frac_words_unique
null
qsc_code_frac_chars_top_2grams
int64
qsc_code_frac_chars_top_3grams
int64
qsc_code_frac_chars_top_4grams
int64
qsc_code_frac_chars_dupe_5grams
int64
qsc_code_frac_chars_dupe_6grams
int64
qsc_code_frac_chars_dupe_7grams
int64
qsc_code_frac_chars_dupe_8grams
int64
qsc_code_frac_chars_dupe_9grams
int64
qsc_code_frac_chars_dupe_10grams
int64
qsc_code_frac_chars_replacement_symbols
int64
qsc_code_frac_chars_digital
int64
qsc_code_frac_chars_whitespace
int64
qsc_code_size_file_byte
int64
qsc_code_num_lines
int64
qsc_code_num_chars_line_max
int64
qsc_code_num_chars_line_mean
int64
qsc_code_frac_chars_alphabet
int64
qsc_code_frac_chars_comments
int64
qsc_code_cate_xml_start
int64
qsc_code_frac_lines_dupe_lines
int64
qsc_code_cate_autogen
int64
qsc_code_frac_lines_long_string
int64
qsc_code_frac_chars_string_length
int64
qsc_code_frac_chars_long_word_length
int64
qsc_code_frac_lines_string_concat
null
qsc_code_cate_encoded_data
int64
qsc_code_frac_chars_hex_words
int64
qsc_code_frac_lines_prompt_comments
int64
qsc_code_frac_lines_assert
int64
qsc_codepython_cate_ast
int64
qsc_codepython_frac_lines_func_ratio
int64
qsc_codepython_cate_var_zero
int64
qsc_codepython_frac_lines_pass
int64
qsc_codepython_frac_lines_import
int64
qsc_codepython_frac_lines_simplefunc
int64
qsc_codepython_score_lines_no_logic
int64
qsc_codepython_frac_lines_print
int64
effective
string
hits
int64
c61623b37bddc297ff4efcaa0c5fed293a59e6f0
12,000
py
Python
model/tests.py
nosnhojn/poser
9585459377392b2662dcc63174d465ba5a7581f4
[ "BSD-3-Clause" ]
1
2016-05-11T18:37:56.000Z
2016-05-11T18:37:56.000Z
model/tests.py
nosnhojn/poser
9585459377392b2662dcc63174d465ba5a7581f4
[ "BSD-3-Clause" ]
null
null
null
model/tests.py
nosnhojn/poser
9585459377392b2662dcc63174d465ba5a7581f4
[ "BSD-3-Clause" ]
null
null
null
import unittest from model import Cell, Module, OutputType, CellType, Mux import random class CellTests (unittest.TestCase): def setUp(self): self.c = Cell() def tearDown(self): pass def testAsyncOutputFalseWhenBothInputsFalse(self): self.c.driveInputs([False, False]) self.assertFalse(self.c.asyncOutput()) def testAsyncOutputFalseWhenOneInputFalse(self): self.c.driveInputs([True, False]) self.assertFalse(self.c.asyncOutput()) def testAsyncOutputTrueWhenBothInputsTrue(self): self.c.driveInputs([True, True]) self.assertTrue(self.c.asyncOutput()) def testSyncOutputResetsToFalse(self): self.assertFalse(self.c.syncOutput()) def testSyncOutputFalseWhenBothInputsFalse(self): self.c.driveInputs([False, False]) self.c.clk() self.assertFalse(self.c.syncOutput()) def testSyncOutputTrueWhenBothInputsTrue(self): self.c.driveInputs([True, True]) self.c.clk() self.assertTrue(self.c.syncOutput()) def testSyncOutputUpdatesWith2ndClk(self): self.c.driveInputs([True, True]) self.c.clk() self.c.driveInputs([False, False]) self.c.clk() self.assertFalse(self.c.syncOutput()) def testSyncOutputHolds(self): self.c.driveInputs([True, True]) self.c.clk() self.c.clk() self.assertTrue(self.c.syncOutput()) def testAsyncStableWhenFalse(self): self.c.driveInputs([False, False]) self.c.driveInputs([False, False]) self.assertTrue(self.c.isStable()) def testAsyncStableWhenBothTrue(self): self.c.driveInputs([True, True]) self.c.driveInputs([True, True]) self.assertTrue(self.c.isStable()) def testAsyncStableWhenBothFalse(self): self.c.driveInputs([False, False]) self.c.driveInputs([False, False]) self.assertTrue(self.c.isStable()) def testAsyncNotStableWhenAChanges(self): self.c.driveInputs([True, True]) self.c.driveInputs([False, True]) self.assertFalse(self.c.isStable()) def testAsyncNotStableWhenBChanges(self): self.c.driveInputs([True, True]) self.c.clk() self.c.driveInputs([True, False]) self.c.clk() self.assertFalse(self.c.isStable()) def testCellCanBeOr(self): self.c.setOperator(CellType._or) self.c.driveInputs([False, True]) self.assertTrue(self.c.asyncOutput()) def testCellCanBeXor(self): self.c.setOperator(CellType._xor) self.c.driveInputs([True, True]) self.assertFalse(self.c.asyncOutput()) self.c.driveInputs([False, False]) self.assertFalse(self.c.asyncOutput()) self.c.driveInputs([False, True]) self.assertTrue(self.c.asyncOutput()) def testSetForAsyncOutput(self): self.c.setOutputType(OutputType.async) self.c.driveInputs([True, True]) self.assertTrue(self.c.output()) def testSetForSyncOutput(self): self.c.setOutputType(OutputType.sync) self.c.driveInputs([True, True]) self.assertFalse(self.c.output()) self.c.clk() self.assertTrue(self.c.output()) def testGetOutputType(self): self.c.setOutputType(OutputType.sync) self.assertTrue(self.c.getOutputType() == OutputType.sync) def testCellHistory(self): self.c.setOutputType(OutputType.sync) self.c.driveInputs([True, True]) for i in range(50): if i == 49: self.c.driveInputs([False, False]) self.c.clk() self.c.output() self.assertEqual(len(self.c.cellHistory()), 50) self.assertEqual(self.c.cellHistory(), [True] * 49 + [False]) def testCellHistoryFixed(self): self.c.setOutputType(OutputType.sync) self.c.driveInputs([True, True]) for i in range(50): self.c.clk() self.c.output() self.assertTrue(self.c.cellHistoryFixed()) def testCellHistoryNotFixed(self): self.c.setOutputType(OutputType.sync) self.c.driveInputs([True, True]) self.c.clk() self.c.output() self.c.driveInputs([False, True]) self.c.clk() self.c.output() self.assertFalse(self.c.cellHistoryFixed()) def testNoCellHistoryForAsync(self): self.c.setOutputType(OutputType.async) self.c.driveInputs([True, True]) self.c.output() self.c.driveInputs([False, True]) self.c.output() self.assertFalse(self.c.cellHistoryFixed()) class ModuleTests (unittest.TestCase): def setUp(self): self.m = Module() def tearDown(self): pass def depth(self): return len(self.m.cells) def width(self): return len(self.m.cells[0]) def createGridAndTieCell0Input(self, wIn, wOut, width, depth=1, initValForCell0 = False): self.m.createGrid(wIn, wOut, width, depth) self.m.tieCell0([initValForCell0]) def testInit4x1(self): self.createGridAndTieCell0Input(4, 4, 4, 1) self.assertTrue(self.depth() == 1) self.assertTrue(self.width() == 4) def testInitNxN(self): self.createGridAndTieCell0Input(7, 7, 7, 6) self.assertTrue(self.depth() == 6) self.assertTrue(self.width() == 7) def test2x1AndTiedLow(self): self.createGridAndTieCell0Input(2, 2, 2, 1) self.m.driveInputs([True, True]) self.assertEqual(self.m.sampleOutputs(), [False, False]) def test2x1AndTiedHigh(self): self.createGridAndTieCell0Input(2, 2, 2, 1, True) self.m.driveInputs([True, True]) self.assertEqual(self.m.sampleOutputs(), [True, True]) def test3x1AndTiedHigh(self): self.createGridAndTieCell0Input(3, 3, 3, 1, True) self.m.driveInputs([True, True, False]) self.assertEqual(self.m.sampleOutputs(), [True, True, False]) def test2x2AndTiedHigh(self): self.createGridAndTieCell0Input(2, 2, 2, 2, True) self.m.driveInputs([True, True]) self.assertEqual(self.m.sampleOutputs(), [True, True]) self.m.driveInputs([True, False]) self.assertEqual(self.m.sampleOutputs(), [False, False]) def test3x2AndTiedHigh(self): self.createGridAndTieCell0Input(3, 3, 3, 2, True) self.m.driveInputs([True, True, True]) self.assertEqual(self.m.sampleOutputs(), [True, True, True]) self.m.driveInputs([True, False, True]) self.assertEqual(self.m.sampleOutputs(), [False, False, False]) def testFixNumberOfFlopsTo0(self): self.createGridAndTieCell0Input(25, 25, 25, 14, True) self.m.setNumFlops(0) self.assertTrue(self.m.getNumFlops() == 0) def testFixNumberOfFlopsToLtWidth(self): self.createGridAndTieCell0Input(25, 25, 25, 14, True) self.m.setNumFlops(17) self.assertTrue(self.m.getNumFlops() == 17) def testFixNumberOfFlopsToGtWidth(self): self.createGridAndTieCell0Input(25, 25, 25, 14, True) self.m.setNumFlops(28) self.assertTrue(self.m.getNumFlops() == 28) def testFixNumberOfFlopsToMax(self): self.createGridAndTieCell0Input(25, 25, 25, 14, True) self.m.setNumFlops(25 * 14) self.assertTrue(self.m.getNumFlops() == (25 * 14)) def test2x1FloppedAndTiedHigh(self): self.createGridAndTieCell0Input(2, 2, 2, 1, True) self.m.setNumFlops(2) self.m.driveInputs([True, True]) self.m.clk() self.assertEqual(self.m.sampleOutputs(), [True, False]) self.m.clk() self.assertEqual(self.m.sampleOutputs(), [True, True]) def testOutputMuxOnlyExistsWhenOutputSmallerThanInputWidth(self): self.createGridAndTieCell0Input(2, 2, 2) self.assertEqual(self.m.outputMux, None) def testOutputMuxForMoreInputsThanOutputs(self): self.createGridAndTieCell0Input(2, 1, 2) self.assertNotEqual(self.m.outputMux, None) def testOutputSizeFor2Inputs1Output(self): self.createGridAndTieCell0Input(2, 1, 2) self.m.driveInputs([True, True]) self.assertEqual(len(self.m.sampleOutputs()), 1) def testOutputFor2Inputs1Output(self): self.createGridAndTieCell0Input(2, 1, 2, 1, True) self.m.driveInputs([True, True]) self.assertEqual(self.m.sampleOutputs(), [ True ]) def testOutputFor3Inputs2Output(self): self.createGridAndTieCell0Input(3, 2, 3, 1, True) self.m.driveInputs([True, True, False]) self.assertEqual(self.m.sampleOutputs(), [ True, False ]) def testOutputFor4Inputs3Output(self): self.createGridAndTieCell0Input(4, 3, 4, 1, True) self.m.driveInputs([True, True, True, False]) self.assertEqual(self.m.sampleOutputs(), [ True, True, False ]) def testOutputFor5Inputs4Output(self): self.createGridAndTieCell0Input(5, 4, 5, 1, True) self.m.driveInputs([True, True, True, False, False]) self.assertEqual(self.m.sampleOutputs(), [ True, True, False, False ]) def testOutputFor8Inputs5Output(self): self.createGridAndTieCell0Input(8, 5, 8, 1, True) self.m.driveInputs([True] * 6 + [False, False]) self.assertEqual(self.m.sampleOutputs(), [ True, True, True, False, False ]) def testModuleHasFixedCells(self): self.createGridAndTieCell0Input(2, 2, 2) self.m.setNumFlops(2) self.m.driveInputs([True] * 2) self.m.clk() self.m.sampleOutputs() self.m.clk() self.m.sampleOutputs() self.assertTrue(self.m.moduleHasFixedCells()) def testModuleHasNoFixedCells(self): self.createGridAndTieCell0Input(2, 2, 2, 1, True) self.m.cells[0][1].setOutputType(OutputType.sync) self.m.driveInputs([True] * 2) self.m.clk() self.m.sampleOutputs() self.m.driveInputs([False] * 2) self.m.clk() self.m.sampleOutputs() self.assertFalse(self.m.moduleHasFixedCells()) def testOutputHistory(self): self.createGridAndTieCell0Input(2, 2, 2, 1, True) self.m.driveInputs([True, True]) self.m.sampleOutputs() self.m.sampleOutputs() self.m.sampleOutputs() self.assertEqual(len(self.m.outputHistory()), 3) self.assertEqual(self.m.outputHistory(), [ [True, True], [True, True], [True, True] ]) self.assertTrue(self.m.outputsFixed()) def testOutputsNotFixed(self): self.createGridAndTieCell0Input(2, 2, 2, 1, True) self.m.driveInputs([True, True]) self.m.sampleOutputs() self.m.driveInputs([False, False]) self.m.sampleOutputs() self.assertFalse(self.m.outputsFixed()) def testOutputFor1Input2Outputs(self): self.createGridAndTieCell0Input(1, 2, 2, 1, True) self.m.driveInputs([True]) self.assertEqual(self.m.sampleOutputs(), [ True, True ]) def testOutputFor2Input4Outputs(self): self.createGridAndTieCell0Input(2, 4, 4, 1, True) self.m.driveInputs([True, True]) self.assertEqual(self.m.sampleOutputs(), [ True, True ] * 2) def testOutputForLargerGridWidth(self): self.createGridAndTieCell0Input(2, 4, 6, 1, True) self.m.driveInputs([True, True]) self.assertEqual(self.m.sampleOutputs(), [ True, True ] * 2) class MuxTests (unittest.TestCase): def setUp(self): self.m = Mux() def tearDown(self): pass def testInputSelect2InputSelect0(self): self.m.driveInputs([False, True]) self.assertEqual(self.m.inputSelect(), 0) def testInputSelect2InputSelect1(self): self.m.driveInputs([True, True]) self.assertEqual(self.m.inputSelect(), 1) def testInputSelect3InputSelect0(self): self.m.driveInputs([False, False, True]) self.assertEqual(self.m.inputSelect(), 0) def testInputSelect3InputSelect1(self): self.m.driveInputs([True, False, True]) self.assertEqual(self.m.inputSelect(), 1) def testInputSelect3InputSelect2(self): self.m.driveInputs([False, True, True]) self.assertEqual(self.m.inputSelect(), 2) def testInputSelect3InputSelectOverflow(self): self.m.driveInputs([True, True, True]) self.assertEqual(self.m.inputSelect(), 2) def testInputSelect4InputSelect3(self): self.m.driveInputs([True, True, True, False]) self.assertEqual(self.m.inputSelect(), 3) def test2InputSelect0(self): self.m.driveInputs([False, False]) self.assertFalse(self.m.asyncOutput()) def test2InputSelect1(self): self.m.driveInputs([True, True]) self.assertTrue(self.m.asyncOutput()) def test4InputSelect3(self): self.m.driveInputs([True, True, True, False]) self.assertFalse(self.m.asyncOutput()) if __name__ == "__main__": unittest.main()
28.985507
91
0.694833
1,408
12,000
5.914773
0.102273
0.060639
0.079851
0.064842
0.68696
0.633525
0.56256
0.479107
0.435759
0.329251
0
0.025248
0.158333
12,000
413
92
29.05569
0.799307
0
0
0.546667
0
0
0.000667
0
0
0
0
0
0.233333
0
null
null
0.01
0.01
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
c6170afc30e453f2a312a63f60a55b9794498ce1
4,197
py
Python
tests/components/smarttub/test_config_flow.py
MrDelik/core
93a66cc357b226389967668441000498a10453bb
[ "Apache-2.0" ]
30,023
2016-04-13T10:17:53.000Z
2020-03-02T12:56:31.000Z
tests/components/smarttub/test_config_flow.py
jagadeeshvenkatesh/core
1bd982668449815fee2105478569f8e4b5670add
[ "Apache-2.0" ]
31,101
2020-03-02T13:00:16.000Z
2022-03-31T23:57:36.000Z
tests/components/smarttub/test_config_flow.py
jagadeeshvenkatesh/core
1bd982668449815fee2105478569f8e4b5670add
[ "Apache-2.0" ]
11,956
2016-04-13T18:42:31.000Z
2020-03-02T09:32:12.000Z
"""Test the smarttub config flow.""" from unittest.mock import patch from smarttub import LoginFailed from homeassistant import config_entries, data_entry_flow from homeassistant.components.smarttub.const import DOMAIN from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from tests.common import MockConfigEntry async def test_form(hass): """Test we get the form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors"] == {} with patch( "homeassistant.components.smarttub.async_setup_entry", return_value=True, ) as mock_setup_entry: result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_EMAIL: "test-email", CONF_PASSWORD: "test-password"}, ) assert result["type"] == "create_entry" assert result["title"] == "test-email" assert result["data"] == { CONF_EMAIL: "test-email", CONF_PASSWORD: "test-password", } await hass.async_block_till_done() mock_setup_entry.assert_called_once() async def test_form_invalid_auth(hass, smarttub_api): """Test we handle invalid auth.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) smarttub_api.login.side_effect = LoginFailed result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_EMAIL: "test-email", CONF_PASSWORD: "test-password"}, ) assert result["type"] == "form" assert result["errors"] == {"base": "invalid_auth"} async def test_reauth_success(hass, smarttub_api, account): """Test reauthentication flow.""" mock_entry = MockConfigEntry( domain=DOMAIN, data={CONF_EMAIL: "test-email", CONF_PASSWORD: "test-password"}, unique_id=account.id, ) mock_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={ "source": config_entries.SOURCE_REAUTH, "unique_id": mock_entry.unique_id, "entry_id": mock_entry.entry_id, }, data=mock_entry.data, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "reauth_confirm" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_EMAIL: "test-email3", CONF_PASSWORD: "test-password3"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "reauth_successful" assert mock_entry.data[CONF_EMAIL] == "test-email3" assert mock_entry.data[CONF_PASSWORD] == "test-password3" async def test_reauth_wrong_account(hass, smarttub_api, account): """Test reauthentication flow if the user enters credentials for a different already-configured account.""" mock_entry1 = MockConfigEntry( domain=DOMAIN, data={CONF_EMAIL: "test-email1", CONF_PASSWORD: "test-password1"}, unique_id=account.id, ) mock_entry1.add_to_hass(hass) mock_entry2 = MockConfigEntry( domain=DOMAIN, data={CONF_EMAIL: "test-email2", CONF_PASSWORD: "test-password2"}, unique_id="mockaccount2", ) mock_entry2.add_to_hass(hass) # we try to reauth account #2, and the user successfully authenticates to account #1 account.id = mock_entry1.unique_id result = await hass.config_entries.flow.async_init( DOMAIN, context={ "source": config_entries.SOURCE_REAUTH, "unique_id": mock_entry2.unique_id, "entry_id": mock_entry2.entry_id, }, data=mock_entry2.data, ) assert result["type"] == data_entry_flow.RESULT_TYPE_FORM assert result["step_id"] == "reauth_confirm" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_EMAIL: "test-email1", CONF_PASSWORD: "test-password1"} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "already_configured"
33.309524
111
0.672147
506
4,197
5.310277
0.193676
0.066989
0.043543
0.062523
0.580945
0.534053
0.534053
0.439524
0.411611
0.377373
0
0.006352
0.212295
4,197
125
112
33.576
0.806413
0.026686
0
0.351064
0
0
0.141899
0.013158
0
0
0
0
0.191489
1
0
false
0.106383
0.06383
0
0.06383
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
c617ffba3ed7d86f83e8204d0efd8b5ec19f40d4
476
py
Python
ex4.py
JasperStfun/OOP
fb6c084979c2550a01b8dd07a24c244d31f943a0
[ "Apache-2.0" ]
null
null
null
ex4.py
JasperStfun/OOP
fb6c084979c2550a01b8dd07a24c244d31f943a0
[ "Apache-2.0" ]
null
null
null
ex4.py
JasperStfun/OOP
fb6c084979c2550a01b8dd07a24c244d31f943a0
[ "Apache-2.0" ]
null
null
null
class DefenerVector: def __init__(self, v): self.__v = v def __enter__(self): self.__temp = self.__v[:] return self.__temp def __exit__(self, exc_type, exc_val, exc_tb): if exc_type is None: self.__v[:] = self.__temp return False v1 = [1, 2, 3] v2 = [1, 2] try: with DefenerVector(v1) as dv: for i in range(len(dv)): dv[i] += v2[i] except Exception as e: print(e) print(v1)
21.636364
50
0.544118
70
476
3.3
0.514286
0.08658
0.077922
0
0
0
0
0
0
0
0
0.031447
0.331933
476
22
51
21.636364
0.694969
0
0
0
0
0
0
0
0
0
0
0
0
1
0.157895
false
0
0
0
0.315789
0.105263
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c61aff15e6261423fb5fd8677c7a2c1c475568d6
785
py
Python
src/features/migrations/0025_enable_all_remote_config_feature_states.py
augustuswm/flagsmith-api
6f37947fe3791726a92b4df2cdbded11e77387d3
[ "BSD-3-Clause" ]
1,259
2021-06-10T11:24:09.000Z
2022-03-31T10:30:44.000Z
src/features/migrations/0025_enable_all_remote_config_feature_states.py
augustuswm/flagsmith-api
6f37947fe3791726a92b4df2cdbded11e77387d3
[ "BSD-3-Clause" ]
392
2021-06-10T11:12:29.000Z
2022-03-31T10:13:53.000Z
src/features/migrations/0025_enable_all_remote_config_feature_states.py
augustuswm/flagsmith-api
6f37947fe3791726a92b4df2cdbded11e77387d3
[ "BSD-3-Clause" ]
58
2021-06-11T03:18:07.000Z
2022-03-31T14:39:10.000Z
# Generated by Django 2.2.17 on 2021-01-10 12:35 from django.db import migrations def enable_all_remote_config_feature_states(apps, schema_editor): FeatureState = apps.get_model('features', 'FeatureState') # update all existing remote config feature states to maintain current # functionality when hiding disabled flags since we've now merged flags # and remote config feature states. FeatureState.objects.filter(feature__type="CONFIG").update(enabled=True) def reverse(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('features', '0024_auto_20200917_1032'), ] operations = [ migrations.RunPython( enable_all_remote_config_feature_states, reverse_code=reverse ) ]
26.166667
76
0.723567
96
785
5.71875
0.645833
0.087432
0.138434
0.182149
0.123862
0.123862
0
0
0
0
0
0.050713
0.196178
785
29
77
27.068966
0.819334
0.278981
0
0
1
0
0.101604
0.040998
0
0
0
0
0
1
0.133333
false
0.066667
0.066667
0
0.4
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
3
c61b4b710f700b7e7d84698ef9c73f9fe55fc76c
1,488
py
Python
tamcolors/tests/utils_tests/identifier_tests.py
cmcmarrow/tamcolors
65a5f2455bbe35a739b98d14af158c3df7feb786
[ "Apache-2.0" ]
29
2020-07-17T23:46:17.000Z
2022-02-06T05:36:44.000Z
tamcolors/tests/utils_tests/identifier_tests.py
sudo-nikhil/tamcolors
65a5f2455bbe35a739b98d14af158c3df7feb786
[ "Apache-2.0" ]
42
2020-07-25T19:39:52.000Z
2021-02-24T01:19:58.000Z
tamcolors/tests/utils_tests/identifier_tests.py
sudo-nikhil/tamcolors
65a5f2455bbe35a739b98d14af158c3df7feb786
[ "Apache-2.0" ]
8
2020-07-18T23:02:48.000Z
2020-12-30T04:07:35.000Z
# built in libraries import unittest.mock from tempfile import TemporaryDirectory from os.path import join # tamcolors libraries from tamcolors.utils import identifier class IdentifierTests(unittest.TestCase): def test_globals(self): self.assertIsInstance(identifier.IDENTIFIER_FILE_NAME, str) self.assertIsInstance(identifier.IDENTIFIER_SIZE, int) def test_generate_identifier(self): with TemporaryDirectory() as tmp_dir_name: tmp_name = join(tmp_dir_name, "temp.id") self.assertIsInstance(identifier.generate_identifier_bytes(tmp_name), bytes) self.assertIsInstance(identifier.generate_identifier_bytes(tmp_name), bytes) self.assertIsInstance(identifier.generate_identifier_bytes(tmp_name, 1000), bytes) self.assertIsInstance(identifier.generate_identifier_bytes(tmp_name, 9999), bytes) def test_get_identifier_bytes(self): with TemporaryDirectory() as tmp_dir_name: tmp_name = join(tmp_dir_name, "temp2.id") tmp_id = identifier.get_identifier_bytes(tmp_name) self.assertIsInstance(tmp_id, bytes) self.assertEqual(len(tmp_id), identifier.IDENTIFIER_SIZE) for _ in range(10): self.assertEqual(tmp_id, identifier.get_identifier_bytes(tmp_name)) self.assertNotEqual(identifier.generate_identifier_bytes(tmp_name, identifier.IDENTIFIER_SIZE + 1000), tmp_id)
41.333333
114
0.716398
169
1,488
6.023669
0.272189
0.061886
0.123772
0.151277
0.492141
0.492141
0.452849
0.452849
0.452849
0.302554
0
0.012723
0.207661
1,488
35
115
42.514286
0.850721
0.025538
0
0.16
0
0
0.010366
0
0
0
0
0
0.4
1
0.12
false
0
0.16
0
0.32
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c61b82fdb5df4f14bd3407dbc13cb9a344c9c650
2,847
py
Python
source.py
FahimFBA/Invisible-Cloak-Using-Python
4ed662f8ec6ab7bd90c5cf337d10ff8d2496843b
[ "MIT" ]
2
2021-03-29T07:29:39.000Z
2021-12-11T18:05:45.000Z
source.py
FahimFBA/Invisible-Cloak-Using-Python
4ed662f8ec6ab7bd90c5cf337d10ff8d2496843b
[ "MIT" ]
1
2021-12-12T06:37:32.000Z
2021-12-12T16:36:19.000Z
source.py
FahimFBA/Invisible-Cloak-Using-Python
4ed662f8ec6ab7bd90c5cf337d10ff8d2496843b
[ "MIT" ]
2
2021-02-14T15:11:52.000Z
2021-07-08T20:22:58.000Z
# start importing some modules # importing OpenCV import cv2 # using this module , we can process images and videos to identify objects, faces, or even handwriting of a human. # importing NumPy import numpy as np # NumPy is usually imported under the np alias. NumPy is a Python library used for working with arrays. It also has functions for working in domain of linear algebra, fourier transform, and matrices # importing another essential module named time import time # The Python time module provides many ways of representing time in code, such as objects, numbers, and strings. It also provides functionality other than representing time, like waiting during code execution and measuring the efficiency of our code. # I'll use a print function here. It's optional. print("Hey! Have you ever heard about invisible cloak?") print("What is an invisible cloak?") print(""" You have watched invisible cloak in "Harry Potter" a lot, haven't you? It's the same thing. How would I provide you that cloak? Grab a red cloth first! I'll convert that cloth into an invisible cloak with my project!!! """) # starting the initial part cap = cv2.VideoCapture(0) # It lets you create a video capture object which is helpful to capture videos through webcam and then you may perform desired operations on that video. # I need to suspend execution time for 1 seconds now. I'll used it to capture the still background image. time.sleep(1) background = 0 # background plot # capturing the live frame for i in range(30): ret,background = cap.read() # flipping the image background = np.flip(background,axis=1) while(cap.isOpened()): ret, img = cap.read() # reading from the ongoing video img = np.flip(img,axis=1) hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # Converting the image : from BGR to HSV value = (35, 35) blurred = cv2.GaussianBlur(hsv, value,0) # configuration for the mask1 lower_red = np.array([0,120,70]) upper_red = np.array([10,255,255]) mask1 = cv2.inRange(hsv,lower_red,upper_red) # configuration for the mask2 lower_red = np.array([170,120,70]) upper_red = np.array([180,255,255]) mask2 = cv2.inRange(hsv,lower_red,upper_red) # The upper blocks of code (mask1 and mask2) can be replaced with some other code depending the color of your cloth which you would use as the invisible cloak mask = mask1+mask2 mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, np.ones((5,5),np.uint8)) # Morphological Transformations img[np.where(mask==255)] = background[np.where(mask==255)] cv2.imshow('Display',img) # display the image in the specified window k = cv2.waitKey(10) # cv2. waitKey() is a keyboard binding function. The function waits for specified milliseconds for any keyboard event. if k == 27: break
38.472973
250
0.724974
449
2,847
4.57461
0.474388
0.03408
0.019474
0.014606
0.047712
0.047712
0.028238
0
0
0
0
0.034031
0.194942
2,847
73
251
39
0.862129
0.537408
0
0
0
0
0.25522
0
0
0
0
0
0
1
0
false
0
0.085714
0
0.085714
0.085714
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c61d0aed14163a5df84fbf6f3f9906dee796c9d6
207
py
Python
keyvalues/__init__.py
JulioC/keyvalues-python
45bd5aa8fff36372099d8fe855406a649294736f
[ "MIT" ]
6
2016-04-19T22:54:20.000Z
2021-01-12T04:49:30.000Z
keyvalues/__init__.py
JulioC/keyvalues-python
45bd5aa8fff36372099d8fe855406a649294736f
[ "MIT" ]
1
2017-06-23T03:47:02.000Z
2017-09-27T01:25:43.000Z
keyvalues/__init__.py
JulioC/keyvalues-python
45bd5aa8fff36372099d8fe855406a649294736f
[ "MIT" ]
2
2016-02-01T00:16:39.000Z
2017-06-23T02:35:09.000Z
__version_info__ = ('0', '1', '1') __version__ = '.'.join(__version_info__) from keyvalues.keyvalues import KeyValues def load_keyvalues(filename): kv = KeyValues() kv.load(filename) return kv
20.7
41
0.700483
25
207
5.2
0.52
0.169231
0
0
0
0
0
0
0
0
0
0.017341
0.164251
207
9
42
23
0.734104
0
0
0
0
0
0.019324
0
0
0
0
0
0
1
0.142857
false
0
0.142857
0
0.428571
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
c61dc702b237c15662d2418ed34215b2b2a25a9f
1,999
py
Python
rolling/apply.py
andrewcfreeman/rolling
7cff8e45bbebaf64a5da1ad6e7d1a7619eebca17
[ "MIT" ]
189
2018-03-12T00:31:19.000Z
2022-03-26T00:17:38.000Z
rolling/apply.py
andrewcfreeman/rolling
7cff8e45bbebaf64a5da1ad6e7d1a7619eebca17
[ "MIT" ]
23
2017-12-31T17:50:48.000Z
2021-11-27T15:31:54.000Z
rolling/apply.py
andrewcfreeman/rolling
7cff8e45bbebaf64a5da1ad6e7d1a7619eebca17
[ "MIT" ]
7
2019-01-28T02:53:49.000Z
2021-11-11T18:34:45.000Z
from collections import deque from itertools import islice from .base import RollingObject class Apply(RollingObject): """ Iterator object that applies a function to a rolling window over a Python iterable. Parameters ---------- iterable : any iterable object window_size : integer, the size of the rolling window moving over the iterable operation : callable, default sum a function, or class implementing a __call__ method, to be applied to each window Complexity ---------- Update time: operation dependent Memory usage: O(k) where k is the size of the rolling window Examples -------- Rolling sum using builtin sum(): >>> import rolling >>> seq = (8, 1, 1, 3, 6, 5) >>> r_sum = rolling.Apply(seq, 3, operation=sum) >>> next(r_sum) 10 >>> next(r_sum) 5 Reverse each window: >>> r_rev = rolling.Apply(seq, 4, operation=lambda x: list(reversed(x))) >>> list(r_rev) [[3, 1, 1, 8], [6, 3, 1, 1], [5, 6, 3, 1]] """ def _init_fixed(self, iterable, window_size, operation=sum, **kwargs): head = islice(self._iterator, window_size - 1) self._buffer = deque(head, maxlen=window_size) self._operation = operation def _init_variable(self, iterable, window_size, operation=sum, **kwargs): self._buffer = deque(maxlen=window_size) self._operation = operation @property def current_value(self): return self._operation(self._buffer) def _add_new(self, new): self._buffer.append(new) def _remove_old(self): self._buffer.popleft() def _update_window(self, new): self._buffer.append(new) @property def _obs(self): return len(self._buffer) def __repr__(self): return "Rolling(operation='{}', window_size={}, window_type='{}')".format( self._operation.__name__, self.window_size, self.window_type )
24.084337
82
0.62031
253
1,999
4.699605
0.371542
0.067283
0.035324
0.020185
0.216989
0.216989
0.067283
0
0
0
0
0.016249
0.261131
1,999
82
83
24.378049
0.788761
0.405203
0
0.222222
0
0
0.054183
0.021863
0
0
0
0
0
1
0.296296
false
0
0.111111
0.111111
0.555556
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
3
c61de299d4e4c292c61a91562c711d62f7565f8f
7,333
py
Python
src/user/role_service.py
fugwenna/bunkbot
f438c6a7d1f2c1797755eb8287bc1499c0cf2a88
[ "MIT" ]
2
2017-05-10T03:41:12.000Z
2017-08-12T12:51:44.000Z
src/user/role_service.py
fugwenna/bunkbot
f438c6a7d1f2c1797755eb8287bc1499c0cf2a88
[ "MIT" ]
13
2017-08-09T00:41:17.000Z
2021-09-04T17:47:11.000Z
src/user/role_service.py
fugwenna/bunkbot
f438c6a7d1f2c1797755eb8287bc1499c0cf2a88
[ "MIT" ]
4
2017-05-10T01:15:03.000Z
2021-03-02T03:49:45.000Z
from typing import List from discord import Role, Color, role from ..bunkbot import BunkBot from ..channel.channel_service import ChannelService from ..core.bunk_user import BunkUser from ..core.service import Service from ..db.database_service import DatabaseService class RoleService(Service): """ Service responsible for handling role references and removing/adding new roles Parameters ----------- bot: Bunkbot Super class instance of the bot database: DatabaseService Super class instance of the database service channels: ChannelService Access to the server channels and other channel functions """ def __init__(self, bot: BunkBot, database: DatabaseService, channels: ChannelService): super().__init__(bot, database) self.admin: Role = None self.channels: ChannelService = channels def get_role(self, role_name: str) -> Role: """ Get a role directly from the server by name Parameters ----------- role_name: str Name of the role to retrieve from the server """ return next((role for role in self.server.roles if role.name == role_name), None) def get_role_by_pattern(self, pattern: str, roles: List[Role] = None) -> Role: """ Get a role directly from the server with a pattern "contains" Parameters ----------- pattern: str Pattern which will be used to fuzzy search a role name roles: List[Role] (optional) Optional list of roles to search if the default server is not used """ if roles is None: roles = self.server.roles return next((role for role in roles if pattern in role.name), None) async def rm_role(self, role_name: str, user: BunkUser = None) -> None: """ Non-event driven - directly remove a role when another service has deemed appropriate Parameters ----------- role_name: str Name of the role to remove user: Bunkuser (optional) When supplied, the role will be removed from a user rather than the server list """ if user is not None: roles = user.member.roles.copy() roles = [r for r in user.member.roles if r.name != role_name] await user.set_roles(roles) else: roles: List[Role] = [r for r in self.bot.server.roles.copy() if r.name == role_name] for role in roles: ref: Role = role await ref.delete() async def rm_roles_from_user(self, role_names: List[str], user: BunkUser) -> None: """ Non-event driven - directly remove a role when another service has deemed appropriate Parameters ----------- role_names: List[str] List of the roles to remove user: Bunkuser User from which the roles will be removed from a user """ roles: List[Role] = user.member.roles.copy() new_roles: List[Role] = [r for r in roles if r.name not in role_names] await user.set_roles(new_roles) async def add_role_to_user(self, role_name: str, user: BunkUser, color: Color = None) -> Role: """ Non-event driven - directly add a role when another service has deemed appropriate Parameters ----------- role_name: str Name of the role to add user: BunkUser User which to add the role color: Color (optional) Optionally add a color to the role Returns -------- Role added to the user """ roles: List[Role] = await self._get_user_roles_to_set(user.member.roles.copy(), role_name, user, color) await user.set_roles(roles) return self.get_role(role_name) async def add_roles_to_user(self, role_names: List[str], user: BunkUser, color: Color = None) -> List[Role]: """ Non-event driven - directly add multiple roles when another service has deemed appropriate Parameters ----------- role_names: List[str] List of roles to add to the user user: BunkUser User which to add the roles color: Color (optional) Optionally add a color to the roles Returns -------- Roles added to the user """ roles = user.member.roles.copy() for role_name in role_names: roles = await self._get_user_roles_to_set(roles, role_name, user, color) await user.set_roles(roles) return roles async def _get_user_roles_to_set(self, current_roles: List[Role], role_name: str, user: BunkUser, color: Color = None) -> List[Role]: if not user.has_role(role_name): role = self.get_role(role_name) if role is None: if color is None: role: Role = await self.bot.server.create_role(name=role_name) else: role: Role = await self.bot.server.create_role(name=role_name, color=color) current_roles.append(role) return current_roles async def prune_orphaned_roles(self, pattern: str = None) -> None: """ When updating users/roles check for roles which are no longer being used Parameters ----------- pattern: str (optional) Only pruned orphaned roles that contain a specific pattern in the name """ if self.bot.server is None: pass else: empty_color_roles: List[str] = [] if pattern is None: empty_color_roles = [r.name for r in self.bot.server.roles if len(r.members) == 0] else: empty_color_roles = [r.name for r in self.bot.server.roles if pattern in r.name and len(r.members) == 0] for orphan_role in empty_color_roles: await self.channels.log_info("Removing role `{0}`".format(orphan_role)) await self.rm_role(orphan_role) async def get_role_containing(self, pattern: str, user: BunkUser) -> Role: """ Get a user role that contains a given pattern in the name Parameters ----------- pattern: str Pattern which the role name must contain user: BunkUser User which to find the role """ role = next((r for r in user.member.roles if pattern in r.name.lower()), None) return role async def get_lowest_index_for(self, pattern: str) -> int: """ Get the server role index of a given role name (pattern) Parameters ----------- pattern: str Pattern which to locate a role by it's index """ roles: List[int] = [r.position for r in self.bot.server.roles if pattern in r.name] roles.sort() if len(roles) == 0: return 1 return roles[:1][0]
32.591111
138
0.569617
919
7,333
4.43852
0.151251
0.049032
0.018877
0.01569
0.451091
0.359402
0.313067
0.27188
0.200785
0.171366
0
0.001457
0.344879
7,333
224
139
32.736607
0.847627
0.096277
0
0.123288
0
0
0.004732
0
0
0
0
0
0
1
0.041096
false
0.013699
0.09589
0
0.260274
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c61e07f6e1d7dbddc3e330dbcdac65bf1c316ee7
2,166
py
Python
src/dfd/models/interface.py
cicheck/dfd
b02752f958cfea2f85222e2b4b3ba7e265a6152d
[ "MIT" ]
null
null
null
src/dfd/models/interface.py
cicheck/dfd
b02752f958cfea2f85222e2b4b3ba7e265a6152d
[ "MIT" ]
2
2021-12-31T17:44:20.000Z
2021-12-31T19:51:11.000Z
src/dfd/models/interface.py
cicheck/dfd
b02752f958cfea2f85222e2b4b3ba7e265a6152d
[ "MIT" ]
null
null
null
from __future__ import annotations import abc import enum import pathlib import typing as t class Prediction(enum.Enum): """Represents model prediction.""" def _generate_next_value_(name, start, count, last_values): return name REAL = enum.auto() FAKE = enum.auto() UNCERTAIN = enum.auto() @classmethod def from_confidence(cls, confidence: float, threshold: float = 0.5) -> Prediction: """Translate model confidence into prediction using given threshold. Returns: Model prediction over given threshold. """ if confidence >= threshold: return cls.FAKE if 1 - confidence >= threshold: return cls.REAL return cls.UNCERTAIN class ModelInterface(abc.ABC): """Height level wrapper around actual models used underneath. The goal of exposed interface is to hide implementation details such as what library is used to define models. Currently interface operates on paths and handles only data stored on disk. """ @abc.abstractmethod def train(self, train_ds_path: pathlib.Path, validation_ds_path: pathlib.Path) -> None: """Train model using given train and validation data.""" @abc.abstractmethod def test(self, test_ds_path: pathlib.Path) -> t.Dict[str, float]: """Evaluate model over provided test data. Returns: dict, metrics of interests mapped to their values """ @abc.abstractmethod def predict(self, sample_path: pathlib.Path) -> t.Dict[pathlib.Path, Prediction]: """Make predictions over provided sample of frames.""" @abc.abstractmethod def save(self, path: pathlib.Path): """Save model under given path.""" @classmethod @abc.abstractmethod def load(cls, path: pathlib.Path) -> ModelInterface: """Load model from given path.""" @abc.abstractmethod def get_available_metrics_names(self) -> t.List[str]: """Get names of metrics supported by model. Each metric value will be returned by train and test functions. Returns: names of supported metrics """
27.769231
91
0.66205
262
2,166
5.396947
0.427481
0.054455
0.084866
0.036068
0.028289
0
0
0
0
0
0
0.001847
0.250231
2,166
77
92
28.12987
0.868842
0.368421
0
0.25
1
0
0
0
0
0
0
0
0
1
0.25
false
0
0.15625
0.03125
0.6875
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
c61e8d5ec314a4c9be9e075977a63d201f07a9d2
502
py
Python
chapter2/code/concurrency/threadPoolConcurrency.py
abbbhucho/Mastering-Python-for-Networking-and-Security
f4fb1131253e9daad8da501c297758fdcedfbac3
[ "MIT" ]
98
2018-05-13T20:41:43.000Z
2022-03-31T00:24:01.000Z
chapter2/code/concurrency/threadPoolConcurrency.py
Cyb3rid10ts/Mastering-Python-for-Networking-and-Security
4cf04d1758f17ae378b5e3422404e5b7a174a243
[ "MIT" ]
null
null
null
chapter2/code/concurrency/threadPoolConcurrency.py
Cyb3rid10ts/Mastering-Python-for-Networking-and-Security
4cf04d1758f17ae378b5e3422404e5b7a174a243
[ "MIT" ]
62
2018-06-19T13:46:34.000Z
2022-02-11T05:47:24.000Z
#python 3 from concurrent.futures import ThreadPoolExecutor import threading import random def view_thread(): print("Executing Thread") print("Accesing thread : {}".format(threading.get_ident())) print("Thread Executed {}".format(threading.current_thread())) def main(): executor = ThreadPoolExecutor(max_workers=3) thread1 = executor.submit(view_thread) thread1 = executor.submit(view_thread) thread3 = executor.submit(view_thread) if __name__ == '__main__': main()
27.888889
66
0.731076
57
502
6.175439
0.508772
0.113636
0.153409
0.204545
0.176136
0
0
0
0
0
0
0.01171
0.149402
502
18
67
27.888889
0.812646
0.015936
0
0.142857
0
0
0.125506
0
0
0
0
0
0
1
0.142857
false
0
0.214286
0
0.357143
0.214286
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c6221c4f4c97c1af9d1e5e7738396af3bac3c4e6
1,591
py
Python
doc/buildbot/sample_slave.py
elhigu/pocl
726569646d3e95ef7625991aef11a2e84216076a
[ "MIT" ]
1
2020-08-13T06:59:37.000Z
2020-08-13T06:59:37.000Z
doc/buildbot/sample_slave.py
elhigu/pocl
726569646d3e95ef7625991aef11a2e84216076a
[ "MIT" ]
null
null
null
doc/buildbot/sample_slave.py
elhigu/pocl
726569646d3e95ef7625991aef11a2e84216076a
[ "MIT" ]
1
2020-08-13T06:59:39.000Z
2020-08-13T06:59:39.000Z
from buildbot.buildslave import BuildSlave from buildbot.schedulers.basic import SingleBranchScheduler from buildbot.changes import filter from buildbot.config import BuilderConfig from buildbot.schedulers.forcesched import * from poclfactory import createPoclFactory # overrride the 'sample_slave' with a descriptive function name # Note: when finished renaming, the string "sample" should not appear anywhere in this file! # # c - the global buildbot configuration data structure # common_branch - this is the branch that the slave should build. # typically 'master', but during release it will be changed # to the release branch def sample_slave( c, common_branch ): #create a new slave in the master's database c['slaves'].append( BuildSlave( "sample_slave_name", "password" )) # lauch the builders listed in "builderNames" whenever the change poller notices a change to github pocl c['schedulers'].append( SingleBranchScheduler(name="name for scheduler, not sure where this is used", change_filter=filter.ChangeFilter(branch=common_branch), treeStableTimer=60, builderNames=[ "sample_builder_name - this is the name that appears on the webpage"] )) #create one set of steps to build pocl. See poclfactory.py for details # on how to configure it sample_factory = createPoclFactory() #register your build to the master c['builders'].append( BuilderConfig( name = "sample_builder_name - this is the name that appears on the webpage", slavenames=["sample_slave_name"], factory = sample_factory ))
37
105
0.752986
210
1,591
5.628571
0.466667
0.050761
0.022843
0.035533
0.089679
0.089679
0.089679
0.089679
0.089679
0.089679
0
0.001531
0.179133
1,591
42
106
37.880952
0.903522
0.409805
0
0
0
0
0.265152
0
0
0
0
0
0
1
0.043478
false
0.043478
0.26087
0
0.304348
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c6224896f978093621d6275c6b492b553a5f89f0
2,575
py
Python
pqr/__init__.py
pittquantum/PittQuantumRepository
5100ff264e76cb97e5eba2929558a08d0ed158f8
[ "MIT" ]
13
2015-10-11T00:52:52.000Z
2022-03-04T16:26:40.000Z
pqr/__init__.py
pittquantum/backend
5100ff264e76cb97e5eba2929558a08d0ed158f8
[ "MIT" ]
54
2015-05-06T07:33:06.000Z
2015-07-07T05:09:08.000Z
pqr/__init__.py
pittquantum/backend
5100ff264e76cb97e5eba2929558a08d0ed158f8
[ "MIT" ]
4
2017-03-03T03:58:50.000Z
2020-01-23T03:55:30.000Z
from flask import Flask, url_for, request, session, abort import os import re import base64 pqr = Flask(__name__) # Determines the destination of the build. Only usefull if you're using # Frozen-Flask pqr.config['FREEZER_DESTINATION'] = os.path.dirname(os.path.abspath(__file__)) + '/../build' # Function to easily find your assets # In your template use <link rel=stylesheet href="{{ static('filename') }}"> pqr.jinja_env.globals['static'] = ( lambda filename: url_for('static', filename=filename) ) ########################################################################## # Form CSRF protection functions @pqr.before_request def csrf_protect(): if request.method == "POST": token = session.pop('_csrf_token', None) if not token or token != request.form.get('_csrf_token'): abort(403) def generate_csrf_token(): if '_csrf_token' not in session: session['_csrf_token'] = some_random_string() return session['_csrf_token'] def some_random_string(): return base64.urlsafe_b64encode(os.urandom(32)) pqr.jinja_env.globals['csrf_token'] = generate_csrf_token ########################################################################## ########################################################################## # Custom Filters # Auto Subscript any sequence of digits def subnumbers_filter(input): return re.sub("\d+", lambda val: "<sub>" + val.group(0) + "</sub>", input) #Aubscript digits after ~characters removing the ~character def supnumbers_iupac_filter(input): return re.sub("~(.*?)~", lambda val: "<sup>" + val.group(0).replace('~', ' ') + "</sup>", input) # Greek String Replacement def replace_greek_filter(input): choice = "" try: choice = re.findall(r"(Alpha|Beta|Gamma)", input)[0] except IndexError: pass if len(re.findall("(Alpha|Beta|Gamma)[^\w\s]", input)) > 0: return input.replace(choice, '&{};'.format(choice.lower())) else: return input #return re.sub("(Alpha|Beta|Gamma)[^\w\s]", lambda val: "&{};{}".format(choice.lower(), val.group(0)[-1]), input, flags=re.I) # Adding the filters to the environment pqr.jinja_env.filters['subnumbers'] = subnumbers_filter pqr.jinja_env.filters['supnumbersiupac'] = supnumbers_iupac_filter pqr.jinja_env.filters['replacegreek'] = replace_greek_filter assert pqr.jinja_env.filters['subnumbers'] assert pqr.jinja_env.filters['supnumbersiupac'] assert pqr.jinja_env.filters['replacegreek'] ########################################################################## from pqr import views
33.441558
129
0.616311
307
2,575
5.003257
0.407166
0.041667
0.057292
0.070313
0.1875
0
0
0
0
0
0
0.007644
0.136311
2,575
76
130
33.881579
0.683004
0.202718
0
0
0
0
0.151289
0.014327
0
0
0
0
0.069767
1
0.139535
false
0.023256
0.116279
0.069767
0.395349
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c625108183edb6d267c158ee6b26a88a85fb2494
255
py
Python
application/core/common_utils.py
solomonxie/lambda-application-demo
35ac5e17985cdd5694eb154b527d3942ad52cad6
[ "MIT" ]
null
null
null
application/core/common_utils.py
solomonxie/lambda-application-demo
35ac5e17985cdd5694eb154b527d3942ad52cad6
[ "MIT" ]
null
null
null
application/core/common_utils.py
solomonxie/lambda-application-demo
35ac5e17985cdd5694eb154b527d3942ad52cad6
[ "MIT" ]
null
null
null
import json from urllib import request def get_ip(): info = None try: resp = request.urlopen("http://ip-api.com/json/") raw = resp.read() info = json.loads(raw) except Exception as e: print(e) return info
18.214286
57
0.580392
35
255
4.2
0.714286
0
0
0
0
0
0
0
0
0
0
0
0.305882
255
13
58
19.615385
0.830508
0
0
0
0
0
0.090196
0
0
0
0
0
0
1
0.090909
false
0
0.181818
0
0.363636
0.090909
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c625be4168c09da47fadb564f1e3637c6cb209e3
2,205
py
Python
src/boxes/datatypes/calc.py
Peilonrayz/alphabet_learner
13229e53215e3c050f106e00e34f90ca2d6fa256
[ "MIT" ]
null
null
null
src/boxes/datatypes/calc.py
Peilonrayz/alphabet_learner
13229e53215e3c050f106e00e34f90ca2d6fa256
[ "MIT" ]
null
null
null
src/boxes/datatypes/calc.py
Peilonrayz/alphabet_learner
13229e53215e3c050f106e00e34f90ca2d6fa256
[ "MIT" ]
null
null
null
import collections.abc from typing import Union, Sequence, Optional from .primitives import Number from .units import Unit, UnitTypes _Value = Union[Unit, Number, float, int] class Calc: type: UnitTypes @classmethod def build( cls, values: Union[_Value, Sequence[_Value]], operators: Sequence[str] = [], ): _values: Sequence[_Value] = ( values if isinstance(values, collections.abc.Sequence) else [values] ) if len(_values) != len(operators) + 1: raise ValueError("There must be one less operator than values.") calc = CalcOperators( [ CalcValue(value) if not isinstance(value, (float, int)) else CalcValue(Number(value)) for value in _values ], operators[:], ) if len(operators) == 0: return calc._values[0] return calc class CalcValue(Calc): _value: Union[Unit, Number] def __init__(self, value: Union[Unit, Number]): self._value = value if isinstance(value, Unit): self.type = value.TYPE else: self.type = UnitTypes.NONE def __str__(self): return str(self._value) def __repr__(self): return f"CalcValue({self._value!r})" class CalcOperators(Calc): _values: Sequence[Calc] _operators: Sequence[str] def __init__(self, values: Sequence[Calc], operators: Sequence[str]): if len(values) != len(operators) + 1: raise ValueError("There must be one less operator than values.") types = {value.type for value in values if value.type is not UnitTypes.NONE} if 1 < len(types): raise ValueError(f"Cannot mix types {types}") self._values = values self._operators = operators def __str__(self): values = [None] * (len(self._values) * 2 - 1) values[0::2] = self._values values[1::2] = self._operators return " ".join(str(v) for v in values) def __repr__(self): return f"CalcOperators({self._values!r}, {self._operators!r})"
27.911392
84
0.576417
248
2,205
4.943548
0.241935
0.04894
0.034258
0.04894
0.213703
0.184339
0.122349
0.122349
0.122349
0.122349
0
0.007299
0.316553
2,205
78
85
28.269231
0.806238
0
0
0.096774
0
0
0.086621
0.02585
0
0
0
0
0
1
0.112903
false
0
0.064516
0.048387
0.387097
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c626517f412e73181fae98762e0e92e932f1d7ee
676
py
Python
dfrus/machine_code_match.py
dfint/dfrus
84eb206d01e57ba2571b19c2bbbe7765c660fb55
[ "MIT" ]
1
2021-09-11T12:46:01.000Z
2021-09-11T12:46:01.000Z
dfrus/machine_code_match.py
dfint/dfrus
84eb206d01e57ba2571b19c2bbbe7765c660fb55
[ "MIT" ]
8
2021-10-29T18:54:54.000Z
2021-11-29T08:18:05.000Z
dfrus/machine_code_match.py
dfint/dfrus
84eb206d01e57ba2571b19c2bbbe7765c660fb55
[ "MIT" ]
null
null
null
from .binio import from_dword from .opcodes import Reg, mov_reg_imm, mov_acc_mem, mov_rm_reg, x0f_movups, Prefix def match_mov_reg_imm32(b: bytes, reg: Reg, imm: int) -> bool: assert len(b) == 5, b return b[0] == mov_reg_imm | 8 | int(reg) and from_dword(b[1:]) == imm def get_start(s): i = None if s[-1] & 0xfe == mov_acc_mem: i = 1 elif s[-2] & 0xf8 == mov_rm_reg and s[-1] & 0xc7 == 0x05: i = 2 elif s[-3] == 0x0f and s[-2] & 0xfe == x0f_movups and s[-1] & 0xc7 == 0x05: i = 3 return i # prefix is not allowed here assert i is not None if s[-1 - i] == Prefix.operand_size: i += 1 return i
26
82
0.573964
122
676
3.008197
0.401639
0.021798
0.049046
0.043597
0.076294
0.076294
0
0
0
0
0
0.072765
0.288462
676
25
83
27.04
0.690229
0.038462
0
0.111111
0
0
0
0
0
0
0.049383
0
0.111111
1
0.111111
false
0
0.111111
0
0.388889
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c6271a004e236807dbe7bcbd4263febf9681f51b
964
py
Python
tests/database/testmodel.py
LowieHuyghe/edmunds-python
236d087746cb8802a8854b2706b8d3ff009e9209
[ "Apache-2.0" ]
4
2017-09-07T13:39:50.000Z
2018-05-31T16:14:50.000Z
tests/database/testmodel.py
LowieHuyghe/edmunds-python
236d087746cb8802a8854b2706b8d3ff009e9209
[ "Apache-2.0" ]
103
2017-03-19T15:58:21.000Z
2018-07-11T20:36:17.000Z
tests/database/testmodel.py
LowieHuyghe/edmunds-python
236d087746cb8802a8854b2706b8d3ff009e9209
[ "Apache-2.0" ]
2
2017-10-14T15:20:11.000Z
2018-04-20T09:55:44.000Z
from tests.testcase import TestCase from edmunds.database.db import db, mapper, relationship, backref from sqlalchemy.orm import mapper as sqlalchemy_mapper, relationship as sqlalchemy_relationship, backref as sqlalchemy_backref from edmunds.database.databasemanager import DatabaseManager from werkzeug.local import LocalProxy from flask_sqlalchemy import SQLAlchemy class TestModel(TestCase): """ Test the model """ def test_model(self): """ Test model :return: void """ test_db = DatabaseManager.get_sql_alchemy_instance() self.assert_is_instance(db, LocalProxy) self.assert_is_instance(db._get_current_object(), SQLAlchemy) self.assert_equal_deep(test_db, db._get_current_object()) self.assert_equal_deep(sqlalchemy_mapper, mapper) self.assert_equal_deep(sqlalchemy_relationship, relationship) self.assert_equal_deep(sqlalchemy_backref, backref)
32.133333
126
0.745851
113
964
6.088496
0.327434
0.087209
0.087209
0.110465
0.190407
0
0
0
0
0
0
0
0.185685
964
29
127
33.241379
0.876433
0.043568
0
0
0
0
0
0
0
0
0
0
0.4
1
0.066667
false
0
0.4
0
0.533333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
2
c6285b947189b318c16d99d170a80d0888fc3b1c
6,485
py
Python
pvlib/test/test_tracking.py
dacoex/pvlib-python
38c0082f264a468015464aff1026a9ac864b4ed5
[ "BSD-3-Clause" ]
null
null
null
pvlib/test/test_tracking.py
dacoex/pvlib-python
38c0082f264a468015464aff1026a9ac864b4ed5
[ "BSD-3-Clause" ]
null
null
null
pvlib/test/test_tracking.py
dacoex/pvlib-python
38c0082f264a468015464aff1026a9ac864b4ed5
[ "BSD-3-Clause" ]
2
2017-03-08T18:38:05.000Z
2018-06-08T07:29:03.000Z
import logging pvl_logger = logging.getLogger('pvlib') import datetime import numpy as np import pandas as pd from nose.tools import raises, assert_almost_equals from nose.plugins.skip import SkipTest from pandas.util.testing import assert_frame_equal from pvlib.location import Location from pvlib import solarposition from pvlib import tracking def test_solar_noon(): apparent_zenith = pd.Series([10]) apparent_azimuth = pd.Series([180]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=True, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 10, 'surface_azimuth': 90, 'surface_tilt': 0, 'tracker_theta': 0}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) def test_azimuth_north_south(): apparent_zenith = pd.Series([60]) apparent_azimuth = pd.Series([90]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=180, max_angle=90, backtrack=True, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 0, 'surface_azimuth': 90, 'surface_tilt': 60, 'tracker_theta': -60}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=True, gcr=2.0/7.0) expect['tracker_theta'] *= -1 assert_frame_equal(expect, tracker_data) def test_max_angle(): apparent_zenith = pd.Series([60]) apparent_azimuth = pd.Series([90]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=45, backtrack=True, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 15, 'surface_azimuth': 90, 'surface_tilt': 45, 'tracker_theta': 45}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) def test_backtrack(): apparent_zenith = pd.Series([80]) apparent_azimuth = pd.Series([90]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=False, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 0, 'surface_azimuth': 90, 'surface_tilt': 80, 'tracker_theta': 80}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=0, max_angle=90, backtrack=True, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 52.5716, 'surface_azimuth': 90, 'surface_tilt': 27.42833, 'tracker_theta': 27.4283}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) def test_axis_tilt(): apparent_zenith = pd.Series([30]) apparent_azimuth = pd.Series([135]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=30, axis_azimuth=180, max_angle=90, backtrack=True, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 7.286245, 'surface_azimuth': 37.3427, 'surface_tilt': 35.98741, 'tracker_theta': -20.88121}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=30, axis_azimuth=0, max_angle=90, backtrack=True, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 47.6632, 'surface_azimuth': 129.0303, 'surface_tilt': 42.5152, 'tracker_theta': 31.6655}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) def test_axis_azimuth(): apparent_zenith = pd.Series([30]) apparent_azimuth = pd.Series([90]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=90, max_angle=90, backtrack=True, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 30, 'surface_azimuth': 180, 'surface_tilt': 0, 'tracker_theta': 0}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) apparent_zenith = pd.Series([30]) apparent_azimuth = pd.Series([180]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=90, max_angle=90, backtrack=True, gcr=2.0/7.0) expect = pd.DataFrame({'aoi': 0, 'surface_azimuth': 180, 'surface_tilt': 30, 'tracker_theta': 30}, index=[0], dtype=np.float64) assert_frame_equal(expect, tracker_data) @raises(ValueError) def test_index_mismatch(): apparent_zenith = pd.Series([30]) apparent_azimuth = pd.Series([90,180]) tracker_data = tracking.singleaxis(apparent_zenith, apparent_azimuth, axis_tilt=0, axis_azimuth=90, max_angle=90, backtrack=True, gcr=2.0/7.0)
39.30303
81
0.517039
673
6,485
4.745914
0.138187
0.072323
0.055103
0.099875
0.785848
0.754227
0.754227
0.754227
0.741703
0.719474
0
0.069977
0.385197
6,485
165
82
39.30303
0.731126
0
0
0.632479
0
0
0.062442
0
0
0
0
0
0.102564
1
0.059829
false
0
0.08547
0
0.145299
0
0
0
0
null
0
0
0
0
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
5
c62888b176d698967ac4dee70756482d46d7f23e
1,396
py
Python
src/topgearAPI/carro.py
danilo94/ArduinoDashboard
f5dcbd8995c0f135ca0bd899aa9eefd9393eb46a
[ "MIT" ]
2
2019-05-25T21:21:31.000Z
2019-12-15T15:33:56.000Z
src/topgearAPI/carro.py
domsamuka/ArduinoDashboard
f5dcbd8995c0f135ca0bd899aa9eefd9393eb46a
[ "MIT" ]
null
null
null
src/topgearAPI/carro.py
domsamuka/ArduinoDashboard
f5dcbd8995c0f135ca0bd899aa9eefd9393eb46a
[ "MIT" ]
2
2019-12-15T15:33:33.000Z
2019-12-17T01:50:26.000Z
from MemoryHandler import * from addresses import * from struct import * class carro (object): def __init__(self): self.velocidade=0 self.gasolina=0 self.pontos=0 self.posicao=0 self.rpm=0 self.nitro=0 self.gerenciadorMemoria = MemoryHandler("zsnesw.exe") def update(self): self.updateVel() self.updateGas() self.updatePontos() self.updatePosicao() self.updateRpm() self.updateNitro() def pack(self): data = '1;'+str(self.velocidade)+';'+str(self.gasolina)+';'+str(self.pontos)+';'+str(self.posicao)+';'+str(self.rpm)+';'+str(self.nitro)+';' return data def updatePosicao(self): self.posicao = (int) ((self.gerenciadorMemoria.lerByte(CARROSAFRENTE)) + 1) def updateVel(self): self.velocidade = (int)(self.gerenciadorMemoria.lerPalavra(SPEEDMETER)/10) pass def updateGas(self): self.gasolina = (int) (100 - (((self.gerenciadorMemoria.lerByte(FUELCONSUMP))*100)/20)) pass def updatePontos(self): self.pontos = self.gerenciadorMemoria.lerByte(POINTS) pass def updateRpm(self): self.rpm = 0 pass def updateNitro(self): self.nitro = (int) ( self.gerenciadorMemoria.lerByte(0x00C64B06) - 53) pass
27.372549
149
0.588109
144
1,396
5.673611
0.319444
0.078335
0.141983
0.078335
0
0
0
0
0
0
0
0.027861
0.280086
1,396
50
150
27.92
0.785075
0
0
0.179487
0
0
0.013383
0
0
0
0.007435
0
0
1
0.230769
false
0.128205
0.076923
0
0.358974
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
c628a854cb921505c3553f10d9c7e5209dafaeeb
10,483
py
Python
tests/test_base_api.py
yhegen/cumulocity-python-api
729d29a518426fe118ed315df84020578a6961fb
[ "Apache-2.0" ]
9
2021-02-16T08:53:08.000Z
2022-02-15T11:58:19.000Z
tests/test_base_api.py
yhegen/cumulocity-python-api
729d29a518426fe118ed315df84020578a6961fb
[ "Apache-2.0" ]
4
2021-04-20T12:26:41.000Z
2022-02-09T09:52:11.000Z
tests/test_base_api.py
yhegen/cumulocity-python-api
729d29a518426fe118ed315df84020578a6961fb
[ "Apache-2.0" ]
3
2021-04-26T23:05:32.000Z
2021-12-09T14:13:58.000Z
# Copyright (c) 2020 Software AG, # Darmstadt, Germany and/or Software AG USA Inc., Reston, VA, USA, # and/or its subsidiaries and/or its affiliates and/or their licensors. # Use, reproduction, transfer, publication or disclosure is prohibited except # as specifically provided for in your License Agreement with Software AG. # pylint: disable=protected-access, redefined-outer-name import base64 from unittest.mock import patch import json import pytest import requests import responses from c8y_api._base_api import CumulocityRestApi # noqa (protected-access) @pytest.fixture(scope='function') def mock_c8y() -> CumulocityRestApi: """Provide mock CumulocityRestApi instance.""" return CumulocityRestApi( base_url='http://base.com', tenant_id='t12345', username='username', password='password', application_key='application_key') @pytest.fixture(scope='module') def httpbin_basic() -> CumulocityRestApi: """Provide mock CumulocityRestApi instance for httpbin with basic auth.""" return CumulocityRestApi( base_url='https://httpbin.org', tenant_id='t12345', username='username', password='password' ) def assert_auth_header(c8y, headers): """Assert that the given auth header is correctly formatted.""" auth_header = headers['Authorization'].lstrip('Basic ') expected = f'{c8y.tenant_id}/{c8y.username}:{c8y.password}' assert base64.b64decode(auth_header) == expected.encode('utf-8') def assert_accept_header(headers, accept='application/json'): """Assert that the accept header matches the expectation.""" assert headers['Accept'] == accept def assert_content_header(headers, content_type='application/json'): """Assert that the content-type header matches the expectation.""" assert headers['Content-Type'] == content_type def assert_application_key_header(c8y, headers): """Assert that the application key header matches the expectation.""" assert headers[c8y.HEADER_APPLICATION_KEY] == c8y.application_key @pytest.mark.parametrize('args, expected', [ ({'accept': 'application/json'}, {'Accept': 'application/json'}), ({'content_tYPe': 'content/TYPE'}, {'Content-Type': 'content/TYPE'}), ({'some': 'thing', 'mORE_Of_this': 'same'}, {'Some': 'thing', 'More-Of-This': 'same'}), ({'empty': None, 'accept': 'accepted'}, {'Accept': 'accepted'}), ({'empty1': None, 'empty2': None}, None), ({'accept': ''}, {'Accept': None}), ]) def test_prepare_headers(args, expected): """Verify header preparation.""" assert CumulocityRestApi._prepare_headers(**args) == expected @pytest.mark.parametrize('method', ['get', 'post', 'put']) def test_remove_accept_header(mock_c8y: CumulocityRestApi, method): """Verify that the default accept header can be unset/removed.""" with responses.RequestsMock() as rsps: rsps.add(method=method.upper(), url=mock_c8y.base_url + '/resource', status=200, json={}) kwargs = {'resource': '/resource', 'accept': ''} if method.startswith('p'): kwargs['json'] = {} func = getattr(mock_c8y, method) func(**kwargs) assert 'Accept' not in rsps.calls[0].request.headers @pytest.mark.online @pytest.mark.parametrize('method', ['get', 'post', 'put']) def test_remove_accept_header_online(httpbin_basic: CumulocityRestApi, method): """Verify that the unset accept header are actually not sent.""" kwargs = {'resource': '/anything', 'accept': ''} if method.startswith('p'): kwargs['json'] = {} func = getattr(httpbin_basic, method) response = func(**kwargs) assert 'Accept' not in response['headers'] @pytest.mark.parametrize('method', ['get', 'post', 'put', 'delete']) def test_no_application_key_header(mock_c8y: CumulocityRestApi, method): """Verify that the application key header is not present by default.""" c8y = CumulocityRestApi(mock_c8y.base_url, mock_c8y.tenant_id, mock_c8y.username, mock_c8y.username) with responses.RequestsMock() as rsps: rsps.add(method=method.upper(), url=mock_c8y.base_url + '/resource', status=200, json={'result': True}) kwargs = {'resource': '/resource'} if method.startswith('p'): kwargs['json'] = {} func = getattr(c8y, method) if method.startswith('p'): kwargs.update({'json': {}}) func(**kwargs) request_headers = rsps.calls[0].request.headers assert CumulocityRestApi.HEADER_APPLICATION_KEY not in request_headers @pytest.mark.online def test_basic_auth_get(httpbin_basic: CumulocityRestApi): """Verify that the basic auth headers are added for the REST requests.""" c8y = httpbin_basic # first we verify that the auth is there for GET requests response = c8y.get('/anything') assert_auth_header(c8y, response['headers']) def test_post_defaults(mock_c8y: CumulocityRestApi): """Verify the basic functionality of the POST requests.""" with responses.RequestsMock() as rsps: rsps.add(method=responses.POST, url=mock_c8y.base_url + '/resource', status=201, json={'result': True}) response = mock_c8y.post('/resource', json={'request': True}) request_body = rsps.calls[0].request.body request_headers = rsps.calls[0].request.headers assert json.loads(request_body)['request'] assert_auth_header(mock_c8y, request_headers) assert_accept_header(request_headers) assert_content_header(request_headers) assert_application_key_header(mock_c8y, request_headers) assert response['result'] def test_post_explicits(mock_c8y: CumulocityRestApi): """Verify the basic functionality of the POST requests.""" with responses.RequestsMock() as rsps: rsps.add(method=responses.POST, url=mock_c8y.base_url + '/resource', status=201, json={'result': True}) response = mock_c8y.post('/resource', accept='custom/accept', content_type='custom/content', json={'request': True}) request_body = rsps.calls[0].request.body request_headers = rsps.calls[0].request.headers assert json.loads(request_body)['request'] assert_auth_header(mock_c8y, request_headers) assert_accept_header(request_headers, 'custom/accept') assert_content_header(request_headers, 'custom/content') assert_application_key_header(mock_c8y, request_headers) assert response['result'] @pytest.mark.online def test_get_default(httpbin_basic: CumulocityRestApi): """Verify that the get function with default parameters works as expected.""" c8y = httpbin_basic # (1) with implicit parameters given and all default response = c8y.get(resource='/anything/resource?p1=v1&p2=v2') # auth header must always be present assert response['headers']['Authorization'] # by default we accept JSON assert response['headers']['Accept'] == 'application/json' # inline parameters recognized assert response['args']['p1'] assert response['args']['p2'] @pytest.mark.online def test_get_explicit(httpbin_basic: CumulocityRestApi): """Verify that the get function with explicit parameters works as expected.""" c8y = httpbin_basic response = c8y.get(resource='/anything/resource', params={'p1': 'v1', 'p2': 3}, accept='something/custom') # auth header must always be present assert response['headers']['Authorization'] # expecting our custom accept header assert response['headers']['Accept'] == 'something/custom' # explicit parameters recognized assert response['args']['p1'] assert response['args']['p2'] def test_get_ordered_response(): """Verify that the response JSON can be ordered on request.""" c8y = CumulocityRestApi(base_url='', tenant_id='', username='', password='') with patch('requests.Session.get') as get_mock: mock_response = requests.Response() mock_response.status_code = 200 mock_response._content = b'{"list": [1, 2, 3, 4, 5], "x": "xxx", "m": "mmm", "c": "ccc"}' get_mock.return_value = mock_response response = c8y.get('any', ordered=True) elements = list(response.items()) # first element is a list assert elements[0][0] == 'list' assert elements[0][1] == [1, 2, 3, 4, 5] # 2nd to 4th are some elements in order assert (elements[1][0], elements[2][0], elements[3][0]) == ('x', 'm', 'c') def test_get_404(): """Verify that a 404 results in a KeyError and a message naming the missing resource.""" c8y = CumulocityRestApi(base_url='', tenant_id='', username='', password='') with patch('requests.Session.get') as get_mock: mock_response = requests.Response() mock_response.status_code = 404 get_mock.return_value = mock_response with pytest.raises(KeyError) as error: c8y.get('some/key') assert 'some/key' in str(error) def test_delete_defaults(mock_c8y: CumulocityRestApi): """Verify the basic funtionality of the DELETE requests.""" with responses.RequestsMock() as rsps: rsps.add(method=responses.DELETE, url=mock_c8y.base_url + '/resource', status=204) mock_c8y.delete('/resource') request_headers = rsps.calls[0].request.headers assert_auth_header(mock_c8y, request_headers) assert_application_key_header(mock_c8y, request_headers) def test_empty_response(mock_c8y: CumulocityRestApi): """Verify that an empty GET/POST/PUT responses doesn't break the code.""" with responses.RequestsMock() as rsps: rsps.add(method=responses.GET, url=mock_c8y.base_url + '/resource', status=200) mock_c8y.get('/resource') with responses.RequestsMock() as rsps: rsps.add(method=responses.POST, url=mock_c8y.base_url + '/resource', status=201) mock_c8y.post('/resource', json={}) with responses.RequestsMock() as rsps: rsps.add(method=responses.PUT, url=mock_c8y.base_url + '/resource', status=200) mock_c8y.put('/resource', json={})
35.900685
110
0.659258
1,249
10,483
5.38751
0.183347
0.033289
0.032694
0.018725
0.575866
0.511517
0.429484
0.385793
0.350572
0.304206
0
0.018568
0.208814
10,483
291
111
36.024055
0.792742
0.180864
0
0.466667
0
0.005556
0.137817
0.00885
0
0
0
0
0.216667
1
0.105556
false
0.027778
0.038889
0
0.155556
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c62b0f6c1dafe4863a081c29e104df05db4c301e
866
py
Python
src/xsdtools/jsonschema_generator.py
pietrodelugas/xsdtools
b30e5f6b41c079cca01b3fb8c36feee484df8e34
[ "BSD-3-Clause" ]
1
2020-12-17T04:50:47.000Z
2020-12-17T04:50:47.000Z
src/xsdtools/jsonschema_generator.py
pietrodelugas/xsdtools
b30e5f6b41c079cca01b3fb8c36feee484df8e34
[ "BSD-3-Clause" ]
null
null
null
src/xsdtools/jsonschema_generator.py
pietrodelugas/xsdtools
b30e5f6b41c079cca01b3fb8c36feee484df8e34
[ "BSD-3-Clause" ]
2
2021-07-21T10:38:08.000Z
2021-09-16T17:50:25.000Z
# # Copyright (c) 2020, Quantum Espresso Foundation and SISSA. # Internazionale Superiore di Studi Avanzati). All rights reserved. # This file is distributed under the terms of the BSD 3-Clause license. # See the file 'LICENSE' in the root directory of the present distribution, # or https://opensource.org/licenses/BSD-3-Clause # from .abstract_generator import AbstractGenerator class JSONSchemaGenerator(AbstractGenerator): """ JSON Schema generic generator for XSD schemas. """ formal_language = 'JSON Schema' default_paths = ['templates/json-schema/'] builtin_types = { 'string': 'string', 'boolean': 'boolean', 'float': 'number', 'double': 'number', 'integer': 'integer', 'unsignedByte': 'integer', 'nonNegativeInteger': 'integer', 'positiveInteger': 'integer', }
29.862069
75
0.668591
91
866
6.318681
0.747253
0.052174
0.034783
0
0
0
0
0
0
0
0
0.008837
0.215935
866
28
76
30.928571
0.837997
0.420323
0
0
0
0
0.3375
0.045833
0
0
0
0
0
1
0
false
0
0.071429
0
0.357143
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c62d9b91a6c0cb24173d60044e7948da3e09c288
4,135
py
Python
bright/tests/test_bright.py
bright-dev/bright
af3ff83d37880787443b1a8e785f375142d42882
[ "WTFPL" ]
3
2016-05-08T06:13:10.000Z
2019-02-14T10:01:22.000Z
bright/tests/test_bright.py
bright-dev/bright
af3ff83d37880787443b1a8e785f375142d42882
[ "WTFPL" ]
null
null
null
bright/tests/test_bright.py
bright-dev/bright
af3ff83d37880787443b1a8e785f375142d42882
[ "WTFPL" ]
null
null
null
"""Bright general tests""" from unittest import TestCase import nose from nose.tools import assert_equal, assert_not_equal, assert_raises, raises, \ assert_almost_equal, assert_true, assert_false, with_setup import os import warnings import tables as tb import numpy as np from pyne import nucname import bright bright_conf = bright.bright_conf # # Fixtures # def setup_h5(): if 'isos.h5' in os.listdir('.'): return f = tb.openFile('isos.h5', 'w') f.createArray(f.root, "ToIsos", np.array([92235, 922380, 10010]), "ToIsos") f.createArray(f.root, "NotIsos", np.array([92235, 922380, 10010]), "NotIsos") f.close() def teardown_h5(): os.remove('isos.h5') def setup_txt(): with open('isos.txt', 'w') as f: f.write('U-235, 922380\n10010}') def teardown_txt(): os.remove('isos.txt') # # Tests # def test_bright_start(): current = os.getenv("BRIGHT_DATA") os.environ["BRIGHT_DATA"] = "/foo/bar" new = os.getenv("BRIGHT_DATA") bright.bright_start() assert_equal(new, "/foo/bar") os.environ["BRIGHT_DATA"] = current def test_track_nucs(): old_isolist = bright_conf.track_nucs new_isolist = [922350, 10010] bright_conf.track_nucs = set(new_isolist) assert_equal(bright_conf.track_nucs, set([10010, 922350])) bright_conf.track_nucs = old_isolist def test_verbosity(): old_verbosity = bright_conf.verbosity bright_conf.verbosity = 100 assert_equal(bright_conf.verbosity, 100) bright.verbosity = old_verbosity def test_write_hdf5(): old_write = bright_conf.write_hdf5 bright_conf.write_hdf5 = False assert_false(bright_conf.write_hdf5) bright_conf.write_hdf5 = 1 assert_true(bright_conf.write_hdf5) bright_conf.write_hdf5 = old_write def test_write_text(): old_write = bright_conf.write_text bright_conf.write_text = False assert_false(bright_conf.write_text) bright_conf.write_text = 1 assert_true(bright_conf.write_text) bright_conf.write_text = old_write def test_output_filename(): assert_equal( bright_conf.output_filename, 'fuel_cycle.h5') bright_conf.output_filename = 'new_name.h5' assert_equal( bright_conf.output_filename, 'new_name.h5') @with_setup(setup_h5) def test_load_track_nucs_hdf5_1(): old_isos = bright_conf.track_nucs bright_conf.track_nucs = set([80160]) bright.load_track_nucs_hdf5('isos.h5') assert_equal(bright_conf.track_nucs, set([10010, 80160, 922350, 922380])) bright_conf.track_nucs = old_isos @with_setup(setup_h5) def test_load_track_nucs_hdf5_2(): old_isos = bright_conf.track_nucs bright_conf.track_nucs = set([80160]) bright.load_track_nucs_hdf5('isos.h5', '/NotIsos') assert_equal(bright_conf.track_nucs, set([10010, 80160, 922350, 922380])) bright_conf.track_nucs = old_isos @with_setup(setup_h5) def test_load_track_nucs_hdf5_3(): old_isos = bright_conf.track_nucs bright_conf.track_nucs = set([80160]) bright.load_track_nucs_hdf5('isos.h5', '', True) assert_equal(bright_conf.track_nucs, set([10010, 922350, 922380])) bright_conf.track_nucs = old_isos @with_setup(setup_h5, teardown_h5) def test_load_track_nucs_hdf5_4(): old_isos = bright_conf.track_nucs bright_conf.track_nucs = set([80160]) bright.load_track_nucs_hdf5('isos.h5', '/NotIsos', True) assert_equal(bright_conf.track_nucs, set([10010, 922350, 922380])) bright_conf.track_nucs = old_isos @with_setup(setup_txt) def test_load_track_nucs_text_1(): old_isos = bright_conf.track_nucs bright_conf.track_nucs = set([80160]) bright.load_track_nucs_text('isos.txt') assert_equal(bright_conf.track_nucs, set([10010, 80160, 922350, 922380])) bright_conf.track_nucs = old_isos @with_setup(setup_txt, teardown_txt) def test_load_track_nucs_text_2(): old_isos = bright_conf.track_nucs bright_conf.track_nucs = set([80160]) bright.load_track_nucs_text('isos.txt', True) assert_equal(bright_conf.track_nucs, set([10010, 922350, 922380])) bright_conf.track_nucs = old_isos if __name__ == "__main__": nose.main()
28.517241
81
0.728174
614
4,135
4.529316
0.141694
0.1726
0.151025
0.191298
0.642215
0.604099
0.568141
0.516721
0.434736
0.418914
0
0.074828
0.156469
4,135
144
82
28.715278
0.722477
0.008706
0
0.257143
0
0
0.061155
0
0
0
0
0
0.161905
1
0.152381
false
0
0.085714
0
0.247619
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c62dbdcf249b0771af08bd01ce1cb984ad5302f1
81
py
Python
Dog_model/Dog/apps.py
cs-fullstack-2019-fall/django-models-cw-Deltonjr2
3fc667bed19201b75016798bd367d0bde9cb6c00
[ "Apache-2.0" ]
null
null
null
Dog_model/Dog/apps.py
cs-fullstack-2019-fall/django-models-cw-Deltonjr2
3fc667bed19201b75016798bd367d0bde9cb6c00
[ "Apache-2.0" ]
null
null
null
Dog_model/Dog/apps.py
cs-fullstack-2019-fall/django-models-cw-Deltonjr2
3fc667bed19201b75016798bd367d0bde9cb6c00
[ "Apache-2.0" ]
null
null
null
from django.apps import AppConfig class DogConfig(AppConfig): name = 'Dog'
13.5
33
0.728395
10
81
5.9
0.9
0
0
0
0
0
0
0
0
0
0
0
0.185185
81
5
34
16.2
0.893939
0
0
0
0
0
0.037037
0
0
0
0
0
0
1
0
false
0
0.333333
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
c62e4d453948d4cfc525683440c2c6e5323bf2c9
2,568
py
Python
tests/unittest_db.py
zaanposni/umfrageBot
3e19dc0629cde394da2ae8706e6e043b4e87059d
[ "MIT" ]
6
2019-08-15T20:19:38.000Z
2021-02-28T21:33:19.000Z
tests/unittest_db.py
zaanposni/umfrageBot
3e19dc0629cde394da2ae8706e6e043b4e87059d
[ "MIT" ]
31
2019-08-14T08:42:08.000Z
2020-05-07T13:43:43.000Z
tests/unittest_db.py
zaanposni/umfrageBot
3e19dc0629cde394da2ae8706e6e043b4e87059d
[ "MIT" ]
5
2019-08-17T13:39:53.000Z
2020-04-01T07:25:51.000Z
import unittest from pathlib import Path import os import shutil import time from src.bt_utils.handle_sqlite import DatabaseHandler from src.bt_utils.get_content import content_dir from sqlite3 import IntegrityError class TestClass(unittest.TestCase): def testDB(self): if os.path.exists(content_dir): shutil.rmtree(content_dir, ignore_errors=True) if not os.path.exists(content_dir): os.makedirs(content_dir) else: try: os.remove(os.path.join(content_dir, "bundestag.db")) except OSError: pass self.db = DatabaseHandler() self.roles = ["role1", "role2"] # creates basic table structures if not already present print("Create database and test if creation was successful") self.db.create_structure(self.roles) db_path = Path(os.path.join(content_dir, "bundestag.db")) self.assertTrue(db_path.is_file()) print("Check if database is empty") users = self.db.get_all_users() self.assertEqual(users, []) print("Add user to database and check if he exists.") self.db.add_user(123, self.roles) user = self.db.get_specific_user(123) self.assertEqual(user, (123, 0, 0)) print("Add reaction to user and check if it exists.") self.db.add_reaction(123, "role1") user = self.db.get_specific_user(123) self.assertEqual(user, (123, 1, 0)) print("Remove reaction and check if it does not exist anymore.") self.db.remove_reaction(123, "role1") user = self.db.get_specific_user(123) self.assertEqual(user, (123, 0, 0)) print("Add another user and check if select all users works.") self.db.add_user(124, self.roles) users = self.db.get_all_users() self.assertEqual(users, [(123, 0, 0), (124, 0, 0)]) print("Add another user with invalid id and check if it still get created.") with self.assertRaises(IntegrityError): self.db.add_user(124, self.roles) users = self.db.get_all_users() self.assertEqual(users, [(123, 0, 0), (124, 0, 0)]) print("Add another column and check if it gets applied correctly") self.roles = ["role1", "role2", "role3"] self.db.update_columns(self.roles) users = self.db.get_all_users() self.assertEqual(users, [(123, 0, 0, 0), (124, 0, 0, 0)]) print("Closing connection") del self.db if __name__ == '__main__': unittest.main()
33.789474
84
0.628505
351
2,568
4.472934
0.293447
0.061147
0.040127
0.035669
0.389172
0.357325
0.347771
0.30828
0.30828
0.281529
0
0.041405
0.257009
2,568
75
85
34.24
0.781447
0.020639
0
0.224138
0
0
0.191803
0
0
0
0
0
0.155172
1
0.017241
false
0.017241
0.137931
0
0.172414
0.155172
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c62ff5ebe57088aca1b17d3ec477eb124d6fc9bd
1,777
py
Python
mxnet_load_model.py
whn09/mxnet-ssd
ff15817dbf6d3c6d3fc69fbf6bef4c4d61490159
[ "MIT" ]
1
2019-09-11T02:07:50.000Z
2019-09-11T02:07:50.000Z
mxnet_load_model.py
whn09/mxnet-ssd
ff15817dbf6d3c6d3fc69fbf6bef4c4d61490159
[ "MIT" ]
null
null
null
mxnet_load_model.py
whn09/mxnet-ssd
ff15817dbf6d3c6d3fc69fbf6bef4c4d61490159
[ "MIT" ]
null
null
null
# load model and predicate import mxnet as mx import numpy as np # define test data batch_size = 1 num_batch = 1 filepath = 'frame-1.jpg' DEFAULT_INPUT_SHAPE = 300 # load model sym, arg_params, aux_params = mx.model.load_checkpoint("model/deploy_model_algo_1", 0) # load with net name and epoch num mod = mx.mod.Module(symbol=sym, context=mx.cpu(), data_names=["data"], label_names=["cls_prob"]) print('data_names:', mod.data_names) print('output_names:', mod.output_names) #print('data_shapes:', mod.data_shapes) #print('label_shapes:', mod.label_shapes) #print('output_shapes:', mod.output_shapes) mod.bind(data_shapes=[("data", (1, 3, DEFAULT_INPUT_SHAPE, DEFAULT_INPUT_SHAPE))], for_training=False) mod.set_params(arg_params, aux_params) # , allow_missing=True import cv2 img = cv2.cvtColor(cv2.imread(filepath), cv2.COLOR_BGR2RGB) print(img.shape) img = cv2.resize(img, (DEFAULT_INPUT_SHAPE, DEFAULT_INPUT_SHAPE)) img = np.swapaxes(img, 0, 2) img = np.swapaxes(img, 1, 2) img = img[np.newaxis, :] print(img.shape) # # predict # eval_data = np.array([img]) # eval_label = np.zeros(len(eval_data)) # just need to be the same length, empty is ok # eval_iter = mx.io.NDArrayIter(eval_data, eval_label, batch_size, shuffle=False) # print('eval_iter.provide_data:', eval_iter.provide_data) # print('eval_iter.provide_label:', eval_iter.provide_label) # predict_stress = mod.predict(eval_iter, num_batch) # print(predict_stress) # you can transfer to numpy array # forward from collections import namedtuple Batch = namedtuple('Batch', ['data']) mod.forward(Batch([mx.nd.array(img)])) prob = mod.get_outputs()[0].asnumpy() prob = np.squeeze(prob) # Grab top result, convert to python list of lists and return results = [prob[i].tolist() for i in range(4)] print(results)
34.843137
121
0.747327
287
1,777
4.425087
0.400697
0.037795
0.066929
0.028346
0.053543
0.053543
0
0
0
0
0
0.013898
0.109173
1,777
50
122
35.54
0.788377
0.403489
0
0.074074
0
0
0.081888
0.024085
0
0
0
0
0
1
0
false
0
0.148148
0
0.148148
0.185185
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c63135668085d0506f3e10e5b3343cb3a4bdce5a
577
py
Python
dataMapper.py
cbrandl/csv_costanalyser
c4e2c53bb7f13e56aec07425e5c0e1f0bed6b8fa
[ "MIT" ]
null
null
null
dataMapper.py
cbrandl/csv_costanalyser
c4e2c53bb7f13e56aec07425e5c0e1f0bed6b8fa
[ "MIT" ]
null
null
null
dataMapper.py
cbrandl/csv_costanalyser
c4e2c53bb7f13e56aec07425e5c0e1f0bed6b8fa
[ "MIT" ]
null
null
null
class dataMapper: def __init__(self, data): self.__data = data self.__structure = self.getDataStructure() def getDataStructure(self): headings = self.__data[0] structure = {} for key in headings: structure[key.lower()] = '' return structure def map(self): dataSet = [] for dataRecord in self.__data[1:]: item = {} for index, key in enumerate(self.__structure): item[key] = dataRecord[index] dataSet.append(item) return dataSet
27.47619
58
0.551127
57
577
5.333333
0.403509
0.105263
0
0
0
0
0
0
0
0
0
0.005319
0.348354
577
20
59
28.85
0.803191
0
0
0
0
0
0
0
0
0
0
0
0
1
0.166667
false
0
0
0
0.333333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c63176fa74c364cbbea0d4a75b777050b148c47b
2,778
py
Python
tests/integrate_test/samples/sample_internal_call_scores/sample_link_score/sample_link_score.py
bayeshack2016/icon-service
36cab484d2e41548d7f2f74526f127ee3a4423fc
[ "Apache-2.0" ]
52
2018-08-24T02:28:43.000Z
2021-07-06T04:44:22.000Z
tests/integrate_test/samples/sample_internal_call_scores/sample_link_score/sample_link_score.py
bayeshack2016/icon-service
36cab484d2e41548d7f2f74526f127ee3a4423fc
[ "Apache-2.0" ]
62
2018-09-17T06:59:16.000Z
2021-12-15T06:02:51.000Z
tests/integrate_test/samples/sample_internal_call_scores/sample_link_score/sample_link_score.py
bayeshack2016/icon-service
36cab484d2e41548d7f2f74526f127ee3a4423fc
[ "Apache-2.0" ]
35
2018-09-14T02:42:10.000Z
2022-02-05T10:34:46.000Z
from iconservice import * class SampleInterface(InterfaceScore): @interface def set_value(self, value: int) -> None: pass @interface def get_value(self) -> int: pass @interface def get_db(self) -> IconScoreDatabase: pass @interface def fallback_via_internal_call(self) -> None: pass @interface def fallback_via_not_payable_internal_call(self) -> None: pass class SampleLinkScore(IconScoreBase): _SCORE_ADDR = 'score_addr' @eventlog(indexed=1) def Changed(self, value: int): pass def __init__(self, db: IconScoreDatabase) -> None: super().__init__(db) self._value = VarDB('value', db, value_type=int) self._addr_score = VarDB(self._SCORE_ADDR, db, value_type=Address) def on_install(self, value: int=0) -> None: super().on_install() self._value.set(value) def on_update(self) -> None: super().on_update() @external(readonly=False) def add_score_func(self, score_addr: Address) -> None: self._addr_score.set(score_addr) @external(readonly=True) def get_value(self) -> int: test_interface = self.create_interface_score(self._addr_score.get(), SampleInterface) return test_interface.get_value() @external def set_value(self, value: int): test_interface = self.create_interface_score(self._addr_score.get(), SampleInterface) test_interface.set_value(value) self.Changed(value) def _get_other_score_db(self): interface_score = self.create_interface_score(self._addr_score.get(), SampleInterface) return interface_score.get_db() @external(readonly=True) def get_data_from_other_score(self) -> bool: db = self._get_other_score_db() db.get(b'dummy_key') return True @external def put_data_to_other_score_db(self): db = self._get_other_score_db() db.put(b'dummy_key', b'dummy_value') @external(readonly=False) def transfer_icx_to_other_score(self, value: int) -> None: test_interface = self.create_interface_score(self._addr_score.get(), SampleInterface) test_interface.icx(value).fallback_via_internal_call() @external(readonly=False) def transfer_icx_to_other_score_fail(self, value: int) -> None: test_interface = self.create_interface_score(self._addr_score.get(), SampleInterface) test_interface.icx(value).fallback_via_not_payable_internal_call() @external(readonly=False) @payable def transfer_all_icx_to_other_score(self) -> None: amount: int = self.icx.get_balance(self.address) self.call(self._addr_score.get(), 'fallback_via_internal_call', {}, amount) @payable def fallback(self) -> None: pass
31.213483
94
0.688985
358
2,778
4.99162
0.175978
0.045327
0.058198
0.053721
0.502518
0.387241
0.332401
0.306659
0.306659
0.254057
0
0.000903
0.202304
2,778
88
95
31.568182
0.805505
0
0
0.348485
0
0
0.025198
0.009359
0
0
0
0
0
1
0.287879
false
0.106061
0.015152
0
0.393939
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
0
0
0
2
c631f8352fb062e1fdfef1179ba0676d0f9d2d26
489
py
Python
setup.py
ulicar/sentry-cli
c95a77f8b74ced7c41dc8ab61fd31fdf64c08880
[ "MIT" ]
null
null
null
setup.py
ulicar/sentry-cli
c95a77f8b74ced7c41dc8ab61fd31fdf64c08880
[ "MIT" ]
null
null
null
setup.py
ulicar/sentry-cli
c95a77f8b74ced7c41dc8ab61fd31fdf64c08880
[ "MIT" ]
null
null
null
#!/usr/bin/python from setuptools import setup setup( name = "python-sentry", version = "1.0", author = "Josip Domsic", author_email = "josip.domsic+github@gmail.com", description = ("Pure Python CLI for sentry, as well as client library"), license = "MIT", keywords = "python Sentry CLI", url = "https://github.com/ulicar/sentry-cli", packages=['sentry'], data_files = [ ('/usr/local/bin/', [ 'sentry-cli' ]) ], )
23.285714
76
0.580777
57
489
4.947368
0.649123
0.095745
0
0
0
0
0
0
0
0
0
0.00551
0.257669
489
20
77
24.45
0.77135
0.03272
0
0
0
0
0.417373
0.061441
0
0
0
0
0
1
0
true
0
0.058824
0
0.058824
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
1
c6323bdd3e94514d523e80b9e992ba25f2230d0f
790
py
Python
crawler/src/config/config.py
HVHO/holiday-pharmacy
e641dca93ed0cc0e3ffa28f54a1da6a86c1cfe22
[ "MIT" ]
null
null
null
crawler/src/config/config.py
HVHO/holiday-pharmacy
e641dca93ed0cc0e3ffa28f54a1da6a86c1cfe22
[ "MIT" ]
null
null
null
crawler/src/config/config.py
HVHO/holiday-pharmacy
e641dca93ed0cc0e3ffa28f54a1da6a86c1cfe22
[ "MIT" ]
null
null
null
import json import os def load_config(): PYTHON_ENV = os.getenv("PYTHON_ENV", default="DEV") if PYTHON_ENV == "DEV": with open("./crawler/src/config/config-dev.json") as f: config = json.load(f) host = config["database_host"] name = config["database_name"] user = config["database_user"] _pass = config["database_pass"] auth_key = config["kakao_auth_key"] elif PYTHON_ENV == "PRD": host = os.getenv("database_host") name = os.getenv("database_name") user = os.getenv("database_user") _pass = os.getenv("database_pass") auth_key = os.getenv("kakao_auth_key") return {"host": host, "name": name, "user": user, "pass": _pass, "kakao_auth_key": auth_key}
34.347826
96
0.594937
100
790
4.45
0.29
0.107865
0.14382
0.085393
0
0
0
0
0
0
0
0
0.259494
790
22
97
35.909091
0.760684
0
0
0
0
0
0.274684
0.04557
0
0
0
0
0
1
0.052632
false
0.157895
0.105263
0
0.210526
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
c633041a2c7d19a40de6c87bb53ba1dfc7b15b1a
672
py
Python
alexandriadocs/core/tests/test_models.py
srtab/alexandria-docs
94b221a4140db23ad6d97a98c7cf521fbdefbc0a
[ "Apache-2.0" ]
2
2017-03-26T22:38:49.000Z
2017-04-22T11:28:07.000Z
alexandriadocs/core/tests/test_models.py
srtab/alexandriadocs
94b221a4140db23ad6d97a98c7cf521fbdefbc0a
[ "Apache-2.0" ]
22
2017-06-10T17:15:59.000Z
2018-08-06T14:57:44.000Z
alexandriadocs/core/tests/test_models.py
srtab/alexandriadocs
94b221a4140db23ad6d97a98c7cf521fbdefbc0a
[ "Apache-2.0" ]
1
2018-08-04T08:12:47.000Z
2018-08-04T08:12:47.000Z
# -*- coding: utf-8 -*- from django.test import SimpleTestCase from core.models import VisibilityMixin class VisibilityMixinTest(SimpleTestCase): def test_is_private(self): visibility = VisibilityMixin() self.assertTrue(visibility.is_private) visibility = VisibilityMixin( visibility_level=VisibilityMixin.Level.PUBLIC) self.assertFalse(visibility.is_private) def test_is_public(self): visibility = VisibilityMixin( visibility_level=VisibilityMixin.Level.PUBLIC) self.assertTrue(visibility.is_public) visibility = VisibilityMixin() self.assertFalse(visibility.is_public)
30.545455
58
0.714286
64
672
7.34375
0.34375
0.212766
0.038298
0.110638
0.297872
0.297872
0.297872
0.297872
0
0
0
0.001873
0.205357
672
21
59
32
0.878277
0.03125
0
0.4
0
0
0
0
0
0
0
0
0.266667
1
0.133333
false
0
0.133333
0
0.333333
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c6337ba6bb736b172e7ae3a784113684d1641780
5,320
py
Python
STResNet/plots/error_plots.py
vtsuperdarn/deep_leaning_on_GSP_TEC
f5989d1742be9c02edbcab37433f468cb2c5f771
[ "MIT" ]
9
2018-09-17T02:11:26.000Z
2020-12-16T12:28:35.000Z
STResNet/plots/error_plots.py
vtsuperdarn/deep_leaning_on_GSP_TEC
f5989d1742be9c02edbcab37433f468cb2c5f771
[ "MIT" ]
null
null
null
STResNet/plots/error_plots.py
vtsuperdarn/deep_leaning_on_GSP_TEC
f5989d1742be9c02edbcab37433f468cb2c5f771
[ "MIT" ]
6
2018-07-23T13:37:10.000Z
2022-01-19T17:51:19.000Z
import datetime import pandas import seaborn as sns import matplotlib.pyplot as plt import os import re import glob amean_err = [] astddev_err = [] amin_err = [] amax_err = [] rmean_err = [] rstddev_err = [] rmin_err = [] rmax_err = [] #loading the true and predicted tec maps for calculating the min/max error, mean and stddev error for both absolute and relative differences for i in range(32): #print i path = "predicted_tec_files/{}_pred_*.npy".format(i) for fnm in glob.glob(path): pred = np.load(fnm).tolist() pred = np.array(pred) #print pred.shape path = "predicted_tec_files/{}_y_*.npy".format(i) for fnm in glob.glob(path): truth = np.load(fnm).tolist() truth = np.array(truth) #print truth.shape pred = np.squeeze(pred) truth = np.squeeze(truth) diff_absolute = abs(pred - truth) diff_relative = abs((pred - truth)/truth) #print diff.shape #flattern operation diff_absolute = np.reshape(diff_absolute, (32,-1)) diff_relative = np.reshape(diff_relative, (32,-1)) #print diff.shape amean_err += np.mean(diff_absolute, axis=1).tolist() astddev_err += np.std(diff_absolute, axis=1).tolist() amin_err += np.min(diff_absolute, axis=1).tolist() amax_err += np.max(diff_absolute,axis=1).tolist() rmean_err += np.mean(diff_relative, axis=1).tolist() rstddev_err += np.std(diff_relative, axis=1).tolist() rmin_err += np.min(diff_relative, axis=1).tolist() rmax_err += np.max(diff_relative,axis=1).tolist() #starting from 168 because we want one day cycle plot amean_err = amean_err[168:] astddev_err = astddev_err[168:] amin_err = amin_err[168:] amax_err = amax_err[168:] rmean_err = rmean_err[168:] rstddev_err = rstddev_err[168:] rmin_err = rmin_err[168:] rmax_err = rmax_err[168:] amean_err = np.array(amean_err) astddev_err = np.array(astddev_err) amin_err = np.array(amin_err) amax_err = np.array(amax_err) print(amean_err.shape) print(astddev_err.shape) print(amin_err.shape) print(amax_err.shape) rmean_err = np.array(rmean_err) rstddev_err = np.array(rstddev_err) rmin_err = np.array(rmin_err) rmax_err = np.array(rmax_err) print(rmean_err.shape) print(rstddev_err.shape) print(rmin_err.shape) print(rmax_err.shape) #plotting the absolute error plots sns.set_style("whitegrid") sns.set_context("poster") f, axArr = plt.subplots(5, sharex=True, figsize=(20, 20)) xlim1 = amean_err.shape[0] dates = [] stdate = datetime.datetime(2015, 1, 12, 0, 5) dummy = datetime.datetime(2015, 1, 12, 0, 10) tec_resolution = (dummy - stdate) dates.append(stdate) for i in range(1, 856): dates.append(dates[i-1]+tec_resolution) x_val = dates print(len(x_val)) cl = sns.color_palette('bright', 4) axArr[0].plot(x_val, amean_err, color=cl[0]) axArr[1].plot(x_val, astddev_err, color=cl[1]) axArr[2].plot(x_val, amin_err, color=cl[2]) axArr[3].plot(x_val, amax_err, color=cl[3]) axArr[4].plot(x_val, amean_err, color=cl[0], label='mean') axArr[4].plot(x_val, astddev_err, color=cl[1], label='stddev') axArr[0].set_ylabel("Mean", fontsize=14) axArr[1].set_ylabel("Stddev", fontsize=14) axArr[2].set_ylabel("Min", fontsize=14) axArr[3].set_ylabel("Max", fontsize=14) axArr[4].set_ylabel("Mean/Stddev", fontsize=14) axArr[-1].set_xlabel("TIME", fontsize=14) axArr[0].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[1].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[2].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[3].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[4].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[4].legend( bbox_to_anchor=(0., 1.02, 1., .102), loc=1, ncol=2, borderaxespad=0.1 ) f.savefig('error_plot_absolute.png', dpi=f.dpi, bbox_inches='tight') #plotting the relative error plots sns.set_style("whitegrid") sns.set_context("poster") f, axArr = plt.subplots(5, sharex=True, figsize=(20, 20)) xlim1 = rmean_err.shape[0] dates = [] stdate = datetime.datetime(2015, 1, 12, 0, 5) dummy = datetime.datetime(2015, 1, 12, 0, 10) tec_resolution = (dummy - stdate) dates.append(stdate) for i in range(1, 856): dates.append(dates[i-1]+tec_resolution) x_val = dates print(len(x_val)) cl = sns.color_palette('bright', 4) axArr[0].plot(x_val, rmean_err, color=cl[0]) axArr[1].plot(x_val, rstddev_err, color=cl[1]) axArr[2].plot(x_val, rmin_err, color=cl[2]) axArr[3].plot(x_val, rmax_err, color=cl[3]) axArr[4].plot(x_val, rmean_err, color=cl[0], label='mean') axArr[4].plot(x_val, rstddev_err, color=cl[1], label='stddev') axArr[0].set_ylabel("Mean", fontsize=14) axArr[1].set_ylabel("Stddev", fontsize=14) axArr[2].set_ylabel("Min", fontsize=14) axArr[3].set_ylabel("Max", fontsize=14) axArr[4].set_ylabel("Mean/Stddev", fontsize=14) axArr[-1].set_xlabel("TIME", fontsize=14) axArr[0].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[1].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[2].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[3].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[4].get_xaxis().set_major_formatter(DateFormatter('%H:%M')) axArr[4].legend( bbox_to_anchor=(0., 1.02, 1., .102), loc=1, ncol=2, borderaxespad=0.1 ) f.savefig('error_plot_relative.png', dpi=f.dpi, bbox_inches='tight')
31.111111
140
0.71015
892
5,320
4.044843
0.154709
0.022173
0.026608
0.044346
0.623614
0.572616
0.572616
0.558758
0.545455
0.473392
0
0.043219
0.117105
5,320
170
141
31.294118
0.724931
0.065977
0
0.40625
0
0
0.059084
0.02198
0
0
0
0
0
1
0
false
0
0.054688
0
0.054688
0.078125
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c63435b48134fbdbc1eba24cadcae4cf22b07d3a
1,969
py
Python
online_judges/sub_two/sub_two_challenge.py
stephank007/python_challenges
dfd8d18c03a06735f6e4e02b0660007fe2d02f07
[ "Apache-2.0" ]
null
null
null
online_judges/sub_two/sub_two_challenge.py
stephank007/python_challenges
dfd8d18c03a06735f6e4e02b0660007fe2d02f07
[ "Apache-2.0" ]
null
null
null
online_judges/sub_two/sub_two_challenge.py
stephank007/python_challenges
dfd8d18c03a06735f6e4e02b0660007fe2d02f07
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # coding: utf-8 # This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges). # # Challenge Notebook # ## Problem: Sum of Two Integers (Subtraction Variant). # # See the [LeetCode](https://leetcode.com/problems/sum-of-two-integers/) problem page. # # * [Constraints](#Constraints) # * [Test Cases](#Test-Cases) # * [Algorithm](#Algorithm) # * [Code](#Code) # * [Unit Test](#Unit-Test) # * [Solution Notebook](#Solution-Notebook) # ## Constraints # # * Can we assume we're working with 32 bit ints? # * Yes # * Can we assume the inputs are valid? # * No, check for None # * Can we assume this fits memory? # * Yes # ## Test Cases # # <pre> # * None input -> TypeError # * 7, 5 -> 2 # * -5, -7 -> 2 # * -5, 7 -> -12 # * 5, -7 -> 12 # </pre> # ## Algorithm # # Refer to the [Solution Notebook](). If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start. # ## Code # In[ ]: class Solution(object): def sub_two(self, val): # TODO: Implement me pass # ## Unit Test # **The following unit test is expected to fail until you solve the challenge.** # In[ ]: # %load test_sub_two.py import unittest class TestSubTwo(unittest.TestCase): def test_sub_two(self): solution = Solution() self.assertRaises(TypeError, solution.sub_two, None) self.assertEqual(solution.sub_two(7, 5), 2) self.assertEqual(solution.sub_two(-5, -7), 2) self.assertEqual(solution.sub_two(-5, 7), -12) self.assertEqual(solution.sub_two(5, -7), 12) print('Success: test_sub_two') def main(): test = TestSubTwo() test.test_sub_two() if __name__ == '__main__': main() # ## Solution Notebook # # Review the [Solution Notebook]() for a discussion on algorithms and code solutions.
22.123596
181
0.643982
266
1,969
4.684211
0.443609
0.048154
0.05618
0.083467
0.102729
0.079454
0.079454
0.079454
0
0
0
0.019846
0.206704
1,969
88
182
22.375
0.777849
0.628238
0
0
0
0
0.043478
0
0
0
0
0.011364
0.277778
1
0.166667
false
0.055556
0.055556
0
0.333333
0.055556
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
2
c6382fdd07fdfdca681e712305a912e00b66a929
1,262
py
Python
src/ipdasite.services/ipdasite/services/interfaces/curator.py
NASA-PDS/planetarydata.org
16731a251c22408b433117f7f01e29d004f11467
[ "Apache-2.0" ]
null
null
null
src/ipdasite.services/ipdasite/services/interfaces/curator.py
NASA-PDS/planetarydata.org
16731a251c22408b433117f7f01e29d004f11467
[ "Apache-2.0" ]
5
2021-03-19T21:41:19.000Z
2022-02-11T14:55:14.000Z
src/ipdasite.services/ipdasite/services/interfaces/curator.py
NASA-PDS/planetarydata.org
16731a251c22408b433117f7f01e29d004f11467
[ "Apache-2.0" ]
null
null
null
# encoding: utf-8 # Copyright 2011 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. '''Curator: interface''' from zope.interface import Interface from zope import schema from ipdasite.services import ProjectMessageFactory as _ class ICurator(Interface): '''A person and agency that is responsible for a service.''' title = schema.TextLine( title=_(u'Name'), description=_(u'Name of this curator.'), required=True, ) description = schema.Text( title=_(u'Description'), description=_(u'A short summary of this curator, used in free-text searches.'), required=False, ) contactName = schema.TextLine( title=_(u'Contact Name'), description=_(u'Name of a person who curates one or more services.'), required=False, ) emailAddress = schema.TextLine( title=_(u'Email Address'), description=_(u'Contact address for a person or workgroup that curates services.'), required=False, ) telephone = schema.TextLine( title=_(u'Telephone'), description=_(u'Public telephone number in international format in order to contact this curator.'), required=False, )
33.210526
108
0.669572
146
1,262
5.712329
0.486301
0.035971
0.091127
0.095923
0.052758
0
0
0
0
0
0
0.005149
0.230586
1,262
37
109
34.108108
0.853759
0.161648
0
0.137931
0
0
0.311005
0
0
0
0
0
0
1
0
false
0
0.103448
0
0.310345
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c638b2c5e25cf3da6255a0d76be797621245e3cf
23
py
Python
deepnade/buml/Results/__init__.py
marinakiseleva/NADE
69ea890fad1e775dfff2db6dad4dd9d11b6a343e
[ "BSD-3-Clause" ]
null
null
null
deepnade/buml/Results/__init__.py
marinakiseleva/NADE
69ea890fad1e775dfff2db6dad4dd9d11b6a343e
[ "BSD-3-Clause" ]
null
null
null
deepnade/buml/Results/__init__.py
marinakiseleva/NADE
69ea890fad1e775dfff2db6dad4dd9d11b6a343e
[ "BSD-3-Clause" ]
1
2021-10-08T19:54:34.000Z
2021-10-08T19:54:34.000Z
from .Results import *
11.5
22
0.73913
3
23
5.666667
1
0
0
0
0
0
0
0
0
0
0
0
0.173913
23
1
23
23
0.894737
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
5
c6392cb56f54b8d5c8c4d8010af78d820fc779d5
472
py
Python
main/migrations/0006_auto_20200120_1628.py
Code-and-Response/ISAC-SIMO-Repo-2
5b0cb0099e128dbacfdc53bf686ef2b069a51bc6
[ "PostgreSQL", "Apache-2.0" ]
5
2021-08-16T16:32:41.000Z
2022-02-22T03:47:49.000Z
main/migrations/0006_auto_20200120_1628.py
Code-and-Response/ISAC-SIMO-Repo-2
5b0cb0099e128dbacfdc53bf686ef2b069a51bc6
[ "PostgreSQL", "Apache-2.0" ]
7
2021-04-12T14:48:48.000Z
2022-02-14T08:30:57.000Z
main/migrations/0006_auto_20200120_1628.py
Code-and-Response/ISAC-SIMO-Repo-2
5b0cb0099e128dbacfdc53bf686ef2b069a51bc6
[ "PostgreSQL", "Apache-2.0" ]
1
2021-04-28T14:28:34.000Z
2021-04-28T14:28:34.000Z
# Generated by Django 3.0.2 on 2020-01-20 10:43 from django.db import migrations, models import main.models class Migration(migrations.Migration): dependencies = [ ('main', '0005_auto_20200120_1619'), ] operations = [ migrations.AlterField( model_name='user', name='image', field=models.ImageField(default='user_images/default.png', upload_to=main.models.PathAndRename('user_images')), ), ]
23.6
123
0.637712
54
472
5.444444
0.722222
0.068027
0
0
0
0
0
0
0
0
0
0.086592
0.241525
472
19
124
24.842105
0.734637
0.095339
0
0
1
0
0.164706
0.108235
0
0
0
0
0
1
0
false
0
0.153846
0
0.384615
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
c63aa739c17a4e754a25a2ea9c3f099089da52a6
350
py
Python
__init__.py
LLNL/ferdinand
af47b415ea1e9cb21a45b20d1f3854bc7f3a4d70
[ "Apache-2.0" ]
null
null
null
__init__.py
LLNL/ferdinand
af47b415ea1e9cb21a45b20d1f3854bc7f3a4d70
[ "Apache-2.0" ]
null
null
null
__init__.py
LLNL/ferdinand
af47b415ea1e9cb21a45b20d1f3854bc7f3a4d70
[ "Apache-2.0" ]
null
null
null
############################################## # # # Ferdinand 0.40, Ian Thompson, LLNL # # # # gnd,endf,fresco,azure,hyrma # # # ############################################## __all__ = ["f90nml"]
38.888889
46
0.18
13
350
4.538462
1
0
0
0
0
0
0
0
0
0
0
0.028249
0.494286
350
8
47
43.75
0.305085
0.328571
0
0
0
0
0.214286
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
3
c63aa7bd0e0701b71a3831892875ee207bc50f62
2,707
py
Python
tests/test_chol.py
luk036/ellalgo
8e83587b271f35c906c0d0aa4175dac153e5e29b
[ "MIT" ]
null
null
null
tests/test_chol.py
luk036/ellalgo
8e83587b271f35c906c0d0aa4175dac153e5e29b
[ "MIT" ]
null
null
null
tests/test_chol.py
luk036/ellalgo
8e83587b271f35c906c0d0aa4175dac153e5e29b
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from __future__ import print_function import numpy as np from ellalgo.oracles.chol_ext import chol_ext def test_chol1(): """[summary]""" l1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] m1 = np.array(l1) Q1 = chol_ext(len(m1)) assert Q1.factorize(m1) def test_chol2(): """[summary]""" l2 = [ [18.0, 22.0, 54.0, 42.0], [22.0, -70.0, 86.0, 62.0], [54.0, 86.0, -174.0, 134.0], [42.0, 62.0, 134.0, -106.0], ] m2 = np.array(l2) Q = chol_ext(len(m2)) assert not Q.factorize(m2) Q.witness() assert Q.p == (0, 2) # assert ep == 1.0 def test_chol3(): """[summary]""" l3 = [[0.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] m3 = np.array(l3) Q = chol_ext(len(m3)) assert not Q.factorize(m3) ep = Q.witness() assert Q.p == (0, 1) assert Q.v[0] == 1.0 assert ep == 0.0 def test_chol4(): """[summary]""" l1 = [[25.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] m1 = np.array(l1) Q1 = chol_ext(len(m1)) Q1.allow_semidefinite = True assert Q1.factorize(m1) def test_chol5(): """[summary]""" l2 = [ [18.0, 22.0, 54.0, 42.0], [22.0, -70.0, 86.0, 62.0], [54.0, 86.0, -174.0, 134.0], [42.0, 62.0, 134.0, -106.0], ] m2 = np.array(l2) Q = chol_ext(len(m2)) Q.allow_semidefinite = True assert not Q.factorize(m2) Q.witness() assert Q.p == (0, 2) # assert ep == 1.0 def test_chol6(): """[summary]""" l3 = [[0.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 11.0]] m3 = np.array(l3) Q = chol_ext(len(m3)) Q.allow_semidefinite = True assert Q.factorize(m3) # [v, ep] = Q.witness2() # assert len(v) == 1 # assert v[0] == 1.0 # assert ep == 0.0 def test_chol7(): """[summary]""" l3 = [[0.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, -20.0]] m3 = np.array(l3) Q = chol_ext(len(m3)) Q.allow_semidefinite = True assert not Q.factorize(m3) ep = Q.witness() assert ep == 20.0 def test_chol8(): """[summary]""" """[summary] """ l3 = [[0.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 20.0]] m3 = np.array(l3) Q = chol_ext(len(m3)) Q.allow_semidefinite = False assert not Q.factorize(m3) def test_chol9(): """[summary]""" """[summary] """ l3 = [[0.0, 15.0, -5.0], [15.0, 18.0, 0.0], [-5.0, 0.0, 20.0]] m3 = np.array(l3) Q = chol_ext(len(m3)) Q.allow_semidefinite = True assert Q.factorize(m3)
23.136752
68
0.472109
467
2,707
2.670236
0.143469
0.056135
0.044908
0.028067
0.817161
0.800321
0.756215
0.756215
0.738573
0.684042
0
0.182733
0.302549
2,707
116
69
23.336207
0.477754
0.088659
0
0.716216
0
0
0
0
0
0
0
0
0.202703
1
0.121622
false
0
0.040541
0
0.162162
0.013514
0
0
0
null
0
0
0
1
1
1
1
1
1
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
8
c63e00866b579ae084343dd771e2b18a8af736d6
867
py
Python
TelloStuff/Tests/Tello.py
svg94/Drone_Prototype-dirty-implementation-
53ea429714beff6966c2b9c82e0c96d53baca66c
[ "MIT" ]
null
null
null
TelloStuff/Tests/Tello.py
svg94/Drone_Prototype-dirty-implementation-
53ea429714beff6966c2b9c82e0c96d53baca66c
[ "MIT" ]
null
null
null
TelloStuff/Tests/Tello.py
svg94/Drone_Prototype-dirty-implementation-
53ea429714beff6966c2b9c82e0c96d53baca66c
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 from TelloSDKPy.djitellopy.tello import Tello import cv2 import pygame import numpy as np import time def main(): #Controller Init pygame.init() joysticks = [] for i in range(0,pygame.joystick.get_count()): joysticks.append(pygame.joystick.Joystick(i)) joysticks[-1].init() print(joysticks[-1].get_name()) #Tello Init while True: for event in pygame.event.get(): if(event.type == pygame.JOYBUTTONDOWN): b = event.button if (b == 0): print("takeoff") drone.takeoff() elif (b == 1): print("land") drone.land() elif (b == 2): print("quit") return 0 if __name__== "__main__": main()
24.083333
53
0.49827
93
867
4.537634
0.505376
0.052133
0
0
0
0
0
0
0
0
0
0.016854
0.384083
867
35
54
24.771429
0.773408
0.053057
0
0
0
0
0.028186
0
0
0
0
0
0
1
0.037037
false
0
0.185185
0
0.259259
0.148148
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c63ed36ee241e548d81bdd20f997dcd995f3ec78
11,761
py
Python
models/SPR.py
fresh-professor/DiverseCont
4be198f5531a7efe2cb91b17066322a38d219127
[ "MIT" ]
21
2021-09-08T14:37:06.000Z
2022-02-28T02:58:35.000Z
models/SPR.py
fresh-professor/DiverseCont
4be198f5531a7efe2cb91b17066322a38d219127
[ "MIT" ]
1
2021-12-28T09:17:38.000Z
2021-12-28T11:49:30.000Z
models/SPR.py
fresh-professor/DiverseCont
4be198f5531a7efe2cb91b17066322a38d219127
[ "MIT" ]
null
null
null
import os from copy import deepcopy import tqdm import torch import torch.nn.functional as F import colorful import numpy as np import networkx as nx from tensorboardX import SummaryWriter from .reservoir import reservoir from components import Net from utils import BetaMixture1D class SPR(torch.nn.Module): """ Train Continual Model self-supervisedly Freeze when required to eval and finetune supervisedly using Purified Buffer. """ def __init__(self, config, writer: SummaryWriter): super().__init__() self.config = config self.device = config['device'] self.writer = writer self.purified_buffer = reservoir['purified'](config, config['purified_buffer_size'], config['purified_buffer_q_poa']) self.delay_buffer = reservoir['delay'](config, config['delayed_buffer_size'], config['delayed_buffer_q_poa']) self.E_max = config['E_max'] self.expert_step = 0 self.base_step = 0 self.base_ft_step = 0 self.expert_number = 0 self.base = self.get_init_base(config) self.expert = self.get_init_expert(config) self.ssl_dir = os.path.join(os.path.dirname(os.path.dirname(self.config['log_dir'])), 'noiserate_{}'.format(config['corruption_percent']), 'expt_{}'.format(config['expert_train_epochs']), 'randomseed_{}'.format(config['random_seed'])) if os.path.exists(self.ssl_dir): with open(os.path.join(self.ssl_dir, 'idx_sets.npy'), 'rb') as f: self.debug_idxs = np.load(f, allow_pickle=True) def get_init_base(self, config): """get initialized base model""" base = Net[config['net']](config) optim_config = config['optimizer'] lr_scheduler_config = deepcopy(config['lr_scheduler']) lr_scheduler_config['options'].update({'T_max': config['base_train_epochs']}) base.setup_optimizer(optim_config) base.setup_lr_scheduler(lr_scheduler_config) return base def get_init_expert(self, config): """get initialized expert model""" expert = Net[config['net']](config) optim_config = config['optimizer'] lr_scheduler_config = deepcopy(config['lr_scheduler']) lr_scheduler_config['options'].update({'T_max': config['expert_train_epochs']}) expert.setup_optimizer(optim_config) expert.setup_lr_scheduler(lr_scheduler_config) return expert def get_init_base_ft(self, config): """get initialized eval model""" base_ft = Net[config['net'] + '_ft'](config) optim_config = config['optimizer_ft'] lr_scheduler_config = config['lr_scheduler_ft'] base_ft.setup_optimizer(optim_config) base_ft.setup_lr_scheduler(lr_scheduler_config) return base_ft def learn(self, x, y, corrupt, idx, step=None): x, y = x.cuda(), y.cuda() for i in range(len(x)): self.delay_buffer.update(imgs=x[i: i + 1], cats=y[i: i + 1], corrupts=corrupt[i: i + 1], idxs=idx[i: i + 1]) if self.delay_buffer.is_full(): if not os.path.exists(os.path.join(self.ssl_dir, 'model{}.ckpt'.format(self.expert_number))): self.expert = self.get_init_expert(self.config) self.train_self_expert() else: self.expert.load_state_dict( torch.load(os.path.join(self.ssl_dir, 'model{}.ckpt'.format(self.expert_number)), map_location=self.device)) ################### data consistency check ###################### if torch.sum(self.delay_buffer.get('idxs') != torch.Tensor(self.debug_idxs[self.expert_number])) != 0: raise Exception("it seems there is a data consistency problem: exp_num {}".format(self.expert_number)) ################### data consistency check ###################### self.train_self_base() clean_idx, clean_p = self.cluster_and_sample() self.update_purified_buffer(clean_idx, clean_p, step) self.expert_number += 1 def update_purified_buffer(self, clean_idx, clean_p, step): """update purified buffer with the filtered samples""" self.purified_buffer.update( imgs=self.delay_buffer.get('imgs')[clean_idx], cats=self.delay_buffer.get('cats')[clean_idx], corrupts=self.delay_buffer.get('corrupts')[clean_idx], idxs=self.delay_buffer.get('idxs')[clean_idx], clean_ps=clean_p) self.delay_buffer.reset() print(colorful.bold_yellow(self.purified_buffer.state('corrupts')).styled_string) self.writer.add_scalar( 'buffer_corrupts', torch.sum(self.purified_buffer.get('corrupts')), step) def cluster_and_sample(self): """filter samples in delay buffer""" self.expert.eval() with torch.no_grad(): xs = self.delay_buffer.get('imgs') ys = self.delay_buffer.get('cats') corrs = self.delay_buffer.get('corrupts') features = self.expert(xs) features = F.normalize(features, dim=1) clean_p = list() clean_idx = list() print("***********************************************") for u_y in torch.unique(ys).tolist(): y_mask = ys == u_y corr = corrs[y_mask] feature = features[y_mask] # ignore negative similairties _similarity_matrix = torch.relu(F.cosine_similarity(feature.unsqueeze(1), feature.unsqueeze(0), dim=-1)) # stochastic ensemble _clean_ps = torch.zeros((self.E_max, len(feature)), dtype=torch.double) for _i in range(self.E_max): similarity_matrix = (_similarity_matrix > torch.rand_like(_similarity_matrix)).type(torch.float32) similarity_matrix[similarity_matrix == 0] = 1e-5 # add small num for ensuring positive matrix g = nx.from_numpy_matrix(similarity_matrix.cpu().numpy()) info = nx.eigenvector_centrality(g, max_iter=6000, weight='weight') # index: value centrality = [info[i] for i in range(len(info))] bmm_model = BetaMixture1D(max_iters=10) # fit beta mixture model c = np.asarray(centrality) c, c_min, c_max = bmm_model.outlier_remove(c) c = bmm_model.normalize(c, c_min, c_max) bmm_model.fit(c) bmm_model.create_lookup(1) # 0: noisy, 1: clean # get posterior c = np.asarray(centrality) c = bmm_model.normalize(c, c_min, c_max) p = bmm_model.look_lookup(c) _clean_ps[_i] = torch.from_numpy(p) _clean_ps = torch.mean(_clean_ps, dim=0) m = _clean_ps > torch.rand_like(_clean_ps) clean_idx.extend(torch.nonzero(y_mask)[:, -1][m].tolist()) clean_p.extend(_clean_ps[m].tolist()) print("class: {}".format(u_y)) print("--- num of selected samples: {}".format(torch.sum(m).item())) print("--- num of selected corrupt samples: {}".format(torch.sum(corr[m]).item())) print("***********************************************") return clean_idx, torch.Tensor(clean_p) def train_self_base(self): """Self Replay. train base model with samples from delay and purified buffer""" bs = self.config['base_batch_size'] # If purified buffer is full, train using it also db_bs = (bs // 2) if self.purified_buffer.is_full() else bs db_bs = min(db_bs, len(self.delay_buffer)) pb_bs = min(bs - db_bs, len(self.purified_buffer)) self.base.train() self.base.init_ntxent(self.config, batch_size=db_bs + pb_bs) dataloader = self.delay_buffer.get_dataloader(batch_size=db_bs, shuffle=True, drop_last=True) for epoch_i in tqdm.trange(self.config['base_train_epochs'], desc="base training", leave=False): for inner_step, data in enumerate(dataloader): x = data['imgs'] self.base.zero_grad() # sample data from purified buffer and merge if pb_bs > 0: replay_data = self.purified_buffer.sample(num=pb_bs) x = torch.cat([replay_data['imgs'], x], dim=0) loss = self.base.get_selfsup_loss(x) loss.backward() self.base.optimizer.step() self.writer.add_scalar( 'continual_base_train_loss', loss, self.base_step + inner_step + epoch_i * len(dataloader)) # warmup for the first 10 epochs if epoch_i >= 10: self.base.lr_scheduler.step() self.writer.flush() self.base_step += self.config['base_train_epochs'] * len(dataloader) def train_self_expert(self): """train expert model with samples from delay""" batch_size =min(self.config['expert_batch_size'], len(self.delay_buffer)) self.expert.train() self.expert.init_ntxent(self.config, batch_size=batch_size) dataloader = self.delay_buffer.get_dataloader(batch_size=batch_size, shuffle=True, drop_last=True) for epoch_i in tqdm.trange(self.config['expert_train_epochs'], desc='expert training', leave=False): for inner_step, data in enumerate(dataloader): x = data['imgs'] self.expert.zero_grad() loss = self.expert.get_selfsup_loss(x) loss.backward() self.expert.optimizer.step() self.writer.add_scalar( 'expert_train_loss', loss, self.expert_step + inner_step + len(dataloader) * epoch_i) # warmup for the first 10 epochs if epoch_i >= 10: self.expert.lr_scheduler.step() self.writer.flush() self.expert_step += self.config['expert_train_epochs'] * len(dataloader) def get_finetuned_model(self): """copy the base and fine-tune for evaluation""" base_ft = self.get_init_base_ft(self.config) # overwrite entries in the state dict ft_dict = base_ft.state_dict() ft_dict.update({k: v for k, v in self.base.state_dict().items() if k in ft_dict}) base_ft.load_state_dict(ft_dict) base_ft.train() dataloader = self.purified_buffer.get_dataloader(batch_size=self.config['ft_batch_size'], shuffle=True, drop_last=True) for epoch_i in tqdm.trange(self.config['ft_epochs'], desc='finetuning', leave=False): for inner_step, data in enumerate(dataloader): x, y = data['imgs'], data['cats'] base_ft.zero_grad() loss = base_ft.get_sup_loss(x, y).mean() loss.backward() base_ft.clip_grad() base_ft.optimizer.step() base_ft.lr_scheduler.step() self.writer.add_scalar( 'ft_train_loss', loss, self.base_ft_step + inner_step + epoch_i * len(dataloader)) self.writer.flush() self.base_ft_step += self.config['ft_epochs'] * len(dataloader) base_ft.eval() return base_ft def forward(self, x): pass
43.884328
127
0.585239
1,452
11,761
4.5
0.184573
0.03367
0.036731
0.027548
0.348944
0.240588
0.197123
0.157637
0.130089
0.121824
0
0.005139
0.288581
11,761
267
128
44.048689
0.775786
0.071337
0
0.147208
0
0
0.085802
0.013
0
0
0
0
0
1
0.055838
false
0.005076
0.060914
0
0.147208
0.030457
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c640ef3189a49dcfa1947c8d0c9f7d5961226015
6,602
py
Python
tests/pyunity/testScene/testScene.py
rayzchen/PyUnity
8ed436eca7a84f05190c1fa275c58da5c6059926
[ "MIT" ]
null
null
null
tests/pyunity/testScene/testScene.py
rayzchen/PyUnity
8ed436eca7a84f05190c1fa275c58da5c6059926
[ "MIT" ]
null
null
null
tests/pyunity/testScene/testScene.py
rayzchen/PyUnity
8ed436eca7a84f05190c1fa275c58da5c6059926
[ "MIT" ]
null
null
null
# Copyright (c) 2020-2022 The PyUnity Team # This file is licensed under the MIT License. # See https://docs.pyunity.x10.bz/en/latest/license.html from pyunity import ( SceneManager, Component, Camera, AudioListener, Light, GameObject, Tag, Transform, GameObjectException, ComponentException, Canvas, PyUnityException, Behaviour, ShowInInspector, RenderTarget, Logger, Vector3, MeshRenderer, Mesh) from . import SceneTestCase class TestScene(SceneTestCase): def testInit(self): scene = SceneManager.AddScene("Scene") assert scene.name == "Scene" assert len(scene.gameObjects) == 2 for gameObject in scene.gameObjects: assert gameObject.scene is scene for component in gameObject.components: assert component.gameObject is gameObject assert component.transform is gameObject.transform assert isinstance(component, Component) assert scene.gameObjects[0].name == "Main Camera" assert scene.gameObjects[1].name == "Light" assert scene.mainCamera is scene.gameObjects[0].components[1] assert len(scene.gameObjects[0].components) == 3 assert len(scene.gameObjects[1].components) == 2 assert scene.gameObjects[0].GetComponent(Camera) is not None assert scene.gameObjects[0].GetComponent(AudioListener) is not None assert scene.gameObjects[1].GetComponent(Light) is not None def testFind(self): scene = SceneManager.AddScene("Scene") a = GameObject("A") b = GameObject("B", a) c = GameObject("C", a) d = GameObject("B", c) scene.AddMultiple(a, b, c, d) tagnum = Tag.AddTag("Custom Tag") a.tag = Tag(tagnum) c.tag = Tag("Custom Tag") assert len(scene.FindGameObjectsByName("B")) == 2 assert scene.FindGameObjectsByName("B") == [b, d] assert scene.FindGameObjectsByTagName("Custom Tag") == [a, c] assert scene.FindGameObjectsByTagNumber(tagnum) == [a, c] assert isinstance(scene.FindComponent(Transform), Transform) assert scene.FindComponents(Transform) == [ scene.mainCamera.transform, scene.gameObjects[1].transform, a.transform, b.transform, c.transform, d.transform] with self.assertRaises(GameObjectException) as exc: scene.FindGameObjectsByTagName("Invalid") assert exc.value == "No tag named Invalid; create a new tag with Tag.AddTag" with self.assertRaises(GameObjectException) as exc: scene.FindGameObjectsByTagNumber(-1) assert exc.value == "No tag at index -1; create a new tag with Tag.AddTag" with self.assertRaises(ComponentException) as exc: scene.FindComponent(Canvas) assert exc.value == "Cannot find component Canvas in scene" def testRootGameObjects(self): scene = SceneManager.AddScene("Scene") a = GameObject("A") b = GameObject("B", a) c = GameObject("C", a) d = GameObject("B", c) scene.AddMultiple(a, b, c, d) assert len(scene.rootGameObjects) == 3 assert scene.rootGameObjects[2] is a def testAddError(self): scene = SceneManager.AddScene("Scene") gameObject = GameObject("GameObject") scene.Add(gameObject) with self.assertRaises(PyUnityException) as exc: scene.Add(gameObject) assert exc.value == "GameObject \"GameObject\" is already in Scene \"Scene\"" def testBare(self): from pyunity.scenes import Scene scene = Scene.Bare("Scene") assert scene.name == "Scene" assert len(scene.gameObjects) == 0 assert scene.mainCamera is None def testDestroy(self): class Test(Behaviour): other = ShowInInspector(GameObject) scene = SceneManager.AddScene("Scene") # Exception fake = GameObject("Not in scene") with self.assertRaises(PyUnityException) as exc: scene.Destroy(fake) assert exc.value == "The provided GameObject is not part of the Scene" # Correct a = GameObject("A") b = GameObject("B", a) c = GameObject("C", a) scene.AddMultiple(a, b, c) assert c.scene is scene assert c in scene.gameObjects scene.Destroy(c) assert c.scene is None assert c not in scene.gameObjects # Multiple scene.Destroy(a) assert b.scene is None assert b not in scene.gameObjects assert c.scene is None assert c not in scene.gameObjects # Components cam = GameObject("Camera") camera = cam.AddComponent(Camera) test = GameObject("Test") test.AddComponent(Test).other = cam target = GameObject("Target") target.AddComponent(RenderTarget).source = camera scene.AddMultiple(cam, test, target) scene.Destroy(cam) assert b.scene is None assert cam not in scene.gameObjects assert test.GetComponent(Test).other is None assert target.GetComponent(RenderTarget).source is None # Main Camera with Logger.TempRedirect(silent=True) as r: scene.Destroy(scene.mainCamera.gameObject) assert r.get() == "Warning: Removing Main Camera from scene 'Scene'\n" def testHas(self): scene = SceneManager.AddScene("Scene") gameObject = GameObject("GameObject") gameObject2 = GameObject("GameObject 2") scene.Add(gameObject) assert scene.Has(gameObject) assert not scene.Has(gameObject2) def testList(self): scene = SceneManager.AddScene("Scene") a = GameObject("A") b = GameObject("B", a) c = GameObject("C", a) d = GameObject("B", c) scene.AddMultiple(b, d, c, a) with Logger.TempRedirect(silent=True) as r: scene.List() assert r.get() == "\n".join([ "/A", "/A/B", "/A/C", "/A/C/B", "/Light", "/Main Camera\n"]) def testInsideFrustrum(self): scene = SceneManager.AddScene("Scene") gameObject = GameObject("Cube") gameObject.transform.position = Vector3(0, 0, 5) renderer = gameObject.AddComponent(MeshRenderer) scene.Add(gameObject) assert not scene.insideFrustrum(renderer) renderer.mesh = Mesh.cube(2) # assert scene.insideFrustrum(renderer)) gameObject.transform.position = Vector3(0, 0, -5) # assert not scene.insideFrustrum(renderer)
36.882682
85
0.628294
735
6,602
5.643537
0.187755
0.065574
0.048216
0.057859
0.372469
0.301109
0.27459
0.202748
0.152604
0.128496
0
0.008656
0.265071
6,602
178
86
37.089888
0.846249
0.041048
0
0.323741
0
0
0.07943
0
0
0
0
0
0.374101
1
0.064748
false
0
0.021583
0
0.100719
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c64201468eb9a627a5893c74a3ccfcc9bf284d58
1,806
py
Python
alembic_migration/alembic_handler.py
NASA-IMPACT/hls-sentinel2-downloader-serverless
e3e4f542fc805c6259f20a6dd932c98cccd4144c
[ "Apache-2.0" ]
null
null
null
alembic_migration/alembic_handler.py
NASA-IMPACT/hls-sentinel2-downloader-serverless
e3e4f542fc805c6259f20a6dd932c98cccd4144c
[ "Apache-2.0" ]
2
2021-07-23T00:49:42.000Z
2021-07-23T00:51:25.000Z
alembic_migration/alembic_handler.py
NASA-IMPACT/hls-sentinel2-downloader-serverless
e3e4f542fc805c6259f20a6dd932c98cccd4144c
[ "Apache-2.0" ]
null
null
null
import logging import os import alembic.command import alembic.config import cfnresponse from db.session import get_session, get_session_maker from retry import retry from sqlalchemy.exc import OperationalError def log(log_statement: str): """ Gets a Logger for the Lambda function with level logging.INFO and logs `log_statement`. This is used multiple times as Alembic takes over the logging configuration so we have to re-take control when we want to log :param log_statement: str to log """ logger = logging.getLogger() logger.setLevel(logging.INFO) logger.info(log_statement) @retry(OperationalError, tries=30, delay=10) def check_rds_connection(): session_maker = get_session_maker() with get_session(session_maker) as db: db.execute("SELECT * FROM pg_catalog.pg_tables;") def handler(event, context): if event["RequestType"] == "Delete": log("Received a Delete Request") cfnresponse.send( event, context, cfnresponse.SUCCESS, {"Response": "Nothing run on deletes"} ) return try: log("Checking connection to RDS") check_rds_connection() log("Connected to RDS") log("Running Alembic Migrations") alembic_config = alembic.config.Config(os.path.join(".", "alembic.ini")) alembic_config.set_main_option("script_location", ".") alembic.command.upgrade(alembic_config, "head") log("Migrations run successfully") cfnresponse.send( event, context, cfnresponse.SUCCESS, {"Response": "Migrations run successfully"}, ) except Exception as ex: log(str(ex)) cfnresponse.send(event, context, cfnresponse.FAILED, {"Response": str(ex)}) raise ex
30.1
87
0.668328
218
1,806
5.426606
0.46789
0.054945
0.050719
0.06847
0.121724
0.089603
0.089603
0
0
0
0
0.002899
0.23588
1,806
59
88
30.610169
0.854348
0.136213
0
0.046512
0
0
0.180809
0.013708
0
0
0
0
0
1
0.069767
false
0
0.186047
0
0.27907
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c642cc7668f9eaa2a24f87fd2cd2fe18ccbe3844
8,988
py
Python
booksoai/oaipmh.py
scieloorg/books-oai
b0114f452c2bddb00ce6414a6926c57b548fb46a
[ "BSD-2-Clause" ]
1
2019-03-16T04:44:08.000Z
2019-03-16T04:44:08.000Z
booksoai/oaipmh.py
DalavanCloud/books-oai
b0114f452c2bddb00ce6414a6926c57b548fb46a
[ "BSD-2-Clause" ]
2
2016-06-06T18:04:31.000Z
2018-02-02T15:26:54.000Z
booksoai/oaipmh.py
DalavanCloud/books-oai
b0114f452c2bddb00ce6414a6926c57b548fb46a
[ "BSD-2-Clause" ]
2
2016-06-06T18:03:54.000Z
2019-03-16T04:43:56.000Z
from __future__ import unicode_literals import plumber from lxml import etree from datetime import datetime import pipeline class BadArgumentError(Exception): """Raised when a Verb receives wrong args.""" class CannotDisseminateFormatError(Exception): """Raised when metadata format is not supported""" class BadVerbError(Exception): """Raised when invalid verb is used""" class IDDoesNotExistError(Exception): """Raised when identifier does not exists""" class NoRecordsMatchError(Exception): """ Raised when all parameters combined result in empty list of records """ class BadResumptionTokenError(Exception): """Raised when invalid resumption token is used""" class IdentifyVerb(object): data = { 'repositoryName': 'SciELO Books', 'protocolVersion': '2.0', 'adminEmail': 'scielo.books@scielo.org', 'deletedRecord': 'persistent', 'granularity': 'YYYY-MM-DD' } allowed_args = set(('verb',)) def __init__(self, last_book, request_kwargs, base_url): if set(request_kwargs) != self.allowed_args: raise BadArgumentError() self.data['request'] = request_kwargs self.data['baseURL'] = base_url self.data['earliestDatestamp'] = last_book.get('updated', datetime.now().date().isoformat()) def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.IdentifyNodePipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class ListMetadataFormatsVerb(object): data = { 'formats': [ { 'prefix': 'oai_dc', 'schema': 'http://www.openarchives.org/OAI/2.0/oai_dc.xsd', 'namespace': 'http://www.openarchives.org/OAI/2.0/oai_dc/' } ] } allowed_args = set(('identifier', 'verb')) def __init__(self, request_kwargs, base_url): diff = set(request_kwargs) - self.allowed_args if diff: raise BadArgumentError() self.data['request'] = request_kwargs self.data['baseURL'] = base_url def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.ListMetadataFormatsPipe(), pipeline.MetadataFormatPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class ListIdentifiersVerb(object): allowed_args = set(('from', 'until', 'set', 'resumptionToken', 'metadataPrefix', 'verb')) def __init__(self, books, request_kwargs, base_url): request_set = set(request_kwargs) diff = request_set - self.allowed_args if not 'resumptionToken' in request_set and not 'metadataPrefix' in request_set: raise BadArgumentError() if diff: raise BadArgumentError() self.data = { 'request': request_kwargs, 'baseURL': base_url, 'books': books, } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.ListIdentifiersPipe(), pipeline.TearDownPipe() ) result = ppl.run([self.data]) return next(result) class ListSetsVerb(object): allowed_args = set(('resumptionToken', 'verb')) def __init__(self, books, request_kwargs, base_url): diff = set(request_kwargs) - self.allowed_args if diff: raise BadArgumentError() self.data = { 'request': request_kwargs, 'baseURL': base_url, 'books': books.distinct('publisher'), } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.ListSetsPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class GetRecordVerb(object): required_args = set(('identifier', 'metadataPrefix', 'verb')) def __init__(self, books, request_kwargs, base_url): if set(request_kwargs) != self.required_args: raise BadArgumentError() self.data = { 'request': request_kwargs, 'baseURL': base_url, 'books': books } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.GetRecordPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class ListRecordsVerb(object): allowed_args = set(('from', 'until', 'set', 'resumptionToken', 'metadataPrefix', 'verb')) def __init__(self, books, request_kwargs, base_url): request_set = set(request_kwargs) diff = request_set - self.allowed_args if not 'resumptionToken' in request_set and not 'metadataPrefix' in request_set: raise BadArgumentError() if diff: raise BadArgumentError() self.data = { 'request': request_kwargs, 'baseURL': base_url, 'books': books, } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.ListRecordsPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class CannotDisseminateFormat(object): def __init__(self, request_kwargs, base_url): self.data = { 'request': request_kwargs, 'baseURL': base_url, } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.MetadataFormatErrorPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class BadVerb(object): def __init__(self, request_kwargs, base_url): self.data = { 'request': request_kwargs, 'baseURL': base_url, } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.BadVerbPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class IDDoesNotExist(object): def __init__(self, request_kwargs, base_url): self.data = { 'request': request_kwargs, 'baseURL': base_url, } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.IdNotExistPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class NoRecordsMatch(object): def __init__(self, request_kwargs, base_url): self.data = { 'request': request_kwargs, 'baseURL': base_url, } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.NoRecordsPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class BadArgument(object): def __init__(self, request_kwargs, base_url, books=None): self.data = { 'request': request_kwargs, 'baseURL': base_url, } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.BadArgumentPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results) class BadResumptionToken(object): def __init__(self, request_kwargs, base_url, books=None): self.data = { 'request': request_kwargs, 'baseURL': base_url, } def __str__(self): ppl = plumber.Pipeline( pipeline.SetupPipe(), pipeline.ResponseDatePipe(), pipeline.RequestPipe(), pipeline.BadResumptionTokenPipe(), pipeline.TearDownPipe() ) results = ppl.run([self.data]) return next(results)
24.897507
100
0.576435
800
8,988
6.25125
0.17
0.077984
0.026395
0.04799
0.726655
0.726655
0.720456
0.718256
0.716657
0.687063
0
0.00097
0.311972
8,988
360
101
24.966667
0.80773
0.029929
0
0.662651
0
0
0.078165
0.002652
0
0
0
0
0
1
0.096386
false
0
0.02008
0
0.269076
0
0
0
0
null
0
0
0
0
1
1
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
5
c642eb175ecb18dbaa59adf93fe2e5472ccf50d1
1,229
py
Python
ch2/q25solution.py
kylepw/ctci
7e2fcc6775db3789d0e425f4fb969acf6c44aad5
[ "MIT" ]
null
null
null
ch2/q25solution.py
kylepw/ctci
7e2fcc6775db3789d0e425f4fb969acf6c44aad5
[ "MIT" ]
null
null
null
ch2/q25solution.py
kylepw/ctci
7e2fcc6775db3789d0e425f4fb969acf6c44aad5
[ "MIT" ]
null
null
null
from LinkedList import LinkedList def sum_lists(ll_a, ll_b): n1, n2 = ll_a.head, ll_b.head ll = LinkedList() carry = 0 while n1 or n2: result = carry if n1: result += n1.value n1 = n1.next if n2: result += n2.value n2 = n2.next ll.add(result % 10) carry = result // 10 if carry: ll.add(carry) return ll def sum_lists_followup(ll_a, ll_b): # Pad the shorter list with zeros if len(ll_a) < len(ll_b): for i in range(len(ll_b) - len(ll_a)): ll_a.add_to_beginning(0) else: for i in range(len(ll_a) - len(ll_b)): ll_b.add_to_beginning(0) # Find sum n1, n2 = ll_a.head, ll_b.head result = 0 while n1 and n2: result = (result * 10) + n1.value + n2.value n1 = n1.next n2 = n2.next # Create new linked list ll = LinkedList() ll.add_multiple([int(i) for i in str(result)]) return ll ll_a = LinkedList() ll_a.generate(4, 0, 9) ll_b = LinkedList() ll_b.generate(3, 0, 9) print(ll_a) print(ll_b) #print(sum_lists(ll_a, ll_b)) print(sum_lists_recursive(ll_a, ll_b)) #print(sum_lists_followup(ll_a, ll_b))
21.561404
52
0.570382
207
1,229
3.188406
0.251208
0.063636
0.045455
0.045455
0.289394
0.277273
0.166667
0.054545
0
0
0
0.045077
0.314076
1,229
57
53
21.561404
0.737841
0.10415
0
0.243902
0
0
0
0
0
0
0
0
0
1
0.04878
false
0
0.02439
0
0.121951
0.073171
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c646039bec76cea06e642add68741d31531aa8e2
5,147
py
Python
cmdb-compliance/libs/server/server_common.py
zjj1002/aws-cloud-cmdb-system
47982007688e5db1272435891cb654ab11d0d60a
[ "Apache-2.0" ]
null
null
null
cmdb-compliance/libs/server/server_common.py
zjj1002/aws-cloud-cmdb-system
47982007688e5db1272435891cb654ab11d0d60a
[ "Apache-2.0" ]
1
2022-01-04T13:53:16.000Z
2022-01-04T13:53:16.000Z
cmdb-optimization/libs/server/server_common.py
zjj1002/aws-cloud-cmdb-system
47982007688e5db1272435891cb654ab11d0d60a
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/5/15 14:44 # @Author : Fred Yangxiaofei # @File : server_common.py # @Role : server公用方法,记录日志,更新资产,推送密钥,主要给手动更新资产使用 from models.server import Server, AssetErrorLog, ServerDetail from libs.db_context import DBContext from libs.web_logs import ins_log from libs.server.sync_public_key import RsyncPublicKey, start_rsync import sqlalchemy def write_error_log(error_list): with DBContext('w') as session: for i in error_list: ip = i.get('ip') msg = i.get('msg') error_log = '推送公钥失败, 错误信息:{}'.format(msg) ins_log.read_log('error', error_log) session.query(Server).filter(Server.ip == ip).update({Server.state: 'false'}) exist_ip = session.query(AssetErrorLog).filter(AssetErrorLog.ip == ip).first() if exist_ip: session.query(AssetErrorLog).filter(AssetErrorLog.ip == ip).update( {AssetErrorLog.error_log: error_log}) else: new_error_log = AssetErrorLog(ip=ip, error_log=error_log) session.add(new_error_log) session.commit() def update_asset(asset_data): """ 更新资产到数据库 :param host_data: 主机返回的资产采集基础数据 :return: """ with DBContext('w') as session: for k, v in asset_data.items(): try: if asset_data[k].get('status'): _sn = v.get('sn', None) _hostname = v.get('host_name', None) _cpu = v.get('cpu', None) _cpu_cores = v.get('cpu_cores', None) _memory = v.get('memory', None) _disk = v.get('disk', None) _os_type = v.get('os_type', None) _os_kernel = v.get('os_kernel', None) # _instance_id = v.get('instance_id', None) # _instance_type = v.get('instance_type', None) # _instance_state = v.get('instance_state', None) exist_detail = session.query(ServerDetail).filter(ServerDetail.ip == k).first() if not exist_detail: # 不存在就新建 new_server_detail = ServerDetail(ip=k, sn=_sn, cpu=_cpu, cpu_cores=_cpu_cores, memory=_memory, disk=_disk, os_type=_os_type, os_kernel=_os_kernel) session.add(new_server_detail) session.commit() session.query(Server).filter(Server.ip == k).update( {Server.hostname: _hostname, Server.state: 'true'}) session.commit() else: # 存在就更新 session.query(ServerDetail).filter(ServerDetail.ip == k).update({ ServerDetail.sn: _sn, ServerDetail.ip: k, ServerDetail.cpu: _cpu, ServerDetail.cpu_cores: _cpu_cores, ServerDetail.disk: _disk, ServerDetail.memory: _memory, ServerDetail.os_type: _os_type, ServerDetail.os_kernel: _os_kernel, }) session.query(Server).filter(Server.ip == k).update( {Server.hostname: _hostname, Server.state: 'true'}) session.commit() except sqlalchemy.exc.IntegrityError as e: ins_log.read_log('error', e) # 状态改为Flse->删除主机Detail--记录错误信息 session.query(Server).filter(Server.ip == k).update({Server.state: 'false'}) session.query(ServerDetail).filter(ServerDetail.ip == k).delete( synchronize_session=False) exist_ip = session.query(AssetErrorLog).filter(AssetErrorLog.ip == k).first() error_log = str(e) if exist_ip: session.query(AssetErrorLog).filter(AssetErrorLog.ip == k).update( {AssetErrorLog.error_log: error_log}) else: new_error_log = AssetErrorLog(ip=k, error_log=error_log) session.add(new_error_log) session.commit() return False def rsync_public_key(server_list): """ 推送PublicKey :return: 只返回推送成功的,失败的直接写错误日志 """ # server_list = [('47.100.231.147', 22, 'root', '-----BEGIN RSA PRIVATE KEYxxxxxEND RSA PRIVATE KEY-----', 'false')] ins_log.read_log('info', 'rsync public key to server') rsync_error_list = [] rsync_sucess_list = [] sync_key_obj = RsyncPublicKey() check = sync_key_obj.check_rsa() if check: res_data = start_rsync(server_list) if not res_data.get('status'): rsync_error_list.append(res_data) else: rsync_sucess_list.append(res_data) if rsync_error_list: write_error_log(rsync_error_list) return rsync_sucess_list if __name__ == '__main__': pass
41.508065
120
0.541092
552
5,147
4.786232
0.25
0.051476
0.024603
0.036336
0.370553
0.342165
0.310371
0.259273
0.259273
0.154428
0
0.007476
0.350301
5,147
123
121
41.845528
0.782596
0.108413
0
0.244186
0
0
0.032863
0
0
0
0
0
0
1
0.034884
false
0.011628
0.05814
0
0.116279
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c6463fc79c5c1fa3ed6d7d6dc133cda7182d1756
1,607
py
Python
src/test/serialization/codec/object/test_string_codec.py
typingtanuki/pyserialization
f4a0d9cff08b3a6ce8f83f3a258c4dce1367d151
[ "Apache-2.0" ]
null
null
null
src/test/serialization/codec/object/test_string_codec.py
typingtanuki/pyserialization
f4a0d9cff08b3a6ce8f83f3a258c4dce1367d151
[ "Apache-2.0" ]
null
null
null
src/test/serialization/codec/object/test_string_codec.py
typingtanuki/pyserialization
f4a0d9cff08b3a6ce8f83f3a258c4dce1367d151
[ "Apache-2.0" ]
null
null
null
import unittest from src.main.serialization.codec.codec import Codec from src.main.serialization.codec.object.stringCodec import StringCodec from src.main.serialization.codec.primitive.shortCodec import ShortCodec from src.main.serialization.codec.utils.byteIo import ByteIo from src.main.serialization.codec.utils.bytes import to_byte from src.test.serialization.codec.test_codec import TestCodec class TestStringCodec(TestCodec): def test_wide_range(self): self.string_seria(None) self.string_seria("abc") self.string_seria("123") self.string_seria("ほげほげ") self.string_seria("漢字漢字") self.string_seria(""" % Total\t\t\t\t % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 162 0 0 0 0 0 \t\t\t 0 --:--:-- --:--:-- --:--:-- 0 100 6 0 6 0 \r\n\0\t\t\t 0 0 0 --:--:-- 0:00:09 --:--:-- 1 漢字漢字漢字漢字漢字漢字漢字漢字 漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字 漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字 漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字漢字""") def string_seria(self, value: None or str): codec: Codec[str] = StringCodec(to_byte(12), 0) writer: ByteIo = self.writer() codec.write(writer, value) writer.close() reader: ByteIo = self.reader() pim: int = codec.read(reader) self.assertEqual(value, pim) reader.close() if __name__ == '__main__': unittest.main()
40.175
116
0.654636
186
1,607
5.548387
0.365591
0.015504
0.087209
0.116279
0.161822
0.077519
0
0
0
0
0
0.02771
0.236465
1,607
39
117
41.205128
0.813366
0
0
0.0625
0
0.03125
0.357187
0.11201
0
0
0
0
0.03125
1
0.0625
false
0
0.21875
0
0.3125
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c647d169764fd3968e368f07e9481ecd112d4727
539
py
Python
dataviz/ex1.py
jonaslindemann/compute-course-public
b8f55595ebbd790d79b525efdff17b8517154796
[ "MIT" ]
4
2021-09-12T12:07:01.000Z
2021-09-29T17:38:34.000Z
dataviz/ex1.py
jonaslindemann/compute-course-public
b8f55595ebbd790d79b525efdff17b8517154796
[ "MIT" ]
null
null
null
dataviz/ex1.py
jonaslindemann/compute-course-public
b8f55595ebbd790d79b525efdff17b8517154796
[ "MIT" ]
5
2020-10-24T16:02:31.000Z
2021-09-28T20:57:46.000Z
# -*- coding: utf-8 -*- """ Created on Wed Jun 7 14:58:44 2017 @author: Jonas Lindemann """ import numpy as np import pyvtk as vtk print("Reading from uvw.dat...") xyzuvw = np.loadtxt('uvw.dat', skiprows=2) print("Converting to points and vectors") points = xyzuvw[:, 0:3].tolist() vectors = xyzuvw[:, 3:].tolist() pointdata = vtk.PointData(vtk.Vectors(vectors, name="vec1"), vtk.Vectors(vectors, name="vec2")) data = vtk.VtkData(vtk.StructuredGrid([96, 65, 48], points), pointdata) data.tofile('uvw','ascii')
24.5
96
0.654917
77
539
4.584416
0.649351
0.033994
0.096317
0.11898
0
0
0
0
0
0
0
0.053215
0.163265
539
21
97
25.666667
0.72949
0.155844
0
0
0
0
0.183529
0
0
0
0
0
0
1
0
false
0
0.2
0
0.2
0.2
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c6487ab8b368f34287f785fc89a730b8d8fe1f9f
2,237
py
Python
nginc/__init__.py
FlorianLudwig/nginc
489546d1b0190047150bf3134071aa88c64f8c3d
[ "Apache-2.0" ]
1
2015-11-01T12:16:17.000Z
2015-11-01T12:16:17.000Z
nginc/__init__.py
FlorianLudwig/nginc
489546d1b0190047150bf3134071aa88c64f8c3d
[ "Apache-2.0" ]
null
null
null
nginc/__init__.py
FlorianLudwig/nginc
489546d1b0190047150bf3134071aa88c64f8c3d
[ "Apache-2.0" ]
null
null
null
# Copyright 2014 Florian Ludwig # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import os import tempfile import subprocess import atexit import shutil import argparse import pkg_resources def start(root, address='127.0.0.1', port=8000): conf_template = pkg_resources.resource_string('nginc', 'nginx.conf') conf_template = conf_template.decode('utf-8') tmp = tempfile.mkdtemp(prefix='nginc') @atexit.register def cleanup_tmp(): shutil.rmtree(tmp) root = os.path.abspath(root) root = root.replace('"', '\\"') config = conf_template.format(tmp=tmp, root=root, port=port, address=address) conf_path = tmp + '/nginx.conf' conf_file = open(conf_path, 'w') conf_file.write(config) conf_file.close() proc = subprocess.Popen(['nginx', '-c', conf_path]) @atexit.register def cleanup_proc(): try: proc.kill() except OSError: pass return proc def main(): parser = argparse.ArgumentParser() parser.add_argument('-p', '--port', type=int, default=8000, help='port to bind to') parser.add_argument('-r', '--root', type=str, default='.', help='directory to serve, defaults to current working directory') parser.add_argument('-a', '--address', type=str, default='127.0.0.1', help='address to bind to') parser.add_argument('-A', action='store_true', help='shortcut for --address 0.0.0.0') args = parser.parse_args() address = args.address if args.A: address = '0.0.0.0' proc = start(args.root, address, args.port) try: proc.wait() except KeyboardInterrupt: proc.kill()
30.22973
89
0.646848
299
2,237
4.769231
0.464883
0.01122
0.047686
0.02244
0.050491
0.035063
0
0
0
0
0
0.021524
0.23156
2,237
73
90
30.643836
0.808028
0.246312
0
0.125
0
0
0.139354
0
0
0
0
0
0
1
0.083333
false
0.020833
0.145833
0
0.25
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c649c2159d59b04bdc795f0bcf96424017779542
1,417
py
Python
Part 2 - Regression/Section 4 - Simple Linear Regression/practice_linear_regression.py
aditya30394/Machine-Learning-A-Z
8caaf1f94f800fcc7bd594569593c4d713c32d9e
[ "MIT" ]
null
null
null
Part 2 - Regression/Section 4 - Simple Linear Regression/practice_linear_regression.py
aditya30394/Machine-Learning-A-Z
8caaf1f94f800fcc7bd594569593c4d713c32d9e
[ "MIT" ]
null
null
null
Part 2 - Regression/Section 4 - Simple Linear Regression/practice_linear_regression.py
aditya30394/Machine-Learning-A-Z
8caaf1f94f800fcc7bd594569593c4d713c32d9e
[ "MIT" ]
null
null
null
# Import important libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Read the data set dataset = pd.read_csv('Salary_Data.csv') X = dataset.iloc[:,:-1].values y = dataset.iloc[:, 1].values # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0) # There is no need to do feature scaling as the linear regression model takes # care of that for us # Fitting Simple linear regression to the training set from sklearn.linear_model import LinearRegression regressor = LinearRegression() regressor.fit(X_train, y_train) # Predicting the test set results y_pred = regressor.predict(X_test) """ Now we will visualize the results that we achieved so far """ # Visualising the Training set results plt.scatter(X_train, y_train, color='red') plt.plot(X_train, regressor.predict(X_train), color='blue') plt.title("Salary VS Experience (Training Set)") plt.xlabel("Years of Experience") plt.ylabel("Salary") plt.show() # Visualising the Test set results plt.scatter(X_test, y_test, color='red') # This is the same line as that of plt.plot(X_train, regressor.predict(X_train), color='blue') plt.plot(X_test, y_pred, color='blue') plt.title("Salary VS Experience (Test Set)") plt.xlabel("Years of Experience") plt.ylabel("Salary") plt.show()
32.953488
94
0.762879
234
1,417
4.5
0.371795
0.039886
0.039886
0.034188
0.281102
0.241216
0.241216
0.186135
0.186135
0.186135
0
0.004058
0.130558
1,417
43
95
32.953488
0.850649
0.314749
0
0.25
0
0
0.16183
0
0
0
0
0
0
1
0
false
0
0.208333
0
0.208333
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c64c0a450e0399b2acbc4deba8555735fd48b6da
1,853
py
Python
source/source_test.py
mengwangk/myinvestor-toolkit
3dca9e1accfccf1583dcdbec80d1a0fe9dae2e81
[ "MIT" ]
7
2019-10-13T18:58:33.000Z
2021-08-07T12:46:22.000Z
source/source_test.py
mengwangk/myinvestor-toolkit
3dca9e1accfccf1583dcdbec80d1a0fe9dae2e81
[ "MIT" ]
7
2019-12-16T21:25:34.000Z
2022-02-10T00:11:22.000Z
source/source_test.py
mengwangk/myinvestor-toolkit
3dca9e1accfccf1583dcdbec80d1a0fe9dae2e81
[ "MIT" ]
4
2020-02-01T11:23:51.000Z
2021-12-13T12:27:18.000Z
# -*- coding: utf-8 -*- """Test for various sources Supported sources - Yahoo Finance - I3Investor - KLSe """ import datetime as dt import string import unittest from source import YahooFinanceSource, GoogleFinanceSource class SourceTest(unittest.TestCase): _TEST_YAHOO_FINANCE_SYMBOL = '6742.KL' _YAHOO_FINANCE_SOURCE = YahooFinanceSource(_TEST_YAHOO_FINANCE_SYMBOL) _TEST_GOOGLE_FINANCE_SYMBOL = "ytlpowr" _GOOGLE_FINANCE_SOURCE = GoogleFinanceSource(_TEST_GOOGLE_FINANCE_SYMBOL) _TODAY = dt.datetime.today().strftime('%Y-%m-%d') @unittest.skip def test_yahoo_get_stock_prices(self): print("Getting historical prices") # Get historical stock data historical_data = self._YAHOO_FINANCE_SOURCE.get_historical_stock_data('2016-05-15', self._TODAY, 'daily') print(historical_data) # prices = historical_data[self._TEST_SYMBOL]['prices'] # print(prices) # for price in prices: # print(price.get('close', None)) # Get current price # current_price = yahoo_finance_source.get_current_price() # print(current_price) @unittest.skip def test_yahoo_get_dividend_history(self): print("Getting historical dividends") dividend_data = self._YAHOO_FINANCE_SOURCE.get_historical_stock_dividend_data('2010-05-15', self._TODAY, 'daily') print(dividend_data) @unittest.skip def test_genereate_a_to_z(self): for c in string.ascii_uppercase: print(c) def test_google_finance_get_stock_prices(self): print("Getting historical prices") historical_prices = self._GOOGLE_FINANCE_SOURCE.get_stock_historical_prices("2010-05-15", self._TODAY) print(historical_prices)
30.377049
114
0.679439
213
1,853
5.544601
0.305164
0.071126
0.060965
0.048264
0.252329
0.234547
0.152413
0.152413
0
0
0
0.021097
0.232596
1,853
60
115
30.883333
0.809423
0.188343
0
0.172414
0
0
0.094086
0
0
0
0
0
0
1
0.137931
false
0
0.137931
0
0.482759
0.241379
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c64e4b280de8cd0b21024951fd1499e577dd81d6
2,197
py
Python
solver.py
n8henrie/knapsack
c52179e43a833d57f0df185d5d225444d1725204
[ "MIT" ]
null
null
null
solver.py
n8henrie/knapsack
c52179e43a833d57f0df185d5d225444d1725204
[ "MIT" ]
null
null
null
solver.py
n8henrie/knapsack
c52179e43a833d57f0df185d5d225444d1725204
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 from collections import namedtuple from itertools import combinations import knapsack def solve_it(input_data, language="rust"): if language == "python": return solve_it_python(input_data) return solve_it_rust(input_data) def solve_it_rust(input_data): return knapsack.solve(input_data) Item = namedtuple("Item", ["index", "value", "weight"]) def solve_it_python(input_data): print("running in python", file=sys.stderr) # parse the input lines = input_data.split("\n") firstLine = lines[0].split() item_count = int(firstLine[0]) capacity = int(firstLine[1]) items = [] for i in range(1, item_count + 1): line = lines[i] parts = line.split() items.append(Item(i - 1, int(parts[0]), int(parts[1]))) # a trivial algorithm for filling the knapsack # it takes items in-order until the knapsack is full value = 0 taken = [0] * len(items) all_combinations = ( comb for n in range(1, len(items) + 1) for comb in combinations(items, n) ) small_enough = ( comb for comb in all_combinations if sum(item.weight for item in comb) <= capacity ) winner = max(small_enough, key=lambda items: sum(i.value for i in items)) value = sum(i.value for i in winner) for idx, item in enumerate(items): if item in winner: taken[idx] = 1 # prepare the solution in the specified output format output_data = str(value) + " " + str(1) + "\n" output_data += " ".join(map(str, taken)) return output_data if __name__ == "__main__": import sys if len(sys.argv) > 1: file_location = sys.argv[1].strip() with open(file_location, "r") as input_data_file: input_data = input_data_file.read() if len(sys.argv) > 2: language = sys.argv[2].lower().strip() print(solve_it(input_data, language=language)) else: print(solve_it(input_data)) else: print( "This test requires an input file. Please select one from the data directory. (i.e. python solver.py ./data/ks_4_0)" )
26.46988
129
0.61766
308
2,197
4.256494
0.340909
0.08238
0.022883
0.036613
0.143402
0.022883
0
0
0
0
0
0.01306
0.268093
2,197
82
130
26.792683
0.802239
0.084206
0
0.071429
0
0.017857
0.088191
0
0
0
0
0
0
1
0.053571
false
0
0.071429
0.017857
0.196429
0.071429
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c65170e65e760d40c99c948a36c0e972a977e113
3,765
py
Python
api/mon/utils.py
klebed/esdc-ce
2c9e4591f344247d345a83880ba86777bb794460
[ "Apache-2.0" ]
97
2016-11-15T14:44:23.000Z
2022-03-13T18:09:15.000Z
api/mon/utils.py
klebed/esdc-ce
2c9e4591f344247d345a83880ba86777bb794460
[ "Apache-2.0" ]
334
2016-11-17T19:56:57.000Z
2022-03-18T10:45:53.000Z
api/mon/utils.py
klebed/esdc-ce
2c9e4591f344247d345a83880ba86777bb794460
[ "Apache-2.0" ]
33
2017-01-02T16:04:13.000Z
2022-02-07T19:20:24.000Z
from django.conf import settings from api.task.internal import InternalTask from api.task.response import mgmt_task_response from vms.utils import AttrDict from vms.models import Vm from que import TG_DC_UNBOUND, TG_DC_BOUND class MonitoringGraph(AttrDict): """ Monitoring graph configuration. """ def __init__(self, name, **params): dict.__init__(self) self['name'] = name self['params'] = params # noinspection PyAbstractClass class MonInternalTask(InternalTask): """ Internal zabbix tasks. """ abstract = True def call(self, *args, **kwargs): # Monitoring is completely disabled if not settings.MON_ZABBIX_ENABLED: return None # Remove unused/useless parameters kwargs.pop('old_json_active', None) return super(MonInternalTask, self).call(*args, **kwargs) def get_mon_vms(sr=('dc',), order_by=('hostname',), **filters): """Return iterator of Vm objects which are monitoring by an internal Zabbix""" filters['slavevm__isnull'] = True vms = Vm.objects.select_related(*sr).filter(**filters)\ .exclude(status=Vm.NOTCREATED)\ .order_by(*order_by) return (vm for vm in vms if vm.dc.settings.MON_ZABBIX_ENABLED and vm.is_zabbix_sync_active() and not vm.is_deploying()) def call_mon_history_task(request, task_function, view_fun_name, obj, dc_bound, serializer, data, graph, graph_settings): """Function that calls task_function callback and returns output mgmt_task_response()""" _apiview_ = { 'view': view_fun_name, 'method': request.method, 'hostname': obj.hostname, 'graph': graph, 'graph_params': serializer.object.copy(), } result = serializer.object.copy() result['desc'] = graph_settings.get('desc', '') result['hostname'] = obj.hostname result['graph'] = graph result['options'] = graph_settings.get('options', {}) result['update_interval'] = graph_settings.get('update_interval', None) result['add_host_name'] = graph_settings.get('add_host_name', False) tidlock = '%s obj:%s graph:%s item_id:%s since:%d until:%d' % (task_function.__name__, obj.uuid, graph, serializer.item_id, round(serializer.object['since'], -2), round(serializer.object['until'], -2)) item_id = serializer.item_id if item_id is None: items = graph_settings['items'] else: item_dict = {'id': item_id} items = [i % item_dict for i in graph_settings['items']] if 'items_search_fun' in graph_settings: # noinspection PyCallingNonCallable items_search = graph_settings['items_search_fun'](graph_settings, item_id) else: items_search = None history = graph_settings['history'] # for VM the task_function is called without task group value because it's DC bound if dc_bound: tg = TG_DC_BOUND else: tg = TG_DC_UNBOUND ter = task_function.call(request, obj.owner.id, (obj.uuid, items, history, result, items_search), tg=tg, meta={'apiview': _apiview_}, tidlock=tidlock) # NOTE: cache_result=tidlock, cache_timeout=60) # Caching is disable here, because it makes no real sense. # The latest graphs must be fetched from zabbix and the older are requested only seldom. return mgmt_task_response(request, *ter, obj=obj, api_view=_apiview_, dc_bound=dc_bound, data=data)
37.277228
106
0.619124
449
3,765
4.962138
0.345212
0.064183
0.028725
0.021544
0
0
0
0
0
0
0
0.001468
0.276228
3,765
100
107
37.65
0.816147
0.162815
0
0.046875
0
0
0.09375
0
0
0
0
0
0
1
0.0625
false
0
0.09375
0
0.265625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c653a244302b5a5341cd24081ae62a5772fcf996
3,291
py
Python
src/mud/database/__init__.py
Martakan/YUMS
57c8c02eac70a62233f9a48d78becb1a25bed64e
[ "MIT" ]
null
null
null
src/mud/database/__init__.py
Martakan/YUMS
57c8c02eac70a62233f9a48d78becb1a25bed64e
[ "MIT" ]
null
null
null
src/mud/database/__init__.py
Martakan/YUMS
57c8c02eac70a62233f9a48d78becb1a25bed64e
[ "MIT" ]
null
null
null
""" A modular, runtime re-loadable database package! A thin wrapper around the Mongo DB library 'motor' with helper functions to abstract away some more complex database operations. """ import sys as __sys import importlib as __importlib import motor.motor_asyncio import asyncio # names of the python modules/packages (folder/file name with no extension) __all__ = ['datatypes', 'character', 'world'] ### Runtime Module Reloading support ############################# ################################################################## __importlib.invalidate_caches() for __mod in __all__: if __mod in dir(): __importlib.reload(__sys.modules[f"{__name__}.{__mod}"]) del __mod ################################################################## from . import * # load all modules with filenames defined by '__all__' class Database: """ Holds references and initialization variables related to the database connection and all helper methods. The class variables listed bellow are related to database names and collection names, as such they should be changed to better fit the MUD. """ # NOTE: there is a newline seperating logical blocks, that is, collections inside the database # are closely under eachother, a blank line seperates each of them. __user_database_name = "test-users" # the database name where all user data is stored __character_collection_name = "test-characters" # collection where individual characters and login is stored __account_collection_name = "test-accounts" # collection where individual player accounts are stored __world_database_name = "test-world" # the database name where all world data is kept __tutorial_collection_name = "tutorial" # the name of the collection where the tutorial is stored datatypes = datatypes def __init__(self, database_uri='mongodb://localhost:27017'): """ Initialize the asynchronous client for the database inside the running eventloop. Due to the import happening before the event loop being established this init function must be called AFTER the main event loop is created to ensure it gets the correct and running event loop is being passed on. I have had "running outside main event loop" errors so please keep this in mind. (That is, ensure this is called from inside the asyncio.run() function and not before it runs) """ self.uri = database_uri # TODO: If issues arise, bump up the max pool size, each change stream cursor makes 1 connection self.client = motor.motor_asyncio.AsyncIOMotorClient(database_uri, io_loop=asyncio.get_running_loop(), maxPoolSize=10000) # add a thin layer on the databases/collections to allow direct manipulation self.character = self.client[self.__user_database_name][self.__character_collection_name] self.world = self.client[self.__world_database_name] # add methods to abstract away complex methods and database operations self.character_helper_methods = character.Character(self.character) self.world_helper_methods = world.World(self.world)
43.88
112
0.679125
409
3,291
5.261614
0.447433
0.033457
0.013011
0.018587
0.021375
0
0
0
0
0
0
0.004277
0.218475
3,291
75
113
43.88
0.832426
0.522941
0
0
0
0
0.093991
0.01926
0
0
0
0.013333
0
1
0.037037
false
0
0.259259
0
0.555556
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
1
0
0
2
c6555d7ff4abb61b8057f24c0663ec8a607ba4a5
714
py
Python
Pillow-4.3.0/Tests/test_image_toqpixmap.py
leorzz/simplemooc
8b1c5e939d534b1fd729596df4c59fc69708b896
[ "MIT" ]
null
null
null
Pillow-4.3.0/Tests/test_image_toqpixmap.py
leorzz/simplemooc
8b1c5e939d534b1fd729596df4c59fc69708b896
[ "MIT" ]
null
null
null
Pillow-4.3.0/Tests/test_image_toqpixmap.py
leorzz/simplemooc
8b1c5e939d534b1fd729596df4c59fc69708b896
[ "MIT" ]
null
null
null
from helper import unittest, PillowTestCase, hopper from test_imageqt import PillowQtTestCase, PillowQPixmapTestCase from PIL import ImageQt if ImageQt.qt_is_installed: from PIL.ImageQt import QPixmap class TestToQPixmap(PillowQPixmapTestCase, PillowTestCase): def test_sanity(self): PillowQtTestCase.setUp(self) for mode in ('1', 'RGB', 'RGBA', 'L', 'P'): data = ImageQt.toqpixmap(hopper(mode)) self.assertIsInstance(data, QPixmap) self.assertFalse(data.isNull()) # Test saving the file tempfile = self.tempfile('temp_{}.png'.format(mode)) data.save(tempfile) if __name__ == '__main__': unittest.main()
25.5
64
0.666667
77
714
6.012987
0.584416
0.056156
0
0
0
0
0
0
0
0
0
0.001821
0.231092
714
27
65
26.444444
0.84153
0.028011
0
0
0
0
0.041908
0
0
0
0
0
0.125
1
0.0625
false
0
0.25
0
0.375
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
c6568e3f6207ae8a99ee488f843417b0e24ee7fa
255
py
Python
auth/serializers.py
sling254/the-hood
ce169abbdc368e1a7e92896abdf8237136456290
[ "MIT" ]
null
null
null
auth/serializers.py
sling254/the-hood
ce169abbdc368e1a7e92896abdf8237136456290
[ "MIT" ]
null
null
null
auth/serializers.py
sling254/the-hood
ce169abbdc368e1a7e92896abdf8237136456290
[ "MIT" ]
null
null
null
from rest_framework import serializers from hood.models import UserProfile class UserProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = UserProfile fields = ('bio', 'birth_date','picture','email','picture')
36.428571
68
0.752941
25
255
7.6
0.76
0
0
0
0
0
0
0
0
0
0
0
0.152941
255
7
69
36.428571
0.87963
0
0
0
0
0
0.125
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.666667
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
c657d8bfb322dd5002f78a47fc6ad0b585ab1382
403
py
Python
packages/markblocks/markblocks/lex/listlexer.py
stattikcms/stattik
5c96d600d105461edb95a11d8050dee3c32edd1e
[ "MIT" ]
1
2021-11-05T06:24:28.000Z
2021-11-05T06:24:28.000Z
packages/markblocks/markblocks/lex/listlexer.py
stattikcms/stattik
5c96d600d105461edb95a11d8050dee3c32edd1e
[ "MIT" ]
null
null
null
packages/markblocks/markblocks/lex/listlexer.py
stattikcms/stattik
5c96d600d105461edb95a11d8050dee3c32edd1e
[ "MIT" ]
null
null
null
from .lexer import Lexer class ListLexer(Lexer): tokens = Lexer.tokens fingerprints = [ (r'(?P<UL>^\*( +)?)', 'UL'), (r'(?P<OL>^\d+.( +)?)', 'OL'), ] def __init__(self): super().__init__() @_(r'^\*( +)?') def UL(self, t): return t @_(r'^\d+.( +)?') def OL(self, t): return t @_(r'.') def SPAN(self, t): return t
18.318182
38
0.419355
47
403
3.361702
0.404255
0.094937
0.208861
0.227848
0.164557
0
0
0
0
0
0
0
0.330025
403
22
39
18.318182
0.585185
0
0
0.166667
0
0
0.141089
0
0
0
0
0
0
1
0.222222
false
0
0.055556
0.166667
0.611111
0.055556
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
5
c658055ce83117b157d548c23979f1dfab0a6ef7
879
py
Python
bdn/job/migrations/0002_auto_20180820_1444.py
OpenSourceUniversity/bdn
8e8d5b4d63ff4cb9bdf7c5f23d07aa3ad3dd0121
[ "MIT" ]
1
2019-01-18T19:57:25.000Z
2019-01-18T19:57:25.000Z
bdn/job/migrations/0002_auto_20180820_1444.py
OpenSourceUniversity/bdn
8e8d5b4d63ff4cb9bdf7c5f23d07aa3ad3dd0121
[ "MIT" ]
3
2019-06-23T17:26:24.000Z
2022-02-11T03:40:54.000Z
bdn/job/migrations/0002_auto_20180820_1444.py
OpenSourceUniversity/bdn
8e8d5b4d63ff4cb9bdf7c5f23d07aa3ad3dd0121
[ "MIT" ]
null
null
null
# Generated by Django 2.0.2 on 2018-08-20 14:44 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('job', '0002_auto_20180820_0901'), ] operations = [ migrations.AlterField( model_name='job', name='experience', field=models.CharField(blank=True, max_length=130, null=True), ), migrations.AlterField( model_name='job', name='industries', field=models.ManyToManyField(blank=True, to='industry.Industry'), ), migrations.AlterField( model_name='job', name='languages', field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(blank=True, max_length=70, null=True), default=[], size=None), ), ]
29.3
150
0.609784
93
879
5.666667
0.548387
0.113852
0.142315
0.165085
0.349146
0.349146
0.144213
0
0
0
0
0.055814
0.266212
879
29
151
30.310345
0.76124
0.051195
0
0.391304
1
0
0.097356
0.027644
0
0
0
0
0
1
0
false
0
0.086957
0
0.217391
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
2
c6584a2c0e693053cb75307e5e476e2c82f9ab5b
900
py
Python
tripmining/model/coordinate.py
LinusDietz/tripmining
0bb57268d623ce7bc6d36f10db529f0bf9645bd6
[ "MIT" ]
3
2020-03-20T10:26:18.000Z
2021-03-12T11:25:31.000Z
tripmining/model/coordinate.py
LinusDietz/tripmining
0bb57268d623ce7bc6d36f10db529f0bf9645bd6
[ "MIT" ]
3
2020-03-19T15:01:44.000Z
2020-04-07T12:17:11.000Z
tripmining/model/coordinate.py
LinusDietz/tripmining
0bb57268d623ce7bc6d36f10db529f0bf9645bd6
[ "MIT" ]
1
2020-01-27T13:11:09.000Z
2020-01-27T13:11:09.000Z
import functools import math import operator class Coordinate: def __init__(self, lat, lng): f_lat = float(lat) if math.fabs(f_lat) > 180: raise ValueError(f'The latitude must be between -180 and 180 degrees, but was {f_lat}!') f_lng = float(lng) if math.fabs(f_lng) > 180: raise ValueError(f'The longitude must be between -180 and 180 degrees, but was {f_lng}!') self.lat = f_lat self.lng = f_lng def __hash__(self) -> int: hashes = map(hash, (self.lat, self.lng)) return functools.reduce(operator.xor, hashes) def __str__(self) -> str: return f"({self.lat}, {self.lng})" def __eq__(self, other: object) -> bool: if self is other: return True if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False
29.032258
101
0.6
124
900
4.064516
0.362903
0.055556
0.059524
0.043651
0.230159
0.142857
0.142857
0.142857
0.142857
0.142857
0
0.028302
0.293333
900
30
102
30
0.764151
0
0
0
0
0
0.176667
0
0
0
0
0
0
1
0.166667
false
0
0.125
0.041667
0.541667
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
c659e8a42adf9d9a4fef0726f9fe5a262dddce52
315
py
Python
odin-libraries/python/pyodin/odin_logger.py
elijah/odin
d181cd86b9909904ba97d8090098a4913c93a894
[ "MIT" ]
null
null
null
odin-libraries/python/pyodin/odin_logger.py
elijah/odin
d181cd86b9909904ba97d8090098a4913c93a894
[ "MIT" ]
null
null
null
odin-libraries/python/pyodin/odin_logger.py
elijah/odin
d181cd86b9909904ba97d8090098a4913c93a894
[ "MIT" ]
null
null
null
from os import environ from requests import post class OdinLogger: @classmethod def log(cls, type, desc, value, id, timestamp): response = post(url="http://localhost:3939/stats/add", data = type + "," + desc + "," + str(value) + "," + id + "," + str(timestamp)) return response.status_code
35
141
0.631746
39
315
5.076923
0.74359
0.080808
0
0
0
0
0
0
0
0
0
0.016129
0.212698
315
8
142
39.375
0.782258
0
0
0
0
0
0.111111
0
0
0
0
0
0
1
0.142857
false
0
0.285714
0
0.714286
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
2
d65cc2e3aa44a8e72e75284f2813f4355fc088be
14,673
py
Python
g2p_aligner.py
ys10/Grapheme-PhonemeAlignment
b7108822bea6da6f1b14e9692affb05d24ae55cb
[ "MIT" ]
4
2018-05-31T02:52:47.000Z
2021-03-12T09:09:57.000Z
g2p_aligner.py
ys10/Grapheme-PhonemeAlignment
b7108822bea6da6f1b14e9692affb05d24ae55cb
[ "MIT" ]
1
2018-03-05T02:30:39.000Z
2018-03-05T02:30:39.000Z
g2p_aligner.py
ys10/Grapheme-PhonemeAlignment
b7108822bea6da6f1b14e9692affb05d24ae55cb
[ "MIT" ]
1
2020-04-22T07:06:33.000Z
2020-04-22T07:06:33.000Z
# coding=utf-8 import numpy as np from itertools import combinations_with_replacement from my_log import logging def load_transcription(transcription_file_name): """ :return: a list of tuple: [ (word: string, phones: list), (word: string, phones: list), ..., (word: string, phones: list), ] """ transcription_list = list() with open(transcription_file_name, "r") as transcription_file: while 1: lines = transcription_file.readlines(10000) if not lines: break for line in lines: line = line.strip() word = line.split("\t")[0] phones = line.split("\t")[1].split(" ") transcription_list.append((word, phones)) pass pass transcription_list = transcription_list logging.debug("transcription_list:") logging.debug(transcription_list) return transcription_list def load_grapheme_dict(transcription_list): """ :return: a dictionary of grapheme-id pair like: {"a": 0, "b": 1, "c": 2, ...,} """ grapheme_set = set() for (word, _) in transcription_list: grapheme_set = grapheme_set.union(word) pass grapheme_list = list(grapheme_set) grapheme_dict = dict() for i in range(len(grapheme_list)): grapheme_dict[grapheme_list[i]] = i pass grapheme_dict = grapheme_dict logging.debug("grapheme_dict:") logging.debug(grapheme_dict) return grapheme_dict def load_phoneme_dict(transcription_list): """ :return: a dictionary of phoneme-id pair like: {"ey1":0, "b":1, "iy2": 2, "s": 3, "iy2": 4, ...,} """ phoneme_set = set() for (_, phones) in transcription_list: phoneme_set = phoneme_set.union(phones) pass phoneme_list = list(phoneme_set) phoneme_list.append("*") phoneme_dict = dict() for i in range(len(phoneme_list)): phoneme_dict[phoneme_list[i]] = i pass phoneme_dict = phoneme_dict logging.debug("phoneme_dict:") logging.debug(phoneme_dict) return phoneme_dict def introduce_epsilon_phone_seq(word, phones): """ Introduce epsilon to every possible location in phones list. :param word: :param phones: :return: a list containing all word-phones pairs with epsilon introduced """ length_diff = len(word) - len(phones) if length_diff < 0: logging.error("Word length is less than phones'!") logging.info(word + "-" + str(phones)) location_combines_with_replace = [c for c in combinations_with_replacement(range(len(phones) + 1), length_diff)] pair_list = list() for locations in location_combines_with_replace: temp_phones = phones.copy() for i in range(len(locations)): temp_phones.insert(locations[i] + i, "*") pass pair_list.append((word, temp_phones)) pass return pair_list def is_prob_matrix_equal(last_prob_matrix, new_prob_matrix, epsilon): """ :param last_prob_matrix: numpy array. :param new_prob_matrix: numpy array. :param epsilon: :return: True: if mean-square error <= epsilon False: if mean-square error > epsilon """ diff_mean = np.mean(np.subtract(last_prob_matrix, new_prob_matrix)) if diff_mean <= epsilon: return True return False def path_to_string(path_list): """ :param path_list: a list of dtw path result, like: [ ("a", "ey1"), ("b", "b_iy1"), ("c", "s_iy1"), ] :return: a string to be writen to the output file, like: abc ey1 b_iy1 s_iy1 """ word_list = [] phones = [] for step_tuple in path_list: word_list.append(step_tuple[0]) phones.append(step_tuple[1]) pass result = "".join(word_list) + "\t" + " ".join(phones) + "\n" return result class Aligner: def __init__(self, training_file_name, test_data_file_name): self.training_data_file_name = training_file_name self.test_data_file_name = test_data_file_name self.transcription_list = list() self.grapheme_dict = dict() self.phoneme_dict = dict() self.prob_matrix = np.zeros(shape=(1, 1)) pass def init_prob_matrix(self): """ :return: matrix containing probabilities of a grapheme match a phoneme, initialized with 0 value. """ g_count = len(self.grapheme_dict) p_count = len(self.phoneme_dict) self.prob_matrix = np.zeros(shape=(g_count, p_count), dtype=np.float32) logging.debug("prob_matrix:") logging.debug(self.prob_matrix) return self.prob_matrix def reset_prob_matrix(self, align_paths): """ Reset prob matrix according to align paths. :param align_paths: a list of step lists, like: [ [ ("a", "ey1"), ("b", "b_iy1"), ..., ("c", "s_iy1"), ], [ ("a", "ey1"), ("b", "b_iy1"), ..., ("c", "s_iy1"), ], ..., [ ("a", "ey1"), ("b", "b_iy1"), ..., ("c", "s_iy1"), ], ] :return: prob matrix """ logging.debug("before reset prob matrix:") logging.debug(self.prob_matrix) for align_path in align_paths: for step in align_path: g_id = self.get_grapheme_id(step[0]) p_id = self.get_phoneme_id(step[1]) self.prob_matrix[g_id][p_id] += 1 pass pass self.normalize_prob_matrix() logging.debug("after reset prob matrix:") logging.debug(self.prob_matrix) return self.prob_matrix def normalize_prob_matrix(self): """ Probability matrix is a matrix with shape: (grapheme_count, phoneme_count). Normalization is to keep sum of each row in the matrix to 1. :return: a normalized probability matrix. """ shape = self.prob_matrix.shape sum_array = np.sum(self.prob_matrix, axis=1) for i in range(shape[0]): for j in range(shape[1]): self.prob_matrix[i][j] /= sum_array[i] pass pass logging.debug("prob_matrix:") logging.debug(self.prob_matrix) return self.prob_matrix def get_grapheme_id(self, grapheme): g_id = self.grapheme_dict[grapheme] return g_id def get_phoneme_id(self, phoneme): p_id = self.phoneme_dict[phoneme] return p_id def distance(self, grapheme, phoneme): """ Calculate the distance(match probability) between a grapheme and a phoneme. :param grapheme: a string like: a :param phoneme: a string like: ey1 :return: probability of grapheme match phoneme """ g_id = self.get_grapheme_id(grapheme) p_id = self.get_phoneme_id(phoneme) distance = self.prob_matrix[g_id][p_id] return distance def init_prob_of_grapheme_match_phoneme(self): """ Initialize prob_matrix: the probability of G matching P, counting with DTW all possible G/P association for all possible epsilon positions in the phonetic :return: prob_matrix """ self.transcription_list = load_transcription(training_data_file_name) self.grapheme_dict = load_grapheme_dict(self.transcription_list) self.phoneme_dict = load_phoneme_dict(self.transcription_list) self.init_prob_matrix() align_paths = [] for (word, phones) in self.transcription_list: pair_list = introduce_epsilon_phone_seq(word, phones) # Introduce epsilon into phone list for (w, p) in pair_list: # align_path, _ = self.dynamic_time_wrapping(w, p) align_path = [] for i in range(len(w)): align_path.append((w[i], p[i])) align_paths.append(align_path) pass self.reset_prob_matrix(align_paths) return self.prob_matrix def dynamic_time_wrapping(self, word, phones): """ Dynamic time wrapping for word-phones pair. :param word: a string represent a word :param phones: a list of string represent some phones :return: a list of tuple represent the best path, like: [ ("a", "ey1"), ("b", "b_iy1"), ..., ("c", "s_iy1"), ] """ g_count = len(word) p_count = len(phones) frame_dist_matrix = np.zeros(shape=(g_count, p_count), dtype=np.float32) # Frame distance matrix. for i in range(g_count): for j in range(p_count): frame_dist_matrix[i][j] = self.distance(word[i], phones[j]) pass pass acc_dist_matrix = np.zeros(shape=(g_count, p_count), dtype=np.float32) # Accumulated distance matrix. acc_dist_matrix[0][0] = frame_dist_matrix[0][0] """Dynamic programming to compute the accumulated probability.""" for i in range(1, g_count): for j in range(p_count): d1 = acc_dist_matrix[i-1][j] if j > 0: d2 = acc_dist_matrix[i-1][j-1] else: d2 = 0 acc_dist_matrix[i][j] = frame_dist_matrix[i][j] + max([d1, d2]) pass pass prob_value = acc_dist_matrix[g_count-1][p_count-1] """Trace back to find the best path with the max accumulated probability.""" align_path = [] i, j = g_count-1, p_count-1 while 1: align_path.append((word[i], phones[j])) if i == 0 & j == 0: break if i > 0: d1 = acc_dist_matrix[i - 1][j] if j > 0: d2 = acc_dist_matrix[i - 1][j - 1] else: d2 = 0 else: d1 = 0 d2 = 0 candidate_steps = [(i-1, j), (i-1, j-1)] candidate_prob = [d1, d2] i, j = candidate_steps[candidate_prob.index(max(candidate_prob))] pass align_path.reverse() return align_path, prob_value def e_step(self): """ Expectation step that computes a optimized path with maximum probability for each word-phones pair. :return: a list of align paths, like: [ [("a", "ey1"), ("b", "b_iy10), ("c", "s_iy0"), ], [("a", "ey1"), ("b", "b_iy10), ], [("a", "ey1"), ("b", "b_iy10), ("c", "s_iy0"), ], [("a", "ey1"), ("b", "b_iy10), ("c", "s_iy0"), ("d", "d_iy0"), ], ] """ align_paths = [] for (word, phones) in self.transcription_list: pair_list = introduce_epsilon_phone_seq(word, phones) logging.debug("pair list:") logging.debug(pair_list) candidate_path_list = [] # Construct a candidate path list for all word-phones for (w, p) in pair_list: align_path, prob_value = self.dynamic_time_wrapping(w, p) candidate_path_list.append((align_path, prob_value)) candidate_path_list.sort(key=lambda x: x[1], reverse=True) # Sort by probability align_paths.append(candidate_path_list[0][0]) # Pick up the promising path with the biggest probability. pass return align_paths def m_step(self, align_paths): """ Maximum likelihood step that resets the frame prob matrix according to align paths generated by e_step. :param align_paths: a list of align paths generated by e_step function. """ self.reset_prob_matrix(align_paths) pass def train(self, iter_num, epsilon): """ Train prop matrix until iter_num or the difference of adjacent iteration results is no more than epsilon. :param iter_num: :param epsilon: """ self.init_prob_of_grapheme_match_phoneme() for i in range(iter_num): logging.info("Training epoch:" + str(i)) last_prob_matrix = self.prob_matrix.copy() align_paths = self.e_step() # Expectation step self.m_step(align_paths) # Maximum step # if self.is_prob_matrix_equal(last_prob_matrix, self.prob_matrix, epsilon): # break pass pass def align(self): """ Align the test data file by current model(frame prob matrix) trained already. :return: """ transcription_list = load_transcription(self.test_data_file_name) result_list = [] for (word, phones) in transcription_list: pair_list = introduce_epsilon_phone_seq(word, phones) candidate_path_list = [] # Construct a candidate path list for all possible word-phones pairs for (w, p) in pair_list: align_path, prob_value = self.dynamic_time_wrapping(w, p) candidate_path_list.append((align_path, prob_value)) candidate_path_list.sort(key=lambda x: x[1], reverse=True) # Sort by probability result_string = path_to_string(candidate_path_list[0][0]) result_list.append(result_string) # Pick up the promising path with the biggest probability. with open(output_file_name, "w") as output_file: output_file.writelines(result_list) pass pass pass if __name__ == '__main__': training_data_file_name = "assets/mini_training_data.txt" test_data_file_name = "assets/mini_test_data.txt" output_file_name = "assets/result.txt" iter_num = 5 epsilon = 0 aligner = Aligner(training_data_file_name, test_data_file_name) aligner.train(iter_num, epsilon) aligner.align()
37.146835
163
0.559395
1,777
14,673
4.380979
0.132808
0.056519
0.030572
0.006936
0.386898
0.334489
0.248298
0.202569
0.170841
0.152087
0
0.012682
0.33899
14,673
394
164
37.241117
0.789978
0.246371
0
0.318182
0
0
0.027892
0.005558
0.004132
0
0
0
0
1
0.078512
false
0.11157
0.012397
0
0.161157
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
1
d65ef125e43cf3342be46e1656a8eaaba3ec76c9
6,483
py
Python
hw-10/rainwater-hw-10.py
rainwaterone/stat656
c582fc8c6a55c377e2b57d1f7b10471d625d79db
[ "MIT" ]
null
null
null
hw-10/rainwater-hw-10.py
rainwaterone/stat656
c582fc8c6a55c377e2b57d1f7b10471d625d79db
[ "MIT" ]
null
null
null
hw-10/rainwater-hw-10.py
rainwaterone/stat656
c582fc8c6a55c377e2b57d1f7b10471d625d79db
[ "MIT" ]
null
null
null
""" STAT 656 HW-10 @author:Lee Rainwater @heavy_lifting_by: Dr. Edward Jones @date: 2020-07-29 """ import pandas as pd # Classes provided from AdvancedAnalytics ver 1.25 from AdvancedAnalytics.Text import text_analysis from AdvancedAnalytics.Text import sentiment_analysis from sklearn.feature_extraction.text import CountVectorizer import numpy as np from AdvancedAnalytics.Text import text_plot def heading(headerstring): """ Centers headerstring on the page. For formatting to stdout Parameters ---------- headerstring : string String that you wish to center. Returns ------- Returns: None. """ tw = 70 # text width lead = int(tw/2)-(int(len(headerstring)/2))-1 tail = tw-lead-len(headerstring)-2 print('\n' + ('*'*tw)) print(('*'*lead) + ' ' + headerstring + ' ' + ('*'*tail)) print(('*'*tw)) return heading("READING DATA SOURCE...") # Set Pandas Columns Width for Excel Columns pd.set_option('max_colwidth', 32000) df = pd.read_excel("hotels.xlsx") text_col = 'Review' #Identify the Data Frame Text Target Column Name # Check if any text was truncated pd_width = pd.get_option('max_colwidth') maxsize = df[text_col].map(len).max() # Maps text_col onto len() and finds max() n_truncated = (df[text_col].map(len) > pd_width).sum() print("\nTEXT LENGTH:") print("{:<17s}{:>6d}".format(" Max. Accepted", pd_width)) print("{:<17s}{:>6d}".format(" Max. Observed", maxsize)) print("{:<17s}{:>6d}".format(" Truncated", n_truncated)) # Initialize TextAnalytics and Sentiment Analysis. ta = text_analysis(synonyms=None, stop_words=None, pos=False, stem=False) # n_terms=2 only displays text containing 2 or more sentiment words for # the list of the highest and lowest sentiment strings sa = sentiment_analysis(n_terms=2) heading("CREATING TOKEN COUNT MATRIX...") # Create Word Frequency by Review Matrix using Custom Sentiment cv = CountVectorizer(max_df=1.0, min_df=1, max_features=None, \ ngram_range=(1,2), analyzer=sa.analyzer, \ vocabulary=sa.sentiment_word_dic) stf = cv.fit_transform(df[text_col]) # Return document-term matrix sterms = cv.get_feature_names() # Map feature indices to feature names heading("CALCULATE AND STORE SENTIMENT SCORES...") # Calculate and Store Sentiment Scores into DataFrame "s_score" s_score = sa.scores(stf, sterms) n_reviews = s_score.shape[0] n_sterms = s_score['n_words'].sum() max_length = df['Review'].apply(len).max() if n_sterms == 0 or n_reviews == 0: print("No sentiment terms found.") p = s_score['n_words'].sum() / n_reviews print('{:-<24s}{:>6d}'.format("\nMaximum Text Length", max_length)) print('{:-<23s}{:>6d}'.format("Total Reviews", n_reviews)) print('{:-<23s}{:>6d}'.format("Total Sentiment Terms", n_sterms)) print('{:-<23s}{:>6.2f}'.format("Avg. Sentiment Terms", p)) # s_score['sentiment'] = s_score['sentiment'].map("{:,.2f}".format) df = df.join(s_score) print("\n", df[['hotel', 'sentiment', 'n_words']], "\n") print(df.groupby(['hotel']).mean()) heading("GENERATING TOTAL WORD CLOUD FOR CORPUS...") tcv = CountVectorizer(max_df=1.0, min_df=1, max_features=None, \ ngram_range=(1,2), analyzer=ta.analyzer) tf = tcv.fit_transform(df[text_col]) terms = tcv.get_feature_names() td = text_plot.term_dic(tf, terms) text_plot.word_cloud_dic(td, max_words=200) heading("GENERATING SENTIMENT WORD CLOUD FOR CORPUS...") corpus_sentiment = {} n_sw = 0 for i in range(n_reviews): # Iterate over the terms with nonzero scores."stf" is a sparse matrix term_list = stf[i].nonzero()[1] if len(term_list)>0: for t in np.nditer(term_list): score = sa.sentiment_dic.get(sterms[t]) if score != None: n_sw += stf[i,t] current_count = corpus_sentiment.get(sterms[t]) if current_count == None: corpus_sentiment[sterms[t]] = stf[i,t] else: corpus_sentiment[sterms[t]] += stf[i,t] # Word cloud for the Sentiment Words found in the Corpus text_plot.word_cloud_dic(corpus_sentiment, max_words=200) n_usw = len(corpus_sentiment) print("\nSENTIMENT TERMS") print("------------------") print("{:.<10s}{:>8d}".format("Unique",n_usw)) print("{:.<10s}{:>8d}".format("Total", n_sw )) print("------------------") heading("GENERATING TOTAL WORD CLOUD FOR BELLAGIO...") tcv = CountVectorizer(max_df=1.0, min_df=1, max_features=None, \ ngram_range=(1,2), analyzer=ta.analyzer) tf = tcv.fit_transform(df[df['hotel']=='Bellagio'][text_col]) terms = tcv.get_feature_names() td = text_plot.term_dic(tf, terms) text_plot.word_cloud_dic(td, max_words=200) heading("GENERATING SENTIMENT WORD CLOUD FOR BELLAGIO...") bcv = CountVectorizer(max_df=1.0, min_df=1, max_features=None, \ ngram_range=(1,2), analyzer=sa.analyzer, \ vocabulary=sa.sentiment_word_dic) bstf = bcv.fit_transform(df[df['hotel']=='Bellagio'][text_col]) # Return document-term matrix bsterms = bcv.get_feature_names() # Map feature indices to feature names heading("CALCULATE AND STORE SENTIMENT SCORES FOR BELLAGIO...") # Calculate and Store Sentiment Scores into DataFrame "s_score" bs_score = sa.scores(bstf, bsterms) bn_reviews = bs_score.shape[0] bn_sterms = bs_score['n_words'].sum() max_length = df['Review'].apply(len).max() if bn_sterms == 0 or bn_reviews == 0: print("No sentiment terms found.") corpus_sentiment = {} n_sw = 0 for i in range(bn_reviews): # Iterate over the terms with nonzero scores."stf" is a sparse matrix term_list = bstf[i].nonzero()[1] if len(term_list)>0: for t in np.nditer(term_list): score = sa.sentiment_dic.get(bsterms[t]) if score != None: n_sw += bstf[i,t] current_count = corpus_sentiment.get(bsterms[t]) if current_count == None: corpus_sentiment[bsterms[t]] = bstf[i,t] else: corpus_sentiment[bsterms[t]] += bstf[i,t] # Word cloud for the Sentiment Words found in the Corpus text_plot.word_cloud_dic(corpus_sentiment, max_words=200) n_usw = len(corpus_sentiment) print("\nBELLAGIO SENTIMENT TERMS") print("------------------") print("{:.<10s}{:>8d}".format("Unique",n_usw)) print("{:.<10s}{:>8d}".format("Total", n_sw )) print("------------------")
37.912281
100
0.653555
919
6,483
4.45049
0.231774
0.04401
0.017604
0.020538
0.587775
0.534474
0.497066
0.429095
0.416626
0.377017
0
0.020691
0.187413
6,483
170
101
38.135294
0.755695
0.197902
0
0.372881
0
0
0.181393
0
0
0
0
0
0
1
0.008475
false
0
0.050847
0
0.067797
0.211864
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d660266eecc102047200d3452d83cf102a416710
497
py
Python
manokee/timing/timing.py
smiszym/manokee
afb63b8ce5ba3f83bb924965b8d5098a6d28c474
[ "MIT" ]
null
null
null
manokee/timing/timing.py
smiszym/manokee
afb63b8ce5ba3f83bb924965b8d5098a6d28c474
[ "MIT" ]
14
2021-03-11T02:05:20.000Z
2022-03-12T01:05:11.000Z
manokee/timing/timing.py
smiszym/manokee
afb63b8ce5ba3f83bb924965b8d5098a6d28c474
[ "MIT" ]
null
null
null
class Timing: def beat_to_seconds(self, beat_number: float) -> float: """ Convert beat number to seconds. :param beat_number: Beat number counted from 0. :return: Time in seconds. """ raise NotImplementedError def seconds_to_beat(self, time: float) -> float: """ Convert seconds to beat number. :param time: Time in seconds. :return: Beat number counted from 0. """ raise NotImplementedError
29.235294
59
0.597586
56
497
5.196429
0.339286
0.206186
0.116838
0.14433
0.151203
0
0
0
0
0
0
0.005917
0.31992
497
16
60
31.0625
0.85503
0.410463
0
0.4
0
0
0
0
0
0
0
0
0
1
0.4
false
0
0
0
0.6
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
d6608bea94750fd60f161e8edb1c0de3cbc454f4
2,113
py
Python
main.py
nizamphoenix/EDD2020
e8d05c38019b98cc8c5e34fd4bc50baceb8d608a
[ "MIT" ]
4
2020-06-08T03:19:57.000Z
2021-10-13T09:40:23.000Z
main.py
nizamphoenix/EDD2020
e8d05c38019b98cc8c5e34fd4bc50baceb8d608a
[ "MIT" ]
null
null
null
main.py
nizamphoenix/EDD2020
e8d05c38019b98cc8c5e34fd4bc50baceb8d608a
[ "MIT" ]
null
null
null
from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler from meditorch.nn.models import UNetResNet from torchsummary import summary import torch.optim as optim from torch.optim import lr_scheduler from meditorch.nn import Trainer from meditorch.utils.plot import plot_image_truemask_predictedmask import numpy as np import EDD from util import resize_images np.random.seed(42) def get_edd_loader(path,validation_split=.25,shuffle_dataset=True): dataset = EDD(path)#instantiating the data set. dataset_size = len(dataset) indices = list(range(dataset_size)) split = int(np.floor(validation_split * dataset_size)) if shuffle_dataset : np.random.shuffle(indices) train_indices, val_indices = indices[split:], indices[:split] train_sampler = SubsetRandomSampler(train_indices) valid_sampler = SubsetRandomSampler(val_indices) loader={ 'train':DataLoader(dataset, batch_size=4, sampler=train_sampler), 'val':DataLoader(dataset, batch_size = 4,sampler=valid_sampler) } return loader def main(): np.random.seed(42) #seting up the data set !mkdir ./EDD2020/resized_masks/ resize_my_images('./EDD2020/EDD2020_release-I_2020-01-15/masks/','./EDD2020/resized_masks/',is_masks=True) !mkdir ./EDD2020/resized_images/ resize_my_images('./EDD2020/EDD2020_release-I_2020-01-15/originalImages/','./EDD2020/resized_images/',is_masks=False) loader = get_edd_loader('./EDD2020/',validation_split=.25,shuffle_dataset=True) #using UNet+ResNet combo model = UNetResNet(in_channel=3, n_classes=5) optimizer_func = optim.Adam(model.parameters(), lr=1e-4) scheduler = lr_scheduler.StepLR(optimizer_func, step_size=10, gamma=0.1) trainer = Trainer(model, optimizer=optimizer_func, scheduler=scheduler) #training trainer.train_model(loader, num_epochs=30) images, masks = next(iter(loader['val'])) #predicting for only a batch of 4 from val set preds = trainer.predict(images) plot_image_truemask_predictedmask(images, masks, preds) if __name__ == '__main__': main()
35.216667
119
0.75769
288
2,113
5.34375
0.385417
0.036387
0.018194
0.023392
0.146849
0.146849
0.05718
0.05718
0.05718
0.05718
0
0.039978
0.135826
2,113
59
120
35.813559
0.802848
0.059158
0
0.045455
0
0
0.089259
0.074634
0
0
0
0
0
0
null
null
0
0.25
null
null
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
d661b7759b3dc688b6b6db70c85b0949bed0d166
10,520
py
Python
dist/geoapi/data/queries.py
tinyperegrine/geoapi
63d50427adef7b8db727f2942b39791bdae32a4c
[ "MIT" ]
2
2021-05-24T22:00:30.000Z
2021-07-26T07:39:23.000Z
src/geoapi/data/queries.py
tinyperegrine/geoapi
63d50427adef7b8db727f2942b39791bdae32a4c
[ "MIT" ]
5
2021-03-19T03:42:09.000Z
2022-03-11T23:59:20.000Z
src/geoapi/data/queries.py
tinyperegrine/geoapi
63d50427adef7b8db727f2942b39791bdae32a4c
[ "MIT" ]
null
null
null
"""Query Object for all read-only queries to the Real Property table """ import os import logging from time import time from typing import List import asyncio import aiohttp import aiofiles import databases from PIL import Image import sqlalchemy from sqlalchemy.sql import select, func import geoapi.common.spatial_utils as spatial_utils import geoapi.common.decorators as decorators from geoapi.common.exceptions import ResourceNotFoundError, ResourceMissingDataError from geoapi.common.json_models import RealPropertyOut, GeometryAndDistanceIn, StatisticsOut class RealPropertyQueries(): """Repository for all DB Query Operations. Different from repository for all transaction operations.""" def __init__(self, connection: databases.Database, real_property_table: sqlalchemy.Table): self._connection = connection self._real_property_table = real_property_table self.logger = logging.getLogger(__name__) async def get_all(self) -> List[RealPropertyOut]: """Gets all the records TODO: add paging Raises: ResourceNotFoundError: if the table is empty Returns: List[RealPropertyOut]: List of outgoing geojson based objects """ select_query = self._real_property_table.select() db_rows = await self._connection.fetch_all(select_query) if not db_rows: msg = "No Properties found!" self.logger.error(msg) raise ResourceNotFoundError(msg) out_list = [RealPropertyOut.from_db(db_row) for db_row in db_rows] return out_list async def get(self, property_id: str) -> RealPropertyOut: """Gets a single record Args: property_id (str): property id to search for Raises: ResourceNotFoundError: if property id not found Returns: RealPropertyOut: Outgoing geojson based object """ select_query = self._real_property_table.select().where( self._real_property_table.c.id == property_id) db_row = await self._connection.fetch_one(select_query) if not db_row: msg = "Property not found - id: {}".format(property_id) self.logger.error(msg) raise ResourceNotFoundError(msg) return RealPropertyOut.from_db(db_row) async def find(self, geometry_distance: GeometryAndDistanceIn) -> List[str]: """Searches for properties within a given distance of a geometry Args: geometry_distance (GeometryAndDistanceIn): geojson based geometry and distance in object Raises: ResourceNotFoundError: if no properties found Returns: List[str]: list of property ids """ geoalchemy_element_buffered = spatial_utils.buffer( geometry_distance.location_geo, geometry_distance.distance) select_query = select([self._real_property_table.c.id]).where( self._real_property_table.c.geocode_geo.ST_Intersects( geoalchemy_element_buffered)) db_rows = await self._connection.fetch_all(select_query) if not db_rows: msg = "No Properties found!" self.logger.error(msg) raise ResourceNotFoundError(msg) out_list = [db_row["id"] for db_row in db_rows] return out_list # helpers for parallel running of queries async def _query_parcels(self, select_query_parcels): parcel_area = await self._connection.fetch_val(select_query_parcels) return parcel_area async def _query_buildings(self, select_query_buildings): db_rows = await self._connection.fetch_all(select_query_buildings) return db_rows async def statistics(self, property_id: str, distance: int) -> StatisticsOut: """Gets statistics for data near a property TODO: replace the property geocode with a redis geocode cache and maintain db sync with postgres with a redis queue. Also, refactor to reduce 'too many locals' Args: property_id (str): property id distance (int): search radius in meters Raises: ResourceNotFoundError: if no property found for the given property id ResourceMissingDataError: if given property does not have geometry info to locate itself Returns: StatisticsOut: A summary statistics outgoing object """ # get property geocode select_query = select([ self._real_property_table.c.geocode_geo ]).where(self._real_property_table.c.id == property_id) db_row = await self._connection.fetch_one(select_query) if db_row is None: msg = "Property not found - id: {}".format(property_id) self.logger.error(msg) raise ResourceNotFoundError(msg) if db_row["geocode_geo"] is None: msg = "Property missing geocode_geo data - id: {}".format( property_id) self.logger.error(msg) raise ResourceMissingDataError(msg) # get zone - buffer around property geojson_obj = spatial_utils.to_geo_json(db_row["geocode_geo"]) geoalchemy_element_buffered = spatial_utils.buffer( geojson_obj, distance) area_distance = spatial_utils.area_distance(geoalchemy_element_buffered, None) zone_area = area_distance['area'] # get parcel area select_query_parcels = select( [func.sum(self._real_property_table.c.parcel_geo.ST_Area())]).where( self._real_property_table.c.parcel_geo.ST_Intersects( geoalchemy_element_buffered)) # get buildings select_query_buildings = select( [self._real_property_table.c.building_geo]).where( self._real_property_table.c.building_geo.ST_Intersects( geoalchemy_element_buffered)) # run queries in parallel parcel_area, db_rows = await asyncio.gather( self._query_parcels(select_query_parcels), self._query_buildings(select_query_buildings), ) # get parcel area result if not parcel_area: parcel_area = 0 parcel_area = round(parcel_area) # get distance and area for buildings if db_rows: area_distance_list = [ spatial_utils.area_distance(db_row["building_geo"], geojson_obj) for db_row in db_rows ] building_area = sum( [area_distance['area'] for area_distance in area_distance_list]) else: area_distance_list = [] building_area = 0 buildings_area_distance = area_distance_list # get final zone density zone_density_percentage = 100 * building_area / zone_area if zone_density_percentage > 100.00: zone_density_percentage = 100.00 zone_density = round(zone_density_percentage, 2) statistics_out = StatisticsOut( parcel_area=parcel_area, buildings_area_distance=buildings_area_distance, zone_area=zone_area, zone_density=zone_density) return statistics_out @decorators.logtime_async(1) async def get_image(self, property_id) -> str: """Gets an image based on url from the database Args: property_id (str): property id Raises: ResourceNotFoundError: if property id not found ResourceMissingDataError: if property does not have a url for image Returns: str: image file name/path """ # get property image url select_query = select([ self._real_property_table.c.image_url ]).where(self._real_property_table.c.id == property_id) db_row = await self._connection.fetch_one(select_query) if db_row is None: msg = "Property not found - id: {}".format(property_id) self.logger.error(msg) raise ResourceNotFoundError(msg) if db_row["image_url"] is None: msg = "Property missing image url - id: {}".format(property_id) self.logger.error(msg) raise ResourceMissingDataError(msg) # get image # with temporary placeholder for progress reporting, add logging etc. # timeouts on url not found, badly formed urls, etc. not handled total_size = 0 start = time() print_size = 0.0 file_name = os.path.join('geoapi/static/tmp', os.path.basename(db_row["image_url"])) timeout = aiohttp.ClientTimeout( total=5 * 60, connect=30) # could put in config eventually try: async with aiohttp.ClientSession(timeout=timeout) as session: async with session.get(db_row["image_url"]) as r: async with aiofiles.open(file_name, 'wb') as fd: self.logger.info('file download started: %s', db_row["image_url"]) while True: chunk = await r.content.read(16144) if not chunk: break await fd.write(chunk) total_size += len(chunk) print_size += len(chunk) if (print_size / (1024 * 1024) ) > 100: # print every 100MB download msg = f'{time() - start:0.2f}s, downloaded: {total_size / (1024 * 1024):0.0f}MB' self.logger.info(msg) print_size = (print_size / (1024 * 1024)) - 100 self.logger.info('file downloaded: %s', file_name) log_msg = f'total time: {time() - start:0.2f}s, total size: {total_size / (1024 * 1024):0.0f}MB' self.logger.info(log_msg) # convert to jpeg file_name_jpg = os.path.splitext(file_name)[0] + ".jpg" img = Image.open(file_name) img.save(file_name_jpg, "JPEG", quality=100) except aiohttp.client_exceptions.ServerTimeoutError as ste: self.logger.error('Time out: %s', str(ste)) raise return file_name_jpg
39.400749
120
0.616825
1,206
10,520
5.150912
0.201493
0.032196
0.046523
0.047328
0.341919
0.314392
0.264488
0.208789
0.17933
0.162911
0
0.011437
0.310171
10,520
266
121
39.548872
0.844564
0.060171
0
0.240741
0
0.012346
0.063832
0
0
0
0
0.007519
0
1
0.006173
false
0
0.092593
0
0.148148
0.024691
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d6640fe2dcd11b0460e228747652381b73af179f
1,685
py
Python
src/api/proxy/proxy.py
HaoJiangGuo/fp-server
9c00b8f0ee64049eb9f214c3efe1fdee977542a6
[ "MIT" ]
2
2018-08-17T06:56:21.000Z
2019-01-08T03:10:32.000Z
src/api/proxy/proxy.py
HaoJiangGuo/fp-server
9c00b8f0ee64049eb9f214c3efe1fdee977542a6
[ "MIT" ]
null
null
null
src/api/proxy/proxy.py
HaoJiangGuo/fp-server
9c00b8f0ee64049eb9f214c3efe1fdee977542a6
[ "MIT" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ API for proxy """ from core import exceptions from core.web import WebHandler from service.proxy.serializers import ProxySerializer from service.proxy.proxy import proxy_srv from utils import log as logger from utils.routes import route def return_developing(): raise exceptions.NotFound(msg=exceptions.ERR_MSG_IS_DEVELOPING) @route(r'/api/proxy/$') class GetProxyHandler(WebHandler): """ proxy api """ async def get(self, *args, **kwargs): """ get proxies """ count = int(self.get_param('count', 1)) scheme = self.get_param('scheme') if scheme: scheme = scheme.lower() anonymity = self.get_param('anonymity') spec = dict(count=count, scheme=scheme, anonymity=anonymity) _items = await proxy_srv.query(spec) items = [] for i in _items: s = ProxySerializer(i) items.append(s.to_representation()) data = { "count": len(items), "detail": items, } # sort_by_speed = self.get_param('sort_by_speed', 0) self.do_success(data) async def post(self, *args, **kwargs): """ create proxies """ datas = self.get_body() logger.debug('datas:', datas, caller=self) self.do_success({'ok': 1}, 'todo') async def delete(self, *args, **kwargs): """ delete proxies """ self.do_success({'ok': 1}, 'todo') @route(r'/api/proxy/report/$') class ReposrProxyHandler(WebHandler): async def post(self, *args, **kwargs): self.do_success({'ok': 1}, 'developing..')
23.402778
68
0.591691
199
1,685
4.899497
0.41206
0.035897
0.057436
0.046154
0.110769
0.094359
0
0
0
0
0
0.004858
0.267062
1,685
71
69
23.732394
0.784615
0.069436
0
0.108108
0
0
0.064917
0
0
0
0
0
0
1
0.027027
false
0
0.162162
0
0.243243
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d66723dcef2bb7193246b5983ca2285df66c7c28
2,058
py
Python
projects/crawler_for_prodect_category/category_output/to_html.py
ice-melt/python-lib
345e34fff7386d91acbb03a01fd4127c5dfed037
[ "MIT" ]
null
null
null
projects/crawler_for_prodect_category/category_output/to_html.py
ice-melt/python-lib
345e34fff7386d91acbb03a01fd4127c5dfed037
[ "MIT" ]
null
null
null
projects/crawler_for_prodect_category/category_output/to_html.py
ice-melt/python-lib
345e34fff7386d91acbb03a01fd4127c5dfed037
[ "MIT" ]
null
null
null
#!/usr/bin/python3 from projects.crawler_for_prodect_category.category_output import output_utils import codecs Logger = output_utils.Logger def output(filename, datas): """ 将爬取的数据导出到html :return: """ Logger.info('Output to html file, please wait ...') # object_serialize('object.pkl',self.datas) # categories , description,url with codecs.open(output_utils.get_filename(filename, 'html'), 'w', 'utf-8') as file: file.write('<html>\n') file.write('<head>\n') file.write('<meta charset="utf-8"/>\n') file.write('<style>\n') file.write('table{font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;' 'width:100%;border-collapse:collapse;}\n') file.write('table th,table td{font-size:1em;border:1px solid #98bf21;padding:3px 7px 2px 7px;}\n') file.write('table th{font-size:1.1em;background-color:#A7C942;color:#ffffff;' 'padding:5px 7px 4px 7px;text-align:left;}\n') file.write('table tr.alt td{background-color:#EAF2D3;color:#000000;}\n') file.write('a:link{text-decoration: none;}\n') file.write('a:visited{text-decoration: none;}\n') file.write('a:hover{text-decoration: underline;}\n') file.write('</style>\n') file.write('</head>\n') file.write('<body>\n') file.write('<table>\n') # 输出首行 file.write('<tr><th>Sequence</th><th>Product Categories</th>' '<th>Product SubCategories</th><th>Description</th></tr>\n') for i in range(len(datas)): key = datas[i] clazz = '' if i % 2 == 0 else ' class="alt" ' file.write('<tr %s><td>%05d</td><td>%s</td><td>%s</td>' '<td><a target="_blank" href="%s">%s</a></td></tr>\n' % (clazz, i + 1, key['categories'], key['subcategories'], key['url'], key['description'])) file.write('</table>\n') file.write('</body>\n') file.write('</html>\n') Logger.info(' Save completed !')
43.787234
113
0.573372
274
2,058
4.270073
0.412409
0.153846
0.136752
0.064103
0.198291
0.157265
0.157265
0
0
0
0
0.024528
0.227405
2,058
46
114
44.73913
0.711321
0.056365
0
0
0
0.114286
0.459093
0.227202
0
0
0
0
0
1
0.028571
false
0
0.057143
0
0.085714
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d66748bfb42fb82f0c12adab0e031e9250276edd
2,947
py
Python
build/lib/WORC/featureprocessing/SelectIndividuals.py
Sikerdebaard/PREDICTFastr
e1f172c3606e6f33edf58008f958dcd1c0ac5b7b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
build/lib/WORC/featureprocessing/SelectIndividuals.py
Sikerdebaard/PREDICTFastr
e1f172c3606e6f33edf58008f958dcd1c0ac5b7b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
build/lib/WORC/featureprocessing/SelectIndividuals.py
Sikerdebaard/PREDICTFastr
e1f172c3606e6f33edf58008f958dcd1c0ac5b7b
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
#!/usr/bin/env python # Copyright 2016-2019 Biomedical Imaging Group Rotterdam, Departments of # Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from sklearn.base import BaseEstimator from sklearn.feature_selection.base import SelectorMixin import numpy as np class SelectIndividuals(BaseEstimator, SelectorMixin): ''' Object to fit feature selection based on the type group the feature belongs to. The label for the feature is used for this procedure. ''' def __init__(self, parameters=['hf_mean', 'sf_compactness']): ''' Parameters ---------- parameters: dict, mandatory Contains the settings for the groups to be selected. Should contain the settings for the following groups: - histogram_features - shape_features - orientation_features - semantic_features - patient_features - coliage_features - phase_features - vessel_features - log_features - texture_features ''' self.parameters = parameters def fit(self, feature_labels): ''' Select only features specificed by parameters per patient. Parameters ---------- feature_labels: list, optional Contains the labels of all features used. The index in this list will be used in the transform funtion to select features. ''' # Remove NAN selectrows = list() for num, l in enumerate(feature_labels): if any(x in l for x in self.parameters): selectrows.append(num) self.selectrows = selectrows def transform(self, inputarray): ''' Transform the inputarray to select only the features based on the result from the fit function. Parameters ---------- inputarray: numpy array, mandatory Array containing the items to use selection on. The type of item in this list does not matter, e.g. floats, strings etc. ''' return np.asarray([np.asarray(x)[self.selectrows].tolist() for x in inputarray]) def _get_support_mask(self): # NOTE: Method is required for the Selector class, but can be empty pass
35.506024
88
0.635562
350
2,947
5.285714
0.497143
0.032432
0.014054
0.017297
0
0
0
0
0
0
0
0.005794
0.297251
2,947
82
89
35.939024
0.887494
0.638616
0
0
0
0
0.027668
0
0
0
0
0
0
1
0.25
false
0.0625
0.1875
0
0.5625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
1
0
0
3
d667529945c63e9ee84e1cddf5e8de3b084ac4c0
5,567
py
Python
hsv.py
FarinaMatteo/siv-project
fbac7c7c114db51d9fdcf90aba296906abdf91af
[ "MIT" ]
null
null
null
hsv.py
FarinaMatteo/siv-project
fbac7c7c114db51d9fdcf90aba296906abdf91af
[ "MIT" ]
null
null
null
hsv.py
FarinaMatteo/siv-project
fbac7c7c114db51d9fdcf90aba296906abdf91af
[ "MIT" ]
1
2021-04-13T11:22:06.000Z
2021-04-13T11:22:06.000Z
""" Background vs Foreground Image segmentation. The goal is to produce a segmentation map that imitates videocalls tools like the ones implemented in Google Meet, Zoom without using Deep Learning- or Machine Learning- based techniques. This script does the following: - builds a background model using the first 3s of the video, acting on the HSV colorspace; - performs frame differencing in the HSV domain; - runs LP filtering (median-filter) on the Saturation difference; - uses Otsu's technique to threshold the saturation and the brightness difference; - concatenates the saturation and the brightness masks to produce the foreground mask; - runs morphological operators one the mask (closing and dilation) with a 3x5 ellipse (resembles the shape of a human face); - uses the foreground mask, the current video stream and a pre-defined background picture to produce the final output. Authors: M. Farina, F. Diprima - University of Trento Last Update (dd/mm/yyyy): 09/04/2021 """ import os import cv2 import time import numpy as np from helpers.variables import * from helpers.utils import build_argparser, codec_from_ext, make_folder, recursive_clean def run(**kwargs): """ Main loop for background removal. """ time_lst = [0] # setup an image for the background bg_pic_path = kwargs['background'] bg_pic = cv2.imread(bg_pic_path) bg_pic = cv2.resize(bg_pic, dst_size) # setup the video writer if needed writer = None if kwargs["output_video"]: codec = codec_from_ext(kwargs["output_video"]) writer = cv2.VideoWriter(kwargs["output_video"], codec, fps, frameSize=(width, height)) # create the output frame folder if needed if kwargs["frame_folder"]: if kwargs["refresh"]: recursive_clean(kwargs["frame_folder"]) make_folder(kwargs["frame_folder"]) # initialize background hsv_bg = np.zeros(dst_shape_multi, dtype='uint16') # start looping through frames frame_count = 0 if cap.isOpened(): while cap.isOpened(): # retrieve the current frame and exit if needed ret, frame = cap.read() if not ret: break # otherwise, perform basic operations on the current frame frame = cv2.resize(frame, dst_size) hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) hsv_frame_blurred = cv2.GaussianBlur(hsv_frame, gauss_kernel, sigmaX=2, sigmaY=2) # build a model for the background during the first frames if frame_count < bg_frame_limit: hsv_bg = hsv_bg.copy() + hsv_frame_blurred if frame_count == bg_frame_limit-1: hsv_bg = np.uint8(hsv_bg.copy() / bg_frame_limit) # when the bg has been modeled, segment the fg else: time_in = time.perf_counter() diff = cv2.absdiff(hsv_frame_blurred, hsv_bg) h_diff, s_diff, v_diff = cv2.split(diff) # automatic global thresholding with Otsu's technique r1, h_diff_thresh = cv2.threshold(h_diff, 1, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) r2, s_diff_thresh = cv2.threshold(s_diff, 1, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) r3, v_diff_thresh = cv2.threshold(v_diff, 1, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) # take into account contribution of saturation and value (aka 'brightness') # clean the saturation mask beforehand, it usually is more unstable s_diff_thresh_median = cv2.medianBlur(s_diff_thresh, ksize=median_ksize) fg_mask = s_diff_thresh_median + v_diff_thresh fg_mask_closed = cv2.morphologyEx(fg_mask, cv2.MORPH_CLOSE, kernel=kernel, iterations=10) fg_mask_dilated = cv2.dilate(fg_mask_closed, kernel=kernel) # compute the actual foreground and background foreground = cv2.bitwise_and(frame, frame, mask=fg_mask_dilated) background = bg_pic - cv2.bitwise_and(bg_pic, bg_pic, mask=fg_mask_dilated) # ... and add them to generate the output image out = cv2.add(foreground, background) # display the output and the masks cv2.imshow("Output", out) # save frames on the fs if the user requested it if kwargs["frame_folder"] and frame_count % kwargs["throttle"] == 0: cv2.imwrite(os.path.join(kwargs["frame_folder"], "{}.jpg".format(frame_count - bg_frame_limit + 1)), out) # write the video on the fs if the user requested it if writer: writer.write(cv2.resize(out, dsize=(width, height))) # quit if needed if cv2.waitKey(ms) & 0xFF==ord('q'): break # keep track of time time_out = time.perf_counter() time_diff = time_out - time_in time_lst.append(time_diff) frame_count += 1 print("Average Time x Frame: ", round(np.sum(np.array(time_lst))/len(time_lst), 2)) cv2.destroyAllWindows() cap.release() if writer: writer.release() if __name__ == "__main__": parser = build_argparser() kwargs = vars(parser.parse_args()) run(**kwargs)
43.492188
126
0.623496
718
5,567
4.657382
0.380223
0.011962
0.025419
0.015251
0.088517
0.071172
0.049641
0.049641
0.049641
0
0
0.018665
0.297467
5,567
128
127
43.492188
0.836359
0.331238
0
0.060606
0
0
0.046208
0
0
0
0.001087
0
0
1
0.015152
false
0
0.090909
0
0.106061
0.015152
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d6690698841bc39fcf328d809c1ae9a9943d7b0f
1,279
py
Python
src/entities/relativeentity.py
alisonbento/steering-all
99797f99180dd64189ea5ed85ff71b66bfd9cf6f
[ "MIT" ]
3
2016-10-10T18:34:55.000Z
2017-08-02T15:18:28.000Z
src/entities/relativeentity.py
alisonbento/steering-all
99797f99180dd64189ea5ed85ff71b66bfd9cf6f
[ "MIT" ]
null
null
null
src/entities/relativeentity.py
alisonbento/steering-all
99797f99180dd64189ea5ed85ff71b66bfd9cf6f
[ "MIT" ]
null
null
null
from entity import Entity class RelativeEntity(Entity): def __init__(self, width, height): Entity.__init__(self, width, height) self.margin = [0, 0, 0, 0] def below(self, entity): self.y = entity.y + entity.height + self.margin[1] def above(self, entity): self.y = entity.y - self.height - self.margin[3] def leftOf(self, entity): self.x = entity.x - self.width - self.margin[2] def rightOf(self, entity): self.x = entity.x + entity.width + self.margin[0] def margin(self, margin): self.margin = margin; def marginLeft(self, margin): self.margin[0] = margin def marginRight(self, margin): self.margin[2] = margin def marginTop(self, margin): self.margin[1] = margin def marginBottom(self, margin): self.margin[3] = margin def alignLeft(self): self.x = 0 + self.margin[0] def alignRight(self, width): self.x = width - self.width - self.margin[2] def alignTop(self): self.y = 0 + self.margin[1] def alignBottom(self, height): self.y = height - self.height - self.margin[3] def centerRelativeX(self, entity): self.x = entity.x + (entity.width / 2) - (self.width / 2) def centerRelativeY(self, entity): self.y = entity.y + (entity.height / 2) - (self.height / 2)
22.839286
63
0.641908
184
1,279
4.418478
0.168478
0.233702
0.103321
0.123001
0.334563
0.334563
0.164822
0.164822
0
0
0
0.021825
0.211884
1,279
55
64
23.254545
0.784722
0
0
0
0
0
0
0
0
0
0
0
0
1
0.457143
false
0
0.028571
0
0.514286
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
3
d66b1cd60139d9cc3f50ee9f63aec7859add227e
6,967
py
Python
cuchem/cuchem/wf/cluster/gpurandomprojection.py
dorukozturk/cheminformatics
c0fa66dd4f4e6650d7286ae2be533c66b7a2b270
[ "Apache-2.0" ]
null
null
null
cuchem/cuchem/wf/cluster/gpurandomprojection.py
dorukozturk/cheminformatics
c0fa66dd4f4e6650d7286ae2be533c66b7a2b270
[ "Apache-2.0" ]
null
null
null
cuchem/cuchem/wf/cluster/gpurandomprojection.py
dorukozturk/cheminformatics
c0fa66dd4f4e6650d7286ae2be533c66b7a2b270
[ "Apache-2.0" ]
null
null
null
#!/opt/conda/envs/rapids/bin/python3 # # Copyright (c) 2020, NVIDIA CORPORATION. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging from functools import singledispatch from typing import List import cudf import cupy import dask import dask_cudf import pandas from cuchemcommon.context import Context from cuchemcommon.data import ClusterWfDAO from cuchemcommon.data.cluster_wf import ChemblClusterWfDao from cuchemcommon.fingerprint import MorganFingerprint from cuchemcommon.utils.logger import MetricsLogger from cuchemcommon.utils.singleton import Singleton from cuml import SparseRandomProjection, KMeans from cuchem.utils.metrics import batched_silhouette_scores from cuchem.wf.cluster import BaseClusterWorkflow logger = logging.getLogger(__name__) @singledispatch def _gpu_random_proj_wrapper(embedding, self): return NotImplemented @_gpu_random_proj_wrapper.register(dask.dataframe.core.DataFrame) def _(embedding, self): logger.info('Converting from dask.dataframe.core.DataFrame...') embedding = embedding.compute() return _gpu_random_proj_wrapper(embedding, self) @_gpu_random_proj_wrapper.register(dask_cudf.core.DataFrame) def _(embedding, self): logger.info('Converting from dask_cudf.core.DataFrame...') embedding = embedding.compute() return _gpu_random_proj_wrapper(embedding, self) @_gpu_random_proj_wrapper.register(pandas.DataFrame) def _(embedding, self): logger.info('Converting from pandas.DataFrame...') embedding = cudf.from_pandas(embedding) return _gpu_random_proj_wrapper(embedding, self) @_gpu_random_proj_wrapper.register(cudf.DataFrame) def _(embedding, self): return self._cluster(embedding) class GpuWorkflowRandomProjection(BaseClusterWorkflow, metaclass=Singleton): def __init__(self, n_molecules: int = None, dao: ClusterWfDAO = ChemblClusterWfDao(MorganFingerprint), n_clusters=7, seed=0): super(GpuWorkflowRandomProjection, self).__init__() self.dao = dao self.n_molecules = n_molecules self.n_clusters = n_clusters self.pca = None self.seed = seed self.n_silhouette = 500000 self.context = Context() self.srp_embedding = SparseRandomProjection(n_components=2) def rand_jitter(self, arr): """ Introduces random displacements to spread the points """ stdev = .023 * cupy.subtract(cupy.max(arr), cupy.min(arr)) for i in range(arr.shape[1]): rnd = cupy.multiply(cupy.random.randn(len(arr)), stdev) arr[:, i] = cupy.add(arr[:, i], rnd) return arr def _cluster(self, embedding): logger.info('Computing cluster...') embedding = embedding.reset_index() n_molecules = embedding.shape[0] # Before reclustering remove all columns that may interfere embedding, prop_series = self._remove_non_numerics(embedding) with MetricsLogger('random_proj', n_molecules) as ml: srp = self.srp_embedding.fit_transform(embedding.values) ml.metric_name = 'spearman_rho' ml.metric_func = self._compute_spearman_rho ml.metric_func_args = (embedding, embedding, srp) with MetricsLogger('kmeans', n_molecules) as ml: kmeans_cuml = KMeans(n_clusters=self.n_clusters) kmeans_cuml.fit(srp) kmeans_labels = kmeans_cuml.predict(srp) ml.metric_name = 'silhouette_score' ml.metric_func = batched_silhouette_scores ml.metric_func_kwargs = {} ml.metric_func_args = (None, None) if self.context.is_benchmark: (srp_sample, kmeans_labels_sample), _ = self._random_sample_from_arrays( srp, kmeans_labels, n_samples=self.n_silhouette) ml.metric_func_args = (srp_sample, kmeans_labels_sample) # Add back the column required for plotting and to correlating data # between re-clustering srp = self.rand_jitter(srp) embedding['cluster'] = kmeans_labels embedding['x'] = srp[:, 0] embedding['y'] = srp[:, 1] # Add back the prop columns for col in prop_series.keys(): embedding[col] = prop_series[col] return embedding def cluster(self, df_mol_embedding=None): logger.info("Executing GPU workflow...") if df_mol_embedding is None: self.n_molecules = self.context.n_molecule df_mol_embedding = self.dao.fetch_molecular_embedding( self.n_molecules, cache_directory=self.context.cache_directory) df_mol_embedding = df_mol_embedding.persist() self.df_embedding = _gpu_random_proj_wrapper(df_mol_embedding, self) return self.df_embedding def recluster(self, filter_column=None, filter_values=None, n_clusters=None): if filter_values is not None: self.df_embedding['filter_col'] = self.df_embedding[filter_column].isin(filter_values) self.df_embedding = self.df_embedding.query('filter_col == True') if n_clusters is not None: self.n_clusters = n_clusters self.df_embedding = _gpu_random_proj_wrapper(self.df_embedding, self) return self.df_embedding def add_molecules(self, chemblids: List): chem_mol_map = {row[0]: row[1] for row in self.dao.fetch_id_from_chembl(chemblids)} molregnos = list(chem_mol_map.keys()) self.df_embedding['id_exists'] = self.df_embedding['id'].isin(molregnos) ldf = self.df_embedding.query('id_exists == True') if hasattr(ldf, 'compute'): ldf = ldf.compute() self.df_embedding = self.df_embedding.drop(['id_exists'], axis=1) missing_mol = set(molregnos).difference(ldf['id'].to_array()) chem_mol_map = {id: chem_mol_map[id] for id in missing_mol} missing_molregno = chem_mol_map.keys() if len(missing_molregno) > 0: new_fingerprints = self.dao.fetch_molecular_embedding_by_id(missing_molregno) new_fingerprints = new_fingerprints.compute() self.df_embedding = self._remove_ui_columns(self.df_embedding) self.df_embedding = self.df_embedding.append(new_fingerprints) return chem_mol_map, molregnos, self.df_embedding
35.912371
98
0.68724
860
6,967
5.317442
0.275581
0.026241
0.062322
0.043735
0.218456
0.176252
0.127706
0.096217
0.085502
0.085502
0
0.005373
0.225348
6,967
193
99
36.098446
0.841949
0.117985
0
0.102362
0
0
0.048992
0.009667
0
0
0
0
0
1
0.086614
false
0
0.133858
0.015748
0.307087
0.03937
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d66bd0ab7aebd9b29dfa99993c201e892a501872
4,688
py
Python
calculate_iHSproportion.py
evodify/population-genetic-analyses
5295f9d68736ac02fc5f3ece43dadd5bf4e98e6f
[ "MIT" ]
3
2018-01-31T09:57:10.000Z
2021-02-03T18:34:01.000Z
calculate_iHSproportion.py
evodify/population-genetic-analyses
5295f9d68736ac02fc5f3ece43dadd5bf4e98e6f
[ "MIT" ]
null
null
null
calculate_iHSproportion.py
evodify/population-genetic-analyses
5295f9d68736ac02fc5f3ece43dadd5bf4e98e6f
[ "MIT" ]
1
2019-09-02T06:13:29.000Z
2019-09-02T06:13:29.000Z
#! /usr/bin/env python ''' This script calculates fractions of SNPs with iHS values above 2.0 over genomic windows of specified size. #Example input: #CHROM POS iHS chr1 14548 -3.32086 chr1 14670 -2.52 chr1 19796 0.977669 chr1 19798 3.604374 chr1 29412 -0.308192 chr1 29813 2.231736 chr1 29847 0.6594 chr1 29873 -2.03918 chr1 30050 -0.113216 chr1 30097 2.0193944 chr1 30135 -0.161264 chr1 30259 0.13628 chr1 30365 -0.357767 chr1 30370 0.953858 chr1 30664 2.0124902 chr1 30723 -0.255984 chr1 30856 3.355832 chr1 30903 -3.196446 chr1 31052 2.590459 chr1 31409 -0.497963 chr1 31414 0.611446 chr1 31424 -0.700634 chr1 31758 2.262846 chr1 31841 -0.50899 chr1 31849 5.392066 chr1 31860 -0.383864 chr1 31864 6.39043 chr1 32008 0.00886538 chr1 32158 -3.451976 chr1 32360 0.194424 chr1 32439 -0.995733 #Example output: #CHROM POS nSNPs iHS chr1 14609.0 2 1.0 chr1 19797.0 2 0.0 chr1 29642.5 4 0.5 chr1 30476.5 10 0.4 chr1 31458.0 9 0.444444444444 chr1 32223.5 4 0.25 #command: $ python calculate_iHSproportion.py \ -i iHS.txt \ -o iHS.window.txt \ -w 1000 \ -t 2 #contact: Dmytro Kryvokhyzha dmytro.kryvokhyzha@evobio.eu ''' ############################# modules ############################# import calls # my custom module ############################# options ############################# parser = calls.CommandLineParser() parser.add_argument( '-i', '--input', help='name of the input file', type=str, required=True) parser.add_argument( '-o', '--output', help='name of the output file', type=str, required=True) parser.add_argument( '-w', '--window', help='sliding window size', type=int, required=True) parser.add_argument( '-t', '--threshold', help='iHS threshold to calculate propotion for', type=int, required=True) args = parser.parse_args() ############################# functions ############################# def proportionWindow(values, threshold): ''' calculates proportion of a values larger than threshold''' largerThan = [] for i in values: if abs(i) >= threshold: largerThan.append(i) windowSize = len(values) proportion = len(largerThan) / float(windowSize) return [windowSize, proportion] ############################# program ############################# print('Opening the file...') windSize = args.window windPosEnd = windSize counter = 0 with open(args.input) as datafile: header_line = datafile.readline() # make output header header_words = header_line.split() chrPos = header_words[0:2] chrPosP = '\t'.join(str(s) for s in chrPos) outputFile = open(args.output, 'w') outputFile.write("%s\tnSNPs\t%s\n" % (chrPosP, header_words[2])) print('Processing the data ...') Vwindow = [] ChrPrevious = '' posS = '' posE = '' for line in datafile: words = line.split() Chr = words[0] pos = int(words[1]) indVal = float(words[2]) # to store the values of a previous line if not ChrPrevious: ChrPrevious = Chr if not posS: posS = pos if not posE: posE = pos # if window size is reached output the results if Chr != ChrPrevious: # if end of a chromosome meanValWindow = proportionWindow(Vwindow, args.threshold) meanValWindowP = '\t'.join(str(s) for s in meanValWindow) calls.processWindow(ChrPrevious, posS, posE, meanValWindowP, outputFile) windPosEnd = windSize Vwindow = [] posS = pos elif pos > windPosEnd: # if end of a window if Vwindow: meanValWindow = proportionWindow(Vwindow, args.threshold) meanValWindowP = '\t'.join(str(s) for s in meanValWindow) calls.processWindow(Chr, posS, posE, meanValWindowP, outputFile) windPosEnd = windPosEnd + windSize Vwindow = [] posS = pos while pos > windPosEnd: # gap is larger than window size windPosEnd = windPosEnd + windSize ChrPrevious = Chr posE = pos # append values Vwindow.append(indVal) # track progress counter += 1 if counter % 1000000 == 0: print str(counter), "lines processed" # process the last window meanValWindow = proportionWindow(Vwindow, args.threshold) meanValWindowP = '\t'.join(str(s) for s in meanValWindow) calls.processWindow(Chr, posS, pos, meanValWindowP, outputFile) datafile.close() outputFile.close() print('Done!')
24.544503
73
0.600256
578
4,688
4.849481
0.377163
0.012843
0.02426
0.012843
0.2137
0.155548
0.155548
0.150196
0.121655
0.121655
0
0.141217
0.256826
4,688
190
74
24.673684
0.663318
0.06506
0
0.369565
0
0
0.078796
0
0
0
0
0
0
0
null
null
0
0.01087
null
null
0.043478
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
d66c0ed5c84f564a500b3ce340b852c977ab112f
2,176
py
Python
pkg/azure/resource_group.py
NihilBabu/xmigrate
c33d0b506a86a0ebef22df8ce299cd84f560d034
[ "Apache-2.0" ]
10
2021-01-02T11:59:46.000Z
2021-06-14T04:38:45.000Z
pkg/azure/resource_group.py
NihilBabu/xmigrate
c33d0b506a86a0ebef22df8ce299cd84f560d034
[ "Apache-2.0" ]
12
2021-01-06T07:02:22.000Z
2021-03-11T06:34:07.000Z
pkg/azure/resource_group.py
NihilBabu/xmigrate
c33d0b506a86a0ebef22df8ce299cd84f560d034
[ "Apache-2.0" ]
3
2021-01-10T12:33:52.000Z
2021-04-12T14:29:13.000Z
# Import the needed management objects from the libraries. The azure.common library # is installed automatically with the other libraries. from azure.common.client_factory import get_client_from_cli_profile from azure.mgmt.resource import ResourceManagementClient from utils.dbconn import * from utils.logger import * from model.project import Project import string, random from azure.common.credentials import ServicePrincipalCredentials # Provision the resource group. async def create_rg(project): con = create_db_con() try: if Project.objects(name=project)[0]['resource_group']: if Project.objects(name=project)[0]['resource_group_created']: return True except Exception as e: print("Reaching Project document failed: "+repr(e)) logger("Reaching Project document failed: "+repr(e),"warning") else: rg_location = Project.objects(name=project)[0]['location'] rg_name = Project.objects(name=project)[0]['resource_group'] try: client_id = Project.objects(name=project)[0]['client_id'] secret = Project.objects(name=project)[0]['secret'] tenant_id = Project.objects(name=project)[0]['tenant_id'] subscription_id = Project.objects(name=project)[0]['subscription_id'] creds = ServicePrincipalCredentials(client_id=client_id, secret=secret, tenant=tenant_id) resource_client = ResourceManagementClient(creds,subscription_id) print("Provisioning a resource group...some operations might take a minute or two.") rg_result = resource_client.resource_groups.create_or_update( rg_name, {"location": rg_location}) print( "Provisioned resource group"+ rg_result.name+" in the "+rg_result.location+" region") Project.objects(name=project).update(resource_group=rg_result.name, resource_group_created=True) con.close() return True except Exception as e: print("Resource group creation failed "+str(e)) logger("Resource group creation failed: "+repr(e),"warning") return False
50.604651
108
0.68704
259
2,176
5.625483
0.320463
0.089224
0.111187
0.154427
0.302677
0.23267
0.128346
0.05628
0
0
0
0.004681
0.214614
2,176
42
109
51.809524
0.847864
0.075368
0
0.157895
0
0
0.182271
0.010956
0
0
0
0
0
1
0
false
0
0.184211
0
0.263158
0.105263
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d66c1cc1ba3efab7c88083eacb18abf18bab0b53
1,049
py
Python
forexml.py
brawnydawg/forexml
62e623e6e7219ad8c7fbca05bf29ea79401741c5
[ "MIT" ]
2
2022-01-15T03:13:07.000Z
2022-01-15T03:13:14.000Z
forexml.py
brawnydawg/forex.ml
62e623e6e7219ad8c7fbca05bf29ea79401741c5
[ "MIT" ]
null
null
null
forexml.py
brawnydawg/forex.ml
62e623e6e7219ad8c7fbca05bf29ea79401741c5
[ "MIT" ]
null
null
null
import numpy from scipy import stats from modules import controler # To compile, us Auto Py to Exe: # Step 1 - install Auto Py to Exe, if not already done # To install the application run this line in cmd: # pip install auto-py-to-exe # To open the application run this line in cmd: # auto-py-to-exe # Step 2 - read the rest of the steps here: # https://dev.to/eshleron/how-to-convert-py-to-exe-step-by-step-guide-3cfi switch = 2 # Mean, Median, Mode if switch == 1 : speed = [99,86,87,88,111,86,103,87,94,78,77,85,86] x = numpy.median(speed) print(x) x = stats.mode(speed) print(x) # Standard Deviation - distance from Mean elif switch == 2 : speed = [86,87,88,86,87,85,86] print("speed = [86,87,88,86,87,85,86]") print("Mean = ", numpy.mean(speed)) print("Standard Deviation = ", numpy.std(speed)) print("") speed = [32,111,138,28,59,77,97] print("speed = [32,111,138,28,59,77,97]") print("Mean = ", numpy.mean(speed)) print("Standard Deviation = ", numpy.std(speed)) controler.app()
26.897436
74
0.653003
181
1,049
3.78453
0.392265
0.029197
0.051095
0.064234
0.491971
0.39562
0.39562
0.308029
0.308029
0.245255
0
0.110718
0.190658
1,049
39
75
26.897436
0.696113
0.375596
0
0.285714
0
0
0.182946
0.071318
0
0
0
0
0
1
0
false
0
0.142857
0
0.142857
0.428571
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
1
d66c664f346efdc6281f1b27109ddcac09232372
694
py
Python
bench/bench_argcomplete.py
solackerman/pytest
0fc00c02a7a39ebd6c57886a85580ea3341e76eb
[ "MIT" ]
4
2020-09-09T15:28:01.000Z
2021-12-01T00:59:56.000Z
bench/bench_argcomplete.py
solackerman/pytest
0fc00c02a7a39ebd6c57886a85580ea3341e76eb
[ "MIT" ]
7
2018-04-04T19:02:43.000Z
2018-04-11T19:03:58.000Z
bench/bench_argcomplete.py
solackerman/pytest
0fc00c02a7a39ebd6c57886a85580ea3341e76eb
[ "MIT" ]
1
2021-04-06T20:06:58.000Z
2021-04-06T20:06:58.000Z
# 10000 iterations, just for relative comparison # 2.7.5 3.3.2 # FilesCompleter 75.1109 69.2116 # FastFilesCompleter 0.7383 1.0760 if __name__ == '__main__': import sys import timeit from argcomplete.completers import FilesCompleter from _pytest._argcomplete import FastFilesCompleter count = 1000 # only a few seconds setup = 'from __main__ import FastFilesCompleter\nfc = FastFilesCompleter()' run = 'fc("/d")' sys.stdout.write('%s\n' % (timeit.timeit(run, setup=setup.replace('Fast', ''), number=count))) sys.stdout.write('%s\n' % (timeit.timeit(run, setup=setup, number=count)))
34.7
80
0.631124
81
694
5.234568
0.592593
0.04717
0.066038
0.070755
0.193396
0.193396
0.193396
0.193396
0.193396
0.193396
0
0.071291
0.252161
694
19
81
36.526316
0.745665
0.259366
0
0
0
0
0.185771
0.043478
0
0
0
0
0
1
0
false
0
0.454545
0
0.454545
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
1
d67095b77014549df9449d344e41a1c0d2d60ab6
374
py
Python
catalog/bindings/gmd/valid_time.py
NIVANorge/s-enda-playground
56ae0a8978f0ba8a5546330786c882c31e17757a
[ "Apache-2.0" ]
null
null
null
catalog/bindings/gmd/valid_time.py
NIVANorge/s-enda-playground
56ae0a8978f0ba8a5546330786c882c31e17757a
[ "Apache-2.0" ]
null
null
null
catalog/bindings/gmd/valid_time.py
NIVANorge/s-enda-playground
56ae0a8978f0ba8a5546330786c882c31e17757a
[ "Apache-2.0" ]
null
null
null
from dataclasses import dataclass from bindings.gmd.time_edge_property_type import TimePrimitivePropertyType __NAMESPACE__ = "http://www.opengis.net/gml" @dataclass class ValidTime(TimePrimitivePropertyType): """ gml:validTime is a convenience property element. """ class Meta: name = "validTime" namespace = "http://www.opengis.net/gml"
23.375
74
0.727273
40
374
6.625
0.625
0.098113
0.120755
0.173585
0.218868
0.218868
0
0
0
0
0
0
0.176471
374
15
75
24.933333
0.86039
0.128342
0
0
0
0
0.196774
0
0
0
0
0
0
1
0
false
0
0.25
0
0.5
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d670c4735ca674e296208c80467697f931ec147e
2,020
py
Python
docs/examples/arch/full_rhino.py
GeneKao/compas_assembly
92fde9cd3948c1b9bb41b4ea7fc866392905182d
[ "MIT" ]
null
null
null
docs/examples/arch/full_rhino.py
GeneKao/compas_assembly
92fde9cd3948c1b9bb41b4ea7fc866392905182d
[ "MIT" ]
null
null
null
docs/examples/arch/full_rhino.py
GeneKao/compas_assembly
92fde9cd3948c1b9bb41b4ea7fc866392905182d
[ "MIT" ]
null
null
null
import os from compas_assembly.datastructures import Assembly from compas_assembly.geometry import Arch from compas_assembly.rhino import AssemblyArtist from compas.rpc import Proxy proxy = Proxy() proxy.restart_server() try: HERE = os.path.dirname(__file__) except NameError: HERE = os.getcwd() DATA = os.path.join(HERE, '../../../data') FILE = os.path.join(DATA, 'arch.json') # ============================================================================== # Assembly # ============================================================================== rise = 5 span = 10 depth = 0.5 thickness = 0.7 n = 40 arch = Arch(rise, span, thickness, depth, n) assembly = Assembly.from_geometry(arch) assembly.node_attribute(0, 'is_support', True) assembly.node_attribute(n - 1, 'is_support', True) # ============================================================================== # Identify the interfaces # ============================================================================== proxy.package = 'compas_assembly.datastructures' # make proxy methods into configurable objects # with __call__ for execution # store the method objects in a dict of callables assembly = proxy.assembly_interfaces_numpy(assembly, tmax=0.02) # ============================================================================== # Compute interface forces # ============================================================================== proxy.package = 'compas_rbe.equilibrium' assembly = proxy.compute_interface_forces_cvx(assembly, solver='CPLEX') # ============================================================================== # Visualize # ============================================================================== artist = AssemblyArtist(assembly, layer="Arch") artist.clear_layer() artist.draw_nodes(color={key: (255, 0, 0) for key in assembly.nodes_where({'is_support': True})}) artist.draw_edges() artist.draw_blocks() artist.draw_interfaces() artist.draw_resultants(scale=0.1) # artist.color_interfaces(mode=1)
29.275362
97
0.517327
193
2,020
5.243523
0.450777
0.049407
0.05336
0
0
0
0
0
0
0
0
0.011976
0.090594
2,020
68
98
29.705882
0.538922
0.421782
0
0
0
0
0.098176
0.045178
0
0
0
0
0
1
0
false
0
0.151515
0
0.151515
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d67132389d902c05a7f58bf458cc631ca552cd15
8,840
py
Python
grinpy/functions/degree.py
somacdivad/grinpy
597f9109b84f1c1aa8c8dd2ac5b572a05ba474de
[ "BSD-3-Clause" ]
12
2019-08-27T11:04:09.000Z
2022-03-03T07:38:42.000Z
grinpy/functions/degree.py
somacdivad/grinpy
597f9109b84f1c1aa8c8dd2ac5b572a05ba474de
[ "BSD-3-Clause" ]
18
2017-12-03T20:20:11.000Z
2019-07-07T18:04:54.000Z
grinpy/functions/degree.py
somacdivad/grinpy
597f9109b84f1c1aa8c8dd2ac5b572a05ba474de
[ "BSD-3-Clause" ]
5
2017-11-28T22:43:05.000Z
2021-07-02T08:48:43.000Z
# -*- coding: utf-8 -*- # Copyright (C) 2017-2019 by # David Amos <somacdivad@gmail.com> # Randy Davila <davilar@uhd.edu> # BSD license. # # Authors: David Amos <somacdivad@gmail.com> # Randy Davila <davilar@uhd.edu> """Assorted degree related graph utilities. """ import collections from grinpy import degree, nodes, number_of_nodes from grinpy.functions.neighborhoods import closed_neighborhood, neighborhood, set_neighborhood, set_closed_neighborhood __all__ = [ "degree_sequence", "min_degree", "max_degree", "average_degree", "number_of_nodes_of_degree_k", "number_of_degree_one_nodes", "number_of_min_degree_nodes", "number_of_max_degree_nodes", "neighborhood_degree_list", "closed_neighborhood_degree_list", "is_regular", "is_k_regular", "is_sub_cubic", "is_cubic", ] def degree_sequence(G): """Return the degree sequence of G. The degree sequence of a graph is the sequence of degrees of the nodes in the graph. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- list The degree sequence of the graph. Examples -------- >>> G = nx.path_graph(3) # Path on 3 nodes >>> nx.degree_sequence(G) [1, 2, 1] """ return [degree(G, v) for v in nodes(G)] def min_degree(G): """Return the minimum degree of G. The minimum degree of a graph is the smallest degree of any node in the graph. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- int The minimum degree of the graph. Examples -------- >>> G = nx.path_graph(3) # Path on 3 nodes >>> nx.min_degree(G) 1 """ D = degree_sequence(G) D.sort() return D[0] def max_degree(G): """Return the maximum degree of G. The maximum degree of a graph is the largest degree of any node in the graph. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- int The maximum degree of the graph. Examples -------- >>> G = nx.path_graph(3) # Path on 3 nodes >>> nx.min_degree(G) 2 """ D = degree_sequence(G) D.sort(reverse=True) return D[0] def average_degree(G): """Return the average degree of G. The average degree of a graph is the average of the degrees of all nodes in the graph. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- float The average degree of the graph. Examples -------- >>> G = nx.star_graph(3) # Star on 4 nodes >>> nx.average_degree(G) 1.5 """ return sum(degree_sequence(G)) / number_of_nodes(G) def number_of_nodes_of_degree_k(G, k): """Return the number of nodes of the graph with degree equal to k. Parameters ---------- G : NetworkX graph An undirected graph. k : int A positive integer. Returns ------- int The number of nodes in the graph with degree equal to k. See Also -------- number_of_leaves, number_of_min_degree_nodes, number_of_max_degree_nodes Examples -------- >>> G = nx.path_graph(3) # Path on 3 nodes >>> nx.number_of_nodes_of_degree_k(G, 1) 2 """ return sum(1 for v in nodes(G) if degree(G, v) == k) def number_of_degree_one_nodes(G): """Return the number of nodes of the graph with degree equal to 1. A vertex with degree equal to 1 is also called a *leaf*. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- int The number of nodes in the graph with degree equal to 1. See Also -------- number_of_nodes_of_degree_k, number_of_min_degree_nodes, number_of_max_degree_nodes Examples -------- >>> G = nx.path_graph(3) # Path on 3 nodes >>> nx.number_of_leaves(G) 2 """ return number_of_nodes_of_degree_k(G, 1) def number_of_min_degree_nodes(G): """Return the number of nodes of the graph with degree equal to the minimum degree of the graph. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- int The number of nodes in the graph with degree equal to the minimum degree. See Also -------- number_of_nodes_of_degree_k, number_of_leaves, number_of_max_degree_nodes, min_degree Examples -------- >>> G = nx.path_graph(3) # Path on 3 nodes >>> nx.number_of_min_degree_nodes(G) 2 """ return number_of_nodes_of_degree_k(G, min_degree(G)) def number_of_max_degree_nodes(G): """Return the number of nodes of the graph with degree equal to the maximum degree of the graph. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- int The number of nodes in the graph with degree equal to the maximum degree. See Also -------- number_of_nodes_of_degree_k, number_of_leaves, number_of_min_degree_nodes, max_degree Examples -------- >>> G = nx.path_graph(3) # Path on 3 nodes >>> nx.number_of_max_degree_nodes(G) 1 """ return number_of_nodes_of_degree_k(G, max_degree(G)) def neighborhood_degree_list(G, nbunch): """Return a list of the unique degrees of all neighbors of nodes in `nbunch`. Parameters ---------- G : NetworkX graph An undirected graph. nbunch : A single node or iterable container of nodes. Returns ------- list A list of the degrees of all nodes in the neighborhood of the nodes in `nbunch`. See Also -------- closed_neighborhood_degree_list, neighborhood Examples -------- >>> import grinpy as gp >>> G = gp.path_graph(3) # Path on 3 nodes >>> gp.neighborhood_degree_list(G, 1) [1, 2] """ if isinstance(nodes, collections.abc.Iterable): return list(set(degree(G, u) for u in set_neighborhood(G, nbunch))) else: return list(set(degree(G, u) for u in neighborhood(G, nbunch))) def closed_neighborhood_degree_list(G, nbunch): """Return a list of the unique degrees of all nodes in the closed neighborhood of the nodes in `nbunch`. Parameters ---------- G : NetworkX graph An undirected graph. nbunch : A single node or iterable container of nodes. Returns ------- list A list of the degrees of all nodes in the closed neighborhood of the nodes in `nbunch`. See Also -------- closed_neighborhood, neighborhood_degree_list Examples -------- >>> import grinpy as gp >>> G = gp.path_graph(3) # Path on 3 nodes >>> gp.closed_neighborhood_degree_list(G, 1) [1, 2, 2] """ if isinstance(nodes, collections.abc.Iterable): return list(set(degree(G, u) for u in set_closed_neighborhood(G, nbunch))) else: return list(set(degree(G, u) for u in closed_neighborhood(G, nbunch))) def is_regular(G): """ Return True if G is regular, and False otherwise. A graph is *regular* if each node has the same degree. Parameters ---------- G : NetworkX graph An undirected graph Returns ------- boolean True if regular, false otherwise. """ return min_degree(G) == max_degree(G) def is_k_regular(G, k): """ Return True if the graph is regular of degree k and False otherwise. A graph is *regular of degree k* if all nodes have degree equal to *k*. Parameters ---------- G : NetworkX graph An undirected graph k : int An integer Returns ------- boolean True if all nodes have degree equal to *k*, False otherwise. """ # check that k is an integer if not float(k).is_integer(): raise TypeError("Expected k to be an integer.") k = int(k) for v in nodes(G): if not degree(G, v) == k: return False return True def is_sub_cubic(G): """ Return True if *G* sub-cubic, and False otherwise. A graph is *sub-cubic* if its maximum degree is at most 3. Parameters ---------- G : NetworkX graph An undirected graph. Returns ------- boolean True if *G* is sub-cubic, False otherwise. """ return max_degree(G) <= 3 def is_cubic(G): """ Return True if *G* is cubic, and False otherwise. A graph is *cubic* if it is regular of degree 3. Parameters ---------- G : NetworkX graph An undirected graph Returns ------- boolean True if *G* is cubic, False otherwise. """ return is_k_regular(G, 3)
21.82716
119
0.602149
1,233
8,840
4.160584
0.107056
0.0577
0.048148
0.065497
0.721832
0.696101
0.64152
0.597076
0.565302
0.559844
0
0.009305
0.282692
8,840
404
120
21.881188
0.799716
0.629638
0
0.126984
0
0
0.123506
0.070828
0
0
0
0
0
1
0.222222
false
0
0.047619
0
0.539683
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
2
d67252401050d3b5004b1ab15ef96c5d2e1fedcf
76
py
Python
tests/app/controller/webhook/github/events/__init__.py
angeleneleow/rocket2
649f49a94d123e78bfd014189e8fede31fa007f6
[ "MIT" ]
null
null
null
tests/app/controller/webhook/github/events/__init__.py
angeleneleow/rocket2
649f49a94d123e78bfd014189e8fede31fa007f6
[ "MIT" ]
null
null
null
tests/app/controller/webhook/github/events/__init__.py
angeleneleow/rocket2
649f49a94d123e78bfd014189e8fede31fa007f6
[ "MIT" ]
null
null
null
"""Contain the tests for the handlers of each supported GitHub webhook."""
38
75
0.75
11
76
5.181818
0.909091
0
0
0
0
0
0
0
0
0
0
0
0.157895
76
1
76
76
0.890625
0.894737
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
d673caa4093bd3809cb0be9e8da138d53b90b322
3,860
py
Python
test/domain_types/test_polygon.py
covjson/covjson-validator
97b6ee445bfcc70ad73d731dce3d67aa4aafaf3a
[ "BSD-3-Clause" ]
null
null
null
test/domain_types/test_polygon.py
covjson/covjson-validator
97b6ee445bfcc70ad73d731dce3d67aa4aafaf3a
[ "BSD-3-Clause" ]
6
2022-02-02T16:52:33.000Z
2022-02-09T09:40:50.000Z
test/domain_types/test_polygon.py
covjson/covjson-validator
97b6ee445bfcc70ad73d731dce3d67aa4aafaf3a
[ "BSD-3-Clause" ]
null
null
null
# Pytests to test the Polygon domain type in the domain.json schema file import pytest from jsonschema.exceptions import ValidationError pytestmark = pytest.mark.schema("/schemas/domain") @pytest.mark.exhaustive def test_valid_polygon_domain(validator, polygon_domain): ''' Tests an example of a Polygon domain ''' validator.validate(polygon_domain) def test_missing_composite_axis(validator, polygon_domain): ''' Invalid: Polygon domain with missing 'composite' axis ''' del polygon_domain["axes"]["composite"] with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_empty_composite_axis(validator, polygon_domain): ''' Invalid: Polygon domain with empty 'composite' axis ''' polygon_domain["axes"]["composite"] = { "values" : [] } with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_wrong_composite_axis_type(validator, polygon_domain): ''' Invalid: Polygon domain with primitive instead of polygon axis ''' polygon_domain["axes"]["composite"] = { "values": [1, 2, 3] } with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_wrong_composite_axis_type2(validator, polygon_domain): ''' Invalid: Polygon domain with tuple instead of polygon axis (invalid polygons) ''' polygon_domain["axes"]["composite"]["values"] = [ [1, 1], [2, 2], [3, 3] ] with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_composite_axis_with_2_values(validator, polygon_domain): ''' Invalid: Polygon domain with composite axis with two polygons ''' polygon_domain["axes"]["composite"]["values"] = [ [ [ [100.0, 1.0], [101.0, 0.0], [101.0, 2.0], [100.0, 2.0], [100.0, 1.0] ] ], [ [ [101.0, 1.0], [102.0, 0.0], [102.0, 2.0], [101.0, 2.0], [101.0, 1.0] ] ] ] with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_wrong_composite_axis_coordinates(validator, polygon_domain): ''' Invalid: Polygon domain with invalid coordinates ''' polygon_domain["axes"]["composite"]["coordinates"] = ["y", "x"] with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_wrong_data_type(validator, polygon_domain): ''' Invalid: Polygon domain with wrong data type ''' polygon_domain["axes"]["composite"]["dataType"] = "tuple" with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_extra_axis(validator, polygon_domain): ''' Invalid: Polygon domain with unrecognised extra axis ''' polygon_domain["axes"]["composite2"] = \ polygon_domain["axes"]["composite"] with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_empty_z_axis(validator, polygon_domain): ''' Invalid: Polygon domain with empty 'z' axis ''' polygon_domain["axes"]["z"] = { "values" : [] } with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_multivalued_z_axis(validator, polygon_domain): ''' Invalid: Polygon domain with multi-valued 'z' axis ''' polygon_domain["axes"]["z"] = { "values" : [1, 2] } with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_empty_t_axis(validator, polygon_domain): ''' Invalid: Polygon domain with empty 't' axis ''' polygon_domain["axes"]["t"] = { "values" : [] } with pytest.raises(ValidationError): validator.validate(polygon_domain) def test_multivalued_t_axis(validator, polygon_domain): ''' Invalid: Polygon domain with multi-valued 't' axis ''' polygon_domain["axes"]["t"] = { "values" : ["2008-01-01T04:00:00Z", "2008-01-01T05:00:00Z"] } with pytest.raises(ValidationError): validator.validate(polygon_domain)
33.275862
97
0.690933
464
3,860
5.571121
0.157328
0.271567
0.110638
0.15087
0.759381
0.747776
0.668472
0.574855
0.49323
0.401547
0
0.031796
0.168912
3,860
115
98
33.565217
0.774002
0.198705
0
0.416667
0
0
0.088587
0
0
0
0
0
0
1
0.216667
false
0
0.033333
0
0.25
0
0
0
0
null
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
d6756e24400a0d5ab6ef197f69d25560e3bddcc6
1,516
py
Python
accounts/models.py
akahard2dj/DjangoBlackberry
4e732d8650dc7d61cd79033d5072d836707b411f
[ "MIT" ]
null
null
null
accounts/models.py
akahard2dj/DjangoBlackberry
4e732d8650dc7d61cd79033d5072d836707b411f
[ "MIT" ]
null
null
null
accounts/models.py
akahard2dj/DjangoBlackberry
4e732d8650dc7d61cd79033d5072d836707b411f
[ "MIT" ]
null
null
null
from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import BaseUserManager, AbstractBaseUser from django.utils import timezone from rest_framework.authtoken.models import Token class BerryManager(BaseUserManager): def create_user(self, email, nickname, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), nickname=nickname, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self): pass @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) class Berry(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) nickname = models.CharField(unique=True, max_length=50) created_at = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) objects = BerryManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['nickname'] def get_full_name(self): return self.nickname def get_short_name(self): return self.nickname @property def is_staff(self): return False
26.596491
72
0.711082
185
1,516
5.697297
0.437838
0.056926
0.02277
0.036053
0.049336
0
0
0
0
0
0
0.004146
0.204485
1,516
56
73
27.071429
0.869818
0
0
0.05
0
0
0.029683
0
0
0
0
0
0
1
0.15
false
0.075
0.175
0.075
0.675
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
2
d6769c3069694a7ae83fbef15106d40f42aed309
1,012
py
Python
tests/test_post.py
Alice-Githui/Blogger
1ae481cc9f2af78e459314c0f09d1bd0ccff614d
[ "MIT" ]
null
null
null
tests/test_post.py
Alice-Githui/Blogger
1ae481cc9f2af78e459314c0f09d1bd0ccff614d
[ "MIT" ]
null
null
null
tests/test_post.py
Alice-Githui/Blogger
1ae481cc9f2af78e459314c0f09d1bd0ccff614d
[ "MIT" ]
null
null
null
import unittest from app.models import Post,User from app import db class PostModelTest(unittest.TestCase): def setUp(self): self.user_Alice=User(username="Alice", password="potato", email="alice@ms.com") self.new_post=Post(id=1,category="All", title="Great Things Take Time", blog="User Tests for blog posts", user=self.user_Alice) def tearDown(self): Post.query.delete() User.query.delete() def test_check_instance_variables(self): self.assertEquals(self.new_post.category,"All") self.assertEquals(self.new_post,title,"Great Things Take Time") self.assertEquals(self.new_post,blog,"User Tests for blog posts") self.assertEquals(self.new_post,user,self.user_Alice) def test_save_post(self): self.new_post.save_post() self.assertTrue(len(Post.query.all())>0) def test_get_post_by_id(self): self.new_post.save_post() got_posts=Post.get_posts("All") self.assertTrue(len(got_posts)== 1)
37.481481
135
0.692688
147
1,012
4.605442
0.340136
0.072378
0.113737
0.135894
0.431315
0.141802
0
0
0
0
0
0.003619
0.18083
1,012
27
136
37.481481
0.813028
0
0
0.090909
0
0
0.124383
0
0
0
0
0
0.272727
1
0.227273
false
0.045455
0.136364
0
0.409091
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
1
d67a53433e748b3dfe2f8fbd06b9c917a36aef79
8,439
py
Python
Game.py
KRHS-GameProgramming-2015/Manpac
959bf7f5195a4edb528fbbf25b8896fcb28d5327
[ "BSD-2-Clause" ]
null
null
null
Game.py
KRHS-GameProgramming-2015/Manpac
959bf7f5195a4edb528fbbf25b8896fcb28d5327
[ "BSD-2-Clause" ]
3
2016-01-19T17:26:16.000Z
2016-02-10T16:59:25.000Z
Game.py
KRHS-GameProgramming-2015/Manpac
959bf7f5195a4edb528fbbf25b8896fcb28d5327
[ "BSD-2-Clause" ]
null
null
null
import sys, pygame, math, random from Wall import * from Ghost import * from Manpac import * from Norb import * from Score import * pygame.init() clock = pygame.time.Clock() width = 700 height = 700 size = width, height bgColor = r,g,b = 0, 0, 0 screen = pygame.display.set_mode(size) while True: ghosts = [Ghost("purple", [random.randint(250, 450),random.randint(250, 450)]), Ghost("blue", [random.randint(250, 450),random.randint(250, 450)]), Ghost("green", [random.randint(250, 450),random.randint(250, 450)])] player = Manpac([7,7], (602,602)) orbs = [Norb([75,75]), Norb([125,75]), Norb([175,75]), Norb([225,75]), Norb([275,75]), Norb([325,75]), Norb([375,75]), Norb([425,75]), Norb([475,75]), Norb([525,75]), Norb([575,75]), Norb([75,125]), Norb([75,175]), Norb([75,225]), Norb([75,275]), Norb([75,325]), Norb([75,375]), Norb([75,425]), Norb([75,475]), Norb([75,525]), Norb([75,575]), Fruit([75,625]), Norb([125,275]), Norb([125,325]), Norb([125,375]), Norb([125,425]), Norb([175,225]), Norb([175,275]), Norb([175,425]), Norb([175,475]), Norb([225,175]), Norb([225,225]), Norb([225,275]), Norb([225,425]), Norb([225,475]), Norb([225,525]), Norb([225,625]), Norb([175,625]), Norb([125,625]), Norb([275,225]), Norb([275,125]), Norb([275,175]), Norb([275,275]), Norb([275,325]), Norb([275,375]), Norb([275,425]), Norb([275,475]), Norb([275,525]), Norb([275,575]), Norb([275,625]), Norb([325,125]), Norb([325,275]), Norb([325,425]), Norb([325,575]), Norb([325,625]), Norb([375,125]), Norb([375,275]), Norb([375,425]), Norb([375,575]), Norb([375,625]), Norb([425,125]), Norb([425,175]), Norb([425,225]), Norb([425,275]), Norb([425,325]), Norb([425,375]), Norb([425,425]), Norb([425,475]), Norb([425,525]), Norb([425,575]), Norb([425,625]), Norb([475,175]), Norb([475,225]), Norb([475,275]), Norb([475,425]), Norb([475,475]), Norb([475,525]), Norb([475,625]), Norb([525,225]), Norb([525,275]), Norb([525,425]), Norb([525,475]), Norb([525,625]), Norb([575,275]), Norb([575,325]), Norb([575,375]), Norb([575,425]), Norb([575,625]), Fruit([625,75]), Norb([625,125]), Norb([625,175]), Norb([625,225]), Norb([625,275]), Norb([625,325]), Norb([625,375]), Norb([625,425]), Norb([625,475]), Norb([625,525]), Norb([625,575]), Norb([625,625]), Eorb([525,175]), Eorb([175,175]), Eorb([175,525]), Eorb([525,525]), ] walls = [Wall([0,0],[800,50]), #0 Wall([0,50],[50,300]), Wall([0,400],[50,650]), Wall([0,650],[700,700]), Wall([650,400],[700,650]), Wall([650,50],[700,300]), #5 Wall([100,100],[250,150]), Wall([100,150],[150,250]), Wall([450,100],[600,150]), Wall([550,150],[600,250]), Wall([100,450],[150,600]), #10 Wall([100,550],[250,600]), Wall([450,550],[600,600]), Wall([550,450],[600,600]), Wall([150,300],[250,400]), Wall([300,150],[400,250]), #15 Wall([450,300],[550,400]), Wall([300,450],[400,550]), #17 ] ghosts = [Ghost("purple", [random.randint(5, 8)*50+25,random.randint(5, 8)*50+25]), Ghost("blue", [random.randint(5, 8)*50+25,random.randint(5, 8)*50+25]), Ghost("green", [random.randint(5, 8)*50+25,random.randint(5, 8)*50+25])] score = Score("Score: ", (125,25)) lives = Score("Lives: ", (125,675)) while player.living and len(orbs) > 0: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: player.go("up") elif event.key == pygame.K_DOWN: player.go("down") elif event.key == pygame.K_LEFT: player.go("left") elif event.key == pygame.K_RIGHT: player.go("right") elif event.type == pygame.KEYUP: if event.key == pygame.K_UP: player.go("stop up") elif event.key == pygame.K_DOWN: player.go("stop down") elif event.key == pygame.K_LEFT: player.go("stop left") elif event.key == pygame.K_RIGHT: player.go("stop right") player.update(size) score.update(player.score) lives.update(player.lives) for wall in walls: player.collideWall(wall) for ghost in ghosts: ghost.update(size) for wall in walls: ghost.collideWall(wall) if ghost.living: if player.collideObject(ghost): if ghost.energized: ghost.die() else: player.die() player.rect.center = (625,625) for orb in orbs: orb.update(size) if player.collideObject(orb): player.score += orb.value if orb.kind == "energizer": for ghost in ghosts: ghost.weaken() orb.living = False print player.score for orb in orbs: if not orb.living: orbs.remove(orb) bgColor = r,g,b screen.fill(bgColor) for orb in orbs: screen.blit(orb.image, orb.rect) screen.blit(player.image, player.rect) for ghost in ghosts: if ghost.living: screen.blit(ghost.image, ghost.rect) for wall in walls: screen.blit(wall.image, wall.rect) screen.blit(score.image,score.rect) screen.blit(lives.image,lives.rect) pygame.display.flip() clock.tick(60) print len(orbs) if len(orbs) == 1: print orbs[0].rect.center while not player.living: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: player = Manpac([7,7], (602,602)) bg = pygame.image.load("MenuStuff/GameOver.png") bgrect = bg.get_rect() bgColor = r,g,b screen.fill(bgColor) screen.blit(bg, bgrect) pygame.display.flip() clock.tick(60) while len(orbs) <= 0: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: player = Manpac([7,7], (602,602)) orbs += [Norb([75,75])] bg = pygame.image.load("MenuStuff/Win screen.png") bgrect = bg.get_rect() bgColor = r,g,b screen.fill(bgColor) screen.blit(bg, bgrect) pygame.display.flip() clock.tick(60)
31.371747
87
0.426472
952
8,439
3.766807
0.131303
0.043503
0.039041
0.041829
0.344953
0.309258
0.30145
0.293921
0.273006
0.180145
0
0.189607
0.409409
8,439
268
88
31.488806
0.529896
0.000948
0
0.209877
0
0
0.017683
0.002611
0
0
0
0
0
0
null
null
0
0.024691
null
null
0.012346
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
1
d67b5cb25f09a20e3140a3f45e07da0db110f262
11,871
py
Python
SNDG/WebServices/Offtarget.py
ezequieljsosa/sndg-bio
5f709b5b572564ec1dfa40d090eca9a34295743e
[ "MIT" ]
null
null
null
SNDG/WebServices/Offtarget.py
ezequieljsosa/sndg-bio
5f709b5b572564ec1dfa40d090eca9a34295743e
[ "MIT" ]
null
null
null
SNDG/WebServices/Offtarget.py
ezequieljsosa/sndg-bio
5f709b5b572564ec1dfa40d090eca9a34295743e
[ "MIT" ]
1
2020-09-01T15:57:54.000Z
2020-09-01T15:57:54.000Z
import logging import multiprocessing import sys from Bio import Entrez from tqdm import tqdm from SNDG import execute, mkdir from SNDG.WebServices import download_file from SNDG.WebServices.NCBI import NCBI Entrez.email = 'A.N.Other@example.com' _log = logging.getLogger(__name__) from collections import defaultdict from SNDG.Annotation.GenebankUtils import GenebankUtils gut_microbiote_assemblies = [x.strip() for x in """GCA_000712235.1 GCA_002017855.1 GCA_002215605.1 GCF_000144975.1 GCF_000146835.1 GCF_000148995.1 GCF_000151245.1 GCF_000153885.1 GCF_000153905.1 GCF_000153925.1 GCF_000154065.1 GCF_000154085.1 GCF_000154105.1 GCF_000154205.1 GCF_000154285.1 GCF_000154305.1 GCF_000154345.1 GCF_000154365.1 GCF_000154385.1 GCF_000154405.1 GCF_000154425.1 GCF_000154465.1 GCF_000154485.1 GCF_000154505.1 GCF_000154525.1 GCF_000154565.1 GCF_000154805.1 GCF_000154825.1 GCF_000154845.1 GCF_000154865.1 GCF_000154985.1 GCF_000155085.1 GCF_000155205.1 GCF_000155435.1 GCF_000155495.1 GCF_000155835.1 GCF_000155855.1 GCF_000155875.1 GCF_000155955.1 GCF_000155975.1 GCF_000155995.1 GCF_000156015.1 GCF_000156035.2 GCF_000156055.1 GCF_000156075.1 GCF_000156175.1 GCF_000156195.1 GCF_000156215.1 GCF_000156375.1 GCF_000156395.1 GCF_000156495.1 GCF_000156515.1 GCF_000156535.1 GCF_000156655.1 GCF_000157015.1 GCF_000157055.1 GCF_000157115.2 GCF_000157935.1 GCF_000157955.1 GCF_000157975.1 GCF_000157995.1 GCF_000158035.1 GCF_000158055.1 GCF_000158075.1 GCF_000158195.2 GCF_000158315.2 GCF_000158435.2 GCF_000158455.1 GCF_000158475.2 GCF_000158555.2 GCF_000158655.1 GCF_000158835.2 GCF_000159175.1 GCF_000159195.1 GCF_000159215.1 GCF_000159495.1 GCF_000159715.1 GCF_000159915.2 GCF_000159975.2 GCF_000160095.1 GCF_000160175.1 GCF_000160455.2 GCF_000160575.1 GCF_000160595.1 GCF_000161955.2 GCF_000162075.1 GCF_000162115.1 GCF_000162575.1 GCF_000163095.1 GCF_000163735.1 GCF_000163955.1 GCF_000164175.1 GCF_000169015.1 GCF_000169035.1 GCF_000169255.2 GCF_000169475.1 GCF_000172135.1 GCF_000172175.1 GCF_000173355.1 GCF_000173795.1 GCF_000173815.1 GCF_000173975.1 GCF_000174195.1 GCF_000174215.1 GCF_000177015.3 GCF_000178195.1 GCF_000178215.1 GCF_000179075.1 GCF_000185325.1 GCF_000185345.1 GCF_000185665.1 GCF_000185685.2 GCF_000185705.2 GCF_000185845.1 GCF_000186505.1 GCF_000186545.1 GCF_000187265.1 GCF_000187895.1 GCF_000188175.1 GCF_000188195.1 GCF_000191845.1 GCF_000191865.1 GCF_000195635.1 GCF_000204455.1 GCF_000205025.1 GCF_000205165.1 GCF_000213555.1 GCF_000218325.1 GCF_000218405.2 GCF_000220825.1 GCF_000220865.1 GCF_000224635.1 GCF_000224655.1 GCF_000225685.1 GCF_000225705.1 GCF_000225745.1 GCF_000225845.1 GCF_000227195.1 GCF_000227255.2 GCF_000231275.1 GCF_000233455.1 GCF_000233495.1 GCF_000233955.1 GCF_000234155.1 GCF_000234175.1 GCF_000235885.1 GCF_000238035.1 GCF_000238615.1 GCF_000238635.1 GCF_000238655.1 GCF_000238675.1 GCF_000238695.1 GCF_000238735.1 GCF_000238755.1 GCF_000239255.1 GCF_000239295.1 GCF_000239335.1 GCF_000239735.1 GCF_000241405.1 GCF_000242215.1 GCF_000242435.1 GCF_000243175.1 GCF_000243215.1 GCF_000245775.1 GCF_000250875.1 GCF_000261205.1 GCF_000273465.1 GCF_000273585.1 GCF_000296445.1 GCF_000296465.1 GCF_000297815.1 GCF_000315485.1 GCF_000320405.1 GCF_000332875.2 GCF_000345045.1 GCF_000349975.1 GCF_000376405.1 GCF_000381365.1 GCF_000382085.1 GCF_000398925.1 GCF_000411235.1 GCF_000411275.1 GCF_000411295.1 GCF_000411315.1 GCF_000411335.1 GCF_000411415.1 GCF_000412335.1 GCF_000413335.1 GCF_000413355.1 GCF_000413375.1 GCF_000466385.1 GCF_000466465.2 GCF_000466485.1 GCF_000466565.1 GCF_000468015.1 GCF_000469305.1 GCF_000469345.1 GCF_000469445.2 GCF_000479045.1 GCF_000507845.1 GCF_000507865.1 GCF_000517805.1 GCF_000690925.1 GCF_000760655.1 GCF_000763035.1 GCF_000763055.1 GCF_000771165.1 GCF_000969835.1 GCF_000969845.1 GCF_001025135.1 GCF_001025155.1 GCF_001185345.1 GCF_001311295.1 GCF_001315785.1 GCF_001434655.1 GCF_001434945.1 GCF_001435475.1 GCF_001435665.1 GCF_001436305.1 GCF_001941425.1 GCF_002222595.1 GCF_900129655.1 GCF_900167285.1 GCF_001025195.1 GCF_001025215.1 GCF_001434175.1""".split("\n")] import gzip class Offtarget(object): DEFAULT_GUT_FILENAME = "gut_microbiota.fasta.gz" DEFAULT_HUMAN_FILENAME = "human_uniprot100.fa.gz" DEG_PROT_URL = {"p": "http://tubic.tju.edu.cn/deg_test/public/download/DEG10.aa.gz", "a": "http://tubic.tju.edu.cn/deg_test/public/download/DEG30.aa.gz", "e": "http://tubic.tju.edu.cn/deg_test/public/download/DEG20.aa.gz" } DEG_FAA_NAMES = { "a": "degaa-a.dat", "p": "degaa-p.dat", "e": "degaa-e.dat" } @staticmethod def download_deg(dst="/data/databases/deg/"): for x in ["p", "e", "a"]: download_file(Offtarget.DEG_PROT_URL[x], f"{dst}/{Offtarget.DEG_FAA_NAMES[x]}.gz", ovewrite=True) execute(f"gunzip -f {dst}/{Offtarget.DEG_FAA_NAMES[x]}.gz") # execute(f"makeblastdb -dbtype prot -in {dst}/{Offtarget.DEG_FAA_NAMES[x]}") @staticmethod def download_human_prots(dst="/data/databases/human/"): file_path = dst + Offtarget.DEFAULT_HUMAN_FILENAME unip_url = "https://www.uniprot.org/uniref/?query=uniprot:(taxonomy:%22Homo%20sapiens%20(Human)%20[9606]%22)%20identity:1.0&format=fasta&force=true&compress=yes" download_file(unip_url, file_path, ovewrite=True, timeout=120) return file_path @staticmethod def create_human_microbiome(dst="/data/databases/human/", update=False): dst_accs = dst + "gut_microbiota_assemblies/" mkdir(dst_accs) final_file = dst + Offtarget.DEFAULT_GUT_FILENAME utils = GenebankUtils() with gzip.open(final_file, "wt") as h: for accession in tqdm(gut_microbiote_assemblies, file=sys.stderr): genome_path = dst_accs + accession + ".genomic.gbff.gz" if update or not os.path.exists(genome_path): genome_path = NCBI.download_assembly(accession, dst_accs) utils.proteins(genome_path, h) return final_file @staticmethod def count_organism_from_microbiome_blast(tbl_blast_result_path, microbiome_fasta, identity_threshold=0.4, out_tbl=None, gene_id_column="id"): prot_org_map = {} organisms = [] with (gzip.open(microbiome_fasta, "rt") if microbiome_fasta.endswith(".gz") else open(microbiome_fasta)) as h: for line in h: if line.startswith(">"): seqid = line.split()[0].strip().replace(">", "") try: org = line.replace("[[", "[").split("[")[1].strip()[:-1] except IndexError: err = "fasta does not have the organism name at the fasta header." err += "example: >HMPREF1002_RS00015 alpha/beta hydrolase [Porphyromonas sp. 31_2]" raise LookupError(err) organisms.append(org) prot_org_map[seqid] = org organisms_count = len(set(organisms)) query_orgs = defaultdict(lambda: []) with open(tbl_blast_result_path) as h: for l in list(h)[1:]: query, hit, identity = l.split()[:3] identity = float(identity) / 100.0 if identity_threshold <= identity: query_orgs[query].append(prot_org_map[hit]) for query, hits in query_orgs.items(): query_orgs[query] = set(hits) if out_tbl: with open(out_tbl, "w") as h: h.write("\t".join( [gene_id_column, "gut_microbiote_count", "gut_microbiote_norm", "gut_microbiote_organisms"]) + "\n") for query, hits in query_orgs.items(): h.write("\t".join( [query, str(len(hits)), str(len(hits) * 1.0 / organisms_count), ";".join(hits)]) + "\n") return query_orgs @staticmethod def offtargets(proteome, dst_resutls, offtarget_db, cpus=multiprocessing.cpu_count(),min_identity=50): cmd = f"diamond blastp --evalue 1e-5 --max-hsps 1 --outfmt 6 --max-target-seqs 10000 --db {offtarget_db} --query {proteome} --threads {cpus}|awk '$3>{min_identity}' > {dst_resutls}" execute(cmd) return dst_resutls if __name__ == "__main__": from SNDG import init_log import argparse import os from SNDG.Sequence import smart_parse parser = argparse.ArgumentParser(description='Offtarget Utilities') subparsers = parser.add_subparsers(help='commands', description='valid subcommands', required=True, dest='command') gut_download = subparsers.add_parser('download', help='Download offtarget data') gut_download.add_argument('-db', '--databases', choices=["all", "deg", "human", "gut_microbiote"], default="all") gut_download.add_argument('-o', '--output', help="output_directory", default="/data/databases/") gut_download.add_argument('--force', action="store_true") gut_microbiote_blast = subparsers.add_parser('gut_microbiote_blast', help='Runs blastp against gut microbiote and counts organisms') gut_microbiote_blast.add_argument('input_faa') gut_microbiote_blast.add_argument('-o', '--output', help="output_directory", default="./") gut_microbiote_blast.add_argument('-db', '--database', help="gut microbiome fasta", default="/data/databases/human/gut_microbiota.fasta.gz") gut_microbiote_blast.add_argument('--cpus', default=multiprocessing.cpu_count()) gut_microbiote_blast.add_argument('--force', action="store_true") args = parser.parse_args() init_log() if args.command == "download": if args.databases in ["all", "gut_microbiote"]: path = f'{args.output}/gut_microbiote/{Offtarget.DEFAULT_GUT_FILENAME}' if args.force or not os.path.exists(path): path = Offtarget.create_human_microbiome(dst=path) else: sys.stderr.write(f'{path} already exists, overwrite using --force') filename = os.path.basename(path) execute( f"zcat {path} | makeblastdb -title gut_microbiote -out {args.output}/human/{filename} -dbtype prot -in -") if args.databases in ["all", "human"]: path = f'{args.output}/human/' if args.force or not os.path.exists(path + Offtarget.DEFAULT_HUMAN_FILENAME): path = Offtarget.download_human_prots(dst=path) else: sys.stderr.write(f'{path} already exists, overwrite using --force') filename = os.path.basename(path) execute( f"zcat {path}{Offtarget.DEFAULT_HUMAN_FILENAME} | makeblastdb -title human -out {path}{Offtarget.DEFAULT_HUMAN_FILENAME} -dbtype prot -in -") if args.databases in ["all", "deg"]: mkdir(f'{args.output}/deg/') Offtarget.download_deg(f'{args.output}/deg/') elif args.command == "gut_microbiote_blast": blast_gut_path = f'{args.output}/gut_microbiome.blast.tbl' gut_result_path = f'{args.output}/gut_microbiome.tbl' # if not os.path.exists(args.database + ".phr"): # raise FileNotFoundError(f"{args.database} index files could not be found. Run makeblastdb") if args.force or not os.path.exists(blast_gut_path): Offtarget.offtargets(args.input_faa, blast_gut_path, offtarget_db=args.database, cpus=args.cpus) else: sys.stderr.write(f'{blast_gut_path} already exists, overwrite using --force') Offtarget.count_organism_from_microbiome_blast(blast_gut_path, args.database, identity_threshold=0.5, out_tbl=gut_result_path)
29.6775
190
0.701289
1,689
11,871
4.673771
0.28952
0.102356
0.018242
0.009501
0.154421
0.111477
0.088928
0.081834
0.060299
0.03775
0
0.242554
0.191138
11,871
399
191
29.75188
0.579567
0.018364
0
0.049315
0
0.019178
0.48708
0.044639
0
0
0
0
0
1
0.013699
false
0
0.041096
0
0.079452
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d67c213b9a36706b9d0346fd0b72cfdc78942fe2
855
py
Python
palabox/processing/text/properly_cut_text.py
marcoboucas/palabox
d6e937db909daac0f9d3c5dff2309c29b5b68ea8
[ "MIT" ]
null
null
null
palabox/processing/text/properly_cut_text.py
marcoboucas/palabox
d6e937db909daac0f9d3c5dff2309c29b5b68ea8
[ "MIT" ]
null
null
null
palabox/processing/text/properly_cut_text.py
marcoboucas/palabox
d6e937db909daac0f9d3c5dff2309c29b5b68ea8
[ "MIT" ]
null
null
null
"""Cut properly some text.""" import re END_OF_SENTENCE_CHARACTERS = {".", ";", "!", "?"} def properly_cut_text( text: str, start_idx: int, end_idx: int, nbr_before: int = 30, nbr_after: int = 30 ) -> str: """Properly cut a text around some interval.""" str_length = len(text) start_idx = max(0, start_idx - nbr_before) end_idx = end_idx + nbr_after # Change the end depending on the value match = re.search(r"\.[^\d]|\?|\!", text[end_idx:], flags=re.IGNORECASE) if match: end_idx = match.end() + end_idx else: end_idx = str_length # Change the beginning depending on the value match = re.search(r"(\.|\?|\!)(?!.*\1)", text[: start_idx - 1], flags=re.IGNORECASE) if match: start_idx = match.end() + 1 else: start_idx = 0 return text[start_idx:end_idx].strip()
27.580645
88
0.604678
124
855
3.959677
0.346774
0.09776
0.07332
0.077393
0.232179
0.13442
0.13442
0.13442
0
0
0
0.01374
0.233918
855
30
89
28.5
0.735878
0.173099
0
0.210526
0
0
0.05036
0
0
0
0
0
0
1
0.052632
false
0
0.052632
0
0.157895
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d67c4663259aa37ae4097e44e2683c283befb25b
1,307
py
Python
Level2/Lessons17687/gamjapark.py
StudyForCoding/ProgrammersLevel
dc957b1c02cc4383a93b8cbf3d739e6c4d88aa25
[ "MIT" ]
null
null
null
Level2/Lessons17687/gamjapark.py
StudyForCoding/ProgrammersLevel
dc957b1c02cc4383a93b8cbf3d739e6c4d88aa25
[ "MIT" ]
null
null
null
Level2/Lessons17687/gamjapark.py
StudyForCoding/ProgrammersLevel
dc957b1c02cc4383a93b8cbf3d739e6c4d88aa25
[ "MIT" ]
1
2021-04-05T07:35:59.000Z
2021-04-05T07:35:59.000Z
# [3차] n진수 게임 import string tmp = string.digits+string.ascii_uppercase[:6] def convert(n, base): q, r = divmod(n, base) if q == 0: return tmp[r] else: return convert(q, base) + tmp[r] def solution(n, t, m, p): answer, nums = '', '' count, cur = 0, 0 while count < t * m: num = convert(cur,n) nums += num count += len(num) cur += 1 for i in range(p-1, count, m): answer += nums[i] return answer[:t] ''' 채점을 시작합니다. 정확성 테스트 테스트 1 〉 통과 (0.01ms, 10.3MB) 테스트 2 〉 통과 (0.02ms, 10.3MB) 테스트 3 〉 통과 (0.02ms, 10.3MB) 테스트 4 〉 통과 (0.03ms, 10.4MB) 테스트 5 〉 통과 (0.11ms, 10.3MB) 테스트 6 〉 통과 (0.11ms, 10.4MB) 테스트 7 〉 통과 (0.21ms, 10.3MB) 테스트 8 〉 통과 (0.14ms, 10.3MB) 테스트 9 〉 통과 (0.12ms, 10.2MB) 테스트 10 〉 통과 (0.14ms, 10.3MB) 테스트 11 〉 통과 (0.14ms, 10.3MB) 테스트 12 〉 통과 (0.16ms, 10.3MB) 테스트 13 〉 통과 (0.14ms, 10.3MB) 테스트 14 〉 통과 (24.25ms, 10.4MB) 테스트 15 〉 통과 (24.34ms, 10.4MB) 테스트 16 〉 통과 (22.35ms, 10.4MB) 테스트 17 〉 통과 (1.03ms, 10.2MB) 테스트 18 〉 통과 (1.30ms, 10.3MB) 테스트 19 〉 통과 (0.36ms, 10.3MB) 테스트 20 〉 통과 (1.15ms, 10.4MB) 테스트 21 〉 통과 (6.58ms, 10.3MB) 테스트 22 〉 통과 (2.70ms, 10.3MB) 테스트 23 〉 통과 (8.42ms, 10.3MB) 테스트 24 〉 통과 (11.47ms, 10.4MB) 테스트 25 〉 통과 (10.08ms, 10.3MB) 테스트 26 〉 통과 (3.43ms, 10.3MB) 채점 결과 정확성: 100.0 합계: 100.0 / 100.0 '''
22.534483
46
0.553175
297
1,307
2.518519
0.316498
0.104278
0.171123
0.042781
0.15508
0.128342
0.128342
0
0
0
0
0.23061
0.260138
1,307
58
47
22.534483
0.516029
0.008416
0
0
0
0
0
0
0
0
0
0
0
1
0.105263
false
0
0.052632
0
0.315789
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
d67ed600e6c41963e2d457d2e537a8860f022e80
1,292
py
Python
models/base.py
IlyaBizyaev/Im2Vec
4fff000c84500c6e977c502519497e27e1f946f2
[ "Apache-2.0" ]
null
null
null
models/base.py
IlyaBizyaev/Im2Vec
4fff000c84500c6e977c502519497e27e1f946f2
[ "Apache-2.0" ]
null
null
null
models/base.py
IlyaBizyaev/Im2Vec
4fff000c84500c6e977c502519497e27e1f946f2
[ "Apache-2.0" ]
null
null
null
from abc import abstractmethod from typing import Any, List import torch def interpolate_vectors(v1: torch.Tensor, v2: torch.Tensor, n: int) -> torch.Tensor: step = (v2 - v1) / (n - 1) return torch.stack([v1 + i * step for i in range(n)], dim=0) def reparameterize(mu: torch.Tensor, log_var: torch.Tensor) -> torch.Tensor: """ Reparameterization trick to sample from N(mu, var) from N(0,1). :param mu: (Tensor) Mean of the latent Gaussian [B x D] :param log_var: (Tensor) Standard deviation of the latent Gaussian [B x D] :return: (Tensor) [B x D] """ std = torch.exp(0.5 * log_var) eps = torch.randn_like(std) return eps * std + mu class BaseVAE(torch.nn.Module): def __init__(self) -> None: super(BaseVAE, self).__init__() def encode(self, inp: torch.Tensor) -> (torch.Tensor, torch.Tensor): raise NotImplementedError def decode(self, inp: torch.Tensor) -> torch.Tensor: raise NotImplementedError def generate(self, x: torch.Tensor, **kwargs) -> torch.Tensor: raise NotImplementedError @abstractmethod def forward(self, *inputs: torch.Tensor) -> List[torch.Tensor]: pass @abstractmethod def loss_function(self, *inputs: Any, **kwargs) -> dict: pass
28.711111
84
0.648607
177
1,292
4.655367
0.40678
0.200243
0.07767
0.106796
0.20267
0.20267
0.17233
0
0
0
0
0.011
0.226006
1,292
44
85
29.363636
0.813
0.170279
0
0.28
0
0
0
0
0
0
0
0
0
1
0.32
false
0.08
0.12
0
0.56
0
0
0
0
null
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
1
0
0
1
0
0
4
d67f25d3516ae26ca8b76017de005e34113a7d6e
7,293
py
Python
process/triplifier.py
biocodellc/ontology-data-pipeline
f89dc159ab710368b3054bf8e8d70fb4c967527c
[ "BSD-3-Clause" ]
13
2020-06-27T18:37:12.000Z
2022-03-07T16:19:14.000Z
process/triplifier.py
biocodellc/ontology-data-pipeline
f89dc159ab710368b3054bf8e8d70fb4c967527c
[ "BSD-3-Clause" ]
31
2019-01-05T18:39:37.000Z
2021-12-13T19:43:40.000Z
process/triplifier.py
biocodellc/ontology-data-pipeline
f89dc159ab710368b3054bf8e8d70fb4c967527c
[ "BSD-3-Clause" ]
1
2021-11-17T19:04:31.000Z
2021-11-17T19:04:31.000Z
# -*- coding: utf-8 -*- import re import pandas as pd import multiprocessing from multiprocessing.dummy import Pool as ThreadPool import logging from .utils import isNull class Triplifier(object): def __init__(self, config): self.config = config self.integer_columns = [] for rule in self.config.rules: if rule['rule'].lower() == 'integer': self.integer_columns.extend(rule['columns']) def triplify(self, data_frame): """ Generate triples using the given data_frame and the config mappings :param data_frame: pandas DataFrame :return: list of triples for the given data_frame data """ triples = [] data_frame = data_frame.fillna('') for index, row in data_frame.iterrows(): triples.extend(self._generate_triples_for_row(row)) triples.extend(self._generate_triples_for_relation_predicates()) triples.extend(self._generate_triples_for_entities()) triples.append(self._generate_ontology_import_triple()) return triples def _generate_triples_for_chunk(self, chunk): triples = [] for index, row in chunk.iterrows(): triples.extend(self._generate_triples_for_row(row)) return triples def _generate_triples_for_row(self, row): row_triples = [] for entity in self.config.entities: s = "<{}{}>".format(entity['identifier_root'], self._get_value(row, entity['unique_key'])) if entity['concept_uri'] != 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': o = "<{}>".format(entity['concept_uri']) row_triples.append("{} <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> {}".format(s, o)) for column, uri in entity['columns']: val = self._get_value(row, column) list_for_column = self.config.get_list(column) # if there is a specified list for this column & the field contains a defined_by, substitute the # defined_by value for the list field literal_val = True if list_for_column and "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" in uri: for i in list_for_column: if i['field'] == val and i['defined_by']: val = i['defined_by'] literal_val = False break # if this is not a list but URI specified is rdf:type for mapping column then we assume this is object Property # and attempt to convert elif "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" in uri: val = self.config._get_uri_from_label(val) literal_val = False # format and print all of the instance data triples if (not isNull(val)): p = "<{}>".format(uri) if literal_val: type = self._get_type(val) o = "\"{}\"^^<http://www.w3.org/2001/XMLSchema#{}>".format(val, type) else: o = "<{}>".format(str(val)) row_triples.append("{} {} {}".format(s, p, o)) # format and print all triples describing relations for relation in self.config.relations: try: subject_entity = self.config.get_entity(relation['subject_entity_alias']) object_entity = self.config.get_entity(relation['object_entity_alias']) s = "<{}{}>".format(subject_entity['identifier_root'], self._get_value(row, subject_entity['unique_key'])) p = "<{}>".format(relation['predicate']) o = "<{}{}>".format(object_entity['identifier_root'], self._get_value(row, object_entity['unique_key'])) row_triples.append("{} {} {}".format(s, p, o)) except Exception as err: raise RuntimeError("Error assigning relations between a subject and an object. " "Check to be sure each relation maps to an entity alias") return row_triples def _generate_triples_for_relation_predicates(self): predicate_triples = [] for relation in self.config.relations: s = "<{}>".format(relation['predicate']) p = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>" o = "<http://www.w3.org/2002/07/owl#ObjectProperty>" predicate_triples.append("{} {} {}".format(s, p, o)) return predicate_triples def _generate_triples_for_entities(self): entity_triples = [] for entity in self.config.entities: entity_triples.extend(self._generate_property_triples(entity['columns'])) if entity['concept_uri'] != 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type': entity_triples.append(self._generate_class_triple(entity['concept_uri'])) return entity_triples def _generate_ontology_import_triple(self): s = "<urn:importInstance>" p = "<http://www.w3.org/2002/07/owl#imports>" o = "<{}>".format(self.config.ontology) return "{} {} {}".format(s, p, o) @staticmethod def _generate_class_triple(concept_uri): s = "<{}>".format(concept_uri) p = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>" o = "<http://www.w3.org/2000/01/rdf-schema#Class>" return "{} {} {}".format(s, p, o) @staticmethod def _generate_property_triples(properties): """ generate triples for the properties of each entity """ property_triples = [] for column, uri in properties: s = "<{}>".format(uri) p = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#type>" o = "<http://www.w3.org/1999/02/22-rdf-syntax-ns#Property>" property_triples.append("{} {} {}".format(s, p, o)) o2 = "<http://www.w3.org/2002/07/owl#DatatypeProperty>" property_triples.append("{} {} {}".format(s, p, o2)) p2 = "<http://www.w3.org/2000/01/rdf-schema#isDefinedBy>" property_triples.append("{} {} {}".format(s, p2, s)) return property_triples def _get_value(self, row_data, column): coerce_integer = False if column in self.integer_columns: coerce_integer = True # TODO: This line breaks in certain situations. Workaround for now: return an empty string on exception try: val = str(row_data[column]) except: return '' # need to perform coercion here as pandas can't store ints along floats and strings. The only way to coerce # to ints is to drop all strings and null values. We don't want to do this in the case of a warning. if coerce_integer: return int(float(val)) if re.fullmatch(r"[+-]?\d+(\.0+)?", str(val)) else val return val @staticmethod def _get_type(val): if re.fullmatch(r"[+-]?\d+", str(val)): return 'integer' elif re.fullmatch(r"[+-]?\d+\.\d+", str(val)): return 'float' else: return 'string'
39.209677
127
0.574935
894
7,293
4.525727
0.214765
0.037074
0.033366
0.044488
0.347751
0.314632
0.219476
0.150766
0.121602
0.09738
0
0.024718
0.295489
7,293
185
128
39.421622
0.762748
0.124092
0
0.224
0
0.072
0.197118
0
0
0
0
0.005405
0
1
0.088
false
0
0.08
0
0.288
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d680bcdee688777add2842ce0bdbc8ac9c241004
455
py
Python
core/urls.py
tyronedamasceno/coffe-api
8cbf48c35c5dbd9ddfbeb921140be1d96a48698f
[ "MIT" ]
null
null
null
core/urls.py
tyronedamasceno/coffe-api
8cbf48c35c5dbd9ddfbeb921140be1d96a48698f
[ "MIT" ]
8
2020-02-12T02:59:28.000Z
2022-02-10T14:02:04.000Z
core/urls.py
tyronedamasceno/coffe-api
8cbf48c35c5dbd9ddfbeb921140be1d96a48698f
[ "MIT" ]
null
null
null
from django.urls import path, include from rest_framework import routers from core import views router = routers.DefaultRouter() router.register('coffe_types', views.CoffeTypeViewSet, base_name='coffe_types') router.register('harvests', views.HarvestViewSet, base_name='harvests') router.register( 'storage_report', views.StorageReportViewSet, base_name='storage_report' ) app_name = 'core' urlpatterns = [ path('', include(router.urls)), ]
22.75
79
0.771429
54
455
6.333333
0.481481
0.122807
0
0
0
0
0
0
0
0
0
0
0.10989
455
19
80
23.947368
0.844444
0
0
0
0
0
0.153846
0
0
0
0
0
0
1
0
false
0
0.230769
0
0.230769
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d6812fee96c936a6d4abcdec5e68b3b5abdd5c3f
409
py
Python
api/core/models.py
vrmartins/poc-django-rest-framework
a4914c25c7decbe16f5233233e9da4dce57f64d8
[ "MIT" ]
null
null
null
api/core/models.py
vrmartins/poc-django-rest-framework
a4914c25c7decbe16f5233233e9da4dce57f64d8
[ "MIT" ]
7
2020-04-05T14:25:37.000Z
2021-09-22T18:50:16.000Z
api/core/models.py
vrmartins/poc-django-rest-framework
a4914c25c7decbe16f5233233e9da4dce57f64d8
[ "MIT" ]
null
null
null
from django.db import models from core.utils.cnpj_is_valid import cnpj_is_valid class Customer(models.Model): name = models.CharField(max_length=50, null=False, blank=False) address = models.CharField(max_length=50, null=False, blank=False) cnpj = models.CharField(max_length=14, unique=True, null=False, blank=False, validators=[cnpj_is_valid]) def __str__(self): return self.name
34.083333
108
0.750611
61
409
4.819672
0.491803
0.061224
0.112245
0.244898
0.306122
0.306122
0.306122
0.306122
0.306122
0
0
0.017094
0.141809
409
11
109
37.181818
0.820513
0
0
0
0
0
0
0
0
0
0
0
0
1
0.125
false
0
0.25
0.125
1
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
1
1
0
0
3
d681b7a1e2748c8e44788cf4efd924a9d9b41944
5,876
py
Python
ros/src/waypoint_updater/waypoint_updater.py
ryan-jonesford/CarND-Capstone
f8095bb2b7370b0825a89d419c19884431dfb754
[ "MIT" ]
null
null
null
ros/src/waypoint_updater/waypoint_updater.py
ryan-jonesford/CarND-Capstone
f8095bb2b7370b0825a89d419c19884431dfb754
[ "MIT" ]
3
2018-11-04T23:54:56.000Z
2018-11-18T19:37:11.000Z
ros/src/waypoint_updater/waypoint_updater.py
ryan-jonesford/CarND-Capstone
f8095bb2b7370b0825a89d419c19884431dfb754
[ "MIT" ]
2
2018-10-29T23:45:15.000Z
2018-11-04T21:43:16.000Z
#!/usr/bin/env python import rospy from geometry_msgs.msg import PoseStamped from styx_msgs.msg import Lane, Waypoint from scipy.spatial import KDTree import numpy as np from std_msgs.msg import Int32 import math ''' This node will publish waypoints from the car's current position to some `x` distance ahead. As mentioned in the doc, you should ideally first implement a version which does not care about traffic lights or obstacles. Once you have created dbw_node, you will update this node to use the status of traffic lights too. Please note that our simulator also provides the exact location of traffic lights and their current status in `/vehicle/traffic_lights` message. You can use this message to build this node as well as to verify your TL classifier. ''' LOOKAHEAD_WPS = 50 # Number of waypoints we will publish. You can change this number UPDATE_RATE = 30 #hz NO_WP = -1 DECEL_RATE = 1.5 # m/s^2 STOPLINE = 3 # waypoints behind stopline to stop DELAY = 20. # update difference between this node and twist_controller in hz class WaypointUpdater(object): def __init__(self, rate_hz=UPDATE_RATE): rospy.init_node('waypoint_updater') self.pose = None self.base_waypoints = None self.waypoints_2d = None self.waypoint_ktree = None self.freq = rate_hz self.nearest_wp_idx = NO_WP self.stop_wp = NO_WP rospy.Subscriber('/current_pose', PoseStamped, self.pose_cb) rospy.Subscriber('/base_waypoints', Lane, self.waypoints_cb) rospy.Subscriber('/traffic_waypoint', Int32, self.traffic_cb) self.final_waypoints_pub = rospy.Publisher('final_waypoints', Lane, queue_size=1) self.loop() def loop(self): rate = rospy.Rate(self.freq) while not rospy.is_shutdown(): if (self.pose != None) and \ (self.base_waypoints != None) and \ (self.waypoint_ktree != None): self.nearest_wp_idx = self.get_nearest_wp_indx() self.publish_waypoints() # don't update unless we get new positional data self.pose = None rate.sleep() def publish_waypoints(self): lane = self.generate_lane() self.final_waypoints_pub.publish(lane) def generate_lane(self): lane = Lane() lane.header = self.base_waypoints.header look_ahead_wp_max = self.nearest_wp_idx + LOOKAHEAD_WPS base_wpts = self.base_waypoints.waypoints[self.nearest_wp_idx:look_ahead_wp_max] if self.stop_wp == NO_WP or (self.stop_wp >= look_ahead_wp_max): lane.waypoints = base_wpts else: temp_waypoints = [] stop_idx = max(self.stop_wp - self.nearest_wp_idx - STOPLINE, 0) for i, wp in enumerate(base_wpts): temp_wp = Waypoint() temp_wp.pose = wp.pose if stop_idx >= STOPLINE: dist = self.distance(base_wpts, i, stop_idx) # account for system lag if DELAY > 0: delay_s = 1./DELAY else: delay_s = 0 # x = xo + vot + .5at^2, xo = 0 dist += self.get_waypoint_velocity(base_wpts[i])*delay_s+.5*DECEL_RATE*delay_s*delay_s # v^2 = vo^2 + 2*a*(x-xo) # v^2 = 0 + 2*a*(dist) # v = sqrt(2*a*dist) vel = math.sqrt(2*DECEL_RATE*dist) if vel < 1.0: vel = 0.0 else: vel = 0.0 temp_wp.twist.twist.linear.x = min(vel, self.get_waypoint_velocity(base_wpts[0])) temp_waypoints.append(temp_wp) lane.waypoints = temp_waypoints return lane def get_nearest_wp_indx(self): ptx = self.pose.pose.position.x pty = self.pose.pose.position.y nearest_indx = self.waypoint_ktree.query([ptx,pty],1)[1] nearest_coord = self.waypoints_2d[nearest_indx] prev_coord = self.waypoints_2d[nearest_indx - 1] neareset_vect = np.array(nearest_coord) prev_vect = np.array(prev_coord) positive_vect = np.array([ptx,pty]) # check if the nearest_coord is infront or behind the car val = np.dot(neareset_vect-prev_vect, positive_vect-neareset_vect) if val > 0.0: # works for waypoints that are in a loop nearest_indx = (nearest_indx + 1) % len(self.waypoints_2d) return nearest_indx def pose_cb(self, msg): self.pose = msg def waypoints_cb(self, lane): self.base_waypoints = lane if not self.waypoints_2d: self.waypoints_2d = [ [ waypoint.pose.pose.position.x, waypoint.pose.pose.position.y ] for waypoint in lane.waypoints ] self.waypoint_ktree = KDTree(self.waypoints_2d) def traffic_cb(self, msg): self.stop_wp = msg.data def obstacle_cb(self, msg): # TODO: Callback for /obstacle_waypoint message. We will implement it later pass def get_waypoint_velocity(self, waypoint): return waypoint.twist.twist.linear.x def set_waypoint_velocity(self, waypoints, waypoint, velocity): waypoints[waypoint].twist.twist.linear.x = velocity def distance(self, waypoints, wp1, wp2): dist = 0 dl = lambda a, b: math.sqrt((a.x-b.x)**2 + (a.y-b.y)**2 + (a.z-b.z)**2) for i in range(wp1, wp2+1): dist += dl(waypoints[wp1].pose.pose.position, waypoints[i].pose.pose.position) wp1 = i return dist if __name__ == '__main__': try: WaypointUpdater() except rospy.ROSInterruptException: rospy.logerr('Could not start waypoint updater node.')
36.955975
131
0.615895
802
5,876
4.32793
0.266833
0.037453
0.030251
0.023048
0.084126
0.035725
0
0
0
0
0
0.015188
0.294078
5,876
158
132
37.189873
0.821601
0.088836
0
0.063636
0
0
0.025512
0
0
0
0
0.006329
0
1
0.109091
false
0.009091
0.063636
0.009091
0.218182
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d681e5845812f47217df144a4c421bd1734a615c
1,633
py
Python
tools/configure.py
corrodedHash/sigmarsGarden
c6070005d9e01523c0b0deb2efbbfa5ffef0ce6f
[ "MIT" ]
null
null
null
tools/configure.py
corrodedHash/sigmarsGarden
c6070005d9e01523c0b0deb2efbbfa5ffef0ce6f
[ "MIT" ]
null
null
null
tools/configure.py
corrodedHash/sigmarsGarden
c6070005d9e01523c0b0deb2efbbfa5ffef0ce6f
[ "MIT" ]
null
null
null
from typing import Any import cv2 import numpy as np from sigmarsGarden.config import Configuration from sigmarsGarden.parse import circle_coords def configure(img: Any) -> Configuration: cv2.namedWindow("configureDisplay") # def click_and_crop(event, x, y, flags, param) -> None: # print(event, x, y, flags, param) # cv2.setMouseCallback("configureDisplay", click_and_crop) cv2.imshow("configureDisplay", img) result = Configuration() result.down_distance = 114 result.right_distance = 66 result.start_coord = (1371, 400) result.radius = 28 circle_color = [0, 0, 0] while True: keycode = cv2.waitKey(0) print(keycode) left = 81 up = 82 down = 84 right = 83 left = 104 up = 116 down = 110 right = 115 esc = 27 start_coord = list(result.start_coord) if keycode == left: start_coord[0] -= 1 elif keycode == right: start_coord[0] += 1 elif keycode == up: start_coord[1] -= 1 elif keycode == down: start_coord[1] += 1 elif keycode == esc: break result.start_coord = (start_coord[0], start_coord[1]) new_img = np.copy(img) for coord in circle_coords(result): new_img = cv2.circle(new_img, coord, result.radius, circle_color) cv2.imshow("configureDisplay", new_img) print(start_coord) return result def main() -> None: x = cv2.imread("testboards/1.jpg") print(configure(x)) if __name__ == "__main__": main()
24.014706
77
0.590325
199
1,633
4.678392
0.38191
0.118153
0.051557
0.025779
0.135338
0.098818
0
0
0
0
0
0.052074
0.306185
1,633
67
78
24.373134
0.769638
0.090631
0
0
0
0
0.048616
0
0
0
0
0
0
1
0.040816
false
0
0.102041
0
0.163265
0.061224
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d682adb11768d513c2f5a3a5ae14d06fb88db0b8
4,847
py
Python
gpt2_generate.py
LindgeW/PreLM
39a6b1c2fc0ccff7e8143f14d113cdfa79f63d79
[ "Apache-2.0" ]
1
2022-03-09T14:40:24.000Z
2022-03-09T14:40:24.000Z
gpt2_generate.py
LindgeW/PreLM
39a6b1c2fc0ccff7e8143f14d113cdfa79f63d79
[ "Apache-2.0" ]
null
null
null
gpt2_generate.py
LindgeW/PreLM
39a6b1c2fc0ccff7e8143f14d113cdfa79f63d79
[ "Apache-2.0" ]
null
null
null
import torch from transformers import GPT2Tokenizer, GPT2LMHeadModel from torch.utils.data import TensorDataset, DataLoader # reference: \transformers\generation_utils.py def select_greedy(logits): next_token_logits = logits[:, -1, :] # Greedy decoding next_token = torch.argmax(next_token_logits, dim=-1) return next_token def select_topk(logits, k=10): # next_token = random.choice(logits[0, -1, :].sort(descending=True)[1][:k]).item() next_token_logits = logits[:, -1, :] top_k = min(max(k, 1), next_token_logits.size(-1)) # Remove all tokens with a probability less than the last token of the top-k indices_to_remove = next_token_logits < torch.topk(next_token_logits, top_k)[0][..., -1, None] next_token_logits[indices_to_remove] = -float("Inf") probs = torch.nn.functional.softmax(next_token_logits, dim=-1) # multinominal方法可以根据给定权重对数组进行多次采样,返回采样后的元素下标 next_token = torch.multinomial(probs, num_samples=1).squeeze(1) return next_token def select_topp(logits, p=0.75): next_token_logits = logits[:, -1, :] # (batch_size, vocab_size) sorted_logits, sorted_indices = torch.sort(next_token_logits, descending=True) cum_probs = torch.cumsum(torch.nn.functional.softmax(sorted_logits, dim=-1), dim=-1) # Remove tokens with cumulative probability above the threshold (token with 0 are kept) sorted_indices_to_remove = cum_probs > p # Shift the indices to the right to keep also the first token above the threshold sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone() sorted_indices_to_remove[..., 0] = 0 # scatter sorted tensors to original indexing indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove) next_token_logits[indices_to_remove] = -float("Inf") probs = torch.nn.functional.softmax(next_token_logits, dim=-1) # multinominal方法可以根据给定权重对数组进行多次采样,返回采样后的元素下标 next_token = torch.multinomial(probs, num_samples=1).squeeze(1) return next_token def read_data(path='./romeo_and_juliet.txt'): with open(path, 'r', encoding='utf-8') as fin: ds = fin.read() return ds def data_processor(dataset, tokenizer, max_len=32): indexed_text = tokenizer.encode(dataset) ds_cut = [] for i in range(0, len(indexed_text)-max_len, max_len): # 将串切成长度为max_len ds_cut.append(indexed_text[i: i+max_len]) ds_tensor = torch.tensor(ds_cut) train_set = TensorDataset(ds_tensor, ds_tensor) # 数据和标签相同 return DataLoader(dataset=train_set, batch_size=8, shuffle=False) def train(train_loader, model, ep=30, device=torch.device('cpu')): optimizer = torch.optim.Adam(model.parameters(), lr=2e-5, eps=1e-8) print(next(model.parameters()).device) model.train() model.to(device) for i in range(ep): total_loss = 0. for bi, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() loss, logits, _ = model(data, labels=target) print('loss:', loss.data.item()) total_loss += loss loss.backward() optimizer.step() print('train loss:', total_loss / len(train_loader)) return model def inference(model, tokenizer, prefix=None, max_len=100, top_k=20, top_p=0.75, temperature=1.): print('inference ... ') print(next(model.parameters()).device) model.eval() indexed_tokens = tokenizer.encode(prefix) tokens_tensor = torch.tensor([indexed_tokens]) final_pred_text = prefix cur_len = tokens_tensor.size(-1) for _ in range(max_len): with torch.no_grad(): output = model(tokens_tensor) logits = output[0] # (batch_size, cur_len, vocab_size) if temperature != 1: logits /= temperature next_idx = select_topk(logits, k=top_k) # next_idx = select_topp(logits, p=0.75) final_pred_text += tokenizer.decode(next_idx) if tokenizer.eos_token in final_pred_text: break # indexed_tokens += [next_idx] # tokens_tensor = torch.tensor([indexed_tokens]) tokens_tensor = torch.cat([tokens_tensor, next_idx.unsqueeze(-1)], dim=-1) cur_len += 1 print(cur_len) return final_pred_text tokenizer = GPT2Tokenizer.from_pretrained('gpt2/en') model = GPT2LMHeadModel.from_pretrained('gpt2/en') # ds = read_data('./romeo_and_juliet.txt') # train_loader = data_processor(ds, tokenizer) # model = train(train_loader, model, ep=3, device=torch.device('cuda', 0)) pred_text = inference(model.to('cpu'), tokenizer, 'Yesterday, Jack said he saw an alien,', top_k=20, top_p=0.8, temperature=0.5) print(pred_text)
39.08871
101
0.676295
663
4,847
4.713424
0.268477
0.05472
0.0576
0.04032
0.26752
0.21184
0.12416
0.12416
0.12416
0.12416
0
0.019156
0.203012
4,847
123
102
39.406504
0.789801
0.17908
0
0.162791
0
0
0.030571
0.005558
0
0
0
0
0
1
0.081395
false
0
0.034884
0
0.197674
0.081395
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d6848f01064221cf2643bf09ab3bba76151a40d4
205
py
Python
main/PluginDemos/connectivityTest/Simulation/connectivityTest.py
JulianoGianlupi/nh-cc3d-4x-base-tool
c0f4aceebd4c5bf3ec39e831ef851e419b161259
[ "CC0-1.0" ]
null
null
null
main/PluginDemos/connectivityTest/Simulation/connectivityTest.py
JulianoGianlupi/nh-cc3d-4x-base-tool
c0f4aceebd4c5bf3ec39e831ef851e419b161259
[ "CC0-1.0" ]
null
null
null
main/PluginDemos/connectivityTest/Simulation/connectivityTest.py
JulianoGianlupi/nh-cc3d-4x-base-tool
c0f4aceebd4c5bf3ec39e831ef851e419b161259
[ "CC0-1.0" ]
1
2021-02-26T21:50:29.000Z
2021-02-26T21:50:29.000Z
from cc3d import CompuCellSetup from connectivityTestSteppables import connectivityTestSteppable CompuCellSetup.register_steppable(steppable=connectivityTestSteppable(frequency=1)) CompuCellSetup.run()
25.625
83
0.887805
17
205
10.647059
0.647059
0
0
0
0
0
0
0
0
0
0
0.010417
0.063415
205
7
84
29.285714
0.932292
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
0
1
0
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
5
d6859b005c6f17914c88f345695e794297b1e815
59
py
Python
models/genetic_algorithms/__init__.py
njellinas/ai-steroids
40e0013bdacb8bee1236305c1384f6b5ac8bd807
[ "MIT" ]
null
null
null
models/genetic_algorithms/__init__.py
njellinas/ai-steroids
40e0013bdacb8bee1236305c1384f6b5ac8bd807
[ "MIT" ]
null
null
null
models/genetic_algorithms/__init__.py
njellinas/ai-steroids
40e0013bdacb8bee1236305c1384f6b5ac8bd807
[ "MIT" ]
null
null
null
from models.genetic_algorithms.population import Population
59
59
0.915254
7
59
7.571429
0.857143
0
0
0
0
0
0
0
0
0
0
0
0.050847
59
1
59
59
0.946429
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
5
d6876109b60f86d0c814c99a79b62726595f011e
167
py
Python
webapp/campaigns/urls.py
AKarbas/datachef-interview-assignment
04a69a0daf0ab5378a2e03913ac60818e3fb73d9
[ "Intel" ]
null
null
null
webapp/campaigns/urls.py
AKarbas/datachef-interview-assignment
04a69a0daf0ab5378a2e03913ac60818e3fb73d9
[ "Intel" ]
null
null
null
webapp/campaigns/urls.py
AKarbas/datachef-interview-assignment
04a69a0daf0ab5378a2e03913ac60818e3fb73d9
[ "Intel" ]
null
null
null
from django.urls import path from . import views app_name = 'campaigns' urlpatterns = [ path('<int:campaign_id>/', views.Campaign.as_view(), name='campaign'), ]
18.555556
74
0.700599
22
167
5.181818
0.681818
0
0
0
0
0
0
0
0
0
0
0
0.143713
167
8
75
20.875
0.797203
0
0
0
0
0
0.209581
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
3
d687affcc64565d8faf1f33b4994b4b1b73c74f1
1,470
py
Python
src/test/test_imperfect_indicitive.py
shrutiichandra/spanish-conjugator
2ebf41b92c14c3e47a873c52fdf4ce1d17bff5e0
[ "MIT" ]
null
null
null
src/test/test_imperfect_indicitive.py
shrutiichandra/spanish-conjugator
2ebf41b92c14c3e47a873c52fdf4ce1d17bff5e0
[ "MIT" ]
null
null
null
src/test/test_imperfect_indicitive.py
shrutiichandra/spanish-conjugator
2ebf41b92c14c3e47a873c52fdf4ce1d17bff5e0
[ "MIT" ]
null
null
null
# -*- coding: iso-8859-15 -*- import spanishconjugator from spanishconjugator.SpanishConjugator import Conjugator # ----------------------------------- Imperfect Indicative ----------------------------------- # def test_imperfect_indicative_yo_ar(): expected = "hablaba" assert Conjugator().conjugate('hablar','imperfect','indicative','yo') == expected def test_imperfect_indicative_tu_ar(): expected = "hablabas" assert Conjugator().conjugate('hablar','imperfect','indicative','tu') == expected def test_imperfect_indicative_usted_ar(): expected = "hablaba" assert Conjugator().conjugate('hablar','imperfect','indicative','usted') == expected def test_imperfect_indicative_nosotros_ar(): expected = 'hablábamos' assert str(Conjugator().conjugate('hablar','imperfect','indicative','nosotros')) == expected def test_imperfect_indicative_vosotros_ar(): expected = "hablabais" assert Conjugator().conjugate('hablar','imperfect','indicative','vosotros') == expected def test_imperfect_indicative_ustedes_ar(): expected = "hablaban" assert Conjugator().conjugate('hablar','imperfect','indicative','ustedes') == expected def test_imperfect_indicative_yo_ar_3(): expected = "charlaba" assert Conjugator().conjugate('charlar','imperfect','indicative','yo') == expected def test_imperfect_indicative_yo_ar_4(): expected = "era" assert Conjugator().conjugate('ser','imperfect','indicative','yo') == expected
39.72973
96
0.702041
144
1,470
6.930556
0.243056
0.323647
0.128257
0.208417
0.626253
0.445892
0.267535
0.225451
0.134269
0
0
0.006112
0.109524
1,470
37
97
39.72973
0.756303
0.081633
0
0.076923
0
0
0.218425
0
0
0
0
0
0.307692
1
0.307692
false
0
0.076923
0
0.384615
0
0
0
0
null
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
0
0
0
3
d68824df1e94960138084688a7d3f88b19a19dff
8,044
py
Python
gradient_chaser.py
RobertOpitz/Gradient_Chaser
ca2011342d28798808769831655b74d9adfc6d26
[ "MIT" ]
null
null
null
gradient_chaser.py
RobertOpitz/Gradient_Chaser
ca2011342d28798808769831655b74d9adfc6d26
[ "MIT" ]
null
null
null
gradient_chaser.py
RobertOpitz/Gradient_Chaser
ca2011342d28798808769831655b74d9adfc6d26
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 13 17:37:31 2020 @author: robertopitz """ import numpy as np from random import randrange from math import isnan import pygame as pg def get_new_prey_pos(pos, board): while True: c = randrange(1,len(board)-1) r = randrange(1,len(board[0])-1) if c != pos[0] or r != pos[1]: if board[c][r] == 0: return np.array([c,r]) def get_next_move(pos, board): c = pos[0] r = pos[1] gradient = np.array([board[c+1][r], board[c-1][r], board[c][r-1], board[c][r+1]]) i = np.argmin(gradient) move = ["RIGHT", "LEFT", "UP", "DOWN"] return move[i] def move_bot(bot_pos, prey_pos, board, penalty_board): c = bot_pos[0] r = bot_pos[1] move = get_next_move(bot_pos, penalty_board) step_size = 1 if move == "UP": if board[c][r-1] == 0: bot_pos[1] -= step_size elif move == "DOWN": if board[c][r+1] == 0: bot_pos[1] += step_size elif move == "LEFT": if board[c-1][r] == 0: bot_pos[0] -= step_size elif move == "RIGHT": if board[c+1][r] == 0: bot_pos[0] += step_size def convert_board(board): new_board = np.zeros(board.shape) new_board = new_board.astype(float) new_board[board == 0.] = np.nan new_board[board == 1.] = float('inf') return new_board def convert_to_draw_board(board): new_board = np.zeros(board.shape) for c in range(np.size(board,0)): for r in range(np.size(board,1)): b = board[c][r] if b == "o" or b == "O" or b == " ": new_board[c,r] = 0 else: new_board[c,r] = 1 return new_board def create_gradient(board): # border is Inf # empty field is NaN step_penalty = 1 nans_present = True border = float('inf') while nans_present: nans_present = False for c in range(1,len(board)-1): for r in range(1,len(board[0])-1): if isnan(board[c][r]): nans_present = True if isnan(board[c+1][r]) and isnan(board[c][r+1]): pass elif isnan(board[c+1][r]) and not isnan(board[c][r+1]): if board[c][r+1] != border: board[c][r] = board[c][r+1] + step_penalty elif not isnan(board[c+1][r]) and isnan(board[c][r+1]): if board[c+1][r] != border: board[c][r] = board[c+1][r] + step_penalty else: if board[c+1][r] != border and \ board[c][r+1] != border: board[c][r] = int(0.5 * (board[c+1][r] + \ board[c][r+1]) + step_penalty) elif board[c+1][r] == border and \ board[c][r+1] != border: board[c][r] = board[c][r+1] + step_penalty elif board[c+1][r] != border and \ board[c][r+1] == border: board[c][r] = board[c+1][r] + step_penalty else: if board[c][r] != border: if isnan(board[c+1][r]): board[c+1][r] = board[c][r] + step_penalty if isnan(board[c][r+1]): board[c][r+1] = board[c][r] + step_penalty return board def nint(f): return int(round(f)) def get_penalty_board(board, prey_pos): new_board = np.copy(board) c = nint(prey_pos[0]) r = nint(prey_pos[1]) new_board[c, r] = 0.0 penalty_board = create_gradient(new_board) return penalty_board def draw_board(screen, board, rs): for c in range(np.size(board,0)): for r in range(np.size(board,1)): if board[c,r] == 1: pg.draw.rect(screen, pg.Color("blue"), pg.Rect(c * rs, r * rs, rs, rs)) def draw_bot(screen, pos, rs): pg.draw.rect(screen, pg.Color("red"), pg.Rect(pos[0] * rs, pos[1] * rs, rs, rs)) def draw_prey(screen, pos, rs): pg.draw.rect(screen, pg.Color("yellow"), pg.Rect(pos[0] * rs, pos[1] * rs, rs, rs)) def play_game(bot_pos_start, board_extern): board = convert_to_draw_board(board_extern) penalty_board_blue_print = convert_board(board) rect_size = 15 bot_pos = np.copy(bot_pos_start) pg.init() screen_color = pg.Color("black") screen = pg.display.set_mode((np.size(board,0) * rect_size, np.size(board,1) * rect_size)) clock = pg.time.Clock() pg.display.set_caption("Clean Bot AI") running = True prey_pos = get_new_prey_pos(bot_pos, board) penalty_board = get_penalty_board(penalty_board_blue_print, prey_pos) while running: move_bot(bot_pos, prey_pos, board, penalty_board) if bot_pos[0] == prey_pos[0] and bot_pos[1] == prey_pos[1]: prey_pos = get_new_prey_pos(bot_pos, board) penalty_board = get_penalty_board(penalty_board_blue_print, prey_pos) screen.fill(screen_color) for event in pg.event.get(): if event.type == pg.QUIT: running = False draw_board(screen, board, rect_size) draw_prey(screen, prey_pos, rect_size) draw_bot(screen, bot_pos, rect_size) clock.tick(60) pg.display.flip() pg.quit() #==MAIN CODE================================================================== board = [list("x--------x---|-|---x----xx----x"),#1 list("|ooOooooo|---| |---|oooO||oooo|"),#2 list("|ox-xo--o|---| |---|o--o--o--o|"),#3 list("|o|-|o||o|---| |---|o||oooo||o|"),#4 list("|o|-|o||o|---| |---|o|x--|o||o|"),#5 list("|ox-xo--ox---x x---xo----|o||o|"),#6 list("|oooooooooooooooooooooooooo||o|"),#7 list("|ox-xo|------| |---|o--o|--x|o|"),#8 list("|o|-|o|--xx--| |---|o||o|--x|o|"),#9 list("|o|-|oooo|| o||oooo||o|"),#10 list("|o|-|o--o|| x---x --o||o--o||o|"),#11 list("|ox-xo||o-- |x-x| ||o--o||o--o|"),#12 list("|ooooo||o ||-|| ||oooo||oooo|"),#13 list("x---|o|x--| |--|| |x--|o|x--|o|"),#14 list("x---|o|x--| |--|| |x--|o|x--|o|"),#15 list("|ooooo||o ||-|| ||oooo||oooo|"),#16 list("|ox-xo||o-- |x-x| ||o--o||o--o|"),#17 list("|o|-|o--o|| x---x --o||o--o||o|"),#18 list("|o|-|oooo|| o||oooo||o|"),#19 list("|o|-|o|--xx--| |---|o||o|--x|o|"),#20 list("|ox-xo|------| |---|o--o|--x|o|"),#21 list("|oooooooooooooooooooooooooo||o|"),#22 list("|ox-xo--ox---x x---xox---|o||o|"),#23 list("|o|-|o||o|---| |---|o|x--|o||o|"),#24 list("|o|-|o||o|---| |---|o||oooo||o|"),#25 list("|ox-xo--o|---| |---|o--o--o--o|"),#26 list("|ooOooooo|---| |---|oooO||oooo|"),#27 list("x--------x---|-|---x----xx----x")#28 ] # board = [[1,1,1,1,1,1,1,1,1], # [1,0,0,0,1,0,0,0,1], # [1,0,0,0,1,0,1,0,1], # [1,0,1,1,1,0,1,0,1], # [1,0,1,0,1,1,1,0,1], # [1,0,0,0,0,0,0,0,1], # [1,0,0,0,1,1,1,0,1], # [1,0,1,0,1,0,1,0,1], # [1,0,1,1,1,0,1,0,1], # [1,0,0,0,1,0,1,0,1], # [1,0,0,0,1,0,0,0,1], # [1,1,1,1,1,1,1,1,1]] board = np.array(board) bot_pos_start = np.array([1,1]) play_game(bot_pos_start, board)
34.084746
80
0.441074
1,182
8,044
2.890017
0.132826
0.087822
0.063525
0.042155
0.523126
0.46897
0.407787
0.390515
0.321721
0.277518
0
0.049211
0.345724
8,044
235
81
34.229787
0.599848
0.076827
0
0.305556
0
0.011111
0.127068
0.016816
0
0
0
0
0
1
0.066667
false
0.005556
0.022222
0.005556
0.127778
0.016667
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d6885aadfed2400899af0bca8750fa5677a2b1f3
1,092
py
Python
start.py
AlexeyProskuryakov/vknotifier
be58008dec0c967718fdbd70da615c1d4966d5b5
[ "MIT" ]
null
null
null
start.py
AlexeyProskuryakov/vknotifier
be58008dec0c967718fdbd70da615c1d4966d5b5
[ "MIT" ]
null
null
null
start.py
AlexeyProskuryakov/vknotifier
be58008dec0c967718fdbd70da615c1d4966d5b5
[ "MIT" ]
null
null
null
# coding:utf-8 import ConfigParser import sys __author__ = '4ikist' from core.engine import NotificatonIniter, TalkHandler, VKEventHandler def load_config(prop_file): cfg = ConfigParser.RawConfigParser() cfg.read(prop_file) api_name = dict(cfg.items('main'))['api_name'] api_credentials = {'api_name': api_name, 'login': dict(cfg.items(api_name))['login'], 'pwd': dict(cfg.items(api_name))['pwd']} print 'api:', api_credentials db_credentials = {'address': dict(cfg.items('storage'))['address'], 'db_name': dict(cfg.items('storage'))['db_name']} print 'db:', db_credentials return api_credentials, db_credentials def main(): api_credentials, db_credentials = load_config(sys.argv[1] if len(sys.argv) > 1 else 'properties.cfg') TalkHandler(api_credentials, db_credentials).start() NotificatonIniter(api_credentials, db_credentials).start() VKEventHandler(api_credentials, refresh_time=3600*3).start() if __name__ == '__main__': main()
34.125
106
0.655678
128
1,092
5.296875
0.359375
0.144543
0.088496
0.199115
0.150442
0
0
0
0
0
0
0.010417
0.208791
1,092
32
107
34.125
0.774306
0.010989
0
0
0
0
0.107824
0
0
0
0
0
0
0
null
null
0
0.130435
null
null
0.086957
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
2
d689694bd6143417bf16953605dd1dede7dec316
1,375
py
Python
prior_config.py
ZENGXH/NPDRAW
339d1d9b4880cce891cafe7c20198ef7c121a29e
[ "MIT" ]
21
2021-06-28T18:29:28.000Z
2022-03-13T09:12:07.000Z
prior_config.py
ZENGXH/NPDRAW
339d1d9b4880cce891cafe7c20198ef7c121a29e
[ "MIT" ]
null
null
null
prior_config.py
ZENGXH/NPDRAW
339d1d9b4880cce891cafe7c20198ef7c121a29e
[ "MIT" ]
2
2021-07-05T02:29:32.000Z
2021-11-02T08:25:14.000Z
from utils.yacs_config import CfgNode as CN __C = CN() cfg = __C # cfg.canvas_init=0 cfg.use_vit=0 cfg.use_fast_vit=0 cfg.img_mean=-1 cfg.vit_mlp_dim=2048 cfg.vit_depth=8 cfg.vit_dropout=1 cfg.concat_one_hot=0 cfg.mask_out_prevloc_samples=0 #cfg.input_id_canvas=0 cfg.register_deprecated_key('input_id_canvas') cfg.use_cnn_process=0 cfg.input_id_only=0 cfg.cond_on_loc=0 cfg.gt_file='' cfg.img_size=28 cfg.pw=10 cfg.register_renamed_key('ps', 'pw') cfg.register_deprecated_key('steps') cfg.register_deprecated_key('canvas_init') cfg.register_deprecated_key('lw') cfg.register_deprecated_key('anchor_dependent') cfg.hid=256 cfg.batch_size=128 cfg.num_epochs=50 cfg.lr=3e-4 ## cfg.lw=1.0 cfg.k=50 cfg.loc_loss_weight=1.0 cfg.cls_loss_weight=1.0 cfg.stp_loss_weight=1.0 cfg.output_folder='./exp/prior' cfg.single_sample=0 cfg.dataset='mnist' cfg.add_empty=0 cfg.add_stop=0 cfg.inputd=2 cfg.model_name='cnn_prior' cfg.hidden_size_prior=64 cfg.hidden_size_vae=256 cfg.use_scheduler=0 cfg.early_stopping=0 cfg.loc_map=1 cfg.nloc=-1 cfg.num_layers=8 #15 cfg.loc_dist='Gaussian' cfg.loc_stride=1 cfg.exp_key='' cfg.device='cuda' cfg.exp_dir='./exp/' # root of all experiments cfg.mhead=0 cfg.kernel_size=7 # for picnn's kernel cfg.permute_order=0 # for picnn's kernel cfg.geometric=0 #cfg.anchor_dependent=0 cfg.start_time='' cfg.pos_encode=0 cfg.use_emb_enc=0
22.177419
48
0.786909
276
1,375
3.637681
0.434783
0.087649
0.104582
0.119522
0.080677
0
0
0
0
0
0
0.050553
0.079273
1,375
61
49
22.540984
0.742496
0.100364
0
0
0
0
0.07824
0
0
0
0
0
0
1
0
false
0
0.017544
0
0.017544
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d689def2b69b86b6725aa76fbe9f83cda3ccc692
1,769
py
Python
2021/09/main2.py
chirsz-ever/aoc
dbdc2e32fbef108752db87f3747ce5898a0775ce
[ "BSL-1.0" ]
null
null
null
2021/09/main2.py
chirsz-ever/aoc
dbdc2e32fbef108752db87f3747ce5898a0775ce
[ "BSL-1.0" ]
null
null
null
2021/09/main2.py
chirsz-ever/aoc
dbdc2e32fbef108752db87f3747ce5898a0775ce
[ "BSL-1.0" ]
null
null
null
#!/usr/bin/env python3 import sys from itertools import repeat, product from operator import mul from functools import reduce inputFile = 'input' if len(sys.argv) >= 2: inputFile = sys.argv[1] heightmap : list[list[int]] = [] with open(inputFile) as fin: for line in fin: heightmap.append([int(c) for c in line.strip()]) width = len(heightmap[0]) height = len(heightmap) def isLowPoint(i, j): h = heightmap[i][j] if i != 0 and heightmap[i - 1][j] <= h: return False if i != height - 1 and heightmap[i + 1][j] <= h: return False if j != 0 and heightmap[i][j - 1] <= h: return False if j != width - 1 and heightmap[i][j + 1] <= h: return False return True lowpoints : list[tuple[int, int]] = [] for i, j in product(range(height), range(width)): if isLowPoint(i, j): lowpoints.append((i, j)) basinlog = [[0 for _ in range(width)] for _ in range(height)] for i, j in product(range(height), range(width)): if heightmap[i][j] == 9: basinlog[i][j] = -1 def findbasin(i, j, t) -> int: if basinlog[i][j] != 0: return 0 basinlog[i][j] = t size = 1 if i != 0 and heightmap[i - 1][j] != 9: size += findbasin(i - 1, j, t) if i != height - 1 and heightmap[i + 1][j] != 9: size += findbasin(i + 1, j, t) if j != 0 and heightmap[i][j - 1] != 9: size += findbasin(i, j - 1, t) if j != width - 1 and heightmap[i][j + 1] != 9: size += findbasin(i, j + 1, t) return size basinsizes : list[int, int] = [] basintoken = 1 for i, j in lowpoints: if (size := findbasin(i, j, basintoken)) != 0: basinsizes.append(size) basintoken += 1 print(f'{reduce(mul, sorted(basinsizes, reverse=True)[:3]) = }')
26.80303
64
0.569248
280
1,769
3.589286
0.217857
0.037811
0.103483
0.055721
0.366169
0.366169
0.366169
0.366169
0.315423
0.208955
0
0.029253
0.265687
1,769
66
64
26.80303
0.744419
0.011871
0
0.113208
0
0
0.033753
0
0
0
0
0
0
1
0.037736
false
0
0.075472
0
0.245283
0.018868
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0
d689f1e24c703d9de5c7460fe0778d147ec02403
974
py
Python
tpDcc/libs/qt/core/traymessage.py
tpDcc/tpQtLib
26b6e893395633a1b189a1b73654891b7688648d
[ "MIT" ]
3
2019-08-26T05:56:12.000Z
2019-10-03T11:35:53.000Z
tpDcc/libs/qt/core/traymessage.py
tpDcc/tpQtLib
26b6e893395633a1b189a1b73654891b7688648d
[ "MIT" ]
null
null
null
tpDcc/libs/qt/core/traymessage.py
tpDcc/tpQtLib
26b6e893395633a1b189a1b73654891b7688648d
[ "MIT" ]
1
2021-03-03T21:01:50.000Z
2021-03-03T21:01:50.000Z
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains custom tray balloon """ from __future__ import print_function, division, absolute_import from Qt.QtWidgets import QWidget, QSystemTrayIcon, QMenu class TrayMessage(QWidget, object): def __init__(self, parent=None): super(TrayMessage, self).__init__(parent=parent) self._tools_icon = None self.tray_icon_menu = QMenu(self) self.tray_icon = QSystemTrayIcon(self) # self.tray_icon.setIcon(self._tools_icon) self.tray_icon.setToolTip('Tray') self.tray_icon.setContextMenu(self.tray_icon_menu) if not QSystemTrayIcon.isSystemTrayAvailable(): raise OSError('Tray Icon is not available!') self.tray_icon.show() def show_message(self, title, msg): try: self.tray_icon.showMessage(title, msg, self._tools_icon) except Exception: self.tray_icon.showMessage(title, msg)
27.055556
68
0.677618
117
974
5.367521
0.470085
0.127389
0.171975
0.050955
0.098726
0.098726
0
0
0
0
0
0.001316
0.219713
974
35
69
27.828571
0.825
0.128337
0
0
0
0
0.036949
0
0
0
0
0
0
1
0.111111
false
0
0.111111
0
0.277778
0.055556
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
1
0