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
1,600
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/exceptions.py
membersuite_api_client.exceptions.NotAnObjectQuery
class NotAnObjectQuery(MemberSuiteAPIError): pass
class NotAnObjectQuery(MemberSuiteAPIError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
4
0
0
1,601
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/exceptions.py
membersuite_api_client.exceptions.NoResultsError
class NoResultsError(MemberSuiteAPIError): pass
class NoResultsError(MemberSuiteAPIError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
4
0
0
1,602
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/exceptions.py
membersuite_api_client.exceptions.MemberSuiteAPIError
class MemberSuiteAPIError(Exception): def __init__(self, result): self.result = result self.exception_type = self.__class__.__name__ def __str__(self): concierge_error = self.get_concierge_error() return "<{exception_type} ConciergeError: {concierge_error}>".format( exception_type=self.exception_type, concierge_error=concierge_error) def get_concierge_error(self): try: return (self.result["body"][self.result_type] ["Errors"]["ConciergeError"]) except KeyError: return (self.result["Errors"])
class MemberSuiteAPIError(Exception): def __init__(self, result): pass def __str__(self): pass def get_concierge_error(self): pass
4
0
5
0
5
0
1
0
1
1
0
5
3
2
3
13
18
3
15
7
11
0
12
7
8
2
3
1
4
1,603
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/exceptions.py
membersuite_api_client.exceptions.LogoutError
class LogoutError(MemberSuiteAPIError): pass
class LogoutError(MemberSuiteAPIError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
4
0
0
1,604
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/exceptions.py
membersuite_api_client.exceptions.LoginToPortalError
class LoginToPortalError(MemberSuiteAPIError): pass
class LoginToPortalError(MemberSuiteAPIError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
4
0
0
1,605
AASHE/python-membersuite-api-client
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_utils.py
membersuite_api_client.tests.test_utils.SubmitMSQLQueryTestCase
class SubmitMSQLQueryTestCase(unittest.TestCase): @classmethod def setUpClass(cls): client.request_session() def test_class_familiar_to_factory(self): individual = submit_msql_object_query( object_query="SELECT OBJECT() FROM INDIVIDUAL", client=client)[0] self.assertIsInstance(individual, Individual) # test_class_not_familiar_to_factory below needs a MemberSuite # object for which at least one instance is available, and which # is not modeled in membersuite_api_client. Don't know of one # of those that's reliably (or even now and then-ly) available, # that's why this test gets skipped. @unittest.skip("Needs data fixture") def test_class_not_familiar_to_factory(self): """Is a base MemberSuiteObject returned when the class is unfamiliar? Test will fail when MemberSuite Task is modeled (and added to membersuite_object_factory.klasses). """ results = submit_msql_object_query( object_query="SELECT OBJECT() FROM ???", client=client) self.assertEqual(type(results[0]), MemberSuiteObject) def test_unpermitted_query(self): with self.assertRaises(ExecuteMSQLError): submit_msql_object_query( object_query="SELECT OBJECT() FROM TermsOfService", client=client) def test_well_formed_but_invalid_msql(self): with self.assertRaises(ExecuteMSQLError): submit_msql_object_query( object_query="SELECT OBJECT() FROM BOB", client=client) def test_query_with_no_results(self): with self.assertRaises(NoResultsError): submit_msql_object_query( object_query=("SELECT OBJECT() FROM INDIVIDUAL " "WHERE LASTNAME = 'bo-o-o-ogus'"), client=client) def test_query_with_multiple_results(self): """Does submit_msql_object_query work with multiple results? NOTE: This test depends on multiple Individuals with LastName of 'User' being available. """ results = submit_msql_object_query( object_query=("SELECT OBJECTS() FROM INDIVIDUAL " "WHERE LASTNAME = 'User'"), client=client) self.assertTrue(len(results))
class SubmitMSQLQueryTestCase(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_class_familiar_to_factory(self): pass @unittest.skip("Needs data fixture") def test_class_not_familiar_to_factory(self): '''Is a base MemberSuiteObject returned when the class is unfamiliar? Test will fail when MemberSuite Task is modeled (and added to membersuite_object_factory.klasses). ''' pass def test_unpermitted_query(self): pass def test_well_formed_but_invalid_msql(self): pass def test_query_with_no_results(self): pass def test_query_with_multiple_results(self): '''Does submit_msql_object_query work with multiple results? NOTE: This test depends on multiple Individuals with LastName of 'User' being available. ''' pass
10
2
6
0
5
1
1
0.35
1
5
4
0
6
0
7
79
60
10
37
13
27
13
21
11
13
1
2
1
7
1,606
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/client.py
membersuite_api_client.client.MembersuiteLoginError
class MembersuiteLoginError(Exception): pass
class MembersuiteLoginError(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
3
1
2
1
1
0
2
1
1
0
3
0
0
1,607
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/client.py
membersuite_api_client.client.ConciergeClient
class ConciergeClient(object): def __init__(self, access_key, secret_key, association_id): """ Initializes Client object by pulling in authentication credentials. Altered to make "request_session" a manual call to facilitate testing. """ self.access_key = access_key self.secret_key = secret_key self.association_id = association_id self.session_id = None self.client = Client('https://soap.membersuite.com/mex') def get_hashed_signature(self, url): """ Process from Membersuite Docs: http://bit.ly/2eSIDxz """ data = "%s%s" % (url, self.association_id) if self.session_id: data = "%s%s" % (data, self.session_id) data_b = bytearray(data, 'utf-8') secret_key = base64.b64decode(self.secret_key) secret_b = bytearray(secret_key) hashed = hmac.new(secret_b, data_b, sha1).digest() return base64.b64encode(hashed).decode("utf-8") def request_session(self): """ Performs initial request to initialize session and get session id necessary to construct all future requests. :return: Session ID to be placed in header of all other requests. """ concierge_request_header = self.construct_concierge_header( url="http://membersuite.com/contracts/IConciergeAPIService/WhoAmI") result = self.client.service.WhoAmI( _soapheaders=[concierge_request_header]) self.session_id = get_session_id(result=result) if not self.session_id: raise MembersuiteLoginError( result["body"]["WhoAmIResult"]["Errors"]) return self.session_id def construct_concierge_header(self, url): """ Constructs the Concierge Request Header lxml object to be used as the '_soapheaders' argument for WSDL methods. """ concierge_request_header = ( etree.Element( etree.QName(XHTML_NAMESPACE, "ConciergeRequestHeader"), nsmap={'sch': XHTML_NAMESPACE})) if self.session_id: session = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "SessionId"))) session.text = self.session_id access_key = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "AccessKeyId"))) access_key.text = self.access_key association_id = (etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "AssociationId"))) association_id.text = self.association_id signature = ( etree.SubElement(concierge_request_header, etree.QName(XHTML_NAMESPACE, "Signature"))) signature.text = self.get_hashed_signature(url=url) return concierge_request_header def execute_object_query(self, object_query, start_record=0, limit_to=400): concierge_request_header = self.construct_concierge_header( url="http://membersuite.com/contracts/" "IConciergeAPIService/ExecuteMSQL") result = self.client.service.ExecuteMSQL( _soapheaders=[concierge_request_header], msqlStatement=object_query, startRecord=start_record, maximumNumberOfRecordsToReturn=limit_to, ) return result
class ConciergeClient(object): def __init__(self, access_key, secret_key, association_id): ''' Initializes Client object by pulling in authentication credentials. Altered to make "request_session" a manual call to facilitate testing. ''' pass def get_hashed_signature(self, url): ''' Process from Membersuite Docs: http://bit.ly/2eSIDxz ''' pass def request_session(self): ''' Performs initial request to initialize session and get session id necessary to construct all future requests. :return: Session ID to be placed in header of all other requests. ''' pass def construct_concierge_header(self, url): ''' Constructs the Concierge Request Header lxml object to be used as the '_soapheaders' argument for WSDL methods. ''' pass def execute_object_query(self, object_query, start_record=0, limit_to=400): pass
6
4
17
2
12
3
2
0.26
1
2
1
0
5
5
5
5
92
15
61
26
54
16
39
25
33
2
1
1
8
1,608
AASHE/python-membersuite-api-client
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_security.py
membersuite_api_client.tests.test_security.IndividualTestCase
class IndividualTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = get_new_client() def setUp(self): self.client.request_session() member_portal_user = _login(client=self.client) self.individual_member = member_portal_user.get_individual( client=self.client) def test_is_member_for_member(self): """Does is_member() work for members? """ is_member = self.individual_member.is_member(client=self.client) self.assertTrue(is_member) # test_is_member_for_nonmember() below can't succeed, because it # doesn't know about any non-member to use. Once non-member data # (at least a non-member Organization and a connected Individudal # with Portal Access) is available, push it into the env in # TEST_NON_MEMBER_MS_PORTAL_USER_ID and # TEST_NON_MEMBER_MS_PORTAL_USER_PASS and unskip this test. @unittest.skip("Because it can't succeed") def test_is_member_for_nonmember(self): """Does is_member() work for non-members? """ client = get_new_client() client.request_session() non_member_portal_user = _login(client=client, member=False) individual_non_member = non_member_portal_user.get_individual( client=client) is_member = individual_non_member.is_member(client=client) self.assertFalse(is_member) def test_get_primary_organization(self): """Does get_primary_organization() work? Assumptions: - self.individual_member has as its primary organization, one named MEMBER_ORG_NAME """ organization = self.individual_member.get_primary_organization( client=self.client) self.assertEqual(MEMBER_ORG_NAME, organization.name) def test_get_primary_organization_fails(self): """What happens when get_primary_organization() fails? """ with self.assertRaises(MemberSuiteAPIError): self.individual_member.primary_organization__rtg = "bogus ID" self.individual_member.get_primary_organization( client=self.client)
class IndividualTestCase(unittest.TestCase): @classmethod def setUpClass(cls): pass def setUpClass(cls): pass def test_is_member_for_member(self): '''Does is_member() work for members? ''' pass @unittest.skip("Because it can't succeed") def test_is_member_for_nonmember(self): '''Does is_member() work for non-members? ''' pass def test_get_primary_organization(self): '''Does get_primary_organization() work? Assumptions: - self.individual_member has as its primary organization, one named MEMBER_ORG_NAME ''' pass def test_get_primary_organization_fails(self): '''What happens when get_primary_organization() fails? ''' pass
9
4
8
1
5
2
1
0.55
1
1
1
0
5
1
6
78
60
12
31
17
22
17
24
15
17
1
2
1
6
1,609
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/financial/models.py
membersuite_api_client.financial.models.Product
class Product(MemberSuiteObject): def __init__(self, membersuite_object_data, session_id=None): """Create an Product object from a the Zeep'ed XML representation of a Membersuite Product. """ super(Product, self).__init__( membersuite_object_data=membersuite_object_data) self.name = self.fields['Name']
class Product(MemberSuiteObject): def __init__(self, membersuite_object_data, session_id=None): '''Create an Product object from a the Zeep'ed XML representation of a Membersuite Product. ''' pass
2
1
8
1
4
3
1
0.6
1
1
0
0
1
1
1
3
10
2
5
3
3
3
4
3
2
1
2
0
1
1,610
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/memberships/services.py
membersuite_api_client.memberships.services.MembershipService
class MembershipService(ChunkQueryMixin, object): def __init__(self, client): """ Requires a ConciergeClient to connect with MemberSuite """ self.client = client def get_current_membership_for_org(self, account_num, verbose=False): """Return a current membership for this org, or, None if there is none. """ all_memberships = self.get_memberships_for_org( account_num=account_num, verbose=verbose) # Look for first membership that hasn't expired yet. for membership in all_memberships: if (membership.expiration_date and membership.expiration_date > datetime.datetime.now()): # noqa return membership # noqa return None def get_memberships_for_org(self, account_num, verbose=False): """ Retrieve all memberships associated with an organization, ordered by expiration date. """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership " \ "WHERE Owner = '%s' ORDER BY ExpirationDate" % account_num membership_list = self.get_long_query(query, verbose=verbose) return membership_list or [] def get_all_memberships( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): """ Retrieve all memberships updated since "since_when" Loop over queries of size limit_to until either a non-full queryset is returned, or max_depth is reached (used in tests). Then the recursion collapses to return a single concatenated list. """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Membership" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if parameters: for k, v in parameters.items(): where_params.append((k, "=", v)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) query += " ORDER BY LocalID" # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations membership_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return membership_list or [] def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Membership(sane_obj)
class MembershipService(ChunkQueryMixin, object): def __init__(self, client): ''' Requires a ConciergeClient to connect with MemberSuite ''' pass def get_current_membership_for_org(self, account_num, verbose=False): '''Return a current membership for this org, or, None if there is none. ''' pass def get_memberships_for_org(self, account_num, verbose=False): ''' Retrieve all memberships associated with an organization, ordered by expiration date. ''' pass def get_all_memberships( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): ''' Retrieve all memberships updated since "since_when" Loop over queries of size limit_to until either a non-full queryset is returned, or max_depth is reached (used in tests). Then the recursion collapses to return a single concatenated list. ''' pass def ms_object_to_model(self, ms_obj): ''' Converts an individual result to a Subscription Model ''' pass
6
5
16
2
9
5
3
0.54
2
4
1
0
5
1
5
7
85
16
46
19
38
25
35
17
29
6
2
2
13
1,611
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/exceptions.py
membersuite_api_client.exceptions.ExecuteMSQLError
class ExecuteMSQLError(MemberSuiteAPIError): pass
class ExecuteMSQLError(MemberSuiteAPIError): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
13
2
0
2
1
1
0
2
1
1
0
4
0
0
1,612
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/memberships/models.py
membersuite_api_client.memberships.models.Membership
class Membership(object): def __init__(self, membership): """ Create a Membership model from MemberSuite Membership object """ self.id = membership["ID"] self.owner = membership["Owner"] self.membership_directory_opt_out = \ membership["MembershipDirectoryOptOut"] self.receives_member_benefits = membership["ReceivesMemberBenefits"] self.current_dues_amount = membership["CurrentDuesAmount"] self.expiration_date = membership["ExpirationDate"] self.type = membership["Type"] self.product = membership["Product"] self.last_modified_date = membership["LastModifiedDate"] self.status = membership["Status"] self.join_date = membership["JoinDate"] self.termination_date = membership["TerminationDate"] self.renewal_date = membership["RenewalDate"]
class Membership(object): def __init__(self, membership): ''' Create a Membership model from MemberSuite Membership object ''' pass
2
1
18
1
15
2
1
0.13
1
0
0
0
1
13
1
1
20
2
16
15
14
2
15
15
13
1
1
0
1
1,613
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_organizations.py
membersuite_api_client.tests.test_organizations.OrganizationServiceTestCase
class OrganizationServiceTestCase(BaseTestCase): def setUp(self): super(OrganizationServiceTestCase, self).setUp() self.service = OrganizationService(self.client) def test_get_orgs(self): """ Can we call the get_orgs method and receive an org object back? """ # Fetch just one org by name parameters = { 'Name': "'%s'" % TEST_MS_MEMBER_ORG_NAME, } org_list = self.service.get_orgs(parameters=parameters) self.assertEqual(len(org_list), 1) self.assertEqual(type(org_list[0]), Organization) # @todo - test since_when parameter # Fetch all orgs using get_all=True # But limit to 1 result per iteration, 2 iterations org_list = self.service.get_orgs(limit_to=1, max_calls=2) self.assertEqual(len(org_list), 2) self.assertEqual(type(org_list[0]), Organization) # How does recursion handle the end? # 8055 records at the time of this test org_list = self.service.get_orgs( start_record=8000, limit_to=10) self.assertGreater(len(org_list), 1) self.assertEqual(type(org_list[0]), Organization) def test_get_org_types(self): """ Test fetching all org type objects """ org_type_list = self.service.get_org_types() self.assertTrue(len(org_type_list)) self.assertTrue(type(org_type_list[0]), OrganizationType)
class OrganizationServiceTestCase(BaseTestCase): def setUp(self): pass def test_get_orgs(self): ''' Can we call the get_orgs method and receive an org object back? ''' pass def test_get_org_types(self): ''' Test fetching all org type objects ''' pass
4
2
12
1
7
4
1
0.55
1
5
3
0
3
1
3
76
40
6
22
8
18
12
19
8
15
1
3
0
3
1,614
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/security/models.py
membersuite_api_client.security.models.PortalUser
class PortalUser(MemberSuiteObject): def __init__(self, membersuite_object_data, session_id=None): """Create a PortalUser object from a the Zeep'ed XML representation of a Membersuite PortalUser. """ super(PortalUser, self).__init__( membersuite_object_data=membersuite_object_data) self.email_address = self.fields["EmailAddress"] self.first_name = self.fields["FirstName"] self.last_name = self.fields["LastName"] self.owner = self.fields["Owner"] self.session_id = session_id def __str__(self): return ("<PortalUser: ID: {id}, email_address: {email_address}, " "first_name: {first_name}, last_name: {last_name}, " "owner: {owner}, session_id: {session_id}>".format( id=self.membersuite_id, email_address=self.email_address, first_name=self.first_name, last_name=self.last_name, owner=self.owner, session_id=self.session_id)) def get_individual(self, client): """Return the Individual that owns this PortalUser. """ if not client.session_id: client.request_session() object_query = ("SELECT OBJECT() FROM INDIVIDUAL " "WHERE ID = '{}'".format(self.owner)) result = client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_object_data = (msql_result["ResultValue"] ["SingleObject"]) else: raise ExecuteMSQLError(result=result) return Individual(membersuite_object_data=membersuite_object_data, portal_user=self)
class PortalUser(MemberSuiteObject): def __init__(self, membersuite_object_data, session_id=None): '''Create a PortalUser object from a the Zeep'ed XML representation of a Membersuite PortalUser. ''' pass def __str__(self): pass def get_individual(self, client): '''Return the Individual that owns this PortalUser. ''' pass
4
2
15
3
11
2
2
0.15
1
3
2
0
3
6
3
5
49
11
33
14
29
5
20
13
16
3
2
1
5
1,615
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/organizations/services.py
membersuite_api_client.organizations.services.OrganizationService
class OrganizationService(ChunkQueryMixin, object): def __init__(self, client=None): """ Accepts a ConciergeClient to connect with MemberSuite """ self.client = client or get_new_client(request_session=True) def get_orgs( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): """ Constructs request to MemberSuite to query organization objects. :param int limit_to: number of records to fetch with each chunk :param int max_calls: the maximum number of calls (chunks) to request :param str parameters: additional query parameter dictionary :param date since_when: fetch records modified after this date :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Organization" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if parameters: for k, v in parameters.items(): where_params.append((k, "=", v)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) if verbose: print("Fetching Organizations...") # note, get_long_query is overkill when just looking at # one org, but it still only executes once # `get_long_query` uses `ms_object_to_model` to return Organizations org_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return org_list def ms_object_to_model(self, ms_obj): " Converts an individual result to an Organization Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Organization(sane_obj) def get_org_types(self): """ Retrieves all current OrganizationType objects """ if not self.client.session_id: self.client.request_session() object_query = "SELECT Objects() FROM OrganizationType" result = self.client.execute_object_query(object_query=object_query) msql_result = result['body']["ExecuteMSQLResult"] return self.package_org_types(msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]["MemberSuiteObject"] ) def package_org_types(self, obj_list): """ Loops through MS objects returned from queries to turn them into OrganizationType objects and pack them into a list for later use. """ org_type_list = [] for obj in obj_list: sane_obj = convert_ms_object( obj['Fields']['KeyValueOfstringanyType'] ) org = OrganizationType(sane_obj) org_type_list.append(org) return org_type_list def get_individuals_for_primary_organization(self, organization): """ Returns all Individuals that have `organization` as a primary org. """ if not self.client.session_id: self.client.request_session() object_query = ("SELECT Objects() FROM Individual WHERE " "PrimaryOrganization = '{}'".format( organization.membersuite_account_num)) result = self.client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_objects = (msql_result["ResultValue"] ["ObjectSearchResult"] ["Objects"]) else: raise ExecuteMSQLError(result=result) individuals = [] if membersuite_objects is not None: for membersuite_object in membersuite_objects["MemberSuiteObject"]: individuals.append( Individual(membersuite_object_data=membersuite_object)) return individuals # get_stars_liaison_for_organization doesn't belong here. It should # live in some AASHE-specific place, not in OrganizationService. def get_stars_liaison_for_organization(self, organization): candidates = self.get_individuals_for_primary_organization( organization=organization) # Check for a STARS Primary Contact first: for candidate in candidates: if "StarsPrimaryContact__rt" in candidate.fields: return candidate # No STARS Primary Contact? Try the account's primary contact: for candidate in candidates: if "Primary_Contact__rt" in candidate.fields: return candidate # No primary contact? Try billing contact: for candidate in candidates: if "Billing_Contact__rt" in candidate.fields: return candidate return None
class OrganizationService(ChunkQueryMixin, object): def __init__(self, client=None): ''' Accepts a ConciergeClient to connect with MemberSuite ''' pass def get_orgs( self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): ''' Constructs request to MemberSuite to query organization objects. :param int limit_to: number of records to fetch with each chunk :param int max_calls: the maximum number of calls (chunks) to request :param str parameters: additional query parameter dictionary :param date since_when: fetch records modified after this date :param int start_record: the first record to return from the query :param bool verbose: print progress to stdout :return: a list of Organization objects ''' pass def ms_object_to_model(self, ms_obj): ''' Converts an individual result to an Organization Model ''' pass def get_org_types(self): ''' Retrieves all current OrganizationType objects ''' pass def package_org_types(self, obj_list): ''' Loops through MS objects returned from queries to turn them into OrganizationType objects and pack them into a list for later use. ''' pass def get_individuals_for_primary_organization(self, organization): ''' Returns all Individuals that have `organization` as a primary org. ''' pass def get_stars_liaison_for_organization(self, organization): pass
8
6
20
3
12
5
4
0.4
2
6
4
0
7
1
7
9
149
31
84
33
73
34
64
30
56
7
2
2
25
1,616
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/security/services.py
membersuite_api_client.security.services.UserService
class UserService(ChunkQueryMixin, object): def __init__(self, client): """ Requires a ConciergeClient to connect with MemberSuite """ self.client = client def get_all_users(self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): """ Retrieve all users """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM Individual" user_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return user_list or [] def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return Individual(sane_obj)
class UserService(ChunkQueryMixin, object): def __init__(self, client): ''' Requires a ConciergeClient to connect with MemberSuite ''' pass def get_all_users(self, limit_to=100, max_calls=None, parameters=None, since_when=None, start_record=0, verbose=False): ''' Retrieve all users ''' pass def ms_object_to_model(self, ms_obj): ''' Converts an individual result to a Subscription Model ''' pass
4
3
8
1
5
2
1
0.44
2
1
1
0
3
1
3
5
30
7
16
9
11
7
12
8
8
2
2
1
4
1,617
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/memberships/models.py
membersuite_api_client.memberships.models.MembershipProduct
class MembershipProduct(object): def __init__(self, membership_type): """ Create a MembershipType model from MembershipDuesProduct object """ self.id = membership_type["ID"] self.name = membership_type["Name"]
class MembershipProduct(object): def __init__(self, membership_type): ''' Create a MembershipType model from MembershipDuesProduct object ''' pass
2
1
5
0
3
2
1
0.5
1
0
0
0
1
2
1
1
7
1
4
4
2
2
4
4
2
1
1
0
1
1,618
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/organizations/models.py
membersuite_api_client.organizations.models.OrganizationType
class OrganizationType(object): def __init__(self, org_type): """Create an OrganizationType model from MemberSuite OrganizationType object """ self.id = org_type["ID"] self.name = org_type["Name"]
class OrganizationType(object): def __init__(self, org_type): '''Create an OrganizationType model from MemberSuite OrganizationType object ''' pass
2
1
6
0
3
3
1
0.75
1
0
0
0
1
2
1
1
8
1
4
4
2
3
4
4
2
1
1
0
1
1,619
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/security/models.py
membersuite_api_client.security.models.Individual
class Individual(MemberSuiteObject): def __init__(self, membersuite_object_data, portal_user=None): """Create an Individual object from the Zeep'ed XML representation of a MemberSuite Individual. """ super(Individual, self).__init__( membersuite_object_data=membersuite_object_data) self.email_address = self.fields["EmailAddress"] self.first_name = self.fields["FirstName"] self.last_name = self.fields["LastName"] self.title = self.fields["Title"] self.primary_organization_id = ( self.fields["PrimaryOrganization__rtg"]) self.portal_user = portal_user def __str__(self): return ("<Individual: ID: {id}, email_address: {email_address}, " "first_name: {first_name}, last_name: {last_name}>".format( id=self.membersuite_id, email_address=self.email_address, first_name=self.first_name, last_name=self.last_name)) @property def phone_number(self): numbers = self.fields["PhoneNumbers"]["MemberSuiteObject"] if len(numbers): for key_value_pair in (numbers[0] ["Fields"]["KeyValueOfstringanyType"]): if key_value_pair["Key"] == "PhoneNumber": return key_value_pair["Value"] return None def is_member(self, client): """Is this Individual a member? Assumptions: - a "primary organization" in MemberSuite is the "current" Organization for an Individual - get_memberships_for_org() returns Memberships ordered such that the first one returned is the "current" one. """ if not client.session_id: client.request_session() primary_organization = self.get_primary_organization(client=client) if primary_organization: membership_service = membership_services.MembershipService( client=client) membership = membership_service.get_current_membership_for_org( account_num=primary_organization.id) if membership: return membership.receives_member_benefits else: return False def get_primary_organization(self, client): """Return the primary Organization for this Individual. """ if self.primary_organization_id is None: return None if not client.session_id: client.request_session() object_query = ("SELECT OBJECT() FROM ORGANIZATION " "WHERE ID = '{}'".format( self.primary_organization_id)) result = client.execute_object_query(object_query) msql_result = result["body"]["ExecuteMSQLResult"] if msql_result["Success"]: membersuite_object_data = (msql_result["ResultValue"] ["SingleObject"]) else: raise ExecuteMSQLError(result=result) # Could omit this step if Organization inherits from MemberSuiteObject. organization = convert_ms_object( membersuite_object_data["Fields"]["KeyValueOfstringanyType"]) return Organization(org=organization)
class Individual(MemberSuiteObject): def __init__(self, membersuite_object_data, portal_user=None): '''Create an Individual object from the Zeep'ed XML representation of a MemberSuite Individual. ''' pass def __str__(self): pass @property def phone_number(self): pass def is_member(self, client): '''Is this Individual a member? Assumptions: - a "primary organization" in MemberSuite is the "current" Organization for an Individual - get_memberships_for_org() returns Memberships ordered such that the first one returned is the "current" one. ''' pass def get_primary_organization(self, client): '''Return the primary Organization for this Individual. ''' pass
7
3
17
4
11
3
3
0.22
1
4
3
0
5
7
5
7
94
23
58
24
51
13
41
22
35
4
2
3
14
1,620
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/subscriptions/services.py
membersuite_api_client.subscriptions.services.SubscriptionService
class SubscriptionService(ChunkQueryMixin, object): def __init__(self, client=None): """ Accepts a ConciergeClient to connect with MemberSuite """ super(SubscriptionService, self).__init__() self.client = client or get_new_client() def get_subscriptions(self, publication_id=None, owner_id=None, since_when=None, limit_to=200, max_calls=None, start_record=0, verbose=False): """ Fetches all subscriptions from Membersuite of a particular `publication_id` if set. """ query = "SELECT Objects() FROM Subscription" # collect all where parameters into a list of # (key, operator, value) tuples where_params = [] if owner_id: where_params.append(('owner', '=', "'%s'" % owner_id)) if publication_id: where_params.append(('publication', '=', "'%s'" % publication_id)) if since_when: d = datetime.date.today() - datetime.timedelta(days=since_when) where_params.append( ('LastModifiedDate', ">", "'%s 00:00:00'" % d)) if where_params: query += " WHERE " query += " AND ".join( ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params]) subscription_list = self.get_long_query( query, limit_to=limit_to, max_calls=max_calls, start_record=start_record, verbose=verbose) return subscription_list def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " return Subscription(membersuite_object_data=ms_obj)
class SubscriptionService(ChunkQueryMixin, object): def __init__(self, client=None): ''' Accepts a ConciergeClient to connect with MemberSuite ''' pass def get_subscriptions(self, publication_id=None, owner_id=None, since_when=None, limit_to=200, max_calls=None, start_record=0, verbose=False): ''' Fetches all subscriptions from Membersuite of a particular `publication_id` if set. ''' pass def ms_object_to_model(self, ms_obj): ''' Converts an individual result to a Subscription Model ''' pass
4
3
14
2
9
3
2
0.37
2
4
1
0
3
1
3
5
45
8
27
11
21
10
21
9
17
5
2
1
7
1,621
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/tests/base.py
membersuite_api_client.tests.base.BaseTestCase
class BaseTestCase(unittest.TestCase): def setUp(self): self.MS_ACCESS_KEY = os.environ["MS_ACCESS_KEY"] self.MS_SECRET_KEY = os.environ["MS_SECRET_KEY"] self.MS_ASSOCIATION_ID = os.environ["MS_ASSOCIATION_ID"] self.client = ConciergeClient( access_key=self.MS_ACCESS_KEY, secret_key=self.MS_SECRET_KEY, association_id=self.MS_ASSOCIATION_ID)
class BaseTestCase(unittest.TestCase): def setUp(self): pass
2
0
9
1
8
0
1
0
1
1
1
3
1
4
1
73
11
2
9
6
7
0
6
6
4
1
2
0
1
1,622
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_client.py
membersuite_api_client.tests.test_client.ConciergeClientTestCase
class ConciergeClientTestCase(unittest.TestCase): def test_signature_hashing(self): """ Tests that we are properly hashing the signature data """ client = ConciergeClient( access_key=MS_ACCESS_KEY, secret_key=("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=="), association_id="00000000-0000-0000-0000-000000000000") # Modify attributes to use sample data from API docs # to test that signature is hashed properly. client.session_id = "11111111-1111-1111-1111-111111111111" signature = client.get_hashed_signature( url="http://membersuite.com/contracts/IConciergeAPIService/WhoAmI") self.assertEqual(signature, "2zsMYdHb/MJUeTjv5cQl5pBuIqU=") def test_request_session(self): """ Can we send a login request and receive a session ID? """ client = ConciergeClient(access_key=MS_ACCESS_KEY, secret_key=MS_SECRET_KEY, association_id=MS_ASSOCIATION_ID) # Send a login request to receive a session id session_id = client.request_session() self.assertTrue(session_id) # Invoke the ListAllReports method to test usage of the # received session ID url = ("http://membersuite.com/contracts/" "IConciergeAPIService/ListAllReports") client.hashed_signature = client.get_hashed_signature(url=url) concierge_request_header = client.construct_concierge_header(url=url) response = client.client.service.ListAllReports( _soapheaders=[concierge_request_header]) # Check that the session ID in the response headers matches the # previously obtained session, so the user was not re-authenticated # but properly used the established session. self.assertEqual(get_session_id(result=response), client.session_id)
class ConciergeClientTestCase(unittest.TestCase): def test_signature_hashing(self): ''' Tests that we are properly hashing the signature data ''' pass def test_request_session(self): ''' Can we send a login request and receive a session ID? ''' pass
3
2
21
2
12
7
1
0.56
1
1
1
0
2
0
2
74
45
6
25
10
22
14
15
10
12
1
2
0
2
1,623
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_exceptions.py
membersuite_api_client.tests.test_exceptions.MemberSuiteAPIErrorTestCase
class MemberSuiteAPIErrorTestCase(unittest.TestCase): @classmethod def setUpClass(cls): client.request_session() try: submit_msql_object_query( object_query="SELECT OBJECT() FROM BOB", client=client) except ExecuteMSQLError as exc: cls.exc = exc def test_get_concierge_error(self): concierge_error = self.exc.get_concierge_error() self.assertTrue(concierge_error is not None) def test___str__(self): self.assertTrue(str(self.exc) > '')
class MemberSuiteAPIErrorTestCase(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_get_concierge_error(self): pass def test___str__(self): pass
5
0
4
0
4
0
1
0
1
2
1
0
2
0
3
75
18
3
15
7
10
0
12
5
8
2
2
1
4
1,624
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/subscriptions/models.py
membersuite_api_client.subscriptions.models.Subscription
class Subscription(MemberSuiteObject): def __init__(self, membersuite_object_data): super(Subscription, self).__init__( membersuite_object_data=membersuite_object_data) self.owner_id = self.fields["Owner"] self.start_date = self.fields["StartDate"] self.expiration_date = self.fields["ExpirationDate"] self.name = self.fields["Name"] self.created_date = self.fields["CreatedDate"] self.order_id = self.fields["OriginalOrder"] def get_order(self, client=None): order = orders_services.get_order(membersuite_id=self.order_id, client=client) return order
class Subscription(MemberSuiteObject): def __init__(self, membersuite_object_data): pass def get_order(self, client=None): pass
3
0
7
0
7
0
1
0
1
1
0
0
2
6
2
4
16
2
14
10
11
0
12
10
9
1
2
0
2
1,625
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_security.py
membersuite_api_client.tests.test_security.PortalUserTestCase
class PortalUserTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = get_new_client() def setUp(self): self.portal_user = _login(client=self.client) def test_generate_username(self): """Does generate_username() work? """ self.portal_user.membersuite_id = "6faf90e4-fake-membersuite-id" self.assertEqual("ms-fake-membersuite-id", models.generate_username()) def test_get_individual(self): """Does get_individual() work? """ individual = self.portal_user.get_individual(client=self.client) self.assertEqual(self.portal_user.first_name, individual.first_name) self.assertEqual(self.portal_user.last_name, individual.last_name) self.assertEqual(self.portal_user.owner, individual.membersuite_id)
class PortalUserTestCase(unittest.TestCase): @classmethod def setUpClass(cls): pass def setUpClass(cls): pass def test_generate_username(self): '''Does generate_username() work? ''' pass def test_get_individual(self): '''Does get_individual() work? ''' pass
6
2
5
1
3
1
1
0.27
1
0
0
0
3
1
4
76
25
6
15
8
9
4
13
7
8
1
2
0
4
1,626
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/models.py
membersuite_api_client.models.MemberSuiteObject
class MemberSuiteObject(object): def __init__(self, membersuite_object_data, membersuite_id=None): """Takes the Zeep'ed XML Representation of a MemberSuiteObject as input. """ self.fields = convert_ms_object( membersuite_object_data["Fields"]["KeyValueOfstringanyType"]) self.extra_data = membersuite_object_data self.membersuite_id = (self.fields["ID"] if membersuite_id is None else membersuite_id) def __str__(self): return ("<MemberSuiteObject: MemberSuite ID: {id}>".format( id=self.membersuite_id))
class MemberSuiteObject(object): def __init__(self, membersuite_object_data, membersuite_id=None): '''Takes the Zeep'ed XML Representation of a MemberSuiteObject as input. ''' pass def __str__(self): pass
3
1
7
1
5
2
2
0.27
1
0
0
6
2
3
2
2
17
3
11
6
8
3
7
6
4
2
1
0
3
1,627
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/memberships/services.py
membersuite_api_client.memberships.services.MembershipProductService
class MembershipProductService(ChunkQueryMixin, object): def __init__(self, client): """ Accepts a ConciergeClient to connect with MemberSuite """ self.client = client def get_all_membership_products(self, verbose=False): """ Retrieves membership product objects """ if not self.client.session_id: self.client.request_session() query = "SELECT Objects() FROM MembershipDuesProduct" membership_product_list = self.get_long_query(query, verbose=verbose) return membership_product_list or [] def ms_object_to_model(self, ms_obj): " Converts an individual result to a Subscription Model " sane_obj = convert_ms_object( ms_obj['Fields']['KeyValueOfstringanyType']) return MembershipProduct(sane_obj)
class MembershipProductService(ChunkQueryMixin, object): def __init__(self, client): ''' Accepts a ConciergeClient to connect with MemberSuite ''' pass def get_all_membership_products(self, verbose=False): ''' Retrieves membership product objects ''' pass def ms_object_to_model(self, ms_obj): ''' Converts an individual result to a Subscription Model ''' pass
4
3
7
1
4
2
1
0.54
2
1
1
0
3
1
3
5
25
5
13
8
9
7
12
8
8
2
2
1
4
1,628
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/orders/models.py
membersuite_api_client.orders.models.OrderLineItem
class OrderLineItem(MemberSuiteObject): def __init__(self, membersuite_object_data, session_id=None): """Create an OrderLineItem object from a the Zeep'ed XML representation of a Membersuite OrderLineItem. """ membersuite_id = value_for_key( membersuite_object_data=membersuite_object_data, key="OrderLineItemID") super(OrderLineItem, self).__init__( membersuite_object_data=membersuite_object_data, membersuite_id=membersuite_id) self.product_id = self.fields["Product"] self.session_id = session_id def __str__(self): return ("<Order: ID: {id}, product: {product} " " session_id: {session_id}>".format( id=self.membersuite_id, product=self.product, session_id=self.session_id)) def get_product(self, client=None): """Return a Product object for this line item. """ client = client or get_new_client(request_session=True) if not client.session_id: client.request_session() product = financial_services.get_product( membersuite_id=self.product_id, client=client) return product
class OrderLineItem(MemberSuiteObject): def __init__(self, membersuite_object_data, session_id=None): '''Create an OrderLineItem object from a the Zeep'ed XML representation of a Membersuite OrderLineItem. ''' pass def __str__(self): pass def get_product(self, client=None): '''Return a Product object for this line item. ''' pass
4
2
10
1
8
2
1
0.21
1
1
0
0
3
4
3
5
35
6
24
10
20
5
14
8
10
2
2
1
4
1,629
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/orders/models.py
membersuite_api_client.orders.models.Order
class Order(MemberSuiteObject): def __init__(self, membersuite_object_data, session_id=None): """Create an Order object from a the Zeep'ed XML representation of a Membersuite Order. """ super(Order, self).__init__( membersuite_object_data=membersuite_object_data) self.session_id = session_id def __str__(self): return ("<Order: ID: {id}, Line Items: {line_items} " " session_id: {session_id}>".format( id=self.membersuite_id, line_items=self.line_items, session_id=self.session_id)) @property def line_items(self): """Returns the OrderLineItem objects for line items in this order. """ membersuite_object_data = ( self.fields["LineItems"]["MemberSuiteObject"]) line_items = [] for datum in membersuite_object_data: line_items.append(OrderLineItem(membersuite_object_data=datum)) return line_items def get_products(self, client=None): """A list of Product objects in this Order. """ client = client or get_new_client(request_session=True) if not client.session_id: client.request_session() products = [] for line_item in self.line_items: products.append(line_item.get_product(client=client)) return products
class Order(MemberSuiteObject): def __init__(self, membersuite_object_data, session_id=None): '''Create an Order object from a the Zeep'ed XML representation of a Membersuite Order. ''' pass def __str__(self): pass @property def line_items(self): '''Returns the OrderLineItem objects for line items in this order. ''' pass def get_products(self, client=None): '''A list of Product objects in this Order. ''' pass
6
3
9
0
6
2
2
0.3
1
2
1
0
4
2
4
6
40
5
27
13
21
8
20
11
15
3
2
1
7
1,630
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/organizations/models.py
membersuite_api_client.organizations.models.Organization
class Organization(object): def __init__(self, org): """Create an Organization model from MemberSuite Organization object """ self.id = self.account_num = org["ID"] self.local_id = self.membersuite_id = org["LocalID"] self.name = self.org_name = org["Name"] self.picklist_name = org["SortName"] or '' self.address = org["Mailing_Address"] if self.address: self.street1 = self.address["Line1"] or '' self.street2 = self.address["Line2"] or '' self.city = self.address["City"] or '' self.state = self.address["State"] or '' self.country = self.address["Country"] self.postal_code = self.address["PostalCode"] or '' self.latitude = self.address["GeocodeLat"] or '' self.longitude = self.address["GeocodeLong"] or '' self.website = org["WebSite"] or '' self.exclude_from_website = False self.is_defunct = (org["Status"] == 'Defunct') self.org_type = org["Type"] self.primary_email = org['EmailAddress'] or '' self.extra_data = org
class Organization(object): def __init__(self, org): '''Create an Organization model from MemberSuite Organization object ''' pass
2
1
28
5
21
2
2
0.09
1
0
0
0
1
22
1
1
30
6
22
21
20
2
22
21
20
2
1
1
2
1,631
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_subscriptions.py
membersuite_api_client.tests.test_subscriptions.SubscriptionTestCase
class SubscriptionTestCase(BaseTestCase): def setUp(self): super(SubscriptionTestCase, self).setUp() self.service = SubscriptionService(self.client)
class SubscriptionTestCase(BaseTestCase): def setUp(self): pass
2
0
3
0
3
0
1
0
1
2
1
0
1
1
1
74
5
1
4
3
2
0
4
3
2
1
3
0
1
1,632
AASHE/python-membersuite-api-client
AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_security.py
membersuite_api_client.tests.test_security.SecurityServicesTestCase
class SecurityServicesTestCase(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = get_new_client() def test_login_to_portal(self): """Can we log in to the portal?""" portal_user = _login(client=self.client) self.assertIsInstance(portal_user, models.PortalUser) def test_login_to_portal_failure(self): """What happens when we can't log in to the portal?""" with self.assertRaises(LoginToPortalError): login_to_portal(username="bo-o-o-gus user ID", password="wrong password", client=self.client, retries=LOGIN_TO_PORTAL_RETRIES, delay=LOGIN_TO_PORTAL_DELAY) def test_logout(self): """Can we logout? This logs out from the API client session, not the MemberSuite Portal. """ self.client.session_id = None self.client.request_session() # A fresh session. Yum! self.assertTrue(self.client.session_id) logout(self.client) self.assertIsNone(self.client.session_id)
class SecurityServicesTestCase(unittest.TestCase): @classmethod def setUpClass(cls): pass def test_login_to_portal(self): '''Can we log in to the portal?''' pass def test_login_to_portal_failure(self): '''What happens when we can't log in to the portal?''' pass def test_logout(self): '''Can we logout? This logs out from the API client session, not the MemberSuite Portal. ''' pass
6
3
7
1
5
2
1
0.35
1
2
2
0
3
1
4
76
35
9
20
8
14
7
15
6
10
1
2
1
4
1,633
AASHE/python-membersuite-api-client
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/AASHE_python-membersuite-api-client/membersuite_api_client/tests/test_memberships.py
membersuite_api_client.tests.test_memberships.MembershipServiceTestCase
class MembershipServiceTestCase(BaseTestCase): def setUp(self): super(MembershipServiceTestCase, self).setUp() self.service = MembershipService(self.client) self.product_service = MembershipProductService(self.client) @unittest.skip("Need an Organization ID for a non-member org") def test_get_membership_for_org(self): """ Get membership info for a test org """ # Test org with a membership membership_list = self.service.get_memberships_for_org( MEMBER_ORG_ID, verbose=False) self.assertEqual(type(membership_list[0]), Membership) # Test org without a membership membership_list = self.service.get_memberships_for_org( NONMEMBER_ORG_ID, verbose=False) self.assertFalse(membership_list) def test_get_all_memberships(self): """ Does the get_all_memberships() method work? """ membership_list = self.service.get_all_memberships( limit_to=1, max_calls=2, verbose=False ) self.assertEqual(len(membership_list), 2) self.assertEqual(type(membership_list[0]), Membership) def test_get_all_membership_products(self): """ Test if we can retrieve all MembershipProduct objects 103 at the time of testing """ service = self.product_service membership_product_list = service.get_all_membership_products() self.assertTrue(len(membership_product_list) > 0) self.assertEqual(type(membership_product_list[0]), MembershipProduct)
class MembershipServiceTestCase(BaseTestCase): def setUp(self): pass @unittest.skip("Need an Organization ID for a non-member org") def test_get_membership_for_org(self): ''' Get membership info for a test org ''' pass def test_get_all_memberships(self): ''' Does the get_all_memberships() method work? ''' pass def test_get_all_membership_products(self): ''' Test if we can retrieve all MembershipProduct objects 103 at the time of testing ''' pass
6
3
9
0
6
3
1
0.48
1
6
4
0
4
2
4
77
42
5
25
12
19
12
19
11
14
1
3
0
4
1,634
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vtkparser/parser.py
meshparser.vtkparser.parser._TopologyState
class _TopologyState(_BaseState): def __init__(self, parent): super(_TopologyState, self).__init__(parent) self._dataset_type = None self._processing = None def parse(self, line): status = False if self._dataset_type is None: # Determine dataset type parts = line.split(' ') if len(parts) > 1 and parts[0] == 'DATASET': self._dataset_type = parts[1] elif self._dataset_type == 'POLYDATA': if self._processing is None: # Determine data type parts = line.split(' ') if len(parts) > 2: self._processing = {'type': parts[0], 'n': int(parts[1]), 'progress': 0, } if self._processing['type'] == 'POINTS': self._processing['datatype'] = parts[2] self._processing['current_pt'] = [] else: self._processing['size'] = int(parts[2]) elif self._processing['type'] == 'POINTS': parts = line.split(' ') for part in parts: if self._processing['datatype'] == 'float': self._processing['current_pt'].append(float(part)) if len(self._processing['current_pt']) == 3: self._parent._points.append(self._processing['current_pt']) self._processing['current_pt'] = [] self._processing['progress'] += 1 if self._processing['progress'] == self._processing['n']: self._processing = None elif self._processing['type'] == 'POLYGONS': parts = line.split(' ') if len(parts): polygon_size = int(parts[0]) if polygon_size == len(parts[1:]): self._parent._elements.append([int(index) for index in parts[1:]]) self._processing['progress'] += 1 if self._processing['progress'] == self._processing['n']: status = True return status
class _TopologyState(_BaseState): def __init__(self, parent): pass def parse(self, line): pass
3
0
26
3
22
1
9
0.04
1
3
0
0
2
2
2
4
54
7
45
9
42
2
38
9
35
16
2
4
17
1,635
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vtkparser/parser.py
meshparser.vtkparser.parser._TitleState
class _TitleState(_BaseState): def parse(self, line): return True
class _TitleState(_BaseState): def parse(self, line): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
4
1
3
2
1
0
3
2
1
1
2
0
1
1,636
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vtkparser/parser.py
meshparser.vtkparser.parser._InitState
class _InitState(_BaseState): pass
class _InitState(_BaseState): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
2
2
0
2
1
1
0
2
1
1
0
2
0
0
1,637
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vtkparser/parser.py
meshparser.vtkparser.parser._HeaderState
class _HeaderState(_BaseState): def parse(self, line): matching = [s for s in KNOWN_FILE_FORMATS if line == s] if matching: return True raise SyntaxError('Unknown file format syntax.')
class _HeaderState(_BaseState): def parse(self, line): pass
2
0
6
1
5
0
2
0
1
1
0
0
1
0
1
3
8
2
6
3
4
0
6
3
4
2
2
1
2
1,638
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vtkparser/parser.py
meshparser.vtkparser.parser._DatasetAttributesState
class _DatasetAttributesState(_BaseState): def parse(self, line): return True
class _DatasetAttributesState(_BaseState): def parse(self, line): pass
2
0
2
0
2
0
1
0
1
0
0
0
1
0
1
3
4
1
3
2
1
0
3
2
1
1
2
0
1
1,639
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vtkparser/parser.py
meshparser.vtkparser.parser._BaseState
class _BaseState(object): def __init__(self, parent=None): self._parent = parent def parse(self, line): """ All instantiated classes must define this method. """
class _BaseState(object): def __init__(self, parent=None): pass def parse(self, line): ''' All instantiated classes must define this method. ''' pass
3
1
3
0
2
2
1
0.75
1
0
0
6
2
1
2
2
9
2
4
4
1
3
4
4
1
1
1
0
2
1,640
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vtkparser/parser.py
meshparser.vtkparser.parser.VTKParser
class VTKParser(BaseParser): ''' classdocs ''' def __init__(self): ''' Constructor ''' super(VTKParser, self).__init__() def can_parse(self, filename): state = _HeaderState(self) with open(filename) as f: lines = f.readlines() header_line = lines.pop(0) try: parseable = state.parse(header_line.rstrip()) except SyntaxError: parseable = False return parseable def parse(self, filename): self._clear() current_state = self._next_state(_InitState()) with open(filename) as f: lines = f.readlines() for line in lines: line = line.rstrip() if current_state is not None and current_state.parse(line): current_state = self._next_state(current_state) def _next_state(self, current_state): state_map = { _InitState: _HeaderState(self), _HeaderState: _TitleState(self), _TitleState: _DataTypeState(self), _DataTypeState: _TopologyState(self), _TopologyState: _DatasetAttributesState(self), _DatasetAttributesState: None, } return state_map[type(current_state)]
class VTKParser(BaseParser): ''' classdocs ''' def __init__(self): ''' Constructor ''' pass def can_parse(self, filename): pass def parse(self, filename): pass def _next_state(self, current_state): pass
5
2
9
1
8
1
2
0.19
1
9
6
0
4
0
4
10
44
6
32
15
27
6
25
13
20
3
2
3
7
1,641
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._WorldInfoNode
class _WorldInfoNode(_BaseNode): """ WorldInfo node. Has optional fields: title (SFString), info (MFString). """ def __init__(self): super(_WorldInfoNode, self).__init__() self._name = 'WorldInfo' self._fields = ['title', 'info'] self._field_types = ['SFString', 'MFString']
class _WorldInfoNode(_BaseNode): ''' WorldInfo node. Has optional fields: title (SFString), info (MFString). ''' def __init__(self): pass
2
1
5
0
5
0
1
0.5
1
1
0
0
1
3
1
13
9
0
6
5
4
3
6
5
4
1
2
0
1
1,642
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._VRMLScene
class _VRMLScene(object): """ Scene information object. """ def __init__(self): self._root = {} self._state = None self._key = None def get_root(self): return self._root def parse(self, line_elements): # If no state is set then we are looking for a node. if self._state is None: element = line_elements.pop(0) if _is_node(element): self._state = _get_vrml_node(element) self._key = element self._root[element] = {} else: raise ParseError('Unknown node: "{0}" where node expected.'.format(element)) else: self._state.parse(line_elements) if self._state.is_finished(): self._root[self._key] = self._state.get_data() self._state = None
class _VRMLScene(object): ''' Scene information object. ''' def __init__(self): pass def get_root(self): pass def parse(self, line_elements): pass
4
1
7
0
7
0
2
0.19
1
1
1
0
3
3
3
3
27
2
21
8
17
4
19
8
15
4
1
2
6
1,643
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/stlparser/parser.py
meshparser.stlparser.parser._RootState
class _RootState(object): pass
class _RootState(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
1,644
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._ShapeNode
class _ShapeNode(_BaseNode): """ Shape node. Has two optional fields. """ def __init__(self): super(_ShapeNode, self).__init__() self._name = 'Shape' self._fields = ['appearance', 'geometry'] self._field_types = ['MFNode', 'MFNode']
class _ShapeNode(_BaseNode): ''' Shape node. Has two optional fields. ''' def __init__(self): pass
2
1
5
0
5
0
1
0.5
1
1
0
0
1
3
1
13
9
0
6
5
4
3
6
5
4
1
2
0
1
1,645
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._FInt32
class _FInt32(_BaseInt): """ Parses single or a list of integers. """
class _FInt32(_BaseInt): ''' Parses single or a list of integers. ''' pass
1
1
0
0
0
0
0
3
1
0
0
0
0
0
0
12
4
0
1
1
0
3
1
1
0
0
3
0
0
1,646
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._FNode
class _FNode(_BaseMultiAble): """ Parses a node, or a multi node array. """ def __init__(self): super(_FNode, self).__init__() self._active_key = None self._active_state = None def clear(self): self._active_key = None self._active_state = None def parse(self, line_elements): while line_elements and not self.is_finished(): element = line_elements[0] consume = True if self.is_open_marker(element): self._data = [] self._multi = True elif self._active_state is not None: consume = False self._active_state.parse(line_elements) if self._active_state.is_finished(): self.add_data({self._active_key: self._active_state.get_data()}) self.clear() if not self._multi: self._finished = True elif self.is_close_marker(element): self._finished = True elif self._active_state is None: if _is_node(element): self._active_key = element self._active_state = _get_vrml_node(element) elif element == 'NULL': self._data = None self._finished = True else: raise ParseError('Unknown node: "{0}" where node expected.'.format(element)) if consume: line_elements.pop(0)
class _FNode(_BaseMultiAble): ''' Parses a node, or a multi node array. ''' def __init__(self): pass def clear(self): pass def parse(self, line_elements): pass
4
1
12
0
12
0
4
0.08
1
2
1
0
3
5
3
13
42
3
36
11
32
3
31
11
27
11
2
4
13
1,647
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._FRotation
class _FRotation(_BaseFloat): """ Parses four floats or a multi four floats. """ def __init__(self): super(_FRotation, self).__init__(4)
class _FRotation(_BaseFloat): ''' Parses four floats or a multi four floats. ''' def __init__(self): pass
2
1
2
0
2
0
1
1
1
1
0
0
1
0
1
13
6
0
3
2
1
3
3
2
1
1
3
0
1
1,648
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._FString
class _FString(_BaseMultiAble): """ Parses a single string or multi string field or event. """ def __init__(self): super(_FString, self).__init__() self._parsing_string = False def parse(self, line_elements): while line_elements and not self.is_finished(): element = line_elements.pop(0) if self.is_open_marker(element): # Multi string self.set_multi() self._data = [] elif self.is_close_marker(element): self.set_multi(False) self.set_finished() else: if self._data is None: self._data = '' index = element.find("\"") # Find the index again if the quote is escaped. while index > 0 and element[index - 1] == '\\': index = element.find("\"", index + 1) if self._parsing_string: inclusive_index = index + 1 if self.is_multi(): stem_string = self._data.pop() if index > -1: stem_string += ' ' + element[:inclusive_index] else: stem_string += ' ' + element self._data.append(stem_string) else: if index > -1: self._data += ' ' + element[:inclusive_index] else: self._data += ' ' + element if index > -1: self._parsing_string = False if not self.is_multi(): self.set_finished() else: self._parsing_string = True if self.is_multi(): self._data.append(element) else: self._data += element
class _FString(_BaseMultiAble): ''' Parses a single string or multi string field or event. ''' def __init__(self): pass def parse(self, line_elements): pass
3
1
22
0
21
1
7
0.12
1
1
0
0
2
2
2
12
49
1
43
9
40
5
36
9
33
13
2
5
14
1,649
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._FVec3f
class _FVec3f(_BaseFloat): """ Parses three floats or a multi floats. """ def __init__(self): super(_FVec3f, self).__init__(3)
class _FVec3f(_BaseFloat): ''' Parses three floats or a multi floats. ''' def __init__(self): pass
2
1
2
0
2
0
1
1
1
1
0
0
1
0
1
13
6
0
3
2
1
3
3
2
1
1
3
0
1
1,650
ABI-Software/MeshParser
ABI-Software_MeshParser/tests/baseparser/test_parser.py
tests.baseparser.test_parser.ParserTestCase
class ParserTestCase(unittest.TestCase): def test_can_parse(self): v = BaseParser() self.assertFalse(v.can_parse('not-a-file')) def test_parse(self): v = BaseParser() self.assertRaises(NotImplementedError, v.parse, 'not-a-file')
class ParserTestCase(unittest.TestCase): def test_can_parse(self): pass def test_parse(self): pass
3
0
3
0
3
0
1
0
1
2
1
0
2
0
2
74
9
2
7
5
4
0
7
5
4
1
2
0
2
1,651
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._IndexedFaceSetNode
class _IndexedFaceSetNode(_BaseNode): """ Indexed face set node. Has 14 optional fields. """ def __init__(self): super(_IndexedFaceSetNode, self).__init__() self._name = 'IndexedFaceSet' self._fields = ['color', 'coord', 'normal', 'texCoord', 'ccw', 'colorIndex', 'colorPerVertex', 'convex', 'coordIndex', 'creaseAngle', 'normalIndex', 'normalPerVertex', 'solid', 'texCoordIndex'] self._field_types = ['SFNode', 'SFNode', 'SFNode', 'SFNode', 'SFBool', 'MFInt32', 'SFBool', 'SFBool', 'MFInt32', 'SFFloat', 'MFInt32', 'SFBool', 'SFBool', 'MFInt32']
class _IndexedFaceSetNode(_BaseNode): ''' Indexed face set node. Has 14 optional fields. ''' def __init__(self): pass
2
1
5
0
5
0
1
0.5
1
1
0
0
1
3
1
13
9
0
6
5
4
3
6
5
4
1
2
0
1
1,652
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._MaterialNode
class _MaterialNode(_BaseNode): """ Shape node. Has two optional fields. """ def __init__(self): super(_MaterialNode, self).__init__() self._name = 'Material' self._fields = ['ambientIntensity', 'diffuseColor', 'emissiveColor', 'shininess', 'specularColor', 'transparency'] self._field_types = ['SFFloat', 'SFColour', 'SFColour', 'SFFloat', 'SFColour', 'SFFloat']
class _MaterialNode(_BaseNode): ''' Shape node. Has two optional fields. ''' def __init__(self): pass
2
1
5
0
5
0
1
0.5
1
1
0
0
1
3
1
13
9
0
6
5
4
3
6
5
4
1
2
0
1
1,653
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._NormalNode
class _NormalNode(_BaseNode): """ Normal node. Has one optional field. """ def __init__(self): super(_NormalNode, self).__init__() self._name = 'Normal' self._fields = ['vector'] self._field_types = ['MFVec3f']
class _NormalNode(_BaseNode): ''' Normal node. Has one optional field. ''' def __init__(self): pass
2
1
5
0
5
0
1
0.5
1
1
0
0
1
3
1
13
9
0
6
5
4
3
6
5
4
1
2
0
1
1,654
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._TransformNode
class _TransformNode(_BaseNode): """ Transform node. Has eight optional fields. """ def __init__(self): super(_TransformNode, self).__init__() self._name = 'Transform' self._fields = ['center', 'children', 'rotation', 'scale', 'scaleOrientation', 'translation', 'bboxCenter', 'bboxSize'] self._field_types = ['SFVec3f', 'MFNode', 'SFRotation', 'SFVec3f', 'SFRotation', 'SFVec3f', 'SFVec3f', 'SFVec3f']
class _TransformNode(_BaseNode): ''' Transform node. Has eight optional fields. ''' def __init__(self): pass
2
1
7
0
7
0
1
0.38
1
1
0
0
1
3
1
13
11
0
8
5
6
3
6
5
4
1
2
0
1
1,655
ABI-Software/MeshParser
ABI-Software_MeshParser/tests/stlparser/test_parser.py
tests.stlparser.test_parser.ParserTestCase
class ParserTestCase(unittest.TestCase): def testExistence(self): v = STLParser() self.assertRaises(IOError, v.parse, 'file that doesnt exist') def testParse1(self): v = STLParser() v.parse(os.path.join(file_path, 'data/ship.stl')) self.assertEqual(828, len(v.get_elements())) def testParse2(self): v = STLParser() test_filename = os.path.join(file_path, 'data/ship.zip') self.assertTrue(v.can_parse(test_filename)) v.parse(test_filename) self.assertEqual(828, len(v.get_elements())) def testParse3(self): v = STLParser() test_filename = os.path.join(file_path, 'data/pelvis.stl') self.assertTrue(v.can_parse(test_filename)) v.parse(test_filename) self.assertEqual(52272, len(v.get_elements())) def testParse4(self): v = STLParser() v.parse(os.path.join(file_path, 'data/pelvis.zip')) self.assertEqual(52272, len(v.get_elements())) def testDuplicatedPoints(self): v = STLParser() v.parse(os.path.join(file_path, 'data/ship.stl')) self.assertEqual(2484, len(v.get_points())) pp = PointPare() pp.add_points(v.get_points()) pp.pare_points() self.assertEqual(450, len(pp.get_pared_points())) def testZeroBased(self): v = STLParser() v.parse(os.path.join(file_path, 'data/pelvis_minimal.stl')) self.assertEqual(33, len(v.get_points())) elements = v.get_elements(zero_based=False) self.assertEqual([4, 5, 6], elements[1]) def testPared(self): v = STLParser() v.parse(os.path.join(file_path, 'data/pelvis_minimal.stl')) self.assertEqual(13, len(v.get_points(pared=True))) elements = v.get_elements(pared=True) self.assertEqual([0, 3, 1], elements[1]) def testParedZeroBased(self): v = STLParser() v.parse(os.path.join(file_path, 'data/pelvis_minimal.stl')) self.assertEqual(33, len(v.get_points())) elements = v.get_elements(zero_based=False, pared=True) self.assertEqual([1, 4, 2], elements[1]) # @unittest.skip("Skipping long test.") def testFailingModelInVersion000400(self): v = STLParser() v.parse(os.path.join(file_path, 'data/amazing_alveoli_minimal.stl')) self.assertEqual(310188, len(v.get_points())) elements = v.get_elements(zero_based=False, pared=True) self.assertEqual([4, 1, 3], elements[1])
class ParserTestCase(unittest.TestCase): def testExistence(self): pass def testParse1(self): pass def testParse2(self): pass def testParse3(self): pass def testParse4(self): pass def testDuplicatedPoints(self): pass def testZeroBased(self): pass def testPared(self): pass def testParedZeroBased(self): pass def testFailingModelInVersion000400(self): pass
11
0
6
0
6
0
1
0.02
1
1
1
0
10
0
10
82
71
14
56
28
45
1
56
28
45
1
2
0
10
1,656
ABI-Software/MeshParser
ABI-Software_MeshParser/tests/vrmlparser/test_parser.py
tests.vrmlparser.test_parser.ParserTestCase
class ParserTestCase(unittest.TestCase): def testExistence(self): v = VRMLParser() self.assertRaises(IOError, v.parse, 'file that doesnt exist') def testParse1(self): v = VRMLParser() test_filename = os.path.join(file_path, 'data/Horse_1_1.wrl') self.assertTrue(v.can_parse(test_filename)) v.parse(test_filename) def testParse2(self): v = VRMLParser() v.parse(os.path.join(file_path, 'data/Horse_1_2.wrl')) self.assertEqual(0, len(v.get_points())) def testParse3(self): v = VRMLParser() v.parse(os.path.join(file_path, 'data/Horse_1_3.wrl')) self.assertEqual(4572, len(v.get_points())) self.assertEqual(9120, len(v.get_elements())) def testOldFormat(self): v = VRMLParser() self.assertRaises(Exception, v.parse, os.path.join(file_path, 'data', 'old_format.wrl')) def testString(self): v = VRMLParser() test_file = os.path.join(file_path, 'data', 'string.wrl') v.parse(test_file) data = v._data self.assertIn('WorldInfo', data) self.assertIn('title', data['WorldInfo']) self.assertIn('info', data['WorldInfo']) self.assertEqual("\" hash # in a \\\"quoted # string\\\"\"", data["WorldInfo"]["title"]) def testFStringSingle(self): from meshparser.vrmlparser.parser import _FString str1 = "\"A test string\"" line_elements = str1.split() fs = _FString() fs.parse(line_elements) self.assertEqual("\"A test string\"", fs.get_data()) def testFStringMulti(self): from meshparser.vrmlparser.parser import _FString str1 = "[ \"Another test string\",\n \"More testing string\" ]" line_elements = str1.split() fs = _FString() fs.parse(line_elements) string_data = fs.get_data() self.assertEqual("\"Another test string\"", string_data[0]) self.assertEqual("\"More testing string\"", string_data[1]) def testFStringMultiSplit(self): from meshparser.vrmlparser.parser import _FString str1 = "[ \"Another test string\"," str2 = "\"More testing string\" ]" line_elements_1 = str1.split() line_elements_2 = str2.split() fs = _FString() fs.parse(line_elements_1) self.assertFalse(fs.is_finished()) fs.parse(line_elements_2) self.assertTrue(fs.is_finished()) string_data = fs.get_data() self.assertEqual("\"Another test string\"", string_data[0]) self.assertEqual("\"More testing string\"", string_data[1]) def testFVec3fSingle1(self): from meshparser.vrmlparser.parser import _FVec3f str1 = '0.176164 0.303858 0.144138' line_elements_1 = str1.split() fv = _FVec3f() fv.parse(line_elements_1) values = fv.get_data() self.assertAlmostEqual(0.176164, values[0]) self.assertAlmostEqual(0.303858, values[1]) self.assertAlmostEqual(0.144138, values[2]) def testFVec3fSingle2(self): from meshparser.vrmlparser.parser import _FVec3f str1 = '-1.67149e-08 -8.78133e-08 3.14159' line_elements_1 = str1.split() fv = _FVec3f() fv.parse(line_elements_1) values = fv.get_data() self.assertAlmostEqual(-1.67149e-08, values[0]) self.assertAlmostEqual(-8.78133e-08, values[1]) self.assertAlmostEqual(3.14159, values[2]) self.assertTrue(fv.is_finished()) def testFNodeSimple(self): from meshparser.vrmlparser.parser import _FNode str1 = "Transform { }" line_elements_1 = str1.split() fn = _FNode() fn.parse(line_elements_1) values = fn.get_data() self.assertIn('Transform', values) def testFNodeMulti(self): from meshparser.vrmlparser.parser import _FNode str1 = "[ Shape { appearance Appearance { material Material { " \ "ambientIntensity 0.2 diffuseColor 1.000 1.000 0.200 } } } ]" line_elements_1 = str1.split() fn = _FNode() fn.parse(line_elements_1) values = fn.get_data() self.assertEqual(1, len(values)) self.assertIn('Shape', values[0]) def testInRange(self): from meshparser.vrmlparser.parser import _check_index_within_index_pairs self.assertTrue(_check_index_within_index_pairs(3, [[2, 4]])) self.assertTrue(_check_index_within_index_pairs(3, [[2, 4], [5, 8]])) self.assertFalse(_check_index_within_index_pairs(1, [[2, 4]])) self.assertFalse(_check_index_within_index_pairs(6, [[2, 4], [9, 15]])) def testComment(self): from meshparser.vrmlparser.parser import _remove_comment test_file = os.path.join(file_path, 'data', 'string.wrl') with open(test_file) as f: lines = f.readlines() for index, line in enumerate(lines): no_comment_line = _remove_comment(line.strip()) if index == 4: self.assertEqual("info [ \" # not a comment\" ]", no_comment_line) elif index == 5: self.assertEqual("", no_comment_line) elif index == 7: self.assertEqual("title \" hash # in a string\" ", no_comment_line) elif index == 8: self.assertEqual("title \" hash # in a \\\"quoted # string\\\"\" ", no_comment_line) def testTransformBasic1(self): from meshparser.vrmlparser.parser import _TransformNode node = _TransformNode() test_file = os.path.join(file_path, 'data', 'transform_test_1.wrl') with open(test_file) as f: lines = f.readlines() while lines: line = lines.pop(0) line_elements = line.split() node.parse(line_elements) self.assertTrue(node.is_finished()) self.assertIn('children', node._data) self.assertEqual(1, len(node._data['children'])) def testTransformBasic2(self): from meshparser.vrmlparser.parser import _TransformNode node = _TransformNode() test_file = os.path.join(file_path, 'data', 'transform_test_2.wrl') with open(test_file) as f: lines = f.readlines() while lines: line = lines.pop(0) line_elements = line.split() node.parse(line_elements) self.assertTrue(node.is_finished()) self.assertIn('children', node._data) self.assertEqual(1, len(node._data['children'])) self.assertIn('Shape', node._data['children'][0]) self.assertIn('appearance', node._data['children'][0]['Shape']) self.assertIn('Appearance', node._data['children'][0]['Shape']['appearance']) def testTransformBasic3(self): from meshparser.vrmlparser.parser import _TransformNode node = _TransformNode() test_file = os.path.join(file_path, 'data', 'transform_test_3.wrl') with open(test_file) as f: lines = f.readlines() while lines: line = lines.pop(0) line_elements = line.split() node.parse(line_elements) self.assertTrue(node.is_finished()) self.assertIn('children', node._data) self.assertEqual(1, len(node._data['children'])) self.assertIn('Shape', node._data['children'][0]) self.assertIn('appearance', node._data['children'][0]['Shape']) self.assertIn('Appearance', node._data['children'][0]['Shape']['appearance']) self.assertIn('material', node._data['children'][0]['Shape']['appearance']['Appearance']) self.assertIn('Material', node._data['children'][0]['Shape']['appearance']['Appearance']['material']) self.assertIn('emissiveColor', node._data['children'][0]['Shape']['appearance']['Appearance']['material']['Material']) def testLab1(self): v = VRMLParser() test_file = os.path.join(file_path, 'data', 'lab1.wrl') self.assertRaises(ParseError, v.parse, test_file) def testDuplicatedPoints(self): v = VRMLParser() v.parse(os.path.join(file_path, 'data/Horse_1_4.wrl')) points = v.get_points() self.assertEqual(33, len(points)) pp = PointPare() pp.add_points(points) pp.pare_points() self.assertEqual(23, len(pp.get_pared_points()))
class ParserTestCase(unittest.TestCase): def testExistence(self): pass def testParse1(self): pass def testParse2(self): pass def testParse3(self): pass def testOldFormat(self): pass def testString(self): pass def testFStringSingle(self): pass def testFStringMulti(self): pass def testFStringMultiSplit(self): pass def testFVec3fSingle1(self): pass def testFVec3fSingle2(self): pass def testFNodeSimple(self): pass def testFNodeMulti(self): pass def testInRange(self): pass def testComment(self): pass def testTransformBasic1(self): pass def testTransformBasic2(self): pass def testTransformBasic3(self): pass def testLab1(self): pass def testDuplicatedPoints(self): pass
21
0
10
1
9
0
1
0.02
1
8
6
0
20
0
20
92
221
40
181
99
148
4
177
95
144
6
2
3
28
1,657
ABI-Software/MeshParser
ABI-Software_MeshParser/tests/test_package.py
tests.test_package.PackageTestCase
class PackageTestCase(unittest.TestCase): def testVersion(self): import meshparser self.assertEqual('0.5.0', meshparser.__version__)
class PackageTestCase(unittest.TestCase): def testVersion(self): pass
2
0
4
1
3
0
1
0
1
0
0
0
1
0
1
73
6
2
4
3
1
0
4
3
1
1
2
0
1
1,658
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/printer.py
meshparser.printer.STLPrinter
class STLPrinter: def __init__(self, mesh, filename): self._mesh = mesh self._filename = filename def print(self): elements = self._mesh.get("elements", []) points = self._mesh.get("points", []) with open(self._filename, 'w') as stl_file: stl_file.write('solid\n') for tri in elements: pt1 = points[tri[0]] pt2 = points[tri[1]] pt3 = points[tri[2]] normal = _calculate_normal(pt1, pt2, pt3) stl_file.write(f' facet normal {normal[0]} {normal[1]} {normal[2]}\n') stl_file.write(' outer loop\n') for ver in [pt1, pt2, pt3]: stl_file.write(f' vertex {ver[0]} {ver[1]} {ver[2]}\n') stl_file.write(' endloop\n') stl_file.write(' endfacet\n') stl_file.write('endsolid\n')
class STLPrinter: def __init__(self, mesh, filename): pass def print(self): pass
3
0
12
2
10
0
2
0
0
0
0
0
2
2
2
2
27
6
21
14
18
0
21
13
18
3
0
3
4
1,659
ABI-Software/MeshParser
ABI-Software_MeshParser/tests/test_manipulation.py
tests.test_manipulation.ManipulationTestCase
class ManipulationTestCase(unittest.TestCase): def test_com_basic(self): mesh = {"points": [[0, 0, 0], [3, 0, 0], [0, 4, 0]], "elements": [[0, 1, 2]]} com = calculate_centre_of_mass(mesh) self.assertEqual([1.0, 1.3333333333333333, 0.0], com) def test_com(self): p = MeshParser() p.parse(os.path.join(file_path, "data/cylinder.stl")) points = p.get_points(True) self.assertEqual(40, len(points)) mesh = {"points": points, "elements": p.get_elements(pared=True)} com = calculate_centre_of_mass(mesh) for i, val in enumerate([9.5, -2.5, 2.5]): self.assertAlmostEqual(val, com[i]) def test_translate_basic(self): mesh = {"points": [[0, 0, 0], [3, 0, 0], [0, 4, 0]], "elements": [[0, 1, 2]]} translated_mesh = translate(mesh, [0.5, 0.5, 0]) com = calculate_centre_of_mass(translated_mesh) for i, val in enumerate([1.5, 1.833333333333, 0]): self.assertAlmostEqual(val, com[i]) def test_translate(self): p = MeshParser() p.parse(os.path.join(file_path, "data/cylinder.stl")) points = p.get_points(True) self.assertEqual(40, len(points)) mesh = {"points": points, "elements": p.get_elements(pared=True)} translated_mesh = translate(mesh, [-9.5, 2.5, -2.5]) com = calculate_centre_of_mass(translated_mesh) for i, val in enumerate([0, 0, 0]): self.assertAlmostEqual(val, com[i]) def test_rotate_basic(self): mesh = {"points": [[0, 0, 0], [3, 0, 0], [0, 4, 0]], "elements": [[0, 1, 2]]} rotated_mesh = rotate(mesh, [0, 0, 1], 90) com = calculate_centre_of_mass(rotated_mesh) for i, val in enumerate([1.333333333333, -1, 0]): self.assertAlmostEqual(val, com[i]) def test_rotate(self): p = MeshParser() p.parse(os.path.join(file_path, "data/cylinder.stl")) points = p.get_points(True) self.assertEqual(40, len(points)) mesh = {"points": points, "elements": p.get_elements(pared=True)} translated_mesh = translate(mesh, [-9.5, 2.5, -2.5]) rotated_mesh = rotate(translated_mesh, [-1, 0, 0], 90) com = calculate_centre_of_mass(rotated_mesh) for i, val in enumerate([0, 0, 0]): self.assertAlmostEqual(val, com[i])
class ManipulationTestCase(unittest.TestCase): def test_com_basic(self): pass def test_com_basic(self): pass def test_translate_basic(self): pass def test_translate_basic(self): pass def test_rotate_basic(self): pass def test_rotate_basic(self): pass
7
0
10
2
8
0
2
0
1
2
1
0
6
0
6
78
64
17
47
35
40
0
47
35
40
2
2
1
11
1,660
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._FFloat
class _FFloat(_BaseFloat): """ Float based colour. """ def __init__(self): super(_FFloat, self).__init__(1)
class _FFloat(_BaseFloat): ''' Float based colour. ''' def __init__(self): pass
2
1
2
0
2
0
1
1
1
1
0
0
1
0
1
13
6
0
3
2
1
3
3
2
1
1
3
0
1
1,661
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._FColour
class _FColour(_BaseFloat): """ Float based colour. """ def __init__(self): super(_FColour, self).__init__(3)
class _FColour(_BaseFloat): ''' Float based colour. ''' def __init__(self): pass
2
1
2
0
2
0
1
1
1
1
0
0
1
0
1
13
6
0
3
2
1
3
3
2
1
1
3
0
1
1,662
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._CoordinateNode
class _CoordinateNode(_BaseNode): """ Coordinate node. Has one optional field. """ def __init__(self): super(_CoordinateNode, self).__init__() self._name = 'Coordinate' self._fields = ['point'] self._field_types = ['MFVec3f']
class _CoordinateNode(_BaseNode): ''' Coordinate node. Has one optional field. ''' def __init__(self): pass
2
1
5
0
5
0
1
0.5
1
1
0
0
1
3
1
13
9
0
6
5
4
3
6
5
4
1
2
0
1
1,663
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/stlparser/parser.py
meshparser.stlparser.parser.STLParser
class STLParser(BaseParser): def __init__(self): super(STLParser, self).__init__() def can_parse(self, filename): parseable = False if is_zipfile(filename): with ZipFile(filename) as stlzip: zipinfolist = stlzip.infolist() if len(zipinfolist) == 1: zipinfo = zipinfolist[0] data = stlzip.read(zipinfo.filename) # Try and determine if this is an ASCII zipped file or binary zipped file. first_bytes = data[:90] if _is_ascii_stl(first_bytes) or _is_binary_stl(first_bytes): parseable = True else: with open(filename, 'rb') as f: first_bytes = f.read(90) parseable = _is_ascii_stl(first_bytes) return parseable def parse(self, filename): self._clear() if is_zipfile(filename): with ZipFile(filename) as stlzip: zipinfolist = stlzip.infolist() if len(zipinfolist) == 1: zipinfo = zipinfolist[0] data = stlzip.read(zipinfo.filename) first_bytes = data[:90] if _is_ascii_stl(first_bytes): lines = data.decode("utf-8").split('\n') self._parse_ascii(lines) elif _is_binary_stl(first_bytes): self._parse_binary(data) else: bin_parseable = False with open(filename, 'rb') as f: first_bytes = f.read(90) ascii_parseable = _is_ascii_stl(first_bytes) if not ascii_parseable: bin_parseable = _is_binary_stl(first_bytes) if ascii_parseable: with open(filename) as f: lines = f.readlines() self._parse_ascii(lines) elif bin_parseable: with open(filename, 'rb') as f: data = f.read() self._parse_binary(data) def _parse_ascii(self, lines): node_indexes = None lines.pop(0) # Remove header line lines.pop() # remove end solid for line in lines: line = line.strip() if line.startswith('facet'): node_indexes = [] elif line.startswith('endfacet'): self._elements.append(node_indexes) elif line.startswith('vertex'): components = [v for v in line.split(' ') if v] if len(components) == 4: pt = [float(components[1]), float(components[2]), float(components[3])] node_indexes.append(len(self._points)) self._points.append(pt) else: raise(Exception('Invalid vertex specified.')) def _parse_binary(self, data): start_byte = 0 end_byte = 80 _ = data[start_byte:end_byte] # header data start_byte = end_byte end_byte += 4 facet_count = struct.unpack('I', data[start_byte:end_byte])[0] for _ in range(facet_count): start_byte = end_byte end_byte = start_byte + 50 element_info = struct.unpack('ffffffffffffH', data[start_byte:end_byte]) pt1 = [element_info[3], element_info[4], element_info[5]] pt1_index = len(self._points) self._points.append(pt1) pt2 = [element_info[6], element_info[7], element_info[8]] pt2_index = len(self._points) self._points.append(pt2) pt3 = [element_info[9], element_info[10], element_info[11]] pt3_index = len(self._points) self._points.append(pt3) self._elements.append([pt1_index, pt2_index, pt3_index])
class STLParser(BaseParser): def __init__(self): pass def can_parse(self, filename): pass def parse(self, filename): pass def _parse_ascii(self, lines): pass def _parse_binary(self, data): pass
6
0
18
1
17
1
4
0.05
1
5
0
0
5
0
5
11
96
8
87
37
81
4
80
33
74
8
2
4
21
1,664
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/exceptions.py
meshparser.exceptions.ParseError
class ParseError(Exception): """ Error encountered when parsing file exception. """
class ParseError(Exception): ''' Error encountered when parsing file exception. ''' pass
1
1
0
0
0
0
0
3
1
0
0
0
0
0
0
10
4
0
1
1
0
3
1
1
0
0
3
0
0
1,665
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser.VRMLParser
class VRMLParser(BaseParser): def __init__(self): super(VRMLParser, self).__init__() self._data = {} def can_parse(self, filename): with open(filename) as f: lines = f.readlines() header_line = lines.pop(0) parseable = _check_header(header_line) return parseable def parse(self, filename): self._clear() scene = _VRMLScene() with open(filename) as f: lines = f.readlines() header_line = lines.pop(0) if not _check_header(header_line): raise ParseError('Header check failed') while lines: current_line = lines.pop(0) current_line = _remove_comment(current_line) line_elements = current_line.strip().split() while len(line_elements): scene.parse(line_elements) self._data = scene.get_root() self._points = self._extract_points() self._elements = self._extract_elements() def _get_indexed_face_set(self): indexed_face_set = None if 'Transform' in self._data and 'children' in self._data['Transform']: if isinstance(self._data['Transform']['children'], list): shapes = self._data['Transform']['children'] if len(shapes) > 1: ParseError('Allow for more than two shapes in a single Transform.') shape = shapes[0] if 'Shape' in shape and 'geometry' in shape['Shape'] and 'IndexedFaceSet' in shape['Shape']['geometry']: indexed_face_set = shape['Shape']['geometry']['IndexedFaceSet'] return indexed_face_set def _extract_points(self): points = [] indexed_face_set = self._get_indexed_face_set() if indexed_face_set is not None and 'coord' in indexed_face_set and 'Coordinate' in indexed_face_set['coord']: coordinates = indexed_face_set['coord']['Coordinate'] if 'point' in coordinates: points = coordinates['point'] return points def _extract_elements(self): elements = [] indexed_face_set = self._get_indexed_face_set() if indexed_face_set is not None and 'coordIndex' in indexed_face_set: coordinate_indexes = indexed_face_set['coordIndex'] elements = _convert_to_element_list(coordinate_indexes) return elements
class VRMLParser(BaseParser): def __init__(self): pass def can_parse(self, filename): pass def parse(self, filename): pass def _get_indexed_face_set(self): pass def _extract_points(self): pass def _extract_elements(self): pass
7
0
10
1
9
0
3
0
1
4
2
0
6
3
6
12
67
14
53
29
46
0
53
27
46
5
2
3
16
1,666
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._BaseNode
class _BaseNode(_BaseParse): """ Base node for all nodes. """ def __init__(self): super(_BaseNode, self).__init__() self._name = '' self._active_field = None self._field_parser = None self._fields = [] self._field_types = [] self._open_marker = '{' self._close_marker = '}' def clear(self): self._active_field = None self._field_parser = None def get_name(self): return self._name def is_open_marker(self, marker): return marker == self._open_marker def is_close_marker(self, marker): return marker == self._close_marker def get_parser(self, field_name): index = self._fields.index(field_name) field_type = self._field_types[index] if field_type in ['SFString', 'MFString']: parser = _FString() elif field_type in ['SFVec3f', 'MFVec3f']: parser = _FVec3f() elif field_type in ['SFRotation']: parser = _FRotation() elif field_type in ['SFFloat']: parser = _FFloat() elif field_type in ['SFColour']: parser = _FColour() elif field_type in ['SFNode', 'MFNode']: parser = _FNode() elif field_type in ['MFInt32']: parser = _FInt32() else: raise ParseError('Unknown field type: "{0}".'.format(field_type)) return parser def add_data(self, key, data): self._data[key] = data def parse(self, line_elements): while line_elements and not self.is_finished(): element = line_elements[0] consume = True if self.is_open_marker(element): self._data = {} elif self._active_field is not None: consume = False self._field_parser.parse(line_elements) if self._field_parser.is_finished(): self.add_data(self._active_field, self._field_parser.get_data()) self.clear() elif self.is_close_marker(element): self.set_finished() else: self._active_field = element self._field_parser = self.get_parser(element) if consume: line_elements.pop(0)
class _BaseNode(_BaseParse): ''' Base node for all nodes. ''' def __init__(self): pass def clear(self): pass def get_name(self): pass def is_open_marker(self, marker): pass def is_close_marker(self, marker): pass def get_parser(self, field_name): pass def add_data(self, key, data): pass def parse(self, line_elements): pass
9
1
8
0
7
0
3
0.05
1
9
8
8
8
8
8
12
72
9
60
22
51
3
50
22
41
8
1
3
21
1,667
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._BaseMultiAble
class _BaseMultiAble(_BaseParse): """ Base class for classes that are able to parse multiple or single items. """ def __init__(self): super(_BaseMultiAble, self).__init__() self._multi = False self._open_marker = '[' self._close_marker = ']' def set_multi(self, state=True): self._multi = state def is_multi(self): return self._multi def is_open_marker(self, marker): return marker == self._open_marker def is_close_marker(self, marker): return marker == self._close_marker def add_data(self, data): if self._multi: self._data.append(data) else: self._data = data
class _BaseMultiAble(_BaseParse): ''' Base class for classes that are able to parse multiple or single items. ''' def __init__(self): pass def set_multi(self, state=True): pass def is_multi(self): pass def is_open_marker(self, marker): pass def is_close_marker(self, marker): pass def add_data(self, data): pass
7
1
3
0
3
0
1
0.16
1
1
0
4
6
4
6
10
27
5
19
11
12
3
18
11
11
2
1
1
7
1,668
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._BaseInt
class _BaseInt(_BaseMultiAble): """ Parses a set number of floats. """ def __init__(self): super(_BaseInt, self).__init__() def parse(self, line_elements): while line_elements and not self.is_finished(): element = line_elements.pop(0) if self._data is None: self._data = [] if self.is_open_marker(element): self._multi = True elif self.is_close_marker(element): self._finished = True else: if element[-1] == ',': element = element[:-1] self.add_data(int(element)) if not self._multi: self.set_finished()
class _BaseInt(_BaseMultiAble): ''' Parses a set number of floats. ''' def __init__(self): pass def parse(self, line_elements): pass
3
1
10
1
9
0
4
0.17
1
2
0
1
2
3
2
12
24
3
18
7
15
3
16
7
13
7
2
3
8
1,669
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._BaseFloat
class _BaseFloat(_BaseMultiAble): """ Parses a set number of floats. """ def __init__(self, float_count=3): super(_BaseFloat, self).__init__() self._float_count = float_count self._current = [] def parse(self, line_elements): while line_elements and not self.is_finished(): element = line_elements.pop(0) if self._data is None: self._data = [] if self.is_open_marker(element): self._multi = True elif self.is_close_marker(element): self._finished = True else: if element[-1] == ',': element = element[:-1] self._current.append(float(element)) if len(self._current) == self._float_count: self.add_data(self._current) self._current = [] if not self._multi: self.set_finished()
class _BaseFloat(_BaseMultiAble): ''' Parses a set number of floats. ''' def __init__(self, float_count=3): pass def parse(self, line_elements): pass
3
1
12
1
11
0
5
0.13
1
2
0
4
2
5
2
12
28
2
23
9
20
3
21
9
18
8
2
4
9
1,670
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._AppearanceNode
class _AppearanceNode(_BaseNode): """ Shape node. Has two optional fields. """ def __init__(self): super(_AppearanceNode, self).__init__() self._name = 'Appearance' self._fields = ['material', 'texture', 'textureTransform'] self._field_types = ['MFNode', 'MFNode', 'MFNode']
class _AppearanceNode(_BaseNode): ''' Shape node. Has two optional fields. ''' def __init__(self): pass
2
1
5
0
5
0
1
0.5
1
1
0
0
1
3
1
13
9
0
6
5
4
3
6
5
4
1
2
0
1
1,671
ABI-Software/MeshParser
ABI-Software_MeshParser/tests/vtkparser/test_parser.py
tests.vtkparser.test_parser.ParserTestCase
class ParserTestCase(unittest.TestCase): def testExistence(self): v = VTKParser() self.assertRaises(IOError, v.parse, 'file that doesnt exist') def testParse1(self): v = VTKParser() test_filename = os.path.join(file_path, 'data/cardiac_jelly.vtk') self.assertTrue(v.can_parse(test_filename)) v.parse(test_filename) def testParse2(self): v = VTKParser() v.parse(os.path.join(file_path, 'data/cardiac_jelly.vtk')) self.assertEqual(1170, len(v.get_points())) self.assertEqual(2314, len(v.get_elements())) def testOldFormat(self): v = VTKParser() test_filename = os.path.join(file_path, 'data/old_format.vtk') self.assertFalse(v.can_parse(test_filename)) self.assertRaises(SyntaxError, v.parse, test_filename) def testBinaryFormat(self): v = VTKParser() self.assertRaises(NotImplementedError, v.parse, os.path.join(file_path, 'data/fake_binary_format.vtk'))
class ParserTestCase(unittest.TestCase): def testExistence(self): pass def testParse1(self): pass def testParse2(self): pass def testOldFormat(self): pass def testBinaryFormat(self): pass
6
0
4
0
4
0
1
0
1
3
1
0
5
0
5
77
28
6
22
13
16
0
22
13
16
1
2
0
5
1,672
ABI-Software/MeshParser
ABI-Software_MeshParser/tests/test_printer.py
tests.test_printer.PrinterTestCase
class PrinterTestCase(unittest.TestCase): def test_print_basic(self): mesh = {"points": [[0, 0, 0], [3, 0, 0], [0, 4, 0]], "elements": [[0, 1, 2]]} translated_mesh = translate(mesh, [0.5, 0.5, 0]) com = calculate_centre_of_mass(translated_mesh) for i, val in enumerate([1.5, 1.833333333333, 0]): self.assertAlmostEqual(val, com[i]) filename = os.path.join(file_path, "data/translated_triangle.stl") print_mesh(translated_mesh, filename) self.assertTrue(filename) os.remove(filename) def test_print(self): p = MeshParser() p.parse(os.path.join(file_path, "data/cylinder.stl")) points = p.get_points(True) self.assertEqual(40, len(points)) mesh = {"points": points, "elements": p.get_elements(pared=True)} translated_mesh = translate(mesh, [-9.5, 2.5, -2.5]) rotated_mesh = rotate(translated_mesh, [-1, 0, 0], 90) shifted_mesh = translate(rotated_mesh, [0.75, 0, 0]) filename = os.path.join(file_path, "data/transformed_cylinder.stl") print_mesh(shifted_mesh, filename) self.assertTrue(filename) os.remove(filename)
class PrinterTestCase(unittest.TestCase): def test_print_basic(self): pass def test_print_basic(self): pass
3
0
16
5
12
0
2
0
1
2
1
0
2
0
2
74
35
11
24
15
21
0
24
15
21
2
2
1
3
1,673
ABI-Software/MeshParser
ABI-Software_MeshParser/src/meshparser/vrmlparser/parser.py
meshparser.vrmlparser.parser._BaseParse
class _BaseParse: """ Base object for all parseable classes. """ def __init__(self): self._finished = False self._data = None def is_finished(self): return self._finished def set_finished(self, state=True): self._finished = state def get_data(self): return self._data
class _BaseParse: ''' Base object for all parseable classes. ''' def __init__(self): pass def is_finished(self): pass def set_finished(self, state=True): pass def get_data(self): pass
5
1
2
0
2
0
1
0.3
0
0
0
2
4
2
4
4
16
3
10
7
5
3
10
7
5
1
0
0
4
1,674
AKSW/SemanticPingbackPy
AKSW_SemanticPingbackPy/semanticpingback.py
semanticpingback.SemanticPingbackReceiver
class SemanticPingbackReceiver(): def __init__(self, baseuri=None, target_allow_external=True, pingback_callback=None, del_pingback_callback=None): self.baseuri = baseuri self.target_allow_external = target_allow_external self.pingback_callback = pingback_callback self.del_pingback_callback = del_pingback_callback logger.debug("Init SemanticPingback") def receivePing(self, source=None, target=None, comment=None, request=None): if request: source = request.values.get("source", None) target = request.values.get("target", None) comment = request.values.get("comment", None) if not source: raise PingException("No source resource given") if not target: raise PingException("No source resource given") try: sourceIri = rdflib.term.URIRef(source) targetIri = rdflib.term.URIRef(target) except Exception as e: raise PingException("Given target resource is not a valid URI.") if not self.target_allow_external: if urllib.parse.urlparse(self.baseuri).netloc != urllib.parse.urlparse(targetIri).netloc: raise PingException("Given target is not from this server (disallowed by config).") links = self.getLinkFromSource(sourceIri, targetIri) if not len(links): if self.del_pingback_callback: self.del_pingback_callback(sourceIri, targetIri, comment) else: if self.pingback_callback: self.pingback_callback(sourceIri, targetIri, links, comment) return links def getLinkFromSource(self, source, target): graph = rdflib.Graph() linkGraph = rdflib.Graph() try: self._load(graph, source) links = graph.triples((source, None, target)) linkGraph += links if len(linkGraph): return linkGraph except Exception as e: logger.debug(e) pass # TODO if graph is empty try loading RDFa # TODO if graph is still empty load html and try to extract hyperlinks # for each found html link to the target create a triple: # source http://rdfs.org/sioc/ns#links_to target raise PingException("No links in source document.") def _load(self, graph, source): """from https://rdflib.readthedocs.io/en/stable/_modules/rdflib/plugins/sparql/sparql.html""" try: return graph.load(source) except: pass try: return graph.load(source, format='n3') except: pass try: return graph.load(source, format='nt') except: raise Exception("Could not load {} as either RDF/XML, N3 or NTriples".format(source))
class SemanticPingbackReceiver(): def __init__(self, baseuri=None, target_allow_external=True, pingback_callback=None, del_pingback_callback=None): pass def receivePing(self, source=None, target=None, comment=None, request=None): pass def getLinkFromSource(self, source, target): pass def _load(self, graph, source): '''from https://rdflib.readthedocs.io/en/stable/_modules/rdflib/plugins/sparql/sparql.html''' pass
5
1
17
1
15
1
5
0.08
0
2
1
0
4
4
4
4
70
6
59
18
53
5
57
15
52
10
0
2
18
1,675
AKSW/SemanticPingbackPy
AKSW_SemanticPingbackPy/semanticpingback.py
semanticpingback.PingException
class PingException(Exception): pass
class PingException(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
1,676
AN3223/fpbox
AN3223_fpbox/fpbox/types.py
fpbox.types.Char
class Char: """Holds a single character""" def __init__(self, char): if isinstance(char, str) and len(char) == 1: self.char = char else: raise FPboxException("Invalid input, Chars must be str with a length of 1") def __repr__(self): return "'{}'".format(self.char) def __str__(self): return self.char def __add__(self, other): return self.char + other
class Char: '''Holds a single character''' def __init__(self, char): pass def __repr__(self): pass def __str__(self): pass def __add__(self, other): pass
5
1
3
0
3
0
1
0.08
0
2
1
0
4
1
4
4
17
4
12
6
7
1
11
6
6
2
0
1
5
1,677
AN3223/fpbox
AN3223_fpbox/fpbox/types.py
fpbox.types.FPboxException
class FPboxException(Exception): pass
class FPboxException(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
1,678
AN3223/fpbox
AN3223_fpbox/test/test_suite.py
test_suite.TestBox
class TestBox(unittest.TestCase): def test_partition(self): def quicksort(xs): if len(xs) > 1: pivot = fp.head(xs) lesser, greater = map(quicksort, fp.partition(lambda x: x < pivot, fp.tail(xs))) return lesser + [pivot] + greater else: return xs self.assertEqual(quicksort([5, 4, 3, 2, 1]), [1, 2, 3, 4, 5]) def test_stream(self): xs = fp.Array(1, 2, 3, 4, 5) xs_mapped = fp.Stream(xs).map(lambda x: x + 1).list() self.assertEqual(xs_mapped, [x + 1 for x in xs]) def less_than_four(x): return x < 4 xs_takewhile = fp.Stream(xs).takewhile(less_than_four).list() self.assertEqual(xs_takewhile, list(takewhile(less_than_four, xs))) xs_dropwhile = fp.Stream(xs).dropwhile(less_than_four).list() self.assertEqual(xs_dropwhile, list(dropwhile(less_than_four, xs))) def test_binmap(self): from operator import sub xs = [10, 15, 20, 25, 30] self.assertEqual(fp.reverse_binmap(sub, xs), [5, 5, 5, 5]) def test_chars(self): self.assertEqual(str(fp.chars('hello')), 'hello') def test_compose(self): fs = [lambda x: x + 1, lambda x: x * 100] f = fp.compose(fs) self.assertEqual(f(1), 101) f = fp.compose(*fs) self.assertEqual(f(1), 101) def test_curry(self): def test(x, y): return x, y f = fp.curry(test) f10 = f(10) f20 = f(20) self.assertEqual(f10(20), (10, 20)) self.assertEqual(f20(10), (20, 10)) def test_collect(self): def genericfunction(*items): return fp.collect(items) xs = (1,2,3,4) self.assertEqual(xs, genericfunction(xs)) self.assertEqual(xs, genericfunction(list(xs))) self.assertEqual(xs, genericfunction((x for x in xs)))
class TestBox(unittest.TestCase): def test_partition(self): pass def quicksort(xs): pass def test_stream(self): pass def less_than_four(x): pass def test_binmap(self): pass def test_chars(self): pass def test_compose(self): pass def test_curry(self): pass def test_partition(self): pass def test_collect(self): pass def genericfunction(*items): pass
12
0
6
1
5
0
1
0
1
7
2
0
7
0
7
79
64
17
47
26
34
0
46
26
33
2
2
1
12
1,679
AN3223/fpbox
AN3223_fpbox/fpbox/types.py
fpbox.types.Array
class Array(Sequence): """ Immutable homogenous collection. It can be initialized with either a single list/tuple/generator (which will return an Array consisting of the contents of said list/tuple/generator) or it can just be given multiple arguments to initialize the Array with """ def __init__(self, *items): self.items = collect(items) self.type = type(head(self.items)) if False in (isinstance(x, self.type) for x in self.items): raise FPboxException("You can't mix types in an Array") def __repr__(self): if self.type == Char: # Creates a representation of [Char] unpacked_chars = [x.char for x in self.items] return '"{}"'.format(sum(unpacked_chars)) else: return str(list(self.items)) def __str__(self): if self.type == Char: return self.__repr__()[1:-1] return self.__repr__() def __add__(self, other): if isinstance(other, Array): other = other.items return Array(self.items + tuple(other)) def __getitem__(self, item): return self.items[item] def __len__(self): return len(self.items)
class Array(Sequence): ''' Immutable homogenous collection. It can be initialized with either a single list/tuple/generator (which will return an Array consisting of the contents of said list/tuple/generator) or it can just be given multiple arguments to initialize the Array with ''' def __init__(self, *items): pass def __repr__(self): pass def __str__(self): pass def __add__(self, other): pass def __getitem__(self, item): pass def __len__(self): pass
7
1
4
0
4
0
2
0.29
1
5
2
0
6
2
6
41
36
6
24
10
17
7
23
10
16
2
6
1
10
1,680
AN3223/fpbox
AN3223_fpbox/fpbox/types.py
fpbox.types.Stream
class Stream: """ Takes any iterable, returns a Stream object that gives access to a set of lazy (FP-related) methods. Some things to note: no methods mutate the iterable, most methods return a Stream object, and the Stream objects themselves are generators that yield the contents of the original iterable """ def __init__(self, xs): self.xs = xs def __iter__(self): return (x for x in self.xs) def map(self, f): return Stream(lazymap(f, self)) def filter(self, f): return Stream(lazyfilter(f, self)) def reduce(self, f): return Stream(lazy_reduce(f, self)) def takewhile(self, f): return Stream(takewhile(f, self)) def dropwhile(self, f): return Stream(dropwhile(f, self)) def list(self): """Packs the stream up into a list""" return list(self) def tuple(self): """Packs the stream up into a tuple""" return tuple(self)
class Stream: ''' Takes any iterable, returns a Stream object that gives access to a set of lazy (FP-related) methods. Some things to note: no methods mutate the iterable, most methods return a Stream object, and the Stream objects themselves are generators that yield the contents of the original iterable ''' def __init__(self, xs): pass def __iter__(self): pass def map(self, f): pass def filter(self, f): pass def reduce(self, f): pass def takewhile(self, f): pass def dropwhile(self, f): pass def list(self): '''Packs the stream up into a list''' pass def tuple(self): '''Packs the stream up into a tuple''' pass
10
3
2
0
2
0
1
0.47
0
2
0
0
9
1
9
9
37
9
19
11
9
9
19
11
9
1
0
0
9
1,681
ANCIR/granoloader
ANCIR_granoloader/granoloader/mapping.py
granoloader.mapping.ObjectMapper
class ObjectMapper(object): def __init__(self, name, model): self.name = name self.model = model def convert_type(self, value, spec): """ Some well-educated format guessing. """ data_type = spec.get('type', 'string').lower().strip() if data_type in ['bool', 'boolean']: return value.lower() in BOOL_TRUISH elif data_type in ['int', 'integer']: try: return int(value) except (ValueError, TypeError): return None elif data_type in ['float', 'decimal', 'real']: try: return float(value) except (ValueError, TypeError): return None elif data_type in ['date', 'datetime', 'timestamp']: if 'format' in spec: format_list = self._get_date_format_list(spec.get('format')) if format_list is None: raise MappingException( '%s format mapping is not valid: %r' % (spec.get('column'), spec.get('format')) ) for format, precision in format_list: try: return {'value': datetime.strptime(value, format), 'value_precision': precision} except (ValueError, TypeError): pass return None else: try: return parser.parse(value) except (ValueError, TypeError): return None elif data_type == 'file': try: return self._get_file(value) except: raise return value def _get_date_format_list(self, format_value, precision=None): if isinstance(format_value, basestring): return [(format_value, precision)] elif isinstance(format_value, list): return [(fv, precision) for fv in format_value] elif isinstance(format_value, dict): format_list = [] # try the most precise format first for key in ('time', 'day', 'month', 'year'): if key not in format_value: continue format_list.extend(self._get_date_format_list( format_value[key], precision=key )) return format_list return None @property def columns(self): for column in self.model.get('columns'): if 'default' in column: column['required'] = False if column.get('skip_empty'): column['required'] = False yield self._patch_column(column) def _patch_column(self, column): return column def _get_file(self, url): response = requests.get(url) file_like_obj = StringIO(response.content) file_like_obj.name = url return file_like_obj def get_value(self, spec, row): """ Returns the value or a dict with a 'value' entry plus extra fields. """ column = spec.get('column') default = spec.get('default') if column is None: if default is not None: return self.convert_type(default, spec) return value = row.get(column) if is_empty(value): if default is not None: return self.convert_type(default, spec) return None return self.convert_type(value, spec) def get_source(self, spec, row): """ Sources can be specified as plain strings or as a reference to a column. """ value = self.get_value({'column': spec.get('source_url_column')}, row) if value is not None: return value return spec.get('source_url') def load_properties(self, obj, row): source_url = self.get_source(self.model, row) for column in self.columns: col_source_url = self.get_source(column, row) col_source_url = col_source_url or source_url value = self.get_value(column, row) extra_fields = {} if isinstance(value, dict): extra_fields = value value = extra_fields.get('value') del extra_fields['value'] if value is None and column.get('required', True): raise RowException('%s is not valid: %s' % ( column.get('column'), row.get(column.get('column')))) if value is None and column.get('skip_empty', False): continue obj.set(column.get('property'), value, source_url=source_url, **extra_fields) if column.get('unique', False): obj.unique(column.get('property'), only_active=column.get('unique_active', True))
class ObjectMapper(object): def __init__(self, name, model): pass def convert_type(self, value, spec): ''' Some well-educated format guessing. ''' pass def _get_date_format_list(self, format_value, precision=None): pass @property def columns(self): pass def _patch_column(self, column): pass def _get_file(self, url): pass def get_value(self, spec, row): ''' Returns the value or a dict with a 'value' entry plus extra fields. ''' pass def get_source(self, spec, row): ''' Sources can be specified as plain strings or as a reference to a column. ''' pass def load_properties(self, obj, row): pass
11
3
13
0
12
0
4
0.04
1
9
2
2
9
2
9
9
131
13
114
30
103
4
96
29
86
14
1
4
40
1,682
ANCIR/granoloader
ANCIR_granoloader/granoloader/mapping.py
granoloader.mapping.EntityMapper
class EntityMapper(ObjectMapper): def load(self, loader, row): source_url = self.get_source(self.model, row) entity = loader.make_entity(self.model.get('schema'), source_url=source_url) self.load_properties(entity, row) if entity.properties.get('name', None) is None: return entity.save() return entity def _patch_column(self, column): if column.get('property') == 'name': column['unique'] = True column['unique_active'] = False return column
class EntityMapper(ObjectMapper): def load(self, loader, row): pass def _patch_column(self, column): pass
3
0
7
0
7
0
2
0
1
0
0
0
2
0
2
11
17
2
15
5
12
0
14
5
11
2
2
1
4
1,683
ANCIR/granoloader
ANCIR_granoloader/granoloader/mapping.py
granoloader.mapping.MappingException
class MappingException(Exception): pass
class MappingException(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
1,684
ANCIR/granoloader
ANCIR_granoloader/granoloader/mapping.py
granoloader.mapping.MappingLoader
class MappingLoader(object): def __init__(self, grano, model): self.grano = grano self.loader = Loader(grano, source_url=model.get('source_url')) self.model = model @property def entities(self): for name, model in self.model.get('entities', {}).items(): yield EntityMapper(name, model) @property def relations(self): for name, model in self.model.get('relations', {}).items(): yield RelationMapper(name, model) def load(self, data): """ Load a single row of data and convert it into entities and relations. """ objs = {} for mapper in self.entities: objs[mapper.name] = mapper.load(self.loader, data) for mapper in self.relations: objs[mapper.name] = mapper.load(self.loader, data, objs)
class MappingLoader(object): def __init__(self, grano, model): pass @property def entities(self): pass @property def relations(self): pass def load(self, data): ''' Load a single row of data and convert it into entities and relations. ''' pass
7
1
5
0
4
1
2
0.11
1
2
2
0
4
3
4
4
26
5
19
14
12
2
17
12
12
3
1
1
8
1,685
ANCIR/granoloader
ANCIR_granoloader/granoloader/mapping.py
granoloader.mapping.RelationMapper
class RelationMapper(ObjectMapper): def load(self, loader, row, objs): source_url = self.get_source(self.model, row) source = objs.get(self.model.get('source')) target = objs.get(self.model.get('target')) if None in [source, target]: return relation = loader.make_relation(self.model.get('schema'), source, target, source_url=source_url) self.load_properties(relation, row) relation.save() return relation
class RelationMapper(ObjectMapper): def load(self, loader, row, objs): pass
2
0
12
0
12
0
2
0
1
0
0
0
1
0
1
10
14
1
13
6
11
0
11
6
9
2
2
1
2
1,686
ANCIR/granoloader
ANCIR_granoloader/granoloader/mapping.py
granoloader.mapping.RowException
class RowException(Exception): pass
class RowException(Exception): pass
1
0
0
0
0
0
0
0
1
0
0
0
0
0
0
10
2
0
2
1
1
0
2
1
1
0
3
0
0
1,687
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_sitk_to_ants
class TestModule_sitk_to_ants(unittest.TestCase): def setUp(self): shape = (32, 24, 16) self.img = sitk.GetImageFromArray(np.arange(np.prod(shape), dtype=float).reshape(shape)) self.img.SetSpacing([0.5, 0.5, 2.0]) self.img.SetOrigin([1.2, 5.7, -3.4]) self.img.SetDirection(sitk.VersorTransform([1, 0, 0], 0.5).GetMatrix()) def tearDown(self): pass def test_from_sitk(self): ants_img = ants.from_sitk(self.img) with TemporaryDirectory() as temp_dir: temp_fpath = os.path.join(temp_dir, "img.nrrd") ants.image_write(ants_img, temp_fpath) img = sitk.ReadImage(temp_fpath) nptest.assert_equal( sitk.GetArrayViewFromImage(self.img), sitk.GetArrayViewFromImage(img) ) nptest.assert_almost_equal(self.img.GetOrigin(), img.GetOrigin()) nptest.assert_almost_equal(self.img.GetSpacing(), img.GetSpacing()) nptest.assert_almost_equal(self.img.GetDirection(), img.GetDirection()) def test_ito_sitk(self): with TemporaryDirectory() as temp_dir: temp_fpath = os.path.join(temp_dir, "img.nrrd") sitk.WriteImage(self.img, temp_fpath) ants_img = ants.image_read(temp_fpath) img = ants.to_sitk(ants_img) nptest.assert_equal( sitk.GetArrayViewFromImage(self.img), sitk.GetArrayViewFromImage(img) ) nptest.assert_almost_equal(self.img.GetOrigin(), img.GetOrigin()) nptest.assert_almost_equal(self.img.GetSpacing(), img.GetSpacing()) nptest.assert_almost_equal(self.img.GetDirection(), img.GetDirection())
class TestModule_sitk_to_ants(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_from_sitk(self): pass def test_ito_sitk(self): pass
5
0
9
1
8
0
1
0
1
2
0
0
4
1
4
76
40
7
33
15
28
0
29
13
24
1
2
1
4
1,688
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_smooth_image
class TestModule_smooth_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_smooth_image_example(self): image = ants.image_read(ants.get_ants_data("r16")) simage = ants.smooth_image(image, (1.2, 1.5))
class TestModule_smooth_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_smooth_image_example(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
0
3
75
10
2
8
6
4
0
8
6
4
1
2
0
3
1,689
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_threshold_image
class TestModule_threshold_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_threshold_image_example(self): image = ants.image_read(ants.get_ants_data("r16")) timage = ants.threshold_image(image, 0.5, 1e15)
class TestModule_threshold_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_threshold_image_example(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
0
3
75
10
2
8
6
4
0
8
6
4
1
2
0
3
1,690
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_simulate_displacement_field
class TestModule_simulate_displacement_field(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_simulate_exponential_displacement_field_2d(self): image = ants.image_read(ants.get_ants_data("r16")) exp_field = ants.simulate_displacement_field(image, field_type="exponential") def test_simulate_bspline_displacement_field_2d(self): image = ants.image_read(ants.get_ants_data("r16")) bsp_field = ants.simulate_displacement_field(image, field_type="bspline")
class TestModule_simulate_displacement_field(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_simulate_exponential_displacement_field_2d(self): pass def test_simulate_bspline_displacement_field_2d(self): pass
5
0
3
0
3
0
1
0
1
0
0
0
4
0
4
76
14
3
11
9
6
0
11
9
6
1
2
0
4
1,691
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestRandom
class TestRandom(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_bspline_field(self): points = np.array([[-50, -50]]) deltas = np.array([[10, 10]]) bspline_field = ants.fit_bspline_displacement_field( displacement_origins=points, displacements=deltas, origin=[0.0, 0.0], spacing=[1.0, 1.0], size=[100, 100], direction=np.array([[-1, 0], [0, -1]]), number_of_fitting_levels=4, mesh_size=(1, 1)) def test_quantile(self): img = ants.image_read(ants.get_data('r16')) ants.rank_intensity(img) def test_ilr(self): nsub = 20 mu, sigma = 0, 1 outcome = np.random.normal( mu, sigma, nsub ) covar = np.random.normal( mu, sigma, nsub ) mat = np.random.normal( mu, sigma, (nsub, 500 ) ) mat2 = np.random.normal( mu, sigma, (nsub, 500 ) ) data = {'covar':covar,'outcome':outcome} df = pd.DataFrame( data ) vlist = { "mat1": mat, "mat2": mat2 } myform = " outcome ~ covar * mat1 " result = ants.ilr( df, vlist, myform) myform = " mat2 ~ covar + mat1 " result = ants.ilr( df, vlist, myform) def test_quantile(self): img = ants.image_read(ants.get_data('r16')) ants.quantile(img, 0.5) ants.quantile(img, (0.5, 0.75)) def test_bandpass(self): brainSignal = np.random.randn( 400, 1000 ) tr = 1 filtered = ants.bandpass_filter_matrix( brainSignal, tr = tr ) def test_compcorr(self): cc = ants.compcor( ants.image_read(ants.get_ants_data("ch2")) ) def test_histogram_match(self): src_img = ants.image_read(ants.get_data('r16')) ref_img = ants.image_read(ants.get_data('r64')) src_ref = ants.histogram_match_image(src_img, ref_img) src_img = ants.image_read(ants.get_data('r16')) ref_img = ants.image_read(ants.get_data('r64')) src_ref = ants.histogram_match_image2(src_img, ref_img) def test_averaging(self): x0=[ ants.get_data('r16'), ants.get_data('r27'), ants.get_data('r62'), ants.get_data('r64') ] x1=[] for k in range(len(x0)): x1.append( ants.image_read( x0[k] ) ) avg=ants.average_images(x0) avg1=ants.average_images(x1) avg2=ants.average_images(x1,mask=0) avg3=ants.average_images(x1,mask=1,normalize=True) def test_n3_2(self): image = ants.image_read( ants.get_ants_data('r16') ) image_n3 = ants.n3_bias_field_correction2(image) def test_add_noise(self): image = ants.image_read(ants.get_ants_data('r16')) noise_image = ants.add_noise_to_image(image, 'additivegaussian', (0.0, 1.0)) noise_image = ants.add_noise_to_image(image, 'saltandpepper', (0.1, 0.0, 100.0)) noise_image = ants.add_noise_to_image(image, 'shot', 1.0) noise_image = ants.add_noise_to_image(image, 'speckle', 1.0) def test_hessian_objectness(self): image = ants.image_read(ants.get_ants_data('r16')) hessian = ants.hessian_objectness(image) def test_thin_plate_spline(self): points = np.array([[-50, -50]]) deltas = np.array([[10, 10]]) tps_field = ants.fit_thin_plate_spline_displacement_field( displacement_origins=points, displacements=deltas, origin=[0.0, 0.0], spacing=[1.0, 1.0], size=[100, 100], direction=np.array([[-1, 0], [0, -1]])) def test_multi_label_morph(self): img = ants.image_read(ants.get_data('r16')) labels = ants.get_mask(img,1,150) + ants.get_mask(img,151,225) * 2 labels_dilated = ants.multi_label_morphology(labels, 'MD', 2) # should see original label regions preserved in dilated version # label N should have mean N and 0 variance print(ants.label_stats(labels_dilated, labels)) def test_hausdorff_distance(self): r16 = ants.image_read( ants.get_ants_data('r16') ) r64 = ants.image_read( ants.get_ants_data('r64') ) s16 = ants.kmeans_segmentation( r16, 3 )['segmentation'] s64 = ants.kmeans_segmentation( r64, 3 )['segmentation'] stats = ants.hausdorff_distance(s16, s64) def test_channels_first(self): import ants image = ants.image_read(ants.get_ants_data('r16')) image2 = ants.image_read(ants.get_ants_data('r16')) img3 = ants.merge_channels([image,image2]) img4 = ants.merge_channels([image,image2], channels_first=True) self.assertTrue(np.allclose(img3.numpy()[:,:,0], img4.numpy()[0,:,:])) self.assertTrue(np.allclose(img3.numpy()[:,:,1], img4.numpy()[1,:,:]))
class TestRandom(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_bspline_field(self): pass def test_quantile(self): pass def test_ilr(self): pass def test_quantile(self): pass def test_bandpass(self): pass def test_compcorr(self): pass def test_histogram_match(self): pass def test_averaging(self): pass def test_n3_2(self): pass def test_add_noise(self): pass def test_hessian_objectness(self): pass def test_thin_plate_spline(self): pass def test_multi_label_morph(self): pass def test_hausdorff_distance(self): pass def test_channels_first(self): pass
18
0
6
0
5
0
1
0.02
1
1
0
0
17
0
17
89
113
17
94
70
75
2
87
70
68
2
2
1
18
1,692
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_weingarten_image_curvature
class TestModule_weingarten_image_curvature(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_weingarten_image_curvature_example(self): image = ants.image_read(ants.get_ants_data("mni")).resample_image((3, 3, 3)) imagecurv = ants.weingarten_image_curvature(image) image2 = ants.image_read(ants.get_ants_data("r16")).resample_image((2, 2)) imagecurv2 = ants.weingarten_image_curvature(image2)
class TestModule_weingarten_image_curvature(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_weingarten_image_curvature_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
13
3
10
8
6
0
10
8
6
1
2
0
3
1,693
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_bias_correction
class TestModule_bias_correction(unittest.TestCase): def setUp(self): img2d = ants.image_read(ants.get_ants_data("r16")) img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) self.imgs = [img2d, img3d] def tearDown(self): pass def test_n3_bias_field_correction_example(self): image = ants.image_read(ants.get_ants_data("r16")) image_n3 = ants.n3_bias_field_correction(image) def test_n3_bias_field_correction(self): for img in self.imgs: image_n3 = ants.n3_bias_field_correction(img) def test_n4_bias_field_correction_example(self): image = ants.image_read(ants.get_ants_data("r16")) image_n4 = ants.n4_bias_field_correction(image) # spline param list image_n4 = ants.n4_bias_field_correction(image, spline_param=(10, 10)) # image not float image_ui = image.clone("unsigned int") image_n4 = ants.n4_bias_field_correction(image_ui) # weight mask mask = ants.image_clone(image > image.mean(), pixeltype="float") ants.n4_bias_field_correction(image, weight_mask=mask) # len(spline_param) != img.dimension with self.assertRaises(Exception): ants.n4_bias_field_correction(image, spline_param=(10, 10, 10)) # weight mask not ANTsImage with self.assertRaises(Exception): ants.n4_bias_field_correction(image, weight_mask=0.4) def test_n4_bias_field_correction(self): # def n4_bias_field_correction(image, mask=None, shrink_factor=4, # convergence={'iters':[50,50,50,50], 'tol':1e-07}, # spline_param=200, verbose=False, weight_mask=None): for img in self.imgs: image_n4 = ants.n4_bias_field_correction(img) mask = ants.image_clone(img > img.mean(), pixeltype="float") image_n4 = ants.n4_bias_field_correction(img, mask=mask) def test_abp_n4_example(self): img = ants.image_read(ants.get_ants_data("r16")) img = ants.iMath(img, "Normalize") * 255.0 img2 = ants.abp_n4(img) def test_abp_n4(self): # def abp_n4(image, intensity_truncation=(0.025,0.975,256), mask=None, usen3=False): for img in self.imgs: img2 = ants.abp_n4(img) img3 = ants.abp_n4(img, usen3=True) # intensity trunction doesnt have three values with self.assertRaises(Exception): img = self.imgs[0] ants.abp_n4(img, intensity_truncation=(1, 2))
class TestModule_bias_correction(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_n3_bias_field_correction_example(self): pass def test_n3_bias_field_correction_example(self): pass def test_n4_bias_field_correction_example(self): pass def test_n4_bias_field_correction_example(self): pass def test_abp_n4_example(self): pass def test_abp_n4_example(self): pass
9
0
7
1
5
1
1
0.24
1
1
0
0
8
1
8
80
64
13
41
28
32
10
41
28
32
2
2
1
11
1,694
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_pad_image
class TestModule_pad_image(unittest.TestCase): def setUp(self): self.img2d = ants.image_read(ants.get_ants_data("r16")) self.img3d = ants.image_read(ants.get_ants_data("mni")).resample_image((2, 2, 2)) def tearDown(self): pass def test_pad_image_example(self): img = self.img2d.clone() img.set_origin((0, 0)) img.set_spacing((2, 2)) # isotropic pad via pad_width padded = ants.pad_image(img, pad_width=(10, 10)) self.assertEqual(padded.shape, (img.shape[0] + 10, img.shape[1] + 10)) for img_orig_elem, pad_orig_elem in zip(img.origin, padded.origin): self.assertAlmostEqual(pad_orig_elem, img_orig_elem - 10, places=3) img = self.img2d.clone() img.set_origin((0, 0)) img.set_spacing((2, 2)) img = ants.resample_image(img, (128,128), 1, 1) # isotropic pad via shape padded = ants.pad_image(img, shape=(160,160)) self.assertSequenceEqual(padded.shape, (160, 160)) img = self.img3d.clone() img = ants.resample_image(img, (128,160,96), 1, 1) padded = ants.pad_image(img) self.assertSequenceEqual(padded.shape, (160, 160, 160)) # pad only on superior side img = self.img3d.clone() padded = ants.pad_image(img, pad_width=[(0,4),(0,8),(0,12)]) self.assertSequenceEqual(padded.shape, (img.shape[0] + 4, img.shape[1] + 8, img.shape[2] + 12)) self.assertSequenceEqual(img.origin, padded.origin)
class TestModule_pad_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_pad_image_example(self): pass
4
0
11
1
9
1
1
0.11
1
1
0
0
3
2
3
75
36
5
28
9
24
3
28
9
24
2
2
1
4
1,695
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_ndimage_to_list
class TestModule_ndimage_to_list(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_ndimage_to_list(self): image = ants.image_read(ants.get_ants_data("r16")) image2 = ants.image_read(ants.get_ants_data("r64")) ants.set_spacing(image, (2, 2)) ants.set_spacing(image2, (2, 2)) imageTar = ants.make_image((*image2.shape, 2)) ants.set_spacing(imageTar, (2, 2, 2)) image3 = ants.list_to_ndimage(imageTar, [image, image2]) self.assertEqual(image3.dimension, 3) ants.set_direction(image3, np.eye(3) * 2) images_unmerged = ants.ndimage_to_list(image3) self.assertEqual(len(images_unmerged), 2) self.assertEqual(images_unmerged[0].dimension, 2)
class TestModule_ndimage_to_list(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_ndimage_to_list(self): pass
4
0
6
0
6
0
1
0
1
0
0
0
3
0
3
75
20
2
18
9
14
0
18
9
14
1
2
0
3
1,696
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_morphology
class TestModule_morphology(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_morphology(self): fi = ants.image_read(ants.get_ants_data("r16")) mask = ants.get_mask(fi) dilated_ball = ants.morphology( mask, operation="dilate", radius=3, mtype="binary", shape="ball" ) eroded_box = ants.morphology( mask, operation="erode", radius=3, mtype="binary", shape="box" ) opened_annulus = ants.morphology( mask, operation="open", radius=5, mtype="binary", shape="annulus", thickness=2, ) ## --- ## mtype = "binary" mask = mask.clone() for operation in {"dilate", "erode", "open", "close"}: for shape in {"ball", "box", "cross", "annulus", "polygon"}: morph = ants.morphology( mask, operation=operation, radius=3, mtype=mtype, shape=shape ) self.assertTrue(isinstance(morph, ants.core.ants_image.ANTsImage)) # invalid operation with self.assertRaises(Exception): ants.morphology( mask, operation="invalid-operation", radius=3, mtype=mtype, shape=shape ) mtype = "grayscale" img = ants.image_read(ants.get_ants_data("r16")) for operation in {"dilate", "erode", "open", "close"}: morph = ants.morphology(img, operation=operation, radius=3, mtype=mtype) self.assertTrue(isinstance(morph, ants.core.ants_image.ANTsImage)) # invalid operation with self.assertRaises(Exception): ants.morphology( img, operation="invalid-operation", radius=3, mtype="grayscale" ) # invalid morphology type with self.assertRaises(Exception): ants.morphology( img, operation="dilate", radius=3, mtype="invalid-morphology" ) # invalid shape with self.assertRaises(Exception): ants.morphology( mask, operation="dilate", radius=3, mtype="binary", shape="invalid-shape", )
class TestModule_morphology(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_morphology(self): pass
4
0
21
1
18
2
2
0.09
1
1
0
0
3
0
3
75
66
6
55
14
51
5
30
14
26
4
2
2
6
1,697
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_mni2tal
class TestModule_mni2tal(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_mni2tal_example(self): ants.mni2tal((10, 12, 14))
class TestModule_mni2tal(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_mni2tal_example(self): pass
4
0
2
0
2
0
1
0
1
0
0
0
3
0
3
75
9
2
7
4
3
0
7
4
3
1
2
0
3
1,698
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_mask_image
class TestModule_mask_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_mask_image_example(self): myimage = ants.image_read(ants.get_ants_data("r16")) mask = ants.get_mask(myimage) myimage_mask = ants.mask_image(myimage, mask, (2, 3)) seg = ants.kmeans_segmentation(myimage, 3) myimage_mask = ants.mask_image(myimage, seg["segmentation"], (1, 3))
class TestModule_mask_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_mask_image_example(self): pass
4
0
3
0
3
0
1
0
1
0
0
0
3
0
3
75
13
2
11
8
7
0
11
8
7
1
2
0
3
1,699
ANTsX/ANTsPy
tests/test_utils.py
test_utils.TestModule_make_points_image
class TestModule_make_points_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_make_points_image_example(self): image = ants.image_read(ants.get_ants_data("r16")) points = np.array([[102, 76],[134, 129]]) points_image = ants.make_points_image(points, image, radius=5) stats = ants.label_stats(image, points_image) self.assertTrue(np.allclose(stats['Volume'].to_numpy()[1:3], 97.0, atol=1e-5)) self.assertTrue(np.allclose(stats['x'].to_numpy()[1:3], points[:,0], atol=1e-5)) self.assertTrue(np.allclose(stats['y'].to_numpy()[1:3], points[:,1], atol=1e-5)) points = np.array([[102, 76, 50],[134, 129, 50]]) # Shouldn't allow 3D points on a 2D image with self.assertRaises(Exception): points_image = ants.make_points_image(image, points, radius=3)
class TestModule_make_points_image(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_make_points_image_example(self): pass
4
0
6
0
5
0
1
0.06
1
1
0
0
3
0
3
75
20
3
16
8
12
1
16
8
12
1
2
1
3