id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
142,248 |
KeepSafe/android-resource-remover
|
KeepSafe_android-resource-remover/android_clean_app.py
|
android_clean_app.Issue
|
class Issue:
"""
Stores a single issue reported by Android Lint
"""
def __init__(self, filepath, remove_file):
self.filepath = filepath
self.remove_file = remove_file
self.elements = []
def __str__(self):
return '{0} {1}'.format(self.filepath, self.elements)
def __repr__(self):
return '{0} {1}'.format(self.filepath, self.elements)
def add_element(self, message):
res_all = re.findall(self.pattern, message)
if res_all:
self._process_match(res_all)
else:
print("The pattern '%s' seems to find nothing in the error message '%s'. We can't find the resource and "
"can't remove it. The pattern might have changed, please check and report this in github issues." % (
self.pattern.pattern, message))
|
class Issue:
'''
Stores a single issue reported by Android Lint
'''
def __init__(self, filepath, remove_file):
pass
def __str__(self):
pass
def __repr__(self):
pass
def add_element(self, message):
pass
| 5 | 1 | 4 | 0 | 4 | 0 | 1 | 0.18 | 0 | 0 | 0 | 2 | 4 | 3 | 4 | 4 | 25 | 5 | 17 | 9 | 12 | 3 | 14 | 9 | 9 | 2 | 0 | 1 | 5 |
142,249 |
KeepSafe/android-resource-remover
|
KeepSafe_android-resource-remover/android_clean_app.py
|
android_clean_app.UnusedResourceIssue
|
class UnusedResourceIssue(Issue):
pattern = re.compile('The resource `?([^`]+)`? appears to be unused')
def _process_match(self, match_result):
bits = match_result[0].split('.')[-2:]
self.elements.append((bits[0], bits[1]))
|
class UnusedResourceIssue(Issue):
def _process_match(self, match_result):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 6 | 1 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 1 | 0 | 1 |
142,250 |
KeepSafe/android-resource-remover
|
KeepSafe_android-resource-remover/test/test_clean_app.py
|
test_clean_app.CleanAppTestCase
|
class CleanAppTestCase(unittest.TestCase):
def test_lookup_manifest_path(self):
res = clean_app.get_manifest_path('./test/android_app_2')
expected = os.path.abspath('./test/android_app_2/src/main/AndroidManifest.xml')
self.assertEqual(expected, res)
def test_lookup_manifest_old_path(self):
res = clean_app.get_manifest_path('./test/android_app')
expected = os.path.abspath('./test/android_app/AndroidManifest.xml')
self.assertEqual(expected, res)
def test_reads_all_unused_resource_issues(self):
issues = clean_app.parse_lint_result('./test/android_app/lint-result.xml',
'./test/android_app/AndroidManifest.xml')
actual = list(filter(lambda i: isinstance(i, clean_app.UnusedResourceIssue), issues))
self.assertEqual(15, len(actual))
def test_reads_untranslatable_extra_translation_issues(self):
issues = clean_app.parse_lint_result('./test/android_app/lint-result.xml',
'./test/android_app/AndroidManifest.xml')
actual = list(filter(lambda i: isinstance(i, clean_app.ExtraTranslationIssue), issues))
self.assertEqual(1, len(actual))
def test_marks_resource_as_save_to_remove(self):
actual = clean_app.parse_lint_result('./test/android_app/lint-result.xml',
'./test/android_app/AndroidManifest.xml')
remove_entire_file = list(filter(lambda issue: issue.remove_file, actual))
self.assertEqual(11, len(remove_entire_file))
def test_marks_resource_as_not_save_to_remove_if_it_has_used_values(self):
actual = clean_app.parse_lint_result('./test/android_app/lint-result.xml',
'./test/android_app/AndroidManifest.xml')
not_remove_entire_file = list(filter(lambda issue: not issue.remove_file, actual))
self.assertEqual(5, len(not_remove_entire_file))
def test_extracts_correct_info_about_unused_resources(self):
issues = clean_app.parse_lint_result('./test/android_app/lint-result.xml',
'./test/android_app/AndroidManifest.xml')
not_remove_entire_file = list(filter(lambda issue: not issue.remove_file, issues))
actual = list(filter(lambda issue: os.path.normpath(issue.filepath) == os.path.normpath(
'res/values/strings.xml'), not_remove_entire_file))[0]
self.assertGreater(len(actual.elements), 0)
self.assertEqual(('string', 'missing'), actual.elements[0])
def test_extracts_correct_info_about_extra_translations(self):
issues = clean_app.parse_lint_result('./test/android_app/lint-result.xml',
'./test/android_app/AndroidManifest.xml')
not_remove_entire_file = list(filter(lambda issue: not issue.remove_file, issues))
issues = list(filter(lambda issue: os.path.normpath(issue.filepath) == os.path.normpath(
'res/values-fr/strings.xml'), not_remove_entire_file))
actual = map(lambda i: i.elements[0], issues)
self.assertIn(('string', 'untranslatable'), actual)
def test_removes_given_resources_if_safe(self):
temp, temp_path = tempfile.mkstemp()
os.close(temp)
issue = clean_app.UnusedResourceIssue(temp_path, True)
clean_app.remove_unused_resources([issue], os.path.dirname(temp_path), False)
with self.assertRaises(IOError):
open(temp_path)
def _removes_an_unused_value_from_a_file(self, message, expected_elements_count=2):
temp, temp_path = tempfile.mkstemp()
os.write(temp, """
<resources>
<string name="app_name">android_app</string>
<string name="missing">missing</string>
<string name="app_name1">android_app1</string>
</resources>
""".encode('utf-8'))
os.close(temp)
issue = clean_app.UnusedResourceIssue(temp_path, False)
issue.add_element(message)
clean_app.remove_unused_resources([issue], os.path.dirname(temp_path), True)
root = ET.parse(temp_path).getroot()
self.assertEqual(expected_elements_count, len(root.findall('string')))
def test_removes_an_unused_value_from_a_file_old_format(self):
message = 'The resource R.string.missing appears to be unused'
self._removes_an_unused_value_from_a_file(message)
def test_removes_an_unused_value_from_a_file_new_format(self):
message = 'The resource `R.string.missing` appears to be unused'
self._removes_an_unused_value_from_a_file(message)
def test_handle_incorrect_missing_resource_pattern(self):
message = 'Wrong pattern !!!'
self._removes_an_unused_value_from_a_file(message, 3)
def test_ignores_layouts(self):
temp, temp_path = tempfile.mkstemp()
os.write(temp, """
<resources>
<string name="app_name">android_app</string>
<layout name="missing">missing</layout>
<string name="app_name1">android_app1</string>
</resources>
""".encode('UTF-8'))
os.close(temp)
issue = clean_app.UnusedResourceIssue(temp_path, False)
issue.add_element('The resource R.string.missing appears to be unused')
clean_app.remove_unused_resources([issue], os.path.dirname(temp_path), False)
root = ET.parse(temp_path).getroot()
self.assertEqual(1, len(root.findall('layout')))
def test_remove_resource_file_skip_missing_files(self):
issue = MagicMock()
issue.elements = [['dummy']]
with patch('os.remove') as patch_remove:
clean_app.remove_resource_file(issue, 'dummy', False)
self.assertFalse(patch_remove.called)
def test_remove_value_only_if_the_file_still_exists(self):
temp, temp_path = tempfile.mkstemp()
os.close(temp)
os.remove(temp_path)
issue = clean_app.UnusedResourceIssue(temp_path, False)
issue.add_element('The resource `R.drawable.drawable_missing` appears to be unused')
clean_app.remove_unused_resources([issue], os.path.dirname(temp_path), False)
def test_whitelist_string_refs(self):
expected = ['untranslatable', 'app_name']
res = clean_app.get_manifest_string_refs('./test/android_app/AndroidManifest.xml')
self.assertEqual(res, expected)
def test_removes_an_extra_translation_value_from_a_file(self, ):
temp, temp_path = tempfile.mkstemp()
os.write(temp, """
<resources>
<string name="app_name">android_app</string>
<string name="extra">extra translation</string>
</resources>
""".encode('utf-8'))
os.close(temp)
issue = clean_app.ExtraTranslationIssue(temp_path, False)
issue.add_element('The resource string "`extra`" has been marked as `translatable="false"`')
clean_app.remove_unused_resources([issue], os.path.dirname(temp_path), True)
root = ET.parse(temp_path).getroot()
self.assertEqual(1, len(root.findall('string')))
|
class CleanAppTestCase(unittest.TestCase):
def test_lookup_manifest_path(self):
pass
def test_lookup_manifest_old_path(self):
pass
def test_reads_all_unused_resource_issues(self):
pass
def test_reads_untranslatable_extra_translation_issues(self):
pass
def test_marks_resource_as_save_to_remove(self):
pass
def test_marks_resource_as_not_save_to_remove_if_it_has_used_values(self):
pass
def test_extracts_correct_info_about_unused_resources(self):
pass
def test_extracts_correct_info_about_extra_translations(self):
pass
def test_removes_given_resources_if_safe(self):
pass
def _removes_an_unused_value_from_a_file(self, message, expected_elements_count=2):
pass
def test_removes_an_unused_value_from_a_file_old_format(self):
pass
def test_removes_an_unused_value_from_a_file_new_format(self):
pass
def test_handle_incorrect_missing_resource_pattern(self):
pass
def test_ignores_layouts(self):
pass
def test_remove_resource_file_skip_missing_files(self):
pass
def test_remove_value_only_if_the_file_still_exists(self):
pass
def test_whitelist_string_refs(self):
pass
def test_removes_an_extra_translation_value_from_a_file(self, ):
pass
| 19 | 0 | 7 | 1 | 7 | 0 | 1 | 0 | 1 | 5 | 2 | 0 | 18 | 0 | 18 | 90 | 152 | 30 | 122 | 57 | 103 | 0 | 97 | 56 | 78 | 1 | 2 | 1 | 18 |
142,251 |
KeepSafe/android-resource-remover
|
KeepSafe_android-resource-remover/android_clean_app.py
|
android_clean_app.ExtraTranslationIssue
|
class ExtraTranslationIssue(Issue):
pattern = re.compile('The resource string \"`([^`]+)`\" has been marked as `translatable=\"false')
def _process_match(self, match_result):
self.elements.append(('string', match_result[0]))
|
class ExtraTranslationIssue(Issue):
def _process_match(self, match_result):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 1 | 0 | 1 |
142,252 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/streaming_client.py
|
switcheo.streaming_client.OrderEventsNamespace
|
class OrderEventsNamespace(SocketIOClientNamespace):
def __init__(self):
self.lock = threading.Lock()
self.namespace = '/v2/orders'
self.order_events = {}
SocketIOClientNamespace.__init__(self, namespace=self.namespace)
def on_connect(self):
pass
def on_disconnect(self):
pass
def on_join(self):
pass
def on_all(self, data):
self.lock.acquire()
self.order_events = data
self.lock.release()
def on_updates(self, data):
update_events = data["events"]
self.lock.acquire()
self.order_events["orders"] + update_events
self.lock.release()
|
class OrderEventsNamespace(SocketIOClientNamespace):
def __init__(self):
pass
def on_connect(self):
pass
def on_disconnect(self):
pass
def on_join(self):
pass
def on_all(self, data):
pass
def on_updates(self, data):
pass
| 7 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 6 | 3 | 6 | 6 | 27 | 6 | 21 | 11 | 14 | 0 | 21 | 11 | 14 | 1 | 1 | 0 | 6 |
142,253 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/switcheo_client.py
|
switcheo.switcheo_client.SwitcheoClient
|
class SwitcheoClient(AuthenticatedClient, PublicClient):
def __init__(self,
switcheo_network="test",
blockchain_network="neo",
private_key=None):
self.api_url = url_dict[switcheo_network]
self.blockchain = network_dict[blockchain_network]
self.contract_version = current_contract_version(
PublicClient().get_latest_contracts()[self.blockchain.upper()], PublicClient().get_contracts())
super().__init__(blockchain=self.blockchain,
contract_version=self.contract_version,
api_url=self.api_url)
self.private_key = private_key
def order_history(self, address, pair=None):
return self.get_orders(neo_get_scripthash_from_address(address=address), pair=pair)
def balance_current_contract(self, *addresses):
address_list = []
for address in addresses:
address_list.append(neo_get_scripthash_from_address(address=address))
return self.get_balance(addresses=address_list, contracts=self.current_contract_hash)
def balance_by_contract(self, *addresses):
address_list = []
contract_dict = {}
for address in addresses:
address_list.append(neo_get_scripthash_from_address(address=address))
contracts = self.get_contracts()
for blockchain in contracts:
contract_dict[blockchain] = {}
for key in contracts[blockchain]:
contract_dict[blockchain][key] =\
self.get_balance(addresses=address_list, contracts=contracts[blockchain][key])
return contract_dict
def balance_by_address_by_contract(self, *addresses):
contract_dict = {}
for address in addresses:
contract_dict[address] = self.balance_by_contract(address)
return contract_dict
def limit_buy(self, price, quantity, pair, use_native_token=True):
"""
limit_buy(price=0.0002, quantity=1000, pair='SWTH_NEO')
limit_buy(price=0.0000001, quantity=1000000, pair='JRC_ETH')
:param price:
:param quantity:
:param pair:
:param use_native_token:
:return:
"""
if 'ETH' in pair:
use_native_token = False
return self.order(order_type="limit",
side="buy",
pair=pair,
price=price,
quantity=quantity,
private_key=self.private_key,
use_native_token=use_native_token)
def limit_sell(self, price, quantity, pair, use_native_token=True):
"""
limit_sell(price=0.0006, quantity=500, pair='SWTH_NEO')
limit_sell(price=0.000001, quantity=100000, pair='JRC_ETH')
:param price:
:param quantity:
:param pair:
:param use_native_token:
:return:
"""
if 'ETH' in pair:
use_native_token = False
return self.order(order_type="limit",
side="sell",
pair=pair,
price=price,
quantity=quantity,
private_key=self.private_key,
use_native_token=use_native_token)
def market_buy(self, quantity, pair, use_native_token=True):
"""
market_buy(quantity=100, pair='SWTH_NEO')
market_buy(quantity=100000, pair='JRC_ETH')
:param quantity:
:param pair:
:param use_native_token:
:return:
"""
if 'ETH' in pair:
use_native_token = False
return self.order(order_type="market",
side="buy",
pair=pair,
price=0,
quantity=quantity,
private_key=self.private_key,
use_native_token=use_native_token)
def market_sell(self, quantity, pair, use_native_token=True):
"""
market_sell(quantity=100, pair='SWTH_NEO')
market_sell(quantity=100000, pair='JRC_ETH')
:param quantity:
:param pair:
:param use_native_token:
:return:
"""
if 'ETH' in pair:
use_native_token = False
return self.order(order_type="market",
side="sell",
pair=pair,
price=0,
quantity=quantity,
private_key=self.private_key,
use_native_token=use_native_token)
|
class SwitcheoClient(AuthenticatedClient, PublicClient):
def __init__(self,
switcheo_network="test",
blockchain_network="neo",
private_key=None):
pass
def order_history(self, address, pair=None):
pass
def balance_current_contract(self, *addresses):
pass
def balance_by_contract(self, *addresses):
pass
def balance_by_address_by_contract(self, *addresses):
pass
def limit_buy(self, price, quantity, pair, use_native_token=True):
'''
limit_buy(price=0.0002, quantity=1000, pair='SWTH_NEO')
limit_buy(price=0.0000001, quantity=1000000, pair='JRC_ETH')
:param price:
:param quantity:
:param pair:
:param use_native_token:
:return:
'''
pass
def limit_sell(self, price, quantity, pair, use_native_token=True):
'''
limit_sell(price=0.0006, quantity=500, pair='SWTH_NEO')
limit_sell(price=0.000001, quantity=100000, pair='JRC_ETH')
:param price:
:param quantity:
:param pair:
:param use_native_token:
:return:
'''
pass
def market_buy(self, quantity, pair, use_native_token=True):
'''
market_buy(quantity=100, pair='SWTH_NEO')
market_buy(quantity=100000, pair='JRC_ETH')
:param quantity:
:param pair:
:param use_native_token:
:return:
'''
pass
def market_sell(self, quantity, pair, use_native_token=True):
'''
market_sell(quantity=100, pair='SWTH_NEO')
market_sell(quantity=100000, pair='JRC_ETH')
:param quantity:
:param pair:
:param use_native_token:
:return:
'''
pass
| 10 | 4 | 13 | 1 | 8 | 4 | 2 | 0.44 | 2 | 1 | 0 | 0 | 9 | 4 | 9 | 43 | 128 | 17 | 77 | 27 | 64 | 34 | 46 | 24 | 36 | 4 | 3 | 2 | 18 |
142,254 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/test_switcheo_client.py
|
switcheo.test_switcheo_client.TestSwitcheoClient
|
class TestSwitcheoClient(unittest.TestCase):
def test_order_history(self):
orders_list = [{
'id': 'ecb6ee9e-de8d-46d6-953b-afcc976be1ae',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'pair': 'SWTH_NEO',
'side': 'buy',
'price': '0.00001',
'quantity': '1000000000000',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '6000000',
'want_amount': '30000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-08T18:39:13.864Z',
'status': 'processed',
'order_status': 'cancelled',
'txn': None,
'offer_asset_blockchain': 'neo',
'want_asset_blockchain': 'neo',
'broadcast_cutoff_at': '2019-05-04T15:53:04.809Z',
'scheduled_cancellation_at': None,
'counterpart_swap': None,
"unlock_swap_txn": None,
'fills': [],
'fill_groups': [],
'makes': []
}]
orders_list = orders_list[0].keys()
all_orders = sc.order_history(address=testnet_address1)
self.assertTrue(set(all_orders[0].keys()).issubset(set(orders_list)))
def test_balance_current_contract(self):
expected_balance_current_contract_child_key_set = set(['confirming', 'confirmed', 'locked'])
balance_current_contract = sc.balance_current_contract(testnet_address1)
balance_current_contract_child_key_set = set(balance_current_contract.keys())
self.assertTrue(
balance_current_contract_child_key_set.issubset(expected_balance_current_contract_child_key_set))
def test_balance_by_contract(self):
expected_balance_by_contract_key_set = set(['NEO', 'ETH', 'QTUM', 'EOS'])
expected_balance_by_contract_child_key_set = set(['V1', 'V1_5', 'V2', 'V3'])
expected_balance_by_contract_sub_key_set = set(['confirming', 'confirmed', 'locked'])
balance_by_contract = sc.balance_by_contract(testnet_address1)
balance_by_contract_key_set = set(balance_by_contract.keys())
self.assertTrue(balance_by_contract_key_set.issubset(expected_balance_by_contract_key_set))
balance_by_contract_neo = balance_by_contract['NEO']
balance_by_contract_eth = balance_by_contract['ETH']
balance_by_contract_child_key_set = set(balance_by_contract_neo.keys())
self.assertTrue(balance_by_contract_child_key_set.issubset(expected_balance_by_contract_child_key_set))
balance_by_contract_sub_key_set = set(balance_by_contract_neo['V1'])
self.assertTrue(balance_by_contract_sub_key_set.issubset(expected_balance_by_contract_sub_key_set))
balance_by_contract_child_key_set = set(balance_by_contract_eth.keys())
self.assertTrue(balance_by_contract_child_key_set.issubset(expected_balance_by_contract_child_key_set))
balance_by_contract_sub_key_set = set(balance_by_contract_eth['V1'])
self.assertTrue(balance_by_contract_sub_key_set.issubset(expected_balance_by_contract_sub_key_set))
def test_balance_by_address_by_contract(self):
expected_balance_by_address_key_set = set([testnet_address1, testnet_address2])
balance_by_address_key_set = set(sc.balance_by_address_by_contract(testnet_address1, testnet_address2).keys())
self.assertTrue(balance_by_address_key_set.issubset(expected_balance_by_address_key_set))
|
class TestSwitcheoClient(unittest.TestCase):
def test_order_history(self):
pass
def test_balance_current_contract(self):
pass
def test_balance_by_contract(self):
pass
def test_balance_by_address_by_contract(self):
pass
| 5 | 0 | 16 | 0 | 16 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 4 | 0 | 4 | 76 | 68 | 4 | 64 | 21 | 59 | 0 | 32 | 21 | 27 | 1 | 2 | 0 | 4 |
142,255 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/utils.py
|
switcheo.utils.SwitcheoApiException
|
class SwitcheoApiException(Exception):
def __init__(self, error_code, error_message, error):
super(SwitcheoApiException, self).__init__(error_message)
self.error_code = error_code
self.error = error
|
class SwitcheoApiException(Exception):
def __init__(self, error_code, error_message, error):
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 2 | 1 | 11 | 6 | 1 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 3 | 0 | 1 |
142,256 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/utils.py
|
switcheo.utils.Request
|
class Request(object):
def __init__(self, api_url='https://test-api.switcheo.network/', api_version="/v2", timeout=30):
self.base_url = api_url.rstrip('/')
self.url = self.base_url + api_version
self.timeout = timeout
def get(self, path, params=None):
"""Perform GET request"""
r = requests.get(url=self.url + path, params=params, timeout=self.timeout)
r.raise_for_status()
return r.json()
def post(self, path, data=None, json_data=None, params=None):
"""Perform POST request"""
r = requests.post(url=self.url + path, data=data, json=json_data, params=params, timeout=self.timeout)
try:
r.raise_for_status()
except requests.exceptions.HTTPError:
raise SwitcheoApiException(r.json().get('error_code'), r.json().get('error_message'), r.json().get('error'))
return r.json()
def status(self):
r = requests.get(url=self.base_url)
r.raise_for_status()
return r.json()
|
class Request(object):
def __init__(self, api_url='https://test-api.switcheo.network/', api_version="/v2", timeout=30):
pass
def get(self, path, params=None):
'''Perform GET request'''
pass
def post(self, path, data=None, json_data=None, params=None):
'''Perform POST request'''
pass
def status(self):
pass
| 5 | 2 | 5 | 0 | 5 | 1 | 1 | 0.1 | 1 | 1 | 1 | 0 | 4 | 3 | 4 | 4 | 26 | 4 | 20 | 11 | 15 | 2 | 20 | 11 | 15 | 2 | 1 | 1 | 5 |
142,257 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/test_switcheo_utils.py
|
switcheo.test_switcheo_utils.TestSwitcheoUtils
|
class TestSwitcheoUtils(unittest.TestCase):
def test_get_epoch_milliseconds(self):
self.assertGreaterEqual(get_epoch_milliseconds(), 13)
def test_num2hexstring(self):
self.assertEqual(num2hexstring(0), '00')
self.assertEqual(num2hexstring(255), 'ff')
self.assertEqual(num2hexstring(256, size=2, little_endian=True), '0001')
self.assertEqual(num2hexstring(2222, size=2, little_endian=True), 'ae08')
def test_num2varint(self):
self.assertEqual(num2varint(0), '00')
self.assertEqual(num2varint(252), 'fc')
self.assertEqual(num2varint(253), 'fdfd00')
self.assertEqual(num2varint(255), 'fdff00')
self.assertEqual(num2varint(256), 'fd0001')
self.assertEqual(num2varint(2222), 'fdae08')
self.assertEqual(num2varint(111111), 'fe07b20100')
self.assertEqual(num2varint(11111111111), 'ffc719469602000000')
def test_reverse_hex(self):
self.assertEqual(reverse_hex('ABCD'), 'CDAB')
self.assertEqual(reverse_hex('0000000005f5e100'), '00e1f50500000000')
def test_stringify_message(self):
json_msg = {"name": "John Smith", "age": 27, "siblings": ["Jane", "Joe"]}
stringify_msg = '{"age":27,"name":"John Smith","siblings":["Jane","Joe"]}'
self.assertEqual(stringify_message(json_msg), stringify_msg)
def test_current_contract_hash(self):
pc = PublicClient()
expected_current_contract_dict = {
'NEO': '58efbb3cca7f436a55b1a05c0f36788d2d9a032e',
'ETH': '0x4d19fd42e780d56ff6464fe9e7d5158aee3d125d',
'QTUM': 'fake_qtum_contract_hash',
'EOS': 'toweredbyob2'
}
self.assertDictEqual(current_contract_hash(pc.contracts), expected_current_contract_dict)
def test_request_get(self):
json_msg = {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}
self.assertDictEqual(r.get(path='/posts/1'), json_msg)
def test_request_post(self):
json_dict = {
'title': 'foo',
'body': 'bar',
'userId': 1}
json_msg = {
'id': 101,
'title': 'foo',
'body': 'bar',
'userId': 1}
self.assertDictEqual(r.post(path='/posts', json_data=json_dict), json_msg)
def test_request_status(self):
self.assertDictEqual(s.status(), {'status': 'ok'})
|
class TestSwitcheoUtils(unittest.TestCase):
def test_get_epoch_milliseconds(self):
pass
def test_num2hexstring(self):
pass
def test_num2varint(self):
pass
def test_reverse_hex(self):
pass
def test_stringify_message(self):
pass
def test_current_contract_hash(self):
pass
def test_request_get(self):
pass
def test_request_post(self):
pass
def test_request_status(self):
pass
| 10 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 9 | 0 | 9 | 81 | 62 | 9 | 53 | 17 | 43 | 0 | 37 | 17 | 27 | 1 | 2 | 0 | 9 |
142,258 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/test_public_client.py
|
switcheo.test_public_client.TestPublicClient
|
class TestPublicClient(unittest.TestCase):
def test_get_exchange_status(self):
exchange_status_dict = {'status': 'ok'}
self.assertDictEqual(pc.get_exchange_status(), exchange_status_dict)
def test_get_exchange_time(self):
exchange_time_dict = {'timestamp': 1533362081336}
self.assertGreater(pc.get_exchange_time()['timestamp'], exchange_time_dict['timestamp'])
def test_get_token_details(self):
exchange_token_list = ['NEO', 'GAS', 'SWTH', 'ETH']
exchange_token_request = pc.get_token_details()
self.assertTrue(set(exchange_token_request.keys()).issuperset(set(exchange_token_list)))
def test_get_candlesticks(self):
candles_key_list = ['time', 'open', 'close', 'high', 'low', 'volume', 'quote_volume']
candles_request = pc.get_candlesticks(pair="SWTH_NEO",
start_time=round(time.time()) - 360000,
end_time=round(time.time()),
interval=60)
for candle in candles_request:
candles_request = list(candle.keys())
self.assertTrue(set(candles_request).issubset(set(candles_key_list)))
def test_get_last_24_hours(self):
last_stats_list = ['pair', 'open', 'close', 'high', 'low', 'volume', 'quote_volume']
last_24_hours_request = pc.get_last_24_hours()
for pair in last_24_hours_request:
last_24_hours_request = list(pair.keys())
self.assertTrue(set(last_24_hours_request).issubset(set(last_stats_list)))
def test_get_last_price(self):
last_price_dict = {
'SWTH': ['ETH', 'NEO']
}
last_price_request = pc.get_last_price()
for pair in last_price_request:
last_price_request[pair] = list(last_price_request[pair].keys())
self.assertTrue(set(last_price_request.keys()).issuperset(set(last_price_dict.keys())))
for pair in last_price_dict:
self.assertTrue(set(last_price_request[pair]).issubset(set(last_price_dict[pair])))
def test_get_offers(self):
offers_list = [{
'id': '023bff30-ca83-453c-90e9-95502b52f492',
'offer_asset': 'SWTH',
'want_asset': 'NEO',
'available_amount': 9509259,
'offer_amount': 9509259,
'want_amount': 9509259,
'address': '7f345d1a031c4099540dbbbc220d4e5640ab2b6f'}]
offers_set_list = set(offers_list[0].keys())
offered_list = pc.get_offers()
self.assertTrue(set(offered_list[0].keys()).issubset(offers_set_list))
offered_set_list = set()
for offer in offered_list:
for key in offer.keys():
offered_set_list.add(key)
self.assertTrue(offered_set_list.issubset(offers_set_list))
offered_list = pc_eth.get_offers(pair="JRC_ETH")
self.assertTrue(set(offered_list[0].keys()).issubset(offers_set_list))
offered_set_list = set()
for offer in offered_list:
for key in offer.keys():
offered_set_list.add(key)
self.assertTrue(offered_set_list.issubset(offers_set_list))
def test_get_trades(self):
trades_key_list = ['id', 'fill_amount', 'take_amount', 'event_time', 'is_buy']
trades_list = pc.get_trades(pair="SWTH_NEO",
limit=1,
start_time=int(round(time.time())) - 2419200,
end_time=int(round(time.time())))
trades_list = trades_list[0].keys()
self.assertTrue(set(trades_list).issubset(set(trades_key_list)))
with self.assertRaises(ValueError):
pc.get_trades(pair="SWTH_NEO", limit=0)
with self.assertRaises(ValueError):
pc.get_trades(pair="SWTH_NEO", limit=1000000)
def test_get_pairs(self):
all_pairs = ['GAS_NEO', 'SWTH_NEO', 'TMN_NEO', 'TKY_NEO', 'LEO_ETH', 'MKR_ETH', 'ETH_WBTC']
neo_pairs = ['GAS_NEO', 'SWTH_NEO', 'ACAT_NEO', 'ASA_NEO', 'AVA_NEO', 'FTWX_NEO', 'MCT_NEO',
'NOS_NEO', 'NRVE_NEO', 'PHX_NEO', 'QLC_NEO', 'SOUL_NEO', 'TKY_NEO', 'TMN_NEO']
self.assertTrue(set(pc.get_pairs(show_inactive=True)).issuperset(set(all_pairs)))
self.assertTrue(set(pc.get_pairs(base="NEO", show_inactive=True)).issuperset(set(neo_pairs)))
def test_get_contracts(self):
contracts_dict = {
'NEO': {
'V1': '0ec5712e0f7c63e4b0fea31029a28cea5e9d551f',
'V1_5': 'c41d8b0c30252ce7e8b6d95e9ce13fdd68d2a5a8',
'V2': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'V3': '58efbb3cca7f436a55b1a05c0f36788d2d9a032e'
},
'ETH': {
'V1': '0x4dcf0244742e72309666db20d367f6dd196e884e',
'V2': '0x4d19fd42e780d56ff6464fe9e7d5158aee3d125d'
},
'EOS': {
'V1': 'toweredbyob2'
},
'QTUM': {
'V1': 'fake_qtum_contract_hash'
}
}
self.assertDictEqual(pc.get_contracts(), contracts_dict)
def test_get_orders(self):
orders_list = [{
'id': 'ecb6ee9e-de8d-46d6-953b-afcc976be1ae',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'pair': 'SWTH_NEO',
'side': 'buy',
'price': '0.000001',
'quantity': '1000000',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '6000000',
'want_amount': '30000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-08T18:39:13.864Z',
'status': 'processed',
'order_status': 'processed',
'txn': None,
'offer_asset_blockchain': 'neo',
'want_asset_blockchain': 'neo',
'broadcast_cutoff_at': '2019-05-04T15:53:04.809Z',
'scheduled_cancellation_at': None,
'counterpart_swap': None,
"unlock_swap_txn": None,
'fills': [],
'fill_groups': [],
'makes': []
}]
switcheo_orders_list = orders_list.copy()
orders_list = orders_list[0].keys()
testnet_scripthash = 'fea2b883725ef2d194c9060f606cd0a0468a2c59'
all_orders = pc.get_orders(address=testnet_scripthash)
switcheo_orders = pc.get_orders(address=testnet_scripthash, pair="SWTH_NEO")
self.assertGreaterEqual(len(all_orders), len(switcheo_orders))
self.assertTrue(set(all_orders[0].keys()).issubset(set(orders_list)))
switcheo_orders_list_set = set()
switcheo_orders_set = set()
for order in switcheo_orders_list:
switcheo_orders_list_set.add(order['offer_asset_id'])
switcheo_orders_list_set.add(order['want_asset_id'])
for order in switcheo_orders:
switcheo_orders_set.add(order['offer_asset_id'])
switcheo_orders_set.add(order['want_asset_id'])
self.assertTrue(switcheo_orders_set.issubset(switcheo_orders_list_set))
def test_get_balance(self):
balance_dict = {
'confirming': {},
'confirmed': {
'GAS': '90000000.0',
'SWTH': '73580203956.0',
'NEO': '113073528.0'},
'locked': {
'GAS': '9509259.0',
'NEO': '4000000.0'}}
balance_dict_set = set(balance_dict.keys())
first_address = ['ca7316f459db1d3b444f57fe1ab875b3a607c200']
second_address = ['fea2b883725ef2d194c9060f606cd0a0468a2c59']
all_addresses = ['ca7316f459db1d3b444f57fe1ab875b3a607c200', 'fea2b883725ef2d194c9060f606cd0a0468a2c59']
contracts = pc.get_contracts()
all_contracts = []
for chain in contracts:
for contract in contracts[chain]:
if chain == 'NEO':
all_contracts.append(contracts[chain][contract])
first_balance_dict = pc.get_balance(addresses=first_address, contracts=all_contracts)
first_balance_dict_set = set(first_balance_dict.keys())
second_balance_dict = pc.get_balance(addresses=second_address, contracts=all_contracts)
second_balance_dict_set = set(second_balance_dict.keys())
all_balance_dict = pc.get_balance(addresses=all_addresses, contracts=all_contracts)
all_balance_dict_set = set(all_balance_dict.keys())
self.assertTrue(first_balance_dict_set.issubset(balance_dict_set))
self.assertTrue(second_balance_dict_set.issubset(balance_dict_set))
self.assertTrue(all_balance_dict_set.issubset(balance_dict_set))
sum_balance_dict = {'confirmed': {
'GAS': str(int(float(first_balance_dict['confirmed']['GAS'])) + int(
float(second_balance_dict['confirmed']['GAS']))),
'NEO': str(int(float(first_balance_dict['confirmed']['NEO'])) + int(
float(second_balance_dict['confirmed']['NEO']))),
'SWTH': str(int(float(first_balance_dict['confirmed']['SWTH'])) + int(
float(second_balance_dict['confirmed']['SWTH']))),
}}
self.assertDictEqual(all_balance_dict['confirmed'], sum_balance_dict['confirmed'])
|
class TestPublicClient(unittest.TestCase):
def test_get_exchange_status(self):
pass
def test_get_exchange_time(self):
pass
def test_get_token_details(self):
pass
def test_get_candlesticks(self):
pass
def test_get_last_24_hours(self):
pass
def test_get_last_price(self):
pass
def test_get_offers(self):
pass
def test_get_trades(self):
pass
def test_get_pairs(self):
pass
def test_get_contracts(self):
pass
def test_get_orders(self):
pass
def test_get_balance(self):
pass
| 13 | 0 | 16 | 0 | 15 | 0 | 2 | 0 | 1 | 6 | 0 | 0 | 12 | 0 | 12 | 84 | 199 | 14 | 185 | 61 | 172 | 0 | 106 | 61 | 93 | 5 | 2 | 3 | 25 |
142,259 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/test_authenticated_client.py
|
switcheo.test_authenticated_client.TestAuthenticatedClient
|
class TestAuthenticatedClient(unittest.TestCase):
def test_deposit(self):
deposited_dict = {'result': 'ok'}
deposit_dict = ac.deposit(asset="SWTH", amount=0.000001, private_key=kp)
deposit_dict.pop('transaction_hash')
self.assertDictEqual(deposit_dict, deposited_dict)
deposit_dict = ac.deposit(asset="GAS", amount=0.000001, private_key=kp)
deposit_dict.pop('transaction_hash')
self.assertDictEqual(deposit_dict, deposited_dict)
def test_withdrawal(self):
swth_withdrawn_dict = {
'event_type': 'withdrawal',
'amount': '-100',
'asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'blockchain': 'neo',
'reason_code': 9,
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'transaction_hash': None,
'contract_hash': '58efbb3cca7f436a55b1a05c0f36788d2d9a032e',
'approval_transaction_hash': None,
'group_index': 0,
'params_hash': None
}
swth_withdrawal_dict = ac.withdrawal(asset="SWTH", amount=0.000001, private_key=kp)
swth_withdrawal_dict.pop('id')
swth_withdrawal_dict.pop('status')
swth_withdrawal_dict.pop('created_at')
swth_withdrawal_dict.pop('updated_at')
self.assertDictEqual(swth_withdrawal_dict, swth_withdrawn_dict)
gas_withdrawn_dict = {
'event_type': 'withdrawal',
'amount': '-100',
'asset_id': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'blockchain': 'neo',
'reason_code': 9,
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'transaction_hash': None,
'contract_hash': '58efbb3cca7f436a55b1a05c0f36788d2d9a032e',
'approval_transaction_hash': None,
'group_index': 0,
'params_hash': None
}
gas_withdrawal_dict = ac.withdrawal(asset="GAS", amount=0.000001, private_key=kp)
gas_withdrawal_dict.pop('id')
gas_withdrawal_dict.pop('status')
gas_withdrawal_dict.pop('created_at')
gas_withdrawal_dict.pop('updated_at')
self.assertDictEqual(gas_withdrawal_dict, gas_withdrawn_dict)
def test_create_and_cancel_order(self):
order = ac.order(pair="SWTH_NEO", side="buy",
price=0.00001, quantity=10000, private_key=kp,
use_native_token=True, order_type="limit")
ac.cancel_order(order_id=order['id'], private_key=kp)
testnet_scripthash = 'fea2b883725ef2d194c9060f606cd0a0468a2c59'
cancelled = False
for trade in ac.get_orders(address=testnet_scripthash):
if trade['id'] == order['id'] and\
trade['status'] == 'processed' and\
trade['makes'][0]['status'] in ['cancelled', 'cancelling']:
cancelled = True
self.assertTrue(cancelled)
def test_order_filter(self):
# Test side filter
with self.assertRaises(ValueError):
ac.order(pair="SWTH_NEO", side="test",
price=0.0001, quantity=100, private_key=kp,
use_native_token=True, order_type="limit")
# Test order_type filter
with self.assertRaises(ValueError):
ac.order(pair="SWTH_NEO", side="buy",
price=0.0001, quantity=100, private_key=kp,
use_native_token=True, order_type="test")
|
class TestAuthenticatedClient(unittest.TestCase):
def test_deposit(self):
pass
def test_withdrawal(self):
pass
def test_create_and_cancel_order(self):
pass
def test_order_filter(self):
pass
| 5 | 0 | 18 | 1 | 17 | 1 | 2 | 0.03 | 1 | 1 | 0 | 0 | 4 | 0 | 4 | 76 | 78 | 6 | 70 | 15 | 65 | 2 | 38 | 15 | 33 | 3 | 2 | 2 | 6 |
142,260 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/streaming_client.py
|
switcheo.streaming_client.TradeEventsNamespace
|
class TradeEventsNamespace(SocketIOClientNamespace):
def __init__(self):
self.lock = threading.Lock()
self.namespace = '/v2/trades'
self.trade_events = {}
SocketIOClientNamespace.__init__(self, namespace=self.namespace)
def on_connect(self):
pass
def on_disconnect(self):
pass
def on_join(self):
pass
def on_all(self, data):
self.lock.acquire()
self.trade_events[data["room"]["pair"]] = data
self.lock.release()
digest_hash = data["digest"]
trades = data["trades"]
trade_digest_hash = sha1_hash_digest(stringify_message(trades))
if digest_hash != trade_digest_hash:
self.emit(event="leave", data=data["room"], namespace='/v2/trades')
self.emit(event="join", data=data["room"], namespace='/v2/trades')
def on_updates(self, data):
update_digest = data["digest"]
update_pair = data["room"]["pair"]
update_events = data["events"]
update_limit = data["limit"]
self.lock.acquire()
self.trade_events[update_pair]["trades"] = update_events + \
self.trade_events[update_pair]["trades"]
trade_slice = update_limit - 1
self.trade_events[update_pair]["trades"] = self.trade_events[update_pair]["trades"][0:trade_slice]
trades = self.trade_events[update_pair]["trades"]
self.lock.release()
trade_digest_hash = sha1_hash_digest(stringify_message(trades))
if update_digest != trade_digest_hash:
self.emit(event="leave", data=data["room"], namespace='/v2/trades')
self.emit(event="join", data=data["room"], namespace='/v2/trades')
|
class TradeEventsNamespace(SocketIOClientNamespace):
def __init__(self):
pass
def on_connect(self):
pass
def on_disconnect(self):
pass
def on_join(self):
pass
def on_all(self, data):
pass
def on_updates(self, data):
pass
| 7 | 0 | 6 | 0 | 6 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 6 | 3 | 6 | 6 | 44 | 6 | 38 | 20 | 31 | 0 | 37 | 20 | 30 | 2 | 1 | 1 | 8 |
142,261 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/test_fixed8.py
|
switcheo.test_fixed8.TestFixed8
|
class TestFixed8(unittest.TestCase):
def test_fixed8_inheritance(self):
self.assertEqual(SwitcheoFixed8(2050000).ToString(), '0.0205')
self.assertEqual(SwitcheoFixed8(100000000).ToInt(), 1)
def test_to_hex(self):
self.assertEqual(SwitcheoFixed8(205).toHex(), '00000004c5e52d00')
self.assertEqual(SwitcheoFixed8(0.0205).toHex(), '00000000001f47d0')
def test_to_reverse_hex(self):
self.assertEqual(SwitcheoFixed8(205).toReverseHex(), '002de5c504000000')
self.assertEqual(SwitcheoFixed8(0.0205).toReverseHex(), 'd0471f0000000000')
def test_num2fixed8(self):
self.assertEqual(num2fixed8(205), '002de5c504000000')
self.assertEqual(num2fixed8(0.0205), 'd0471f0000000000')
with self.assertRaises(ValueError):
num2fixed8(205, size=1.1)
|
class TestFixed8(unittest.TestCase):
def test_fixed8_inheritance(self):
pass
def test_to_hex(self):
pass
def test_to_reverse_hex(self):
pass
def test_num2fixed8(self):
pass
| 5 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 2 | 1 | 0 | 4 | 0 | 4 | 76 | 19 | 4 | 15 | 5 | 10 | 0 | 15 | 5 | 10 | 1 | 2 | 1 | 4 |
142,262 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/public_client.py
|
switcheo.public_client.PublicClient
|
class PublicClient(object):
"""
This class allows the user to interact with the Switcheo decentralized exchange API to retrieve information about
the available options on the exchange, including system health, time, trade offers, etc.
"""
def __init__(self,
blockchain="neo",
contract_version='V3',
api_url='https://test-api.switcheo.network/',
api_version='/v2'):
"""
:param blockchain: Choose which blockchain to trade on. Allowed value are neo (future eth and qtum)
:type blockchain: str
:param api_url: The URL for the Switcheo API endpoint.
:type api_url: str
:param api_version: Choose the version of the Switcho API to use.
:type api_version: str
"""
self.request = Request(api_url=api_url, api_version=api_version, timeout=30)
self.blockchain = blockchain
self.blockchain_key = blockchain.upper()
self.contracts = self.get_contracts()
self.contract_version = contract_version.upper()
self.contract_hash = self.contracts[self.blockchain_key][self.contract_version]
self.current_contract_hash = self.get_latest_contracts()[self.blockchain_key]
def get_exchange_status(self):
"""
Function to fetch the state of the exchange.
Execution of this function is as follows::
get_exchange_status()
The expected return result for this function is as follows::
{
'status': 'ok'
}
:return: Dictionary in the form of a JSON message with the exchange status.
"""
return self.request.status()
def get_exchange_time(self):
"""
Function to fetch the time on the exchange in to synchronized server time.
Execution of this function is as follows::
get_exchange_time()
The expected return result for this function is as follows::
{
'timestamp': 1533362081336
}
:return: Dictionary in the form of a JSON message with the exchange epoch time in milliseconds.
"""
return self.request.get(path='/exchange/timestamp')
def get_contracts(self):
"""
Function to fetch the contract hashes for each smart contract deployed on the defined blockchain.
Execution of this function is as follows::
get_contracts()
The expected return result for this function is as follows::
{
'NEO': {
'V1': '0ec5712e0f7c63e4b0fea31029a28cea5e9d551f',
'V1_5': '01bafeeafe62e651efc3a530fde170cf2f7b09bd',
'V2': '91b83e96f2a7c4fdf0c1688441ec61986c7cae26'
},
'ETH': {
'V1': '0x0000000000000000000000000000000000000000'
}
}
:return: Dictionary containing the list of smart contract hashes per blockchain and version.
"""
return self.request.get(path='/exchange/contracts')
def get_latest_contracts(self):
"""
Function to fetch the active contract hash for each smart contract deployed on the defined blockchain.
Execution of this function is as follows::
get_latest_contracts()
The expected return result for this function is as follows::
{
"NEO": "d524fbb2f83f396368bc0183f5e543cae54ef532",
"ETH": "0x6ee18298fd6bc2979df9d27569842435a7d55e65",
"EOS": "oboluswitch4",
"QTUM": "0x2b25406b0000c3661e9c88890690fd4b5c7b4234"
}
:return: Dictionary containing the latest smart contract hash for each blockchain.
"""
return self.request.get(path='/exchange/latest_contracts')
def get_pairs(self, base=None, show_details=False, show_inactive=False):
"""
Function to fetch a list of trading pairs offered on the Switcheo decentralized exchange.
Execution of this function is as follows::
get_pairs() # Fetch all pairs
get_pairs(base="SWTH") # Fetch only SWTH base pairs
get_pairs(show_details=True) # Fetch all pairs with extended information !Attention return value changes!
The expected return result for this function is as follows::
[
'GAS_NEO',
'SWTH_NEO',
'MCT_NEO',
'NKN_NEO',
....
'SWTH_GAS',
'MCT_GAS',
'NKN_GAS',
....
'MCT_SWTH',
'NKN_SWTH'
]
If you use the show_details parameter the server return a list with dictionaries as follows::
[
{'name': 'GAS_NEO', 'precision': 3},
{'name': 'SWTH_NEO', 'precision': 6},
{'name': 'ACAT_NEO', 'precision': 8},
{'name': 'APH_NEO', 'precision': 5},
{'name': 'ASA_NEO', 'precision': 8},
....
]
:param base: The base trade pair to optionally filter available trade pairs.
:type base: str
:param show_details: Extended information for the pairs.
:type show_details: bool
:return: List of trade pairs available for trade on Switcheo.
"""
api_params = {}
if show_details:
api_params["show_details"] = show_details
if show_inactive:
api_params["show_inactive"] = show_inactive
if base is not None and base in ["NEO", "GAS", "SWTH", "USD", "ETH"]:
api_params["bases"] = [base]
return self.request.get(path='/exchange/pairs', params=api_params)
def get_token_details(self, show_listing_details=False, show_inactive=False):
"""
Function to fetch the available tokens available to trade on the Switcheo exchange.
Execution of this function is as follows::
get_token_details()
get_token_details(show_listing_details=True)
get_token_details(show_inactive=True)
get_token_details(show_listing_details=True, show_inactive=True)
The expected return result for this function is as follows::
{
'NEO': {
'hash': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'decimals': 8
},
'GAS': {
'hash': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'decimals': 8
},
'SWTH': {
'hash': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'decimals': 8
},
...
}
:param show_listing_details: Parameter flag to indicate whether or not to show the token listing details.
:type show_listing_details: bool
:param show_inactive: Flag to return the tokens that are no longer traded on the Switcheo Exchange.
:type show_inactive: bool
:return: Dictionary in the form of a JSON message with the available tokens for trade on the Switcheo exchange.
"""
api_params = {
"show_listing_details": show_listing_details,
"show_inactive": show_inactive
}
return self.request.get(path='/exchange/tokens', params=api_params)
def get_exchange_message(self):
"""
Function to fetch the Switcheo Exchange message to ensure pertinent information is handled gracefully.
Execution of this function is as follows::
get_exchange_message()
The expected return result for this function is as follows::
{
'message': 'Welcome to Switcheo Beta.',
'message_type': 'info'
}
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
"""
return self.request.get(path='/exchange/announcement_message')
def get_exchange_fees(self):
"""
Function to fetch the Switcheo Exchange fees to assist with automated trading calculations.
Execution of this function is as follows::
get_exchange_fees()
The expected return result for this function is as follows::
[
{
"maker": {
"default": 0
},
"taker": {
"default": 0.002
},
"network_fee_subsidy_threshold": {
"neo": 0.1,
"eth": 0.1
},
"max_taker_fee_ratio": {
"neo": 0.005,
"eth": 0.1
},
"native_fee_discount": 0.75,
"native_fee_asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
"enforce_native_fees": [
"RHT",
"RHTC"
],
"native_fee_exchange_rates": {
"NEO": "952.38095238",
"GAS": "297.14285714",
...
"ETH": "0",
"JRC": "0",
"SWC": "0"
},
"network_fees": {
"eth": "2466000000000000",
"neo": "200000"
},
"network_fees_for_wdl": {
"eth": "873000000000000",
"neo": "0"
}
}
]
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
"""
return self.request.get(path='/fees')
def get_exchange_swap_pairs(self):
"""
Function to fetch the Switcheo Exchange list of atomic swap pairs.
Execution of this function is as follows::
get_exchange_swap_pairs()
The expected return result for this function is as follows::
[
"SWTH_ETH",
"NEO_ETH",
"EOS_ETH",
"NEO_DAI",
"SDUSD_DAI",
"EOS_NEO",
"NEO_WBTC"
]
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
"""
return self.request.get(path='/exchange/swap_pairs')
def get_exchange_swap_pricing(self, pair):
"""
Function to fetch the swap pricing for the pair requested.
Execution of this function is as follows::
get_exchange_swap_pricing(pair="SWTH_ETH")
The expected return result for this function is as follows::
{
"buy": {
"x": "740144428000000",
"y": "96969492513000000000",
"k": "71771429569484667564000000000000000"
},
"sell": {
"x": "96969492513000000000",
"y": "740144428000000",
"k": "71771429569484667564000000000000000"
}
}
:param pair: The trading pair used to request candle statistics.
:type pair: str
:return: List of dictionaries containing the candles statistics based on the parameter filters.
"""
api_params = {
"pair": pair
}
return self.request.get(path='/exchange/swap_pricing', params=api_params)
def get_exchange_swap_contracts(self):
"""
Function to fetch the Switcheo Exchange list of atomic swap contracts.
Execution of this function is as follows::
get_exchange_swap_contracts()
The expected return result for this function is as follows::
{
"ETH": {
"V1": "0xeab64b2320a1fc1e65f4c7253385ec18e4b4313b"
}
}
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
"""
return self.request.get(path='/exchange/atomic_swap_contracts')
def get_candlesticks(self, pair, start_time, end_time, interval):
"""
Function to fetch trading metrics from the past 24 hours for all trading pairs offered on the exchange.
Execution of this function is as follows::
get_candlesticks(pair="SWTH_NEO",
start_time=round(time.time()) - 350000,
end_time=round(time.time()),
interval=360))
The expected return result for this function is as follows::
[{
'time': '1533168000',
'open': '0.00046835',
'close': '0.00046835',
'high': '0.00046835',
'low': '0.00046835',
'volume': '240315335.0',
'quote_volume': '513110569018.0'
},{
'time': '1533081600',
'open': '0.00046835',
'close': '0.00046835',
'high': '0.00046835',
'low': '0.00046835',
'volume': '1170875.0',
'quote_volume': '2500000000.0'
},
...
]
:param pair: The trading pair used to request candle statistics.
:type pair: str
:param start_time: The start time (in epoch seconds) range for collecting candle statistics.
:type start_time: int
:param end_time: The end time (in epoch seconds) range for collecting candle statistics.
:type end_time: int
:param interval: The time interval (in minutes) for candle statistics. Allowed values: 1, 5, 30, 60, 360, 1440
:type interval: int
:return: List of dictionaries containing the candles statistics based on the parameter filters.
"""
api_params = {
"pair": pair,
"interval": interval,
"start_time": start_time,
"end_time": end_time,
"contract_hash": self.contract_hash
}
return self.request.get(path='/tickers/candlesticks', params=api_params)
def get_last_24_hours(self):
"""
Function to fetch trading metrics from the past 24 hours for all trading pairs offered on the exchange.
Execution of this function is as follows::
get_last_24_hours()
The expected return result for this function is as follows::
[{
'pair': 'SWTH_NEO',
'open': '0.000407',
'close': 0.00040911',
'high': '0.00041492',
'low': '0.00036',
'volume': '34572662197.0',
'quote_volume': '86879788270667.0'
},{
'pair': 'GAS_NEO',
'open': '0.3',
'close': '0.30391642',
'high': '0.352',
'low': '0.2925',
'volume': '4403569005.0',
'quote_volume': '14553283004.0'
},{
....
}]
:return: List of dictionaries containing the statistics of each trading pair over the last 24 hours.
"""
return self.request.get(path='/tickers/last_24_hours')
def get_last_price(self, symbols=None, bases=None):
"""
Function to fetch the most recently executed trade on the order book for each trading pair.
Execution of this function is as follows::
get_last_price()
get_last_price(symbols=['SWTH','GAS'])
get_last_price(bases=['NEO'])
get_last_price(symbols=['SWTH','GAS'], bases=['NEO'])
The expected return result for this function is as follows::
{
'SWTH': {
'GAS': '0.0015085',
'NEO': '0.00040911'
},
'GAS': {
'NEO': '0.30391642'
},
....
}
:param symbols: The trading symbols to retrieve the last price on the Switcheo Exchange.
:type symbols: list
:param bases: The base pair to retrieve the last price of symbols on the Switcheo Exchange.
:type bases: list
:return: Dictionary of trade symbols with the most recently executed trade price.
"""
api_params = {}
if symbols is not None:
api_params['symbols'] = symbols
if bases is not None:
api_params['bases'] = bases
return self.request.get(path='/tickers/last_price', params=api_params)
def get_offers(self, pair="SWTH_NEO"):
"""
Function to fetch the open orders on the order book for the trade pair requested.
Execution of this function is as follows::
get_offers(pair="SWTH_NEO")
The expected return result for this function is as follows::
[{
'id': '2716c0ca-59bb-4c86-8ee4-6b9528d0e5d2',
'offer_asset': 'GAS',
'want_asset': 'NEO',
'available_amount': 9509259,
'offer_amount': 30000000,
'want_amount': 300000000,
'address': '7f345d1a031c4099540dbbbc220d4e5640ab2b6f'
}, {
....
}]
:param pair: The trading pair that will be used to request open offers on the order book.
:type pair: str
:return: List of dictionaries consisting of the open offers for the requested trading pair.
"""
api_params = {
"pair": pair,
"contract_hash": self.contract_hash
}
return self.request.get(path='/offers', params=api_params)
def get_offer_book(self, pair="SWTH_NEO"):
"""
Function to fetch the open orders formatted on the order book for the trade pair requested.
Execution of this function is as follows::
get_offer_book(pair="SWTH_NEO")
The expected return result for this function is as follows::
{
'asks': [{
'price': '0.00068499',
'quantity': '43326.8348443'
}, {
'price': '0.000685',
'quantity': '59886.34'
}, {
....
}],
'bids': [{
'price': '0.00066602',
'quantity': '3255.99999999'
}, {
'price': '0.00066601',
'quantity': '887.99999999'
}, {
....
}]
}
:param pair: The trading pair that will be used to request open offers on the order book.
:type pair: str
:return: List of dictionaries consisting of the open offers for the requested trading pair.
"""
api_params = {
"pair": pair,
"contract_hash": self.contract_hash
}
return self.request.get(path='/offers/book', params=api_params)
def get_trades(self, pair="SWTH_NEO", start_time=None, end_time=None, limit=5000):
"""
Function to fetch a list of filled trades for the parameters requested.
Execution of this function is as follows::
get_trades(pair="SWTH_NEO", limit=3)
The expected return result for this function is as follows::
[{
'id': '15bb16e2-7a80-4de1-bb59-bcaff877dee0',
'fill_amount': 100000000,
'take_amount': 100000000,
'event_time': '2018-08-04T15:00:12.634Z',
'is_buy': True
}, {
'id': 'b6f9e530-60ff-46ff-9a71-362097a2025e',
'fill_amount': 47833882,
'take_amount': 97950000000,
'event_time': '2018-08-03T02:44:47.706Z',
'is_buy': True
}, {
'id': '7a308ccc-b7f5-46a3-bf6b-752ab076cc9f',
'fill_amount': 1001117,
'take_amount': 2050000000,
'event_time': '2018-08-03T02:32:50.703Z',
'is_buy': True
}]
:param pair: The trading pair that will be used to request filled trades.
:type pair: str
:param start_time: Only return trades after this time (in epoch seconds).
:type start_time: int
:param end_time: Only return trades before this time (in epoch seconds).
:type end_time: int
:param limit: The number of filled trades to return. Min: 1, Max: 10000, Default: 5000
:type limit: int
:return: List of dictionaries consisting of filled orders that meet requirements of the parameters passed to it.
"""
if limit > 10000 or limit < 1:
raise ValueError("Attempting to request more trades than allowed by the API.")
api_params = {
"blockchain": self.blockchain,
"pair": pair,
"contract_hash": self.contract_hash
}
if start_time is not None:
api_params['from'] = start_time
if end_time is not None:
api_params['to'] = end_time
if limit != 5000:
api_params['limit'] = limit
return self.request.get(path='/trades', params=api_params)
def get_recent_trades(self, pair="SWTH_NEO"):
"""
Function to fetch a list of the 20 most recently filled trades for the parameters requested.
Execution of this function is as follows::
get_recent_trades(pair="SWTH_NEO")
The expected return result for this function is as follows::
[{
'id': '15bb16e2-7a80-4de1-bb59-bcaff877dee0',
'fill_amount': 100000000,
'take_amount': 100000000,
'event_time': '2018-08-04T15:00:12.634Z',
'is_buy': True
}, {
'id': 'b6f9e530-60ff-46ff-9a71-362097a2025e',
'fill_amount': 47833882,
'take_amount': 97950000000,
'event_time': '2018-08-03T02:44:47.706Z',
'is_buy': True
}, ...., {
'id': '7a308ccc-b7f5-46a3-bf6b-752ab076cc9f',
'fill_amount': 1001117,
'take_amount': 2050000000,
'event_time': '2018-08-03T02:32:50.703Z',
'is_buy': True
}]
:param pair: The trading pair that will be used to request filled trades.
:type pair: str
:return: List of 20 dictionaries consisting of filled orders for the trade pair.
"""
api_params = {
"pair": pair
}
return self.request.get(path='/trades/recent', params=api_params)
def get_orders(self, address, chain_name='NEO', contract_version='V3', pair=None, from_epoch_time=None,
order_status=None, before_id=None, limit=50):
"""
Function to fetch the order history of the given address.
Execution of this function is as follows::
get_orders(address=neo_get_scripthash_from_address(address=address))
The expected return result for this function is as follows::
[{
'id': '7cbdf481-6acf-4bf3-a1ed-4773f31e6931',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '53718500',
'want_amount': '110000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-03T02:44:47.692Z',
'status': 'processed',
'fills': [{
'id': 'b6f9e530-60ff-46ff-9a71-362097a2025e',
'offer_hash': '95b3b03be0bff8f58aa86a8dd599700bbaeaffc05078329d5b726b6b995f4cda',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'fill_amount': '47833882',
'want_amount': '97950000000',
'filled_amount': '',
'fee_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'fee_amount': '73462500',
'price': '0.00048835',
'txn': None,
'status': 'success',
'created_at': '2018-08-03T02:44:47.706Z',
'transaction_hash': '694745a09e33845ec008cfb79c73986a556e619799ec73274f82b30d85bda13a'
}],
'makes': [{
'id': '357088a0-cc80-49ab-acdd-980589c2d7d8',
'offer_hash': '420cc85abf02feaceb1bcd91489a0c1949c972d2a9a05ae922fa15d79de80c00',
'available_amount': '0',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '5884618',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '12050000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.000488350041493775933609958506224066390041494',
'status': 'cancelled',
'created_at': '2018-08-03T02:44:47.708Z',
'transaction_hash': '1afa946546550151bbbd19f197a87cec92e9be58c44ec431cae42076298548b7',
'trades': []
}]
}, {
....
}]
:param address: The ScriptHash of the address to filter orders for.
:type address: str
:param pair: The trading pair to filter order requests on.
:type pair: str
:param chain_name: The name of the chain to find orders against.
:type chain_name: str
:param contract_version: The version of the contract to find orders against.
:type contract_version: str
:param from_epoch_time: Only return orders that are last updated at or after this time.
:type from_epoch_time: int
:param order_status: Only return orders have this status. Possible values are open, cancelled, completed.
:type order_status: str
:param before_id: Only return orders that are created before the order with this id.
:type before_id: str
:param limit: Only return up to this number of orders (min: 1, max: 200, default: 50).
:type limit: int
:return: List of dictionaries containing the orders for the given NEO address and (optional) trading pair.
"""
api_params = {
"address": address,
"contract_hash": self.get_contracts()[chain_name.upper()][contract_version.upper()],
"limit": limit
}
if pair is not None:
api_params['pair'] = pair
if from_epoch_time is not None:
api_params['from_epoch_time'] = from_epoch_time
if order_status is not None:
api_params['order_status'] = order_status
if before_id is not None:
api_params['before_id'] = before_id
return self.request.get(path='/orders', params=api_params)
def get_balance(self, addresses, contracts):
"""
Function to fetch the current account balance for the given address in the Switcheo smart contract.
Execution of this function is as follows::
get_balance(address=neo_get_scripthash_from_address(address=address))
The expected return result for this function is as follows::
{
'confirming': {},
'confirmed': {
'GAS': '100000000.0',
'SWTH': '97976537500.0',
'NEO': '52166118.0'
},
'locked': {}
}
:param addresses: The ScriptHash of the address(es) to retrieve its Smart Contract balance.
:type addresses: list
:param contracts: The contract hash(es) to retrieve all addresses Smart Contract balance.
:type contracts: list
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
"""
api_params = {
"addresses[]": addresses,
"contract_hashes[]": contracts
}
return self.request.get(path='/balances', params=api_params)
|
class PublicClient(object):
'''
This class allows the user to interact with the Switcheo decentralized exchange API to retrieve information about
the available options on the exchange, including system health, time, trade offers, etc.
'''
def __init__(self,
blockchain="neo",
contract_version='V3',
api_url='https://test-api.switcheo.network/',
api_version='/v2'):
'''
:param blockchain: Choose which blockchain to trade on. Allowed value are neo (future eth and qtum)
:type blockchain: str
:param api_url: The URL for the Switcheo API endpoint.
:type api_url: str
:param api_version: Choose the version of the Switcho API to use.
:type api_version: str
'''
pass
def get_exchange_status(self):
'''
Function to fetch the state of the exchange.
Execution of this function is as follows::
get_exchange_status()
The expected return result for this function is as follows::
{
'status': 'ok'
}
:return: Dictionary in the form of a JSON message with the exchange status.
'''
pass
def get_exchange_time(self):
'''
Function to fetch the time on the exchange in to synchronized server time.
Execution of this function is as follows::
get_exchange_time()
The expected return result for this function is as follows::
{
'timestamp': 1533362081336
}
:return: Dictionary in the form of a JSON message with the exchange epoch time in milliseconds.
'''
pass
def get_contracts(self):
'''
Function to fetch the contract hashes for each smart contract deployed on the defined blockchain.
Execution of this function is as follows::
get_contracts()
The expected return result for this function is as follows::
{
'NEO': {
'V1': '0ec5712e0f7c63e4b0fea31029a28cea5e9d551f',
'V1_5': '01bafeeafe62e651efc3a530fde170cf2f7b09bd',
'V2': '91b83e96f2a7c4fdf0c1688441ec61986c7cae26'
},
'ETH': {
'V1': '0x0000000000000000000000000000000000000000'
}
}
:return: Dictionary containing the list of smart contract hashes per blockchain and version.
'''
pass
def get_latest_contracts(self):
'''
Function to fetch the active contract hash for each smart contract deployed on the defined blockchain.
Execution of this function is as follows::
get_latest_contracts()
The expected return result for this function is as follows::
{
"NEO": "d524fbb2f83f396368bc0183f5e543cae54ef532",
"ETH": "0x6ee18298fd6bc2979df9d27569842435a7d55e65",
"EOS": "oboluswitch4",
"QTUM": "0x2b25406b0000c3661e9c88890690fd4b5c7b4234"
}
:return: Dictionary containing the latest smart contract hash for each blockchain.
'''
pass
def get_pairs(self, base=None, show_details=False, show_inactive=False):
'''
Function to fetch a list of trading pairs offered on the Switcheo decentralized exchange.
Execution of this function is as follows::
get_pairs() # Fetch all pairs
get_pairs(base="SWTH") # Fetch only SWTH base pairs
get_pairs(show_details=True) # Fetch all pairs with extended information !Attention return value changes!
The expected return result for this function is as follows::
[
'GAS_NEO',
'SWTH_NEO',
'MCT_NEO',
'NKN_NEO',
....
'SWTH_GAS',
'MCT_GAS',
'NKN_GAS',
....
'MCT_SWTH',
'NKN_SWTH'
]
If you use the show_details parameter the server return a list with dictionaries as follows::
[
{'name': 'GAS_NEO', 'precision': 3},
{'name': 'SWTH_NEO', 'precision': 6},
{'name': 'ACAT_NEO', 'precision': 8},
{'name': 'APH_NEO', 'precision': 5},
{'name': 'ASA_NEO', 'precision': 8},
....
]
:param base: The base trade pair to optionally filter available trade pairs.
:type base: str
:param show_details: Extended information for the pairs.
:type show_details: bool
:return: List of trade pairs available for trade on Switcheo.
'''
pass
def get_token_details(self, show_listing_details=False, show_inactive=False):
'''
Function to fetch the available tokens available to trade on the Switcheo exchange.
Execution of this function is as follows::
get_token_details()
get_token_details(show_listing_details=True)
get_token_details(show_inactive=True)
get_token_details(show_listing_details=True, show_inactive=True)
The expected return result for this function is as follows::
{
'NEO': {
'hash': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'decimals': 8
},
'GAS': {
'hash': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'decimals': 8
},
'SWTH': {
'hash': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'decimals': 8
},
...
}
:param show_listing_details: Parameter flag to indicate whether or not to show the token listing details.
:type show_listing_details: bool
:param show_inactive: Flag to return the tokens that are no longer traded on the Switcheo Exchange.
:type show_inactive: bool
:return: Dictionary in the form of a JSON message with the available tokens for trade on the Switcheo exchange.
'''
pass
def get_exchange_message(self):
'''
Function to fetch the Switcheo Exchange message to ensure pertinent information is handled gracefully.
Execution of this function is as follows::
get_exchange_message()
The expected return result for this function is as follows::
{
'message': 'Welcome to Switcheo Beta.',
'message_type': 'info'
}
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
'''
pass
def get_exchange_fees(self):
'''
Function to fetch the Switcheo Exchange fees to assist with automated trading calculations.
Execution of this function is as follows::
get_exchange_fees()
The expected return result for this function is as follows::
[
{
"maker": {
"default": 0
},
"taker": {
"default": 0.002
},
"network_fee_subsidy_threshold": {
"neo": 0.1,
"eth": 0.1
},
"max_taker_fee_ratio": {
"neo": 0.005,
"eth": 0.1
},
"native_fee_discount": 0.75,
"native_fee_asset_id": "ab38352559b8b203bde5fddfa0b07d8b2525e132",
"enforce_native_fees": [
"RHT",
"RHTC"
],
"native_fee_exchange_rates": {
"NEO": "952.38095238",
"GAS": "297.14285714",
...
"ETH": "0",
"JRC": "0",
"SWC": "0"
},
"network_fees": {
"eth": "2466000000000000",
"neo": "200000"
},
"network_fees_for_wdl": {
"eth": "873000000000000",
"neo": "0"
}
}
]
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
'''
pass
def get_exchange_swap_pairs(self):
'''
Function to fetch the Switcheo Exchange list of atomic swap pairs.
Execution of this function is as follows::
get_exchange_swap_pairs()
The expected return result for this function is as follows::
[
"SWTH_ETH",
"NEO_ETH",
"EOS_ETH",
"NEO_DAI",
"SDUSD_DAI",
"EOS_NEO",
"NEO_WBTC"
]
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
'''
pass
def get_exchange_swap_pricing(self, pair):
'''
Function to fetch the swap pricing for the pair requested.
Execution of this function is as follows::
get_exchange_swap_pricing(pair="SWTH_ETH")
The expected return result for this function is as follows::
{
"buy": {
"x": "740144428000000",
"y": "96969492513000000000",
"k": "71771429569484667564000000000000000"
},
"sell": {
"x": "96969492513000000000",
"y": "740144428000000",
"k": "71771429569484667564000000000000000"
}
}
:param pair: The trading pair used to request candle statistics.
:type pair: str
:return: List of dictionaries containing the candles statistics based on the parameter filters.
'''
pass
def get_exchange_swap_contracts(self):
'''
Function to fetch the Switcheo Exchange list of atomic swap contracts.
Execution of this function is as follows::
get_exchange_swap_contracts()
The expected return result for this function is as follows::
{
"ETH": {
"V1": "0xeab64b2320a1fc1e65f4c7253385ec18e4b4313b"
}
}
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
'''
pass
def get_candlesticks(self, pair, start_time, end_time, interval):
'''
Function to fetch trading metrics from the past 24 hours for all trading pairs offered on the exchange.
Execution of this function is as follows::
get_candlesticks(pair="SWTH_NEO",
start_time=round(time.time()) - 350000,
end_time=round(time.time()),
interval=360))
The expected return result for this function is as follows::
[{
'time': '1533168000',
'open': '0.00046835',
'close': '0.00046835',
'high': '0.00046835',
'low': '0.00046835',
'volume': '240315335.0',
'quote_volume': '513110569018.0'
},{
'time': '1533081600',
'open': '0.00046835',
'close': '0.00046835',
'high': '0.00046835',
'low': '0.00046835',
'volume': '1170875.0',
'quote_volume': '2500000000.0'
},
...
]
:param pair: The trading pair used to request candle statistics.
:type pair: str
:param start_time: The start time (in epoch seconds) range for collecting candle statistics.
:type start_time: int
:param end_time: The end time (in epoch seconds) range for collecting candle statistics.
:type end_time: int
:param interval: The time interval (in minutes) for candle statistics. Allowed values: 1, 5, 30, 60, 360, 1440
:type interval: int
:return: List of dictionaries containing the candles statistics based on the parameter filters.
'''
pass
def get_last_24_hours(self):
'''
Function to fetch trading metrics from the past 24 hours for all trading pairs offered on the exchange.
Execution of this function is as follows::
get_last_24_hours()
The expected return result for this function is as follows::
[{
'pair': 'SWTH_NEO',
'open': '0.000407',
'close': 0.00040911',
'high': '0.00041492',
'low': '0.00036',
'volume': '34572662197.0',
'quote_volume': '86879788270667.0'
},{
'pair': 'GAS_NEO',
'open': '0.3',
'close': '0.30391642',
'high': '0.352',
'low': '0.2925',
'volume': '4403569005.0',
'quote_volume': '14553283004.0'
},{
....
}]
:return: List of dictionaries containing the statistics of each trading pair over the last 24 hours.
'''
pass
def get_last_price(self, symbols=None, bases=None):
'''
Function to fetch the most recently executed trade on the order book for each trading pair.
Execution of this function is as follows::
get_last_price()
get_last_price(symbols=['SWTH','GAS'])
get_last_price(bases=['NEO'])
get_last_price(symbols=['SWTH','GAS'], bases=['NEO'])
The expected return result for this function is as follows::
{
'SWTH': {
'GAS': '0.0015085',
'NEO': '0.00040911'
},
'GAS': {
'NEO': '0.30391642'
},
....
}
:param symbols: The trading symbols to retrieve the last price on the Switcheo Exchange.
:type symbols: list
:param bases: The base pair to retrieve the last price of symbols on the Switcheo Exchange.
:type bases: list
:return: Dictionary of trade symbols with the most recently executed trade price.
'''
pass
def get_offers(self, pair="SWTH_NEO"):
'''
Function to fetch the open orders on the order book for the trade pair requested.
Execution of this function is as follows::
get_offers(pair="SWTH_NEO")
The expected return result for this function is as follows::
[{
'id': '2716c0ca-59bb-4c86-8ee4-6b9528d0e5d2',
'offer_asset': 'GAS',
'want_asset': 'NEO',
'available_amount': 9509259,
'offer_amount': 30000000,
'want_amount': 300000000,
'address': '7f345d1a031c4099540dbbbc220d4e5640ab2b6f'
}, {
....
}]
:param pair: The trading pair that will be used to request open offers on the order book.
:type pair: str
:return: List of dictionaries consisting of the open offers for the requested trading pair.
'''
pass
def get_offer_book(self, pair="SWTH_NEO"):
'''
Function to fetch the open orders formatted on the order book for the trade pair requested.
Execution of this function is as follows::
get_offer_book(pair="SWTH_NEO")
The expected return result for this function is as follows::
{
'asks': [{
'price': '0.00068499',
'quantity': '43326.8348443'
}, {
'price': '0.000685',
'quantity': '59886.34'
}, {
....
}],
'bids': [{
'price': '0.00066602',
'quantity': '3255.99999999'
}, {
'price': '0.00066601',
'quantity': '887.99999999'
}, {
....
}]
}
:param pair: The trading pair that will be used to request open offers on the order book.
:type pair: str
:return: List of dictionaries consisting of the open offers for the requested trading pair.
'''
pass
def get_trades(self, pair="SWTH_NEO", start_time=None, end_time=None, limit=5000):
'''
Function to fetch a list of filled trades for the parameters requested.
Execution of this function is as follows::
get_trades(pair="SWTH_NEO", limit=3)
The expected return result for this function is as follows::
[{
'id': '15bb16e2-7a80-4de1-bb59-bcaff877dee0',
'fill_amount': 100000000,
'take_amount': 100000000,
'event_time': '2018-08-04T15:00:12.634Z',
'is_buy': True
}, {
'id': 'b6f9e530-60ff-46ff-9a71-362097a2025e',
'fill_amount': 47833882,
'take_amount': 97950000000,
'event_time': '2018-08-03T02:44:47.706Z',
'is_buy': True
}, {
'id': '7a308ccc-b7f5-46a3-bf6b-752ab076cc9f',
'fill_amount': 1001117,
'take_amount': 2050000000,
'event_time': '2018-08-03T02:32:50.703Z',
'is_buy': True
}]
:param pair: The trading pair that will be used to request filled trades.
:type pair: str
:param start_time: Only return trades after this time (in epoch seconds).
:type start_time: int
:param end_time: Only return trades before this time (in epoch seconds).
:type end_time: int
:param limit: The number of filled trades to return. Min: 1, Max: 10000, Default: 5000
:type limit: int
:return: List of dictionaries consisting of filled orders that meet requirements of the parameters passed to it.
'''
pass
def get_recent_trades(self, pair="SWTH_NEO"):
'''
Function to fetch a list of the 20 most recently filled trades for the parameters requested.
Execution of this function is as follows::
get_recent_trades(pair="SWTH_NEO")
The expected return result for this function is as follows::
[{
'id': '15bb16e2-7a80-4de1-bb59-bcaff877dee0',
'fill_amount': 100000000,
'take_amount': 100000000,
'event_time': '2018-08-04T15:00:12.634Z',
'is_buy': True
}, {
'id': 'b6f9e530-60ff-46ff-9a71-362097a2025e',
'fill_amount': 47833882,
'take_amount': 97950000000,
'event_time': '2018-08-03T02:44:47.706Z',
'is_buy': True
}, ...., {
'id': '7a308ccc-b7f5-46a3-bf6b-752ab076cc9f',
'fill_amount': 1001117,
'take_amount': 2050000000,
'event_time': '2018-08-03T02:32:50.703Z',
'is_buy': True
}]
:param pair: The trading pair that will be used to request filled trades.
:type pair: str
:return: List of 20 dictionaries consisting of filled orders for the trade pair.
'''
pass
def get_orders(self, address, chain_name='NEO', contract_version='V3', pair=None, from_epoch_time=None,
order_status=None, before_id=None, limit=50):
'''
Function to fetch the order history of the given address.
Execution of this function is as follows::
get_orders(address=neo_get_scripthash_from_address(address=address))
The expected return result for this function is as follows::
[{
'id': '7cbdf481-6acf-4bf3-a1ed-4773f31e6931',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '53718500',
'want_amount': '110000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-03T02:44:47.692Z',
'status': 'processed',
'fills': [{
'id': 'b6f9e530-60ff-46ff-9a71-362097a2025e',
'offer_hash': '95b3b03be0bff8f58aa86a8dd599700bbaeaffc05078329d5b726b6b995f4cda',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'fill_amount': '47833882',
'want_amount': '97950000000',
'filled_amount': '',
'fee_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'fee_amount': '73462500',
'price': '0.00048835',
'txn': None,
'status': 'success',
'created_at': '2018-08-03T02:44:47.706Z',
'transaction_hash': '694745a09e33845ec008cfb79c73986a556e619799ec73274f82b30d85bda13a'
}],
'makes': [{
'id': '357088a0-cc80-49ab-acdd-980589c2d7d8',
'offer_hash': '420cc85abf02feaceb1bcd91489a0c1949c972d2a9a05ae922fa15d79de80c00',
'available_amount': '0',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '5884618',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '12050000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.000488350041493775933609958506224066390041494',
'status': 'cancelled',
'created_at': '2018-08-03T02:44:47.708Z',
'transaction_hash': '1afa946546550151bbbd19f197a87cec92e9be58c44ec431cae42076298548b7',
'trades': []
}]
}, {
....
}]
:param address: The ScriptHash of the address to filter orders for.
:type address: str
:param pair: The trading pair to filter order requests on.
:type pair: str
:param chain_name: The name of the chain to find orders against.
:type chain_name: str
:param contract_version: The version of the contract to find orders against.
:type contract_version: str
:param from_epoch_time: Only return orders that are last updated at or after this time.
:type from_epoch_time: int
:param order_status: Only return orders have this status. Possible values are open, cancelled, completed.
:type order_status: str
:param before_id: Only return orders that are created before the order with this id.
:type before_id: str
:param limit: Only return up to this number of orders (min: 1, max: 200, default: 50).
:type limit: int
:return: List of dictionaries containing the orders for the given NEO address and (optional) trading pair.
'''
pass
def get_balance(self, addresses, contracts):
'''
Function to fetch the current account balance for the given address in the Switcheo smart contract.
Execution of this function is as follows::
get_balance(address=neo_get_scripthash_from_address(address=address))
The expected return result for this function is as follows::
{
'confirming': {},
'confirmed': {
'GAS': '100000000.0',
'SWTH': '97976537500.0',
'NEO': '52166118.0'
},
'locked': {}
}
:param addresses: The ScriptHash of the address(es) to retrieve its Smart Contract balance.
:type addresses: list
:param contracts: The contract hash(es) to retrieve all addresses Smart Contract balance.
:type contracts: list
:return: Dictionary containing the sum of all addresses smart contract balances by processing state.
'''
pass
| 22 | 22 | 35 | 4 | 6 | 25 | 2 | 4.36 | 1 | 2 | 1 | 2 | 21 | 7 | 21 | 21 | 753 | 105 | 121 | 45 | 94 | 527 | 86 | 40 | 64 | 5 | 1 | 1 | 34 |
142,263 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/neo/test_transactions.py
|
switcheo.neo.test_transactions.TestTransactions
|
class TestTransactions(unittest.TestCase):
def test_serialize_transaction(self):
serialized_transaction = 'd101520800e1f505000000001432e125258b7db0a0dffde5bd03b2b859253538ab14592c8a46a0d06c600f06c994d1f25e7283b8a2fe53c1076465706f73697467823b63e7c70a795a7615a38d1ba67d9e54c195a100000000000000000220592c8a46a0d06c600f06c994d1f25e7283b8a2fe206a3d9b359fc17d711017daa6c0e14d6172a791ed02ead8ad4d5a5ac8cb55002feb2708e0eabef0e1a50d36cd30170d587c693b9bf000003d71ff3949598927923f5156501af8a1ac8c67b1b24f97fa25151eafd2e458c81f0001e72d286979ee6cb1b7e65dfddfb2e384100b8d148e7758de42e4168b71792c6001000000000000007335f929546270b8f811a0f9427b5712457107e7'
self.assertEqual(serialize_transaction(transaction=transaction_dict, signed=False), serialized_transaction)
def test_serialize_transaction_attribute(self):
serialized_attributes = []
serialized_attribute_expected_list = ['20592c8a46a0d06c600f06c994d1f25e7283b8a2fe',
'206a3d9b359fc17d711017daa6c0e14d6172a791ed']
for attribute in transaction_dict['attributes']:
serialized_attributes.append(serialize_transaction_attribute(attr=attribute))
self.assertListEqual(serialized_attributes, serialized_attribute_expected_list)
def test_serialize_transaction_input(self):
serialized_inputs = []
serialized_input_expected_list = ['ead8ad4d5a5ac8cb55002feb2708e0eabef0e1a50d36cd30170d587c693b9bf00000',
'3d71ff3949598927923f5156501af8a1ac8c67b1b24f97fa25151eafd2e458c81f00']
for txn_input in transaction_dict['inputs']:
serialized_inputs.append(serialize_transaction_input(txn_input=txn_input))
self.assertListEqual(serialized_inputs, serialized_input_expected_list)
def test_serialize_transaction_output(self):
serialized_outputs = []
serialized_output_expected_list = ['e72d286979ee6cb1b7e65dfddfb2e384100b8d148e7758de42e4168b71792c6001000000000000007335f929546270b8f811a0f9427b5712457107e7']
for txn_output in transaction_dict['outputs']:
serialized_outputs.append(serialize_transaction_output(txn_output=txn_output))
self.assertListEqual(serialized_outputs, serialized_output_expected_list)
def test_serialize_witness(self):
# This is not used by Switcheo and I can't find a good test transaction for this, will pass for now.
pass
def test_serialize_claim_exclusive(self):
with self.assertRaises(ValueError):
serialize_claim_exclusive(transaction=transaction_dict)
# Switcheo will not be allowing for GAS claims so this should never be necessary.
# transaction_claim_dict = transaction_dict.copy()
# transaction_claim_dict['type'] = 2
# self.assertEqual(serialize_claim_exclusive(transaction=transaction_claim_dict), '')
def test_serialize_contract_exclusive(self):
with self.assertRaises(ValueError):
serialize_contract_exclusive(transaction=transaction_dict)
transaction_contract_dict = transaction_dict.copy()
transaction_contract_dict['type'] = 128
self.assertEqual(serialize_contract_exclusive(transaction=transaction_contract_dict), '')
def test_serialize_invocation_exclusive(self):
serialized_invocation = '520800e1f505000000001432e125258b7db0a0dffde5bd03b2b859253538ab14592c8a46a0d06c600f06c994d1f25e7283b8a2fe53c1076465706f73697467823b63e7c70a795a7615a38d1ba67d9e54c195a10000000000000000'
self.assertEqual(serialize_invocation_exclusive(transaction=transaction_dict), serialized_invocation)
transaction_invocation_dict = transaction_dict.copy()
transaction_invocation_dict['type'] = 128
with self.assertRaises(ValueError):
serialize_invocation_exclusive(transaction=transaction_invocation_dict)
|
class TestTransactions(unittest.TestCase):
def test_serialize_transaction(self):
pass
def test_serialize_transaction_attribute(self):
pass
def test_serialize_transaction_input(self):
pass
def test_serialize_transaction_output(self):
pass
def test_serialize_witness(self):
pass
def test_serialize_claim_exclusive(self):
pass
def test_serialize_contract_exclusive(self):
pass
def test_serialize_invocation_exclusive(self):
pass
| 9 | 0 | 5 | 0 | 5 | 0 | 1 | 0.12 | 1 | 1 | 0 | 0 | 8 | 0 | 8 | 80 | 55 | 8 | 42 | 22 | 33 | 5 | 40 | 22 | 31 | 2 | 2 | 1 | 11 |
142,264 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/neo/test_neo_utils.py
|
switcheo.neo.test_neo_utils.TestNeoUtils
|
class TestNeoUtils(unittest.TestCase):
def test_sign_message(self):
signed_message = 'f60f6896a87d6d35e62668958e08fb5a7c26c1c381c5ed6ad5b1ad9f6f6e826b1ab7695ad4ddd337438da1cd802b5e19dc6861700f4bd87a58dfa002cde11a3a'
self.assertEqual(sign_message(encoded_message=encoded_message,private_key_hex=testnet_privatekey_hexstring),
signed_message)
def test_sign_transaction(self):
signed_transaction = 'cb511f7acf269d22690cf656b2f868fc10d12baff2f398ad175ae7e5a1e599f02d63a52d13aa3f3a6b57eaa0231e9fc4f1ab7900c34240033232c5a9f6b8214b'
self.assertEqual(sign_transaction(transaction=transaction_dict, private_key_hex=testnet_privatekey_hexstring),
signed_transaction)
def test_sign_array(self):
pass
# signed_array = {'e30a7fdf-779c-4623-8f92-8a961450d843': 'b1b821d7aa3c3d388370eba8e910de5c3605fcae2d584b0e89e932658f6b335a6aac65c52928e6eebf85919464897b8966a5a4dbcfd92eb28a3ae88299533f2c', '7dac087c-3709-48ea-83e1-83eadfc4cbe5': 'b1b821d7aa3c3d388370eba8e910de5c3605fcae2d584b0e89e932658f6b335a6aac65c52928e6eebf85919464897b8966a5a4dbcfd92eb28a3ae88299533f2c'}
# self.assertEqual(sign_txn_array(messages=transaction_array, private_key_hex=testnet_privatekey_hexstring)['e30a7fdf-779c-4623-8f92-8a961450d843'],
# signed_array['e30a7fdf-779c-4623-8f92-8a961450d843'])
def test_encode_message(self):
self.assertEqual(encode_message(message=message), encoded_message)
self.assertEqual(encode_message(message=json_message), json_encoded_message)
def test_to_neo_asset_amount(self):
self.assertEqual(to_neo_asset_amount(10), '1000000000')
self.assertEqual(to_neo_asset_amount(.01), '1000000')
with self.assertRaises(ValueError):
to_neo_asset_amount(0.0000000000001)
with self.assertRaises(ValueError):
to_neo_asset_amount(100000000)
def test_private_key_to_hex(self):
self.assertEqual(private_key_to_hex(key_pair=kp), testnet_privatekey_hexstring)
def test_neo_get_scripthash_from_address(self):
self.assertEqual(neo_get_scripthash_from_address(address=testnet_address), testnet_scripthash)
def test_neo_get_address_from_scripthash(self):
self.assertEqual(neo_get_address_from_scripthash(scripthash=testnet_scripthash), testnet_address)
def test_neo_get_public_key_from_private_key(self):
self.assertEqual(neo_get_public_key_from_private_key(private_key=testnet_privatekey).ToString(), testnet_publickey)
def test_neo_get_scripthash_from_private_key(self):
self.assertEqual(str(neo_get_scripthash_from_private_key(private_key=testnet_privatekey)), testnet_scripthash)
def test_open_wallet(self):
self.assertEqual(open_wallet(testnet_privatekey_hexstring).PublicKey, kp.PublicKey)
self.assertEqual(open_wallet(testnet_privatekey_hexstring).PrivateKey, kp.PrivateKey)
self.assertEqual(open_wallet(testnet_privatekey_hexstring).GetAddress(), kp.GetAddress())
def test_create_offer_hash(self):
self.assertEqual(create_offer_hash(neo_address='APuP9GsSCPJKrexPe49afDV8CQYubZGWd8',
offer_asset_amt=6000000,
offer_asset_hash='c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
want_asset_amt=30000000000,
want_asset_hash='ab38352559b8b203bde5fddfa0b07d8b2525e132',
txn_uuid='ecb6ee9e-de8d-46d6-953b-afcc976be1ae'),
'95a9502f11c62b85cf790b83104c89d3198a3b4dac6ba8a0e19090a8ee2207c7')
|
class TestNeoUtils(unittest.TestCase):
def test_sign_message(self):
pass
def test_sign_transaction(self):
pass
def test_sign_array(self):
pass
def test_encode_message(self):
pass
def test_to_neo_asset_amount(self):
pass
def test_private_key_to_hex(self):
pass
def test_neo_get_scripthash_from_address(self):
pass
def test_neo_get_address_from_scripthash(self):
pass
def test_neo_get_public_key_from_private_key(self):
pass
def test_neo_get_scripthash_from_private_key(self):
pass
def test_open_wallet(self):
pass
def test_create_offer_hash(self):
pass
| 13 | 0 | 4 | 0 | 4 | 0 | 1 | 0.07 | 1 | 2 | 0 | 0 | 12 | 0 | 12 | 84 | 58 | 12 | 43 | 15 | 30 | 3 | 35 | 15 | 22 | 1 | 2 | 1 | 12 |
142,265 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/authenticated_client.py
|
switcheo.authenticated_client.AuthenticatedClient
|
class AuthenticatedClient(PublicClient):
def __init__(self,
blockchain='neo',
contract_version='V3',
api_url='https://test-api.switcheo.network/',
api_version='/v2'):
PublicClient.__init__(self,
blockchain=blockchain,
contract_version=contract_version,
api_url=api_url,
api_version=api_version)
self.infura_dict = {
'https://api.switcheo.network': 'https://infura.io/',
'https://api.switcheo.network/': 'https://infura.io/',
'api.switcheo.network': 'https://infura.io/',
'api.switcheo.network/': 'https://infura.io/',
'https://test-api.switcheo.network': 'https://ropsten.infura.io/',
'https://test-api.switcheo.network/': 'https://ropsten.infura.io/',
'test-api.switcheo.network': 'https://ropsten.infura.io/',
'test-api.switcheo.network/': 'https://ropsten.infura.io/'
}
self.infura_url = self.infura_dict[api_url]
self.blockchain_amount = {
'eth': partial(to_wei, unit='ether'),
'neo': to_neo_asset_amount
}
self.sign_create_cancellation_function = {
'eth': sign_create_cancellation_eth,
'neo': sign_create_cancellation_neo
}
self.sign_execute_cancellation_function = {
'eth': sign_execute_cancellation_eth,
'neo': sign_execute_cancellation_neo
}
self.sign_create_deposit_function = {
'eth': sign_create_deposit_eth,
'neo': sign_create_deposit_neo
}
self.sign_execute_deposit_function = {
'eth': partial(sign_execute_deposit_eth, infura_url=self.infura_url),
'neo': sign_execute_deposit_neo
}
self.sign_create_order_function = {
'eth': sign_create_order_eth,
'neo': sign_create_order_neo
}
self.sign_execute_order_function = {
'eth': sign_execute_order_eth,
'neo': sign_execute_order_neo
}
self.sign_create_withdrawal_function = {
'eth': sign_create_withdrawal_eth,
'neo': sign_create_withdrawal_neo
}
self.sign_execute_withdrawal_function = {
'eth': sign_execute_withdrawal_eth,
'neo': sign_execute_withdrawal_neo
}
def cancel_order(self, order_id, private_key):
"""
This function is a wrapper function around the create and execute cancellation functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
cancel_order(order_id=order['id'], private_key=kp)
cancel_order(order_id=order['id'], private_key=eth_private_key)
The expected return result for this function is the same as the execute_cancellation function::
{
'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T11:16:47.021Z',
'status': 'processed',
'fills': [],
'makes': [
{
'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74',
'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92',
'available_amount': '0',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.0002',
'status': 'cancelling',
'created_at': '2018-08-05T11:16:47.036Z',
'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415',
'trades': []
}
]
}
:param order_id: The order ID of the open transaction on the order book that you want to cancel.
:type order_id: str
:param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain.
:type private_key: KeyPair
:return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain.
"""
create_cancellation = self.create_cancellation(order_id=order_id, private_key=private_key)
return self.execute_cancellation(cancellation_params=create_cancellation, private_key=private_key)
def create_cancellation(self, order_id, private_key):
"""
Function to create a cancellation request for the order ID from the open orders on the order book.
Execution of this function is as follows::
create_cancellation(order_id=order['id'], private_key=kp)
The expected return result for this function is as follows::
{
'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74',
'transaction': {
'hash': '50d99ebd7e57dbdceb7edc2014da5f446c8f44cc0a0b6d9c762a29e8a74bb051',
'sha256': '509edb9888fa675988fa71a27600b2655e63fe979424f13f5c958897b2e99ed8',
'type': 209,
'version': 1,
'attributes': [
{
'usage': 32,
'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'
}
],
'inputs': [
{
'prevHash': '9eaca1adcbbc0669a936576cb9ad03c11c99c356347aae3037ce1f0e4d330d85',
'prevIndex': 0
}, {
'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d',
'prevIndex': 37
}
],
'outputs': [
{
'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'scriptHash': 'e707714512577b42f9a011f8b870625429f93573',
'value': 1e-08
}
],
'scripts': [],
'script': '....',
'gas': 0
},
'script_params': {
'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'operation': 'cancelOffer',
'args': [
'923ebd865a6c5db39bd67403c1677f29d3949d9d8d9a2eb36a56dabd2dd83068'
]
}
}
:param order_id: The order ID of the open transaction on the order book that you want to cancel.
:type order_id: str
:param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain.
:type private_key: KeyPair
:return: Dictionary that contains the cancellation request along with blockchain transaction information.
"""
cancellation_params = {
"order_id": order_id,
"timestamp": get_epoch_milliseconds()
}
api_params = self.sign_create_cancellation_function[self.blockchain](cancellation_params, private_key)
return self.request.post(path='/cancellations', json_data=api_params)
def execute_cancellation(self, cancellation_params, private_key):
"""
This function executes the order created before it and signs the transaction to be submitted to the blockchain.
Execution of this function is as follows::
execute_cancellation(cancellation_params=create_cancellation, private_key=kp)
The expected return result for this function is as follows::
{
'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T11:16:47.021Z',
'status': 'processed',
'fills': [],
'makes': [
{
'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74',
'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92',
'available_amount': '0',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.0002',
'status': 'cancelling',
'created_at': '2018-08-05T11:16:47.036Z',
'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415',
'trades': []
}
]
}
:param cancellation_params: Parameters generated from the Switcheo API to cancel an order on the order book.
:type cancellation_params: dict
:param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain.
:type private_key: KeyPair
:return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain.
"""
cancellation_id = cancellation_params['id']
api_params = self.sign_execute_cancellation_function[self.blockchain](cancellation_params, private_key)
return self.request.post(path='/cancellations/{}/broadcast'.format(cancellation_id), json_data=api_params)
def deposit(self, asset, amount, private_key):
"""
This function is a wrapper function around the create and execute deposit functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
deposit(asset="SWTH", amount=1.1, private_key=KeyPair)
deposit(asset="SWTH", amount=1.1, private_key=eth_private_key)
The expected return result for this function is the same as the execute_deposit function::
{
'result': 'ok'
}
:param asset: Symbol or Script Hash of asset ID from the available products.
:type asset: str
:param amount: The amount of coins/tokens to be deposited.
:type amount: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the result status of the deposit attempt.
"""
create_deposit = self.create_deposit(asset=asset, amount=amount, private_key=private_key)
return self.execute_deposit(deposit_params=create_deposit, private_key=private_key)
def create_deposit(self, asset, amount, private_key):
"""
Function to create a deposit request by generating a transaction request from the Switcheo API.
Execution of this function is as follows::
create_deposit(asset="SWTH", amount=1.1, private_key=KeyPair)
create_deposit(asset="ETH", amount=1.1, private_key=eth_private_key)
The expected return result for this function is as follows::
{
'id': '768e2079-1504-4dad-b688-7e1e99ec0a24',
'transaction': {
'hash': '72b74c96b9174e9b9e1b216f7e8f21a6475e6541876a62614df7c1998c6e8376',
'sha256': '2109cbb5eea67a06f5dd8663e10fcd1128e28df5721a25d993e05fe2097c34f3',
'type': 209,
'version': 1,
'attributes': [
{
'usage': 32,
'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'
}
],
'inputs': [
{
'prevHash': 'f09b3b697c580d1730cd360da5e1f0beeae00827eb2f0055cbc85a5a4dadd8ea',
'prevIndex': 0
}, {
'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d',
'prevIndex': 31
}
],
'outputs': [
{
'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'scriptHash': 'e707714512577b42f9a011f8b870625429f93573',
'value': 1e-08
}
],
'scripts': [],
'script': '....',
'gas': 0
},
'script_params': {
'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'operation': 'deposit',
'args': [
'592c8a46a0d06c600f06c994d1f25e7283b8a2fe',
'32e125258b7db0a0dffde5bd03b2b859253538ab',
100000000
]
}
}
:param asset: Symbol or Script Hash of asset ID from the available products.
:type asset: str
:param amount: The amount of coins/tokens to be deposited.
:type amount: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary response of signed deposit request that is ready to be executed on the specified blockchain.
"""
signable_params = {
'blockchain': self.blockchain,
'asset_id': asset,
'amount': str(self.blockchain_amount[self.blockchain](amount)),
'timestamp': get_epoch_milliseconds(),
'contract_hash': self.contract_hash
}
api_params = self.sign_create_deposit_function[self.blockchain](signable_params, private_key)
return self.request.post(path='/deposits', json_data=api_params)
def execute_deposit(self, deposit_params, private_key):
"""
Function to execute the deposit request by signing the transaction generated by the create deposit function.
Execution of this function is as follows::
execute_deposit(deposit_params=create_deposit, private_key=KeyPair)
execute_deposit(deposit_params=create_deposit, private_key=eth_private_key)
The expected return result for this function is as follows::
{
'result': 'ok'
}
:param deposit_params: Parameters from the API to be signed and deposited to the Switcheo Smart Contract.
:type deposit_params: dict
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the result status of the deposit attempt.
"""
deposit_id = deposit_params['id']
api_params = self.sign_execute_deposit_function[self.blockchain](deposit_params, private_key)
return self.request.post(path='/deposits/{}/broadcast'.format(deposit_id), json_data=api_params)
def order(self, pair, side, private_key, price=None, quantity=None, use_native_token=True,
order_type="limit", offer_amount=None, receiving_address=None, worst_acceptable_price=None):
"""
This function is a wrapper function around the create and execute order functions to help make this processes
simpler for the end user by combining these requests in 1 step. Trading can take place on normal (spot) markets
and atomic swap markets. The required arguments differ between those cases.
Execution of this function for spot- and swap-markets respectively is as follows::
order(pair="SWTH_NEO", side="buy",
price=0.0002, quantity=100,
private_key=kp, use_native_token=True, order_type="limit")
order(pair="SWTH_ETH", side="buy",
offer_amount=0.1, receiving_address=fea2b883725ef2d194c9060f606cd0a0468a2c59,
private_key=kp, use_native_token=True, order_type="limit")
The expected return result for this function is the same as the execute_order function::
{
'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T10:38:37.714Z',
'status': 'processed',
'fills': [],
'makes': [
{
'id': 'e30a7fdf-779c-4623-8f92-8a961450d843',
'offer_hash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968',
'available_amount': '2000000',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.0002',
'status': 'confirming',
'created_at': '2018-08-05T10:38:37.731Z',
'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
'trades': []
}
]
}
:param pair: The trading pair this order is being submitted for.
:type pair: str
:param side: The side of the trade being submitted i.e. buy or sell
:type side: str
:param price: The price target for this trade.
:type price: float
:param quantity: The amount of the asset being exchanged in the trade.
:type quantity: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token.
:type use_native_token: bool
:param order_type: The type of order being submitted, currently this can only be a limit order.
:type order_type: str
:return: Dictionary of the transaction on the order book.
:type offer_amount: str
:return: The amount of the asset that is offered in the swap trade.
:type receiving_address:
:return: The address the tokens received in the swap are sent to.
:type worst_acceptable_price:
:return: The lower or upper price limit for which the trade will be performed
"""
create_order = self.create_order(private_key=private_key, pair=pair, side=side, price=price,
quantity=quantity, use_native_token=use_native_token,
order_type=order_type, offer_amount=offer_amount,
receiving_address=receiving_address, worst_acceptable_price=worst_acceptable_price)
return self.execute_order(order_params=create_order, private_key=private_key)
def create_order(self, pair, side, private_key, price=None, quantity=None, use_native_token=True,
order_type="limit", otc_address=None, offer_amount=None, receiving_address=None,
worst_acceptable_price=None):
"""
Function to create an order for the trade pair and details requested.
Execution of this function is as follows::
create_order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp,
use_native_token=True, order_type="limit")
The expected return result for this function is as follows::
{
'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T10:38:37.714Z',
'status': 'pending',
'fills': [],
'makes': [
{
'id': 'e30a7fdf-779c-4623-8f92-8a961450d843',
'offer_hash': None,
'available_amount': None,
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': None,
'txn': {
'offerHash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968',
'hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
'sha256': 'f0b70640627947584a2976edeb055a124ae85594db76453532b893c05618e6ca',
'invoke': {
'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'operation': 'makeOffer',
'args': [
'592c8a46a0d06c600f06c994d1f25e7283b8a2fe',
'9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5',
2000000,
'32e125258b7db0a0dffde5bd03b2b859253538ab',
10000000000,
'65333061376664662d373739632d343632332d386639322d386139363134353064383433'
]
},
'type': 209,
'version': 1,
'attributes': [
{
'usage': 32,
'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'
}
],
'inputs': [
{
'prevHash': '0fcfd792a9d20a7795255d1d3d3927f5968b9953e80d16ffd222656edf8fedbc',
'prevIndex': 0
}, {
'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d',
'prevIndex': 35
}
],
'outputs': [
{
'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'scriptHash': 'e707714512577b42f9a011f8b870625429f93573',
'value': 1e-08
}
],
'scripts': [],
'script': '....',
'gas': 0
},
'cancel_txn': None,
'price': '0.0002',
'status': 'pending',
'created_at': '2018-08-05T10:38:37.731Z',
'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
'trades': []
}
]
}
:param pair: The trading pair this order is being submitted for.
:type pair: str
:param side: The side of the trade being submitted i.e. buy or sell
:type side: str
:param price: The price target for this trade.
:type price: float
:param quantity: The amount of the asset being exchanged in the trade.
:type quantity: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token.
:type use_native_token: bool
:param order_type: The type of order being submitted, currently this can only be a limit order.
:type order_type: str
:param otc_address: The address to trade with for Over the Counter exchanges.
:type otc_address: str
:return: Dictionary of order details to specify which parts of the trade will be filled (taker) or open (maker)
:type offer_amount: str
:return: The amount of the asset that is offered in the swap trade.
:type receiving_address:
:return: The address the tokens received in the swap are sent to.
:type worst_acceptable_price:
:return: The lower or upper price limit for which the trade will be performed
"""
if side.lower() not in ["buy", "sell"]:
raise ValueError("Allowed trade types are buy or sell, you entered {}".format(side.lower()))
if order_type.lower() not in ["limit", "market", "otc"]:
raise ValueError("Allowed order type is limit, you entered {}".format(order_type.lower()))
if order_type.lower() == "otc" and otc_address is None:
raise ValueError("OTC Address is required when trade type is otc (over the counter).")
order_params = {
"blockchain": self.blockchain,
"pair": pair,
"side": side,
"use_native_tokens": use_native_token,
"timestamp": get_epoch_milliseconds(),
"contract_hash": self.contract_hash
}
if not offer_amount is None:
order_params["price"] = None
order_params["offer_amount"] = str(self.blockchain_amount[self.blockchain](offer_amount))
order_params["receiving_address"] = receiving_address
order_params["worst_acceptable_price"] = worst_acceptable_price
order_params["order_type"] = "market"
else:
order_params["price"] = '{:.8f}'.format(price) if order_type.lower() != "market" else None
order_params["quantity"] = str(self.blockchain_amount[self.blockchain](quantity))
order_params["order_type"] = order_type
api_params = self.sign_create_order_function[self.blockchain](order_params, private_key)
return self.request.post(path='/orders', json_data=api_params)
def execute_order(self, order_params, private_key):
"""
This function executes the order created before it and signs the transaction to be submitted to the blockchain.
Execution of this function is as follows::
execute_order(order_params=create_order, private_key=kp)
The expected return result for this function is the same as the execute_order function::
{
'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T10:38:37.714Z',
'status': 'processed',
'fills': [],
'makes': [
{
'id': 'e30a7fdf-779c-4623-8f92-8a961450d843',
'offer_hash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968',
'available_amount': '2000000',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.0002',
'status': 'confirming',
'created_at': '2018-08-05T10:38:37.731Z',
'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
'trades': []
}
]
}
:param order_params: Dictionary generated from the create order function.
:type order_params: dict
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary of the transaction on the order book.
"""
order_id = order_params['id']
api_params = self.sign_execute_order_function[self.blockchain](order_params, private_key)
return self.request.post(path='/orders/{}/broadcast'.format(order_id), json_data=api_params)
def withdrawal(self, asset, amount, private_key):
"""
This function is a wrapper function around the create and execute withdrawal functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
withdrawal(asset="SWTH", amount=1.1, private_key=kp))
The expected return result for this function is the same as the execute_withdrawal function::
{
'event_type': 'withdrawal',
'amount': -100000,
'asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'status': 'confirming',
'id': '96e5f797-435b-40ab-9085-4e95c6749218',
'blockchain': 'neo',
'reason_code': 9,
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'transaction_hash': None,
'created_at': '2018-08-05T10:03:58.885Z',
'updated_at': '2018-08-05T10:03:59.828Z',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82'
}
:param asset: Script Hash of asset ID from the available products.
:type asset: str
:param amount: The amount of coins/tokens to be withdrawn.
:type amount: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the status of the withdrawal request and blockchain details.
"""
create_withdrawal = self.create_withdrawal(asset=asset, amount=amount, private_key=private_key)
return self.execute_withdrawal(withdrawal_params=create_withdrawal, private_key=private_key)
def create_withdrawal(self, asset, amount, private_key):
"""
Function to create a withdrawal request by generating a withdrawal ID request from the Switcheo API.
Execution of this function is as follows::
create_withdrawal(asset="SWTH", amount=1.1, private_key=kp)
The expected return result for this function is as follows::
{
'id': 'a5a4d396-fa9f-4191-bf50-39a3d06d5e0d'
}
:param asset: Script Hash of asset ID from the available products.
:type asset: str
:param amount: The amount of coins/tokens to be withdrawn.
:type amount: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the withdrawal ID generated by the Switcheo API.
"""
signable_params = {
'blockchain': self.blockchain,
'asset_id': asset,
'amount': str(self.blockchain_amount[self.blockchain](amount)),
'timestamp': get_epoch_milliseconds(),
'contract_hash': self.contract_hash
}
api_params = self.sign_create_withdrawal_function[self.blockchain](signable_params, private_key)
return self.request.post(path='/withdrawals', json_data=api_params)
def execute_withdrawal(self, withdrawal_params, private_key):
"""
This function is to sign the message generated from the create withdrawal function and submit it to the
blockchain for transfer from the smart contract to the owners address.
Execution of this function is as follows::
execute_withdrawal(withdrawal_params=create_withdrawal, private_key=kp)
The expected return result for this function is as follows::
{
'event_type': 'withdrawal',
'amount': -100000,
'asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'status': 'confirming',
'id': '96e5f797-435b-40ab-9085-4e95c6749218',
'blockchain': 'neo',
'reason_code': 9,
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'transaction_hash': None,
'created_at': '2018-08-05T10:03:58.885Z',
'updated_at': '2018-08-05T10:03:59.828Z',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82'
}
:param withdrawal_params: Dictionary from the create withdrawal function to sign and submit to the blockchain.
:type withdrawal_params: dict
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the status of the withdrawal request and blockchain transaction details.
"""
withdrawal_id = withdrawal_params['id']
api_params = self.sign_execute_withdrawal_function[self.blockchain](withdrawal_params, private_key)
return self.request.post(path='/withdrawals/{}/broadcast'.format(withdrawal_id), json_data=api_params)
|
class AuthenticatedClient(PublicClient):
def __init__(self,
blockchain='neo',
contract_version='V3',
api_url='https://test-api.switcheo.network/',
api_version='/v2'):
pass
def cancel_order(self, order_id, private_key):
'''
This function is a wrapper function around the create and execute cancellation functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
cancel_order(order_id=order['id'], private_key=kp)
cancel_order(order_id=order['id'], private_key=eth_private_key)
The expected return result for this function is the same as the execute_cancellation function::
{
'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T11:16:47.021Z',
'status': 'processed',
'fills': [],
'makes': [
{
'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74',
'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92',
'available_amount': '0',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.0002',
'status': 'cancelling',
'created_at': '2018-08-05T11:16:47.036Z',
'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415',
'trades': []
}
]
}
:param order_id: The order ID of the open transaction on the order book that you want to cancel.
:type order_id: str
:param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain.
:type private_key: KeyPair
:return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain.
'''
pass
def create_cancellation(self, order_id, private_key):
'''
Function to create a cancellation request for the order ID from the open orders on the order book.
Execution of this function is as follows::
create_cancellation(order_id=order['id'], private_key=kp)
The expected return result for this function is as follows::
{
'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74',
'transaction': {
'hash': '50d99ebd7e57dbdceb7edc2014da5f446c8f44cc0a0b6d9c762a29e8a74bb051',
'sha256': '509edb9888fa675988fa71a27600b2655e63fe979424f13f5c958897b2e99ed8',
'type': 209,
'version': 1,
'attributes': [
{
'usage': 32,
'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'
}
],
'inputs': [
{
'prevHash': '9eaca1adcbbc0669a936576cb9ad03c11c99c356347aae3037ce1f0e4d330d85',
'prevIndex': 0
}, {
'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d',
'prevIndex': 37
}
],
'outputs': [
{
'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'scriptHash': 'e707714512577b42f9a011f8b870625429f93573',
'value': 1e-08
}
],
'scripts': [],
'script': '....',
'gas': 0
},
'script_params': {
'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'operation': 'cancelOffer',
'args': [
'923ebd865a6c5db39bd67403c1677f29d3949d9d8d9a2eb36a56dabd2dd83068'
]
}
}
:param order_id: The order ID of the open transaction on the order book that you want to cancel.
:type order_id: str
:param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain.
:type private_key: KeyPair
:return: Dictionary that contains the cancellation request along with blockchain transaction information.
'''
pass
def execute_cancellation(self, cancellation_params, private_key):
'''
This function executes the order created before it and signs the transaction to be submitted to the blockchain.
Execution of this function is as follows::
execute_cancellation(cancellation_params=create_cancellation, private_key=kp)
The expected return result for this function is as follows::
{
'id': 'b8e617d5-f5ed-4600-b8f2-7d370d837750',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T11:16:47.021Z',
'status': 'processed',
'fills': [],
'makes': [
{
'id': '6b9f40de-f9bb-46b6-9434-d281f8c06b74',
'offer_hash': '6830d82dbdda566ab32e9a8d9d9d94d3297f67c10374d69bb35d6c5a86bd3e92',
'available_amount': '0',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.0002',
'status': 'cancelling',
'created_at': '2018-08-05T11:16:47.036Z',
'transaction_hash': 'e5b08c4a55c7494f1ec7dd93ac2bb2b4e84e77dec9e00e91be1d520cb818c415',
'trades': []
}
]
}
:param cancellation_params: Parameters generated from the Switcheo API to cancel an order on the order book.
:type cancellation_params: dict
:param private_key: The KeyPair that will be used to sign the transaction sent to the blockchain.
:type private_key: KeyPair
:return: Dictionary of the transaction details and state after sending the signed transaction to the blockchain.
'''
pass
def deposit(self, asset, amount, private_key):
'''
This function is a wrapper function around the create and execute deposit functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
deposit(asset="SWTH", amount=1.1, private_key=KeyPair)
deposit(asset="SWTH", amount=1.1, private_key=eth_private_key)
The expected return result for this function is the same as the execute_deposit function::
{
'result': 'ok'
}
:param asset: Symbol or Script Hash of asset ID from the available products.
:type asset: str
:param amount: The amount of coins/tokens to be deposited.
:type amount: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the result status of the deposit attempt.
'''
pass
def create_deposit(self, asset, amount, private_key):
'''
Function to create a deposit request by generating a transaction request from the Switcheo API.
Execution of this function is as follows::
create_deposit(asset="SWTH", amount=1.1, private_key=KeyPair)
create_deposit(asset="ETH", amount=1.1, private_key=eth_private_key)
The expected return result for this function is as follows::
{
'id': '768e2079-1504-4dad-b688-7e1e99ec0a24',
'transaction': {
'hash': '72b74c96b9174e9b9e1b216f7e8f21a6475e6541876a62614df7c1998c6e8376',
'sha256': '2109cbb5eea67a06f5dd8663e10fcd1128e28df5721a25d993e05fe2097c34f3',
'type': 209,
'version': 1,
'attributes': [
{
'usage': 32,
'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'
}
],
'inputs': [
{
'prevHash': 'f09b3b697c580d1730cd360da5e1f0beeae00827eb2f0055cbc85a5a4dadd8ea',
'prevIndex': 0
}, {
'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d',
'prevIndex': 31
}
],
'outputs': [
{
'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'scriptHash': 'e707714512577b42f9a011f8b870625429f93573',
'value': 1e-08
}
],
'scripts': [],
'script': '....',
'gas': 0
},
'script_params': {
'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'operation': 'deposit',
'args': [
'592c8a46a0d06c600f06c994d1f25e7283b8a2fe',
'32e125258b7db0a0dffde5bd03b2b859253538ab',
100000000
]
}
}
:param asset: Symbol or Script Hash of asset ID from the available products.
:type asset: str
:param amount: The amount of coins/tokens to be deposited.
:type amount: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary response of signed deposit request that is ready to be executed on the specified blockchain.
'''
pass
def execute_deposit(self, deposit_params, private_key):
'''
Function to execute the deposit request by signing the transaction generated by the create deposit function.
Execution of this function is as follows::
execute_deposit(deposit_params=create_deposit, private_key=KeyPair)
execute_deposit(deposit_params=create_deposit, private_key=eth_private_key)
The expected return result for this function is as follows::
{
'result': 'ok'
}
:param deposit_params: Parameters from the API to be signed and deposited to the Switcheo Smart Contract.
:type deposit_params: dict
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the result status of the deposit attempt.
'''
pass
def order(self, pair, side, private_key, price=None, quantity=None, use_native_token=True,
order_type="limit", offer_amount=None, receiving_address=None, worst_acceptable_price=None):
'''
This function is a wrapper function around the create and execute order functions to help make this processes
simpler for the end user by combining these requests in 1 step. Trading can take place on normal (spot) markets
and atomic swap markets. The required arguments differ between those cases.
Execution of this function for spot- and swap-markets respectively is as follows::
order(pair="SWTH_NEO", side="buy",
price=0.0002, quantity=100,
private_key=kp, use_native_token=True, order_type="limit")
order(pair="SWTH_ETH", side="buy",
offer_amount=0.1, receiving_address=fea2b883725ef2d194c9060f606cd0a0468a2c59,
private_key=kp, use_native_token=True, order_type="limit")
The expected return result for this function is the same as the execute_order function::
{
'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T10:38:37.714Z',
'status': 'processed',
'fills': [],
'makes': [
{
'id': 'e30a7fdf-779c-4623-8f92-8a961450d843',
'offer_hash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968',
'available_amount': '2000000',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.0002',
'status': 'confirming',
'created_at': '2018-08-05T10:38:37.731Z',
'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
'trades': []
}
]
}
:param pair: The trading pair this order is being submitted for.
:type pair: str
:param side: The side of the trade being submitted i.e. buy or sell
:type side: str
:param price: The price target for this trade.
:type price: float
:param quantity: The amount of the asset being exchanged in the trade.
:type quantity: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token.
:type use_native_token: bool
:param order_type: The type of order being submitted, currently this can only be a limit order.
:type order_type: str
:return: Dictionary of the transaction on the order book.
:type offer_amount: str
:return: The amount of the asset that is offered in the swap trade.
:type receiving_address:
:return: The address the tokens received in the swap are sent to.
:type worst_acceptable_price:
:return: The lower or upper price limit for which the trade will be performed
'''
pass
def create_order(self, pair, side, private_key, price=None, quantity=None, use_native_token=True,
order_type="limit", otc_address=None, offer_amount=None, receiving_address=None,
worst_acceptable_price=None):
'''
Function to create an order for the trade pair and details requested.
Execution of this function is as follows::
create_order(pair="SWTH_NEO", side="buy", price=0.0002, quantity=100, private_key=kp,
use_native_token=True, order_type="limit")
The expected return result for this function is as follows::
{
'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T10:38:37.714Z',
'status': 'pending',
'fills': [],
'makes': [
{
'id': 'e30a7fdf-779c-4623-8f92-8a961450d843',
'offer_hash': None,
'available_amount': None,
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': None,
'txn': {
'offerHash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968',
'hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
'sha256': 'f0b70640627947584a2976edeb055a124ae85594db76453532b893c05618e6ca',
'invoke': {
'scriptHash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'operation': 'makeOffer',
'args': [
'592c8a46a0d06c600f06c994d1f25e7283b8a2fe',
'9b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc5',
2000000,
'32e125258b7db0a0dffde5bd03b2b859253538ab',
10000000000,
'65333061376664662d373739632d343632332d386639322d386139363134353064383433'
]
},
'type': 209,
'version': 1,
'attributes': [
{
'usage': 32,
'data': '592c8a46a0d06c600f06c994d1f25e7283b8a2fe'
}
],
'inputs': [
{
'prevHash': '0fcfd792a9d20a7795255d1d3d3927f5968b9953e80d16ffd222656edf8fedbc',
'prevIndex': 0
}, {
'prevHash': 'c858e4d2af1e1525fa974fb2b1678caca1f81a5056513f922789594939ff713d',
'prevIndex': 35
}
],
'outputs': [
{
'assetId': '602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7',
'scriptHash': 'e707714512577b42f9a011f8b870625429f93573',
'value': 1e-08
}
],
'scripts': [],
'script': '....',
'gas': 0
},
'cancel_txn': None,
'price': '0.0002',
'status': 'pending',
'created_at': '2018-08-05T10:38:37.731Z',
'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
'trades': []
}
]
}
:param pair: The trading pair this order is being submitted for.
:type pair: str
:param side: The side of the trade being submitted i.e. buy or sell
:type side: str
:param price: The price target for this trade.
:type price: float
:param quantity: The amount of the asset being exchanged in the trade.
:type quantity: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:param use_native_token: Flag to indicate whether or not to pay fees with the Switcheo native token.
:type use_native_token: bool
:param order_type: The type of order being submitted, currently this can only be a limit order.
:type order_type: str
:param otc_address: The address to trade with for Over the Counter exchanges.
:type otc_address: str
:return: Dictionary of order details to specify which parts of the trade will be filled (taker) or open (maker)
:type offer_amount: str
:return: The amount of the asset that is offered in the swap trade.
:type receiving_address:
:return: The address the tokens received in the swap are sent to.
:type worst_acceptable_price:
:return: The lower or upper price limit for which the trade will be performed
'''
pass
def execute_order(self, order_params, private_key):
'''
This function executes the order created before it and signs the transaction to be submitted to the blockchain.
Execution of this function is as follows::
execute_order(order_params=create_order, private_key=kp)
The expected return result for this function is the same as the execute_order function::
{
'id': '4e6a59fd-d750-4332-aaf0-f2babfa8ad67',
'blockchain': 'neo',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82',
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'side': 'buy',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'offer_amount': '2000000',
'want_amount': '10000000000',
'transfer_amount': '0',
'priority_gas_amount': '0',
'use_native_token': True,
'native_fee_transfer_amount': 0,
'deposit_txn': None,
'created_at': '2018-08-05T10:38:37.714Z',
'status': 'processed',
'fills': [],
'makes': [
{
'id': 'e30a7fdf-779c-4623-8f92-8a961450d843',
'offer_hash': 'b45ddfb97ade5e0363d9e707dac9ad1c530448db263e86494225a0025006f968',
'available_amount': '2000000',
'offer_asset_id': 'c56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b',
'offer_amount': '2000000',
'want_asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'want_amount': '10000000000',
'filled_amount': '0.0',
'txn': None,
'cancel_txn': None,
'price': '0.0002',
'status': 'confirming',
'created_at': '2018-08-05T10:38:37.731Z',
'transaction_hash': '5c4cb1e73b9f2e608b6e768e0654649a4d15e08a7fe63fc536c454fa563a2f0f',
'trades': []
}
]
}
:param order_params: Dictionary generated from the create order function.
:type order_params: dict
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary of the transaction on the order book.
'''
pass
def withdrawal(self, asset, amount, private_key):
'''
This function is a wrapper function around the create and execute withdrawal functions to help make this
processes simpler for the end user by combining these requests in 1 step.
Execution of this function is as follows::
withdrawal(asset="SWTH", amount=1.1, private_key=kp))
The expected return result for this function is the same as the execute_withdrawal function::
{
'event_type': 'withdrawal',
'amount': -100000,
'asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'status': 'confirming',
'id': '96e5f797-435b-40ab-9085-4e95c6749218',
'blockchain': 'neo',
'reason_code': 9,
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'transaction_hash': None,
'created_at': '2018-08-05T10:03:58.885Z',
'updated_at': '2018-08-05T10:03:59.828Z',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82'
}
:param asset: Script Hash of asset ID from the available products.
:type asset: str
:param amount: The amount of coins/tokens to be withdrawn.
:type amount: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the status of the withdrawal request and blockchain details.
'''
pass
def create_withdrawal(self, asset, amount, private_key):
'''
Function to create a withdrawal request by generating a withdrawal ID request from the Switcheo API.
Execution of this function is as follows::
create_withdrawal(asset="SWTH", amount=1.1, private_key=kp)
The expected return result for this function is as follows::
{
'id': 'a5a4d396-fa9f-4191-bf50-39a3d06d5e0d'
}
:param asset: Script Hash of asset ID from the available products.
:type asset: str
:param amount: The amount of coins/tokens to be withdrawn.
:type amount: float
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the withdrawal ID generated by the Switcheo API.
'''
pass
def execute_withdrawal(self, withdrawal_params, private_key):
'''
This function is to sign the message generated from the create withdrawal function and submit it to the
blockchain for transfer from the smart contract to the owners address.
Execution of this function is as follows::
execute_withdrawal(withdrawal_params=create_withdrawal, private_key=kp)
The expected return result for this function is as follows::
{
'event_type': 'withdrawal',
'amount': -100000,
'asset_id': 'ab38352559b8b203bde5fddfa0b07d8b2525e132',
'status': 'confirming',
'id': '96e5f797-435b-40ab-9085-4e95c6749218',
'blockchain': 'neo',
'reason_code': 9,
'address': 'fea2b883725ef2d194c9060f606cd0a0468a2c59',
'transaction_hash': None,
'created_at': '2018-08-05T10:03:58.885Z',
'updated_at': '2018-08-05T10:03:59.828Z',
'contract_hash': 'a195c1549e7da61b8da315765a790ac7e7633b82'
}
:param withdrawal_params: Dictionary from the create withdrawal function to sign and submit to the blockchain.
:type withdrawal_params: dict
:param private_key: The Private Key (ETH) or KeyPair (NEO) for the wallet being used to sign deposit message.
:type private_key: KeyPair or str
:return: Dictionary with the status of the withdrawal request and blockchain transaction details.
'''
pass
| 14 | 12 | 57 | 4 | 11 | 42 | 1 | 3.73 | 1 | 3 | 0 | 1 | 13 | 11 | 13 | 34 | 757 | 67 | 146 | 52 | 125 | 544 | 73 | 45 | 59 | 6 | 2 | 1 | 18 |
142,266 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/Fixed8.py
|
switcheo.Fixed8.SwitcheoFixed8
|
class SwitcheoFixed8(Fixed8):
def toHex(self):
hexstring = hex(round(self.value * self.D))[2:]
return "{:0>16s}".format(hexstring)
def toReverseHex(self):
return reverse_hex(self.toHex())
|
class SwitcheoFixed8(Fixed8):
def toHex(self):
pass
def toReverseHex(self):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 8 | 2 | 6 | 4 | 3 | 0 | 6 | 4 | 3 | 1 | 1 | 0 | 2 |
142,267 |
KeithSSmith/switcheo-python
|
KeithSSmith_switcheo-python/switcheo/streaming_client.py
|
switcheo.streaming_client.OrderBooksNamespace
|
class OrderBooksNamespace(SocketIOClientNamespace):
def __init__(self):
self.lock = threading.Lock()
self.namespace = '/v2/books'
self.order_book = {}
SocketIOClientNamespace.__init__(self, namespace=self.namespace)
def on_connect(self):
pass
def on_disconnect(self):
pass
def on_join(self):
pass
def on_all(self, data):
self.lock.acquire()
self.order_book[data["room"]["pair"]] = data
self.lock.release()
digest_hash = data["digest"]
book = data["book"]
book_digest_hash = sha1_hash_digest(stringify_message(book))
if digest_hash != book_digest_hash:
self.emit(event="leave", data=data["room"], namespace='/v2/books')
self.emit(event="join", data=data["room"], namespace='/v2/books')
def on_updates(self, data):
update_digest = data["digest"]
update_pair = data["room"]["pair"]
update_events = data["events"]
buy_event = False
sell_event = False
if "symbol" in self.order_book[update_pair]["book"]:
del self.order_book[update_pair]["book"]["symbol"]
self.lock.acquire()
for event in update_events:
price_match = False
event_iteration = 0
if event["side"] == "buy":
event_side = "buys"
buy_event = True
elif event["side"] == "sell":
event_side = "sells"
sell_event = True
event_price = event["price"]
event_change = event["delta"]
for side in self.order_book[update_pair]["book"][event_side]:
if side["price"] == event_price:
price_match = True
updated_amount = int(side["amount"]) + int(event_change)
if updated_amount == 0:
self.order_book[update_pair]["book"][event_side].remove(side)
else:
updated_book = {}
updated_book["amount"] = str(updated_amount)
updated_book["price"] = str(event_price)
self.order_book[update_pair]["book"][event_side][event_iteration] = updated_book
break
event_iteration += 1
if not price_match:
new_book = {}
new_book["amount"] = event_change
new_book["price"] = event_price
self.order_book[update_pair]["book"][event_side].append(new_book)
if buy_event and sell_event:
self.order_book[update_pair]["book"]["buys"] = sorted(
self.order_book[update_pair]["book"]["buys"], key=itemgetter("price"), reverse=True)
self.order_book[update_pair]["book"]["sells"] = sorted(
self.order_book[update_pair]["book"]["sells"], key=itemgetter("price"), reverse=True)
elif buy_event:
self.order_book[update_pair]["book"]["buys"] = sorted(
self.order_book[update_pair]["book"]["buys"], key=itemgetter("price"), reverse=True)
elif sell_event:
self.order_book[update_pair]["book"]["sells"] = sorted(
self.order_book[update_pair]["book"]["sells"], key=itemgetter("price"), reverse=True)
book = self.order_book[update_pair]["book"]
self.lock.release()
book_digest_hash = sha1_hash_digest(stringify_message(book))
if update_digest != book_digest_hash:
self.emit(event="leave", data=data["room"], namespace='/v2/books')
self.emit(event="join", data=data["room"], namespace='/v2/books')
|
class OrderBooksNamespace(SocketIOClientNamespace):
def __init__(self):
pass
def on_connect(self):
pass
def on_disconnect(self):
pass
def on_join(self):
pass
def on_all(self, data):
pass
def on_updates(self, data):
pass
| 7 | 0 | 13 | 0 | 13 | 0 | 3 | 0 | 1 | 3 | 0 | 0 | 6 | 3 | 6 | 6 | 83 | 6 | 77 | 30 | 70 | 0 | 69 | 30 | 62 | 13 | 1 | 4 | 19 |
142,268 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/library.py
|
foundations.library.LibraryHook
|
class LibraryHook(foundations.data_structures.Structure):
"""
Defines a library hook used by the :class:`Library` class to bind target library functions.
"""
def __init__(self, **kwargs):
"""
Initializes the class.
Usage::
LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p)
:param name: Name of the target library function to bind.
:type name: unicode
:param arguments_types: Required function arguments type (Refer to Python `ctypes - 15.17.1.7
<http://docs.python.org/library/ctypes.html#specifying-the-required-argument-types-function-prototypes>`_
module for more informations). ( List )
:param return_value: Function return type (Refer to Python `ctypes - 15.17.1.8
<http://docs.python.org/library/ctypes.html#return-types>`_ module for more informations). ( Object )
"""
LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__))
foundations.data_structures.Structure.__init__(self, **kwargs)
|
class LibraryHook(foundations.data_structures.Structure):
'''
Defines a library hook used by the :class:`Library` class to bind target library functions.
'''
def __init__(self, **kwargs):
'''
Initializes the class.
Usage::
LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p)
:param name: Name of the target library function to bind.
:type name: unicode
:param arguments_types: Required function arguments type (Refer to Python `ctypes - 15.17.1.7
<http://docs.python.org/library/ctypes.html#specifying-the-required-argument-types-function-prototypes>`_
module for more informations). ( List )
:param return_value: Function return type (Refer to Python `ctypes - 15.17.1.8
<http://docs.python.org/library/ctypes.html#return-types>`_ module for more informations). ( Object )
'''
pass
| 2 | 2 | 20 | 5 | 3 | 12 | 1 | 3.75 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 33 | 25 | 6 | 4 | 2 | 2 | 15 | 4 | 2 | 2 | 1 | 3 | 0 | 1 |
142,269 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/globals/constants.py
|
foundations.globals.constants.Constants
|
class Constants():
"""
Defines **Foundations** package default constants.
"""
application_name = "Foundations"
"""
:param application_name: Package Application name.
:type application_name: unicode
"""
major_version = "2"
"""
:param major_version: Package major version.
:type major_version: unicode
"""
minor_version = "1"
"""
:param minor_version: Package minor version.
:type minor_version: unicode
"""
change_version = "0"
"""
:param change_version: Package change version.
:type change_version: unicode
"""
version = ".".join((major_version, minor_version, change_version))
"""
:param version: Package version.
:type version: unicode
"""
logger = "Foundations_Logger"
"""
:param logger: Package logger name.
:type logger: unicode
"""
verbosity_level = 3
"""
:param verbosity_level: Default logging verbosity level.
:type verbosity_level: int
"""
verbosity_labels = ("Critical", "Error", "Warning", "Info", "Debug")
"""
:param verbosity_labels: Logging verbosity labels.
:type verbosity_labels: tuple
"""
logging_default_formatter = "Default"
"""
:param logging_default_formatter: Default logging formatter name.
:type logging_default_formatter: unicode
"""
logging_separators = "*" * 96
"""
:param logging_separators: Logging separators.
:type logging_separators: unicode
"""
default_codec = "utf-8"
"""
:param default_codec: Default codec.
:type default_codec: unicode
"""
codec_error = "ignore"
"""
:param codec_error: Default codec error behavior.
:type codec_error: unicode
"""
application_directory = os.sep.join(("Foundations", ".".join((major_version, minor_version))))
"""
:param application_directory: Package Application directory.
:type application_directory: unicode
"""
if platform.system() == "Windows" or platform.system() == "Microsoft" or platform.system() == "Darwin":
provider_directory = "HDRLabs"
"""
:param provider_directory: Package provider directory.
:type provider_directory: unicode
"""
elif platform.system() == "Linux":
provider_directory = ".HDRLabs"
"""
:param provider_directory: Package provider directory.
:type provider_directory: unicode
"""
null_object = "None"
"""
:param null_object: Default null object string.
:type null_object: unicode
"""
|
class Constants():
'''
Defines **Foundations** package default constants.
'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3.53 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 91 | 5 | 19 | 16 | 18 | 67 | 18 | 16 | 17 | 0 | 0 | 1 | 0 |
142,270 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.UserError
|
class UserError(AbstractUserError):
"""
Defines user exception.
"""
pass
|
class UserError(AbstractUserError):
'''
Defines user exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,271 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.PathRemoveError
|
class PathRemoveError(AbstractIOError):
"""
Defines path remove exception.
"""
pass
|
class PathRemoveError(AbstractIOError):
'''
Defines path remove exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,272 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/parsers.py
|
foundations.parsers.AttributeCompound
|
class AttributeCompound(foundations.data_structures.Structure):
"""
Defines a storage object for attributes compounds usually encountered in
`sIBL_GUI <https://github.com/KelSolaar/sIBL_GUI>`_ Templates files.
Some attributes compounds:
- Name = @Name | Standard | String | Template Name
- Background|BGfile = @BGfile
- showCamerasDialog = @showCamerasDialog | 0 | Boolean | Cameras Selection Dialog
"""
def __init__(self, **kwargs):
"""
Initializes the class.
Usage::
AttributeCompound(name="showCamerasDialog",
value="0",
link="@showCamerasDialog",
type="Boolean",
alias="Cameras Selection Dialog")
:param \*\*kwargs: name, value, link, type, alias.
:type \*\*kwargs: dict
"""
LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__))
foundations.data_structures.Structure.__init__(self, **kwargs)
|
class AttributeCompound(foundations.data_structures.Structure):
'''
Defines a storage object for attributes compounds usually encountered in
`sIBL_GUI <https://github.com/KelSolaar/sIBL_GUI>`_ Templates files.
Some attributes compounds:
- Name = @Name | Standard | String | Template Name
- Background|BGfile = @BGfile
- showCamerasDialog = @showCamerasDialog | 0 | Boolean | Cameras Selection Dialog
'''
def __init__(self, **kwargs):
'''
Initializes the class.
Usage::
AttributeCompound(name="showCamerasDialog",
value="0",
link="@showCamerasDialog",
type="Boolean",
alias="Cameras Selection Dialog")
:param \*\*kwargs: name, value, link, type, alias.
:type \*\*kwargs: dict
'''
pass
| 2 | 2 | 19 | 5 | 3 | 11 | 1 | 4.75 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 33 | 32 | 9 | 4 | 2 | 2 | 19 | 4 | 2 | 2 | 1 | 3 | 0 | 1 |
142,273 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/cache.py
|
foundations.cache.Cache
|
class Cache(dict):
"""
Defines the cache object and provides various methods to interact with its content.
Usage:
"""
def __init__(self, **kwargs):
"""
Initializes the class.
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
"""
dict.__init__(self, **kwargs)
def add_content(self, **content):
"""
Adds given content to the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache
{'Luke': 'Skywalker', 'John': 'Doe'}
:param \*\*content: Content to add.
:type \*\*content: \*\*
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Adding '{0}' content to the cache.".format(self.__class__.__name__, content))
self.update(**content)
return True
def remove_content(self, *keys):
"""
Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
{}
:param \*keys: Content to remove.
:type \*keys: \*
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Removing '{0}' content from the cache.".format(self.__class__.__name__, keys))
for key in keys:
if not key in self:
raise KeyError("{0} | '{1}' key doesn't exists in cache content!".format(self.__class__.__name__, key))
del self[key]
return True
def get_content(self, key):
"""
Gets given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.get_content("Luke")
'Skywalker'
:param key: Content to retrieve.
:type key: object
:return: Content.
:rtype: object
"""
LOGGER.debug("> Retrieving '{0}' content from the cache.".format(self.__class__.__name__, key))
return self.get(key)
def flush_content(self):
"""
Flushes the cache content.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.flush_content()
True
>>> cache
{}
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Flushing cache content.".format(self.__class__.__name__))
self.clear()
return True
|
class Cache(dict):
'''
Defines the cache object and provides various methods to interact with its content.
Usage:
'''
def __init__(self, **kwargs):
'''
Initializes the class.
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
'''
pass
def add_content(self, **content):
'''
Adds given content to the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache
{'Luke': 'Skywalker', 'John': 'Doe'}
:param \*\*content: Content to add.
:type \*\*content: \*\*
:return: Method success.
:rtype: bool
'''
pass
def remove_content(self, *keys):
'''
Removes given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.remove_content("Luke", "John")
True
>>> cache
{}
:param \*keys: Content to remove.
:type \*keys: \*
:return: Method success.
:rtype: bool
'''
pass
def get_content(self, key):
'''
Gets given content from the cache.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.get_content("Luke")
'Skywalker'
:param key: Content to retrieve.
:type key: object
:return: Content.
:rtype: object
'''
pass
def flush_content(self):
'''
Flushes the cache content.
Usage::
>>> cache = Cache()
>>> cache.add_content(John="Doe", Luke="Skywalker")
True
>>> cache.flush_content()
True
>>> cache
{}
:return: Method success.
:rtype: bool
'''
pass
| 6 | 6 | 20 | 5 | 4 | 12 | 1 | 3 | 1 | 1 | 0 | 0 | 5 | 0 | 5 | 32 | 114 | 30 | 21 | 7 | 15 | 63 | 21 | 7 | 15 | 3 | 2 | 2 | 7 |
142,274 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.ObjectTypeError
|
class ObjectTypeError(AbstractObjectError):
"""
Defines invalid object type exception.
"""
pass
|
class ObjectTypeError(AbstractObjectError):
'''
Defines invalid object type exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,275 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/data_structures.py
|
foundations.data_structures.Lookup
|
class Lookup(dict):
"""
Extends dict type to provide a lookup by value(s).
Usage:
>>> person = Lookup(firstName="Doe", lastName="John", gender="male")
>>> person.get_first_key_from_value("Doe")
'firstName'
>>> persons = foundations.data_structures.Lookup(John="Doe", Jane="Doe", Luke="Skywalker")
>>> persons.get_keys_from_value("Doe")
['Jane', 'John']
"""
def get_first_key_from_value(self, value):
"""
Gets the first key from given value.
:param value: Value.
:type value: object
:return: Key.
:rtype: object
"""
for key, data in self.iteritems():
if data == value:
return key
def get_keys_from_value(self, value):
"""
Gets the keys from given value.
:param value: Value.
:type value: object
:return: Keys.
:rtype: object
"""
return [key for key, data in self.iteritems() if data == value]
|
class Lookup(dict):
'''
Extends dict type to provide a lookup by value(s).
Usage:
>>> person = Lookup(firstName="Doe", lastName="John", gender="male")
>>> person.get_first_key_from_value("Doe")
'firstName'
>>> persons = foundations.data_structures.Lookup(John="Doe", Jane="Doe", Luke="Skywalker")
>>> persons.get_keys_from_value("Doe")
['Jane', 'John']
'''
def get_first_key_from_value(self, value):
'''
Gets the first key from given value.
:param value: Value.
:type value: object
:return: Key.
:rtype: object
'''
pass
def get_keys_from_value(self, value):
'''
Gets the keys from given value.
:param value: Value.
:type value: object
:return: Keys.
:rtype: object
'''
pass
| 3 | 3 | 12 | 2 | 3 | 7 | 2 | 3.43 | 1 | 0 | 0 | 0 | 2 | 0 | 2 | 29 | 39 | 8 | 7 | 5 | 4 | 24 | 7 | 4 | 4 | 3 | 2 | 2 | 4 |
142,276 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/tests/tests_foundations/tests_nodes.py
|
foundations.tests.tests_foundations.tests_nodes.TestAbstractCompositeNode.test_list_family.FamilyC
|
class FamilyC(AbstractCompositeNode):
__family = "C"
|
class FamilyC(AbstractCompositeNode):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 75 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 5 | 0 | 0 |
142,277 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/tests/tests_foundations/tests_nodes.py
|
foundations.tests.tests_foundations.tests_nodes.TestAbstractCompositeNode.test_list_family.FamilyB
|
class FamilyB(AbstractCompositeNode):
__family = "B"
|
class FamilyB(AbstractCompositeNode):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 75 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 5 | 0 | 0 |
142,278 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/tests/tests_foundations/resources/dummy.py
|
foundations.tests.tests_foundations.resources.dummy.Dummy
|
class Dummy(object):
"""
Defines a dummy class mainly used to test :mod:`foundations.trace` module.
"""
def __init__(self):
self.__attribute = GLOBAL_RETURN_VALUE
@property
def attribute(self):
return self.__attribute
@attribute.setter
def attribute(self, value):
self.__attribute = value
@attribute.deleter
def attribute(self):
return
def __str__(self):
pass
def __repr__(self):
pass
def __private_method(self):
return self.__private_method.__name__
def public_method(self):
return self.public_method.__name__
@foundations.trace.untracable
def untraced_public(self):
return self.untraced_public.__name__
@staticmethod
def static_method():
return Dummy.static_method.__name__
@classmethod
def class_method(cls):
return cls.class_method.__name__
|
class Dummy(object):
'''
Defines a dummy class mainly used to test :mod:`foundations.trace` module.
'''
def __init__(self):
pass
@property
def attribute(self):
pass
@attribute.setter
def attribute(self):
pass
@attribute.deleter
def attribute(self):
pass
def __str__(self):
pass
def __repr__(self):
pass
def __private_method(self):
pass
def public_method(self):
pass
@foundations.trace.untracable
def untraced_public(self):
pass
@staticmethod
def static_method():
pass
@classmethod
def class_method(cls):
pass
| 18 | 1 | 2 | 0 | 2 | 0 | 1 | 0.1 | 1 | 0 | 0 | 1 | 9 | 1 | 11 | 11 | 43 | 11 | 29 | 19 | 11 | 3 | 23 | 13 | 11 | 1 | 1 | 0 | 11 |
142,279 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/tcp_server.py
|
foundations.tcp_server.TCPServer
|
class TCPServer(object):
"""
Defines a TCP server.
"""
def __init__(self, address, port, handler=EchoRequestsHandler):
"""
Initializes the class.
Usage::
>>> tcp_server = TCPServer("127.0.0.1", 16384)
>>> tcp_server.start()
True
>>> tcp_server.stop()
True
:param address: Server address.
:type address: unicode
:param port: Server port list.
:type port: int
:param handler: Request handler. ( SocketServer.BaseRequestHandler )
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
self.__address = None
self.address = address
self.__port = None
self.port = port
self.__handler = None
self.handler = handler
self.__server = None
self.__worker = None
self.__online = False
@property
def address(self):
"""
Property for **self.__address** attribute.
:return: self.__address.
:rtype: unicode
"""
return self.__address
@address.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def address(self, value):
"""
Setter for **self.__address** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"address", value)
self.__address = value
@address.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def address(self):
"""
Deleter for **self.__address** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "address"))
@property
def port(self):
"""
Property for **self.__port** attribute.
:return: self.__port.
:rtype: int
"""
return self.__port
@port.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def port(self, value):
"""
Setter for **self.__port** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format(
"port", value)
assert type(value) >= 0 and type(value) >= 65535, \
"'{0}' attribute: '{1}' value must be in 0-65535 range!".format(
"port", value)
self.__port = value
@port.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def port(self):
"""
Deleter for **self.__port** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "port"))
@property
def handler(self):
"""
Property for **self.__handler** attribute.
:return: self.__handler.
:rtype: unicode
"""
return self.__handler
@handler.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def handler(self, value):
"""
Setter for **self.__handler** attribute.
:param value: Attribute value. ( SocketServer.BaseRequestHandler )
"""
if value is not None:
assert issubclass(value, SocketServer.BaseRequestHandler), \
"'{0}' attribute: '{1}' is not 'SocketServer.BaseRequestHandler' subclass!".format(
"handler", value)
self.__handler = value
self.__handler.container = self
@handler.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def handler(self):
"""
Deleter for **self.__handler** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "handler"))
@property
def online(self):
"""
Property for **self.__online** attribute.
:return: self.__online.
:rtype: unicode
"""
return self.__online
@online.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def online(self, value):
"""
Setter for **self.__online** attribute.
:param value: Attribute value.
:type value: bool
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "online"))
@online.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def online(self):
"""
Deleter for **self.__online** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "online"))
@foundations.exceptions.handle_exceptions(foundations.exceptions.ServerOperationError)
def start(self):
"""
Starts the TCP server.
:return: Method success.
:rtype: bool
"""
if self.__online:
raise foundations.exceptions.ServerOperationError(
"{0} | '{1}' TCP Server is already online!".format(self.__class__.__name__, self))
try:
self.__server = SocketServer.TCPServer(
(self.__address, self.__port), self.__handler)
self.__worker = threading.Thread(
target=self.__server.serve_forever)
self.__worker.setDaemon(True)
self.__worker.start()
self.__online = True
LOGGER.info(
"{0} | TCP Server successfully started with '{1}' address on '{2}' port using '{3}' requests handler!".format(
self.__class__.__name__, self.__address, self.__port, self.__handler.__name__))
return True
except socket.error as error:
if error.errno in (errno.EADDRINUSE, errno.EADDRNOTAVAIL):
LOGGER.warning(
"!> {0} | Cannot start TCP Server, address is already in use on port '{1}'!".format(
self.__class__.__name__, self.__port))
else:
raise error
@foundations.exceptions.handle_exceptions(foundations.exceptions.ServerOperationError)
def stop(self, terminate=False):
"""
Stops the TCP server.
:return: Method success.
:rtype: bool
"""
if not self.__online:
raise foundations.exceptions.ServerOperationError(
"{0} | '{1}' TCP Server is not online!".format(self.__class__.__name__, self))
if not terminate:
self.__server.shutdown()
else:
self.__server._BaseServer__shutdown_request = True
self.__server = None
self.__worker = None
self.__online = False
LOGGER.info("{0} | TCP Server successfully stopped!".format(
self.__class__.__name__))
return True
|
class TCPServer(object):
'''
Defines a TCP server.
'''
def __init__(self, address, port, handler=EchoRequestsHandler):
'''
Initializes the class.
Usage::
>>> tcp_server = TCPServer("127.0.0.1", 16384)
>>> tcp_server.start()
True
>>> tcp_server.stop()
True
:param address: Server address.
:type address: unicode
:param port: Server port list.
:type port: int
:param handler: Request handler. ( SocketServer.BaseRequestHandler )
'''
pass
@property
def address(self):
'''
Property for **self.__address** attribute.
:return: self.__address.
:rtype: unicode
'''
pass
@address.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def address(self):
'''
Setter for **self.__address** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@address.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def address(self):
'''
Deleter for **self.__address** attribute.
'''
pass
@property
def port(self):
'''
Property for **self.__port** attribute.
:return: self.__port.
:rtype: int
'''
pass
@port.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def port(self):
'''
Setter for **self.__port** attribute.
:param value: Attribute value.
:type value: int
'''
pass
@port.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def port(self):
'''
Deleter for **self.__port** attribute.
'''
pass
@property
def handler(self):
'''
Property for **self.__handler** attribute.
:return: self.__handler.
:rtype: unicode
'''
pass
@handler.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def handler(self):
'''
Setter for **self.__handler** attribute.
:param value: Attribute value. ( SocketServer.BaseRequestHandler )
'''
pass
@handler.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def handler(self):
'''
Deleter for **self.__handler** attribute.
'''
pass
@property
def online(self):
'''
Property for **self.__online** attribute.
:return: self.__online.
:rtype: unicode
'''
pass
@online.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def online(self):
'''
Setter for **self.__online** attribute.
:param value: Attribute value.
:type value: bool
'''
pass
@online.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def online(self):
'''
Deleter for **self.__online** attribute.
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.ServerOperationError)
def start(self):
'''
Starts the TCP server.
:return: Method success.
:rtype: bool
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.ServerOperationError)
def stop(self, terminate=False):
'''
Stops the TCP server.
:return: Method success.
:rtype: bool
'''
pass
| 38 | 16 | 13 | 2 | 6 | 5 | 2 | 0.72 | 1 | 8 | 3 | 0 | 15 | 6 | 15 | 15 | 236 | 49 | 109 | 37 | 71 | 78 | 70 | 22 | 54 | 4 | 1 | 2 | 23 |
142,280 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/rotating_backup.py
|
foundations.rotating_backup.RotatingBackup
|
class RotatingBackup(object):
"""
Defines a rotating backup system.
"""
def __init__(self, source=None, destination=None, count=3):
"""
Initializes the class.
.. warning::
Backups destination folder should not be the same than the folder containing the source to be backup!
Usage::
>>> file = "File.txt"
>>> destination = "backup"
>>> backup = RotatingBackup(file, destination)
>>> backup.backup()
True
>>> for i in range(3):
... backup.backup()
...
True
True
True
>>> import os
>>> os.listdir(destination)
['File.txt', 'File.txt.1', 'File.txt.2', 'File.txt.3']
:param source: Backup source.
:type source: unicode
:param destination: Backup destination.
:type destination: unicode
:param count: Backups count.
:type count: int
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
# --- Setting class attributes. ---
self.__source = None
self.__source = source
self.__destination = None
self.__destination = destination
self.__count = None
self.__count = count
@property
def source(self):
"""
Property for **self.__source** attribute.
:return: self.__source.
:rtype: unicode
"""
return self.__source
@source.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def source(self, value):
"""
Setter for **self.__source** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"source", value)
assert os.path.exists(
value), "'{0}' attribute: '{1}' file doesn't exists!".format("source", value)
self.__source = value
@source.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def source(self):
"""
Deleter for **self.__source** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "source"))
@property
def destination(self):
"""
Property for **self.__destination** attribute.
:return: self.__destination.
:rtype: unicode
"""
return self.__destination
@destination.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def destination(self, value):
"""
Setter for **self.__destination** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"destination", value)
self.__destination = value
@destination.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def destination(self):
"""
Deleter for **self.__destination** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "destination"))
@property
def count(self):
"""
Property for **self.__count** attribute.
:return: self.__count.
:rtype: int
"""
return self.__count
@count.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def count(self, value):
"""
Setter for **self.__count** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format(
"count", value)
assert value > 0, "'{0}' attribute: '{1}' need to be exactly positive!".format(
"count", value)
self.__count = value
@count.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def count(self):
"""
Deleter for **self.__count** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "count"))
def backup(self):
"""
Does the rotating backup.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Storing '{0}' file backup.".format(self.__source))
foundations.common.path_exists(
self.__destination) or foundations.io.set_directory(self.__destination)
destination = os.path.join(
self.__destination, os.path.basename(self.__source))
for i in range(self.__count - 1, 0, -1):
sfn = "{0}.{1}".format(destination, i)
dfn = "{0}.{1}".format(destination, i + 1)
if foundations.common.path_exists(sfn):
if foundations.common.path_exists(dfn):
foundations.io.remove(dfn)
os.renames(sfn, dfn)
foundations.common.path_exists(destination) and os.rename(
destination, destination + ".1")
foundations.io.copy(self.__source, destination)
return True
|
class RotatingBackup(object):
'''
Defines a rotating backup system.
'''
def __init__(self, source=None, destination=None, count=3):
'''
Initializes the class.
.. warning::
Backups destination folder should not be the same than the folder containing the source to be backup!
Usage::
>>> file = "File.txt"
>>> destination = "backup"
>>> backup = RotatingBackup(file, destination)
>>> backup.backup()
True
>>> for i in range(3):
... backup.backup()
...
True
True
True
>>> import os
>>> os.listdir(destination)
['File.txt', 'File.txt.1', 'File.txt.2', 'File.txt.3']
:param source: Backup source.
:type source: unicode
:param destination: Backup destination.
:type destination: unicode
:param count: Backups count.
:type count: int
'''
pass
@property
def source(self):
'''
Property for **self.__source** attribute.
:return: self.__source.
:rtype: unicode
'''
pass
@source.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def source(self):
'''
Setter for **self.__source** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@source.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def source(self):
'''
Deleter for **self.__source** attribute.
'''
pass
@property
def destination(self):
'''
Property for **self.__destination** attribute.
:return: self.__destination.
:rtype: unicode
'''
pass
@destination.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def destination(self):
'''
Setter for **self.__destination** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@destination.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def destination(self):
'''
Deleter for **self.__destination** attribute.
'''
pass
@property
def count(self):
'''
Property for **self.__count** attribute.
:return: self.__count.
:rtype: int
'''
pass
@count.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def count(self):
'''
Setter for **self.__count** attribute.
:param value: Attribute value.
:type value: int
'''
pass
@count.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def count(self):
'''
Deleter for **self.__count** attribute.
'''
pass
def backup(self):
'''
Does the rotating backup.
:return: Method success.
:rtype: bool
'''
pass
| 27 | 12 | 14 | 2 | 5 | 6 | 2 | 1.06 | 1 | 4 | 1 | 0 | 11 | 3 | 11 | 11 | 180 | 36 | 70 | 28 | 43 | 74 | 49 | 19 | 37 | 4 | 1 | 3 | 17 |
142,281 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/pkzip.py
|
foundations.pkzip.Pkzip
|
class Pkzip(object):
"""
Defines methods to manipulate zip files.
"""
def __init__(self, archive=None):
"""
Initializes the class.
Usage::
>>> import tempfile
>>> temp_directory = tempfile.mkdtemp()
>>> zip_file = Pkzip("zip_file.zip")
>>> zip_file.extract(temp_directory)
True
:param archive: Archive to manipulate.
:type archive: unicode
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
# --- Setting class attributes. ---
self.__archive = None
self.archive = archive
@property
def archive(self):
"""
Property for **self.__archive** attribute.
:return: self.__archive.
:rtype: unicode
"""
return self.__archive
@archive.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def archive(self, value):
"""
Setter for **self.__archive** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"archive", value)
assert os.path.exists(
value), "'{0}' attribute: '{1}' file doesn't exists!".format("archive", value)
self.__archive = value
@archive.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def archive(self):
"""
Deleter for **self.__archive** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "archive"))
@foundations.exceptions.handle_exceptions(foundations.exceptions.DirectoryExistsError,
foundations.exceptions.FileExistsError,
zipfile.BadZipfile)
def extract(self, target):
"""
Extracts the archive file to given directory.
:param target: Target extraction directory.
:type target: unicode
:return: Method success.
:rtype: bool
"""
if not foundations.common.path_exists(self.__archive):
raise foundations.exceptions.FileExistsError("{0} | '{1}' file doesn't exists!".format(
self.__class__.__name__, self.__archive))
if not foundations.common.path_exists(target):
raise foundations.exceptions.DirectoryExistsError("{0} | '{1}' directory doesn't exists!".format(
self.__class__.__name__, target))
archive = zipfile.ZipFile(self.__archive)
content = archive.namelist()
directories = [item for item in content if item.endswith("/")]
files = [item for item in content if not item.endswith("/")]
directories.sort()
directories.reverse()
for directory in directories:
not os.path.isdir(os.path.join(target, directory)) and foundations.io.set_directory(
os.path.join(target, directory))
for file in files:
LOGGER.info("{0} | Extracting '{1}' file!".format(
self.__class__.__name__, file))
with open(os.path.join(target, file), "w") as output:
buffer = StringIO(archive.read(file))
bufferSize = 2 ** 20
data = buffer.read(bufferSize)
while data:
output.write(data)
data = buffer.read(bufferSize)
return True
|
class Pkzip(object):
'''
Defines methods to manipulate zip files.
'''
def __init__(self, archive=None):
'''
Initializes the class.
Usage::
>>> import tempfile
>>> temp_directory = tempfile.mkdtemp()
>>> zip_file = Pkzip("zip_file.zip")
>>> zip_file.extract(temp_directory)
True
:param archive: Archive to manipulate.
:type archive: unicode
'''
pass
@property
def archive(self):
'''
Property for **self.__archive** attribute.
:return: self.__archive.
:rtype: unicode
'''
pass
@archive.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def archive(self):
'''
Setter for **self.__archive** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@archive.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def archive(self):
'''
Deleter for **self.__archive** attribute.
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.DirectoryExistsError,
foundations.exceptions.FileExistsError,
zipfile.BadZipfile)
def extract(self, target):
'''
Extracts the archive file to given directory.
:param target: Target extraction directory.
:type target: unicode
:return: Method success.
:rtype: bool
'''
pass
| 12 | 6 | 18 | 4 | 8 | 6 | 2 | 0.7 | 1 | 5 | 3 | 0 | 5 | 1 | 5 | 5 | 108 | 23 | 50 | 23 | 36 | 35 | 37 | 16 | 31 | 6 | 1 | 3 | 11 |
142,282 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/parsers.py
|
foundations.parsers.SectionsFileParser
|
class SectionsFileParser(foundations.io.File):
"""
Defines methods to parse sections file format files,
an alternative configuration file parser is available directly with Python: :class:`ConfigParser.ConfigParser`.
The parser given by this class has some major differences with Python :class:`ConfigParser.ConfigParser`:
- | Sections and attributes are stored in their appearance order by default.
( Using Python :class:`collections.OrderedDict` )
- | A default section ( **_default** ) will store orphans attributes
( Attributes appearing before any declared section ).
- File comments are stored inside the :obj:`SectionsFileParser.comments` class property.
- | Sections, attributes and values are whitespaces stripped by default
but can also be stored with their leading and trailing whitespaces.
- | Values are quotations markers stripped by default
but can also be stored with their leading and trailing quotations markers.
- Attributes are namespaced by default allowing sections merge without keys collisions.
"""
def __init__(self,
file=None,
splitters=("=", ":"),
namespace_splitter="|",
comment_limiters=(";", "#"),
comment_marker="#",
quotation_markers=("\"", "'", "`"),
raw_section_content_identifier="__raw__",
defaults_section="_defaults",
preserve_order=True):
"""
Initializes the class.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse(strip_comments=False)
<foundations.parsers.SectionsFileParser object at 0x293892011>
>>> sections_file_parser.sections.keys()
[u'Section A', u'Section B']
>>> sections_file_parser.comments
OrderedDict([(u'Section A|#0', {u'content': u'Comment.', u'id': 0})])
:param file: Current file path.
:type file: unicode
:param splitters: Splitter characters.
:type splitters: tuple or list
:param namespace_splitter: Namespace splitters character.
:type namespace_splitter: unicode
:param comment_limiters: Comment limiters characters.
:type comment_limiters: tuple or list
:param comment_marker: Character use to prefix extracted comments idientifiers.
:type comment_marker: unicode
:param quotation_markers: Quotation markers characters.
:type quotation_markers: tuple or list
:param raw_section_content_identifier: Raw section content identifier.
:type raw_section_content_identifier: unicode
:param defaults_section: Default section name.
:type defaults_section: unicode
:param preserve_order: Data order is preserved.
:type preserve_order: bool
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
foundations.io.File.__init__(self, file)
# --- Setting class attributes. ---
self.__splitters = None
self.splitters = splitters
self.__namespace_splitter = None
self.namespace_splitter = namespace_splitter
self.__comment_limiters = None
self.comment_limiters = comment_limiters
self.__comment_marker = None
self.comment_marker = comment_marker
self.__quotation_markers = None
self.quotation_markers = quotation_markers
self.__raw_section_content_identifier = None
self.raw_section_content_identifier = raw_section_content_identifier
self.__defaults_section = None
self.defaults_section = defaults_section
self.__preserve_order = None
self.preserve_order = preserve_order
if not preserve_order:
self.__sections = {}
self.__comments = {}
else:
self.__sections = OrderedDict()
self.__comments = OrderedDict()
self.__parsing_errors = []
@property
def splitters(self):
"""
Property for **self.__splitters** attribute.
:return: self.__splitters.
:rtype: tuple or list
"""
return self.__splitters
@splitters.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def splitters(self, value):
"""
Setter for **self.__splitters** attribute.
:param value: Attribute value.
:type value: tuple or list
"""
if value is not None:
assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format(
"splitters", value)
for element in value:
assert type(element) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"splitters", element)
assert len(element) == 1, "'{0}' attribute: '{1}' has multiples characters!".format(
"splitter", element)
assert not re.search(r"\w", element), "'{0}' attribute: '{1}' is an alphanumeric character!".format(
"splitter", element)
self.__splitters = value
@splitters.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def splitters(self):
"""
Deleter for **self.__splitters** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "splitters"))
@property
def namespace_splitter(self):
"""
Property for **self.__namespace_splitter** attribute.
:return: self.__namespace_splitter.
:rtype: unicode
"""
return self.__namespace_splitter
@namespace_splitter.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def namespace_splitter(self, value):
"""
Setter for **self.__namespace_splitter** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"namespace_splitter", value)
assert len(value) == 1, "'{0}' attribute: '{1}' has multiples characters!".format("namespace_splitter",
value)
assert not re.search(r"\w", value), "'{0}' attribute: '{1}' is an alphanumeric character!".format(
"namespace_splitter", value)
self.__namespace_splitter = value
@namespace_splitter.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def namespace_splitter(self):
"""
Deleter for **self.__namespace_splitter** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "namespace_splitter"))
@property
def comment_limiters(self):
"""
Property for **self.__comment_limiters** attribute.
:return: self.__comment_limiters.
:rtype: tuple or list
"""
return self.__comment_limiters
@comment_limiters.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def comment_limiters(self, value):
"""
Setter for **self.__comment_limiters** attribute.
:param value: Attribute value.
:type value: tuple or list
"""
if value is not None:
assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format(
"comment_limiters", value)
for element in value:
assert type(element) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"comment_limiters", element)
self.__comment_limiters = value
@comment_limiters.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def comment_limiters(self):
"""
Deleter for **self.__comment_limiters** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "comment_limiters"))
@property
def comment_marker(self):
"""
Property for **self.__comment_marker** attribute.
:return: self.__comment_marker.
:rtype: unicode
"""
return self.__comment_marker
@comment_marker.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def comment_marker(self, value):
"""
Setter for **self.__comment_marker** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"comment_marker", value)
assert not re.search(r"\w", value), "'{0}' attribute: '{1}' is an alphanumeric character!".format(
"comment_marker", value)
self.__comment_marker = value
@comment_marker.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def comment_marker(self):
"""
Deleter for **self.__comment_marker** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "comment_marker"))
@property
def quotation_markers(self):
"""
Property for **self.__quotation_markers** attribute.
:return: self.__quotation_markers.
:rtype: tuple or list
"""
return self.__quotation_markers
@quotation_markers.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def quotation_markers(self, value):
"""
Setter for **self.__quotation_markers** attribute.
:param value: Attribute value.
:type value: tuple or list
"""
if value is not None:
assert type(value) in (tuple, list), "'{0}' attribute: '{1}' type is not 'tuple' or 'list'!".format(
"quotation_markers", value)
for element in value:
assert type(element) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"quotation_markers", element)
assert len(element) == 1, "'{0}' attribute: '{1}' has multiples characters!".format("quotation_markers",
element)
assert not re.search(r"\w", element), "'{0}' attribute: '{1}' is an alphanumeric character!".format(
"quotation_markers", element)
self.__quotation_markers = value
@quotation_markers.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def quotation_markers(self):
"""
Deleter for **self.__quotation_markers** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "quotation_markers"))
@property
def raw_section_content_identifier(self):
"""
Property for **self. __raw_section_content_identifier** attribute.
:return: self.__raw_section_content_identifier.
:rtype: unicode
"""
return self.__raw_section_content_identifier
@raw_section_content_identifier.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def raw_section_content_identifier(self, value):
"""
Setter for **self. __raw_section_content_identifier** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"raw_section_content_identifier", value)
self.__raw_section_content_identifier = value
@raw_section_content_identifier.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def raw_section_content_identifier(self):
"""
Deleter for **self. __raw_section_content_identifier** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "raw_section_content_identifier"))
@property
def defaults_section(self):
"""
Property for **self.__defaults_section** attribute.
:return: self.__defaults_section.
:rtype: unicode
"""
return self.__defaults_section
@defaults_section.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def defaults_section(self, value):
"""
Setter for **self.__defaults_section** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"defaults_section", value)
self.__defaults_section = value
@defaults_section.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def defaults_section(self):
"""
Deleter for **self.__defaults_section** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "defaults_section"))
@property
def sections(self):
"""
Property for **self.__sections** attribute.
:return: self.__sections.
:rtype: OrderedDict or dict
"""
return self.__sections
@sections.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def sections(self, value):
"""
Setter for **self.__sections** attribute.
:param value: Attribute value.
:type value: OrderedDict or dict
"""
if value is not None:
assert type(value) in (OrderedDict, dict), "'{0}' attribute: '{1}' type is not \
'OrderedDict' or 'dict'!".format("sections", value)
for key, element in value.iteritems():
assert type(key) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"sections", key)
assert type(element) in (OrderedDict, dict), "'{0}' attribute: '{1}' type is not \
'OrderedDict' or 'dict'!".format("sections", key)
self.__sections = value
@sections.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def sections(self):
"""
Deleter for **self.__sections** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "sections"))
@property
def comments(self):
"""
Property for **self.__comments** attribute.
:return: self.__comments.
:rtype: OrderedDict or dict
"""
return self.__comments
@comments.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def comments(self, value):
"""
Setter for **self.__comments** attribute.
:param value: Attribute value.
:type value: OrderedDict or dict
"""
if value is not None:
assert type(value) in (OrderedDict, dict), "'{0}' attribute: '{1}' type is not \
'OrderedDict' or 'dict'!".format("comments", value)
for key, element in value.iteritems():
assert type(key) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"comments", key)
assert type(element) in (OrderedDict, dict), "'{0}' attribute: '{1}' type is not \
'OrderedDict' or 'dict'!".format("comments", key)
self.__comments = value
@comments.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def comments(self):
"""
Deleter for **self.__comments** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "comments"))
@property
def parsing_errors(self):
"""
Property for **self.__parsing_errors** attribute.
:return: self.__parsing_errors.
:rtype: list
"""
return self.__parsing_errors
@parsing_errors.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def parsing_errors(self, value):
"""
Setter for **self.__parsing_errors** attribute.
:param value: Attribute value.
:type value: list
"""
if value is not None:
assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format(
"parsing_errors", value)
for element in value:
assert issubclass(element.__class__, foundations.exceptions.AbstractParsingError), \
"'{0}' attribute: '{1}' is not a '{2}' subclass!".format(
"parsing_errors", element, foundations.exceptions.AbstractParsingError.__class__.__name__)
self.__parsing_errors = value
@parsing_errors.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def parsing_errors(self):
"""
Deleter for **self.__parsing_errors** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "parsing_errors"))
@property
def preserve_order(self):
"""
Property for **self.__preserve_order** attribute.
:return: self.__preserve_order.
:rtype: bool
"""
return self.__preserve_order
@preserve_order.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def preserve_order(self, value):
"""
Setter method for **self.__preserve_order** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format(
"preserve_order", value)
self.__preserve_order = value
@preserve_order.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def preserve_order(self):
"""
Deleter method for **self.__preserve_order** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "preserve_order"))
def __getitem__(self, section):
"""
Reimplements the :meth:`object.__getitem__` method.
:param section: Section name.
:type section: unicode
:return: Layout.
:rtype: Layout
"""
return self.__sections.__getitem__(section)
def __setitem__(self, section, value):
"""
Reimplements the :meth:`object.__getitem__` method.
:param section: Section name.
:type section: unicode
:param section: Value.
:type section: dict
:return: Layout.
:rtype: Layout
"""
return self.__sections.__setitem__(section, value)
def __iter__(self):
"""
Reimplements the :meth:`object.__iter__` method.
:return: Layouts iterator.
:rtype: object
"""
return self.__sections.iteritems()
def __contains__(self, section):
"""
Reimplements the :meth:`object.__contains__` method.
:param section: Section name.
:type section: unicode
:return: Section existence.
:rtype: bool
"""
return self.section_exists(section)
def __len__(self):
"""
Reimplements the :meth:`object.__len__` method.
:return: Sections count.
:rtype: int
"""
return len(self.__sections)
@foundations.exceptions.handle_exceptions(foundations.exceptions.FileStructureParsingError)
def parse(self,
raw_sections=None,
namespaces=True,
strip_comments=True,
strip_whitespaces=True,
strip_quotation_markers=True,
raise_parsing_errors=True):
"""
Process the file content and extracts the sections / attributes
as nested :class:`collections.OrderedDict` dictionaries or dictionaries.
Usage::
>>> content = ["; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse(strip_comments=False)
<foundations.parsers.SectionsFileParser object at 0x860323123>
>>> sections_file_parser.sections.keys()
[u'_defaults']
>>> sections_file_parser.sections["_defaults"].values()
[u'Value A', u'Value B']
>>> sections_file_parser.parse(strip_comments=False, strip_quotation_markers=False)
<foundations.parsers.SectionsFileParser object at 0x860323123>
>>> sections_file_parser.sections["_defaults"].values()
[u'"Value A"', u'"Value B"']
>>> sections_file_parser.comments
OrderedDict([(u'_defaults|#0', {u'content': u'Comment.', u'id': 0})])
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x860323123>
>>> sections_file_parser.sections["_defaults"]
OrderedDict([(u'_defaults|Attribute 1', u'Value A'), (u'_defaults|Attribute 2', u'Value B')])
>>> sections_file_parser.parse(namespaces=False)
<foundations.parsers.SectionsFileParser object at 0x860323123>
>>> sections_file_parser.sections["_defaults"]
OrderedDict([(u'Attribute 1', u'Value A'), (u'Attribute 2', u'Value B')])
:param raw_sections: Ignored raw sections.
:type raw_sections: tuple or list
:param namespaces: Attributes and comments are namespaced.
:type namespaces: bool
:param strip_comments: Comments are stripped.
:type strip_comments: bool
:param strip_whitespaces: Whitespaces are stripped.
:type strip_whitespaces: bool
:param strip_quotation_markers: Attributes values quotation markers are stripped.
:type strip_quotation_markers: bool
:param raise_parsing_errors: Raise parsing errors.
:type raise_parsing_errors: bool
:return: SectionFileParser instance.
:rtype: SectionFileParser
"""
LOGGER.debug("> Reading sections from: '{0}'.".format(self.path))
if not self.content:
self.read()
attributes = {} if not self.__preserve_order else OrderedDict()
section = self.__defaults_section
raw_sections = raw_sections or []
commentId = 0
for i, line in enumerate(self.content):
# Comments matching.
search = re.search(
r"^\s*[{0}](?P<comment>.+)$".format("".join(self.__comment_limiters)), line)
if search:
if not strip_comments:
comment = namespaces and foundations.namespace.set_namespace(section, "{0}{1}".format(
self.__comment_marker, commentId), self.__namespace_splitter) or \
"{0}{1}".format(self.__comment_marker, commentId)
self.__comments[comment] = {"id": commentId, "content": strip_whitespaces and
search.group(
"comment").strip() or search.group(
"comment")}
commentId += 1
continue
# Sections matching.
search = re.search(r"^\s*\[(?P<section>.+)\]\s*$", line)
if search:
section = strip_whitespaces and search.group(
"section").strip() or search.group("section")
if not self.__preserve_order:
attributes = {}
else:
attributes = OrderedDict()
rawContent = []
continue
if section in raw_sections:
rawContent.append(line)
attributes[self.__raw_section_content_identifier] = rawContent
else:
# Empty line matching.
search = re.search(r"^\s*$", line)
if search:
continue
# Attributes matching.
search = re.search(r"^(?P<attribute>.+?)[{0}](?P<value>.+)$".format("".join(self.__splitters)), line) \
or re.search(r"^(?P<attribute>.+?)[{0}]\s*$".format("".join(self.__splitters)), line)
if search:
attribute = search.group("attribute").strip(
) if strip_whitespaces else search.group("attribute")
attribute = foundations.namespace.set_namespace(section, attribute, self.__namespace_splitter) \
if namespaces else attribute
if len(search.groups()) == 2:
value = search.group("value").strip(
) if strip_whitespaces else search.group("value")
attributes[attribute] = value.strip("".join(self.__quotation_markers)) \
if strip_quotation_markers else value
else:
attributes[attribute] = None
else:
self.__parsing_errors.append(foundations.exceptions.AttributeStructureParsingError(
"Attribute structure is invalid: {0}".format(line), i + 1))
self.__sections[section] = attributes
LOGGER.debug("> Sections: '{0}'.".format(self.__sections))
LOGGER.debug("> '{0}' file parsing done!".format(self.path))
if self.__parsing_errors and raise_parsing_errors:
raise foundations.exceptions.FileStructureParsingError(
"{0} | '{1}' structure is invalid, parsing exceptions occured!".format(self.__class__.__name__,
self.path))
return self
def section_exists(self, section):
"""
Checks if given section exists.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x845683844>
>>> sections_file_parser.section_exists("Section A")
True
>>> sections_file_parser.section_exists("Section C")
False
:param section: Section to check existence.
:type section: unicode
:return: Section existence.
:rtype: bool
"""
if section in self.__sections:
LOGGER.debug(
"> '{0}' section exists in '{1}'.".format(section, self))
return True
else:
LOGGER.debug(
"> '{0}' section doesn't exists in '{1}'.".format(section, self))
return False
def attribute_exists(self, attribute, section):
"""
Checks if given attribute exists.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x234564563>
>>> sections_file_parser.attribute_exists("Attribute 1", "Section A")
True
>>> sections_file_parser.attribute_exists("Attribute 2", "Section A")
False
:param attribute: Attribute to check existence.
:type attribute: unicode
:param section: Section to search attribute into.
:type section: unicode
:return: Attribute existence.
:rtype: bool
"""
if foundations.namespace.remove_namespace(attribute, root_only=True) in self.get_attributes(section,
strip_namespaces=True):
LOGGER.debug("> '{0}' attribute exists in '{1}' section.".format(
attribute, section))
return True
else:
LOGGER.debug("> '{0}' attribute doesn't exists in '{1}' section.".format(
attribute, section))
return False
def get_attributes(self, section, strip_namespaces=False):
"""
Returns given section attributes.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x125698322>
>>> sections_file_parser.get_attributes("Section A")
OrderedDict([(u'Section A|Attribute 1', u'Value A')])
>>> sections_file_parser.preserve_order=False
>>> sections_file_parser.get_attributes("Section A")
{u'Section A|Attribute 1': u'Value A'}
>>> sections_file_parser.preserve_order=True
>>> sections_file_parser.get_attributes("Section A", strip_namespaces=True)
OrderedDict([(u'Attribute 1', u'Value A')])
:param section: Section containing the requested attributes.
:type section: unicode
:param strip_namespaces: Strip namespaces while retrieving attributes.
:type strip_namespaces: bool
:return: Attributes.
:rtype: OrderedDict or dict
"""
LOGGER.debug("> Getting section '{0}' attributes.".format(section))
attributes = OrderedDict() if self.__preserve_order else dict()
if not self.section_exists(section):
return attributes
if strip_namespaces:
for attribute, value in self.__sections[section].iteritems():
attributes[foundations.namespace.remove_namespace(
attribute, root_only=True)] = value
else:
attributes.update(self.__sections[section])
LOGGER.debug("> Attributes: '{0}'.".format(attributes))
return attributes
def get_all_attributes(self):
"""
Returns all sections attributes.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x845683844>
>>> sections_file_parser.get_all_attributes()
OrderedDict([(u'Section A|Attribute 1', u'Value A'), (u'Section B|Attribute 2', u'Value B')])
>>> sections_file_parser.preserve_order=False
>>> sections_file_parser.get_all_attributes()
{u'Section B|Attribute 2': u'Value B', u'Section A|Attribute 1': u'Value A'}
:return: All sections / files attributes.
:rtype: OrderedDict or dict
"""
all_attributes = OrderedDict() if self.__preserve_order else dict()
for attributes in self.__sections.itervalues():
for attribute, value in attributes.iteritems():
all_attributes[attribute] = value
return all_attributes
@foundations.exceptions.handle_exceptions(foundations.exceptions.FileStructureParsingError)
def get_value(self, attribute, section, default=""):
"""
Returns requested attribute value.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x679302423>
>>> sections_file_parser.get_value("Attribute 1", "Section A")
u'Value A'
:param attribute: Attribute name.
:type attribute: unicode
:param section: Section containing the searched attribute.
:type section: unicode
:param default: Default return value.
:type default: object
:return: Attribute value.
:rtype: unicode
"""
if not self.attribute_exists(attribute, section):
return default
if attribute in self.__sections[section]:
value = self.__sections[section][attribute]
elif foundations.namespace.set_namespace(section, attribute) in self.__sections[section]:
value = self.__sections[section][foundations.namespace.set_namespace(
section, attribute)]
LOGGER.debug(
"> Attribute: '{0}', value: '{1}'.".format(attribute, value))
return value
def set_value(self, attribute, section, value):
"""
Sets requested attribute value.
Usage::
>>> content = ["[Section A]\\n", "; Comment.\\n", "Attribute 1 = \\"Value A\\"\\n", "\\n", \
"[Section B]\\n", "Attribute 2 = \\"Value B\\"\\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x109304209>
>>> sections_file_parser.set_value("Attribute 3", "Section C", "Value C")
True
:param attribute: Attribute name.
:type attribute: unicode
:param section: Section containing the searched attribute.
:type section: unicode
:param value: Attribute value.
:type value: object
:return: Definition success.
:rtype: bool
"""
if not self.section_exists(section):
LOGGER.debug("> Adding '{0}' section.".format(section))
self.__sections[section] = OrderedDict(
) if self.__preserve_order else dict()
self.__sections[section][attribute] = value
return True
def write(self,
namespaces=False,
splitter="=",
comment_limiter=(";"),
spaces_around_splitter=True,
space_after_comment_limiter=True):
"""
Writes defined file using :obj:`SectionsFileParser.sections` and
:obj:`SectionsFileParser.comments` class properties content.
Usage::
>>> sections = {"Section A": {"Section A|Attribute 1": "Value A"}, \
"Section B": {"Section B|Attribute 2": "Value B"}}
>>> sections_file_parser = SectionsFileParser("SectionsFile.rc")
>>> sections_file_parser.sections = sections
>>> sections_file_parser.write()
True
>>> sections_file_parser.read()
u'[Section A]\\nAttribute 1 = Value A\\n\\n[Section B]\\nAttribute 2 = Value B\\n'
:param namespaces: Attributes are namespaced.
:type namespaces: bool
:param splitter: Splitter character.
:type splitter: unicode
:param comment_limiter: Comment limiter character.
:type comment_limiter: unicode
:param spaces_around_splitter: Spaces around attributes and value splitters.
:type spaces_around_splitter: bool
:param space_after_comment_limiter: Space after comments limiter.
:type space_after_comment_limiter: bool
:return: Method success.
:rtype: bool
"""
self.uncache()
LOGGER.debug("> Setting '{0}' file content.".format(self.path))
attribute_template = "{{0}} {0} {{1}}\n".format(splitter) if spaces_around_splitter else \
"{{0}}{0}{{1}}\n".format(splitter)
attribute_template = foundations.strings.replace(
attribute_template, {"{{": "{", "}}": "}"})
comment_template = space_after_comment_limiter and "{0} {{0}}\n".format(comment_limiter) or \
"{0}{{0}}\n".format(comment_limiter)
if self.__defaults_section in self.__sections:
LOGGER.debug("> Appending '{0}' default section.".format(
self.__defaults_section))
if self.__comments:
for comment, value in self.__comments.iteritems():
if self.__defaults_section in comment:
value = value["content"] or ""
LOGGER.debug(
"> Appending '{0}' comment with '{1}' value.".format(comment, value))
self.content.append(comment_template.format(value))
for attribute, value in self.__sections[self.__defaults_section].iteritems():
attribute = namespaces and attribute or foundations.namespace.remove_namespace(attribute,
self.__namespace_splitter,
root_only=True)
value = value or ""
LOGGER.debug(
"> Appending '{0}' attribute with '{1}' value.".format(attribute, value))
self.content.append(
attribute_template.format(attribute, value))
self.content.append("\n")
for i, section in enumerate(self.__sections):
LOGGER.debug("> Appending '{0}' section.".format(section))
self.content.append("[{0}]\n".format(section))
if self.__comments:
for comment, value in self.__comments.iteritems():
if section in comment:
value = value["content"] or ""
LOGGER.debug(
"> Appending '{0}' comment with '{1}' value.".format(comment, value))
self.content.append(comment_template.format(value))
for attribute, value in self.__sections[section].iteritems():
if foundations.namespace.remove_namespace(attribute) == self.__raw_section_content_identifier:
LOGGER.debug(
"> Appending '{0}' raw section content.".format(section))
for line in value:
self.content.append(line)
else:
LOGGER.debug("> Appending '{0}' section.".format(section))
attribute = namespaces and attribute or foundations.namespace.remove_namespace(attribute,
self.__namespace_splitter,
root_only=True)
value = value or ""
LOGGER.debug(
"> Appending '{0}' attribute with '{1}' value.".format(attribute, value))
self.content.append(
attribute_template.format(attribute, value))
if i != len(self.__sections) - 1:
self.content.append("\n")
foundations.io.File.write(self)
return True
|
class SectionsFileParser(foundations.io.File):
'''
Defines methods to parse sections file format files,
an alternative configuration file parser is available directly with Python: :class:`ConfigParser.ConfigParser`.
The parser given by this class has some major differences with Python :class:`ConfigParser.ConfigParser`:
- | Sections and attributes are stored in their appearance order by default.
( Using Python :class:`collections.OrderedDict` )
- | A default section ( **_default** ) will store orphans attributes
( Attributes appearing before any declared section ).
- File comments are stored inside the :obj:`SectionsFileParser.comments` class property.
- | Sections, attributes and values are whitespaces stripped by default
but can also be stored with their leading and trailing whitespaces.
- | Values are quotations markers stripped by default
but can also be stored with their leading and trailing quotations markers.
- Attributes are namespaced by default allowing sections merge without keys collisions.
'''
def __init__(self,
file=None,
splitters=("=", ":"),
namespace_splitter="|",
comment_limiters=(";", "#"),
comment_marker="#",
quotation_markers=("\"", "'", "`"),
raw_section_content_identifier="__raw__",
defaults_section="_defaults",
preserve_order=True):
'''
Initializes the class.
Usage::
>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse(strip_comments=False)
<foundations.parsers.SectionsFileParser object at 0x293892011>
>>> sections_file_parser.sections.keys()
[u'Section A', u'Section B']
>>> sections_file_parser.comments
OrderedDict([(u'Section A|#0', {u'content': u'Comment.', u'id': 0})])
:param file: Current file path.
:type file: unicode
:param splitters: Splitter characters.
:type splitters: tuple or list
:param namespace_splitter: Namespace splitters character.
:type namespace_splitter: unicode
:param comment_limiters: Comment limiters characters.
:type comment_limiters: tuple or list
:param comment_marker: Character use to prefix extracted comments idientifiers.
:type comment_marker: unicode
:param quotation_markers: Quotation markers characters.
:type quotation_markers: tuple or list
:param raw_section_content_identifier: Raw section content identifier.
:type raw_section_content_identifier: unicode
:param defaults_section: Default section name.
:type defaults_section: unicode
:param preserve_order: Data order is preserved.
:type preserve_order: bool
'''
pass
@property
def splitters(self):
'''
Property for **self.__splitters** attribute.
:return: self.__splitters.
:rtype: tuple or list
'''
pass
@splitters.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def splitters(self):
'''
Setter for **self.__splitters** attribute.
:param value: Attribute value.
:type value: tuple or list
'''
pass
@splitters.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def splitters(self):
'''
Deleter for **self.__splitters** attribute.
'''
pass
@property
def namespace_splitter(self):
'''
Property for **self.__namespace_splitter** attribute.
:return: self.__namespace_splitter.
:rtype: unicode
'''
pass
@namespace_splitter.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def namespace_splitter(self):
'''
Setter for **self.__namespace_splitter** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@namespace_splitter.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def namespace_splitter(self):
'''
Deleter for **self.__namespace_splitter** attribute.
'''
pass
@property
def comment_limiters(self):
'''
Property for **self.__comment_limiters** attribute.
:return: self.__comment_limiters.
:rtype: tuple or list
'''
pass
@comment_limiters.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def comment_limiters(self):
'''
Setter for **self.__comment_limiters** attribute.
:param value: Attribute value.
:type value: tuple or list
'''
pass
@comment_limiters.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def comment_limiters(self):
'''
Deleter for **self.__comment_limiters** attribute.
'''
pass
@property
def comment_marker(self):
'''
Property for **self.__comment_marker** attribute.
:return: self.__comment_marker.
:rtype: unicode
'''
pass
@comment_marker.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def comment_marker(self):
'''
Setter for **self.__comment_marker** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@comment_marker.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def comment_marker(self):
'''
Deleter for **self.__comment_marker** attribute.
'''
pass
@property
def quotation_markers(self):
'''
Property for **self.__quotation_markers** attribute.
:return: self.__quotation_markers.
:rtype: tuple or list
'''
pass
@quotation_markers.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def quotation_markers(self):
'''
Setter for **self.__quotation_markers** attribute.
:param value: Attribute value.
:type value: tuple or list
'''
pass
@quotation_markers.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def quotation_markers(self):
'''
Deleter for **self.__quotation_markers** attribute.
'''
pass
@property
def raw_section_content_identifier(self):
'''
Property for **self. __raw_section_content_identifier** attribute.
:return: self.__raw_section_content_identifier.
:rtype: unicode
'''
pass
@raw_section_content_identifier.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def raw_section_content_identifier(self):
'''
Setter for **self. __raw_section_content_identifier** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@raw_section_content_identifier.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def raw_section_content_identifier(self):
'''
Deleter for **self. __raw_section_content_identifier** attribute.
'''
pass
@property
def defaults_section(self):
'''
Property for **self.__defaults_section** attribute.
:return: self.__defaults_section.
:rtype: unicode
'''
pass
@defaults_section.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def defaults_section(self):
'''
Setter for **self.__defaults_section** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@defaults_section.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def defaults_section(self):
'''
Deleter for **self.__defaults_section** attribute.
'''
pass
@property
def sections(self):
'''
Property for **self.__sections** attribute.
:return: self.__sections.
:rtype: OrderedDict or dict
'''
pass
@sections.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def sections(self):
'''
Setter for **self.__sections** attribute.
:param value: Attribute value.
:type value: OrderedDict or dict
'''
pass
@sections.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def sections(self):
'''
Deleter for **self.__sections** attribute.
'''
pass
@property
def comments(self):
'''
Property for **self.__comments** attribute.
:return: self.__comments.
:rtype: OrderedDict or dict
'''
pass
@comments.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def comments(self):
'''
Setter for **self.__comments** attribute.
:param value: Attribute value.
:type value: OrderedDict or dict
'''
pass
@comments.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def comments(self):
'''
Deleter for **self.__comments** attribute.
'''
pass
@property
def parsing_errors(self):
'''
Property for **self.__parsing_errors** attribute.
:return: self.__parsing_errors.
:rtype: list
'''
pass
@parsing_errors.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def parsing_errors(self):
'''
Setter for **self.__parsing_errors** attribute.
:param value: Attribute value.
:type value: list
'''
pass
@parsing_errors.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def parsing_errors(self):
'''
Deleter for **self.__parsing_errors** attribute.
'''
pass
@property
def preserve_order(self):
'''
Property for **self.__preserve_order** attribute.
:return: self.__preserve_order.
:rtype: bool
'''
pass
@preserve_order.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def preserve_order(self):
'''
Setter method for **self.__preserve_order** attribute.
:param value: Attribute value.
:type value: bool
'''
pass
@preserve_order.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def preserve_order(self):
'''
Deleter method for **self.__preserve_order** attribute.
'''
pass
def __getitem__(self, section):
'''
Reimplements the :meth:`object.__getitem__` method.
:param section: Section name.
:type section: unicode
:return: Layout.
:rtype: Layout
'''
pass
def __setitem__(self, section, value):
'''
Reimplements the :meth:`object.__getitem__` method.
:param section: Section name.
:type section: unicode
:param section: Value.
:type section: dict
:return: Layout.
:rtype: Layout
'''
pass
def __iter__(self):
'''
Reimplements the :meth:`object.__iter__` method.
:return: Layouts iterator.
:rtype: object
'''
pass
def __contains__(self, section):
'''
Reimplements the :meth:`object.__contains__` method.
:param section: Section name.
:type section: unicode
:return: Section existence.
:rtype: bool
'''
pass
def __len__(self):
'''
Reimplements the :meth:`object.__len__` method.
:return: Sections count.
:rtype: int
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.FileStructureParsingError)
def parse(self,
raw_sections=None,
namespaces=True,
strip_comments=True,
strip_whitespaces=True,
strip_quotation_markers=True,
raise_parsing_errors=True):
'''
Process the file content and extracts the sections / attributes
as nested :class:`collections.OrderedDict` dictionaries or dictionaries.
Usage::
>>> content = ["; Comment.\n", "Attribute 1 = \"Value A\"\n", "Attribute 2 = \"Value B\"\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse(strip_comments=False)
<foundations.parsers.SectionsFileParser object at 0x860323123>
>>> sections_file_parser.sections.keys()
[u'_defaults']
>>> sections_file_parser.sections["_defaults"].values()
[u'Value A', u'Value B']
>>> sections_file_parser.parse(strip_comments=False, strip_quotation_markers=False)
<foundations.parsers.SectionsFileParser object at 0x860323123>
>>> sections_file_parser.sections["_defaults"].values()
[u'"Value A"', u'"Value B"']
>>> sections_file_parser.comments
OrderedDict([(u'_defaults|#0', {u'content': u'Comment.', u'id': 0})])
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x860323123>
>>> sections_file_parser.sections["_defaults"]
OrderedDict([(u'_defaults|Attribute 1', u'Value A'), (u'_defaults|Attribute 2', u'Value B')])
>>> sections_file_parser.parse(namespaces=False)
<foundations.parsers.SectionsFileParser object at 0x860323123>
>>> sections_file_parser.sections["_defaults"]
OrderedDict([(u'Attribute 1', u'Value A'), (u'Attribute 2', u'Value B')])
:param raw_sections: Ignored raw sections.
:type raw_sections: tuple or list
:param namespaces: Attributes and comments are namespaced.
:type namespaces: bool
:param strip_comments: Comments are stripped.
:type strip_comments: bool
:param strip_whitespaces: Whitespaces are stripped.
:type strip_whitespaces: bool
:param strip_quotation_markers: Attributes values quotation markers are stripped.
:type strip_quotation_markers: bool
:param raise_parsing_errors: Raise parsing errors.
:type raise_parsing_errors: bool
:return: SectionFileParser instance.
:rtype: SectionFileParser
'''
pass
def section_exists(self, section):
'''
Checks if given section exists.
Usage::
>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x845683844>
>>> sections_file_parser.section_exists("Section A")
True
>>> sections_file_parser.section_exists("Section C")
False
:param section: Section to check existence.
:type section: unicode
:return: Section existence.
:rtype: bool
'''
pass
def attribute_exists(self, attribute, section):
'''
Checks if given attribute exists.
Usage::
>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x234564563>
>>> sections_file_parser.attribute_exists("Attribute 1", "Section A")
True
>>> sections_file_parser.attribute_exists("Attribute 2", "Section A")
False
:param attribute: Attribute to check existence.
:type attribute: unicode
:param section: Section to search attribute into.
:type section: unicode
:return: Attribute existence.
:rtype: bool
'''
pass
def get_attributes(self, section, strip_namespaces=False):
'''
Returns given section attributes.
Usage::
>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x125698322>
>>> sections_file_parser.get_attributes("Section A")
OrderedDict([(u'Section A|Attribute 1', u'Value A')])
>>> sections_file_parser.preserve_order=False
>>> sections_file_parser.get_attributes("Section A")
{u'Section A|Attribute 1': u'Value A'}
>>> sections_file_parser.preserve_order=True
>>> sections_file_parser.get_attributes("Section A", strip_namespaces=True)
OrderedDict([(u'Attribute 1', u'Value A')])
:param section: Section containing the requested attributes.
:type section: unicode
:param strip_namespaces: Strip namespaces while retrieving attributes.
:type strip_namespaces: bool
:return: Attributes.
:rtype: OrderedDict or dict
'''
pass
def get_all_attributes(self):
'''
Returns all sections attributes.
Usage::
>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x845683844>
>>> sections_file_parser.get_all_attributes()
OrderedDict([(u'Section A|Attribute 1', u'Value A'), (u'Section B|Attribute 2', u'Value B')])
>>> sections_file_parser.preserve_order=False
>>> sections_file_parser.get_all_attributes()
{u'Section B|Attribute 2': u'Value B', u'Section A|Attribute 1': u'Value A'}
:return: All sections / files attributes.
:rtype: OrderedDict or dict
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.FileStructureParsingError)
def get_value(self, attribute, section, default=""):
'''
Returns requested attribute value.
Usage::
>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x679302423>
>>> sections_file_parser.get_value("Attribute 1", "Section A")
u'Value A'
:param attribute: Attribute name.
:type attribute: unicode
:param section: Section containing the searched attribute.
:type section: unicode
:param default: Default return value.
:type default: object
:return: Attribute value.
:rtype: unicode
'''
pass
def set_value(self, attribute, section, value):
'''
Sets requested attribute value.
Usage::
>>> content = ["[Section A]\n", "; Comment.\n", "Attribute 1 = \"Value A\"\n", "\n", "[Section B]\n", "Attribute 2 = \"Value B\"\n"]
>>> sections_file_parser = SectionsFileParser()
>>> sections_file_parser.content = content
>>> sections_file_parser.parse()
<foundations.parsers.SectionsFileParser object at 0x109304209>
>>> sections_file_parser.set_value("Attribute 3", "Section C", "Value C")
True
:param attribute: Attribute name.
:type attribute: unicode
:param section: Section containing the searched attribute.
:type section: unicode
:param value: Attribute value.
:type value: object
:return: Definition success.
:rtype: bool
'''
pass
def write(self,
namespaces=False,
splitter="=",
comment_limiter=(";"),
spaces_around_splitter=True,
space_after_comment_limiter=True):
'''
Writes defined file using :obj:`SectionsFileParser.sections` and
:obj:`SectionsFileParser.comments` class properties content.
Usage::
>>> sections = {"Section A": {"Section A|Attribute 1": "Value A"}, "Section B": {"Section B|Attribute 2": "Value B"}}
>>> sections_file_parser = SectionsFileParser("SectionsFile.rc")
>>> sections_file_parser.sections = sections
>>> sections_file_parser.write()
True
>>> sections_file_parser.read()
u'[Section A]\nAttribute 1 = Value A\n\n[Section B]\nAttribute 2 = Value B\n'
:param namespaces: Attributes are namespaced.
:type namespaces: bool
:param splitter: Splitter character.
:type splitter: unicode
:param comment_limiter: Comment limiter character.
:type comment_limiter: unicode
:param spaces_around_splitter: Spaces around attributes and value splitters.
:type spaces_around_splitter: bool
:param space_after_comment_limiter: Space after comments limiter.
:type space_after_comment_limiter: bool
:return: Method success.
:rtype: bool
'''
pass
| 105 | 48 | 19 | 3 | 8 | 9 | 2 | 1 | 1 | 10 | 4 | 0 | 47 | 11 | 47 | 60 | 1,004 | 173 | 417 | 141 | 292 | 416 | 276 | 86 | 228 | 17 | 2 | 4 | 109 |
142,283 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestIsBaseTraced.test_is_base_traced.Dummy2
|
class Dummy2(Dummy):
pass
|
class Dummy2(Dummy):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 2 | 0 | 0 |
142,284 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tcp_server.py
|
foundations.tcp_server.EchoRequestsHandler
|
class EchoRequestsHandler(SocketServer.BaseRequestHandler):
"""
Defines the default echo requests handler.
"""
def handle(self):
"""
Reimplements the :meth:`SocketServer.BaseRequestHandler.handle` method.
:return: Method success.
:rtype: bool
"""
while True:
data = self.request.recv(1024)
if not data:
break
self.request.send(data)
return True
|
class EchoRequestsHandler(SocketServer.BaseRequestHandler):
'''
Defines the default echo requests handler.
'''
def handle(self):
'''
Reimplements the :meth:`SocketServer.BaseRequestHandler.handle` method.
:return: Method success.
:rtype: bool
'''
pass
| 2 | 2 | 15 | 3 | 7 | 5 | 3 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 20 | 4 | 8 | 3 | 6 | 8 | 8 | 3 | 6 | 3 | 1 | 2 | 3 |
142,285 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.AttributeStructureParsingError
|
class AttributeStructureParsingError(AbstractParsingError):
"""
Defines exception raised while parsing attribute structure.
"""
def __init__(self, value, line=None):
"""
Initializes the class.
:param value: Error value or message.
:type value: unicode
:param line: Line number where exception occured.
:type line: int
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
AbstractParsingError.__init__(self, value)
# --- Setting class attributes. ---
self.__line = None
self.line = line
@property
def line(self):
"""
Property for **self.__line** attribute.
:return: self.__line.
:rtype: int
"""
return self.__line
@line.setter
@handle_exceptions(AssertionError)
def line(self, value):
"""
Setter for **self.__line** attribute.
:param value: Attribute value.
:type value: int
"""
if value is not None:
assert type(value) is int, "'{0}' attribute: '{1}' type is not 'int'!".format(
"line", value)
assert value > 0, "'{0}' attribute: '{1}' need to be exactly positive!".format(
"line", value)
self.__line = value
@line.deleter
@handle_exceptions(Exception)
def line(self):
"""
Deleter for **self.__line** attribute.
"""
raise Exception("{0} | '{1}' attribute is not deletable!".format(
self.__class__.__name__, "line"))
def __str__(self):
"""
Returns the exception representation.
:return: Exception representation.
:rtype: unicode
"""
if self.__line:
return "Line '{0}': '{1}'.".format(self.__line, str(self.value))
else:
return str(self.value)
|
class AttributeStructureParsingError(AbstractParsingError):
'''
Defines exception raised while parsing attribute structure.
'''
def __init__(self, value, line=None):
'''
Initializes the class.
:param value: Error value or message.
:type value: unicode
:param line: Line number where exception occured.
:type line: int
'''
pass
@property
def line(self):
'''
Property for **self.__line** attribute.
:return: self.__line.
:rtype: int
'''
pass
@line.setter
@handle_exceptions(AssertionError)
def line(self):
'''
Setter for **self.__line** attribute.
:param value: Attribute value.
:type value: int
'''
pass
@line.deleter
@handle_exceptions(Exception)
def line(self):
'''
Deleter for **self.__line** attribute.
'''
pass
def __str__(self):
'''
Returns the exception representation.
:return: Exception representation.
:rtype: unicode
'''
pass
| 11 | 6 | 11 | 2 | 4 | 5 | 1 | 1.16 | 1 | 3 | 0 | 0 | 5 | 1 | 5 | 20 | 70 | 16 | 25 | 10 | 14 | 29 | 19 | 7 | 13 | 2 | 5 | 1 | 7 |
142,286 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/io.py
|
foundations.io.File
|
class File(object):
"""
Defines methods to read / write and append to files or retrieve online file content.
"""
def __init__(self, path=None, content=None):
"""
Initializes the class.
Usage::
>>> file = File(u"file.txt")
>>> file.content = [u"Some file content ...\\n", u"... ready to be saved!\\n"]
>>> file.write()
True
>>> file.read()
u'Some file content ...\\n... ready to be saved!\\n'
:param path: File path.
:type path: unicode
:param content: Content.
:type content: list
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
# --- Setting class attributes. ---
self.__path = None
self.path = path
self.__content = None
self.content = content or []
@property
def path(self):
"""
Property for **self.__path** attribute.
:return: self.__path.
:rtype: unicode
"""
return self.__path
@path.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def path(self, value):
"""
Setter for **self.__path** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"path", value)
self.__path = value
@path.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def path(self):
"""
Deleter for **self.__path** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "path"))
@property
def content(self):
"""
Property for **self.__content** attribute.
:return: self.__content.
:rtype: list
"""
return self.__content
@content.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def content(self, value):
"""
Setter for **self.__content** attribute.
:param value: Attribute value.
:type value: list
"""
if value is not None:
assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format(
"content", value)
self.__content = value
@content.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def content(self):
"""
Deleter for **self.__content** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "content"))
@foundations.exceptions.handle_exceptions(foundations.exceptions.UrlReadError,
foundations.exceptions.FileReadError,
IOError)
def cache(self, mode="r", encoding=Constants.default_codec, errors=Constants.codec_error):
"""
Reads given file content and stores it in the content cache.
:param mode: File read mode.
:type mode: unicode
:param encoding: File encoding codec.
:type encoding: unicode
:param errors: File encoding errors handling.
:type errors: unicode
:return: Method success.
:rtype: bool
"""
self.uncache()
if foundations.strings.is_website(self.__path):
try:
LOGGER.debug(
"> Caching '{0}' online file content.".format(self.__path))
self.__content = urllib2.urlopen(self.__path).readlines()
return True
except urllib2.URLError as error:
raise foundations.exceptions.UrlReadError(
"!> {0} | '{1}' url is not readable: '{2}'.".format(self.__class__.__name__, self.__path, error))
elif foundations.common.path_exists(self.__path):
if not is_readable(self.__path):
raise foundations.exceptions.FileReadError(
"!> {0} | '{1}' file is not readable!".format(self.__class__.__name__, self.__path))
with codecs.open(self.__path, mode, encoding, errors) as file:
LOGGER.debug(
"> Caching '{0}' file content.".format(self.__path))
self.__content = file.readlines()
return True
return False
def uncache(self):
"""
Uncaches the cached content.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Uncaching '{0}' file content.".format(self.__path))
self.__content = []
return True
def read(self):
"""
Returns defined file content.
:return: File content.
:rtype: unicode
"""
return "".join(self.__content) if self.cache() else ""
@foundations.exceptions.handle_exceptions(foundations.exceptions.UrlWriteError,
foundations.exceptions.FileWriteError)
def write(self, mode="w", encoding=Constants.default_codec, errors=Constants.codec_error):
"""
Writes content to defined file.
:param mode: File write mode.
:type mode: unicode
:param encoding: File encoding codec.
:type encoding: unicode
:param errors: File encoding errors handling.
:type errors: unicode
:return: Method success.
:rtype: bool
"""
if foundations.strings.is_website(self.__path):
raise foundations.exceptions.UrlWriteError(
"!> {0} | '{1}' url is not writable!".format(self.__class__.__name__, self.__path))
if foundations.common.path_exists(self.__path):
if not is_writable(self.__path):
raise foundations.exceptions.FileWriteError(
"!> {0} | '{1}' file is not writable!".format(self.__class__.__name__, self.__path))
with codecs.open(self.__path, mode, encoding, errors) as file:
LOGGER.debug("> Writing '{0}' file content.".format(self.__path))
for line in self.__content:
file.write(line)
return True
return False
@foundations.exceptions.handle_exceptions(foundations.exceptions.UrlWriteError,
foundations.exceptions.FileWriteError)
def append(self, mode="a", encoding=Constants.default_codec, errors=Constants.codec_error):
"""
Appends content to defined file.
:param mode: File write mode.
:type mode: unicode
:param encoding: File encoding codec.
:type encoding: unicode
:param errors: File encoding errors handling.
:type errors: unicode
:return: Method success.
:rtype: bool
"""
if foundations.strings.is_website(self.__path):
raise foundations.exceptions.UrlWriteError(
"!> {0} | '{1}' url is not writable!".format(self.__class__.__name__, self.__path))
if foundations.common.path_exists(self.__path):
if not is_writable(self.__path):
raise foundations.exceptions.FileWriteError(
"!> {0} | '{1}' file is not writable!".format(self.__class__.__name__, self.__path))
with codecs.open(self.__path, mode, encoding, errors) as file:
LOGGER.debug(
"> Appending to '{0}' file content.".format(self.__path))
for line in self.__content:
file.write(line)
return True
return False
@foundations.exceptions.handle_exceptions(foundations.exceptions.UrlWriteError)
def clear(self, encoding=Constants.default_codec):
"""
Clears the defined file content.
:param encoding: File encoding codec.
:type encoding: unicode
:return: Method success.
:rtype: bool
"""
if foundations.strings.is_website(self.__path):
raise foundations.exceptions.UrlWriteError(
"!> {0} | '{1}' url is not writable!".format(self.__class__.__name__, self.__path))
if self.uncache():
LOGGER.debug("> Clearing '{0}' file content.".format(self.__path))
return self.write(encoding=encoding)
else:
return False
|
class File(object):
'''
Defines methods to read / write and append to files or retrieve online file content.
'''
def __init__(self, path=None, content=None):
'''
Initializes the class.
Usage::
>>> file = File(u"file.txt")
>>> file.content = [u"Some file content ...\n", u"... ready to be saved!\n"]
>>> file.write()
True
>>> file.read()
u'Some file content ...\n... ready to be saved!\n'
:param path: File path.
:type path: unicode
:param content: Content.
:type content: list
'''
pass
@property
def path(self):
'''
Property for **self.__path** attribute.
:return: self.__path.
:rtype: unicode
'''
pass
@path.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def path(self):
'''
Setter for **self.__path** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@path.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def path(self):
'''
Deleter for **self.__path** attribute.
'''
pass
@property
def content(self):
'''
Property for **self.__content** attribute.
:return: self.__content.
:rtype: list
'''
pass
@content.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def content(self):
'''
Setter for **self.__content** attribute.
:param value: Attribute value.
:type value: list
'''
pass
@content.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def content(self):
'''
Deleter for **self.__content** attribute.
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.UrlReadError,
foundations.exceptions.FileReadError,
IOError)
def cache(self, mode="r", encoding=Constants.default_codec, errors=Constants.codec_error):
'''
Reads given file content and stores it in the content cache.
:param mode: File read mode.
:type mode: unicode
:param encoding: File encoding codec.
:type encoding: unicode
:param errors: File encoding errors handling.
:type errors: unicode
:return: Method success.
:rtype: bool
'''
pass
def uncache(self):
'''
Uncaches the cached content.
:return: Method success.
:rtype: bool
'''
pass
def read(self):
'''
Returns defined file content.
:return: File content.
:rtype: unicode
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.UrlWriteError,
foundations.exceptions.FileWriteError)
def write(self, mode="w", encoding=Constants.default_codec, errors=Constants.codec_error):
'''
Writes content to defined file.
:param mode: File write mode.
:type mode: unicode
:param encoding: File encoding codec.
:type encoding: unicode
:param errors: File encoding errors handling.
:type errors: unicode
:return: Method success.
:rtype: bool
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.UrlWriteError,
foundations.exceptions.FileWriteError)
def append(self, mode="a", encoding=Constants.default_codec, errors=Constants.codec_error):
'''
Appends content to defined file.
:param mode: File write mode.
:type mode: unicode
:param encoding: File encoding codec.
:type encoding: unicode
:param errors: File encoding errors handling.
:type errors: unicode
:return: Method success.
:rtype: bool
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.UrlWriteError)
def clear(self, encoding=Constants.default_codec):
'''
Clears the defined file content.
:param encoding: File encoding codec.
:type encoding: unicode
:return: Method success.
:rtype: bool
'''
pass
| 28 | 14 | 16 | 3 | 7 | 7 | 2 | 0.9 | 1 | 8 | 6 | 2 | 13 | 2 | 13 | 13 | 247 | 48 | 105 | 36 | 73 | 94 | 76 | 18 | 62 | 5 | 1 | 2 | 30 |
142,287 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/library.py
|
foundations.library.Library
|
class Library(object):
"""
| Defines methods to bind a C / C++ Library.
| The class is a singleton and will bind only one time a given library.
Each unique library instance is stored in :attr:`Library.instances` attribute
and get returned if the library is requested again through a new instantiation.
"""
__instances = {}
"""
:param __instances: Libraries instances.
:type __instances: dict
"""
callback = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p)
"""
:param callback: callback.
:type callback: ctypes.CFUNCTYPE
"""
@foundations.exceptions.handle_exceptions(foundations.exceptions.LibraryInstantiationError)
def __new__(cls, *args, **kwargs):
"""
Constructor of the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
:return: Class instance.
:rtype: Library
"""
path = foundations.common.get_first_item(args)
if foundations.common.path_exists(path):
if not path in cls._Library__instances:
cls._Library__instances[path] = object.__new__(cls)
return cls._Library__instances[path]
else:
raise foundations.exceptions.LibraryInstantiationError(
"{0} | '{1}' library path doesn't exists!".format(cls.__class__.__name__, path))
@foundations.exceptions.handle_exceptions(foundations.exceptions.LibraryInitializationError)
def __init__(self, path, functions=None, bind_library=True):
"""
Initializes the class.
Usage::
>>> import ctypes
>>> path = "FreeImage.dll"
>>> functions = (LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p),)
>>> library = Library(path, functions)
>>> library.FreeImage_GetVersion()
'3.15.1'
:param path: Library path.
:type path: unicode
:param functions: Binding functions list.
:type functions: tuple
:param bind_library: Library will be binded on initialization.
:type bind_library: bool
"""
if hasattr(self.instances[path], "_Library__initialized"):
return
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
# --- Setting class attributes. ---
self.__initialized = True
self.__path = None
self.path = path
self.__functions = None
self.functions = functions
self.__library = None
if platform.system() == "Windows" or platform.system() == "Microsoft":
loading_function = ctypes.windll
else:
loading_function = ctypes.cdll
if self.path:
self.__library = loading_function.LoadLibrary(path)
else:
raise foundations.exceptions.LibraryInitializationError("{0} | '{1}' library not found!".format(
self.__class__.__name__, path))
bind_library and self.bind_library()
@property
def instances(self):
"""
Property for **self.__instances** attribute.
:return: self.__instances.
:rtype: WeakValueDictionary
"""
return self.__instances
@instances.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def instances(self, value):
"""
Setter for **self.__instances** attribute.
:param value: Attribute value.
:type value: WeakValueDictionary
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "instances"))
@instances.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def instances(self):
"""
Deleter for **self.__instances** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "instances"))
@property
def initialized(self):
"""
Property for **self.__initialized** attribute.
:return: self.__initialized.
:rtype: unicode
"""
return self.__initialized
@initialized.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def initialized(self, value):
"""
Setter for **self.__initialized** attribute.
:param value: Attribute value.
:type value: unicode
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "initialized"))
@initialized.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def initialized(self):
"""
Deleter for **self.__initialized** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "initialized"))
@property
def path(self):
"""
Property for **self.__path** attribute.
:return: self.__path.
:rtype: unicode
"""
return self.__path
@path.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def path(self, value):
"""
Setter for **self.__path** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"path", value)
assert os.path.exists(
value), "'{0}' attribute: '{1}' file doesn't exists!".format("path", value)
self.__path = value
@path.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def path(self):
"""
Deleter for **self.__path** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "path"))
@property
def functions(self):
"""
Property for **self.__functions** attribute.
:return: self.__functions.
:rtype: tuple
"""
return self.__functions
@functions.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def functions(self, value):
"""
Setter for **self.__functions** attribute.
:param value: Attribute value.
:type value: tuple
"""
if value is not None:
assert type(value) is tuple, "'{0}' attribute: '{1}' type is not 'tuple'!".format(
"functions", value)
for element in value:
assert type(element) is LibraryHook, "'{0}' attribute: '{1}' type is not 'LibraryHook'!".format(
"functions", element)
self.__functions = value
@functions.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def functions(self):
"""
Deleter for **self.__functions** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "functions"))
@property
def library(self):
"""
Property for **self.__library** attribute.
:return: self.__library.
:rtype: object
"""
return self.__library
@library.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def library(self, value):
"""
Setter for **self.__library** attribute.
:param value: Attribute value.
:type value: object
"""
self.__library = value
@library.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def library(self):
"""
Deleter for **self.__library** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "library"))
def bind_function(self, function):
"""
Binds given function to a class object attribute.
Usage::
>>> import ctypes
>>> path = "FreeImage.dll"
>>> function = LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p)
>>> library = Library(path, bind_library=False)
>>> library.bind_function(function)
True
>>> library.FreeImage_GetVersion()
'3.15.1'
:param function: Function to bind.
:type function: LibraryHook
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Binding '{0}' library '{1}' function.".format(
self.__class__.__name__, function.name))
function_object = getattr(self.__library, function.name)
setattr(self, function.name, function_object)
if function.arguments_types:
function_object.argtypes = function.arguments_types
if function.return_value:
function_object.restype = function.return_value
return True
def bind_library(self):
"""
Binds the Library using functions registered in the **self.__functions** attribute.
Usage::
>>> import ctypes
>>> path = "FreeImage.dll"
>>> functions = (LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p),)
>>> library = Library(path, functions, bind_library=False)
>>> library.bind_library()
True
>>> library.FreeImage_GetVersion()
'3.15.1'
:return: Method success.
:rtype: bool
"""
if self.__functions:
for function in self.__functions:
self.bind_function(function)
return True
|
class Library(object):
'''
| Defines methods to bind a C / C++ Library.
| The class is a singleton and will bind only one time a given library.
Each unique library instance is stored in :attr:`Library.instances` attribute
and get returned if the library is requested again through a new instantiation.
'''
@foundations.exceptions.handle_exceptions(foundations.exceptions.LibraryInstantiationError)
def __new__(cls, *args, **kwargs):
'''
Constructor of the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
:return: Class instance.
:rtype: Library
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.LibraryInitializationError)
def __init__(self, path, functions=None, bind_library=True):
'''
Initializes the class.
Usage::
>>> import ctypes
>>> path = "FreeImage.dll"
>>> functions = (LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p),)
>>> library = Library(path, functions)
>>> library.FreeImage_GetVersion()
'3.15.1'
:param path: Library path.
:type path: unicode
:param functions: Binding functions list.
:type functions: tuple
:param bind_library: Library will be binded on initialization.
:type bind_library: bool
'''
pass
@property
def instances(self):
'''
Property for **self.__instances** attribute.
:return: self.__instances.
:rtype: WeakValueDictionary
'''
pass
@instances.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def instances(self):
'''
Setter for **self.__instances** attribute.
:param value: Attribute value.
:type value: WeakValueDictionary
'''
pass
@instances.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def instances(self):
'''
Deleter for **self.__instances** attribute.
'''
pass
@property
def initialized(self):
'''
Property for **self.__initialized** attribute.
:return: self.__initialized.
:rtype: unicode
'''
pass
@initialized.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def initialized(self):
'''
Setter for **self.__initialized** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@initialized.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def initialized(self):
'''
Deleter for **self.__initialized** attribute.
'''
pass
@property
def path(self):
'''
Property for **self.__path** attribute.
:return: self.__path.
:rtype: unicode
'''
pass
@path.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def path(self):
'''
Setter for **self.__path** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@path.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def path(self):
'''
Deleter for **self.__path** attribute.
'''
pass
@property
def functions(self):
'''
Property for **self.__functions** attribute.
:return: self.__functions.
:rtype: tuple
'''
pass
@functions.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def functions(self):
'''
Setter for **self.__functions** attribute.
:param value: Attribute value.
:type value: tuple
'''
pass
@functions.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def functions(self):
'''
Deleter for **self.__functions** attribute.
'''
pass
@property
def library(self):
'''
Property for **self.__library** attribute.
:return: self.__library.
:rtype: object
'''
pass
@library.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def library(self):
'''
Setter for **self.__library** attribute.
:param value: Attribute value.
:type value: object
'''
pass
@library.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def library(self):
'''
Deleter for **self.__library** attribute.
'''
pass
def bind_function(self, function):
'''
Binds given function to a class object attribute.
Usage::
>>> import ctypes
>>> path = "FreeImage.dll"
>>> function = LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p)
>>> library = Library(path, bind_library=False)
>>> library.bind_function(function)
True
>>> library.FreeImage_GetVersion()
'3.15.1'
:param function: Function to bind.
:type function: LibraryHook
:return: Method success.
:rtype: bool
'''
pass
def bind_library(self):
'''
Binds the Library using functions registered in the **self.__functions** attribute.
Usage::
>>> import ctypes
>>> path = "FreeImage.dll"
>>> functions = (LibraryHook(name="FreeImage_GetVersion", arguments_types=None, return_value=ctypes.c_char_p),)
>>> library = Library(path, functions, bind_library=False)
>>> library.bind_library()
True
>>> library.FreeImage_GetVersion()
'3.15.1'
:return: Method success.
:rtype: bool
'''
pass
| 47 | 20 | 14 | 2 | 5 | 6 | 2 | 1.13 | 1 | 6 | 4 | 0 | 19 | 4 | 19 | 19 | 322 | 68 | 119 | 48 | 72 | 135 | 78 | 31 | 58 | 4 | 1 | 2 | 31 |
142,288 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/nodes.py
|
foundations.nodes.AbstractCompositeNode
|
class AbstractCompositeNode(AbstractNode):
"""
| Defines the base composite Node class.
| It provides compositing capabilities allowing the assembly of graphs and various trees structures.
"""
__family = "AbstractComposite"
"""
:param __family: Node family.
:type __family: unicode
"""
def __init__(self, name=None, parent=None, children=None, **kwargs):
"""
Initializes the class.
:param name: Node name.
:type name: unicode
:param parent: Node parent.
:type parent: AbstractNode or AbstractCompositeNode
:param children: Children.
:type children: list
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
:note: :data:`pickle.HIGHEST_PROTOCOL` must be used to pickle :class:`foundations.nodes.AbstractCompositeNode` class.
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
AbstractNode.__init__(self, name, **kwargs)
# --- Setting class attributes. ---
self.__parent = None
self.parent = parent
self.__children = None
self.children = children or []
parent and parent.add_child(self)
@property
def parent(self):
"""
Property for **self.__parent** attribute.
:return: self.__parent.
:rtype: AbstractNode or AbstractCompositeNode
"""
return self.__parent
@parent.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def parent(self, value):
"""
Setter for **self.__parent** attribute.
:param value: Attribute value.
:type value: AbstractNode or AbstractCompositeNode
"""
if value is not None:
assert issubclass(value.__class__, AbstractNode), "'{0}' attribute: '{1}' is not a '{2}' subclass!".format(
"parent", value, AbstractNode.__class__.__name__)
self.__parent = value
@parent.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def parent(self):
"""
Deleter for **self.__parent** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "name"))
@property
def children(self):
"""
Property for **self.__children** attribute.
:return: self.__children.
:rtype: list
"""
return self.__children
@children.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def children(self, value):
"""
Setter for **self.__children** attribute.
:param value: Attribute value.
:type value: list
"""
if value is not None:
assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format(
"children", value)
for element in value:
assert issubclass(element.__class__,
AbstractNode), "'{0}' attribute: '{1}' is not a '{2}' subclass!".format(
"children", element, AbstractNode.__class__.__name__)
self.__children = value
@children.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def children(self):
"""
Deleter for **self.__children** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "children"))
def __eq__(self, object):
"""
Reimplements the :meth:`AbstractNode.__eq__` method.
:param object: Comparing object.
:type object: object
:return: Equality.
:rtype: bool
"""
if self is object:
return True
elif isinstance(object, AbstractCompositeNode):
for childA, childB in zip(self.__children, object.children):
return childA.identity == childB.identity
else:
return False
def child(self, index):
"""
Returns the child associated with given index.
Usage::
>>> node_b = AbstractCompositeNode("MyNodeB")
>>> node_c = AbstractCompositeNode("MyNodeC")
>>> node_a = AbstractCompositeNode("MyNodeA", children=[node_b, node_c])
>>> node_a.child(0)
<AbstractCompositeNode object at 0x10107b6f0>
>>> node_a.child(0).name
u'MyNodeB'
:param index: Child index.
:type index: int
:return: Child node.
:rtype: AbstractNode or AbstractCompositeNode or Object
"""
if not self.__children:
return
if index >= 0 and index < len(self.__children):
return self.__children[index]
def index_of(self, child):
"""
Returns the given child index.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.index_of(node_b)
0
>>> node_a.index_of(node_c)
1
:param child: Child node.
:type child: AbstractNode or AbstractCompositeNode or Object
:return: Child index.
:rtype: int
"""
for i, item in enumerate(self.__children):
if child is item:
return i
def row(self):
"""
Returns the Node row.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_b.row()
0
>>> node_c.row()
1
:return: Node row.
:rtype: int
"""
if self.__parent:
return self.__parent.index_of(self)
def add_child(self, child):
"""
Adds given child to the node.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB")
>>> node_a.add_child(node_b)
True
>>> node_a.children
[<AbstractCompositeNode object at 0x10107afe0>]
:param child: Child node.
:type child: AbstractNode or AbstractCompositeNode or Object
:return: Method success.
:rtype: bool
"""
self.__children.append(child)
child.parent = self
return True
def remove_child(self, index):
"""
Removes child at given index from the Node children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.remove_child(1)
True
>>> [child.name for child in node_a.children]
[u'MyNodeB']
:param index: Node index.
:type index: int
:return: Removed child.
:rtype: AbstractNode or AbstractCompositeNode or Object
"""
if index < 0 or index > len(self.__children):
return
child = self.__children.pop(index)
child.parent = None
return child
def insert_child(self, child, index):
"""
Inserts given child at given index.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_d = AbstractCompositeNode("MyNodeD")
>>> node_a.insert_child(node_d, 1)
True
>>> [child.name for child in node_a.children]
[u'MyNodeB', u'MyNodeD', u'MyNodeC']
:param child: Child node.
:type child: AbstractNode or AbstractCompositeNode or Object
:param index: Insertion index.
:type index: int
:return: Method success.
:rtype: bool
"""
if index < 0 or index > len(self.__children):
return False
self.__children.insert(index, child)
child.parent = self
return child
def has_children(self):
"""
Returns if the Node has children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_a.has_children()
False
:return: Children count.
:rtype: int
"""
return True if self.children_count() > 0 else False
def children_count(self):
"""
Returns the children count.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.children_count()
2
:return: Children count.
:rtype: int
"""
return len(self.__children)
def sort_children(self, attribute=None, reverse_order=False):
"""
Sorts the children using either the given attribute or the Node name.
:param attribute: Attribute name used for sorting.
:type attribute: unicode
:param reverse_order: Sort in reverse order.
:type reverse_order: bool
:return: Method success.
:rtype: bool
"""
sorted_children = []
if attribute:
sortable_children = []
unsortable_children = []
for child in self.__children:
if child.attribute_exists(attribute):
sortable_children.append(child)
else:
unsortable_children.append(child)
sorted_children = sorted(sortable_children, key=lambda x: getattr(
x, attribute).value, reverse=reverse_order or False)
sorted_children.extend(unsortable_children)
else:
sorted_children = sorted(self.children, key=lambda x: (
x.name), reverse=reverse_order or False)
self.__children = sorted_children
for child in self.__children:
child.sort_children(attribute, reverse_order)
return True
def find_children(self, pattern=r".*", flags=0, candidates=None):
"""
Finds the children matching the given patten.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.find_children("c", re.IGNORECASE)
[<AbstractCompositeNode object at 0x101078040>]
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:param candidates: Matching candidates.
:type candidates: list
:return: Matching children.
:rtype: list
"""
if candidates is None:
candidates = []
for child in self.__children:
if re.search(pattern, child.name, flags):
child not in candidates and candidates.append(child)
child.find_children(pattern, flags, candidates)
return candidates
def find_family(self, pattern=r".*", flags=0, node=None):
"""
Returns the Nodes from given family.
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:param node: Node to start walking from.
:type node: AbstractNode or AbstractCompositeNode or Object
:return: Family nodes.
:rtype: list
"""
return [node for node in foundations.walkers.nodes_walker(node or self) if
re.search(pattern, node.family, flags)]
def list_node(self, tab_level=-1):
"""
Lists the current Node and its children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> print node_a.list_node()
|----'MyNodeA'
|----'MyNodeB'
|----'MyNodeC'
:param tab_level: Tab level.
:type tab_level: int
:return: Node listing.
:rtype: unicode
"""
output = ""
tab_level += 1
for i in range(tab_level):
output += "\t"
output += "|----'{0}'\n".format(self.name)
for child in self.__children:
output += child.list_node(tab_level)
tab_level -= 1
return output
|
class AbstractCompositeNode(AbstractNode):
'''
| Defines the base composite Node class.
| It provides compositing capabilities allowing the assembly of graphs and various trees structures.
'''
def __init__(self, name=None, parent=None, children=None, **kwargs):
'''
Initializes the class.
:param name: Node name.
:type name: unicode
:param parent: Node parent.
:type parent: AbstractNode or AbstractCompositeNode
:param children: Children.
:type children: list
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
:note: :data:`pickle.HIGHEST_PROTOCOL` must be used to pickle :class:`foundations.nodes.AbstractCompositeNode` class.
'''
pass
@property
def parent(self):
'''
Property for **self.__parent** attribute.
:return: self.__parent.
:rtype: AbstractNode or AbstractCompositeNode
'''
pass
@parent.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def parent(self):
'''
Setter for **self.__parent** attribute.
:param value: Attribute value.
:type value: AbstractNode or AbstractCompositeNode
'''
pass
@parent.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def parent(self):
'''
Deleter for **self.__parent** attribute.
'''
pass
@property
def children(self):
'''
Property for **self.__children** attribute.
:return: self.__children.
:rtype: list
'''
pass
@children.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def children(self):
'''
Setter for **self.__children** attribute.
:param value: Attribute value.
:type value: list
'''
pass
@children.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def children(self):
'''
Deleter for **self.__children** attribute.
'''
pass
def __eq__(self, object):
'''
Reimplements the :meth:`AbstractNode.__eq__` method.
:param object: Comparing object.
:type object: object
:return: Equality.
:rtype: bool
'''
pass
def children(self):
'''
Returns the child associated with given index.
Usage::
>>> node_b = AbstractCompositeNode("MyNodeB")
>>> node_c = AbstractCompositeNode("MyNodeC")
>>> node_a = AbstractCompositeNode("MyNodeA", children=[node_b, node_c])
>>> node_a.child(0)
<AbstractCompositeNode object at 0x10107b6f0>
>>> node_a.child(0).name
u'MyNodeB'
:param index: Child index.
:type index: int
:return: Child node.
:rtype: AbstractNode or AbstractCompositeNode or Object
'''
pass
def index_of(self, child):
'''
Returns the given child index.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.index_of(node_b)
0
>>> node_a.index_of(node_c)
1
:param child: Child node.
:type child: AbstractNode or AbstractCompositeNode or Object
:return: Child index.
:rtype: int
'''
pass
def row(self):
'''
Returns the Node row.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_b.row()
0
>>> node_c.row()
1
:return: Node row.
:rtype: int
'''
pass
def add_child(self, child):
'''
Adds given child to the node.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB")
>>> node_a.add_child(node_b)
True
>>> node_a.children
[<AbstractCompositeNode object at 0x10107afe0>]
:param child: Child node.
:type child: AbstractNode or AbstractCompositeNode or Object
:return: Method success.
:rtype: bool
'''
pass
def remove_child(self, index):
'''
Removes child at given index from the Node children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.remove_child(1)
True
>>> [child.name for child in node_a.children]
[u'MyNodeB']
:param index: Node index.
:type index: int
:return: Removed child.
:rtype: AbstractNode or AbstractCompositeNode or Object
'''
pass
def insert_child(self, child, index):
'''
Inserts given child at given index.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_d = AbstractCompositeNode("MyNodeD")
>>> node_a.insert_child(node_d, 1)
True
>>> [child.name for child in node_a.children]
[u'MyNodeB', u'MyNodeD', u'MyNodeC']
:param child: Child node.
:type child: AbstractNode or AbstractCompositeNode or Object
:param index: Insertion index.
:type index: int
:return: Method success.
:rtype: bool
'''
pass
def has_children(self):
'''
Returns if the Node has children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_a.has_children()
False
:return: Children count.
:rtype: int
'''
pass
def children_count(self):
'''
Returns the children count.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.children_count()
2
:return: Children count.
:rtype: int
'''
pass
def sort_children(self, attribute=None, reverse_order=False):
'''
Sorts the children using either the given attribute or the Node name.
:param attribute: Attribute name used for sorting.
:type attribute: unicode
:param reverse_order: Sort in reverse order.
:type reverse_order: bool
:return: Method success.
:rtype: bool
'''
pass
def find_children(self, pattern=r".*", flags=0, candidates=None):
'''
Finds the children matching the given patten.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> node_a.find_children("c", re.IGNORECASE)
[<AbstractCompositeNode object at 0x101078040>]
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:param candidates: Matching candidates.
:type candidates: list
:return: Matching children.
:rtype: list
'''
pass
def find_family(self, pattern=r".*", flags=0, node=None):
'''
Returns the Nodes from given family.
:param pattern: Matching pattern.
:type pattern: unicode
:param flags: Matching regex flags.
:type flags: int
:param node: Node to start walking from.
:type node: AbstractNode or AbstractCompositeNode or Object
:return: Family nodes.
:rtype: list
'''
pass
def list_node(self, tab_level=-1):
'''
Lists the current Node and its children.
Usage::
>>> node_a = AbstractCompositeNode("MyNodeA")
>>> node_b = AbstractCompositeNode("MyNodeB", node_a)
>>> node_c = AbstractCompositeNode("MyNodeC", node_a)
>>> print node_a.list_node()
|----'MyNodeA'
|----'MyNodeB'
|----'MyNodeC'
:param tab_level: Tab level.
:type tab_level: int
:return: Node listing.
:rtype: unicode
'''
pass
| 31 | 21 | 19 | 3 | 6 | 10 | 2 | 1.76 | 1 | 6 | 1 | 2 | 20 | 2 | 20 | 75 | 429 | 90 | 123 | 42 | 92 | 216 | 102 | 36 | 81 | 5 | 4 | 3 | 43 |
142,289 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/nodes.py
|
foundations.nodes.AbstractNode
|
class AbstractNode(foundations.data_structures.Structure):
"""
| Defines the base Node class.
| Although it can be instancied directly that class is meant to be subclassed.
:note: Doesn't provide compositing capabilities, :class:`AbstractCompositeNode` class must be used for that purpose.
"""
__family = "Abstract"
"""
:param __family: Node family.
:type __family: unicode
"""
__instance_id = 1
"""
:param __instance_id: Node id.
:type __instance_id: int
"""
__nodes_instances = weakref.WeakValueDictionary()
"""
:param __nodes_instances: Nodes instances.
:type __nodes_instances: dict
"""
def __new__(cls, *args, **kwargs):
"""
Constructor of the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
:return: Class instance.
:rtype: AbstractNode
"""
instance = super(AbstractNode, cls).__new__(cls)
instance._AbstractNode__identity = AbstractNode._AbstractNode__instance_id
AbstractNode._AbstractNode__nodes_instances[instance.__identity] = instance
AbstractNode._AbstractNode__instance_id += 1
return instance
def __init__(self, name=None, **kwargs):
"""
Initializes the class.
Usage::
>>> node_a = AbstractNode("MyNodeA")
>>> node_a.identity
1
>>> node_b = AbstractNode()
>>> node_b.name
u'Abstract2'
>>> node_b.identity
2
:param name: Node name.
:type name: unicode
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
foundations.data_structures.Structure.__init__(self, **kwargs)
# --- Setting class attributes. ---
self.__name = None
self.name = name or self.__get_default_node_name()
@property
def family(self):
"""
Property for **self.__family** attribute.
:return: self.__family.
:rtype: unicode
"""
return getattr(self, "_{0}__{1}".format(self.__class__.__name__, "family"))
@family.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def family(self, value):
"""
Setter for **self.__family** attribute.
:param value: Attribute value.
:type value: unicode
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "family"))
@family.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def family(self):
"""
Deleter for **self.__family** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "family"))
@property
def nodes_instances(self):
"""
Property for **self.__nodes_instances** attribute.
:return: self.__nodes_instances.
:rtype: WeakValueDictionary
"""
return self.__nodes_instances
@nodes_instances.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def nodes_instances(self, value):
"""
Setter for **self.__nodes_instances** attribute.
:param value: Attribute value.
:type value: WeakValueDictionary
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "nodes_instances"))
@nodes_instances.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def nodes_instances(self):
"""
Deleter for **self.__nodes_instances** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "nodes_instances"))
@property
def identity(self):
"""
Property for **self.__identity** attribute.
:return: self.__identity.
:rtype: unicode
"""
return self.__identity
@identity.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def identity(self, value):
"""
Setter for **self.__identity** attribute.
:param value: Attribute value.
:type value: unicode
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "identity"))
@identity.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def identity(self):
"""
Deleter for **self.__identity** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "identity"))
@property
def name(self):
"""
Property for **self.__name** attribute.
:return: self.__name.
:rtype: unicode
"""
return self.__name
@name.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def name(self, value):
"""
Setter for **self.__name** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"name", value)
self.__name = value
@name.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def name(self):
"""
Deleter for **self.__name** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "name"))
def __repr__(self):
"""
Reimplements the :meth:`foundations.data_structures.Structure.__repr__` method.
:return: Object representation.
:rtype: unicode
"""
return "<{0} object at {1}>".format(self.__class__.__name__, hex(id(self)))
def __hash__(self):
"""
Reimplements the :meth:`foundations.data_structures.Structure.__hash__` method.
:return: Object hash.
:rtype: int
:note: :class:`foundations.data_structures.Structure` inherits from **dict** and
should not be made hashable because of its mutability, however considering the fact the id
is used as the hash value, making the object hashable should be fairly safe.
"""
return hash(id(self))
def __get_default_node_name(self):
"""
Gets the default Node name.
:return: Node name.
:rtype: unicode
"""
return "{0}{1}".format(self.family, self.__identity)
@classmethod
def get_node_by_identity(cls, identity):
"""
Returns the Node with given identity.
Usage::
>>> node_a = AbstractNode("MyNodeA")
>>> AbstractNode.get_node_by_identity(1)
<AbstractNode object at 0x101043a80>
:param identity: Node identity.
:type identity: int
:return: Node.
:rtype: AbstractNode
:note: Nodes identities are starting from '1' to nodes instances count.
"""
return cls.__nodes_instances.get(identity, None)
def list_attributes(self):
"""
Returns the Node attributes names.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.list_attributes()
['attributeB', 'attributeA']
:return: Attributes names.
:rtype: list
"""
return [attribute for attribute, value in self.iteritems() if issubclass(value.__class__, Attribute)]
def get_attributes(self):
"""
Returns the Node attributes.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(value="A"), attributeB=Attribute(value="B"))
>>> node_a.get_attributes()
[<Attribute object at 0x7fa471d3b5e0>, <Attribute object at 0x101e6c4a0>]
:return: Attributes.
:rtype: list
"""
return [attribute for attribute in self.itervalues() if issubclass(attribute.__class__, Attribute)]
def attribute_exists(self, name):
"""
Returns if given attribute exists in the node.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.attribute_exists("attributeA")
True
>>> node_a.attribute_exists("attributeC")
False
:param name: Attribute name.
:type name: unicode
:return: Attribute exists.
:rtype: bool
"""
if name in self:
if issubclass(self[name].__class__, Attribute):
return True
return False
@foundations.exceptions.handle_exceptions(foundations.exceptions.NodeAttributeTypeError)
def add_attribute(self, name, value):
"""
Adds given attribute to the node.
Usage::
>>> node_a = AbstractNode()
>>> node_a.add_attribute("attributeA", Attribute())
True
>>> node_a.list_attributes()
[u'attributeA']
:param name: Attribute name.
:type name: unicode
:param value: Attribute value.
:type value: Attribute
:return: Method success.
:rtype: bool
"""
if not issubclass(value.__class__, Attribute):
raise foundations.exceptions.NodeAttributeTypeError(
"Node attribute value must be a '{0}' class instance!".format(Attribute.__class__.__name__))
if self.attribute_exists(name):
raise foundations.exceptions.NodeAttributeExistsError(
"Node attribute '{0}' already exists!".format(name))
self[name] = value
return True
@foundations.exceptions.handle_exceptions(foundations.exceptions.NodeAttributeExistsError)
def remove_attribute(self, name):
"""
Removes given attribute from the node.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.remove_attribute("attributeA")
True
>>> node_a.list_attributes()
['attributeB']
:param name: Attribute name.
:type name: unicode
:return: Method success.
:rtype: bool
"""
if not self.attribute_exists(name):
raise foundations.exceptions.NodeAttributeExistsError(
"Node attribute '{0}' doesn't exists!".format(name))
del self[name]
return True
|
class AbstractNode(foundations.data_structures.Structure):
'''
| Defines the base Node class.
| Although it can be instancied directly that class is meant to be subclassed.
:note: Doesn't provide compositing capabilities, :class:`AbstractCompositeNode` class must be used for that purpose.
'''
def __new__(cls, *args, **kwargs):
'''
Constructor of the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
:return: Class instance.
:rtype: AbstractNode
'''
pass
def __init__(self, name=None, **kwargs):
'''
Initializes the class.
Usage::
>>> node_a = AbstractNode("MyNodeA")
>>> node_a.identity
1
>>> node_b = AbstractNode()
>>> node_b.name
u'Abstract2'
>>> node_b.identity
2
:param name: Node name.
:type name: unicode
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
'''
pass
@property
def family(self):
'''
Property for **self.__family** attribute.
:return: self.__family.
:rtype: unicode
'''
pass
@family.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def family(self):
'''
Setter for **self.__family** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@family.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def family(self):
'''
Deleter for **self.__family** attribute.
'''
pass
@property
def nodes_instances(self):
'''
Property for **self.__nodes_instances** attribute.
:return: self.__nodes_instances.
:rtype: WeakValueDictionary
'''
pass
@nodes_instances.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def nodes_instances(self):
'''
Setter for **self.__nodes_instances** attribute.
:param value: Attribute value.
:type value: WeakValueDictionary
'''
pass
@nodes_instances.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def nodes_instances(self):
'''
Deleter for **self.__nodes_instances** attribute.
'''
pass
@property
def identity(self):
'''
Property for **self.__identity** attribute.
:return: self.__identity.
:rtype: unicode
'''
pass
@identity.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def identity(self):
'''
Setter for **self.__identity** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@identity.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def identity(self):
'''
Deleter for **self.__identity** attribute.
'''
pass
@property
def name(self):
'''
Property for **self.__name** attribute.
:return: self.__name.
:rtype: unicode
'''
pass
@name.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def name(self):
'''
Setter for **self.__name** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@name.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def name(self):
'''
Deleter for **self.__name** attribute.
'''
pass
def __repr__(self):
'''
Reimplements the :meth:`foundations.data_structures.Structure.__repr__` method.
:return: Object representation.
:rtype: unicode
'''
pass
def __hash__(self):
'''
Reimplements the :meth:`foundations.data_structures.Structure.__hash__` method.
:return: Object hash.
:rtype: int
:note: :class:`foundations.data_structures.Structure` inherits from **dict** and
should not be made hashable because of its mutability, however considering the fact the id
is used as the hash value, making the object hashable should be fairly safe.
'''
pass
def __get_default_node_name(self):
'''
Gets the default Node name.
:return: Node name.
:rtype: unicode
'''
pass
@classmethod
def get_node_by_identity(cls, identity):
'''
Returns the Node with given identity.
Usage::
>>> node_a = AbstractNode("MyNodeA")
>>> AbstractNode.get_node_by_identity(1)
<AbstractNode object at 0x101043a80>
:param identity: Node identity.
:type identity: int
:return: Node.
:rtype: AbstractNode
:note: Nodes identities are starting from '1' to nodes instances count.
'''
pass
def list_attributes(self):
'''
Returns the Node attributes names.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.list_attributes()
['attributeB', 'attributeA']
:return: Attributes names.
:rtype: list
'''
pass
def get_attributes(self):
'''
Returns the Node attributes.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(value="A"), attributeB=Attribute(value="B"))
>>> node_a.get_attributes()
[<Attribute object at 0x7fa471d3b5e0>, <Attribute object at 0x101e6c4a0>]
:return: Attributes.
:rtype: list
'''
pass
def attribute_exists(self, name):
'''
Returns if given attribute exists in the node.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.attribute_exists("attributeA")
True
>>> node_a.attribute_exists("attributeC")
False
:param name: Attribute name.
:type name: unicode
:return: Attribute exists.
:rtype: bool
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.NodeAttributeTypeError)
def add_attribute(self, name, value):
'''
Adds given attribute to the node.
Usage::
>>> node_a = AbstractNode()
>>> node_a.add_attribute("attributeA", Attribute())
True
>>> node_a.list_attributes()
[u'attributeA']
:param name: Attribute name.
:type name: unicode
:param value: Attribute value.
:type value: Attribute
:return: Method success.
:rtype: bool
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.NodeAttributeExistsError)
def remove_attribute(self, name):
'''
Removes given attribute from the node.
Usage::
>>> node_a = AbstractNode("MyNodeA", attributeA=Attribute(), attributeB=Attribute())
>>> node_a.remove_attribute("attributeA")
True
>>> node_a.list_attributes()
['attributeB']
:param name: Attribute name.
:type name: unicode
:return: Method success.
:rtype: bool
'''
pass
| 47 | 24 | 13 | 3 | 3 | 7 | 1 | 1.82 | 1 | 6 | 4 | 1 | 22 | 1 | 23 | 55 | 377 | 92 | 101 | 45 | 54 | 184 | 70 | 29 | 46 | 3 | 3 | 2 | 29 |
142,290 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/nodes.py
|
foundations.nodes.Attribute
|
class Attribute(foundations.data_structures.Structure):
"""
Defines a storage object for the :class:`AbstractNode` class attributes.
"""
def __init__(self, name=None, value=None, **kwargs):
"""
Initializes the class.
Usage::
>>> attribute = Attribute(name="My Attribute", value="My Value")
>>> attribute.name
u'My Attribute'
>>> attribute["name"]
u'My Attribute'
>>> attribute.value
u'My Value'
>>> attribute["value"]
u'My Value'
:param name: Attribute name.
:type name: unicode
:param value: Attribute value.
:type value: object
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
foundations.data_structures.Structure.__init__(self, **kwargs)
# --- Setting class attributes. ---
self.__name = None
self.name = name
self.__value = None
self.value = value
@property
def name(self):
"""
Property for **self.__name** attribute.
:return: Value.
:rtype: unicode
"""
return self.__name
@name.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def name(self, value):
"""
Setter for **self.__name** attribute.
:param name: Attribute name.
:type name: unicode
"""
self.__name = value
@name.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def name(self):
"""
Deleter for **name** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "name"))
@property
def value(self):
"""
Property for **self.__value** attribute.
:return: Value.
:rtype: object
"""
return self.__value
@value.setter
def value(self, value):
"""
Setter for **self.__value** attribute.
:param value: Attribute value.
:type value: object
"""
self.__value = value
@value.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def value(self):
"""
Deleter for **value** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "value"))
def __hash__(self):
"""
Reimplements the :meth:`foundations.data_structures.Structure.__hash__` method.
:return: Object hash.
:rtype: int
:note: :class:`foundations.data_structures.Structure` inherits from **dict** and
should not be made hashable because of its mutability, however considering the fact the id
is used as the hash value, making the object hashable should be fairly safe.
"""
return hash(id(self))
def __repr__(self):
"""
Reimplements the :meth:`foundations.data_structures.Structure.__repr__` method.
:return: Object representation.
:rtype: unicode
"""
return "<{0} object at {1}>".format(self.__class__.__name__, hex(id(self)))
|
class Attribute(foundations.data_structures.Structure):
'''
Defines a storage object for the :class:`AbstractNode` class attributes.
'''
def __init__(self, name=None, value=None, **kwargs):
'''
Initializes the class.
Usage::
>>> attribute = Attribute(name="My Attribute", value="My Value")
>>> attribute.name
u'My Attribute'
>>> attribute["name"]
u'My Attribute'
>>> attribute.value
u'My Value'
>>> attribute["value"]
u'My Value'
:param name: Attribute name.
:type name: unicode
:param value: Attribute value.
:type value: object
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
'''
pass
@property
def name(self):
'''
Property for **self.__name** attribute.
:return: Value.
:rtype: unicode
'''
pass
@name.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def name(self):
'''
Setter for **self.__name** attribute.
:param name: Attribute name.
:type name: unicode
'''
pass
@name.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def name(self):
'''
Deleter for **name** attribute.
'''
pass
@property
def value(self):
'''
Property for **self.__value** attribute.
:return: Value.
:rtype: object
'''
pass
@value.setter
def value(self):
'''
Setter for **self.__value** attribute.
:param value: Attribute value.
:type value: object
'''
pass
@value.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def value(self):
'''
Deleter for **value** attribute.
'''
pass
def __hash__(self):
'''
Reimplements the :meth:`foundations.data_structures.Structure.__hash__` method.
:return: Object hash.
:rtype: int
:note: :class:`foundations.data_structures.Structure` inherits from **dict** and
should not be made hashable because of its mutability, however considering the fact the id
is used as the hash value, making the object hashable should be fairly safe.
'''
pass
def __repr__(self):
'''
Reimplements the :meth:`foundations.data_structures.Structure.__repr__` method.
:return: Object representation.
:rtype: unicode
'''
pass
| 19 | 10 | 12 | 2 | 3 | 7 | 1 | 1.77 | 1 | 1 | 1 | 0 | 9 | 2 | 9 | 41 | 127 | 30 | 35 | 18 | 16 | 62 | 24 | 12 | 14 | 1 | 3 | 0 | 9 |
142,291 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/parsers.py
|
foundations.parsers.PlistFileParser
|
class PlistFileParser(foundations.io.File):
"""
Defines methods to parse plist files.
"""
def __init__(self, file=None):
"""
Initializes the class.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.elements.keys()
[u'Dictionary A', u'Number A', u'Array A', u'String A', u'Date A', u'Boolean A', u'Data A']
>>> plist_file_parser.elements["Dictionary A"]
{u'String C': u'My Value C', u'String B': u'My Value B'}
:param file: Current file path.
:type file: unicode
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
foundations.io.File.__init__(self, file)
# --- Setting class attributes. ---
self.__elements = None
self.__parsing_errors = None
self.__unserializers = {"array": lambda x: [value.text for value in x],
"dict": lambda x: dict((x[i].text, x[i + 1].text) for i in range(0, len(x), 2)),
"key": lambda x: foundations.strings.to_string(x.text) or "",
"string": lambda x: foundations.strings.to_string(x.text) or "",
"data": lambda x: base64.decodestring(x.text or ""),
"date": lambda x: datetime.datetime(*map(int, re.findall("\d+", x.text))),
"true": lambda x: True,
"false": lambda x: False,
"real": lambda x: float(x.text),
"integer": lambda x: int(x.text)}
@property
def elements(self):
"""
Property for **self.__elements** attribute.
:return: self.__elements.
:rtype: OrderedDict or dict
"""
return self.__elements
@elements.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def elements(self, value):
"""
Setter for **self.__elements** attribute.
:param value: Attribute value.
:type value: OrderedDict or dict
"""
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not dict'!".format(
"elements", value)
self.__elements = value
@elements.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def elements(self):
"""
Deleter for **self.__elements** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "elements"))
@property
def parsing_errors(self):
"""
Property for **self.__parsing_errors** attribute.
:return: self.__parsing_errors.
:rtype: list
"""
return self.__parsing_errors
@parsing_errors.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def parsing_errors(self, value):
"""
Setter for **self.__parsing_errors** attribute.
:param value: Attribute value.
:type value: list
"""
if value is not None:
assert type(value) is list, "'{0}' attribute: '{1}' type is not 'list'!".format(
"parsing_errors", value)
for element in value:
assert issubclass(element.__class__, foundations.exceptions.AbstractParsingError), \
"'{0}' attribute: '{1}' is not a '{2}' subclass!".format(
"parsing_errors", element, foundations.exceptions.AbstractParsingError.__class__.__name__)
self.__parsing_errors = value
@parsing_errors.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def parsing_errors(self):
"""
Deleter for **self.__parsing_errors** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "parsing_errors"))
@property
def unserializers(self):
"""
Property for **self.__unserializers** attribute.
:return: self.__unserializers.
:rtype: dict
"""
return self.__unserializers
@unserializers.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def unserializers(self, value):
"""
Setter for **self.__unserializers** attribute.
:param value: Attribute value.
:type value: dict
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is read only!".format(self.__class__.__name__, "unserializers"))
@unserializers.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def unserializers(self):
"""
Deleter for **self.__unserializers** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "unserializers"))
@foundations.exceptions.handle_exceptions(foundations.exceptions.FileStructureParsingError)
def parse(self, raise_parsing_errors=True):
"""
Process the file content.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.elements.keys()
[u'Dictionary A', u'Number A', u'Array A', u'String A', u'Date A', u'Boolean A', u'Data A']
:param raise_parsing_errors: Raise parsing errors.
:type raise_parsing_errors: bool
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Reading elements from: '{0}'.".format(self.path))
element_tree_parser = ElementTree.iterparse(self.path)
self.__parsing_errors = []
for action, element in element_tree_parser:
unmarshal = self.__unserializers.get(element.tag)
if unmarshal:
data = unmarshal(element)
element.clear()
element.text = data
elif element.tag != "plist":
self.__parsing_errors.append(foundations.exceptions.FileStructureParsingError(
"Unknown element: {0}".format(element.tag)))
if self.__parsing_errors:
if raise_parsing_errors:
raise foundations.exceptions.FileStructureParsingError(
"{0} | '{1}' structure is invalid, parsing exceptions occured!".format(self.__class__.__name__,
self.path))
else:
self.__elements = foundations.common.get_first_item(
element_tree_parser.root).text
return True
def element_exists(self, element):
"""
Checks if given element exists.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.element_exists("String A")
True
>>> plist_file_parser.element_exists("String Nemo")
False
:param element: Element to check existence.
:type element: unicode
:return: Element existence.
:rtype: bool
"""
if not self.__elements:
return False
for item in foundations.walkers.dictionaries_walker(self.__elements):
path, key, value = item
if key == element:
LOGGER.debug("> '{0}' attribute exists.".format(element))
return True
LOGGER.debug("> '{0}' element doesn't exists.".format(element))
return False
def filter_values(self, pattern, flags=0):
"""
| Filters the :meth:`PlistFileParser.elements` class property elements using given pattern.
| Will return a list of matching elements values, if you want to get only one element value, use
the :meth:`PlistFileParser.get_value` method instead.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.filter_values(r"String A")
[u'My Value A']
>>> plist_file_parser.filter_values(r"String.*")
[u'My Value C', u'My Value B', u'My Value A']
:param pattern: Regex filtering pattern.
:type pattern: unicode
:param flags: Regex flags.
:type flags: int
:return: Values.
:rtype: list
"""
values = []
if not self.__elements:
return values
for item in foundations.walkers.dictionaries_walker(self.__elements):
path, element, value = item
if re.search(pattern, element, flags):
values.append(value)
return values
def get_value(self, element):
"""
| Returns the given element value.
| If multiple elements with the same name exists, only the first encountered will be returned.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.get_value("String A")
u'My Value A'
:param element: Element to get the value.
:type element: unicode
:return: Element value.
:rtype: object
"""
if not self.__elements:
return
values = self.filter_values(r"^{0}$".format(element))
return foundations.common.get_first_item(values)
|
class PlistFileParser(foundations.io.File):
'''
Defines methods to parse plist files.
'''
def __init__(self, file=None):
'''
Initializes the class.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.elements.keys()
[u'Dictionary A', u'Number A', u'Array A', u'String A', u'Date A', u'Boolean A', u'Data A']
>>> plist_file_parser.elements["Dictionary A"]
{u'String C': u'My Value C', u'String B': u'My Value B'}
:param file: Current file path.
:type file: unicode
'''
pass
@property
def elements(self):
'''
Property for **self.__elements** attribute.
:return: self.__elements.
:rtype: OrderedDict or dict
'''
pass
@elements.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def elements(self):
'''
Setter for **self.__elements** attribute.
:param value: Attribute value.
:type value: OrderedDict or dict
'''
pass
@elements.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def elements(self):
'''
Deleter for **self.__elements** attribute.
'''
pass
@property
def parsing_errors(self):
'''
Property for **self.__parsing_errors** attribute.
:return: self.__parsing_errors.
:rtype: list
'''
pass
@parsing_errors.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def parsing_errors(self):
'''
Setter for **self.__parsing_errors** attribute.
:param value: Attribute value.
:type value: list
'''
pass
@parsing_errors.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def parsing_errors(self):
'''
Deleter for **self.__parsing_errors** attribute.
'''
pass
@property
def unserializers(self):
'''
Property for **self.__unserializers** attribute.
:return: self.__unserializers.
:rtype: dict
'''
pass
@unserializers.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def unserializers(self):
'''
Setter for **self.__unserializers** attribute.
:param value: Attribute value.
:type value: dict
'''
pass
@unserializers.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def unserializers(self):
'''
Deleter for **self.__unserializers** attribute.
'''
pass
@foundations.exceptions.handle_exceptions(foundations.exceptions.FileStructureParsingError)
def parse(self, raise_parsing_errors=True):
'''
Process the file content.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.elements.keys()
[u'Dictionary A', u'Number A', u'Array A', u'String A', u'Date A', u'Boolean A', u'Data A']
:param raise_parsing_errors: Raise parsing errors.
:type raise_parsing_errors: bool
:return: Method success.
:rtype: bool
'''
pass
def element_exists(self, element):
'''
Checks if given element exists.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.element_exists("String A")
True
>>> plist_file_parser.element_exists("String Nemo")
False
:param element: Element to check existence.
:type element: unicode
:return: Element existence.
:rtype: bool
'''
pass
def filter_values(self, pattern, flags=0):
'''
| Filters the :meth:`PlistFileParser.elements` class property elements using given pattern.
| Will return a list of matching elements values, if you want to get only one element value, use
the :meth:`PlistFileParser.get_value` method instead.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.filter_values(r"String A")
[u'My Value A']
>>> plist_file_parser.filter_values(r"String.*")
[u'My Value C', u'My Value B', u'My Value A']
:param pattern: Regex filtering pattern.
:type pattern: unicode
:param flags: Regex flags.
:type flags: int
:return: Values.
:rtype: list
'''
pass
def get_value(self, element):
'''
| Returns the given element value.
| If multiple elements with the same name exists, only the first encountered will be returned.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.get_value("String A")
u'My Value A'
:param element: Element to get the value.
:type element: unicode
:return: Element value.
:rtype: object
'''
pass
| 31 | 15 | 18 | 3 | 6 | 8 | 2 | 1.09 | 1 | 11 | 3 | 0 | 14 | 3 | 14 | 27 | 283 | 59 | 107 | 39 | 76 | 117 | 71 | 29 | 56 | 6 | 2 | 2 | 29 |
142,292 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/environment.py
|
foundations.environment.Environment
|
class Environment(object):
"""
Defines methods to manipulate environment variables.
"""
def __init__(self, *args, **kwargs):
"""
Initializes the class.
Usage::
>>> environment = Environment(JOHN="DOE", DOE="JOHN")
>>> environment.set_values()
True
>>> import os
>>> os.environ["JOHN"]
u'DOE'
>>> os.environ["DOE"]
u'JOHN'
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
# --- Setting class attributes. ---
self.__variables = {}
self.__add_variables(*args, **kwargs)
@property
def variables(self):
"""
Property for **self.__variables** attribute.
:return: self.__variables.
:rtype: dict
"""
return self.__variables
@variables.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def variables(self, value):
"""
Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict
"""
if value is not None:
assert type(value) is dict, "'{0}' attribute: '{1}' type is not 'dict'!".format(
"variables", value)
for key, element in value.iteritems():
assert type(key) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"variables", key)
assert type(element) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format(
"variables", element)
self.__variables = value
@variables.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def variables(self):
"""
Deleter for **self.__variables** attribute.
"""
raise foundations.exceptions.ProgrammingError(
"{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "variables"))
def __add_variables(self, *args, **kwargs):
"""
Adds given variables to __variables attribute.
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
"""
for variable in args:
self.__variables[variable] = None
self.__variables.update(kwargs)
def get_values(self, *args):
"""
Gets environment variables values.
Usage::
>>> environment = Environment("HOME")
>>> environment.get_values()
{'HOME': u'/Users/JohnDoe'}
>>> environment.get_values("USER")
{'HOME': u'/Users/JohnDoe', 'USER': u'JohnDoe'}
:param \*args: Additional variables names to retrieve values from.
:type \*args: \*
:return: Variables : Values.
:rtype: dict
"""
args and self.__add_variables(*args)
LOGGER.debug("> Object environment variables: '{0}'.".format(
",".join((key for key in self.__variables if key))))
LOGGER.debug(
"> Available system environment variables: '{0}'".format(os.environ.keys()))
for variable in self.__variables:
value = os.environ.get(variable, None)
self.__variables[variable] = foundations.strings.to_string(
value) if value else None
return self.__variables
def set_values(self, **kwargs):
"""
Sets environment variables values.
Usage::
>>> environment = Environment()
>>> environment.set_values(JOHN="DOE", DOE="JOHN")
True
>>> import os
>>> os.environ["JOHN"]
'DOE'
>>> os.environ["DOE"]
'JOHN'
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
:return: Method success.
:rtype: unicode
:note: Any variable with a **None** value will be skipped.
"""
self.__variables.update(kwargs)
for key, value in self.__variables.iteritems():
if value is None:
continue
LOGGER.debug(
"> Setting environment variable '{0}' with value '{1}'.".format(key, value))
os.environ[key] = value
return True
def get_value(self, variable=None):
"""
Gets given environment variable value.
:param variable: Variable to retrieve value.
:type variable: unicode
:return: Variable value.
:rtype: unicode
:note: If the **variable** argument is not given the first **self.__variables** attribute value will be returned.
"""
if variable:
self.get_values(variable)
return self.__variables[variable]
else:
self.get_values()
return foundations.common.get_first_item(self.__variables.values())
def set_value(self, variable, value):
"""
Sets given environment variable with given value.
:param variable: Variable to set value.
:type variable: unicode
:param value: Variable value.
:type value: unicode
:return: Method success.
:rtype: bool
"""
return self.set_values(**{variable: value})
|
class Environment(object):
'''
Defines methods to manipulate environment variables.
'''
def __init__(self, *args, **kwargs):
'''
Initializes the class.
Usage::
>>> environment = Environment(JOHN="DOE", DOE="JOHN")
>>> environment.set_values()
True
>>> import os
>>> os.environ["JOHN"]
u'DOE'
>>> os.environ["DOE"]
u'JOHN'
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
'''
pass
@property
def variables(self):
'''
Property for **self.__variables** attribute.
:return: self.__variables.
:rtype: dict
'''
pass
@variables.setter
@foundations.exceptions.handle_exceptions(AssertionError)
def variables(self):
'''
Setter for **self.__variables** attribute.
:param value: Attribute value.
:type value: dict
'''
pass
@variables.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def variables(self):
'''
Deleter for **self.__variables** attribute.
'''
pass
def __add_variables(self, *args, **kwargs):
'''
Adds given variables to __variables attribute.
:param \*args: Variables.
:type \*args: \*
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
'''
pass
def get_values(self, *args):
'''
Gets environment variables values.
Usage::
>>> environment = Environment("HOME")
>>> environment.get_values()
{'HOME': u'/Users/JohnDoe'}
>>> environment.get_values("USER")
{'HOME': u'/Users/JohnDoe', 'USER': u'JohnDoe'}
:param \*args: Additional variables names to retrieve values from.
:type \*args: \*
:return: Variables : Values.
:rtype: dict
'''
pass
def set_values(self, **kwargs):
'''
Sets environment variables values.
Usage::
>>> environment = Environment()
>>> environment.set_values(JOHN="DOE", DOE="JOHN")
True
>>> import os
>>> os.environ["JOHN"]
'DOE'
>>> os.environ["DOE"]
'JOHN'
:param \*\*kwargs: Variables : Values.
:type \*\*kwargs: \*
:return: Method success.
:rtype: unicode
:note: Any variable with a **None** value will be skipped.
'''
pass
def get_values(self, *args):
'''
Gets given environment variable value.
:param variable: Variable to retrieve value.
:type variable: unicode
:return: Variable value.
:rtype: unicode
:note: If the **variable** argument is not given the first **self.__variables** attribute value will be returned.
'''
pass
def set_values(self, **kwargs):
'''
Sets given environment variable with given value.
:param variable: Variable to set value.
:type variable: unicode
:param value: Variable value.
:type value: unicode
:return: Method success.
:rtype: bool
'''
pass
| 15 | 10 | 18 | 3 | 5 | 9 | 2 | 1.61 | 1 | 3 | 1 | 0 | 9 | 1 | 9 | 9 | 179 | 38 | 54 | 19 | 39 | 87 | 44 | 16 | 34 | 3 | 1 | 2 | 17 |
142,293 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.UrlWriteError
|
class UrlWriteError(AbstractIOError):
"""
Defines file write exception.
"""
pass
|
class UrlWriteError(AbstractIOError):
'''
Defines file write exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,294 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestIsReadOnly.test_is_read_only.Writable
|
class Writable(object):
pass
|
class Writable(object):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
142,295 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.PathExistsError
|
class PathExistsError(AbstractOsError):
"""
Defines non existing path exception.
"""
pass
|
class PathExistsError(AbstractOsError):
'''
Defines non existing path exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 2 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,296 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/data_structures.py
|
foundations.data_structures.NestedAttribute
|
class NestedAttribute(object):
"""
Defines an helper object providing methods to manipulate nested attributes.
Usage:
>>> nest = NestedAttribute()
>>> nest.my.nested.attribute = "Value"
>>> nest.my.nested.attribute
Value
>>> nest.another.very.deeply.nested.attribute = 64
>>> nest.another.very.deeply.nested.attribute
64
"""
def __getattr__(self, attribute):
"""
Returns requested attribute.
:param attribute: Attribute name.
:type attribute: unicode
:return: Attribute.
:rtype: object
"""
self.__dict__[attribute] = NestedAttribute()
return self.__dict__[attribute]
def __setattr__(self, attribute, value):
"""
Sets given attribute with given value.
:param attribute: Attribute name.
:type attribute: unicode
:param name: Attribute value.
:type name: object
"""
namespaces = attribute.split(".")
object.__setattr__(reduce(object.__getattribute__, namespaces[:-1], self), namespaces[-1], value)
def __delattr__(self, attribute):
"""
Deletes given attribute with.
:param attribute: Attribute name.
:type attribute: unicode
"""
namespaces = attribute.split(".")
object.__delattr__(reduce(object.__getattribute__, namespaces[:-1], self), namespaces[-1])
|
class NestedAttribute(object):
'''
Defines an helper object providing methods to manipulate nested attributes.
Usage:
>>> nest = NestedAttribute()
>>> nest.my.nested.attribute = "Value"
>>> nest.my.nested.attribute
Value
>>> nest.another.very.deeply.nested.attribute = 64
>>> nest.another.very.deeply.nested.attribute
64
'''
def __getattr__(self, attribute):
'''
Returns requested attribute.
:param attribute: Attribute name.
:type attribute: unicode
:return: Attribute.
:rtype: object
'''
pass
def __setattr__(self, attribute, value):
'''
Sets given attribute with given value.
:param attribute: Attribute name.
:type attribute: unicode
:param name: Attribute value.
:type name: object
'''
pass
def __delattr__(self, attribute):
'''
Deletes given attribute with.
:param attribute: Attribute name.
:type attribute: unicode
'''
pass
| 4 | 4 | 11 | 2 | 3 | 6 | 1 | 3 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 51 | 11 | 10 | 6 | 6 | 30 | 10 | 6 | 6 | 1 | 1 | 0 | 3 |
142,297 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/data_structures.py
|
foundations.data_structures.OrderedStructure
|
class OrderedStructure(OrderedDict):
"""
| Defines an object similar to C/C++ structured type.
| Contrary to the :class:`Structure` since this class inherits from :class:`collections.OrderedDict`,
its content is ordered.
Usage:
>>> people = OrderedStructure([("personA", "John"), ("personB", "Jane"), ("personC", "Luke")])
>>> people
OrderedStructure([('personA', 'John'), ('personB', 'Jane'), ('personC', 'Luke')])
>>> people.keys()
['personA', 'personB', 'personC']
>>> people.personA
'John'
>>> del(people["personA"])
>>> people["personA"]
Traceback (most recent call last):
File "<console>", line 1, in <module>
KeyError: 'personA'
>>> people.personA
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'OrderedStructure' object has no attribute 'personA'
>>> people.personB = "Kate"
>>> people["personB"]
'Kate'
>>> people.personB
'Kate'
"""
def __init__(self, *args, **kwargs):
"""
Initializes the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
"""
OrderedDict.__init__(self, *args, **kwargs)
def __setitem__(self, key, value, *args, **kwargs):
"""
Sets a key and sibling attribute with given value.
:param key: Key.
:type key: object
:param value: Value.
:type value: object
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
"""
OrderedDict.__setitem__(self, key, value, *args, **kwargs)
OrderedDict.__setattr__(self, key, value)
def __delitem__(self, key, *args, **kwargs):
"""
Deletes both key and sibling attribute.
:param key: Key.
:type key: object
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
"""
OrderedDict.__delitem__(self, key, *args, **kwargs)
OrderedDict.__delattr__(self, key)
def __setattr__(self, attribute, value):
"""
Sets both key and sibling attribute with given value.
:param attribute: Attribute.
:type attribute: object
:param value: Value.
:type value: object
"""
if sys.version_info[:2] <= (2, 6):
if not attribute in ("_OrderedDict__map", "_OrderedDict__end"):
OrderedDict.__setitem__(self, attribute, value)
else:
if hasattr(self, "_OrderedDict__root") and hasattr(self, "_OrderedDict__map"):
if self._OrderedDict__root:
OrderedDict.__setitem__(self, attribute, value)
OrderedDict.__setattr__(self, attribute, value)
def __delattr__(self, attribute):
"""
Deletes both key and sibling attribute.
:param attribute: Attribute.
:type attribute: object
"""
if sys.version_info[:2] <= (2, 6):
if not attribute in ("_OrderedDict__map", "_OrderedDict__end"):
OrderedDict.__delitem__(self, attribute)
else:
if hasattr(self, "_OrderedDict__root") and hasattr(self, "_OrderedDict__map"):
if self._OrderedDict__root:
OrderedDict.__delitem__(self, attribute)
OrderedDict.__delattr__(self, attribute)
|
class OrderedStructure(OrderedDict):
'''
| Defines an object similar to C/C++ structured type.
| Contrary to the :class:`Structure` since this class inherits from :class:`collections.OrderedDict`,
its content is ordered.
Usage:
>>> people = OrderedStructure([("personA", "John"), ("personB", "Jane"), ("personC", "Luke")])
>>> people
OrderedStructure([('personA', 'John'), ('personB', 'Jane'), ('personC', 'Luke')])
>>> people.keys()
['personA', 'personB', 'personC']
>>> people.personA
'John'
>>> del(people["personA"])
>>> people["personA"]
Traceback (most recent call last):
File "<console>", line 1, in <module>
KeyError: 'personA'
>>> people.personA
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'OrderedStructure' object has no attribute 'personA'
>>> people.personB = "Kate"
>>> people["personB"]
'Kate'
>>> people.personB
'Kate'
'''
def __init__(self, *args, **kwargs):
'''
Initializes the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
'''
pass
def __setitem__(self, key, value, *args, **kwargs):
'''
Sets a key and sibling attribute with given value.
:param key: Key.
:type key: object
:param value: Value.
:type value: object
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
'''
pass
def __delitem__(self, key, *args, **kwargs):
'''
Deletes both key and sibling attribute.
:param key: Key.
:type key: object
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
'''
pass
def __setattr__(self, attribute, value):
'''
Sets both key and sibling attribute with given value.
:param attribute: Attribute.
:type attribute: object
:param value: Value.
:type value: object
'''
pass
def __delattr__(self, attribute):
'''
Deletes both key and sibling attribute.
:param attribute: Attribute.
:type attribute: object
'''
pass
| 6 | 6 | 15 | 2 | 5 | 8 | 3 | 2.44 | 1 | 0 | 0 | 0 | 5 | 0 | 5 | 5 | 110 | 17 | 27 | 6 | 21 | 66 | 25 | 6 | 19 | 5 | 1 | 3 | 13 |
142,298 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/data_structures.py
|
foundations.data_structures.Structure
|
class Structure(dict):
"""
Defines an object similar to C/C++ structured type.
Usage:
>>> person = Structure(firstName="Doe", lastName="John", gender="male")
>>> person.firstName
'Doe'
>>> person.keys()
['gender', 'firstName', 'lastName']
>>> person["gender"]
'male'
>>> del(person["gender"])
>>> person["gender"]
Traceback (most recent call last):
File "<console>", line 1, in <module>
KeyError: 'gender'
>>> person.gender
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Structure' object has no attribute 'gender'
"""
def __init__(self, *args, **kwargs):
"""
Initializes the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
"""
dict.__init__(self, **kwargs)
self.__dict__.update(**kwargs)
def __getattr__(self, attribute):
"""
Returns given attribute value.
:return: Attribute value.
:rtype: object
"""
try:
return dict.__getitem__(self, attribute)
except KeyError:
raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, attribute))
def __setattr__(self, attribute, value):
"""
Sets both key and sibling attribute with given value.
:param attribute: Attribute.
:type attribute: object
:param value: Value.
:type value: object
"""
dict.__setitem__(self, attribute, value)
object.__setattr__(self, attribute, value)
__setitem__ = __setattr__
def __delattr__(self, attribute):
"""
Deletes both key and sibling attribute.
:param attribute: Attribute.
:type attribute: object
"""
dict.__delitem__(self, attribute)
object.__delattr__(self, attribute)
__delitem__ = __delattr__
def update(self, *args, **kwargs):
"""
Reimplements the :meth:`Dict.update` method.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
"""
dict.update(self, *args, **kwargs)
self.__dict__.update(*args, **kwargs)
|
class Structure(dict):
'''
Defines an object similar to C/C++ structured type.
Usage:
>>> person = Structure(firstName="Doe", lastName="John", gender="male")
>>> person.firstName
'Doe'
>>> person.keys()
['gender', 'firstName', 'lastName']
>>> person["gender"]
'male'
>>> del(person["gender"])
>>> person["gender"]
Traceback (most recent call last):
File "<console>", line 1, in <module>
KeyError: 'gender'
>>> person.gender
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Structure' object has no attribute 'gender'
'''
def __init__(self, *args, **kwargs):
'''
Initializes the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Key / Value pairs.
:type \*\*kwargs: dict
'''
pass
def __getattr__(self, attribute):
'''
Returns given attribute value.
:return: Attribute value.
:rtype: object
'''
pass
def __setattr__(self, attribute, value):
'''
Sets both key and sibling attribute with given value.
:param attribute: Attribute.
:type attribute: object
:param value: Value.
:type value: object
'''
pass
def __delattr__(self, attribute):
'''
Deletes both key and sibling attribute.
:param attribute: Attribute.
:type attribute: object
'''
pass
def update(self, *args, **kwargs):
'''
Reimplements the :meth:`Dict.update` method.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
'''
pass
| 6 | 6 | 12 | 2 | 3 | 6 | 1 | 2.55 | 1 | 2 | 0 | 4 | 5 | 0 | 5 | 32 | 90 | 19 | 20 | 8 | 14 | 51 | 20 | 8 | 14 | 2 | 2 | 1 | 6 |
142,299 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.AbstractError
|
class AbstractError(Exception):
"""
Defines the abstract base class for all **Foundations** package exceptions.
"""
def __init__(self, value):
"""
Initializes the class.
:param value: Error value or message.
:type value: unicode
"""
LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__))
# --- Setting class attributes. ---
self.__value = value
@property
def value(self):
"""
Property for **self.__value** attribute.
:return: self.__value.
:rtype: object
"""
return self.__value
@value.setter
def value(self, value):
"""
Setter for **self.__value** attribute.
:param value: Attribute value.
:type value: object
"""
self.__value = value
@value.deleter
def value(self):
"""
Deleter for **self.__value** attribute.
"""
raise Exception("{0} | '{1}' attribute is not deletable!".format(self.__class__.__name__, "value"))
def __str__(self):
"""
Returns the exception representation.
:return: Exception representation.
:rtype: unicode
"""
return str(self.__value)
|
class AbstractError(Exception):
'''
Defines the abstract base class for all **Foundations** package exceptions.
'''
def __init__(self, value):
'''
Initializes the class.
:param value: Error value or message.
:type value: unicode
'''
pass
@property
def value(self):
'''
Property for **self.__value** attribute.
:return: self.__value.
:rtype: object
'''
pass
@value.setter
def value(self):
'''
Setter for **self.__value** attribute.
:param value: Attribute value.
:type value: object
'''
pass
@value.deleter
def value(self):
'''
Deleter for **self.__value** attribute.
'''
pass
def __str__(self):
'''
Returns the exception representation.
:return: Exception representation.
:rtype: unicode
'''
pass
| 9 | 6 | 9 | 2 | 2 | 5 | 1 | 1.8 | 1 | 1 | 0 | 11 | 5 | 1 | 5 | 15 | 57 | 15 | 15 | 10 | 6 | 27 | 12 | 7 | 6 | 1 | 3 | 0 | 5 |
142,300 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.AnsiEscapeCodeExistsError
|
class AnsiEscapeCodeExistsError(AbstractError):
"""
Defines exception used for non existing *ANSI* escape codes.
"""
pass
|
class AnsiEscapeCodeExistsError(AbstractError):
'''
Defines exception used for non existing *ANSI* escape codes.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
142,301 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.BreakIteration
|
class BreakIteration(AbstractError):
"""
Breaks nested loop iteration.
"""
pass
|
class BreakIteration(AbstractError):
'''
Breaks nested loop iteration.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
142,302 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.DirectoryCreationError
|
class DirectoryCreationError(AbstractIOError):
"""
Defines directory creation exception.
"""
pass
|
class DirectoryCreationError(AbstractIOError):
'''
Defines directory creation exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,303 |
KelSolaar/Foundations
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/KelSolaar_Foundations/foundations/ui/common.py
|
foundations.ui.common.QWidget_factory.QWidget
|
class QWidget(Form, Base):
"""
Derives from :def:`QWidget_factory` class factory definition.
"""
def __init__(self, *args, **kwargs):
"""
Initializes the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
"""
LOGGER.debug("> Initializing '{0}()' class.".format(
self.__class__.__name__))
super(QWidget, self).__init__(*args, **kwargs)
self.__ui_file = file
self.__geometry = None
self.setupUi(self)
@property
def ui_file(self):
"""
Property for **self.__ui_file** attribute.
:return: self.__ui_file.
:rtype: unicode
"""
return self.__ui_file
@ui_file.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def ui_file(self, value):
"""
Setter for **self.__ui_file** attribute.
:param value: Attribute value.
:type value: unicode
"""
raise foundations.exceptions.ProgrammingError("{0} | '{1}' attribute is read only!".format(
self.__class__.__name__, "ui_file"))
@ui_file.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def ui_file(self):
"""
Deleter for **self.__ui_file** attribute.
"""
raise foundations.exceptions.ProgrammingError("{0} | '{1}' attribute is not deletable!".format(
self.__class__.__name__, "ui_file"))
def show(self, setGeometry=True):
"""
Reimplements the :meth:`QWidget.show` method.
:param setGeometry: Set geometry.
:type setGeometry: bool
"""
if not setGeometry:
super(QWidget, self).show()
return
wasHidden = not self.isVisible()
if self.__geometry is None and wasHidden:
center_widget_on_screen(self)
super(QWidget, self).show()
if self.__geometry is not None and wasHidden:
self.restoreGeometry(self.__geometry)
def closeEvent(self, event):
"""
Reimplements the :meth:`QWidget.closeEvent` method.
:param event: QEvent.
:type event: QEvent
"""
self.__geometry = self.saveGeometry()
event.accept()
|
class QWidget(Form, Base):
'''
Derives from :def:`QWidget_factory` class factory definition.
'''
def __init__(self, *args, **kwargs):
'''
Initializes the class.
:param \*args: Arguments.
:type \*args: \*
:param \*\*kwargs: Keywords arguments.
:type \*\*kwargs: \*\*
'''
pass
@property
def ui_file(self):
'''
Property for **self.__ui_file** attribute.
:return: self.__ui_file.
:rtype: unicode
'''
pass
@ui_file.setter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def ui_file(self):
'''
Setter for **self.__ui_file** attribute.
:param value: Attribute value.
:type value: unicode
'''
pass
@ui_file.deleter
@foundations.exceptions.handle_exceptions(foundations.exceptions.ProgrammingError)
def ui_file(self):
'''
Deleter for **self.__ui_file** attribute.
'''
pass
def show(self, setGeometry=True):
'''
Reimplements the :meth:`QWidget.show` method.
:param setGeometry: Set geometry.
:type setGeometry: bool
'''
pass
def closeEvent(self, event):
'''
Reimplements the :meth:`QWidget.closeEvent` method.
:param event: QEvent.
:type event: QEvent
'''
pass
| 12 | 7 | 13 | 3 | 5 | 5 | 2 | 1 | 2 | 2 | 1 | 0 | 6 | 2 | 6 | 6 | 92 | 26 | 33 | 13 | 21 | 33 | 26 | 10 | 19 | 4 | 1 | 1 | 9 |
142,304 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.DirectoryExistsError
|
class DirectoryExistsError(PathExistsError):
"""
Defines non existing directory exception.
"""
pass
|
class DirectoryExistsError(PathExistsError):
'''
Defines non existing directory exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 6 | 0 | 0 |
142,305 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.FileExistsError
|
class FileExistsError(PathExistsError):
"""
Defines non existing file exception.
"""
pass
|
class FileExistsError(PathExistsError):
'''
Defines non existing file exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 6 | 0 | 0 |
142,306 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.FileReadError
|
class FileReadError(AbstractIOError):
"""
Defines file read exception.
"""
pass
|
class FileReadError(AbstractIOError):
'''
Defines file read exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,307 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.FileStructureParsingError
|
class FileStructureParsingError(AbstractParsingError):
"""
Defines exception raised while parsing file structure.
"""
pass
|
class FileStructureParsingError(AbstractParsingError):
'''
Defines exception raised while parsing file structure.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,308 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.FileWriteError
|
class FileWriteError(AbstractIOError):
"""
Defines file write exception.
"""
pass
|
class FileWriteError(AbstractIOError):
'''
Defines file write exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,309 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.NodeAttributeExistsError
|
class NodeAttributeExistsError(AbstractNodeError, ObjectExistsError):
"""
Defines non existing Node attribute exception.
"""
pass
|
class NodeAttributeExistsError(AbstractNodeError, ObjectExistsError):
'''
Defines non existing Node attribute exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 6 | 0 | 0 |
142,310 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.ObjectExistsError
|
class ObjectExistsError(AbstractObjectError):
"""
Defines non existing object exception.
"""
pass
|
class ObjectExistsError(AbstractObjectError):
'''
Defines non existing object exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,311 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.PathCopyError
|
class PathCopyError(AbstractIOError):
"""
Defines path copy exception.
"""
pass
|
class PathCopyError(AbstractIOError):
'''
Defines path copy exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
142,312 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/exceptions.py
|
foundations.exceptions.ExecutionError
|
class ExecutionError(AbstractError):
"""
Defines execution exception.
"""
pass
|
class ExecutionError(AbstractError):
'''
Defines execution exception.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
142,313 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_cache.py
|
foundations.tests.tests_foundations.tests_cache.TestCache
|
class TestCache(unittest.TestCase):
"""
Defines :class:`foundations.cache.Cache` class units tests methods.
"""
def test_required_methods(self):
"""
Tests presence of required methods.
"""
required_methods = ("add_content",
"remove_content",
"get_content",
"flush_content")
for method in required_methods:
self.assertIn(method, dir(Cache))
def test_add_content(self):
"""
Tests :meth:`foundations.cache.Cache.add_content` method.
"""
cache = Cache()
self.assertTrue(cache.add_content(John="Doe", Luke="Skywalker"))
self.assertDictEqual(cache, {"John": "Doe", "Luke": "Skywalker"})
def test_removeContent(self):
"""
Tests :meth:`foundations.cache.Cache.remove_content` method.
"""
cache = Cache()
cache.add_content(John="Doe", Luke="Skywalker")
self.assertTrue(cache.remove_content("John", "Luke"))
self.assertDictEqual(cache, {})
def test_get_content(self):
"""
Tests :meth:`foundations.cache.Cache.get_content` method.
"""
cache = Cache()
content = {"John": "Doe", "Luke": "Skywalker"}
cache.add_content(**content)
for key, value in content.iteritems():
self.assertEqual(cache.get_content(key), value)
def test_flush_content(self):
"""
Tests :meth:`foundations.cache.Cache.flush_content` method.
"""
cache = Cache()
cache.add_content(John="Doe", Luke="Skywalker")
self.assertTrue(cache.flush_content())
self.assertDictEqual(cache, {})
|
class TestCache(unittest.TestCase):
'''
Defines :class:`foundations.cache.Cache` class units tests methods.
'''
def test_required_methods(self):
'''
Tests presence of required methods.
'''
pass
def test_add_content(self):
'''
Tests :meth:`foundations.cache.Cache.add_content` method.
'''
pass
def test_removeContent(self):
'''
Tests :meth:`foundations.cache.Cache.remove_content` method.
'''
pass
def test_get_content(self):
'''
Tests :meth:`foundations.cache.Cache.get_content` method.
'''
pass
def test_flush_content(self):
'''
Tests :meth:`foundations.cache.Cache.flush_content` method.
'''
pass
| 6 | 6 | 10 | 1 | 5 | 3 | 1 | 0.64 | 1 | 1 | 1 | 0 | 5 | 0 | 5 | 77 | 57 | 11 | 28 | 14 | 22 | 18 | 25 | 14 | 19 | 2 | 2 | 1 | 7 |
142,314 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_namespace.py
|
foundations.tests.tests_foundations.tests_namespace.TestGetNamespace
|
class TestGetNamespace(unittest.TestCase):
"""
Defines :func:`foundations.namespace.get_namespace` definition units tests methods.
"""
def test_get_namespace(self):
"""
Tests :func:`foundations.namespace.get_namespace` definition.
"""
self.assertIsInstance(foundations.namespace.get_namespace("Namespace:Attribute", ":"), unicode)
self.assertEqual(foundations.namespace.get_namespace("Namespace|Attribute"), "Namespace")
self.assertEqual(foundations.namespace.get_namespace("Namespace:Attribute", ":"), "Namespace")
self.assertEqual(foundations.namespace.get_namespace("Namespace|Attribute|Value", root_only=True), "Namespace")
self.assertIsNone(foundations.namespace.get_namespace("Namespace"))
|
class TestGetNamespace(unittest.TestCase):
'''
Defines :func:`foundations.namespace.get_namespace` definition units tests methods.
'''
def test_get_namespace(self):
'''
Tests :func:`foundations.namespace.get_namespace` definition.
'''
pass
| 2 | 2 | 10 | 1 | 6 | 3 | 1 | 0.86 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 7 | 2 | 5 | 6 | 7 | 2 | 5 | 1 | 2 | 0 | 1 |
142,315 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_common.py
|
foundations.tests.tests_foundations.tests_common.TestFilterPath
|
class TestFilterPath(unittest.TestCase):
"""
Defines :func:`foundations.common.filter_path` definition units tests methods.
"""
def test_filter_path(self):
"""
Tests :func:`foundations.common.filter_path` definition.
"""
self.assertEqual(foundations.common.filter_path(None), "")
self.assertEqual(foundations.common.filter_path(__file__), __file__)
|
class TestFilterPath(unittest.TestCase):
'''
Defines :func:`foundations.common.filter_path` definition units tests methods.
'''
def test_filter_path(self):
'''
Tests :func:`foundations.common.filter_path` definition.
'''
pass
| 2 | 2 | 7 | 1 | 3 | 3 | 1 | 1.5 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 12 | 2 | 4 | 2 | 2 | 6 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
142,316 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestTraceClass
|
class TestTraceClass(unittest.TestCase):
"""
Defines :func:`foundations.trace.trace_class` definition units tests methods.
"""
def test_trace_class(self):
"""
Tests :func:`foundations.trace.trace_class` definition.
"""
self.assertFalse(foundations.trace.is_traced(Dummy))
self.assertTrue(foundations.trace.trace_class(Dummy))
self.assertTrue(foundations.trace.is_traced(Dummy))
for method in TRACABLE_METHODS.iterkeys():
self.assertTrue(foundations.trace.is_traced(getattr(Dummy, method)))
for method in UNTRACABLE_METHODS.iterkeys():
self.assertFalse(foundations.trace.is_traced(getattr(Dummy, method)))
for name, accessor in inspect.getmembers(Dummy, lambda x: type(x) is property):
self.assertTrue(foundations.trace.is_traced(accessor.fget))
self.assertTrue(foundations.trace.is_traced(accessor.fset))
self.assertTrue(foundations.trace.is_traced(accessor.fdel))
foundations.trace.untrace_class(Dummy)
self.assertTrue(foundations.trace.trace_class(Dummy, pattern=r"^public_method$"))
self.assertTrue(foundations.trace.is_traced(getattr(Dummy, "public_method")))
self.assertFalse(foundations.trace.is_traced(getattr(Dummy, "class_method")))
foundations.trace.untrace_class(Dummy)
self.assertTrue(foundations.trace.trace_class(Dummy, pattern=r"^(?:(?!public_method).)*$"))
self.assertFalse(foundations.trace.is_traced(getattr(Dummy, "public_method")))
self.assertTrue(foundations.trace.is_traced(getattr(Dummy, "class_method")))
foundations.trace.untrace_class(Dummy)
|
class TestTraceClass(unittest.TestCase):
'''
Defines :func:`foundations.trace.trace_class` definition units tests methods.
'''
def test_trace_class(self):
'''
Tests :func:`foundations.trace.trace_class` definition.
'''
pass
| 2 | 2 | 33 | 9 | 21 | 3 | 4 | 0.27 | 1 | 3 | 1 | 0 | 1 | 0 | 1 | 73 | 38 | 10 | 22 | 4 | 20 | 6 | 22 | 4 | 20 | 4 | 2 | 1 | 4 |
142,317 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestSetUntraced
|
class TestSetUntraced(unittest.TestCase):
"""
Defines :func:`foundations.trace.set_untraced` definition units tests methods.
"""
def test_set_traced(self):
"""
Tests :func:`foundations.trace.set_untraced` definition.
"""
object = lambda: None
foundations.trace.set_traced(object)
self.assertTrue(foundations.trace.set_untraced(object))
self.assertFalse(hasattr(object, foundations.trace.TRACER_SYMBOL))
|
class TestSetUntraced(unittest.TestCase):
'''
Defines :func:`foundations.trace.set_untraced` definition units tests methods.
'''
def test_set_traced(self):
'''
Tests :func:`foundations.trace.set_untraced` definition.
'''
pass
| 2 | 2 | 9 | 1 | 5 | 3 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 14 | 2 | 6 | 3 | 4 | 6 | 6 | 3 | 4 | 1 | 2 | 0 | 1 |
142,318 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestSetUntracable
|
class TestSetUntracable(unittest.TestCase):
"""
Defines :func:`foundations.trace.set_untracable` definition units tests methods.
"""
def test_set_untracable(self):
"""
Tests :func:`foundations.trace.set_untracable` definition.
"""
object = foundations.trace.untracable(lambda: None)
self.assertTrue(hasattr(object, foundations.trace.UNTRACABLE_SYMBOL))
|
class TestSetUntracable(unittest.TestCase):
'''
Defines :func:`foundations.trace.set_untracable` definition units tests methods.
'''
def test_set_untracable(self):
'''
Tests :func:`foundations.trace.set_untracable` definition.
'''
pass
| 2 | 2 | 7 | 1 | 3 | 3 | 1 | 1.5 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 12 | 2 | 4 | 3 | 2 | 6 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
142,319 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestSetTracerHook
|
class TestSetTracerHook(unittest.TestCase):
"""
Defines :func:`foundations.trace.set_tracer_hook` definition units tests methods.
"""
def test_set_tracer_hook(self):
"""
Tests :func:`foundations.trace.set_tracer_hook` definition.
"""
object, hook = lambda: None, ""
self.assertTrue(foundations.trace.set_tracer_hook(object, hook))
self.assertTrue(hasattr(object, foundations.trace.TRACER_HOOK))
|
class TestSetTracerHook(unittest.TestCase):
'''
Defines :func:`foundations.trace.set_tracer_hook` definition units tests methods.
'''
def test_set_tracer_hook(self):
'''
Tests :func:`foundations.trace.set_tracer_hook` definition.
'''
pass
| 2 | 2 | 8 | 1 | 4 | 3 | 1 | 1.2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 13 | 2 | 5 | 3 | 3 | 6 | 5 | 3 | 3 | 1 | 2 | 0 | 1 |
142,320 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestSetTraced
|
class TestSetTraced(unittest.TestCase):
"""
Defines :func:`foundations.trace.set_traced` definition units tests methods.
"""
def test_set_traced(self):
"""
Tests :func:`foundations.trace.set_traced` definition.
"""
object = lambda: None
self.assertTrue(foundations.trace.set_traced(object))
self.assertTrue(hasattr(object, foundations.trace.TRACER_SYMBOL))
|
class TestSetTraced(unittest.TestCase):
'''
Defines :func:`foundations.trace.set_traced` definition units tests methods.
'''
def test_set_traced(self):
'''
Tests :func:`foundations.trace.set_traced` definition.
'''
pass
| 2 | 2 | 8 | 1 | 4 | 3 | 1 | 1.2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 13 | 2 | 5 | 3 | 3 | 6 | 5 | 3 | 3 | 1 | 2 | 0 | 1 |
142,321 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestRegisterModule
|
class TestRegisterModule(unittest.TestCase):
"""
Defines :func:`foundations.trace.register_module` definition units tests methods.
"""
def test_register_module(self):
"""
Tests :func:`foundations.trace.register_module` definition.
"""
registered_modules = foundations.trace.REGISTERED_MODULES
foundations.trace.REGISTERED_MODULES = set()
module = foundations.tests.tests_foundations.resources.dummy
self.assertTrue(foundations.trace.register_module(module))
self.assertIn(module, foundations.trace.REGISTERED_MODULES)
self.assertTrue(foundations.trace.register_module())
self.assertIn(sys.modules[__name__], foundations.trace.REGISTERED_MODULES)
foundations.trace.REGISTERED_MODULES = foundations.trace.REGISTERED_MODULES
|
class TestRegisterModule(unittest.TestCase):
'''
Defines :func:`foundations.trace.register_module` definition units tests methods.
'''
def test_register_module(self):
'''
Tests :func:`foundations.trace.register_module` definition.
'''
pass
| 2 | 2 | 16 | 4 | 9 | 3 | 1 | 0.6 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 21 | 5 | 10 | 4 | 8 | 6 | 10 | 4 | 8 | 1 | 2 | 0 | 1 |
142,322 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestIsUntracable
|
class TestIsUntracable(unittest.TestCase):
"""
Defines :func:`foundations.trace.is_untracable` definition units tests methods.
"""
def test_is_untracable(self):
"""
Tests :func:`foundations.trace.is_untracable` definition.
"""
object = foundations.trace.untracable(lambda: None)
self.assertTrue(foundations.trace.is_untracable(object))
self.assertFalse(foundations.trace.is_untracable(lambda: None))
|
class TestIsUntracable(unittest.TestCase):
'''
Defines :func:`foundations.trace.is_untracable` definition units tests methods.
'''
def test_is_untracable(self):
'''
Tests :func:`foundations.trace.is_untracable` definition.
'''
pass
| 2 | 2 | 8 | 1 | 4 | 3 | 1 | 1.2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 13 | 2 | 5 | 3 | 3 | 6 | 5 | 3 | 3 | 1 | 2 | 0 | 1 |
142,323 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestIsTraced
|
class TestIsTraced(unittest.TestCase):
"""
Defines :func:`foundations.trace.is_traced` definition units tests methods.
"""
def test_is_traced(self):
"""
Tests :func:`foundations.trace.is_traced` definition.
"""
object = lambda: None
foundations.trace.set_traced(object)
self.assertTrue(foundations.trace.is_traced(object))
self.assertFalse(foundations.trace.is_traced(lambda: None))
|
class TestIsTraced(unittest.TestCase):
'''
Defines :func:`foundations.trace.is_traced` definition units tests methods.
'''
def test_is_traced(self):
'''
Tests :func:`foundations.trace.is_traced` definition.
'''
pass
| 2 | 2 | 9 | 1 | 5 | 3 | 1 | 1 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 14 | 2 | 6 | 3 | 4 | 6 | 6 | 3 | 4 | 1 | 2 | 0 | 1 |
142,324 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestIsStaticMethod
|
class TestIsStaticMethod(unittest.TestCase):
"""
Defines :func:`foundations.trace.is_static_method` definition units tests methods.
"""
def test_is_static_method(self):
"""
Tests :func:`foundations.trace.is_static_method` definition.
"""
self.assertTrue(foundations.trace.is_static_method(Dummy.static_method))
self.assertFalse(foundations.trace.is_static_method(Dummy.public_method))
|
class TestIsStaticMethod(unittest.TestCase):
'''
Defines :func:`foundations.trace.is_static_method` definition units tests methods.
'''
def test_is_static_method(self):
'''
Tests :func:`foundations.trace.is_static_method` definition.
'''
pass
| 2 | 2 | 7 | 1 | 3 | 3 | 1 | 1.5 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 12 | 2 | 4 | 2 | 2 | 6 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
142,325 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestIsReadOnly
|
class TestIsReadOnly(unittest.TestCase):
"""
Defines :func:`foundations.trace.is_read_only` definition units tests methods.
"""
def test_is_read_only(self):
"""
Tests :func:`foundations.trace.is_read_only` definition.
"""
self.assertTrue(foundations.trace.is_read_only(unicode))
self.assertTrue(foundations.trace.is_read_only(""))
self.assertTrue(foundations.trace.is_read_only(dict))
self.assertTrue(foundations.trace.is_read_only(dict()))
class Writable(object):
pass
self.assertFalse(foundations.trace.is_read_only(Writable))
self.assertFalse(foundations.trace.is_read_only(Writable()))
|
class TestIsReadOnly(unittest.TestCase):
'''
Defines :func:`foundations.trace.is_read_only` definition units tests methods.
'''
def test_is_read_only(self):
'''
Tests :func:`foundations.trace.is_read_only` definition.
'''
pass
class Writable(object):
| 3 | 2 | 15 | 3 | 9 | 3 | 1 | 0.6 | 1 | 2 | 1 | 0 | 1 | 0 | 1 | 73 | 20 | 4 | 10 | 3 | 7 | 6 | 10 | 3 | 7 | 1 | 2 | 0 | 1 |
142,326 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestIsClassMethod
|
class TestIsClassMethod(unittest.TestCase):
"""
Defines :func:`foundations.trace.is_class_method` definition units tests methods.
"""
def test_is_class_method(self):
"""
Tests :func:`foundations.trace.is_class_method` definition.
"""
for key, value in {Dummy.class_method: True, Dummy.public_method: False,
Dummy.static_method: False}.iteritems():
self.assertEqual(foundations.trace.is_class_method(key), value)
|
class TestIsClassMethod(unittest.TestCase):
'''
Defines :func:`foundations.trace.is_class_method` definition units tests methods.
'''
def test_is_class_method(self):
'''
Tests :func:`foundations.trace.is_class_method` definition.
'''
pass
| 2 | 2 | 8 | 1 | 4 | 3 | 2 | 1.2 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 13 | 2 | 5 | 3 | 3 | 6 | 4 | 3 | 2 | 2 | 2 | 1 | 2 |
142,327 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestIsBaseTraced
|
class TestIsBaseTraced(unittest.TestCase):
"""
Defines :func:`foundations.trace.is_base_traced` definition units tests methods.
"""
def test_is_base_traced(self):
"""
Tests :func:`foundations.trace.is_base_traced` definition.
"""
class Dummy2(Dummy):
pass
self.assertFalse(foundations.trace.is_base_traced(Dummy2))
foundations.trace.trace_class(Dummy)
self.assertTrue(foundations.trace.is_base_traced(Dummy2))
foundations.trace.untrace_class(Dummy)
|
class TestIsBaseTraced(unittest.TestCase):
'''
Defines :func:`foundations.trace.is_base_traced` definition units tests methods.
'''
def test_is_base_traced(self):
'''
Tests :func:`foundations.trace.is_base_traced` definition.
'''
pass
class Dummy2(Dummy):
| 3 | 2 | 15 | 5 | 7 | 3 | 1 | 0.75 | 1 | 2 | 2 | 0 | 1 | 0 | 1 | 73 | 20 | 6 | 8 | 3 | 5 | 6 | 8 | 3 | 5 | 1 | 2 | 0 | 1 |
142,328 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestInstallTracer
|
class TestInstallTracer(unittest.TestCase):
"""
Defines :func:`foundations.trace.install_tracer` definition units tests methods.
"""
def test_install_tracer(self):
"""
Tests :func:`foundations.trace.install_tracer` definition.
"""
registered_modules = foundations.trace.REGISTERED_MODULES
foundations.trace.REGISTERED_MODULES = set()
module = foundations.tests.tests_foundations.resources.dummy
foundations.trace.register_module(module)
self.assertTrue(foundations.trace.install_tracer(pattern=r"Nemo"))
self.assertFalse(foundations.trace.is_traced(module))
self.assertTrue(foundations.trace.install_tracer(pattern=r"\w+ummy"))
self.assertTrue(foundations.trace.is_traced(module))
foundations.trace.uninstall_tracer()
foundations.trace.REGISTERED_MODULES = foundations.trace.REGISTERED_MODULES
|
class TestInstallTracer(unittest.TestCase):
'''
Defines :func:`foundations.trace.install_tracer` definition units tests methods.
'''
def test_install_tracer(self):
'''
Tests :func:`foundations.trace.install_tracer` definition.
'''
pass
| 2 | 2 | 17 | 3 | 11 | 3 | 1 | 0.5 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 22 | 4 | 12 | 4 | 10 | 6 | 12 | 4 | 10 | 1 | 2 | 0 | 1 |
142,329 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestGetTracerHook
|
class TestGetTracerHook(unittest.TestCase):
"""
Defines :func:`foundations.trace.get_tracer_hook` definition units tests methods.
"""
def test_get_tracer_hook(self):
"""
Tests :func:`foundations.trace.get_tracer_hook` definition.
"""
object, hook = lambda: None, ""
foundations.trace.set_tracer_hook(object, hook),
self.assertEqual(foundations.trace.get_tracer_hook(object), hook)
|
class TestGetTracerHook(unittest.TestCase):
'''
Defines :func:`foundations.trace.get_tracer_hook` definition units tests methods.
'''
def test_get_tracer_hook(self):
'''
Tests :func:`foundations.trace.get_tracer_hook` definition.
'''
pass
| 2 | 2 | 8 | 1 | 4 | 3 | 1 | 1.2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 13 | 2 | 5 | 3 | 3 | 6 | 5 | 3 | 3 | 1 | 2 | 0 | 1 |
142,330 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestGetTraceName
|
class TestGetTraceName(unittest.TestCase):
"""
Defines :func:`foundations.trace.get_trace_name` definition units tests methods.
"""
def test_get_trace_name(self):
"""
Tests :func:`foundations.trace.get_trace_name` definition.
"""
self.assertEqual(foundations.trace.get_trace_name(dummy1),
"foundations.tests.tests_foundations.resources.dummy.dummy1")
self.assertEqual(foundations.trace.get_trace_name(Dummy.public_method),
"foundations.tests.tests_foundations.resources.dummy.Dummy.public_method")
self.assertEqual(foundations.trace.get_trace_name(Dummy._Dummy__private_method),
"foundations.tests.tests_foundations.resources.dummy.Dummy.__private_method")
self.assertEqual(foundations.trace.get_trace_name(Dummy.attribute),
"foundations.tests.tests_foundations.resources.dummy.Dummy.attribute")
|
class TestGetTraceName(unittest.TestCase):
'''
Defines :func:`foundations.trace.get_trace_name` definition units tests methods.
'''
def test_get_trace_name(self):
'''
Tests :func:`foundations.trace.get_trace_name` definition.
'''
pass
| 2 | 2 | 13 | 1 | 9 | 3 | 1 | 0.6 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 18 | 2 | 10 | 2 | 8 | 6 | 6 | 2 | 4 | 1 | 2 | 0 | 1 |
142,331 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestGetObjectName
|
class TestGetObjectName(unittest.TestCase):
"""
Defines :func:`foundations.trace.get_object_name` definition units tests methods.
"""
def test_get_object_name(self):
"""
Tests :func:`foundations.trace.get_object_name` definition.
"""
self.assertEqual(foundations.trace.get_object_name(Dummy.attribute), "attribute")
self.assertEqual(foundations.trace.get_object_name(foundations.trace.get_object_name),
foundations.trace.get_object_name.__name__)
self.assertEqual(foundations.trace.get_object_name(Dummy), "Dummy")
self.assertEqual(foundations.trace.get_object_name(Dummy()), "Dummy")
|
class TestGetObjectName(unittest.TestCase):
'''
Defines :func:`foundations.trace.get_object_name` definition units tests methods.
'''
def test_get_object_name(self):
'''
Tests :func:`foundations.trace.get_object_name` definition.
'''
pass
| 2 | 2 | 10 | 1 | 6 | 3 | 1 | 0.86 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 7 | 2 | 5 | 6 | 6 | 2 | 4 | 1 | 2 | 0 | 1 |
142,332 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestGetMethodName
|
class TestGetMethodName(unittest.TestCase):
"""
Defines :func:`foundations.trace.get_method_name` definition units tests methods.
"""
def test_get_method_name(self):
"""
Tests :func:`foundations.trace.get_method_name` definition.
"""
self.assertEqual(foundations.trace.get_method_name(Dummy.public_method), "public_method")
self.assertEqual(foundations.trace.get_method_name(Dummy._Dummy__private_method), "_Dummy__private_method")
|
class TestGetMethodName(unittest.TestCase):
'''
Defines :func:`foundations.trace.get_method_name` definition units tests methods.
'''
def test_get_method_name(self):
'''
Tests :func:`foundations.trace.get_method_name` definition.
'''
pass
| 2 | 2 | 7 | 1 | 3 | 3 | 1 | 1.5 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 12 | 2 | 4 | 2 | 2 | 6 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
142,333 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestFormatArgument
|
class TestFormatArgument(unittest.TestCase):
"""
Defines :func:`foundations.trace.format_argument` definition units tests methods.
"""
def test_format_argument(self):
"""
Tests :func:`foundations.trace.format_argument` definition.
"""
self.assertEqual(foundations.trace.format_argument(("x", range(3))), "x=[0, 1, 2]")
|
class TestFormatArgument(unittest.TestCase):
'''
Defines :func:`foundations.trace.format_argument` definition units tests methods.
'''
def test_format_argument(self):
'''
Tests :func:`foundations.trace.format_argument` definition.
'''
pass
| 2 | 2 | 6 | 1 | 2 | 3 | 1 | 2 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 11 | 2 | 3 | 2 | 1 | 6 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
142,334 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestEvaluateTraceRequest
|
class TestEvaluateTraceRequest(unittest.TestCase):
"""
Defines :func:`foundations.trace.evaluate_trace_request` definition units tests methods.
"""
def test_evaluate_trace_request(self):
"""
Tests :func:`foundations.trace.evaluate_trace_request` definition.
"""
module = foundations.tests.tests_foundations.resources.dummy
self.assertTrue(foundations.trace.evaluate_trace_request(
"'foundations.tests.tests_foundations.resources.dummy'"))
self.assertTrue(foundations.trace.is_traced(module))
foundations.trace.untrace_module(module)
self.assertTrue(foundations.trace.evaluate_trace_request(
"['foundations.tests.tests_foundations.resources.dummy']"))
self.assertTrue(foundations.trace.is_traced(module))
foundations.trace.untrace_module(module)
self.assertTrue(foundations.trace.evaluate_trace_request(
"{'foundations.tests.tests_foundations.resources.dummy' : (r'.*', 0)}"))
self.assertTrue(foundations.trace.is_traced(module))
foundations.trace.untrace_module(module)
self.assertTrue(foundations.trace.evaluate_trace_request(
"{'foundations.tests.tests_foundations.resources.dummy' : (r'^(?:(?!dummy1).)*$', 0)}"))
self.assertTrue(foundations.trace.is_traced(module))
self.assertFalse(foundations.trace.is_traced(getattr(module, "dummy1")))
foundations.trace.untrace_module(module)
|
class TestEvaluateTraceRequest(unittest.TestCase):
'''
Defines :func:`foundations.trace.evaluate_trace_request` definition units tests methods.
'''
def test_evaluate_trace_request(self):
'''
Tests :func:`foundations.trace.evaluate_trace_request` definition.
'''
pass
| 2 | 2 | 31 | 9 | 19 | 3 | 1 | 0.3 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 36 | 10 | 20 | 3 | 18 | 6 | 16 | 3 | 14 | 1 | 2 | 0 | 1 |
142,335 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_tcp_server.py
|
foundations.tests.tests_foundations.tests_tcp_server.TestTCPServer
|
class TestTCPServer(unittest.TestCase):
"""
Defines :class:`foundations.tcp_server.TCPServer` class units tests methods.
"""
def test_required_attributes(self):
"""
Tests presence of required attributes.
"""
required_attributes = ("address", "port", "handler", "online")
for attribute in required_attributes:
self.assertIn(attribute, dir(TCPServer))
def test_required_methods(self):
"""
Tests presence of required methods.
"""
required_methods = ("start", "stop")
for method in required_methods:
self.assertIn(method, dir(TCPServer))
def test_start(self):
"""
Tests :meth:`foundations.tcp_server.TCPServer.start` method.
"""
tcp_server = TCPServer("127.0.0.1", 16384)
self.assertTrue(tcp_server.start())
self.assertEqual(tcp_server.online, True)
tcp_server.stop()
def test_stop(self):
"""
Tests :meth:`foundations.tcp_server.TCPServer.stop` method.
"""
tcp_server = TCPServer("127.0.0.1", 16384)
tcp_server.start()
self.assertTrue(tcp_server.stop())
self.assertEqual(tcp_server.online, False)
|
class TestTCPServer(unittest.TestCase):
'''
Defines :class:`foundations.tcp_server.TCPServer` class units tests methods.
'''
def test_required_attributes(self):
'''
Tests presence of required attributes.
'''
pass
def test_required_methods(self):
'''
Tests presence of required methods.
'''
pass
def test_start(self):
'''
Tests :meth:`foundations.tcp_server.TCPServer.start` method.
'''
pass
def test_stop(self):
'''
Tests :meth:`foundations.tcp_server.TCPServer.stop` method.
'''
pass
| 5 | 5 | 9 | 2 | 5 | 3 | 2 | 0.79 | 1 | 1 | 1 | 0 | 4 | 0 | 4 | 76 | 44 | 10 | 19 | 11 | 14 | 15 | 19 | 11 | 14 | 2 | 2 | 1 | 6 |
142,336 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_tcp_server.py
|
foundations.tests.tests_foundations.tests_tcp_server.TestEchoRequestsHandler
|
class TestEchoRequestsHandler(unittest.TestCase):
"""
Defines :class:`foundations.tcp_server.EchoRequestsHandler` class units tests methods.
"""
def test_required_methods(self):
"""
Tests presence of required methods.
"""
required_methods = ("handle",)
for method in required_methods:
self.assertIn(method, dir(EchoRequestsHandler))
def test_handle(self):
"""
Tests :meth:`foundations.tcp_server.TCPServer.handle` method.
"""
tcp_server = TCPServer("127.0.0.1", 16384)
tcp_server.start()
connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection.connect(("127.0.0.1", 16384))
data = "Hello World!"
connection.send(data)
self.assertEqual(connection.recv(1024), data)
connection.close()
tcp_server.stop()
|
class TestEchoRequestsHandler(unittest.TestCase):
'''
Defines :class:`foundations.tcp_server.EchoRequestsHandler` class units tests methods.
'''
def test_required_methods(self):
'''
Tests presence of required methods.
'''
pass
def test_handle(self):
'''
Tests :meth:`foundations.tcp_server.TCPServer.handle` method.
'''
pass
| 3 | 3 | 12 | 2 | 7 | 3 | 2 | 0.6 | 1 | 3 | 2 | 0 | 2 | 0 | 2 | 74 | 29 | 5 | 15 | 8 | 12 | 9 | 15 | 8 | 12 | 2 | 2 | 1 | 3 |
142,337 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_strings.py
|
foundations.tests.tests_foundations.tests_strings.TestToString
|
class TestToString(unittest.TestCase):
"""
Defines :func:`foundations.strings.to_string` definition units tests methods.
"""
def test_to_string(self):
"""
Tests :func:`foundations.strings.to_string` definition.
"""
self.assertIsInstance(foundations.strings.to_string(str("myData")), unicode)
self.assertIsInstance(foundations.strings.to_string(u"myData"), unicode)
self.assertIsInstance(foundations.strings.to_string(0), unicode)
self.assertIsInstance(foundations.strings.to_string(None), unicode)
self.assertIsInstance(foundations.strings.to_string(True), unicode)
|
class TestToString(unittest.TestCase):
'''
Defines :func:`foundations.strings.to_string` definition units tests methods.
'''
def test_to_string(self):
'''
Tests :func:`foundations.strings.to_string` definition.
'''
pass
| 2 | 2 | 10 | 1 | 6 | 3 | 1 | 0.86 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 7 | 2 | 5 | 6 | 7 | 2 | 5 | 1 | 2 | 0 | 1 |
142,338 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_common.py
|
foundations.tests.tests_foundations.tests_common.TestDependencyResolver
|
class TestDependencyResolver(unittest.TestCase):
"""
Defines :func:`foundations.common.dependency_resolver` definition units tests methods.
"""
def test_dependency_resolver(self):
"""
Tests :func:`foundations.common.dependency_resolver` definition.
"""
dependencies = {"c": ("a", "b"),
"d": ("c",),
"f": ("b",)}
self.assertEquals(foundations.common.dependency_resolver(dependencies),
[set(["a", "b"]), set(["c", "f"]), set(["d"])])
|
class TestDependencyResolver(unittest.TestCase):
'''
Defines :func:`foundations.common.dependency_resolver` definition units tests methods.
'''
def test_dependency_resolver(self):
'''
Tests :func:`foundations.common.dependency_resolver` definition.
'''
pass
| 2 | 2 | 11 | 2 | 6 | 3 | 1 | 0.86 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 16 | 3 | 7 | 3 | 5 | 6 | 4 | 3 | 2 | 1 | 2 | 0 | 1 |
142,339 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_strings.py
|
foundations.tests.tests_foundations.tests_strings.TestToForwardSlashes
|
class TestToForwardSlashes(unittest.TestCase):
"""
Defines :func:`foundations.strings.to_forward_slashes` definition units tests methods.
"""
def test_to_forward_slashes(self):
"""
Tests :func:`foundations.strings.to_forward_slashes` definition.
"""
self.assertIsInstance(foundations.strings.to_forward_slashes("To\\Forward\\Slashes\\Test\\Case"), unicode)
self.assertEqual(foundations.strings.to_forward_slashes("To\\Forward\\Slashes\\Test\\Case"),
"To/Forward/Slashes/Test/Case")
self.assertEqual(foundations.strings.to_forward_slashes(
"\\Users/JohnDoe\\Documents"), "/Users/JohnDoe/Documents")
|
class TestToForwardSlashes(unittest.TestCase):
'''
Defines :func:`foundations.strings.to_forward_slashes` definition units tests methods.
'''
def test_to_forward_slashes(self):
'''
Tests :func:`foundations.strings.to_forward_slashes` definition.
'''
pass
| 2 | 2 | 10 | 1 | 6 | 3 | 1 | 0.86 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 7 | 2 | 5 | 6 | 5 | 2 | 3 | 1 | 2 | 0 | 1 |
142,340 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_strings.py
|
foundations.tests.tests_foundations.tests_strings.TestToBackwardSlashes
|
class TestToBackwardSlashes(unittest.TestCase):
"""
Defines :func:`foundations.strings.to_backward_slashes` definition units tests methods.
"""
def test_to_backward_slashes(self):
"""
Tests :func:`foundations.strings.to_backward_slashes` definition.
"""
self.assertIsInstance(foundations.strings.to_backward_slashes("\\Users\\JohnDoe\\Documents"), unicode)
self.assertEqual(foundations.strings.to_backward_slashes("To/Forward/Slashes/Test/Case"),
"To\\Forward\\Slashes\\Test\\Case")
self.assertEqual(foundations.strings.to_backward_slashes(
"/Users/JohnDoe/Documents"), "\\Users\\JohnDoe\\Documents")
|
class TestToBackwardSlashes(unittest.TestCase):
'''
Defines :func:`foundations.strings.to_backward_slashes` definition units tests methods.
'''
def test_to_backward_slashes(self):
'''
Tests :func:`foundations.strings.to_backward_slashes` definition.
'''
pass
| 2 | 2 | 10 | 1 | 6 | 3 | 1 | 0.86 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 7 | 2 | 5 | 6 | 5 | 2 | 3 | 1 | 2 | 0 | 1 |
142,341 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_strings.py
|
foundations.tests.tests_foundations.tests_strings.TestReplace
|
class TestReplace(unittest.TestCase):
"""
Defines :func:`foundations.strings.replace` definition units tests methods.
"""
def test_replace(self):
"""
Tests :func:`foundations.strings.replace` definition.
"""
self.assertIsInstance(foundations.strings.replace("To@Forward|Slashes@Test|Case", {}), unicode)
self.assertEqual(foundations.strings.replace("To@Forward|Slashes@Test|Case", {"@": "|", "|": ":"}),
"To:Forward:Slashes:Test:Case")
self.assertEqual(foundations.strings.replace("To@Forward@Slashes@Test@Case", {"@": "|", "|": "@"}),
"To@Forward@Slashes@Test@Case")
|
class TestReplace(unittest.TestCase):
'''
Defines :func:`foundations.strings.replace` definition units tests methods.
'''
def test_replace(self):
'''
Tests :func:`foundations.strings.replace` definition.
'''
pass
| 2 | 2 | 10 | 1 | 6 | 3 | 1 | 0.86 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 7 | 2 | 5 | 6 | 5 | 2 | 3 | 1 | 2 | 0 | 1 |
142,342 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_strings.py
|
foundations.tests.tests_foundations.tests_strings.TestRemoveStrip
|
class TestRemoveStrip(unittest.TestCase):
"""
Defines :func:`foundations.strings.remove_strip` definition units tests methods.
"""
def test_remove_strip(self):
"""
Tests :func:`foundations.strings.remove_strip` definition.
"""
self.assertIsInstance(foundations.strings.remove_strip("John Doe", "John"), unicode)
self.assertEqual(foundations.strings.remove_strip("John Doe", "John"), "Doe")
self.assertEqual(foundations.strings.remove_strip("John Doe", "Doe"), "John")
|
class TestRemoveStrip(unittest.TestCase):
'''
Defines :func:`foundations.strings.remove_strip` definition units tests methods.
'''
def test_remove_strip(self):
'''
Tests :func:`foundations.strings.remove_strip` definition.
'''
pass
| 2 | 2 | 8 | 1 | 4 | 3 | 1 | 1.2 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 13 | 2 | 5 | 2 | 3 | 6 | 5 | 2 | 3 | 1 | 2 | 0 | 1 |
142,343 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_strings.py
|
foundations.tests.tests_foundations.tests_strings.TestIsWebsite
|
class TestIsWebsite(unittest.TestCase):
"""
Defines :func:`foundations.strings.is_website` definition units tests methods.
"""
def test_is_website(self):
"""
Tests :func:`foundations.strings.is_website` definition.
"""
self.assertIsInstance(foundations.strings.is_website("http://domain.com"), bool)
self.assertTrue(foundations.strings.is_website("http://www.domain.com"))
self.assertTrue(foundations.strings.is_website("http://domain.com"))
self.assertTrue(foundations.strings.is_website("https://domain.com"))
self.assertTrue(foundations.strings.is_website("ftp://domain.com"))
self.assertTrue(foundations.strings.is_website("http://domain.subdomain.com"))
self.assertFalse(foundations.strings.is_website(".com"))
self.assertFalse(foundations.strings.is_website("domain.com"))
|
class TestIsWebsite(unittest.TestCase):
'''
Defines :func:`foundations.strings.is_website` definition units tests methods.
'''
def test_is_website(self):
'''
Tests :func:`foundations.strings.is_website` definition.
'''
pass
| 2 | 2 | 13 | 1 | 9 | 3 | 1 | 0.6 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 18 | 2 | 10 | 2 | 8 | 6 | 10 | 2 | 8 | 1 | 2 | 0 | 1 |
142,344 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_strings.py
|
foundations.tests.tests_foundations.tests_strings.TestIsEmail
|
class TestIsEmail(unittest.TestCase):
"""
Defines :func:`foundations.strings.is_email` definition units tests methods.
"""
def test_is_email(self):
"""
Tests :func:`foundations.strings.is_email` definition.
"""
self.assertIsInstance(foundations.strings.is_email("john.doe@domain.com"), bool)
self.assertTrue(foundations.strings.is_email("john.doe@domain.com"))
self.assertTrue(foundations.strings.is_email("john.doe@domain.server.department.company.com"))
self.assertFalse(foundations.strings.is_email("john.doe"))
self.assertFalse(foundations.strings.is_email("john.doe@domain"))
|
class TestIsEmail(unittest.TestCase):
'''
Defines :func:`foundations.strings.is_email` definition units tests methods.
'''
def test_is_email(self):
'''
Tests :func:`foundations.strings.is_email` definition.
'''
pass
| 2 | 2 | 10 | 1 | 6 | 3 | 1 | 0.86 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 73 | 15 | 2 | 7 | 2 | 5 | 6 | 7 | 2 | 5 | 1 | 2 | 0 | 1 |
142,345 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestTraceFunction
|
class TestTraceFunction(unittest.TestCase):
"""
Defines :func:`foundations.trace.trace_function` definition units tests functions.
"""
def test_trace_function(self):
"""
This function tests :func:`foundations.trace.trace_function` definition.
"""
module = foundations.tests.tests_foundations.resources.dummy
for name, function in TRACABLE_DEFINITIONS.iteritems():
self.assertFalse(foundations.trace.is_traced(function))
self.assertTrue(foundations.trace.trace_function(module, function))
self.assertTrue(foundations.trace.is_traced(getattr(module, name)))
foundations.trace.untrace_function(module, getattr(module, name))
|
class TestTraceFunction(unittest.TestCase):
'''
Defines :func:`foundations.trace.trace_function` definition units tests functions.
'''
def test_trace_function(self):
'''
This function tests :func:`foundations.trace.trace_function` definition.
'''
pass
| 2 | 2 | 11 | 1 | 7 | 3 | 2 | 0.75 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 16 | 2 | 8 | 4 | 6 | 6 | 8 | 4 | 6 | 2 | 2 | 1 | 2 |
142,346 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestTraceMethod
|
class TestTraceMethod(unittest.TestCase):
"""
Defines :func:`foundations.trace.trace_method` definition units tests methods.
"""
def test_trace_method(self):
"""
Tests :func:`foundations.trace.trace_method` definition.
"""
for name, method in TRACABLE_METHODS.iteritems():
self.assertFalse(foundations.trace.is_traced(method))
self.assertTrue(foundations.trace.trace_method(Dummy, method))
self.assertTrue(foundations.trace.is_traced(getattr(Dummy, name)))
foundations.trace.untrace_method(Dummy, getattr(Dummy, name))
for name, method in UNTRACABLE_METHODS.iteritems():
self.assertFalse(foundations.trace.is_traced(method))
self.assertFalse(foundations.trace.trace_method(Dummy, getattr(Dummy, name)))
self.assertFalse(foundations.trace.is_traced(getattr(Dummy, name)))
|
class TestTraceMethod(unittest.TestCase):
'''
Defines :func:`foundations.trace.trace_method` definition units tests methods.
'''
def test_trace_method(self):
'''
Tests :func:`foundations.trace.trace_method` definition.
'''
pass
| 2 | 2 | 15 | 2 | 10 | 3 | 3 | 0.55 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 73 | 20 | 3 | 11 | 3 | 9 | 6 | 11 | 3 | 9 | 3 | 2 | 1 | 3 |
142,347 |
KelSolaar/Foundations
|
KelSolaar_Foundations/foundations/tests/tests_foundations/tests_trace.py
|
foundations.tests.tests_foundations.tests_trace.TestTraceModule
|
class TestTraceModule(unittest.TestCase):
"""
Defines :func:`foundations.trace.trace_module` definition units tests methods.
"""
def test_trace_module(self):
"""
Tests :func:`foundations.trace.trace_module` definition.
"""
module = foundations.tests.tests_foundations.resources.dummy
self.assertTrue(foundations.trace.trace_module(module))
self.assertTrue(foundations.trace.is_traced(module))
for name, definition in TRACABLE_DEFINITIONS.iteritems():
self.assertTrue(foundations.trace.is_traced(getattr(module, name)))
for name, definition in UNTRACABLE_DEFINITIONS.iteritems():
self.assertFalse(foundations.trace.is_traced(getattr(module, name)))
self.assertIn(module, foundations.trace.REGISTERED_MODULES)
foundations.trace.untrace_module(module)
self.assertTrue(foundations.trace.trace_module(module, pattern=r"^dummy1$"))
self.assertTrue(foundations.trace.is_traced(getattr(module, dummy1.__name__)))
self.assertFalse(foundations.trace.is_traced(getattr(module, dummy2.__name__)))
foundations.trace.untrace_module(module)
self.assertTrue(foundations.trace.trace_module(module, pattern=r"^(?:(?!dummy1).)*$"))
self.assertFalse(foundations.trace.is_traced(getattr(module, dummy1.__name__)))
self.assertTrue(foundations.trace.is_traced(getattr(module, dummy3.__name__)))
foundations.trace.untrace_module(module)
|
class TestTraceModule(unittest.TestCase):
'''
Defines :func:`foundations.trace.trace_module` definition units tests methods.
'''
def test_trace_module(self):
'''
Tests :func:`foundations.trace.trace_module` definition.
'''
pass
| 2 | 2 | 30 | 9 | 18 | 3 | 3 | 0.32 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 35 | 10 | 19 | 4 | 17 | 6 | 19 | 4 | 17 | 3 | 2 | 1 | 3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.