Пример #1
0
 def setUp(self):
     self.pb = Phonebook()
     self.contacts = [
         Contact("Taco McCat", "205-011-2358"),
         Contact("Burrito D'Leeto", "256-011-2358"),
     ]
     self.pb._entries = list(self.contacts)
Пример #2
0
 def test_delete_contact(self):
     test_contact = Contact("test", "user","700000000", "*****@*****.**")
     test_contact.save_contact()
     test_contact2=Contact("test", "user", "978899877766", "*****@*****.**")
     test_contact2.save_contact()
     test_contact.delete_contact()
     self.assertEqual(len(Contact.contact_list),1)
Пример #3
0
def main():
    contact = Contact(name='chi nguyen', email='*****@*****.**')
    contact2 = Contact(name='phong nguyen', email='*****@*****.**')

    print()
    print("Contact list:")
    for idx, c in enumerate(Contact.all_contacts):
        print(str(idx + 1), '. ', c.name, '\t', c.email)
Пример #4
0
 def extract_contact(self):
     if not self.type_in(c.IPMSG_BR_ENTRY, c.IPMSG_ANSENTRY):
         contact = Contact(name=self.name, group='', host=self.host, addr=self.addr, login=self.name)
         contact.temporary = True
     else:
         contact = Contact(name=self.msg, group=self.group, host=self.host, addr=self.addr, login=self.name)
         contact.encrypt_opt = self.test(c.IPMSG_ENCRYPTOPT)
     return contact
Пример #5
0
def main():
    bd = GestionBD(BaseMySQL.dbName, BaseMySQL.user, BaseMySQL.passwd,
                   BaseMySQL.host)
    if bd.echec:
        sys.exit()
    while 1:
        print "\nQue voulez-vous faire :\n"\
          "1) Créer les tables de la base de données\n"\
          "2) Supprimer les tables de la base de données ?\n"\
          "3) Entrer des employés\n"\
          "4) Lister des employés\n"\
          "5) Exécuter une requête SQL quelconque\n"\
          "6) Enregister sous format ldif\n"\
          "7) Terminer ?                         Votre choix :",
        ch = int(raw_input())
        if ch == 1:
            # Create all the tables described in the thesaurus
            bd.creerTables(BaseMySQL.dicoT)
        elif ch == 2:
            # Drop all the tables described in the thesaurus
            bd.supprimerTables(BaseMySQL.dicoT)
        elif ch == 3:
            # Integration of employees
            table = {3: 'employes'}[ch]
            enreg = Sauvegarde(bd, table)
            while 1:
                if enreg.save():
                    break
        elif ch == 4:
            # List of all employees
            table = {4: 'employes'}[ch]
            if bd.executerReq("SELECT * FROM %s" % table):
                records = bd.resultatReq()
                for rec in records:
                    for item in rec:
                        print item,
                    print
        elif ch == 5:
            # Any query
            req = raw_input("Enter SQL query : ")
            if bd.executerReq(req):
                print bd.resultatReq()
        elif ch == 6:
            # Save
            fic = raw_input('Enter filename to process: ')
            ofi = open(fic, "w")
            contact = Contact()
            table = {6: 'employes'}[ch]
            if bd.executerReq("SELECT * FROM %s" % table):
                records = bd.resultatReq()
                for rec in records:
                    contact = Contact(*rec[1:])
                    ofi.write(contact.get_contact_ldif())
                ofi.close()
        else:
            bd.commit()
            bd.close()
            break
Пример #6
0
def main():
    phonebook = Phonebook()

    person1 = Contact("Maija", "Mehiläinen", "29392949", 1994)
    person2 = Contact("Matti", "Meikäläinen", "03846737", 1995)

    phonebook.AddContact(person1)
    phonebook.AddContact(person2)

    phonebook.PrintContacts()
