body_hash
stringlengths
64
64
body
stringlengths
23
109k
docstring
stringlengths
1
57k
path
stringlengths
4
198
name
stringlengths
1
115
repository_name
stringlengths
7
111
repository_stars
float64
0
191k
lang
stringclasses
1 value
body_without_docstring
stringlengths
14
108k
unified
stringlengths
45
133k
31f0e85355a8ae2414aca06967f18f4e7aa86d201dae8955669b92e1dbec36eb
def test_get_person_from_tax_id_fails_multiple(self): 'Test get_person_from_tax_id returns void result\n ' tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_person_multiple(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaMultipleObjectsReturned): atoka_conn.get_person_from_tax_id(tax_id)
Test get_person_from_tax_id returns void result
tests/test_atokaconn.py
test_get_person_from_tax_id_fails_multiple
openpolis/atokaconn
1
python
def test_get_person_from_tax_id_fails_multiple(self): '\n ' tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_person_multiple(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaMultipleObjectsReturned): atoka_conn.get_person_from_tax_id(tax_id)
def test_get_person_from_tax_id_fails_multiple(self): '\n ' tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_person_multiple(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaMultipleObjectsReturned): atoka_conn.get_person_from_tax_id(tax_id)<|docstring|>Test get_person_from_tax_id returns void result<|endoftext|>
a48f917012e1bed83d4da1a83eded96126784f50f035391cb49bacf011496dae
def test_search_person_fails_doesnotexist(self): 'Test search_person returns a not found result\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaObjectDoesNotExist): atoka_conn.search_person(person)
Test search_person returns a not found result
tests/test_atokaconn.py
test_search_person_fails_doesnotexist
openpolis/atokaconn
1
python
def test_search_person_fails_doesnotexist(self): '\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaObjectDoesNotExist): atoka_conn.search_person(person)
def test_search_person_fails_doesnotexist(self): '\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaObjectDoesNotExist): atoka_conn.search_person(person)<|docstring|>Test search_person returns a not found result<|endoftext|>
d80726d0d79bce88f90de3414756e3b9adc1c1db6d74a045d3d7c28b9ed849b4
def test_search_person_fails_notok(self): 'Test search_person returns not ok\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaResponseError): atoka_conn.search_person(person)
Test search_person returns not ok
tests/test_atokaconn.py
test_search_person_fails_notok
openpolis/atokaconn
1
python
def test_search_person_fails_notok(self): '\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaResponseError): atoka_conn.search_person(person)
def test_search_person_fails_notok(self): '\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaResponseError): atoka_conn.search_person(person)<|docstring|>Test search_person returns not ok<|endoftext|>
c4c6b78e94cfe5271ef56fb0548d81559593733387c576c4614c059ec2eb3d39
def test_search_person_fails_multiple(self): 'Test search_person returns multiple results\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_person_multiple(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaMultipleObjectsReturned): atoka_conn.search_person(person)
Test search_person returns multiple results
tests/test_atokaconn.py
test_search_person_fails_multiple
openpolis/atokaconn
1
python
def test_search_person_fails_multiple(self): '\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_person_multiple(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaMultipleObjectsReturned): atoka_conn.search_person(person)
def test_search_person_fails_multiple(self): '\n ' parent_area = AreaFactory(name='Lazio') area = AreaFactory(name='Roma', parent=parent_area) person = PersonFactory.create(family_name=faker.last_name_male(), given_name=faker.first_name_male(), birth_date=faker.date(pattern='%Y-%m-%d', end_datetime='-47y'), birth_location_area=area) person.tax_id = faker.ssn() self.mock_get.return_value = MockResponse(get_person_multiple(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaMultipleObjectsReturned): atoka_conn.search_person(person)<|docstring|>Test search_person returns multiple results<|endoftext|>
389ffabc70649200cd7444203ea6636db670be3d43117ee5ffa2947b1f496529
def test_get_companies_from_tax_id_ok(self): 'Test getcompany_from_tax_id returns one result\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', logger=logger) atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1) self.assertEqual(atoka_p[0]['base']['taxId'], tax_id) self.assertEqual(('shares' in atoka_p[0]), True)
Test getcompany_from_tax_id returns one result
tests/test_atokaconn.py
test_get_companies_from_tax_id_ok
openpolis/atokaconn
1
python
def test_get_companies_from_tax_id_ok(self): '\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', logger=logger) atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1) self.assertEqual(atoka_p[0]['base']['taxId'], tax_id) self.assertEqual(('shares' in atoka_p[0]), True)
def test_get_companies_from_tax_id_ok(self): '\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', logger=logger) atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1) self.assertEqual(atoka_p[0]['base']['taxId'], tax_id) self.assertEqual(('shares' in atoka_p[0]), True)<|docstring|>Test getcompany_from_tax_id returns one result<|endoftext|>
2781ece49f02495f6fc568935009230429c70ddb3060fa3b4fc5f9297346208f
def test_get_companies_from_tax_id_ok_extend_response(self): 'Test get_companies_from_tax_id returns more than 50 results\n ' tax_id = '01234567890' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', logger=logger) atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertGreaterEqual(len(atoka_p), 50)
Test get_companies_from_tax_id returns more than 50 results
tests/test_atokaconn.py
test_get_companies_from_tax_id_ok_extend_response
openpolis/atokaconn
1
python
def test_get_companies_from_tax_id_ok_extend_response(self): '\n ' tax_id = '01234567890' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', logger=logger) atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertGreaterEqual(len(atoka_p), 50)
def test_get_companies_from_tax_id_ok_extend_response(self): '\n ' tax_id = '01234567890' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', logger=logger) atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertGreaterEqual(len(atoka_p), 50)<|docstring|>Test get_companies_from_tax_id returns more than 50 results<|endoftext|>
016aecacadbeaa1d1cff7460770d07e8d81732a80f168e832a823ea83ce912ee
def test_get_companies_from_tax_id_multiple_results(self): 'Test getcompany_from_tax_id returns more than one result\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 2) self.assertEqual(atoka_p[0]['base']['taxId'], tax_id) self.assertEqual(atoka_p[1]['base']['taxId'], tax_id) self.assertEqual(('shares' in atoka_p[0]), True) self.assertEqual(('shares' in atoka_p[1]), False)
Test getcompany_from_tax_id returns more than one result
tests/test_atokaconn.py
test_get_companies_from_tax_id_multiple_results
openpolis/atokaconn
1
python
def test_get_companies_from_tax_id_multiple_results(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 2) self.assertEqual(atoka_p[0]['base']['taxId'], tax_id) self.assertEqual(atoka_p[1]['base']['taxId'], tax_id) self.assertEqual(('shares' in atoka_p[0]), True) self.assertEqual(('shares' in atoka_p[1]), False)
def test_get_companies_from_tax_id_multiple_results(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_companies_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 2) self.assertEqual(atoka_p[0]['base']['taxId'], tax_id) self.assertEqual(atoka_p[1]['base']['taxId'], tax_id) self.assertEqual(('shares' in atoka_p[0]), True) self.assertEqual(('shares' in atoka_p[1]), False)<|docstring|>Test getcompany_from_tax_id returns more than one result<|endoftext|>
f581769d7aedad7e7ec2fad6b4d3c27124c1a9ffec2d4f8d45c60b504e939d2a
def test_get_companies_from_tax_id_returns_empty_if_missing(self): 'Test get_person_from_tax_id returns void result\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])
Test get_person_from_tax_id returns void result
tests/test_atokaconn.py
test_get_companies_from_tax_id_returns_empty_if_missing
openpolis/atokaconn
1
python
def test_get_companies_from_tax_id_returns_empty_if_missing(self): '\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])
def test_get_companies_from_tax_id_returns_empty_if_missing(self): '\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])<|docstring|>Test get_person_from_tax_id returns void result<|endoftext|>
8e18971f29a0706a9d4b4ab9e5a8bd5f0388a0b2f934e9a118c655fbdf57bb72
def test_get_companies_from_tax_id_empty_if_post_response_notok(self): 'Test get_companies_from_tax_id returns empty list when response is not ok\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])
Test get_companies_from_tax_id returns empty list when response is not ok
tests/test_atokaconn.py
test_get_companies_from_tax_id_empty_if_post_response_notok
openpolis/atokaconn
1
python
def test_get_companies_from_tax_id_empty_if_post_response_notok(self): '\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])
def test_get_companies_from_tax_id_empty_if_post_response_notok(self): '\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])<|docstring|>Test get_companies_from_tax_id returns empty list when response is not ok<|endoftext|>
f759263f10208c57f5affbc97eb6556cdad9d8af189eabd894983a1f1e94df13
def test_get_companies_from_tax_id_empty_if_post_request_timeouts(self): 'Test get_companies_from_tax_id returns empty list when post reuest timeouts\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') self.mock_post.side_effect = Timeout() atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, []) self.mock_post.side_effect = None
Test get_companies_from_tax_id returns empty list when post reuest timeouts
tests/test_atokaconn.py
test_get_companies_from_tax_id_empty_if_post_request_timeouts
openpolis/atokaconn
1
python
def test_get_companies_from_tax_id_empty_if_post_request_timeouts(self): '\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') self.mock_post.side_effect = Timeout() atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, []) self.mock_post.side_effect = None
def test_get_companies_from_tax_id_empty_if_post_request_timeouts(self): '\n ' tax_id = faker.ssn() self.mock_post.return_value = MockResponse(get_void_response(), status_code=404, ok=False, reason='Requested URI was not found here') self.mock_post.side_effect = Timeout() atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, []) self.mock_post.side_effect = None<|docstring|>Test get_companies_from_tax_id returns empty list when post reuest timeouts<|endoftext|>
f02014f1a359a68ff390c677d88ab34ff3a915fc9a56eb3fcc4071a3384d9c8f
def test_get_companies_from_tax_id_empty_if_post_request_response_void(self): 'Test get_companies_from_tax_id returns empty list when post reuest returns a void response\n ' tax_id = faker.ssn() self.mock_post.return_value = None atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])
Test get_companies_from_tax_id returns empty list when post reuest returns a void response
tests/test_atokaconn.py
test_get_companies_from_tax_id_empty_if_post_request_response_void
openpolis/atokaconn
1
python
def test_get_companies_from_tax_id_empty_if_post_request_response_void(self): '\n ' tax_id = faker.ssn() self.mock_post.return_value = None atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])
def test_get_companies_from_tax_id_empty_if_post_request_response_void(self): '\n ' tax_id = faker.ssn() self.mock_post.return_value = None atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_companies_from_tax_ids(tax_id, packages='base,shares', active='true') self.assertEqual(items, [])<|docstring|>Test get_companies_from_tax_id returns empty list when post reuest returns a void response<|endoftext|>
4795d9d7eb27fe379545bc1277144913d61a54eece973f025a2f315e37fed166
def test_get_items_from_ids_fails_wrong_ids_field_name(self): 'Test get_items_from_ids fails when an unknown ids_field_name is passed\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='companies', ids_field_name='cfs', batch_size=50, packages='base,shares', active='true')
Test get_items_from_ids fails when an unknown ids_field_name is passed
tests/test_atokaconn.py
test_get_items_from_ids_fails_wrong_ids_field_name
openpolis/atokaconn
1
python
def test_get_items_from_ids_fails_wrong_ids_field_name(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='companies', ids_field_name='cfs', batch_size=50, packages='base,shares', active='true')
def test_get_items_from_ids_fails_wrong_ids_field_name(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='companies', ids_field_name='cfs', batch_size=50, packages='base,shares', active='true')<|docstring|>Test get_items_from_ids fails when an unknown ids_field_name is passed<|endoftext|>
31e68afa28c12327ac3b8da2ba01aca792ea32e891d60fc7df418855fd5a0ff8
def test_get_items_from_ids_fails_wrong_item_type(self): 'Test get_items_from_ids fails when an unknown iem_type is passed\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='smurfs', ids_field_name='taxIds', batch_size=50, packages='base,shares', active='true')
Test get_items_from_ids fails when an unknown iem_type is passed
tests/test_atokaconn.py
test_get_items_from_ids_fails_wrong_item_type
openpolis/atokaconn
1
python
def test_get_items_from_ids_fails_wrong_item_type(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='smurfs', ids_field_name='taxIds', batch_size=50, packages='base,shares', active='true')
def test_get_items_from_ids_fails_wrong_item_type(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='smurfs', ids_field_name='taxIds', batch_size=50, packages='base,shares', active='true')<|docstring|>Test get_items_from_ids fails when an unknown iem_type is passed<|endoftext|>
f47789fbf1d8ffd0cdc25990a86db4164ee702a9ee9e056f279b66604ec56fdb
def test_get_items_from_ids_fails_wrong_batch_size(self): 'Test get_items_from_ids fails when an batch_size out of range is passed\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='companies', ids_field_name='taxIds', batch_size=100, packages='base,shares', active='true')
Test get_items_from_ids fails when an batch_size out of range is passed
tests/test_atokaconn.py
test_get_items_from_ids_fails_wrong_batch_size
openpolis/atokaconn
1
python
def test_get_items_from_ids_fails_wrong_batch_size(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='companies', ids_field_name='taxIds', batch_size=100, packages='base,shares', active='true')
def test_get_items_from_ids_fails_wrong_batch_size(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') with self.assertRaises(AtokaException): _ = atoka_conn.get_items_from_ids(tax_id.split(','), item_type='companies', ids_field_name='taxIds', batch_size=100, packages='base,shares', active='true')<|docstring|>Test get_items_from_ids fails when an batch_size out of range is passed<|endoftext|>
f7fb93664bcbcead8b98df6ae62f1b06cfbb0350c1c4c24c59718297eb8cb1f3
def test_get_items_from_ids_returns_empty_list_if_empty_ids(self): 'Test get_items_from_ids returns and empy items list when an empty ids list is passed\n ' self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') ids = atoka_conn.get_items_from_ids([], item_type='companies', ids_field_name='taxIds', batch_size=50, packages='base,shares', active='true') self.assertEqual(len(ids), 0)
Test get_items_from_ids returns and empy items list when an empty ids list is passed
tests/test_atokaconn.py
test_get_items_from_ids_returns_empty_list_if_empty_ids
openpolis/atokaconn
1
python
def test_get_items_from_ids_returns_empty_list_if_empty_ids(self): '\n ' self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') ids = atoka_conn.get_items_from_ids([], item_type='companies', ids_field_name='taxIds', batch_size=50, packages='base,shares', active='true') self.assertEqual(len(ids), 0)
def test_get_items_from_ids_returns_empty_list_if_empty_ids(self): '\n ' self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') ids = atoka_conn.get_items_from_ids([], item_type='companies', ids_field_name='taxIds', batch_size=50, packages='base,shares', active='true') self.assertEqual(len(ids), 0)<|docstring|>Test get_items_from_ids returns and empy items list when an empty ids list is passed<|endoftext|>
97fb0a90e11aa999a90d73a8ca7d7dcafdc5d123c678d2e4b31010786640da09
def test_get_items_from_ids_ok_with_chunks_and_logger(self): 'Test get_items_from_ids is ok when requests are grouped in chunks (batch_size=1)\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', max_batch_file_lines=1, logger=logger) items = atoka_conn.get_items_from_ids(['02438750586', '01234567890'], item_type='companies', ids_field_name='taxIds', batch_size=1, packages='base,shares', active='true') self.assertEqual(len(items), 2) self.assertEqual(items[0]['base']['taxId'], tax_id)
Test get_items_from_ids is ok when requests are grouped in chunks (batch_size=1)
tests/test_atokaconn.py
test_get_items_from_ids_ok_with_chunks_and_logger
openpolis/atokaconn
1
python
def test_get_items_from_ids_ok_with_chunks_and_logger(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', max_batch_file_lines=1, logger=logger) items = atoka_conn.get_items_from_ids(['02438750586', '01234567890'], item_type='companies', ids_field_name='taxIds', batch_size=1, packages='base,shares', active='true') self.assertEqual(len(items), 2) self.assertEqual(items[0]['base']['taxId'], tax_id)
def test_get_items_from_ids_ok_with_chunks_and_logger(self): '\n ' tax_id = '02438750586' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing', max_batch_file_lines=1, logger=logger) items = atoka_conn.get_items_from_ids(['02438750586', '01234567890'], item_type='companies', ids_field_name='taxIds', batch_size=1, packages='base,shares', active='true') self.assertEqual(len(items), 2) self.assertEqual(items[0]['base']['taxId'], tax_id)<|docstring|>Test get_items_from_ids is ok when requests are grouped in chunks (batch_size=1)<|endoftext|>
0eb253bc6ee7a5d503cc2f1bc53b9d32e2bf96d28403fdc7afee2d8c28cfbfc1
def test_get_companies_economics_ok(self): 'Test get_companies_from_tax_ids with economics details has the correct information\n ' tax_ids = ['02241890223', '09988761004'] self.mock_post.return_value = MockResponse(get_companies_economics(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_resp = atoka_conn.get_companies_from_tax_ids(tax_ids, packages='base,economics', active='true') self.assertEqual(len(atoka_resp), 2) c = atoka_resp[0] self.assertEqual(c['base']['taxId'], tax_ids[0]) self.assertEqual(('economics' in c), True) ce = c['economics'] self.assertEqual(('balanceSheets' in ce), True) self.assertEqual((len(ce['balanceSheets']) > 1), True) self.assertEqual(('employees' in ce), True) self.assertEqual((len(ce['employees']) > 1), True)
Test get_companies_from_tax_ids with economics details has the correct information
tests/test_atokaconn.py
test_get_companies_economics_ok
openpolis/atokaconn
1
python
def test_get_companies_economics_ok(self): '\n ' tax_ids = ['02241890223', '09988761004'] self.mock_post.return_value = MockResponse(get_companies_economics(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_resp = atoka_conn.get_companies_from_tax_ids(tax_ids, packages='base,economics', active='true') self.assertEqual(len(atoka_resp), 2) c = atoka_resp[0] self.assertEqual(c['base']['taxId'], tax_ids[0]) self.assertEqual(('economics' in c), True) ce = c['economics'] self.assertEqual(('balanceSheets' in ce), True) self.assertEqual((len(ce['balanceSheets']) > 1), True) self.assertEqual(('employees' in ce), True) self.assertEqual((len(ce['employees']) > 1), True)
def test_get_companies_economics_ok(self): '\n ' tax_ids = ['02241890223', '09988761004'] self.mock_post.return_value = MockResponse(get_companies_economics(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_resp = atoka_conn.get_companies_from_tax_ids(tax_ids, packages='base,economics', active='true') self.assertEqual(len(atoka_resp), 2) c = atoka_resp[0] self.assertEqual(c['base']['taxId'], tax_ids[0]) self.assertEqual(('economics' in c), True) ce = c['economics'] self.assertEqual(('balanceSheets' in ce), True) self.assertEqual((len(ce['balanceSheets']) > 1), True) self.assertEqual(('employees' in ce), True) self.assertEqual((len(ce['employees']) > 1), True)<|docstring|>Test get_companies_from_tax_ids with economics details has the correct information<|endoftext|>
945f53896ce8c2857850eec8a845cf0af6de406353bf2e5a0091519dba7136b1
def test_get_companies_from_atoka_ids_ok(self): 'Test test get_companies_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_companies_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)
Test test get_companies_from_atoka_ids returns one result The test only needs to test the correct wrapping of get_items_from_ids, so it mocks the usual response, not a correct one
tests/test_atokaconn.py
test_get_companies_from_atoka_ids_ok
openpolis/atokaconn
1
python
def test_get_companies_from_atoka_ids_ok(self): 'Test test get_companies_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_companies_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)
def test_get_companies_from_atoka_ids_ok(self): 'Test test get_companies_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_companies_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)<|docstring|>Test test get_companies_from_atoka_ids returns one result The test only needs to test the correct wrapping of get_items_from_ids, so it mocks the usual response, not a correct one<|endoftext|>
1e1cabf802418716af848e0180c2b8b7c69d5a23e33482502c1d996c3908fced
def test_get_people_from_tax_ids_ok(self): 'Test test get_people_from_tax_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_people_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)
Test test get_people_from_tax_ids returns one result The test only needs to test the correct wrapping of get_items_from_ids, so it mocks the usual response, not a correct one
tests/test_atokaconn.py
test_get_people_from_tax_ids_ok
openpolis/atokaconn
1
python
def test_get_people_from_tax_ids_ok(self): 'Test test get_people_from_tax_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_people_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)
def test_get_people_from_tax_ids_ok(self): 'Test test get_people_from_tax_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_people_from_tax_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)<|docstring|>Test test get_people_from_tax_ids returns one result The test only needs to test the correct wrapping of get_items_from_ids, so it mocks the usual response, not a correct one<|endoftext|>
db0c39d2bb0dc0a3be81b0abc0f702ea17e4fa39782f22bdb6a2f56492e72a92
def test_get_people_from_atoka_ids_ok(self): 'Test test get_people_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_people_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)
Test test get_people_from_atoka_ids returns one result The test only needs to test the correct wrapping of get_items_from_ids, so it mocks the usual response, not a correct one
tests/test_atokaconn.py
test_get_people_from_atoka_ids_ok
openpolis/atokaconn
1
python
def test_get_people_from_atoka_ids_ok(self): 'Test test get_people_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_people_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)
def test_get_people_from_atoka_ids_ok(self): 'Test test get_people_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_people_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)<|docstring|>Test test get_people_from_atoka_ids returns one result The test only needs to test the correct wrapping of get_items_from_ids, so it mocks the usual response, not a correct one<|endoftext|>
60b32011b7b344f1eab5c073516f71b382ee6c2b1984852a9d1b39ff397c4d0c
def test_get_roles_from_atoka_ids_ok(self): 'Test test get_roles_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_roles_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)
Test test get_roles_from_atoka_ids returns one result The test only needs to test the correct wrapping of get_items_from_ids, so it mocks the usual response, not a correct one
tests/test_atokaconn.py
test_get_roles_from_atoka_ids_ok
openpolis/atokaconn
1
python
def test_get_roles_from_atoka_ids_ok(self): 'Test test get_roles_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_roles_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)
def test_get_roles_from_atoka_ids_ok(self): 'Test test get_roles_from_atoka_ids returns one result\n\n The test only needs to test the correct wrapping of get_items_from_ids,\n so it mocks the usual response, not a correct one\n ' tax_id = '80002270660' self.mock_post.return_value = MockResponse(get_companies(tax_id), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') atoka_p = atoka_conn.get_roles_from_atoka_ids(tax_id.split(','), packages='base,shares', active='true') self.assertEqual(len(atoka_p), 1)<|docstring|>Test test get_roles_from_atoka_ids returns one result The test only needs to test the correct wrapping of get_items_from_ids, so it mocks the usual response, not a correct one<|endoftext|>
c3fb9cce5fc3cf4ff9f2c812fced8141b6f7570ecaa2a2de735261749aa6ec2b
def test_get_roles_from_atoka_ids_handles_doesnotexist(self): 'Test get_roles_from_atoka_ids handles the AtokaObjectDoesNotExist exception and returns empty list\n ' self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_roles_from_atoka_ids([faker.ssn(), faker.ssn()]) self.assertEqual(len(items), 0)
Test get_roles_from_atoka_ids handles the AtokaObjectDoesNotExist exception and returns empty list
tests/test_atokaconn.py
test_get_roles_from_atoka_ids_handles_doesnotexist
openpolis/atokaconn
1
python
def test_get_roles_from_atoka_ids_handles_doesnotexist(self): '\n ' self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_roles_from_atoka_ids([faker.ssn(), faker.ssn()]) self.assertEqual(len(items), 0)
def test_get_roles_from_atoka_ids_handles_doesnotexist(self): '\n ' self.mock_post.return_value = MockResponse(get_void_response(), status_code=200, ok=True) atoka_conn = AtokaConn(key='testing') items = atoka_conn.get_roles_from_atoka_ids([faker.ssn(), faker.ssn()]) self.assertEqual(len(items), 0)<|docstring|>Test get_roles_from_atoka_ids handles the AtokaObjectDoesNotExist exception and returns empty list<|endoftext|>
4b743b561ea26eb957a4efd7e27ac6a88675bde92229ff2dc3e0af3b3711aea7
def __init__(self, verbose=False): '\n ta\n ' self.verbose = False self.errors = {(- 1): RuntimeError('ERR_UNKNOWN'), (- 2): RuntimeError('ERR_FAIL'), (- 3): RuntimeError('ERR_NOT_INITIALIZED'), (- 4): RuntimeError('ERR_NOT_APPLICABLE'), (- 5): RuntimeError('ERR_PARAMETER_NOT_FOUND'), (- 6): RuntimeError('ERR_INDEX'), (- 7): RuntimeError('ERR_INCORRECT_ELEMENT_SET'), (- 8): RuntimeError('ERR_INCORRECT_LENS_MODE'), (- 9): RuntimeError('ERR_INCORRECT_PASS_ENERGY'), (- 10): RuntimeError('ERR_INCORRECT_ANALYZER_REGION'), (- 11): RuntimeError('ERR_INCORRECT_DETECTOR_REGION'), (- 12): RuntimeError('ERR_READONLY'), (- 13): RuntimeError('ERR_NO_INSTRUMENT'), (- 14): RuntimeError('ERR_ACQUIRING'), (- 15): RuntimeError('ERR_INITIALIZE_FAIL'), (- 16): RuntimeError('ERR_LOAD_LIBRARY'), (- 17): RuntimeError('ERR_OPEN_INSTRUMENT'), (- 18): RuntimeError('ERR_QT_RUNNING'), (- 19): RuntimeError('ERR_INVALID_DIR'), 8: RuntimeError('ERR_TIMEOUT'), 9: RuntimeError('ERR_NOT_IMPLEMENTED')} self.warnings = {313: 'Failed to zero supplies'}
ta
ses_error.py
__init__
bzwartsenberg/SESWrapper
6
python
def __init__(self, verbose=False): '\n \n ' self.verbose = False self.errors = {(- 1): RuntimeError('ERR_UNKNOWN'), (- 2): RuntimeError('ERR_FAIL'), (- 3): RuntimeError('ERR_NOT_INITIALIZED'), (- 4): RuntimeError('ERR_NOT_APPLICABLE'), (- 5): RuntimeError('ERR_PARAMETER_NOT_FOUND'), (- 6): RuntimeError('ERR_INDEX'), (- 7): RuntimeError('ERR_INCORRECT_ELEMENT_SET'), (- 8): RuntimeError('ERR_INCORRECT_LENS_MODE'), (- 9): RuntimeError('ERR_INCORRECT_PASS_ENERGY'), (- 10): RuntimeError('ERR_INCORRECT_ANALYZER_REGION'), (- 11): RuntimeError('ERR_INCORRECT_DETECTOR_REGION'), (- 12): RuntimeError('ERR_READONLY'), (- 13): RuntimeError('ERR_NO_INSTRUMENT'), (- 14): RuntimeError('ERR_ACQUIRING'), (- 15): RuntimeError('ERR_INITIALIZE_FAIL'), (- 16): RuntimeError('ERR_LOAD_LIBRARY'), (- 17): RuntimeError('ERR_OPEN_INSTRUMENT'), (- 18): RuntimeError('ERR_QT_RUNNING'), (- 19): RuntimeError('ERR_INVALID_DIR'), 8: RuntimeError('ERR_TIMEOUT'), 9: RuntimeError('ERR_NOT_IMPLEMENTED')} self.warnings = {313: 'Failed to zero supplies'}
def __init__(self, verbose=False): '\n \n ' self.verbose = False self.errors = {(- 1): RuntimeError('ERR_UNKNOWN'), (- 2): RuntimeError('ERR_FAIL'), (- 3): RuntimeError('ERR_NOT_INITIALIZED'), (- 4): RuntimeError('ERR_NOT_APPLICABLE'), (- 5): RuntimeError('ERR_PARAMETER_NOT_FOUND'), (- 6): RuntimeError('ERR_INDEX'), (- 7): RuntimeError('ERR_INCORRECT_ELEMENT_SET'), (- 8): RuntimeError('ERR_INCORRECT_LENS_MODE'), (- 9): RuntimeError('ERR_INCORRECT_PASS_ENERGY'), (- 10): RuntimeError('ERR_INCORRECT_ANALYZER_REGION'), (- 11): RuntimeError('ERR_INCORRECT_DETECTOR_REGION'), (- 12): RuntimeError('ERR_READONLY'), (- 13): RuntimeError('ERR_NO_INSTRUMENT'), (- 14): RuntimeError('ERR_ACQUIRING'), (- 15): RuntimeError('ERR_INITIALIZE_FAIL'), (- 16): RuntimeError('ERR_LOAD_LIBRARY'), (- 17): RuntimeError('ERR_OPEN_INSTRUMENT'), (- 18): RuntimeError('ERR_QT_RUNNING'), (- 19): RuntimeError('ERR_INVALID_DIR'), 8: RuntimeError('ERR_TIMEOUT'), 9: RuntimeError('ERR_NOT_IMPLEMENTED')} self.warnings = {313: 'Failed to zero supplies'}<|docstring|>ta<|endoftext|>
d65185fb319b8bbf2157de3c3d3a090b1dbc0dfe1c504fdc1f28bf801b7d897a
def write_file(trigram_probs_dict, model_name=None): '\n # Writes nicely formatted contents\n # of trigram_probs_dict to a file,\n # called trigram_model.txt. If the file\n # already exists, each new model is\n # appended to the end of the file.\n ' if (not model_name): model_name = 'UNTITLED MODEL' else: model_name = model_name.upper() with open('trigram_model.txt', 'a') as f: f.write(' \t\t**** {0} ****\n\n'.format(model_name)) entries = 0 for (key, value) in sorted(trigram_probs_dict.items()): f.write(' {0} : {1}, '.format(key, value)) if (entries == 5): f.write('\n') entries = 0 else: entries += 1 f.write('\n\n\n') return
# Writes nicely formatted contents # of trigram_probs_dict to a file, # called trigram_model.txt. If the file # already exists, each new model is # appended to the end of the file.
txtsh/ngrammer/write_file.py
write_file
jvasilakes/txtsh
1
python
def write_file(trigram_probs_dict, model_name=None): '\n # Writes nicely formatted contents\n # of trigram_probs_dict to a file,\n # called trigram_model.txt. If the file\n # already exists, each new model is\n # appended to the end of the file.\n ' if (not model_name): model_name = 'UNTITLED MODEL' else: model_name = model_name.upper() with open('trigram_model.txt', 'a') as f: f.write(' \t\t**** {0} ****\n\n'.format(model_name)) entries = 0 for (key, value) in sorted(trigram_probs_dict.items()): f.write(' {0} : {1}, '.format(key, value)) if (entries == 5): f.write('\n') entries = 0 else: entries += 1 f.write('\n\n\n') return
def write_file(trigram_probs_dict, model_name=None): '\n # Writes nicely formatted contents\n # of trigram_probs_dict to a file,\n # called trigram_model.txt. If the file\n # already exists, each new model is\n # appended to the end of the file.\n ' if (not model_name): model_name = 'UNTITLED MODEL' else: model_name = model_name.upper() with open('trigram_model.txt', 'a') as f: f.write(' \t\t**** {0} ****\n\n'.format(model_name)) entries = 0 for (key, value) in sorted(trigram_probs_dict.items()): f.write(' {0} : {1}, '.format(key, value)) if (entries == 5): f.write('\n') entries = 0 else: entries += 1 f.write('\n\n\n') return<|docstring|># Writes nicely formatted contents # of trigram_probs_dict to a file, # called trigram_model.txt. If the file # already exists, each new model is # appended to the end of the file.<|endoftext|>
8c4b64580f7c963b97ffbaf90861df0a040851757fa97ba036f46486bcc6f401
def load_data(): 'Load the MNIST dataset into train & testing set.\n\n Returns:\n train, test (tuple): Training and testing set.\n ' (train, test) = tf.keras.datasets.mnist.load_data() return (train, test)
Load the MNIST dataset into train & testing set. Returns: train, test (tuple): Training and testing set.
eager-execution/mnist-eager.py
load_data
victor-iyiola/tensorflow-examples
0
python
def load_data(): 'Load the MNIST dataset into train & testing set.\n\n Returns:\n train, test (tuple): Training and testing set.\n ' (train, test) = tf.keras.datasets.mnist.load_data() return (train, test)
def load_data(): 'Load the MNIST dataset into train & testing set.\n\n Returns:\n train, test (tuple): Training and testing set.\n ' (train, test) = tf.keras.datasets.mnist.load_data() return (train, test)<|docstring|>Load the MNIST dataset into train & testing set. Returns: train, test (tuple): Training and testing set.<|endoftext|>
d56a5357579b1f82d7c642b452dfc47b3df1de4a0053b9bdd657f1e60ee475b1
def pre_process(features, labels): 'Flatten images & one-hot encode labels.\n\n Arguments:\n features {tf.Tensor} -- Dataset images.\n labels {tf.Tensor} -- Dataset labels.\n\n Returns:\n {(tf.Tensor, tf.Tensor)} -- features, labels\n ' features = np.array(features, dtype=np.float32) img_size_flat = np.prod(features.shape[1:]) features = features.reshape(((- 1), img_size_flat)) num_classes = len(np.unique(labels)) labels = tf.one_hot(indices=labels, depth=num_classes) return (features, labels)
Flatten images & one-hot encode labels. Arguments: features {tf.Tensor} -- Dataset images. labels {tf.Tensor} -- Dataset labels. Returns: {(tf.Tensor, tf.Tensor)} -- features, labels
eager-execution/mnist-eager.py
pre_process
victor-iyiola/tensorflow-examples
0
python
def pre_process(features, labels): 'Flatten images & one-hot encode labels.\n\n Arguments:\n features {tf.Tensor} -- Dataset images.\n labels {tf.Tensor} -- Dataset labels.\n\n Returns:\n {(tf.Tensor, tf.Tensor)} -- features, labels\n ' features = np.array(features, dtype=np.float32) img_size_flat = np.prod(features.shape[1:]) features = features.reshape(((- 1), img_size_flat)) num_classes = len(np.unique(labels)) labels = tf.one_hot(indices=labels, depth=num_classes) return (features, labels)
def pre_process(features, labels): 'Flatten images & one-hot encode labels.\n\n Arguments:\n features {tf.Tensor} -- Dataset images.\n labels {tf.Tensor} -- Dataset labels.\n\n Returns:\n {(tf.Tensor, tf.Tensor)} -- features, labels\n ' features = np.array(features, dtype=np.float32) img_size_flat = np.prod(features.shape[1:]) features = features.reshape(((- 1), img_size_flat)) num_classes = len(np.unique(labels)) labels = tf.one_hot(indices=labels, depth=num_classes) return (features, labels)<|docstring|>Flatten images & one-hot encode labels. Arguments: features {tf.Tensor} -- Dataset images. labels {tf.Tensor} -- Dataset labels. Returns: {(tf.Tensor, tf.Tensor)} -- features, labels<|endoftext|>
1891cf901a9a200cb60adcdbb4775ce9ca0d90ed711884acc0999dd8699a5cd9
def process_data(features: tf.Tensor, labels: tf.Tensor, batch_size: tf.int32=64, buffer_size: tf.int32=1000): "Create TensorFlow data object from tensor slices.\n\n Args:\n features (tf.Tensor): Dataset input images.\n labels (tf.Tensor): Dataset one-hot labels.\n batch_size (tf.int32): Mini batch size.\n buffer_size (tf.int32): Buffer size for shuffling the dataset.\n\n Returns:\n dataset (tf.data.Dataset): TensorFlow's dataset object.\n " dataset = tf.data.Dataset.from_tensor_slices((features, labels)) dataset = dataset.batch(batch_size=batch_size) dataset = dataset.shuffle(buffer_size=buffer_size) return dataset
Create TensorFlow data object from tensor slices. Args: features (tf.Tensor): Dataset input images. labels (tf.Tensor): Dataset one-hot labels. batch_size (tf.int32): Mini batch size. buffer_size (tf.int32): Buffer size for shuffling the dataset. Returns: dataset (tf.data.Dataset): TensorFlow's dataset object.
eager-execution/mnist-eager.py
process_data
victor-iyiola/tensorflow-examples
0
python
def process_data(features: tf.Tensor, labels: tf.Tensor, batch_size: tf.int32=64, buffer_size: tf.int32=1000): "Create TensorFlow data object from tensor slices.\n\n Args:\n features (tf.Tensor): Dataset input images.\n labels (tf.Tensor): Dataset one-hot labels.\n batch_size (tf.int32): Mini batch size.\n buffer_size (tf.int32): Buffer size for shuffling the dataset.\n\n Returns:\n dataset (tf.data.Dataset): TensorFlow's dataset object.\n " dataset = tf.data.Dataset.from_tensor_slices((features, labels)) dataset = dataset.batch(batch_size=batch_size) dataset = dataset.shuffle(buffer_size=buffer_size) return dataset
def process_data(features: tf.Tensor, labels: tf.Tensor, batch_size: tf.int32=64, buffer_size: tf.int32=1000): "Create TensorFlow data object from tensor slices.\n\n Args:\n features (tf.Tensor): Dataset input images.\n labels (tf.Tensor): Dataset one-hot labels.\n batch_size (tf.int32): Mini batch size.\n buffer_size (tf.int32): Buffer size for shuffling the dataset.\n\n Returns:\n dataset (tf.data.Dataset): TensorFlow's dataset object.\n " dataset = tf.data.Dataset.from_tensor_slices((features, labels)) dataset = dataset.batch(batch_size=batch_size) dataset = dataset.shuffle(buffer_size=buffer_size) return dataset<|docstring|>Create TensorFlow data object from tensor slices. Args: features (tf.Tensor): Dataset input images. labels (tf.Tensor): Dataset one-hot labels. batch_size (tf.int32): Mini batch size. buffer_size (tf.int32): Buffer size for shuffling the dataset. Returns: dataset (tf.data.Dataset): TensorFlow's dataset object.<|endoftext|>
e308b68a5fc3eadccb7ec71c27d2e5087b18d448c01fb5c64eb85abc9ae1dbec
@property def linha_digitavel(self): 'Monta a linha digitável a partir do barcode\n\n Esta é a linha que o cliente pode utilizar para digitar se o código\n de barras não estiver legível.\n ' linha = '' if (self.carteira not in ['6', '8']): self.carteira = '8' c1 = self.barcode[0:11] c2 = self.barcode[11:22] c3 = self.barcode[22:33] c4 = self.barcode[33:44] d1 = str(self.dac11(c1)) d2 = str(self.dac11(c2)) d3 = str(self.dac11(c3)) d3 = str(self.dac11(c4)) if (self.carteira == '6'): d1 = str(self.modulo10(c1)) d2 = str(self.modulo10(c2)) d3 = str(self.modulo10(c3)) d3 = str(self.modulo10(c4)) linha = '%s-%s %s-%s %s-%s %s-%s'(c1, d1, c2, d2, c3, d3, c4, d4) return str(linha)
Monta a linha digitável a partir do barcode Esta é a linha que o cliente pode utilizar para digitar se o código de barras não estiver legível.
pyboleto/bank/febraban.py
linha_digitavel
jraylan/pyboleto
14
python
@property def linha_digitavel(self): 'Monta a linha digitável a partir do barcode\n\n Esta é a linha que o cliente pode utilizar para digitar se o código\n de barras não estiver legível.\n ' linha = if (self.carteira not in ['6', '8']): self.carteira = '8' c1 = self.barcode[0:11] c2 = self.barcode[11:22] c3 = self.barcode[22:33] c4 = self.barcode[33:44] d1 = str(self.dac11(c1)) d2 = str(self.dac11(c2)) d3 = str(self.dac11(c3)) d3 = str(self.dac11(c4)) if (self.carteira == '6'): d1 = str(self.modulo10(c1)) d2 = str(self.modulo10(c2)) d3 = str(self.modulo10(c3)) d3 = str(self.modulo10(c4)) linha = '%s-%s %s-%s %s-%s %s-%s'(c1, d1, c2, d2, c3, d3, c4, d4) return str(linha)
@property def linha_digitavel(self): 'Monta a linha digitável a partir do barcode\n\n Esta é a linha que o cliente pode utilizar para digitar se o código\n de barras não estiver legível.\n ' linha = if (self.carteira not in ['6', '8']): self.carteira = '8' c1 = self.barcode[0:11] c2 = self.barcode[11:22] c3 = self.barcode[22:33] c4 = self.barcode[33:44] d1 = str(self.dac11(c1)) d2 = str(self.dac11(c2)) d3 = str(self.dac11(c3)) d3 = str(self.dac11(c4)) if (self.carteira == '6'): d1 = str(self.modulo10(c1)) d2 = str(self.modulo10(c2)) d3 = str(self.modulo10(c3)) d3 = str(self.modulo10(c4)) linha = '%s-%s %s-%s %s-%s %s-%s'(c1, d1, c2, d2, c3, d3, c4, d4) return str(linha)<|docstring|>Monta a linha digitável a partir do barcode Esta é a linha que o cliente pode utilizar para digitar se o código de barras não estiver legível.<|endoftext|>
d920a3638e40c4e3994ce29f2ce556e8a94066d208023207bad11699f5220693
@property def barcode(self): 'Função para gerar código de barras para arrecadação - FEBRABAN\n\n Convenio: Codigo de identificacao no banco\n Carteiras: \n 1. Prefeituras;\n 2. Saneamento;\n 3. Energia Eletrica e Gas;\n 4. Telecomunicacoes;\n 5. Orgaos Governamentais;\n 6. Carnes e Assemelhados \n ou demais Empresas / Orgaos que serao identificadas atraves do CNPJ. \n 7. Multas de transito\n 9. Uso exclusivo do banco\n\n Posição # Conteúdo\n 01 a 01 01 produto\n 02 a 02 01 segmento ( carteira )\n 03 a 03 01 moeda formato\n 04 a 04 01 digito verificador geral\n 05 a 15 11 valor \n # ----- Se telecomunicacao ---------\n 16 a 19 04 Identificacao empresa\n 20 a 44 25 Campo Livre\n # ------ Se empresa CNPJ -----------\n 16 a 23 08 Identificacao Empresa e/ou ident. + codigo definido no banco\n 24 a 44 21 Campo Livre \n\n Total 44\n ' if (self.carteira not in ['6', '8']): self.carteira = '8' barcode = ('%1s%1s%1s%011d%4s%25s' % ('8', self.carteira, self.moeda_formato, (Decimal(self.valor_documento) * 100), self.identificacao[0:4], self.campo_livre)) dv = self.dac11(barcode) if (self.carteira == '6'): dv = self.modulo10(barcode) return ((barcode[0:4] + str(dv)) + barcode[4:])
Função para gerar código de barras para arrecadação - FEBRABAN Convenio: Codigo de identificacao no banco Carteiras: 1. Prefeituras; 2. Saneamento; 3. Energia Eletrica e Gas; 4. Telecomunicacoes; 5. Orgaos Governamentais; 6. Carnes e Assemelhados ou demais Empresas / Orgaos que serao identificadas atraves do CNPJ. 7. Multas de transito 9. Uso exclusivo do banco Posição # Conteúdo 01 a 01 01 produto 02 a 02 01 segmento ( carteira ) 03 a 03 01 moeda formato 04 a 04 01 digito verificador geral 05 a 15 11 valor # ----- Se telecomunicacao --------- 16 a 19 04 Identificacao empresa 20 a 44 25 Campo Livre # ------ Se empresa CNPJ ----------- 16 a 23 08 Identificacao Empresa e/ou ident. + codigo definido no banco 24 a 44 21 Campo Livre Total 44
pyboleto/bank/febraban.py
barcode
jraylan/pyboleto
14
python
@property def barcode(self): 'Função para gerar código de barras para arrecadação - FEBRABAN\n\n Convenio: Codigo de identificacao no banco\n Carteiras: \n 1. Prefeituras;\n 2. Saneamento;\n 3. Energia Eletrica e Gas;\n 4. Telecomunicacoes;\n 5. Orgaos Governamentais;\n 6. Carnes e Assemelhados \n ou demais Empresas / Orgaos que serao identificadas atraves do CNPJ. \n 7. Multas de transito\n 9. Uso exclusivo do banco\n\n Posição # Conteúdo\n 01 a 01 01 produto\n 02 a 02 01 segmento ( carteira )\n 03 a 03 01 moeda formato\n 04 a 04 01 digito verificador geral\n 05 a 15 11 valor \n # ----- Se telecomunicacao ---------\n 16 a 19 04 Identificacao empresa\n 20 a 44 25 Campo Livre\n # ------ Se empresa CNPJ -----------\n 16 a 23 08 Identificacao Empresa e/ou ident. + codigo definido no banco\n 24 a 44 21 Campo Livre \n\n Total 44\n ' if (self.carteira not in ['6', '8']): self.carteira = '8' barcode = ('%1s%1s%1s%011d%4s%25s' % ('8', self.carteira, self.moeda_formato, (Decimal(self.valor_documento) * 100), self.identificacao[0:4], self.campo_livre)) dv = self.dac11(barcode) if (self.carteira == '6'): dv = self.modulo10(barcode) return ((barcode[0:4] + str(dv)) + barcode[4:])
@property def barcode(self): 'Função para gerar código de barras para arrecadação - FEBRABAN\n\n Convenio: Codigo de identificacao no banco\n Carteiras: \n 1. Prefeituras;\n 2. Saneamento;\n 3. Energia Eletrica e Gas;\n 4. Telecomunicacoes;\n 5. Orgaos Governamentais;\n 6. Carnes e Assemelhados \n ou demais Empresas / Orgaos que serao identificadas atraves do CNPJ. \n 7. Multas de transito\n 9. Uso exclusivo do banco\n\n Posição # Conteúdo\n 01 a 01 01 produto\n 02 a 02 01 segmento ( carteira )\n 03 a 03 01 moeda formato\n 04 a 04 01 digito verificador geral\n 05 a 15 11 valor \n # ----- Se telecomunicacao ---------\n 16 a 19 04 Identificacao empresa\n 20 a 44 25 Campo Livre\n # ------ Se empresa CNPJ -----------\n 16 a 23 08 Identificacao Empresa e/ou ident. + codigo definido no banco\n 24 a 44 21 Campo Livre \n\n Total 44\n ' if (self.carteira not in ['6', '8']): self.carteira = '8' barcode = ('%1s%1s%1s%011d%4s%25s' % ('8', self.carteira, self.moeda_formato, (Decimal(self.valor_documento) * 100), self.identificacao[0:4], self.campo_livre)) dv = self.dac11(barcode) if (self.carteira == '6'): dv = self.modulo10(barcode) return ((barcode[0:4] + str(dv)) + barcode[4:])<|docstring|>Função para gerar código de barras para arrecadação - FEBRABAN Convenio: Codigo de identificacao no banco Carteiras: 1. Prefeituras; 2. Saneamento; 3. Energia Eletrica e Gas; 4. Telecomunicacoes; 5. Orgaos Governamentais; 6. Carnes e Assemelhados ou demais Empresas / Orgaos que serao identificadas atraves do CNPJ. 7. Multas de transito 9. Uso exclusivo do banco Posição # Conteúdo 01 a 01 01 produto 02 a 02 01 segmento ( carteira ) 03 a 03 01 moeda formato 04 a 04 01 digito verificador geral 05 a 15 11 valor # ----- Se telecomunicacao --------- 16 a 19 04 Identificacao empresa 20 a 44 25 Campo Livre # ------ Se empresa CNPJ ----------- 16 a 23 08 Identificacao Empresa e/ou ident. + codigo definido no banco 24 a 44 21 Campo Livre Total 44<|endoftext|>
a5868d76ac29e12b65bb6bf1213028a1e4d971e930180219799e0da2a6f494a3
def process_raw_ml(in_file_path: Path, out_file_path: Path, min_rating_num: int=0): '\n process raw movielens ratings data. One line represents one interaction by one user and has the following format:\n userId,movieId\n The lines within user are ordered by timestamp.\n\n in_file_path: path like. movielens ratings file\n out_file_path: path like. processed file\n min_rating_num: int. minimum interactions by one user. Interactions less than min_rating_num would be filtered.\n ' OneRating = namedtuple('OneRating', ['movieid', 'timestamp']) ratings = defaultdict(list) print('Start processing {}.'.format(in_file_path)) with open(in_file_path, 'r', encoding='utf-8') as in_f, open(out_file_path, 'w', encoding='utf-8') as out_f: header = in_f.readline() last_userid = '1' cnt = 0 for line in tqdm(in_f): cnt += 1 line = line.strip().split(',') (userid, movieid, rating, timestamp) = line ratings[userid].append(OneRating(movieid, timestamp)) if (userid != last_userid): if (cnt >= min_rating_num): sorted_ratings = sorted(ratings[last_userid], key=(lambda one_rating: one_rating.timestamp)) for one_rating in sorted_ratings: out_f.write('{},{}\n'.format(last_userid, one_rating.movieid)) last_userid = userid cnt = 1 if (cnt >= min_rating_num): sorted_ratings = sorted(ratings[last_userid], key=(lambda one_rating: one_rating.timestamp)) for one_rating in sorted_ratings: out_f.write('{},{}\n'.format(last_userid, one_rating.movieid)) print('Process raw ml data done.') print('Processed file: {}'.format(out_file_path))
process raw movielens ratings data. One line represents one interaction by one user and has the following format: userId,movieId The lines within user are ordered by timestamp. in_file_path: path like. movielens ratings file out_file_path: path like. processed file min_rating_num: int. minimum interactions by one user. Interactions less than min_rating_num would be filtered.
data_preprocessing.py
process_raw_ml
bycxw/ETC4Rec
0
python
def process_raw_ml(in_file_path: Path, out_file_path: Path, min_rating_num: int=0): '\n process raw movielens ratings data. One line represents one interaction by one user and has the following format:\n userId,movieId\n The lines within user are ordered by timestamp.\n\n in_file_path: path like. movielens ratings file\n out_file_path: path like. processed file\n min_rating_num: int. minimum interactions by one user. Interactions less than min_rating_num would be filtered.\n ' OneRating = namedtuple('OneRating', ['movieid', 'timestamp']) ratings = defaultdict(list) print('Start processing {}.'.format(in_file_path)) with open(in_file_path, 'r', encoding='utf-8') as in_f, open(out_file_path, 'w', encoding='utf-8') as out_f: header = in_f.readline() last_userid = '1' cnt = 0 for line in tqdm(in_f): cnt += 1 line = line.strip().split(',') (userid, movieid, rating, timestamp) = line ratings[userid].append(OneRating(movieid, timestamp)) if (userid != last_userid): if (cnt >= min_rating_num): sorted_ratings = sorted(ratings[last_userid], key=(lambda one_rating: one_rating.timestamp)) for one_rating in sorted_ratings: out_f.write('{},{}\n'.format(last_userid, one_rating.movieid)) last_userid = userid cnt = 1 if (cnt >= min_rating_num): sorted_ratings = sorted(ratings[last_userid], key=(lambda one_rating: one_rating.timestamp)) for one_rating in sorted_ratings: out_f.write('{},{}\n'.format(last_userid, one_rating.movieid)) print('Process raw ml data done.') print('Processed file: {}'.format(out_file_path))
def process_raw_ml(in_file_path: Path, out_file_path: Path, min_rating_num: int=0): '\n process raw movielens ratings data. One line represents one interaction by one user and has the following format:\n userId,movieId\n The lines within user are ordered by timestamp.\n\n in_file_path: path like. movielens ratings file\n out_file_path: path like. processed file\n min_rating_num: int. minimum interactions by one user. Interactions less than min_rating_num would be filtered.\n ' OneRating = namedtuple('OneRating', ['movieid', 'timestamp']) ratings = defaultdict(list) print('Start processing {}.'.format(in_file_path)) with open(in_file_path, 'r', encoding='utf-8') as in_f, open(out_file_path, 'w', encoding='utf-8') as out_f: header = in_f.readline() last_userid = '1' cnt = 0 for line in tqdm(in_f): cnt += 1 line = line.strip().split(',') (userid, movieid, rating, timestamp) = line ratings[userid].append(OneRating(movieid, timestamp)) if (userid != last_userid): if (cnt >= min_rating_num): sorted_ratings = sorted(ratings[last_userid], key=(lambda one_rating: one_rating.timestamp)) for one_rating in sorted_ratings: out_f.write('{},{}\n'.format(last_userid, one_rating.movieid)) last_userid = userid cnt = 1 if (cnt >= min_rating_num): sorted_ratings = sorted(ratings[last_userid], key=(lambda one_rating: one_rating.timestamp)) for one_rating in sorted_ratings: out_f.write('{},{}\n'.format(last_userid, one_rating.movieid)) print('Process raw ml data done.') print('Processed file: {}'.format(out_file_path))<|docstring|>process raw movielens ratings data. One line represents one interaction by one user and has the following format: userId,movieId The lines within user are ordered by timestamp. in_file_path: path like. movielens ratings file out_file_path: path like. processed file min_rating_num: int. minimum interactions by one user. Interactions less than min_rating_num would be filtered.<|endoftext|>
80256f8160328cc3715b2942a04761f31228fac3b407dc77b80b15481f7b9da2
def build_vocab(file_path: Path): '\n Build vocab for interaction data.\n ' print('Start build vocab...') vocab = UserItemVocab() with open(file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip().split(',') (user, movie) = line vocab.update_user(user) vocab.update_item(movie) print('Build vocab done.') print('user num: {}, item num: {}'.format(vocab.get_user_count(), vocab.get_item_count())) return vocab
Build vocab for interaction data.
data_preprocessing.py
build_vocab
bycxw/ETC4Rec
0
python
def build_vocab(file_path: Path): '\n \n ' print('Start build vocab...') vocab = UserItemVocab() with open(file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip().split(',') (user, movie) = line vocab.update_user(user) vocab.update_item(movie) print('Build vocab done.') print('user num: {}, item num: {}'.format(vocab.get_user_count(), vocab.get_item_count())) return vocab
def build_vocab(file_path: Path): '\n \n ' print('Start build vocab...') vocab = UserItemVocab() with open(file_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip().split(',') (user, movie) = line vocab.update_user(user) vocab.update_item(movie) print('Build vocab done.') print('user num: {}, item num: {}'.format(vocab.get_user_count(), vocab.get_item_count())) return vocab<|docstring|>Build vocab for interaction data.<|endoftext|>
62fe91b5b7d99e76f109ad9b6175d4fc75354f2d5695baf22584d645b8ed0da9
def build_data(in_file_path: Path, out_file_path: Path, vocab: UserItemVocab): '\n build data for model.\n Convert user/item name to id.\n ' print('Start build data...') with open(in_file_path, 'r', encoding='utf-8') as in_f, open(out_file_path, 'w', encoding='utf-8') as out_f: for line in in_f: line = line.strip().split(',') (user, movie) = line (user_id, movie_id) = (vocab.convert_user_to_id(user), vocab.convert_item_to_id(movie)) if ((not user_id) or (not movie_id)): continue out_f.write('{} {}\n'.format(user_id, movie_id)) print('Build data done.') print('data file: {}'.format(out_file_path))
build data for model. Convert user/item name to id.
data_preprocessing.py
build_data
bycxw/ETC4Rec
0
python
def build_data(in_file_path: Path, out_file_path: Path, vocab: UserItemVocab): '\n build data for model.\n Convert user/item name to id.\n ' print('Start build data...') with open(in_file_path, 'r', encoding='utf-8') as in_f, open(out_file_path, 'w', encoding='utf-8') as out_f: for line in in_f: line = line.strip().split(',') (user, movie) = line (user_id, movie_id) = (vocab.convert_user_to_id(user), vocab.convert_item_to_id(movie)) if ((not user_id) or (not movie_id)): continue out_f.write('{} {}\n'.format(user_id, movie_id)) print('Build data done.') print('data file: {}'.format(out_file_path))
def build_data(in_file_path: Path, out_file_path: Path, vocab: UserItemVocab): '\n build data for model.\n Convert user/item name to id.\n ' print('Start build data...') with open(in_file_path, 'r', encoding='utf-8') as in_f, open(out_file_path, 'w', encoding='utf-8') as out_f: for line in in_f: line = line.strip().split(',') (user, movie) = line (user_id, movie_id) = (vocab.convert_user_to_id(user), vocab.convert_item_to_id(movie)) if ((not user_id) or (not movie_id)): continue out_f.write('{} {}\n'.format(user_id, movie_id)) print('Build data done.') print('data file: {}'.format(out_file_path))<|docstring|>build data for model. Convert user/item name to id.<|endoftext|>
5f2fb22d082c33e8cae9fae6dce550c9394872c52fcbcc2f0a80b65e1c9a8f2e
def select_file(): 'Creates a window to select a file and plots the file data on the DataAnalysis page' try: temp_file_path = askopenfilename() except: print(('Warning: file path not valid: %s ' % temp_file_path)) return None settings.PATH_DATAFILE = temp_file_path if (settings.DEBUG.status == True): print(('Selected data file path: %s' % settings.PATH_DATAFILE)) plot.plot_static() plot.table_static() lib.window.refresh()
Creates a window to select a file and plots the file data on the DataAnalysis page
gui/lib/files.py
select_file
SEDSIIT/ground-station-app
4
python
def select_file(): try: temp_file_path = askopenfilename() except: print(('Warning: file path not valid: %s ' % temp_file_path)) return None settings.PATH_DATAFILE = temp_file_path if (settings.DEBUG.status == True): print(('Selected data file path: %s' % settings.PATH_DATAFILE)) plot.plot_static() plot.table_static() lib.window.refresh()
def select_file(): try: temp_file_path = askopenfilename() except: print(('Warning: file path not valid: %s ' % temp_file_path)) return None settings.PATH_DATAFILE = temp_file_path if (settings.DEBUG.status == True): print(('Selected data file path: %s' % settings.PATH_DATAFILE)) plot.plot_static() plot.table_static() lib.window.refresh()<|docstring|>Creates a window to select a file and plots the file data on the DataAnalysis page<|endoftext|>
df524a60e408d37c504d7e39be2f2df2ba59a575be14b222c48bff96ebdd244a
def save_file(): "Save the current data on the temporary telemetry data file on a file of the user's choosing" if (settings.PLATFORM == 'windows'): settings.PATH_DATAFILE = (asksaveasfilename(filetypes=[('comma separated value (*.csv)', '*.csv')]) + '.csv') else: settings.PATH_DATAFILE = asksaveasfilename(filetypes=[('comma separated value (*.csv)', '*.csv')]) shutil.copyfile(settings.PATH_LIVEDATA, settings.PATH_DATAFILE) if (settings.DEBUG.status == True): print(('Taking telemetry file: %s' % settings.PATH_LIVEDATA)) print(('Saving as: %s' % settings.PATH_DATAFILE))
Save the current data on the temporary telemetry data file on a file of the user's choosing
gui/lib/files.py
save_file
SEDSIIT/ground-station-app
4
python
def save_file(): if (settings.PLATFORM == 'windows'): settings.PATH_DATAFILE = (asksaveasfilename(filetypes=[('comma separated value (*.csv)', '*.csv')]) + '.csv') else: settings.PATH_DATAFILE = asksaveasfilename(filetypes=[('comma separated value (*.csv)', '*.csv')]) shutil.copyfile(settings.PATH_LIVEDATA, settings.PATH_DATAFILE) if (settings.DEBUG.status == True): print(('Taking telemetry file: %s' % settings.PATH_LIVEDATA)) print(('Saving as: %s' % settings.PATH_DATAFILE))
def save_file(): if (settings.PLATFORM == 'windows'): settings.PATH_DATAFILE = (asksaveasfilename(filetypes=[('comma separated value (*.csv)', '*.csv')]) + '.csv') else: settings.PATH_DATAFILE = asksaveasfilename(filetypes=[('comma separated value (*.csv)', '*.csv')]) shutil.copyfile(settings.PATH_LIVEDATA, settings.PATH_DATAFILE) if (settings.DEBUG.status == True): print(('Taking telemetry file: %s' % settings.PATH_LIVEDATA)) print(('Saving as: %s' % settings.PATH_DATAFILE))<|docstring|>Save the current data on the temporary telemetry data file on a file of the user's choosing<|endoftext|>
d4f88f28bbd8b47ef4cabb84205a8e7349982e8751e088a09daa7f2f44d5faeb
def telemetry_file_init(): 'Clear temporary telemetry flight data file' if os.path.exists(settings.PATH_LIVEDATA): os.remove(settings.PATH_LIVEDATA) else: print('WARNING: Telemetry file not found!') temp_file = open(settings.PATH_LIVEDATA, 'x') temp_file.write('Time,Altitude,Velocity,Acceleration,Latitude,Longitude,Events\n') temp_file.close() if (settings.DEBUG.status == True): print(('Clearing temp file: %s' % settings.PATH_LIVEDATA))
Clear temporary telemetry flight data file
gui/lib/files.py
telemetry_file_init
SEDSIIT/ground-station-app
4
python
def telemetry_file_init(): if os.path.exists(settings.PATH_LIVEDATA): os.remove(settings.PATH_LIVEDATA) else: print('WARNING: Telemetry file not found!') temp_file = open(settings.PATH_LIVEDATA, 'x') temp_file.write('Time,Altitude,Velocity,Acceleration,Latitude,Longitude,Events\n') temp_file.close() if (settings.DEBUG.status == True): print(('Clearing temp file: %s' % settings.PATH_LIVEDATA))
def telemetry_file_init(): if os.path.exists(settings.PATH_LIVEDATA): os.remove(settings.PATH_LIVEDATA) else: print('WARNING: Telemetry file not found!') temp_file = open(settings.PATH_LIVEDATA, 'x') temp_file.write('Time,Altitude,Velocity,Acceleration,Latitude,Longitude,Events\n') temp_file.close() if (settings.DEBUG.status == True): print(('Clearing temp file: %s' % settings.PATH_LIVEDATA))<|docstring|>Clear temporary telemetry flight data file<|endoftext|>
2a74a7f77ffd9a293ae786440066ac93a76adff04d6b6c0b2197ad13dc4a182a
def gen_key(path): '\n Generate a key for use with salt-ssh\n ' cmd = 'ssh-keygen -P "" -f {0} -t rsa -q'.format(path) if (not os.path.isdir(os.path.dirname(path))): os.makedirs(os.path.dirname(path)) subprocess.call(cmd, shell=True)
Generate a key for use with salt-ssh
salt/client/ssh/shell.py
gen_key
belvedere-trading/salt
2
python
def gen_key(path): '\n \n ' cmd = 'ssh-keygen -P -f {0} -t rsa -q'.format(path) if (not os.path.isdir(os.path.dirname(path))): os.makedirs(os.path.dirname(path)) subprocess.call(cmd, shell=True)
def gen_key(path): '\n \n ' cmd = 'ssh-keygen -P -f {0} -t rsa -q'.format(path) if (not os.path.isdir(os.path.dirname(path))): os.makedirs(os.path.dirname(path)) subprocess.call(cmd, shell=True)<|docstring|>Generate a key for use with salt-ssh<|endoftext|>
17a07be8b7f75193afa2586946a67184f9c049f44e85da805e84a5d4faa1b948
def get_error(self, errstr): '\n Parse out an error and return a targeted error string\n ' for line in errstr.split('\n'): if line.startswith('ssh:'): return line if line.startswith('Pseudo-terminal'): continue if ('to the list of known hosts.' in line): continue return line return errstr
Parse out an error and return a targeted error string
salt/client/ssh/shell.py
get_error
belvedere-trading/salt
2
python
def get_error(self, errstr): '\n \n ' for line in errstr.split('\n'): if line.startswith('ssh:'): return line if line.startswith('Pseudo-terminal'): continue if ('to the list of known hosts.' in line): continue return line return errstr
def get_error(self, errstr): '\n \n ' for line in errstr.split('\n'): if line.startswith('ssh:'): return line if line.startswith('Pseudo-terminal'): continue if ('to the list of known hosts.' in line): continue return line return errstr<|docstring|>Parse out an error and return a targeted error string<|endoftext|>
6dbb1bdbce1be3ef23e691f9cdbf8d3d47dff5b94a92950f80edff30484bd6cf
def _key_opts(self): '\n Return options for the ssh command base for Salt to call\n ' options = ['KbdInteractiveAuthentication=no'] if self.passwd: options.append('PasswordAuthentication=yes') else: options.append('PasswordAuthentication=no') if (self.opts.get('_ssh_version', (0,)) > (4, 9)): options.append('GSSAPIAuthentication=no') options.append('ConnectTimeout={0}'.format(self.timeout)) if self.opts.get('ignore_host_keys'): options.append('StrictHostKeyChecking=no') if self.opts.get('no_host_keys'): options.extend(['StrictHostKeyChecking=no', 'UserKnownHostsFile=/dev/null']) known_hosts = self.opts.get('known_hosts_file') if (known_hosts and os.path.isfile(known_hosts)): options.append('UserKnownHostsFile={0}'.format(known_hosts)) if self.port: options.append('Port={0}'.format(self.port)) if self.priv: options.append('IdentityFile={0}'.format(self.priv)) if self.user: options.append('User={0}'.format(self.user)) if self.identities_only: options.append('IdentitiesOnly=yes') ret = [] for option in options: ret.append('-o {0} '.format(option)) return ''.join(ret)
Return options for the ssh command base for Salt to call
salt/client/ssh/shell.py
_key_opts
belvedere-trading/salt
2
python
def _key_opts(self): '\n \n ' options = ['KbdInteractiveAuthentication=no'] if self.passwd: options.append('PasswordAuthentication=yes') else: options.append('PasswordAuthentication=no') if (self.opts.get('_ssh_version', (0,)) > (4, 9)): options.append('GSSAPIAuthentication=no') options.append('ConnectTimeout={0}'.format(self.timeout)) if self.opts.get('ignore_host_keys'): options.append('StrictHostKeyChecking=no') if self.opts.get('no_host_keys'): options.extend(['StrictHostKeyChecking=no', 'UserKnownHostsFile=/dev/null']) known_hosts = self.opts.get('known_hosts_file') if (known_hosts and os.path.isfile(known_hosts)): options.append('UserKnownHostsFile={0}'.format(known_hosts)) if self.port: options.append('Port={0}'.format(self.port)) if self.priv: options.append('IdentityFile={0}'.format(self.priv)) if self.user: options.append('User={0}'.format(self.user)) if self.identities_only: options.append('IdentitiesOnly=yes') ret = [] for option in options: ret.append('-o {0} '.format(option)) return .join(ret)
def _key_opts(self): '\n \n ' options = ['KbdInteractiveAuthentication=no'] if self.passwd: options.append('PasswordAuthentication=yes') else: options.append('PasswordAuthentication=no') if (self.opts.get('_ssh_version', (0,)) > (4, 9)): options.append('GSSAPIAuthentication=no') options.append('ConnectTimeout={0}'.format(self.timeout)) if self.opts.get('ignore_host_keys'): options.append('StrictHostKeyChecking=no') if self.opts.get('no_host_keys'): options.extend(['StrictHostKeyChecking=no', 'UserKnownHostsFile=/dev/null']) known_hosts = self.opts.get('known_hosts_file') if (known_hosts and os.path.isfile(known_hosts)): options.append('UserKnownHostsFile={0}'.format(known_hosts)) if self.port: options.append('Port={0}'.format(self.port)) if self.priv: options.append('IdentityFile={0}'.format(self.priv)) if self.user: options.append('User={0}'.format(self.user)) if self.identities_only: options.append('IdentitiesOnly=yes') ret = [] for option in options: ret.append('-o {0} '.format(option)) return .join(ret)<|docstring|>Return options for the ssh command base for Salt to call<|endoftext|>
993fe2fbe371cf0193bcbbb25490f7de5fff293fb1c5c99efef0f9d9f2e9f42b
def _passwd_opts(self): '\n Return options to pass to ssh\n ' options = ['ControlMaster=auto', 'StrictHostKeyChecking=no'] if (self.opts['_ssh_version'] > (4, 9)): options.append('GSSAPIAuthentication=no') options.append('ConnectTimeout={0}'.format(self.timeout)) if self.opts.get('ignore_host_keys'): options.append('StrictHostKeyChecking=no') if self.opts.get('no_host_keys'): options.extend(['StrictHostKeyChecking=no', 'UserKnownHostsFile=/dev/null']) if self.passwd: options.extend(['PasswordAuthentication=yes', 'PubkeyAuthentication=yes']) else: options.extend(['PasswordAuthentication=no', 'PubkeyAuthentication=yes', 'KbdInteractiveAuthentication=no', 'ChallengeResponseAuthentication=no', 'BatchMode=yes']) if self.port: options.append('Port={0}'.format(self.port)) if self.user: options.append('User={0}'.format(self.user)) if self.identities_only: options.append('IdentitiesOnly=yes') ret = [] for option in options: ret.append('-o {0} '.format(option)) return ''.join(ret)
Return options to pass to ssh
salt/client/ssh/shell.py
_passwd_opts
belvedere-trading/salt
2
python
def _passwd_opts(self): '\n \n ' options = ['ControlMaster=auto', 'StrictHostKeyChecking=no'] if (self.opts['_ssh_version'] > (4, 9)): options.append('GSSAPIAuthentication=no') options.append('ConnectTimeout={0}'.format(self.timeout)) if self.opts.get('ignore_host_keys'): options.append('StrictHostKeyChecking=no') if self.opts.get('no_host_keys'): options.extend(['StrictHostKeyChecking=no', 'UserKnownHostsFile=/dev/null']) if self.passwd: options.extend(['PasswordAuthentication=yes', 'PubkeyAuthentication=yes']) else: options.extend(['PasswordAuthentication=no', 'PubkeyAuthentication=yes', 'KbdInteractiveAuthentication=no', 'ChallengeResponseAuthentication=no', 'BatchMode=yes']) if self.port: options.append('Port={0}'.format(self.port)) if self.user: options.append('User={0}'.format(self.user)) if self.identities_only: options.append('IdentitiesOnly=yes') ret = [] for option in options: ret.append('-o {0} '.format(option)) return .join(ret)
def _passwd_opts(self): '\n \n ' options = ['ControlMaster=auto', 'StrictHostKeyChecking=no'] if (self.opts['_ssh_version'] > (4, 9)): options.append('GSSAPIAuthentication=no') options.append('ConnectTimeout={0}'.format(self.timeout)) if self.opts.get('ignore_host_keys'): options.append('StrictHostKeyChecking=no') if self.opts.get('no_host_keys'): options.extend(['StrictHostKeyChecking=no', 'UserKnownHostsFile=/dev/null']) if self.passwd: options.extend(['PasswordAuthentication=yes', 'PubkeyAuthentication=yes']) else: options.extend(['PasswordAuthentication=no', 'PubkeyAuthentication=yes', 'KbdInteractiveAuthentication=no', 'ChallengeResponseAuthentication=no', 'BatchMode=yes']) if self.port: options.append('Port={0}'.format(self.port)) if self.user: options.append('User={0}'.format(self.user)) if self.identities_only: options.append('IdentitiesOnly=yes') ret = [] for option in options: ret.append('-o {0} '.format(option)) return .join(ret)<|docstring|>Return options to pass to ssh<|endoftext|>
5e7a3da26354e6e59c508ef8b1fd9405fd7fcfe6dd6c813eeb85cf890402c259
def _copy_id_str_old(self): '\n Return the string to execute ssh-copy-id\n ' if self.passwd: return "{0} {1} '{2} -p {3} {4}@{5}'".format('ssh-copy-id', '-i {0}.pub'.format(self.priv), self._passwd_opts(), self.port, self.user, self.host) return None
Return the string to execute ssh-copy-id
salt/client/ssh/shell.py
_copy_id_str_old
belvedere-trading/salt
2
python
def _copy_id_str_old(self): '\n \n ' if self.passwd: return "{0} {1} '{2} -p {3} {4}@{5}'".format('ssh-copy-id', '-i {0}.pub'.format(self.priv), self._passwd_opts(), self.port, self.user, self.host) return None
def _copy_id_str_old(self): '\n \n ' if self.passwd: return "{0} {1} '{2} -p {3} {4}@{5}'".format('ssh-copy-id', '-i {0}.pub'.format(self.priv), self._passwd_opts(), self.port, self.user, self.host) return None<|docstring|>Return the string to execute ssh-copy-id<|endoftext|>
76e237dc93ad5e3fc88e88f587257eeacaee55e16c91f77b6c04bc5f19a170b6
def _copy_id_str_new(self): '\n Since newer ssh-copy-id commands ingest option differently we need to\n have two commands\n ' if self.passwd: return '{0} {1} {2} -p {3} {4}@{5}'.format('ssh-copy-id', '-i {0}.pub'.format(self.priv), self._passwd_opts(), self.port, self.user, self.host) return None
Since newer ssh-copy-id commands ingest option differently we need to have two commands
salt/client/ssh/shell.py
_copy_id_str_new
belvedere-trading/salt
2
python
def _copy_id_str_new(self): '\n Since newer ssh-copy-id commands ingest option differently we need to\n have two commands\n ' if self.passwd: return '{0} {1} {2} -p {3} {4}@{5}'.format('ssh-copy-id', '-i {0}.pub'.format(self.priv), self._passwd_opts(), self.port, self.user, self.host) return None
def _copy_id_str_new(self): '\n Since newer ssh-copy-id commands ingest option differently we need to\n have two commands\n ' if self.passwd: return '{0} {1} {2} -p {3} {4}@{5}'.format('ssh-copy-id', '-i {0}.pub'.format(self.priv), self._passwd_opts(), self.port, self.user, self.host) return None<|docstring|>Since newer ssh-copy-id commands ingest option differently we need to have two commands<|endoftext|>
0eacf39823b457344185666e4f551e0b3a77450f546ab2defc8b188882edc3a3
def copy_id(self): '\n Execute ssh-copy-id to plant the id file on the target\n ' (stdout, stderr, retcode) = self._run_cmd(self._copy_id_str_old()) if ((salt.defaults.exitcodes.EX_OK != retcode) and stderr.startswith('Usage')): (stdout, stderr, retcode) = self._run_cmd(self._copy_id_str_new()) return (stdout, stderr, retcode)
Execute ssh-copy-id to plant the id file on the target
salt/client/ssh/shell.py
copy_id
belvedere-trading/salt
2
python
def copy_id(self): '\n \n ' (stdout, stderr, retcode) = self._run_cmd(self._copy_id_str_old()) if ((salt.defaults.exitcodes.EX_OK != retcode) and stderr.startswith('Usage')): (stdout, stderr, retcode) = self._run_cmd(self._copy_id_str_new()) return (stdout, stderr, retcode)
def copy_id(self): '\n \n ' (stdout, stderr, retcode) = self._run_cmd(self._copy_id_str_old()) if ((salt.defaults.exitcodes.EX_OK != retcode) and stderr.startswith('Usage')): (stdout, stderr, retcode) = self._run_cmd(self._copy_id_str_new()) return (stdout, stderr, retcode)<|docstring|>Execute ssh-copy-id to plant the id file on the target<|endoftext|>
12a127f456d4360baf6c31bd9afa94bcb208b9c26ee0bd800b203989d308409c
def _cmd_str(self, cmd, ssh='ssh'): '\n Return the cmd string to execute\n ' opts = '' tty = self.tty if (ssh != 'ssh'): tty = False if self.passwd: opts = self._passwd_opts() if self.priv: opts = self._key_opts() return '{0} {1} {2} {3} {4}'.format(ssh, ('' if (ssh == 'scp') else self.host), ('-t -t' if tty else ''), opts, cmd)
Return the cmd string to execute
salt/client/ssh/shell.py
_cmd_str
belvedere-trading/salt
2
python
def _cmd_str(self, cmd, ssh='ssh'): '\n \n ' opts = tty = self.tty if (ssh != 'ssh'): tty = False if self.passwd: opts = self._passwd_opts() if self.priv: opts = self._key_opts() return '{0} {1} {2} {3} {4}'.format(ssh, ( if (ssh == 'scp') else self.host), ('-t -t' if tty else ), opts, cmd)
def _cmd_str(self, cmd, ssh='ssh'): '\n \n ' opts = tty = self.tty if (ssh != 'ssh'): tty = False if self.passwd: opts = self._passwd_opts() if self.priv: opts = self._key_opts() return '{0} {1} {2} {3} {4}'.format(ssh, ( if (ssh == 'scp') else self.host), ('-t -t' if tty else ), opts, cmd)<|docstring|>Return the cmd string to execute<|endoftext|>
eadf9f39c70d0cc271f88b52ee15b1cf45555743cdf30df7d145b700856afdf8
def _old_run_cmd(self, cmd): '\n Cleanly execute the command string\n ' try: proc = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) data = proc.communicate() return (data[0], data[1], proc.returncode) except Exception: return ('local', 'Unknown Error', None)
Cleanly execute the command string
salt/client/ssh/shell.py
_old_run_cmd
belvedere-trading/salt
2
python
def _old_run_cmd(self, cmd): '\n \n ' try: proc = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) data = proc.communicate() return (data[0], data[1], proc.returncode) except Exception: return ('local', 'Unknown Error', None)
def _old_run_cmd(self, cmd): '\n \n ' try: proc = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) data = proc.communicate() return (data[0], data[1], proc.returncode) except Exception: return ('local', 'Unknown Error', None)<|docstring|>Cleanly execute the command string<|endoftext|>
87663db18e1fd3d9d3c027d3f883d9bcc25c5fd4e9198a9679cac289ba7da6dc
def _run_nb_cmd(self, cmd): '\n cmd iterator\n ' try: proc = salt.utils.nb_popen.NonBlockingPopen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) while True: time.sleep(0.1) out = proc.recv() err = proc.recv_err() rcode = proc.returncode if ((out is None) and (err is None)): break if err: err = self.get_error(err) (yield (out, err, rcode)) except Exception: (yield ('', 'Unknown Error', None))
cmd iterator
salt/client/ssh/shell.py
_run_nb_cmd
belvedere-trading/salt
2
python
def _run_nb_cmd(self, cmd): '\n \n ' try: proc = salt.utils.nb_popen.NonBlockingPopen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) while True: time.sleep(0.1) out = proc.recv() err = proc.recv_err() rcode = proc.returncode if ((out is None) and (err is None)): break if err: err = self.get_error(err) (yield (out, err, rcode)) except Exception: (yield (, 'Unknown Error', None))
def _run_nb_cmd(self, cmd): '\n \n ' try: proc = salt.utils.nb_popen.NonBlockingPopen(cmd, shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE) while True: time.sleep(0.1) out = proc.recv() err = proc.recv_err() rcode = proc.returncode if ((out is None) and (err is None)): break if err: err = self.get_error(err) (yield (out, err, rcode)) except Exception: (yield (, 'Unknown Error', None))<|docstring|>cmd iterator<|endoftext|>
6ca4941f33671e34697cc19521ce8feb9604d82e80a1e2c9050bdaa53602044b
def exec_nb_cmd(self, cmd): '\n Yield None until cmd finished\n ' r_out = [] r_err = [] rcode = None cmd = self._cmd_str(cmd) logmsg = 'Executing non-blocking command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) log.debug(logmsg) for (out, err, rcode) in self._run_nb_cmd(cmd): if (out is not None): r_out.append(out) if (err is not None): r_err.append(err) (yield (None, None, None)) (yield (''.join(r_out), ''.join(r_err), rcode))
Yield None until cmd finished
salt/client/ssh/shell.py
exec_nb_cmd
belvedere-trading/salt
2
python
def exec_nb_cmd(self, cmd): '\n \n ' r_out = [] r_err = [] rcode = None cmd = self._cmd_str(cmd) logmsg = 'Executing non-blocking command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) log.debug(logmsg) for (out, err, rcode) in self._run_nb_cmd(cmd): if (out is not None): r_out.append(out) if (err is not None): r_err.append(err) (yield (None, None, None)) (yield (.join(r_out), .join(r_err), rcode))
def exec_nb_cmd(self, cmd): '\n \n ' r_out = [] r_err = [] rcode = None cmd = self._cmd_str(cmd) logmsg = 'Executing non-blocking command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) log.debug(logmsg) for (out, err, rcode) in self._run_nb_cmd(cmd): if (out is not None): r_out.append(out) if (err is not None): r_err.append(err) (yield (None, None, None)) (yield (.join(r_out), .join(r_err), rcode))<|docstring|>Yield None until cmd finished<|endoftext|>
43920080165cd72904d88684e6dae9d40dee9fe09ae9e524a18a43888e652dd0
def exec_cmd(self, cmd): '\n Execute a remote command\n ' cmd = self._cmd_str(cmd) logmsg = 'Executing command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) if ('decode("base64")' in logmsg): log.debug('Executed SHIM command. Command logged to TRACE') log.trace(logmsg) else: log.debug(logmsg) ret = self._run_cmd(cmd) return ret
Execute a remote command
salt/client/ssh/shell.py
exec_cmd
belvedere-trading/salt
2
python
def exec_cmd(self, cmd): '\n \n ' cmd = self._cmd_str(cmd) logmsg = 'Executing command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) if ('decode("base64")' in logmsg): log.debug('Executed SHIM command. Command logged to TRACE') log.trace(logmsg) else: log.debug(logmsg) ret = self._run_cmd(cmd) return ret
def exec_cmd(self, cmd): '\n \n ' cmd = self._cmd_str(cmd) logmsg = 'Executing command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) if ('decode("base64")' in logmsg): log.debug('Executed SHIM command. Command logged to TRACE') log.trace(logmsg) else: log.debug(logmsg) ret = self._run_cmd(cmd) return ret<|docstring|>Execute a remote command<|endoftext|>
bdefaa6657882abcfe6f92ef27f8359cee5d87fc84700a93ff9c89034ffdf191
def send(self, local, remote, makedirs=False): '\n scp a file or files to a remote system\n ' if makedirs: self.exec_cmd('mkdir -p {0}'.format(os.path.dirname(remote))) cmd = '{0} {1}:{2}'.format(local, self.host, remote) cmd = self._cmd_str(cmd, ssh='scp') logmsg = 'Executing command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) log.debug(logmsg) return self._run_cmd(cmd)
scp a file or files to a remote system
salt/client/ssh/shell.py
send
belvedere-trading/salt
2
python
def send(self, local, remote, makedirs=False): '\n \n ' if makedirs: self.exec_cmd('mkdir -p {0}'.format(os.path.dirname(remote))) cmd = '{0} {1}:{2}'.format(local, self.host, remote) cmd = self._cmd_str(cmd, ssh='scp') logmsg = 'Executing command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) log.debug(logmsg) return self._run_cmd(cmd)
def send(self, local, remote, makedirs=False): '\n \n ' if makedirs: self.exec_cmd('mkdir -p {0}'.format(os.path.dirname(remote))) cmd = '{0} {1}:{2}'.format(local, self.host, remote) cmd = self._cmd_str(cmd, ssh='scp') logmsg = 'Executing command: {0}'.format(cmd) if self.passwd: logmsg = logmsg.replace(self.passwd, ('*' * 6)) log.debug(logmsg) return self._run_cmd(cmd)<|docstring|>scp a file or files to a remote system<|endoftext|>
22dcc4bddcfa3e83549473602fd2a66541004a9c56152d1ef01e9c045f1129a0
def _run_cmd(self, cmd, key_accept=False, passwd_retries=3): '\n Execute a shell command via VT. This is blocking and assumes that ssh\n is being run\n ' term = salt.utils.vt.Terminal(cmd, shell=True, log_stdout=True, log_stdout_level='trace', log_stderr=True, log_stderr_level='trace', stream_stdout=False, stream_stderr=False) sent_passwd = 0 ret_stdout = '' ret_stderr = '' try: while term.has_unread_data: (stdout, stderr) = term.recv() if stdout: ret_stdout += stdout if stderr: ret_stderr += stderr if (stdout and SSH_PASSWORD_PROMPT_RE.search(stdout)): if (not self.passwd): return ('', 'Permission denied, no authentication information', 254) if (sent_passwd < passwd_retries): term.sendline(self.passwd) sent_passwd += 1 continue else: return ('', 'Password authentication failed', 254) elif (stdout and KEY_VALID_RE.search(stdout)): if key_accept: term.sendline('yes') continue else: term.sendline('no') ret_stdout = 'The host key needs to be accepted, to auto accept run salt-ssh with the -i flag:\n{0}'.format(stdout) return (ret_stdout, '', 254) elif (stdout and stdout.endswith('_||ext_mods||_')): mods_raw = (json.dumps(self.mods, separators=(',', ':')) + '|_E|0|') term.sendline(mods_raw) time.sleep(0.01) return (ret_stdout, ret_stderr, term.exitstatus) finally: term.close(terminate=True, kill=True)
Execute a shell command via VT. This is blocking and assumes that ssh is being run
salt/client/ssh/shell.py
_run_cmd
belvedere-trading/salt
2
python
def _run_cmd(self, cmd, key_accept=False, passwd_retries=3): '\n Execute a shell command via VT. This is blocking and assumes that ssh\n is being run\n ' term = salt.utils.vt.Terminal(cmd, shell=True, log_stdout=True, log_stdout_level='trace', log_stderr=True, log_stderr_level='trace', stream_stdout=False, stream_stderr=False) sent_passwd = 0 ret_stdout = ret_stderr = try: while term.has_unread_data: (stdout, stderr) = term.recv() if stdout: ret_stdout += stdout if stderr: ret_stderr += stderr if (stdout and SSH_PASSWORD_PROMPT_RE.search(stdout)): if (not self.passwd): return (, 'Permission denied, no authentication information', 254) if (sent_passwd < passwd_retries): term.sendline(self.passwd) sent_passwd += 1 continue else: return (, 'Password authentication failed', 254) elif (stdout and KEY_VALID_RE.search(stdout)): if key_accept: term.sendline('yes') continue else: term.sendline('no') ret_stdout = 'The host key needs to be accepted, to auto accept run salt-ssh with the -i flag:\n{0}'.format(stdout) return (ret_stdout, , 254) elif (stdout and stdout.endswith('_||ext_mods||_')): mods_raw = (json.dumps(self.mods, separators=(',', ':')) + '|_E|0|') term.sendline(mods_raw) time.sleep(0.01) return (ret_stdout, ret_stderr, term.exitstatus) finally: term.close(terminate=True, kill=True)
def _run_cmd(self, cmd, key_accept=False, passwd_retries=3): '\n Execute a shell command via VT. This is blocking and assumes that ssh\n is being run\n ' term = salt.utils.vt.Terminal(cmd, shell=True, log_stdout=True, log_stdout_level='trace', log_stderr=True, log_stderr_level='trace', stream_stdout=False, stream_stderr=False) sent_passwd = 0 ret_stdout = ret_stderr = try: while term.has_unread_data: (stdout, stderr) = term.recv() if stdout: ret_stdout += stdout if stderr: ret_stderr += stderr if (stdout and SSH_PASSWORD_PROMPT_RE.search(stdout)): if (not self.passwd): return (, 'Permission denied, no authentication information', 254) if (sent_passwd < passwd_retries): term.sendline(self.passwd) sent_passwd += 1 continue else: return (, 'Password authentication failed', 254) elif (stdout and KEY_VALID_RE.search(stdout)): if key_accept: term.sendline('yes') continue else: term.sendline('no') ret_stdout = 'The host key needs to be accepted, to auto accept run salt-ssh with the -i flag:\n{0}'.format(stdout) return (ret_stdout, , 254) elif (stdout and stdout.endswith('_||ext_mods||_')): mods_raw = (json.dumps(self.mods, separators=(',', ':')) + '|_E|0|') term.sendline(mods_raw) time.sleep(0.01) return (ret_stdout, ret_stderr, term.exitstatus) finally: term.close(terminate=True, kill=True)<|docstring|>Execute a shell command via VT. This is blocking and assumes that ssh is being run<|endoftext|>
a5c669e2eefb4e41ce9346dacf633ef0e61c8026e683d8f385733544a8e4e565
def __init__(self, name=None, latex_label=None, unit=None, minimum=(- np.inf), maximum=np.inf, check_range_nonzero=True, boundary=None): " Implements a Prior object\n\n Parameters\n ==========\n name: str, optional\n Name associated with prior.\n latex_label: str, optional\n Latex label associated with prior, used for plotting.\n unit: str, optional\n If given, a Latex string describing the units of the parameter.\n minimum: float, optional\n Minimum of the domain, default=-np.inf\n maximum: float, optional\n Maximum of the domain, default=np.inf\n check_range_nonzero: boolean, optional\n If True, checks that the prior range is non-zero\n boundary: str, optional\n The boundary condition of the prior, can be 'periodic', 'reflective'\n Currently implemented in cpnest, dynesty and pymultinest.\n " if (check_range_nonzero and (maximum <= minimum)): raise ValueError('maximum {} <= minimum {} for {} prior on {}'.format(maximum, minimum, type(self).__name__, name)) self.name = name self.latex_label = latex_label self.unit = unit self.minimum = minimum self.maximum = maximum self.check_range_nonzero = check_range_nonzero self.least_recently_sampled = None self.boundary = boundary self._is_fixed = False
Implements a Prior object Parameters ========== name: str, optional Name associated with prior. latex_label: str, optional Latex label associated with prior, used for plotting. unit: str, optional If given, a Latex string describing the units of the parameter. minimum: float, optional Minimum of the domain, default=-np.inf maximum: float, optional Maximum of the domain, default=np.inf check_range_nonzero: boolean, optional If True, checks that the prior range is non-zero boundary: str, optional The boundary condition of the prior, can be 'periodic', 'reflective' Currently implemented in cpnest, dynesty and pymultinest.
bilby/core/prior/base.py
__init__
LBJ-Wade/bilby
31
python
def __init__(self, name=None, latex_label=None, unit=None, minimum=(- np.inf), maximum=np.inf, check_range_nonzero=True, boundary=None): " Implements a Prior object\n\n Parameters\n ==========\n name: str, optional\n Name associated with prior.\n latex_label: str, optional\n Latex label associated with prior, used for plotting.\n unit: str, optional\n If given, a Latex string describing the units of the parameter.\n minimum: float, optional\n Minimum of the domain, default=-np.inf\n maximum: float, optional\n Maximum of the domain, default=np.inf\n check_range_nonzero: boolean, optional\n If True, checks that the prior range is non-zero\n boundary: str, optional\n The boundary condition of the prior, can be 'periodic', 'reflective'\n Currently implemented in cpnest, dynesty and pymultinest.\n " if (check_range_nonzero and (maximum <= minimum)): raise ValueError('maximum {} <= minimum {} for {} prior on {}'.format(maximum, minimum, type(self).__name__, name)) self.name = name self.latex_label = latex_label self.unit = unit self.minimum = minimum self.maximum = maximum self.check_range_nonzero = check_range_nonzero self.least_recently_sampled = None self.boundary = boundary self._is_fixed = False
def __init__(self, name=None, latex_label=None, unit=None, minimum=(- np.inf), maximum=np.inf, check_range_nonzero=True, boundary=None): " Implements a Prior object\n\n Parameters\n ==========\n name: str, optional\n Name associated with prior.\n latex_label: str, optional\n Latex label associated with prior, used for plotting.\n unit: str, optional\n If given, a Latex string describing the units of the parameter.\n minimum: float, optional\n Minimum of the domain, default=-np.inf\n maximum: float, optional\n Maximum of the domain, default=np.inf\n check_range_nonzero: boolean, optional\n If True, checks that the prior range is non-zero\n boundary: str, optional\n The boundary condition of the prior, can be 'periodic', 'reflective'\n Currently implemented in cpnest, dynesty and pymultinest.\n " if (check_range_nonzero and (maximum <= minimum)): raise ValueError('maximum {} <= minimum {} for {} prior on {}'.format(maximum, minimum, type(self).__name__, name)) self.name = name self.latex_label = latex_label self.unit = unit self.minimum = minimum self.maximum = maximum self.check_range_nonzero = check_range_nonzero self.least_recently_sampled = None self.boundary = boundary self._is_fixed = False<|docstring|>Implements a Prior object Parameters ========== name: str, optional Name associated with prior. latex_label: str, optional Latex label associated with prior, used for plotting. unit: str, optional If given, a Latex string describing the units of the parameter. minimum: float, optional Minimum of the domain, default=-np.inf maximum: float, optional Maximum of the domain, default=np.inf check_range_nonzero: boolean, optional If True, checks that the prior range is non-zero boundary: str, optional The boundary condition of the prior, can be 'periodic', 'reflective' Currently implemented in cpnest, dynesty and pymultinest.<|endoftext|>
9746917deea2f6b23acfa9bb18ce7cd453acfe1c20753e2ac1749a97326b61d3
def __call__(self): 'Overrides the __call__ special method. Calls the sample method.\n\n Returns\n =======\n float: The return value of the sample method.\n ' return self.sample()
Overrides the __call__ special method. Calls the sample method. Returns ======= float: The return value of the sample method.
bilby/core/prior/base.py
__call__
LBJ-Wade/bilby
31
python
def __call__(self): 'Overrides the __call__ special method. Calls the sample method.\n\n Returns\n =======\n float: The return value of the sample method.\n ' return self.sample()
def __call__(self): 'Overrides the __call__ special method. Calls the sample method.\n\n Returns\n =======\n float: The return value of the sample method.\n ' return self.sample()<|docstring|>Overrides the __call__ special method. Calls the sample method. Returns ======= float: The return value of the sample method.<|endoftext|>
3f5f25c82fd445496ecbfbb0d90456ce80142150fc81114541dd2cbf0cbc7d4a
def __eq__(self, other): "\n Test equality of two prior objects.\n\n Returns true iff:\n\n - The class of the two priors are the same\n - Both priors have the same keys in the __dict__ attribute\n - The instantiation arguments match\n\n We don't check that all entries the the __dict__ attribute\n are equal as some attributes are variable for conditional\n priors.\n\n Parameters\n ==========\n other: Prior\n The prior to compare with\n\n Returns\n =======\n bool\n Whether the priors are equivalent\n\n Notes\n =====\n A special case is made for :code `scipy.stats.beta`: instances.\n It may be possible to remove this as we now only check instantiation\n arguments.\n\n " if (self.__class__ != other.__class__): return False if (sorted(self.__dict__.keys()) != sorted(other.__dict__.keys())): return False this_dict = self.get_instantiation_dict() other_dict = other.get_instantiation_dict() for key in this_dict: if (key == 'least_recently_sampled'): continue if isinstance(this_dict[key], np.ndarray): if (not np.array_equal(this_dict[key], other_dict[key])): return False elif isinstance(this_dict[key], type(scipy.stats.beta(1.0, 1.0))): continue elif (not (this_dict[key] == other_dict[key])): return False return True
Test equality of two prior objects. Returns true iff: - The class of the two priors are the same - Both priors have the same keys in the __dict__ attribute - The instantiation arguments match We don't check that all entries the the __dict__ attribute are equal as some attributes are variable for conditional priors. Parameters ========== other: Prior The prior to compare with Returns ======= bool Whether the priors are equivalent Notes ===== A special case is made for :code `scipy.stats.beta`: instances. It may be possible to remove this as we now only check instantiation arguments.
bilby/core/prior/base.py
__eq__
LBJ-Wade/bilby
31
python
def __eq__(self, other): "\n Test equality of two prior objects.\n\n Returns true iff:\n\n - The class of the two priors are the same\n - Both priors have the same keys in the __dict__ attribute\n - The instantiation arguments match\n\n We don't check that all entries the the __dict__ attribute\n are equal as some attributes are variable for conditional\n priors.\n\n Parameters\n ==========\n other: Prior\n The prior to compare with\n\n Returns\n =======\n bool\n Whether the priors are equivalent\n\n Notes\n =====\n A special case is made for :code `scipy.stats.beta`: instances.\n It may be possible to remove this as we now only check instantiation\n arguments.\n\n " if (self.__class__ != other.__class__): return False if (sorted(self.__dict__.keys()) != sorted(other.__dict__.keys())): return False this_dict = self.get_instantiation_dict() other_dict = other.get_instantiation_dict() for key in this_dict: if (key == 'least_recently_sampled'): continue if isinstance(this_dict[key], np.ndarray): if (not np.array_equal(this_dict[key], other_dict[key])): return False elif isinstance(this_dict[key], type(scipy.stats.beta(1.0, 1.0))): continue elif (not (this_dict[key] == other_dict[key])): return False return True
def __eq__(self, other): "\n Test equality of two prior objects.\n\n Returns true iff:\n\n - The class of the two priors are the same\n - Both priors have the same keys in the __dict__ attribute\n - The instantiation arguments match\n\n We don't check that all entries the the __dict__ attribute\n are equal as some attributes are variable for conditional\n priors.\n\n Parameters\n ==========\n other: Prior\n The prior to compare with\n\n Returns\n =======\n bool\n Whether the priors are equivalent\n\n Notes\n =====\n A special case is made for :code `scipy.stats.beta`: instances.\n It may be possible to remove this as we now only check instantiation\n arguments.\n\n " if (self.__class__ != other.__class__): return False if (sorted(self.__dict__.keys()) != sorted(other.__dict__.keys())): return False this_dict = self.get_instantiation_dict() other_dict = other.get_instantiation_dict() for key in this_dict: if (key == 'least_recently_sampled'): continue if isinstance(this_dict[key], np.ndarray): if (not np.array_equal(this_dict[key], other_dict[key])): return False elif isinstance(this_dict[key], type(scipy.stats.beta(1.0, 1.0))): continue elif (not (this_dict[key] == other_dict[key])): return False return True<|docstring|>Test equality of two prior objects. Returns true iff: - The class of the two priors are the same - Both priors have the same keys in the __dict__ attribute - The instantiation arguments match We don't check that all entries the the __dict__ attribute are equal as some attributes are variable for conditional priors. Parameters ========== other: Prior The prior to compare with Returns ======= bool Whether the priors are equivalent Notes ===== A special case is made for :code `scipy.stats.beta`: instances. It may be possible to remove this as we now only check instantiation arguments.<|endoftext|>
abf2adeb6946aeda249cfc6cffb78dc3d07a8eb80e09a1d279d2f54337c9ece4
def sample(self, size=None): 'Draw a sample from the prior\n\n Parameters\n ==========\n size: int or tuple of ints, optional\n See numpy.random.uniform docs\n\n Returns\n =======\n float: A random number between 0 and 1, rescaled to match the distribution of this Prior\n\n ' self.least_recently_sampled = self.rescale(np.random.uniform(0, 1, size)) return self.least_recently_sampled
Draw a sample from the prior Parameters ========== size: int or tuple of ints, optional See numpy.random.uniform docs Returns ======= float: A random number between 0 and 1, rescaled to match the distribution of this Prior
bilby/core/prior/base.py
sample
LBJ-Wade/bilby
31
python
def sample(self, size=None): 'Draw a sample from the prior\n\n Parameters\n ==========\n size: int or tuple of ints, optional\n See numpy.random.uniform docs\n\n Returns\n =======\n float: A random number between 0 and 1, rescaled to match the distribution of this Prior\n\n ' self.least_recently_sampled = self.rescale(np.random.uniform(0, 1, size)) return self.least_recently_sampled
def sample(self, size=None): 'Draw a sample from the prior\n\n Parameters\n ==========\n size: int or tuple of ints, optional\n See numpy.random.uniform docs\n\n Returns\n =======\n float: A random number between 0 and 1, rescaled to match the distribution of this Prior\n\n ' self.least_recently_sampled = self.rescale(np.random.uniform(0, 1, size)) return self.least_recently_sampled<|docstring|>Draw a sample from the prior Parameters ========== size: int or tuple of ints, optional See numpy.random.uniform docs Returns ======= float: A random number between 0 and 1, rescaled to match the distribution of this Prior<|endoftext|>
9e63c978fa291144f66a9a117a6feac0521697d89ff54bbb76144768dbcfec7d
def rescale(self, val): "\n 'Rescale' a sample from the unit line element to the prior.\n\n This should be overwritten by each subclass.\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n A random number between 0 and 1\n\n Returns\n =======\n None\n\n " return None
'Rescale' a sample from the unit line element to the prior. This should be overwritten by each subclass. Parameters ========== val: Union[float, int, array_like] A random number between 0 and 1 Returns ======= None
bilby/core/prior/base.py
rescale
LBJ-Wade/bilby
31
python
def rescale(self, val): "\n 'Rescale' a sample from the unit line element to the prior.\n\n This should be overwritten by each subclass.\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n A random number between 0 and 1\n\n Returns\n =======\n None\n\n " return None
def rescale(self, val): "\n 'Rescale' a sample from the unit line element to the prior.\n\n This should be overwritten by each subclass.\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n A random number between 0 and 1\n\n Returns\n =======\n None\n\n " return None<|docstring|>'Rescale' a sample from the unit line element to the prior. This should be overwritten by each subclass. Parameters ========== val: Union[float, int, array_like] A random number between 0 and 1 Returns ======= None<|endoftext|>
395451eeee0d9bf95e2ba87410be47817233bf83f5d54766c0d074b886bd878c
def prob(self, val): 'Return the prior probability of val, this should be overwritten\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' return np.nan
Return the prior probability of val, this should be overwritten Parameters ========== val: Union[float, int, array_like] Returns ======= np.nan
bilby/core/prior/base.py
prob
LBJ-Wade/bilby
31
python
def prob(self, val): 'Return the prior probability of val, this should be overwritten\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' return np.nan
def prob(self, val): 'Return the prior probability of val, this should be overwritten\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' return np.nan<|docstring|>Return the prior probability of val, this should be overwritten Parameters ========== val: Union[float, int, array_like] Returns ======= np.nan<|endoftext|>
a8186cf2430379977387b2d14ead6410735199a623c84642c9f685196462d62f
def cdf(self, val): ' Generic method to calculate CDF, can be overwritten in subclass ' from scipy.integrate import cumtrapz if np.any(np.isinf([self.minimum, self.maximum])): raise ValueError('Unable to use the generic CDF calculation for priors withinfinite support') x = np.linspace(self.minimum, self.maximum, 1000) pdf = self.prob(x) cdf = cumtrapz(pdf, x, initial=0) interp = interp1d(x, cdf, assume_sorted=True, bounds_error=False, fill_value=(0, 1)) return interp(val)
Generic method to calculate CDF, can be overwritten in subclass
bilby/core/prior/base.py
cdf
LBJ-Wade/bilby
31
python
def cdf(self, val): ' ' from scipy.integrate import cumtrapz if np.any(np.isinf([self.minimum, self.maximum])): raise ValueError('Unable to use the generic CDF calculation for priors withinfinite support') x = np.linspace(self.minimum, self.maximum, 1000) pdf = self.prob(x) cdf = cumtrapz(pdf, x, initial=0) interp = interp1d(x, cdf, assume_sorted=True, bounds_error=False, fill_value=(0, 1)) return interp(val)
def cdf(self, val): ' ' from scipy.integrate import cumtrapz if np.any(np.isinf([self.minimum, self.maximum])): raise ValueError('Unable to use the generic CDF calculation for priors withinfinite support') x = np.linspace(self.minimum, self.maximum, 1000) pdf = self.prob(x) cdf = cumtrapz(pdf, x, initial=0) interp = interp1d(x, cdf, assume_sorted=True, bounds_error=False, fill_value=(0, 1)) return interp(val)<|docstring|>Generic method to calculate CDF, can be overwritten in subclass<|endoftext|>
8ec3d7474cf833b8a6b131ea5f5ec0ff1aaf72b239888229cbb3d83434d1edcf
def ln_prob(self, val): 'Return the prior ln probability of val, this should be overwritten\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' with np.errstate(divide='ignore'): return np.log(self.prob(val))
Return the prior ln probability of val, this should be overwritten Parameters ========== val: Union[float, int, array_like] Returns ======= np.nan
bilby/core/prior/base.py
ln_prob
LBJ-Wade/bilby
31
python
def ln_prob(self, val): 'Return the prior ln probability of val, this should be overwritten\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' with np.errstate(divide='ignore'): return np.log(self.prob(val))
def ln_prob(self, val): 'Return the prior ln probability of val, this should be overwritten\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' with np.errstate(divide='ignore'): return np.log(self.prob(val))<|docstring|>Return the prior ln probability of val, this should be overwritten Parameters ========== val: Union[float, int, array_like] Returns ======= np.nan<|endoftext|>
235ec6f419a1586456777c83bc195c275ba0e942b91378415e6a752be4c73266
def is_in_prior_range(self, val): 'Returns True if val is in the prior boundaries, zero otherwise\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' return ((val >= self.minimum) & (val <= self.maximum))
Returns True if val is in the prior boundaries, zero otherwise Parameters ========== val: Union[float, int, array_like] Returns ======= np.nan
bilby/core/prior/base.py
is_in_prior_range
LBJ-Wade/bilby
31
python
def is_in_prior_range(self, val): 'Returns True if val is in the prior boundaries, zero otherwise\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' return ((val >= self.minimum) & (val <= self.maximum))
def is_in_prior_range(self, val): 'Returns True if val is in the prior boundaries, zero otherwise\n\n Parameters\n ==========\n val: Union[float, int, array_like]\n\n Returns\n =======\n np.nan\n\n ' return ((val >= self.minimum) & (val <= self.maximum))<|docstring|>Returns True if val is in the prior boundaries, zero otherwise Parameters ========== val: Union[float, int, array_like] Returns ======= np.nan<|endoftext|>
83e5918a13205d5cfe3723e0e07d51678fd1d5e50acc2cdd811a707574d8d858
def __repr__(self): 'Overrides the special method __repr__.\n\n Returns a representation of this instance that resembles how it is instantiated.\n Works correctly for all child classes\n\n Returns\n =======\n str: A string representation of this instance\n\n ' prior_name = self.__class__.__name__ instantiation_dict = self.get_instantiation_dict() args = ', '.join(['{}={}'.format(key, repr(instantiation_dict[key])) for key in instantiation_dict]) return '{}({})'.format(prior_name, args)
Overrides the special method __repr__. Returns a representation of this instance that resembles how it is instantiated. Works correctly for all child classes Returns ======= str: A string representation of this instance
bilby/core/prior/base.py
__repr__
LBJ-Wade/bilby
31
python
def __repr__(self): 'Overrides the special method __repr__.\n\n Returns a representation of this instance that resembles how it is instantiated.\n Works correctly for all child classes\n\n Returns\n =======\n str: A string representation of this instance\n\n ' prior_name = self.__class__.__name__ instantiation_dict = self.get_instantiation_dict() args = ', '.join(['{}={}'.format(key, repr(instantiation_dict[key])) for key in instantiation_dict]) return '{}({})'.format(prior_name, args)
def __repr__(self): 'Overrides the special method __repr__.\n\n Returns a representation of this instance that resembles how it is instantiated.\n Works correctly for all child classes\n\n Returns\n =======\n str: A string representation of this instance\n\n ' prior_name = self.__class__.__name__ instantiation_dict = self.get_instantiation_dict() args = ', '.join(['{}={}'.format(key, repr(instantiation_dict[key])) for key in instantiation_dict]) return '{}({})'.format(prior_name, args)<|docstring|>Overrides the special method __repr__. Returns a representation of this instance that resembles how it is instantiated. Works correctly for all child classes Returns ======= str: A string representation of this instance<|endoftext|>
b66a85cf9a33f74f9bf4f432595a88faf2ffdf0a9e8d772a3050c293c89f5051
@property def _repr_dict(self): '\n Get a dictionary containing the arguments needed to reproduce this object.\n ' property_names = {p for p in dir(self.__class__) if isinstance(getattr(self.__class__, p), property)} subclass_args = infer_args_from_method(self.__init__) dict_with_properties = self.__dict__.copy() for key in property_names.intersection(subclass_args): dict_with_properties[key] = getattr(self, key) return {key: dict_with_properties[key] for key in subclass_args}
Get a dictionary containing the arguments needed to reproduce this object.
bilby/core/prior/base.py
_repr_dict
LBJ-Wade/bilby
31
python
@property def _repr_dict(self): '\n \n ' property_names = {p for p in dir(self.__class__) if isinstance(getattr(self.__class__, p), property)} subclass_args = infer_args_from_method(self.__init__) dict_with_properties = self.__dict__.copy() for key in property_names.intersection(subclass_args): dict_with_properties[key] = getattr(self, key) return {key: dict_with_properties[key] for key in subclass_args}
@property def _repr_dict(self): '\n \n ' property_names = {p for p in dir(self.__class__) if isinstance(getattr(self.__class__, p), property)} subclass_args = infer_args_from_method(self.__init__) dict_with_properties = self.__dict__.copy() for key in property_names.intersection(subclass_args): dict_with_properties[key] = getattr(self, key) return {key: dict_with_properties[key] for key in subclass_args}<|docstring|>Get a dictionary containing the arguments needed to reproduce this object.<|endoftext|>
24f0ad4435d6f825ea1d39a6ca141934527f3c4c49f80998b0f653307aaa23a7
@property def is_fixed(self): "\n Returns True if the prior is fixed and should not be used in the sampler. Does this by checking if this instance\n is an instance of DeltaFunction.\n\n\n Returns\n =======\n bool: Whether it's fixed or not!\n\n " return self._is_fixed
Returns True if the prior is fixed and should not be used in the sampler. Does this by checking if this instance is an instance of DeltaFunction. Returns ======= bool: Whether it's fixed or not!
bilby/core/prior/base.py
is_fixed
LBJ-Wade/bilby
31
python
@property def is_fixed(self): "\n Returns True if the prior is fixed and should not be used in the sampler. Does this by checking if this instance\n is an instance of DeltaFunction.\n\n\n Returns\n =======\n bool: Whether it's fixed or not!\n\n " return self._is_fixed
@property def is_fixed(self): "\n Returns True if the prior is fixed and should not be used in the sampler. Does this by checking if this instance\n is an instance of DeltaFunction.\n\n\n Returns\n =======\n bool: Whether it's fixed or not!\n\n " return self._is_fixed<|docstring|>Returns True if the prior is fixed and should not be used in the sampler. Does this by checking if this instance is an instance of DeltaFunction. Returns ======= bool: Whether it's fixed or not!<|endoftext|>
786244cdce76abc7a9edbba668ffb589517d657cad74eed8549ad0691f83d6f2
@property def latex_label(self): 'Latex label that can be used for plots.\n\n Draws from a set of default labels if no label is given\n\n Returns\n =======\n str: A latex representation for this prior\n\n ' return self.__latex_label
Latex label that can be used for plots. Draws from a set of default labels if no label is given Returns ======= str: A latex representation for this prior
bilby/core/prior/base.py
latex_label
LBJ-Wade/bilby
31
python
@property def latex_label(self): 'Latex label that can be used for plots.\n\n Draws from a set of default labels if no label is given\n\n Returns\n =======\n str: A latex representation for this prior\n\n ' return self.__latex_label
@property def latex_label(self): 'Latex label that can be used for plots.\n\n Draws from a set of default labels if no label is given\n\n Returns\n =======\n str: A latex representation for this prior\n\n ' return self.__latex_label<|docstring|>Latex label that can be used for plots. Draws from a set of default labels if no label is given Returns ======= str: A latex representation for this prior<|endoftext|>
0d34772aee87753a4377566e4f4a44ec4c6bec9d271adbd0ba12fafca9c9fb22
@property def latex_label_with_unit(self): ' If a unit is specified, returns a string of the latex label and unit ' if (self.unit is not None): return '{} [{}]'.format(self.latex_label, self.unit) else: return self.latex_label
If a unit is specified, returns a string of the latex label and unit
bilby/core/prior/base.py
latex_label_with_unit
LBJ-Wade/bilby
31
python
@property def latex_label_with_unit(self): ' ' if (self.unit is not None): return '{} [{}]'.format(self.latex_label, self.unit) else: return self.latex_label
@property def latex_label_with_unit(self): ' ' if (self.unit is not None): return '{} [{}]'.format(self.latex_label, self.unit) else: return self.latex_label<|docstring|>If a unit is specified, returns a string of the latex label and unit<|endoftext|>
c95af5a481df40b6830375d39df9dd8ad33a2a4c11c97761e84b2b6657e84541
@classmethod def from_repr(cls, string): "Generate the prior from it's __repr__" return cls._from_repr(string)
Generate the prior from it's __repr__
bilby/core/prior/base.py
from_repr
LBJ-Wade/bilby
31
python
@classmethod def from_repr(cls, string): return cls._from_repr(string)
@classmethod def from_repr(cls, string): return cls._from_repr(string)<|docstring|>Generate the prior from it's __repr__<|endoftext|>
d4ae3d789c96c0a716b6b7835b153acd4a33d12ce48ab1b1e4bd22ba557885a0
@classmethod def _parse_argument_string(cls, val): "\n Parse a string into the appropriate type for prior reading.\n\n Four tests are applied in the following order:\n\n - If the string is 'None':\n `None` is returned.\n - Else If the string is a raw string, e.g., r'foo':\n A stripped version of the string is returned, e.g., foo.\n - Else If the string contains ', e.g., 'foo':\n A stripped version of the string is returned, e.g., foo.\n - Else If the string contains an open parenthesis, (:\n The string is interpreted as a call to instantiate another prior\n class, Bilby will attempt to recursively construct that prior,\n e.g., Uniform(minimum=0, maximum=1), my.custom.PriorClass(**kwargs).\n - Else:\n Try to evaluate the string using `eval`. Only built-in functions\n and numpy methods can be used, e.g., np.pi / 2, 1.57.\n\n\n Parameters\n ==========\n val: str\n The string version of the argument\n\n Returns\n =======\n val: object\n The parsed version of the argument.\n\n Raises\n ======\n TypeError:\n If val cannot be parsed as described above.\n " if (val == 'None'): val = None elif (re.sub("\\'.*\\'", '', val) in ['r', 'u']): val = val[2:(- 1)] elif ("'" in val): val = val.strip("'") elif ('(' in val): other_cls = val.split('(')[0] vals = '('.join(val.split('(')[1:])[:(- 1)] if ('.' in other_cls): module = '.'.join(other_cls.split('.')[:(- 1)]) other_cls = other_cls.split('.')[(- 1)] else: module = __name__.replace(('.' + os.path.basename(__file__).replace('.py', '')), '') other_cls = getattr(import_module(module), other_cls) val = other_cls.from_repr(vals) else: try: val = eval(val, dict(), dict(np=np, inf=np.inf, pi=np.pi)) except NameError: raise TypeError('Cannot evaluate prior, failed to parse argument {}'.format(val)) return val
Parse a string into the appropriate type for prior reading. Four tests are applied in the following order: - If the string is 'None': `None` is returned. - Else If the string is a raw string, e.g., r'foo': A stripped version of the string is returned, e.g., foo. - Else If the string contains ', e.g., 'foo': A stripped version of the string is returned, e.g., foo. - Else If the string contains an open parenthesis, (: The string is interpreted as a call to instantiate another prior class, Bilby will attempt to recursively construct that prior, e.g., Uniform(minimum=0, maximum=1), my.custom.PriorClass(**kwargs). - Else: Try to evaluate the string using `eval`. Only built-in functions and numpy methods can be used, e.g., np.pi / 2, 1.57. Parameters ========== val: str The string version of the argument Returns ======= val: object The parsed version of the argument. Raises ====== TypeError: If val cannot be parsed as described above.
bilby/core/prior/base.py
_parse_argument_string
LBJ-Wade/bilby
31
python
@classmethod def _parse_argument_string(cls, val): "\n Parse a string into the appropriate type for prior reading.\n\n Four tests are applied in the following order:\n\n - If the string is 'None':\n `None` is returned.\n - Else If the string is a raw string, e.g., r'foo':\n A stripped version of the string is returned, e.g., foo.\n - Else If the string contains ', e.g., 'foo':\n A stripped version of the string is returned, e.g., foo.\n - Else If the string contains an open parenthesis, (:\n The string is interpreted as a call to instantiate another prior\n class, Bilby will attempt to recursively construct that prior,\n e.g., Uniform(minimum=0, maximum=1), my.custom.PriorClass(**kwargs).\n - Else:\n Try to evaluate the string using `eval`. Only built-in functions\n and numpy methods can be used, e.g., np.pi / 2, 1.57.\n\n\n Parameters\n ==========\n val: str\n The string version of the argument\n\n Returns\n =======\n val: object\n The parsed version of the argument.\n\n Raises\n ======\n TypeError:\n If val cannot be parsed as described above.\n " if (val == 'None'): val = None elif (re.sub("\\'.*\\'", , val) in ['r', 'u']): val = val[2:(- 1)] elif ("'" in val): val = val.strip("'") elif ('(' in val): other_cls = val.split('(')[0] vals = '('.join(val.split('(')[1:])[:(- 1)] if ('.' in other_cls): module = '.'.join(other_cls.split('.')[:(- 1)]) other_cls = other_cls.split('.')[(- 1)] else: module = __name__.replace(('.' + os.path.basename(__file__).replace('.py', )), ) other_cls = getattr(import_module(module), other_cls) val = other_cls.from_repr(vals) else: try: val = eval(val, dict(), dict(np=np, inf=np.inf, pi=np.pi)) except NameError: raise TypeError('Cannot evaluate prior, failed to parse argument {}'.format(val)) return val
@classmethod def _parse_argument_string(cls, val): "\n Parse a string into the appropriate type for prior reading.\n\n Four tests are applied in the following order:\n\n - If the string is 'None':\n `None` is returned.\n - Else If the string is a raw string, e.g., r'foo':\n A stripped version of the string is returned, e.g., foo.\n - Else If the string contains ', e.g., 'foo':\n A stripped version of the string is returned, e.g., foo.\n - Else If the string contains an open parenthesis, (:\n The string is interpreted as a call to instantiate another prior\n class, Bilby will attempt to recursively construct that prior,\n e.g., Uniform(minimum=0, maximum=1), my.custom.PriorClass(**kwargs).\n - Else:\n Try to evaluate the string using `eval`. Only built-in functions\n and numpy methods can be used, e.g., np.pi / 2, 1.57.\n\n\n Parameters\n ==========\n val: str\n The string version of the argument\n\n Returns\n =======\n val: object\n The parsed version of the argument.\n\n Raises\n ======\n TypeError:\n If val cannot be parsed as described above.\n " if (val == 'None'): val = None elif (re.sub("\\'.*\\'", , val) in ['r', 'u']): val = val[2:(- 1)] elif ("'" in val): val = val.strip("'") elif ('(' in val): other_cls = val.split('(')[0] vals = '('.join(val.split('(')[1:])[:(- 1)] if ('.' in other_cls): module = '.'.join(other_cls.split('.')[:(- 1)]) other_cls = other_cls.split('.')[(- 1)] else: module = __name__.replace(('.' + os.path.basename(__file__).replace('.py', )), ) other_cls = getattr(import_module(module), other_cls) val = other_cls.from_repr(vals) else: try: val = eval(val, dict(), dict(np=np, inf=np.inf, pi=np.pi)) except NameError: raise TypeError('Cannot evaluate prior, failed to parse argument {}'.format(val)) return val<|docstring|>Parse a string into the appropriate type for prior reading. Four tests are applied in the following order: - If the string is 'None': `None` is returned. - Else If the string is a raw string, e.g., r'foo': A stripped version of the string is returned, e.g., foo. - Else If the string contains ', e.g., 'foo': A stripped version of the string is returned, e.g., foo. - Else If the string contains an open parenthesis, (: The string is interpreted as a call to instantiate another prior class, Bilby will attempt to recursively construct that prior, e.g., Uniform(minimum=0, maximum=1), my.custom.PriorClass(**kwargs). - Else: Try to evaluate the string using `eval`. Only built-in functions and numpy methods can be used, e.g., np.pi / 2, 1.57. Parameters ========== val: str The string version of the argument Returns ======= val: object The parsed version of the argument. Raises ====== TypeError: If val cannot be parsed as described above.<|endoftext|>
a0c762bc7ff486f44bc2f5fb6c218edc088418ca1eb253d56b0b57cd707db7cc
@asyncio.coroutine def render(app): '\n The core rendering loop.\n\n Do not schedule this with ``app.on``; it is scheduled automatically when\n you start the application.\n ' if app.root.dirty: app.log('Rendering') app.stdscr.refresh() app.recalculate_windows() for (box, win, pad, textbox) in app.windows: win.refresh() (x, y) = box.upper_left (dx, dy) = box.lower_right pad.refresh(box._text_offset, 0, (y + 1), (x + 1), (dy - 2), (dx - 2)) app.root.dirty = False app.schedule(render)
The core rendering loop. Do not schedule this with ``app.on``; it is scheduled automatically when you start the application.
hexes/behaviors.py
render
wlonk/hexes
3
python
@asyncio.coroutine def render(app): '\n The core rendering loop.\n\n Do not schedule this with ``app.on``; it is scheduled automatically when\n you start the application.\n ' if app.root.dirty: app.log('Rendering') app.stdscr.refresh() app.recalculate_windows() for (box, win, pad, textbox) in app.windows: win.refresh() (x, y) = box.upper_left (dx, dy) = box.lower_right pad.refresh(box._text_offset, 0, (y + 1), (x + 1), (dy - 2), (dx - 2)) app.root.dirty = False app.schedule(render)
@asyncio.coroutine def render(app): '\n The core rendering loop.\n\n Do not schedule this with ``app.on``; it is scheduled automatically when\n you start the application.\n ' if app.root.dirty: app.log('Rendering') app.stdscr.refresh() app.recalculate_windows() for (box, win, pad, textbox) in app.windows: win.refresh() (x, y) = box.upper_left (dx, dy) = box.lower_right pad.refresh(box._text_offset, 0, (y + 1), (x + 1), (dy - 2), (dx - 2)) app.root.dirty = False app.schedule(render)<|docstring|>The core rendering loop. Do not schedule this with ``app.on``; it is scheduled automatically when you start the application.<|endoftext|>
bb161513e0a17fa49b1f5a9d08c44290ed62d18bf7404701e3ee2b1f8f33ea65
@asyncio.coroutine def quit(app): "\n Basic quitting behavior.\n\n Typically, you'll want to schedule this with:\n\n .. code-block:: python\n\n app.on('q', quit)\n\n or something similar.\n " app.loop.stop()
Basic quitting behavior. Typically, you'll want to schedule this with: .. code-block:: python app.on('q', quit) or something similar.
hexes/behaviors.py
quit
wlonk/hexes
3
python
@asyncio.coroutine def quit(app): "\n Basic quitting behavior.\n\n Typically, you'll want to schedule this with:\n\n .. code-block:: python\n\n app.on('q', quit)\n\n or something similar.\n " app.loop.stop()
@asyncio.coroutine def quit(app): "\n Basic quitting behavior.\n\n Typically, you'll want to schedule this with:\n\n .. code-block:: python\n\n app.on('q', quit)\n\n or something similar.\n " app.loop.stop()<|docstring|>Basic quitting behavior. Typically, you'll want to schedule this with: .. code-block:: python app.on('q', quit) or something similar.<|endoftext|>
152a26d5cd800ede5975196a45883c3bf99f495646da37d4d80a83f8ec71c2f7
def verun(cmd): 'Runs a command inside the virtual environment without\n invoking it\n\n Args:\n cmd(str): Command to be run in the virtual env\n Returns:\n None\n ' run('pew in {0} {1}'.format(package_name(), cmd))
Runs a command inside the virtual environment without invoking it Args: cmd(str): Command to be run in the virtual env Returns: None
tasks/env.py
verun
bharadwajyarlagadda/docMaker
13
python
def verun(cmd): 'Runs a command inside the virtual environment without\n invoking it\n\n Args:\n cmd(str): Command to be run in the virtual env\n Returns:\n None\n ' run('pew in {0} {1}'.format(package_name(), cmd))
def verun(cmd): 'Runs a command inside the virtual environment without\n invoking it\n\n Args:\n cmd(str): Command to be run in the virtual env\n Returns:\n None\n ' run('pew in {0} {1}'.format(package_name(), cmd))<|docstring|>Runs a command inside the virtual environment without invoking it Args: cmd(str): Command to be run in the virtual env Returns: None<|endoftext|>
a5fafcbd07709481a32dde585fe1fa8a4c2570acf81e5bb81bdff96d55fcccee
@task def new(): 'Creates a new virtual environment with the package name.\n ' run('pew new --dont-activate --python={0} {1}'.format(python_bin, package_name())) verun('pip install --upgrade wheel') verun('pip install --upgrade pip')
Creates a new virtual environment with the package name.
tasks/env.py
new
bharadwajyarlagadda/docMaker
13
python
@task def new(): '\n ' run('pew new --dont-activate --python={0} {1}'.format(python_bin, package_name())) verun('pip install --upgrade wheel') verun('pip install --upgrade pip')
@task def new(): '\n ' run('pew new --dont-activate --python={0} {1}'.format(python_bin, package_name())) verun('pip install --upgrade wheel') verun('pip install --upgrade pip')<|docstring|>Creates a new virtual environment with the package name.<|endoftext|>
c63e95fadb010d0e6c2dfe23e0e4a4bfe3575dc4633c965f22b87a3005a96f98
@task def remove(): 'Removes the virtual environment with the package name.\n ' run('pew rm {0}'.format(package_name()))
Removes the virtual environment with the package name.
tasks/env.py
remove
bharadwajyarlagadda/docMaker
13
python
@task def remove(): '\n ' run('pew rm {0}'.format(package_name()))
@task def remove(): '\n ' run('pew rm {0}'.format(package_name()))<|docstring|>Removes the virtual environment with the package name.<|endoftext|>
d5692d44c8d2c05da0d006c6b6d786c0f0ea53727c5b5186ae6ea2fef4684c30
@task def clean(): 'Cleans the directory. Removes .tox and eggs from the project folder\n ' clean_files()
Cleans the directory. Removes .tox and eggs from the project folder
tasks/env.py
clean
bharadwajyarlagadda/docMaker
13
python
@task def clean(): '\n ' clean_files()
@task def clean(): '\n ' clean_files()<|docstring|>Cleans the directory. Removes .tox and eggs from the project folder<|endoftext|>
848daa387f2c52706f950b7f6d2f71117c26f90541d2947a52534fa26ffa21b6
@task def install(): 'Installs all the dependencies in the virtual\n environment\n ' verun('pip install -r {0}'.format(requirements))
Installs all the dependencies in the virtual environment
tasks/env.py
install
bharadwajyarlagadda/docMaker
13
python
@task def install(): 'Installs all the dependencies in the virtual\n environment\n ' verun('pip install -r {0}'.format(requirements))
@task def install(): 'Installs all the dependencies in the virtual\n environment\n ' verun('pip install -r {0}'.format(requirements))<|docstring|>Installs all the dependencies in the virtual environment<|endoftext|>
f5bf2e6a700b830cbf6734200f72d45e72f10f2045b3a96681e19bd67b6a9a41
@task(pre=[clean, remove, new, install], default=True) def init(): 'Performs all the operations to create the virtual environment\n ' print('Installed everything under {0} virtual environment'.format(package_name()))
Performs all the operations to create the virtual environment
tasks/env.py
init
bharadwajyarlagadda/docMaker
13
python
@task(pre=[clean, remove, new, install], default=True) def init(): '\n ' print('Installed everything under {0} virtual environment'.format(package_name()))
@task(pre=[clean, remove, new, install], default=True) def init(): '\n ' print('Installed everything under {0} virtual environment'.format(package_name()))<|docstring|>Performs all the operations to create the virtual environment<|endoftext|>
033a6fae42cbd9c68137e17bbfb5aee2605b41eeabb00176fefe0ff48d7d422a
def start_up(self): 'Performs device specific initialization sequence.' if self.init_power(): if self.init_uart(): if self._break(): self._stop_logging() self._set_clock() self._set_sample_rate() self._start_logging() self.off() return True return False
Performs device specific initialization sequence.
firmware/dev_aml.py
start_up
andreacorbo/Buoy_Controller_v1
0
python
def start_up(self): if self.init_power(): if self.init_uart(): if self._break(): self._stop_logging() self._set_clock() self._set_sample_rate() self._start_logging() self.off() return True return False
def start_up(self): if self.init_power(): if self.init_uart(): if self._break(): self._stop_logging() self._set_clock() self._set_sample_rate() self._start_logging() self.off() return True return False<|docstring|>Performs device specific initialization sequence.<|endoftext|>
bf9d36f2c47fdf2a49c8907cd2c2df2469b83127f89023f8593687053c3a5a4c
def _timeout(self, start, timeout=None): 'Checks if a timeout occourred\n\n Params:\n start(int)\n Returns:\n True or False\n ' if (timeout is None): timeout = self.timeout if ((timeout > 0) and ((utime.time() - start) >= timeout)): return True return False
Checks if a timeout occourred Params: start(int) Returns: True or False
firmware/dev_aml.py
_timeout
andreacorbo/Buoy_Controller_v1
0
python
def _timeout(self, start, timeout=None): 'Checks if a timeout occourred\n\n Params:\n start(int)\n Returns:\n True or False\n ' if (timeout is None): timeout = self.timeout if ((timeout > 0) and ((utime.time() - start) >= timeout)): return True return False
def _timeout(self, start, timeout=None): 'Checks if a timeout occourred\n\n Params:\n start(int)\n Returns:\n True or False\n ' if (timeout is None): timeout = self.timeout if ((timeout > 0) and ((utime.time() - start) >= timeout)): return True return False<|docstring|>Checks if a timeout occourred Params: start(int) Returns: True or False<|endoftext|>
0f2a52efd2bb59b206454726ae75259e1644f318cd9f473eb96b67d9708709f7
def _get_reply(self, timeout=None): 'Returns replies from instrument.\n\n Returns:\n bytes or None\n ' start = utime.time() while (not self._timeout(start, timeout)): if self.uart.any(): return self.uart.read().split(b'\r\n')[1].decode('utf-8') return
Returns replies from instrument. Returns: bytes or None
firmware/dev_aml.py
_get_reply
andreacorbo/Buoy_Controller_v1
0
python
def _get_reply(self, timeout=None): 'Returns replies from instrument.\n\n Returns:\n bytes or None\n ' start = utime.time() while (not self._timeout(start, timeout)): if self.uart.any(): return self.uart.read().split(b'\r\n')[1].decode('utf-8') return
def _get_reply(self, timeout=None): 'Returns replies from instrument.\n\n Returns:\n bytes or None\n ' start = utime.time() while (not self._timeout(start, timeout)): if self.uart.any(): return self.uart.read().split(b'\r\n')[1].decode('utf-8') return<|docstring|>Returns replies from instrument. Returns: bytes or None<|endoftext|>
551aace878cda257d110ab1dfdbe558f6aa752cdbdc196ea691f5bc0adb40c65
def _set_date(self): 'Sets up the instrument date, mm/dd/yy.' if self._get_prompt(): now = utime.localtime() self.uart.write('SET DATE {:02d}/{:02d}/{:02d}\r'.format(now[1], now[2], int(str(now[0])[:(- 2)]))) if (self._get_reply() == self.prompt): return True return False
Sets up the instrument date, mm/dd/yy.
firmware/dev_aml.py
_set_date
andreacorbo/Buoy_Controller_v1
0
python
def _set_date(self): if self._get_prompt(): now = utime.localtime() self.uart.write('SET DATE {:02d}/{:02d}/{:02d}\r'.format(now[1], now[2], int(str(now[0])[:(- 2)]))) if (self._get_reply() == self.prompt): return True return False
def _set_date(self): if self._get_prompt(): now = utime.localtime() self.uart.write('SET DATE {:02d}/{:02d}/{:02d}\r'.format(now[1], now[2], int(str(now[0])[:(- 2)]))) if (self._get_reply() == self.prompt): return True return False<|docstring|>Sets up the instrument date, mm/dd/yy.<|endoftext|>
24c006049479e11e2359aaeb91dcdcd37f0f8daa118d28bddbfd3ec79e510420
def _set_time(self): 'Sets up the instrument time, hh:mm:ss.' if self._get_prompt(): now = utime.localtime() self.uart.write('SET TIME {:02d}:{:02d}:{:02d}\r'.format(now[3], now[4], now[5])) if (self._get_reply() == self.prompt): return True return False
Sets up the instrument time, hh:mm:ss.
firmware/dev_aml.py
_set_time
andreacorbo/Buoy_Controller_v1
0
python
def _set_time(self): if self._get_prompt(): now = utime.localtime() self.uart.write('SET TIME {:02d}:{:02d}:{:02d}\r'.format(now[3], now[4], now[5])) if (self._get_reply() == self.prompt): return True return False
def _set_time(self): if self._get_prompt(): now = utime.localtime() self.uart.write('SET TIME {:02d}:{:02d}:{:02d}\r'.format(now[3], now[4], now[5])) if (self._get_reply() == self.prompt): return True return False<|docstring|>Sets up the instrument time, hh:mm:ss.<|endoftext|>
fcd3a288f2cb86625fc7f9781583a03cdec4fba3e52251132e5edc05e23ac790
def _set_clock(self): 'Syncs the intrument clock.' if (self._set_date() and self._set_time()): utils.log_file('{} => clock synced (dev: {} {} board: {})'.format(self.__qualname__, self._get_date(), self._get_time(), utils.time_string(utime.mktime(utime.localtime())))) return True utils.log_file('{} => unable to sync clock'.format(self.__qualname__)) return False
Syncs the intrument clock.
firmware/dev_aml.py
_set_clock
andreacorbo/Buoy_Controller_v1
0
python
def _set_clock(self): if (self._set_date() and self._set_time()): utils.log_file('{} => clock synced (dev: {} {} board: {})'.format(self.__qualname__, self._get_date(), self._get_time(), utils.time_string(utime.mktime(utime.localtime())))) return True utils.log_file('{} => unable to sync clock'.format(self.__qualname__)) return False
def _set_clock(self): if (self._set_date() and self._set_time()): utils.log_file('{} => clock synced (dev: {} {} board: {})'.format(self.__qualname__, self._get_date(), self._get_time(), utils.time_string(utime.mktime(utime.localtime())))) return True utils.log_file('{} => unable to sync clock'.format(self.__qualname__)) return False<|docstring|>Syncs the intrument clock.<|endoftext|>
bfcc9859a57398b6dc45ca940910d67626b778720c095affe7d98f9fa2f56654
def _set_sample_rate(self): 'Sets intrument sampling rate.' if self._get_prompt(): self.uart.write('SET S {:0d} S\r'.format(self.config['Sample_Rate'])) if (self._get_reply() == self.prompt): self._get_sample_rate() return True utils.log_file('{} => unable to set sampling rate'.format(self.__qualname__)) return False
Sets intrument sampling rate.
firmware/dev_aml.py
_set_sample_rate
andreacorbo/Buoy_Controller_v1
0
python
def _set_sample_rate(self): if self._get_prompt(): self.uart.write('SET S {:0d} S\r'.format(self.config['Sample_Rate'])) if (self._get_reply() == self.prompt): self._get_sample_rate() return True utils.log_file('{} => unable to set sampling rate'.format(self.__qualname__)) return False
def _set_sample_rate(self): if self._get_prompt(): self.uart.write('SET S {:0d} S\r'.format(self.config['Sample_Rate'])) if (self._get_reply() == self.prompt): self._get_sample_rate() return True utils.log_file('{} => unable to set sampling rate'.format(self.__qualname__)) return False<|docstring|>Sets intrument sampling rate.<|endoftext|>
acbcfcaf9b3834064cfe31b245275ddd50c5c1d9c23a2f37f0f3fd2800e06413
def _format_data(self, sample): 'Formats data according to output format.' epoch = utime.time() data = [self.config['String_Label'], utils.unix_epoch(epoch), utils.datestamp(epoch), utils.timestamp(epoch)] sample = sample.split(self.config['Data_Separator']) data.append(','.join(sample[0].split(' '))) for field in sample[1:]: data.append(field) return constants.DATA_SEPARATOR.join(data)
Formats data according to output format.
firmware/dev_aml.py
_format_data
andreacorbo/Buoy_Controller_v1
0
python
def _format_data(self, sample): epoch = utime.time() data = [self.config['String_Label'], utils.unix_epoch(epoch), utils.datestamp(epoch), utils.timestamp(epoch)] sample = sample.split(self.config['Data_Separator']) data.append(','.join(sample[0].split(' '))) for field in sample[1:]: data.append(field) return constants.DATA_SEPARATOR.join(data)
def _format_data(self, sample): epoch = utime.time() data = [self.config['String_Label'], utils.unix_epoch(epoch), utils.datestamp(epoch), utils.timestamp(epoch)] sample = sample.split(self.config['Data_Separator']) data.append(','.join(sample[0].split(' '))) for field in sample[1:]: data.append(field) return constants.DATA_SEPARATOR.join(data)<|docstring|>Formats data according to output format.<|endoftext|>
3825b155a405aa7f19fb60b2018664c7d0c72079a9e6d28afd90bf19b30d01c7
def main(self): 'Captures instrument data.' if (not self.init_uart()): return utils.log_file('{} => acquiring data...'.format(self.__qualname__)) self.led_on() sample = '' new_line = False start = utime.time() while True: if ((utime.time() - start) > (self.config['Samples'] // self.config['Sample_Rate'])): utils.log_file('{} => no data coming from serial'.format(self.__qualname__)) break if self.uart.any(): byte = self.uart.read(1) if (byte == b'\n'): new_line = True elif ((byte == b'\r') and new_line): break elif new_line: sample += byte.decode('utf-8') utils.log_data(self._format_data(sample)) self.led_on() return
Captures instrument data.
firmware/dev_aml.py
main
andreacorbo/Buoy_Controller_v1
0
python
def main(self): if (not self.init_uart()): return utils.log_file('{} => acquiring data...'.format(self.__qualname__)) self.led_on() sample = new_line = False start = utime.time() while True: if ((utime.time() - start) > (self.config['Samples'] // self.config['Sample_Rate'])): utils.log_file('{} => no data coming from serial'.format(self.__qualname__)) break if self.uart.any(): byte = self.uart.read(1) if (byte == b'\n'): new_line = True elif ((byte == b'\r') and new_line): break elif new_line: sample += byte.decode('utf-8') utils.log_data(self._format_data(sample)) self.led_on() return
def main(self): if (not self.init_uart()): return utils.log_file('{} => acquiring data...'.format(self.__qualname__)) self.led_on() sample = new_line = False start = utime.time() while True: if ((utime.time() - start) > (self.config['Samples'] // self.config['Sample_Rate'])): utils.log_file('{} => no data coming from serial'.format(self.__qualname__)) break if self.uart.any(): byte = self.uart.read(1) if (byte == b'\n'): new_line = True elif ((byte == b'\r') and new_line): break elif new_line: sample += byte.decode('utf-8') utils.log_data(self._format_data(sample)) self.led_on() return<|docstring|>Captures instrument data.<|endoftext|>
6be4ea638a768aee27fc505999767a47a3e7b838a9e4a029d55d17beb1171028
def start_up(self): 'Performs device specific initialization sequence.' if self.init_power(): return True return False
Performs device specific initialization sequence.
firmware/dev_aml.py
start_up
andreacorbo/Buoy_Controller_v1
0
python
def start_up(self): if self.init_power(): return True return False
def start_up(self): if self.init_power(): return True return False<|docstring|>Performs device specific initialization sequence.<|endoftext|>
83e1b1b98f065209c603735e908bae9a66c630e6f109a8b2d56f931672dea7b0
def recursive_mapping_update(mapping, **updates): ' Recursively update a dict-tree without clobbering any of the nested dictionaries.\n\n :param mapping: a dict-like object to perform updates on\n :type mapping: dict\n :returns: the updated mapping\n ' for (key, value) in updates.items(): if (isinstance(value, Mapping) and mapping.get(key)): mapping[key] = recursive_mapping_update(mapping[key], **value) else: mapping[key] = value return mapping
Recursively update a dict-tree without clobbering any of the nested dictionaries. :param mapping: a dict-like object to perform updates on :type mapping: dict :returns: the updated mapping
restframework_stripe/util.py
recursive_mapping_update
jayvdb/django-restframework-stripe
1
python
def recursive_mapping_update(mapping, **updates): ' Recursively update a dict-tree without clobbering any of the nested dictionaries.\n\n :param mapping: a dict-like object to perform updates on\n :type mapping: dict\n :returns: the updated mapping\n ' for (key, value) in updates.items(): if (isinstance(value, Mapping) and mapping.get(key)): mapping[key] = recursive_mapping_update(mapping[key], **value) else: mapping[key] = value return mapping
def recursive_mapping_update(mapping, **updates): ' Recursively update a dict-tree without clobbering any of the nested dictionaries.\n\n :param mapping: a dict-like object to perform updates on\n :type mapping: dict\n :returns: the updated mapping\n ' for (key, value) in updates.items(): if (isinstance(value, Mapping) and mapping.get(key)): mapping[key] = recursive_mapping_update(mapping[key], **value) else: mapping[key] = value return mapping<|docstring|>Recursively update a dict-tree without clobbering any of the nested dictionaries. :param mapping: a dict-like object to perform updates on :type mapping: dict :returns: the updated mapping<|endoftext|>
a0cf02c7be15a9bd86938bcdc89d41e90781a7d559bafa00c9fb46cc8f943dde
def __getstate__(self): '\n Returns the pickled data.\n ' return {k: getattr(self, k) for k in BaseSIR._pickled_atts}
Returns the pickled data.
aftercovid/models/_base_sir.py
__getstate__
sdpython/covidsim
0
python
def __getstate__(self): '\n \n ' return {k: getattr(self, k) for k in BaseSIR._pickled_atts}
def __getstate__(self): '\n \n ' return {k: getattr(self, k) for k in BaseSIR._pickled_atts}<|docstring|>Returns the pickled data.<|endoftext|>
c2fbd6883f0496f5808d35fb57d8223fc754db62a0b4825c6cb0aaa09c774578
def __setstate__(self, state): '\n Sets the pickled data.\n ' for (k, v) in state.items(): setattr(self, k, v) if (hasattr(self, '_eq') and (self._eq is not None)): self._init_lambda_()
Sets the pickled data.
aftercovid/models/_base_sir.py
__setstate__
sdpython/covidsim
0
python
def __setstate__(self, state): '\n \n ' for (k, v) in state.items(): setattr(self, k, v) if (hasattr(self, '_eq') and (self._eq is not None)): self._init_lambda_()
def __setstate__(self, state): '\n \n ' for (k, v) in state.items(): setattr(self, k, v) if (hasattr(self, '_eq') and (self._eq is not None)): self._init_lambda_()<|docstring|>Sets the pickled data.<|endoftext|>
882341daed2a1781a6631bc28ee07a49b87c8a74cad10b4753debc6663c43cc3
def _init(self): '\n Starts from the initial values.\n ' def _def_(name, v): if (v is not None): return v if (name == 'N'): return 10000.0 return 0.0 self._val_p = numpy.array([_def_(v[0], v[1]) for v in self._p], dtype=numpy.float64) self._val_q = numpy.array([_def_(v[0], v[1]) for v in self._q], dtype=numpy.float64) self._val_c = numpy.array([_def_(v[0], v[1]) for v in self._c], dtype=numpy.float64) self._val_len = ((len(self._val_p) + len(self._val_q)) + len(self._val_c)) self._val_ind = numpy.array([0, len(self._val_q), (len(self._val_q) + len(self._val_p)), ((len(self._val_q) + len(self._val_p)) + len(self._val_c))]) if (hasattr(self, '_eq') and (self._eq is not None)): self._init_lambda_()
Starts from the initial values.
aftercovid/models/_base_sir.py
_init
sdpython/covidsim
0
python
def _init(self): '\n \n ' def _def_(name, v): if (v is not None): return v if (name == 'N'): return 10000.0 return 0.0 self._val_p = numpy.array([_def_(v[0], v[1]) for v in self._p], dtype=numpy.float64) self._val_q = numpy.array([_def_(v[0], v[1]) for v in self._q], dtype=numpy.float64) self._val_c = numpy.array([_def_(v[0], v[1]) for v in self._c], dtype=numpy.float64) self._val_len = ((len(self._val_p) + len(self._val_q)) + len(self._val_c)) self._val_ind = numpy.array([0, len(self._val_q), (len(self._val_q) + len(self._val_p)), ((len(self._val_q) + len(self._val_p)) + len(self._val_c))]) if (hasattr(self, '_eq') and (self._eq is not None)): self._init_lambda_()
def _init(self): '\n \n ' def _def_(name, v): if (v is not None): return v if (name == 'N'): return 10000.0 return 0.0 self._val_p = numpy.array([_def_(v[0], v[1]) for v in self._p], dtype=numpy.float64) self._val_q = numpy.array([_def_(v[0], v[1]) for v in self._q], dtype=numpy.float64) self._val_c = numpy.array([_def_(v[0], v[1]) for v in self._c], dtype=numpy.float64) self._val_len = ((len(self._val_p) + len(self._val_q)) + len(self._val_c)) self._val_ind = numpy.array([0, len(self._val_q), (len(self._val_q) + len(self._val_p)), ((len(self._val_q) + len(self._val_p)) + len(self._val_c))]) if (hasattr(self, '_eq') and (self._eq is not None)): self._init_lambda_()<|docstring|>Starts from the initial values.<|endoftext|>
82e31d6f8cffae726330fc529f8c02bd2d8d4370dcd870c34120d67a83ac2bba
def get_index(self, name): '\n Returns the index of a name (True or False, position).\n ' for (i, v) in enumerate(self._p): if (v[0] == name): return ('p', i) for (i, v) in enumerate(self._q): if (v[0] == name): return ('q', i) for (i, v) in enumerate(self._c): if (v[0] == name): return ('c', i) raise ValueError("Unable to find name '{}'.".format(name))
Returns the index of a name (True or False, position).
aftercovid/models/_base_sir.py
get_index
sdpython/covidsim
0
python
def get_index(self, name): '\n \n ' for (i, v) in enumerate(self._p): if (v[0] == name): return ('p', i) for (i, v) in enumerate(self._q): if (v[0] == name): return ('q', i) for (i, v) in enumerate(self._c): if (v[0] == name): return ('c', i) raise ValueError("Unable to find name '{}'.".format(name))
def get_index(self, name): '\n \n ' for (i, v) in enumerate(self._p): if (v[0] == name): return ('p', i) for (i, v) in enumerate(self._q): if (v[0] == name): return ('q', i) for (i, v) in enumerate(self._c): if (v[0] == name): return ('c', i) raise ValueError("Unable to find name '{}'.".format(name))<|docstring|>Returns the index of a name (True or False, position).<|endoftext|>
7a7d93652709f24419cb028191ea295a6fc095c724f8db8a79b971fccfa38330
def __setitem__(self, name, value): '\n Updates a value whether it is a parameter or a quantity.\n\n :param name: name\n :param value: new value\n ' (p, pos) = self.get_index(name) if (p == 'p'): self._val_p[pos] = value elif (p == 'q'): self._val_q[pos] = value elif (p == 'c'): self._val_c[pos] = value
Updates a value whether it is a parameter or a quantity. :param name: name :param value: new value
aftercovid/models/_base_sir.py
__setitem__
sdpython/covidsim
0
python
def __setitem__(self, name, value): '\n Updates a value whether it is a parameter or a quantity.\n\n :param name: name\n :param value: new value\n ' (p, pos) = self.get_index(name) if (p == 'p'): self._val_p[pos] = value elif (p == 'q'): self._val_q[pos] = value elif (p == 'c'): self._val_c[pos] = value
def __setitem__(self, name, value): '\n Updates a value whether it is a parameter or a quantity.\n\n :param name: name\n :param value: new value\n ' (p, pos) = self.get_index(name) if (p == 'p'): self._val_p[pos] = value elif (p == 'q'): self._val_q[pos] = value elif (p == 'c'): self._val_c[pos] = value<|docstring|>Updates a value whether it is a parameter or a quantity. :param name: name :param value: new value<|endoftext|>
126805786ef23a2cfbfd7075e7150c704464a18bc8d98afd312c26df9c0a829e
def __getitem__(self, name): '\n Retrieves a value whether it is a parameter or a quantity.\n\n :param name: name\n :return: value\n ' (p, pos) = self.get_index(name) if (p == 'p'): return self._val_p[pos] if (p == 'q'): return self._val_q[pos] if (p == 'c'): return self._val_c[pos]
Retrieves a value whether it is a parameter or a quantity. :param name: name :return: value
aftercovid/models/_base_sir.py
__getitem__
sdpython/covidsim
0
python
def __getitem__(self, name): '\n Retrieves a value whether it is a parameter or a quantity.\n\n :param name: name\n :return: value\n ' (p, pos) = self.get_index(name) if (p == 'p'): return self._val_p[pos] if (p == 'q'): return self._val_q[pos] if (p == 'c'): return self._val_c[pos]
def __getitem__(self, name): '\n Retrieves a value whether it is a parameter or a quantity.\n\n :param name: name\n :return: value\n ' (p, pos) = self.get_index(name) if (p == 'p'): return self._val_p[pos] if (p == 'q'): return self._val_q[pos] if (p == 'c'): return self._val_c[pos]<|docstring|>Retrieves a value whether it is a parameter or a quantity. :param name: name :return: value<|endoftext|>
ad6ead7ca5823cb74988912a37aab042f03319da29ef28378a5e0129421bcd3c
@property def names(self): 'Returns the list of names.' return list(sorted((([v[0] for v in self._p] + [v[0] for v in self._q]) + [v[0] for v in self._c])))
Returns the list of names.
aftercovid/models/_base_sir.py
names
sdpython/covidsim
0
python
@property def names(self): return list(sorted((([v[0] for v in self._p] + [v[0] for v in self._q]) + [v[0] for v in self._c])))
@property def names(self): return list(sorted((([v[0] for v in self._p] + [v[0] for v in self._q]) + [v[0] for v in self._c])))<|docstring|>Returns the list of names.<|endoftext|>
f24d77abda1fd3877d36a339f95a5a5007d22f02dee383bba5a18252d36cf620
@property def quantity_names(self): 'Returns the list of quantities names (unsorted).' return [v[0] for v in self._q]
Returns the list of quantities names (unsorted).
aftercovid/models/_base_sir.py
quantity_names
sdpython/covidsim
0
python
@property def quantity_names(self): return [v[0] for v in self._q]
@property def quantity_names(self): return [v[0] for v in self._q]<|docstring|>Returns the list of quantities names (unsorted).<|endoftext|>
6b38a94747d611c876bf7672953b878db20d843e1895ae130bf3ccde16199624
@property def param_names(self): 'Returns the list of parameters names (unsorted).' return [v[0] for v in self._p]
Returns the list of parameters names (unsorted).
aftercovid/models/_base_sir.py
param_names
sdpython/covidsim
0
python
@property def param_names(self): return [v[0] for v in self._p]
@property def param_names(self): return [v[0] for v in self._p]<|docstring|>Returns the list of parameters names (unsorted).<|endoftext|>
346dda969d49de363ae26adc827ac0bb3f9637cd0df785d561da8dea5eee4669
@property def params_dict(self): 'Returns the list of parameters names in a dictionary.' return {k: self[k] for k in self.param_names}
Returns the list of parameters names in a dictionary.
aftercovid/models/_base_sir.py
params_dict
sdpython/covidsim
0
python
@property def params_dict(self): return {k: self[k] for k in self.param_names}
@property def params_dict(self): return {k: self[k] for k in self.param_names}<|docstring|>Returns the list of parameters names in a dictionary.<|endoftext|>
8832b013a1715ed17ede389c9e7317d2b7a67c533cd1a69fc6d05eeba9d372cb
@property def cst_names(self): 'Returns the list of constants names (unsorted).' return [v[0] for v in self._c]
Returns the list of constants names (unsorted).
aftercovid/models/_base_sir.py
cst_names
sdpython/covidsim
0
python
@property def cst_names(self): return [v[0] for v in self._c]
@property def cst_names(self): return [v[0] for v in self._c]<|docstring|>Returns the list of constants names (unsorted).<|endoftext|>
95c0e1f587bd4e0757b70d8f189db85847f123e2745ac58440aa25a099b3fa4f
@property def vect_names(self): 'Returns the list of names.' return ((([v[0] for v in self._q] + [v[0] for v in self._p]) + [v[0] for v in self._c]) + ['t'])
Returns the list of names.
aftercovid/models/_base_sir.py
vect_names
sdpython/covidsim
0
python
@property def vect_names(self): return ((([v[0] for v in self._q] + [v[0] for v in self._p]) + [v[0] for v in self._c]) + ['t'])
@property def vect_names(self): return ((([v[0] for v in self._q] + [v[0] for v in self._p]) + [v[0] for v in self._c]) + ['t'])<|docstring|>Returns the list of names.<|endoftext|>
c13975fbb548e3d84ff0cec25d692c47610fbbbba604f2e42771dacc6f9d61a8
def vect(self, t=0, out=None, derivative=False): '\n Returns all values as a vector.\n\n :param t: time *t*\n :param out: alternative output array in which to place the\n result. It must have the same shape as the expected output.\n :param derivative: returns the derivatives instead of the values\n :return: values or derivatives\n ' if derivative: if (out is None): out = numpy.empty((((self._val_len + 1) + self._val_ind[1]),), dtype=numpy.float64) self.vect(t=t, out=out) for (i, v) in enumerate(self._leqa): out[(i - self._val_ind[1])] = v(*out[:(self._val_len + 1)]) elif (out is None): out = numpy.empty(((self._val_len + 1),), dtype=numpy.float64) out[:self._val_ind[1]] = self._val_q out[self._val_ind[1]:self._val_ind[2]] = self._val_p out[self._val_ind[2]:self._val_ind[3]] = self._val_c out[self._val_ind[3]] = t return out
Returns all values as a vector. :param t: time *t* :param out: alternative output array in which to place the result. It must have the same shape as the expected output. :param derivative: returns the derivatives instead of the values :return: values or derivatives
aftercovid/models/_base_sir.py
vect
sdpython/covidsim
0
python
def vect(self, t=0, out=None, derivative=False): '\n Returns all values as a vector.\n\n :param t: time *t*\n :param out: alternative output array in which to place the\n result. It must have the same shape as the expected output.\n :param derivative: returns the derivatives instead of the values\n :return: values or derivatives\n ' if derivative: if (out is None): out = numpy.empty((((self._val_len + 1) + self._val_ind[1]),), dtype=numpy.float64) self.vect(t=t, out=out) for (i, v) in enumerate(self._leqa): out[(i - self._val_ind[1])] = v(*out[:(self._val_len + 1)]) elif (out is None): out = numpy.empty(((self._val_len + 1),), dtype=numpy.float64) out[:self._val_ind[1]] = self._val_q out[self._val_ind[1]:self._val_ind[2]] = self._val_p out[self._val_ind[2]:self._val_ind[3]] = self._val_c out[self._val_ind[3]] = t return out
def vect(self, t=0, out=None, derivative=False): '\n Returns all values as a vector.\n\n :param t: time *t*\n :param out: alternative output array in which to place the\n result. It must have the same shape as the expected output.\n :param derivative: returns the derivatives instead of the values\n :return: values or derivatives\n ' if derivative: if (out is None): out = numpy.empty((((self._val_len + 1) + self._val_ind[1]),), dtype=numpy.float64) self.vect(t=t, out=out) for (i, v) in enumerate(self._leqa): out[(i - self._val_ind[1])] = v(*out[:(self._val_len + 1)]) elif (out is None): out = numpy.empty(((self._val_len + 1),), dtype=numpy.float64) out[:self._val_ind[1]] = self._val_q out[self._val_ind[1]:self._val_ind[2]] = self._val_p out[self._val_ind[2]:self._val_ind[3]] = self._val_c out[self._val_ind[3]] = t return out<|docstring|>Returns all values as a vector. :param t: time *t* :param out: alternative output array in which to place the result. It must have the same shape as the expected output. :param derivative: returns the derivatives instead of the values :return: values or derivatives<|endoftext|>
0cbedc1d716f0a53d28057c5cf054b6b920d5d787480a5474bcb33b31c2a32fd
@property def P(self): '\n Returns the parameters\n ' return [(a[0], b, a[2]) for (a, b) in zip(self._p, self._val_p)]
Returns the parameters
aftercovid/models/_base_sir.py
P
sdpython/covidsim
0
python
@property def P(self): '\n \n ' return [(a[0], b, a[2]) for (a, b) in zip(self._p, self._val_p)]
@property def P(self): '\n \n ' return [(a[0], b, a[2]) for (a, b) in zip(self._p, self._val_p)]<|docstring|>Returns the parameters<|endoftext|>
3b7d25ad442483beb68320a8cab46a7cbe70ee7e280f6722df10f7b5db64333b
@property def Q(self): '\n Returns the quantities\n ' return [(a[0], b, a[2]) for (a, b) in zip(self._q, self._val_q)]
Returns the quantities
aftercovid/models/_base_sir.py
Q
sdpython/covidsim
0
python
@property def Q(self): '\n \n ' return [(a[0], b, a[2]) for (a, b) in zip(self._q, self._val_q)]
@property def Q(self): '\n \n ' return [(a[0], b, a[2]) for (a, b) in zip(self._q, self._val_q)]<|docstring|>Returns the quantities<|endoftext|>
bd7ad5d70f2fe27abd63fbca2f26e0c59e6f860265f079ac54a8a5e6420aaefc
@property def C(self): '\n Returns the quantities\n ' return [(a[0], b, a[2]) for (a, b) in zip(self._c, self._val_c)]
Returns the quantities
aftercovid/models/_base_sir.py
C
sdpython/covidsim
0
python
@property def C(self): '\n \n ' return [(a[0], b, a[2]) for (a, b) in zip(self._c, self._val_c)]
@property def C(self): '\n \n ' return [(a[0], b, a[2]) for (a, b) in zip(self._c, self._val_c)]<|docstring|>Returns the quantities<|endoftext|>