Пример #7
0
        def extendShortlist(responseTuple):
            """ @type responseMsg: kademlia.msgtypes.ResponseMessage """
            # The "raw response" tuple contains the response message, and the originating address info
            responseMsg = responseTuple[0]
            originAddress = responseTuple[1]  # tuple: (ip adress, udp port)
            # Make sure the responding node is valid, and abort the operation if it isn't
            if responseMsg.nodeID in activeContacts or responseMsg.nodeID == self.id:
                return responseMsg.nodeID

            # Mark this node as active
            if responseMsg.nodeID in shortlist:
                # Get the contact information from the shortlist...
                aContact = shortlist[shortlist.index(responseMsg.nodeID)]
            else:
                # If it's not in the shortlist; we probably used a fake ID to reach it
                # - reconstruct the contact, using the real node ID this time
                aContact = Contact(responseMsg.nodeID, originAddress[0],
                                   originAddress[1], self._protocol)
            activeContacts.append(aContact)
            # This makes sure "bootstrap"-nodes with "fake" IDs don't get queried twice
            if responseMsg.nodeID not in alreadyContacted:
                alreadyContacted.append(responseMsg.nodeID)
            # Now grow extend the (unverified) shortlist with the returned contacts
            result = responseMsg.response
            #TODO: some validation on the result (for guarding against attacks)
            # If we are looking for a value, first see if this result is the value
            # we are looking for before treating it as a list of contact triples
            if findValue is True and key in result and not 'contacts' in result:
                # We have found the value
                findValueResult[key] = result[key]
                findValueResult['from_peer'] = aContact.address
            else:
                if findValue is True:
                    # We are looking for a value, and the remote node didn't have it
                    # - mark it as the closest "empty" node, if it is
                    if 'closestNodeNoValue' in findValueResult:
                        if self._routingTable.distance(
                                key, responseMsg.nodeID
                        ) < self._routingTable.distance(
                                key, activeContacts[0].id):
                            findValueResult['closestNodeNoValue'] = aContact
                    else:
                        findValueResult['closestNodeNoValue'] = aContact
                    contactTriples = result['contacts']
                else:
                    contactTriples = result
                for contactTriple in contactTriples:
                    if isinstance(contactTriple,
                                  (list, tuple)) and len(contactTriple) == 3:
                        testContact = Contact(contactTriple[0],
                                              contactTriple[1],
                                              contactTriple[2], self._protocol)
                        if testContact not in shortlist:
                            shortlist.append(testContact)
            return responseMsg.nodeID
Пример #8
0
def main():
    phone_book = Phonebook()
    phone_book.add_contact(
        Contact('Дмитрий',
                'Дюков',
                '+70000000000',
                email='*****@*****.**',
                telegram='@dukov',
                email2='*****@*****.**',
                facebook='DyukovDmitry'))
    phone_book.add_contact(
        Contact('Эмануил',
                'Виторган',
                '+70000000001',
                email='*****@*****.**',
                telegram='@emsvit'))
    phone_book.add_contact(
        Contact('Тюльпек',
                'Ганджубасов',
                '+70000000002',
                favorite=True,
                email='*****@*****.**',
                telegram='@gandzhubasov'))
    phone_book.add_contact(
        Contact('Курмультук',
                'Ильясов',
                '+70000000003',
                favorite=True,
                email='*****@*****.**',
                telegram='@mudeni'))
    phone_book.add_contact(
        Contact('Зугинтульба',
                'Иванова',
                '+70000000004',
                favorite=True,
                email='*****@*****.**',
                telegram='@eultubey'))

    print(
        '=====================================Печать всех ====================================================='
    )
    phone_book.print_contacts()
    print(
        '=====================================Удаление по номеру =============================================='
    )
    phone_book.delete_contact('+70000000000')
    print(
        '=====================================Показать избраных ==============================================='
    )
    phone_book.print_favorite()
    print(
        '=====================================Поиск по Имени и Фамилии ========================================'
    )
    phone_book.search_contact('Тюльпек', 'Ганджубасов')
Пример #9
0
 def test_verify_zip_code(self):
     form = {'zip_code': 12345}
     form2 = {'zip_code': 1234}
     form3 = {'zip_code': 123456}
     form4 = {}
     contact = Contact(form)
     contact2 = Contact(form2)
     contact3 = Contact(form3)
     self.assertEqual(toJson(form), str(contact))
     self.assertEqual(toJson(form4), str(contact2))
     self.assertEqual(toJson(form4), str(contact3))
Пример #10
0
 def test_verify_state(self):
     form = {'state': 'MD'}
     form2 = {'state': 'md'}
     form3 = {'state': 'Maryland'}
     form4 = {}
     contact = Contact(form)
     contact2 = Contact(form2)
     contact3 = Contact(form3)
     self.assertEqual(toJson(form), str(contact))
     self.assertEqual(toJson(form), str(contact2))
     self.assertEqual(toJson(form4), str(contact3))
Пример #11
0
def check_input():
    if '-a' in sys.argv:
        try:
            name = check_name('-a')
            phone = raw_input('phone number: ')
            email = raw_input('email address: ')
            person = Contact(name, phone, email)
            add_contact(person)
            list_contact(name)
        except IndexError:
            sys.exit(logger.fail('fatal: not enough arguments'))
        except IOError:
            sys.exit(logger.fail('fatal: contacts database not found'))
    elif '-e' in sys.argv:
        try:
            name = check_name('-e')
            phone = raw_input('phone number: ')
            email = raw_input('email address: ')
            person = Contact(name, phone, email)
            edit_contact(person)
            list_contact(name)
        except IndexError:
            sys.exit(logger.fail('fatal: not enough arguments'))
        except IOError:
            sys.exit(logger.fail('fatal: contacts database not found'))
    elif '-d' in sys.argv:
        try:
            name = check_name('-d')
            person = Contact(name, '', '')
            del_contact(person)
        except IndexError:
            sys.exit(logger.fail('fatal: not enough arguments'))
        except IOError:
            sys.exit(logger.fail('fatal: contacts database not found'))
    elif '-i' in sys.argv:
        init_db()
        sys.exit(logger.ok('success: database created in contacts.json'))
    elif '-l' in sys.argv:
        try:
            name = check_name('-l')
            list_contact(name)
        except IndexError:
            sys.exit(logger.fail('fatal: not enough arguments'))
        except IOError:
            sys.exit(logger.fail('fatal: contacts database not found'))
    else:
        sys.exit(
            logger.warn("""
        usage:
            -i : initialize database / clear existing one
            -a <name> : add contact to database
            -l <name> : list contact information
            -d <name> : remove contact from database
        """))
Пример #12
0
 def add_contact(self, auto=False):
     """Add new contact to list"""
     # Verify contact information
     if not auto:
         new_contact = Contact()
     else:
         new_contact = Contact(auto)
     try:
         self.contacts.append(new_contact)
         print(f"{new_contact.name} added", end="\n\n")
     except Exception as err:
         print(f"Exception Type: {type(err).__name__}")
Пример #13
0
    def __init__(self):

        ollie = Contact('Ollie Diablo', '360-628-3383', '5270 SW Franklin',
                        'Poodle')
        argos = Contact('Argos Blackdog', '503-555-5555',
                        '742 Evergreen Terrace', 'Mutt')
        lucky = Contact('Lucky Dog', '503-555-1234', '2828 Corbett Ave',
                        'Poodle')
        cody = Contact('Cody McFuzzy', '719-555-5500', '2828 Corbett Ave',
                       'Shiba Inu')

        self.new = [ollie, argos, lucky, cody]
Пример #14
0
    def __init__(self, location=None):
        self.location = location if location is not None else get_location()

        with open(self.location, 'rb') as f:
            self.raw_data = f.read()

        self._compile_re_patterns()

        try:
            owner_num = re.findall(self._owner_number_pat, self.raw_data)[0]
            self.owner = Contact(owner_num, 'Owner')
        except IndexError:
            self.owner = Contact('0' * 10, 'Owner')
def main():
    phonebook = PhoneBook("Examples/Classes/contacts.csv", ";")

    # Kaksi oliota. Oliot on luotu samasta luokasta, mutta niillä on omat muuttujien arvonsa (olion tila)
    person1 = Contact("Maija", "Meikäläinen", "123454321", 1990)
    person2 = Contact("Matti", "Meikäläinen", "987656789", 1991)
    person3 = Student("Aimo", "Opiskelija", "1232123", 2000, 12345)

    phonebook.AddContact(person1)
    phonebook.AddContact(person2)
    phonebook.AddContact(person3)

    phonebook.PrintContacts()

    phonebook.SaveContacts(";")
Пример #16
0
def update_contact(user_id, contact_id):
    user = database.get_user_by_id(user_id)
    ping(user)
    contact = database.get_contact_by_id(contact_id)
    try:
        if request.form['Update_button'] is not None:
            values = (contact_id, request.form['Name'], request.form['Number'],
                      request.form['Note'], user.get_id())
            database.update_contact(Contact(*values))
    except KeyError:
        app.logger.info(
            'KeyError exception encountered when updating contact.')
        try:
            if request.form['Delete_button'] is not None:
                database.delete_contact(database.get_contact_by_id(contact_id))
        except KeyError:
            app.logger.error(
                'KeyError exception encountered when deleting contact.')
        except:
            app.logger.error(
                'Unidentified exception encountered when deleting contact.')
    except:
        app.logger.info(
            'Unidentified exception encountered when updating contact.')
    return redirect(url_for('display_contacts', user_id=user.get_id()))
Пример #17
0
 def setUp(self):
     '''
     Set up method to run before each test cases.
     '''
     self.new_contact = Contact(
         "Eva", "Maina", "0722811823",
         "*****@*****.**")  # create contact object
Пример #18
0
    def test_save_multiple_contact(self):

        self.new_contact.save_contact()
        test_contact = Contact("Test", "user", "0712345678",
                               "*****@*****.**")  # new contact
        test_contact.save_contact()
        self.assertEqual(len(Contact.contact_list), 9)
Пример #19
0
    def setUp(self):
        def tearDown(self):

            Contact.contact_list = []

        self.new_contact = Contact("James", "Muriuki", "0712345678",
                                   "*****@*****.**")
Пример #20
0
def add_contact():
    username = None
    if 'username' in session:
        username = session['username']

    if request.method == 'GET':
        return render_template('add-contact.html',
                               site=site,
                               username=username)
    if request.method == 'POST':
        first_name = request.form['firstName']
        last_name = request.form['lastName']
        biography = request.form['biography']
        avatar = request.form['avatar']

        contact = Contact(first_name, last_name)

        if biography != "":
            contact.update_biography(biography)
        if avatar != "":
            contact.avatar_url = avatar

        contact_book.add(contact)

        return redirect(url_for('contacts'))
Пример #21
0
    def setUp(self):
        '''
        Set up method to run before eact test cases.

        '''
        self.new_contact = Contact('James', 'Muriuki', '0712345678',
                                   '*****@*****.**')  # create contact object
Пример #22
0
    def joinNetwork(self, knownNodeAddresses=None):
        """
        Causes the Node to join the Kademlia network; normally, this should be
        called before any other DHT operations.

        @param knownNodeAddresses: A sequence of tuples containing IP address
                                   information for existing nodes on the
                                   Kademlia network, in the format:
                                   C{(<ip address>, (udp port>)}
        @type knownNodeAddresses: tuple
        """
        # Prepare the underlying Kademlia protocol
        # Create temporary contact information for the list of addresses of known nodes
        if knownNodeAddresses is not None:
            bootstrapContacts = []
            for address, port in knownNodeAddresses:
                contact = Contact(self._generateID(), address, port, self._protocol)
                bootstrapContacts.append(contact)
        else:
            bootstrapContacts = None
        # Initiate the Kademlia joining sequence - perform a search for this node's own ID
        self._joinDeferred = self._iterativeFind(self.id, bootstrapContacts)
#        #TODO: Refresh all k-buckets further away than this node's closest neighbour
#        def getBucketAfterNeighbour(*args):
#            for i in range(160):
#                if len(self._buckets[i]) > 0:
#                    return i+1
#            return 160
#        df.addCallback(getBucketAfterNeighbour)
#        df.addCallback(self._refreshKBuckets)
        #protocol.reactor.callLater(10, self.printContacts)
        self._joinDeferred.addCallback(self._persistState)
        self._joinDeferred.addErrback(self._joinNetworkFailed)
        # Start refreshing k-buckets periodically, if necessary
        self.refresher = twisted.internet.reactor.callLater(constants.checkRefreshInterval, self._refreshNode)  # IGNORE:E1101
Пример #23
0
def create_contact(fname, lname, phone, email):
    '''
    function to create a new contact
    '''

    new_contact = Contact(fname, lname, phone, email)
    return new_contact
Пример #24
0
 def test_contact_exists(self):
     self.new_contact.save_contact()
     test_contact = Contact("Test", "user", "0711223344",
                            "*****@*****.**")  # new contact
     test_contact.save_contact()
     contact_exists = Contact.contact_exists("0711223344")
     self.assertTrue(contact_exists)
Пример #25
0
 def test_find_contact_by_number(self):
     self.new_contact.save_contact()
     test_contact = Contact("Test", "user", "0711223344",
                            "*****@*****.**")  # new contact
     test_contact.save_contact()
     found_contact = Contact.find_by_number("0711223344")
     self.assertEqual(found_contact.email, test_contact.email)
Пример #26
0
 def test_delete_contact(self):
     self.new_contact.save_contact()
     test_contact = Contact("Test", "user", "0712345678",
                            "*****@*****.**")  # new contact
     test_contact.save_contact()
     self.new_contact.delete_contact()  # deleting contact object
     self.assertEqual(len(Contact.contact_list), 1)
 def test_add_full_contact(self):
     wd = self.wd
     self.open_home_page(wd)
     self.login(wd, User.ADMIN)
     empty_contact = Contact(lastname='aaa',
                             firstname='bbb',
                             middlename='ccc',
                             nickname='ddd',
                             title='kkk',
                             company='lll',
                             address='mmm',
                             home='111',
                             mobile='222',
                             work='333',
                             fax='444',
                             main='*****@*****.**',
                             secondary='*****@*****.**',
                             other='*****@*****.**',
                             homepage='http://',
                             byear='1994',
                             bmonth='April',
                             bday='15',
                             ayear='2003',
                             amonth='September',
                             aday='4',
                             address2='xxx',
                             phone='777',
                             notes='zzz')
     self.create_new_contact(wd, empty_contact)
     self.return_to_home_page(wd)
     self.logout(wd)
Пример #28
0
def main():
    phonebook = PhoneBook("Examples/Classes/contacts.csv")

    person1 = Contact("Maija", "Meikäläinen", "123456789", 1990)
    person2 = Contact("Matti", "Meikäläinen", "987654321", 1991)
    person3 = Student("Osku", "Opiskelija", "987656789", 2000, 54321)
    person4 = Teacher("Sami", "Kojo-Fry", "12121212", 1987, "A3-??")

    phonebook.AddContact(person1)
    phonebook.AddContact(person2)
    phonebook.AddContact(person3)
    phonebook.AddContact(person4)

    phonebook.PrintContacts()

    phonebook.SaveContacts()
Пример #29
0
 def __init__(self):
     self.client = MongoClient(os.getenv('DB_HOST'), 27017)
     self.db = self.client['db_freshdesk']
     self.tickets = self.db.tickets
     self.contacts = self.db.contacts
     self._ticket = Ticket()
     self._contact = Contact()
 def get_contacts(self):
     sql = """SELECT rowid, last_name, first_name, email, phone
              FROM contacts"""
     for row in self.conn.execute(sql):
         contact = Contact(*row[1:])
         contact.rowid = row[0]
         yield contact