コード例 #1
0
 def loadCollection(self, collectionName: str):
     if collectionName == "" or collectionName == None:
         print("fail")
         return
     elif collectionName == "*":
         for path in self.__dataRoot:
             for item in os.listdir(path):
                 collectionPath = os.path.join(path, item)
                 if os.path.isdir(collectionPath) and item not in self.__colnamnes:
                     col = Collection(
                         baseRoot=path, collectionName=item, generate=False,
                     )
                     self.__collections.append(col)
                     self.__colnamnes.append(str(col))
         return
     elif collectionName in self.__colnamnes:
         print("duplicate Collection name")
         return
     collectionPath: str = os.path.join(self.__newDataRoot, collectionName)
     for path in self.__dataRoot:
         collectionPath = os.path.join(path, collectionName)
         if os.path.isdir(collectionPath):
             col = Collection(
                 baseRoot=path, collectionName=collectionName, generate=False
             )
             self.__collections.append(col)
             self.__colnamnes.append(col.__str__())
             return
     print("Error : Not Exists collection")
コード例 #2
0
 def divide_by_regex(self, regex):
     colf = Collection("firstHalf" + self.name, self.location)
     cols = Collection("secondHalf" + self.name, self.location)
     temp_list = self.list[:]
     for col in temp_list:
         if bool(re.match(regex, col.name)):
             colf.insert(col)
             self.remove(col)
         else:
             cols.insert(col)
             self.remove(col)
     os.rmdir(self.path)
     return colf, cols
コード例 #3
0
 def divide_by_list(self, list):
     colf = Collection("firstHalf" + self.name, self.location)
     cols = Collection("secondHalf" + self.name, self.location)
     temp_list = self.list[:]
     for col in temp_list:
         if col.name in list:
             colf.insert(col)
             self.remove(col)
         else:
             cols.insert(col)
             self.remove(col)
     os.rmdir(self.path)
     return colf, cols
コード例 #4
0
def imp(folder_path):
    col = None
    pos = str(folder_path).rfind("\\")
    name = str(folder_path)
    location = name[:pos]
    name = name[pos + 1:]
    i = 1
    for path in pathlib.Path(folder_path).iterdir():
        print(path)
        if path.is_file():
            if i == 1:
                col = Collection(name, location, "Unknown")
            pos = str(path).rfind("\\")
            name = str(path)
            name = name[pos + 1:]
            pos2 = name.find(".")
            tip = name[pos2 + 1:]
            tempdoc = Document(name, tip, folder_path)
            col.insert(tempdoc)
        if path.is_dir():
            if i == 1:
                col = CompositeCollection(name, location)
            col.insert(imp(path))
        i += 1
    return col
コード例 #5
0
    def CreateCollection(self, CollectionName):
        # Create new collection
        self.CurrentCollection = Collection(CollectionName)

        # Put new collection into list
        self.CollectionsList.append(self.CurrentCollection)
        return
コード例 #6
0
def main():
    file_name = input("Enter file name: ")
    while not Validation.file_exists(file_name):
        file_name = input("Reenter file name: ")
    employees = Collection()
    employees.read(file_name)
    menu_choice = 0
    # print(employees.get_len())
    while menu_choice != 4:
        print("You are in main menu. Possible options:\n"
              "1 - add an employee\n"
              "2 - show all salary\n"
              "3 - show all employees\n"
              "4 - exit program\n"
              "Choose your option: ")
        menu_choice = input()
        print("choice =", menu_choice)
        if int(menu_choice) == 1:
            # print("went elif 1")
            data = input(
                "Enter a LINE which is similar to (with a ', ' as a delimiter or enter 0 to skip)\n"
            )
            if data == 0:
                pass
            new_employee = Employee(data)
            employees.add_worker(new_employee)
        elif int(menu_choice) == 2:
            # print("went elif 2")
            print(employees.all_salary())
        elif int(menu_choice) == 3:
            # print("went elif 3")
            employees.print()
        elif int(menu_choice) == 4:
            print("Have a nice day! Goodbye!")
コード例 #7
0
def logout():
    global user_id
    if user_id == -1:
        return jsonify({'status': '400', 'message': 'Already logged out'})
    global all_events
    all_events = Collection([])
    user_id = -1
    return jsonify({'status': '200', 'message': 'Successfully logged out'})
コード例 #8
0
    def __init__(self):
        # protected variables bind to instance
        self._scene = bpy.context.scene
        self._C = bpy.context
        self._D = bpy.data

        self._object = Object()
        self._collection = Collection()
コード例 #9
0
 def extract_sample(self):
     sample = Collection("sample" + self.name, self.location)
     temp_list = self.list[:]
     for col in temp_list:
         if math.ceil(col.size) % 2 == 0:
             sample.insert(col)
             self.remove(col)
     return sample
コード例 #10
0
def load(fileQuery):
    collectionFile = File.fromQuery(fileQuery)

    #get collection settings and set defaults if not specified
    xmlRoot, = root(collectionFile)
    rootAttribs = xmlRoot.attrs
    title = getAttrib(rootAttribs, 'title', DEFAULT_TITLE)
    thumb = getAttrib(rootAttribs, 'thumb', DEFAULT_THUMB)
    sort = getAttrib(rootAttribs, 'sort', DEFAULT_SORT)
    collectionLimit = getAttrib(rootAttribs, 'collectionLimit',
                                DEFAULT_COLLECTION_LIMIT, AttribType.INT)
    unwatched = getAttrib(rootAttribs, 'unwatched', DEFAULT_UNWATCHED,
                          AttribType.BOOL)
    globalLimit = getAttrib(rootAttribs, 'limit', DEFAULT_GLOBAL_LIMIT,
                            AttribType.INT)
    globalRepeat = getAttrib(rootAttribs, 'repeat', DEFAULT_GLOBAL_REPEAT,
                             AttribType.INT)
    globalPush = getAttrib(rootAttribs, 'push', DEFAULT_GLOBAL_PUSH,
                           AttribType.INT)

    if globalLimit > MAXLIMIT:
        globalLimit = MAXLIMIT

    sources = []
    #channelSources = _processChannels(xmlRoot.channels)
    #playlistSources = _processPlaylists(xmlRoot.playlists)

    for node in xmlRoot.children:
        print node

    types = {
        'channels': _processChannels,
        'playlists': _processPlaylists
    }  #maybe move to bottom
    for node in xmlRoot.children:

        print node

        #get sources and their settings and set the global setting if not specified
        #(which is possibly the default)

        nodeAttribs = node.attrib
        limit = getAttrib(nodeAttribs, 'limit', globalLimit, AttribType.INT)
        repeat = getAttrib(nodeAttribs, 'repeat', globalRepeat, AttribType.INT)
        push = getAttrib(nodeAttribs, 'push', globalPush, AttribType.INT)

        if limit > MAXLIMIT:
            limit = MAXLIMIT

        #process according to the type of source
        sourceType = node.tag
        nodeSources = types[sourceType](nodeAttribs, limit, repeat, push)
        sources.extend(nodeSources)

    collection = Collection(title, thumb, sort, collectionLimit, unwatched,
                            collectionFile, sources)

    return collection
コード例 #11
0
 def get_collection(self, name, or_create=False):
     """
     Return pointer to a collection with the provided name
     Create collection if don't exist
     """
     if name not in self.collections:
         self.collections[name] = Collection()
     
     return self.collections[name]
コード例 #12
0
def print_all_and_search():
    if 'what' in request.args:
        to_search = request.args['what']
        return jsonify(all_events.search3(to_search))
    elif 'sort_by' in request.args and 'sort_type' in request.args and 's' in request.args:
        found_events = Collection(all_events.search3(request.args['s']))
        to_return = found_events.sorting3(request.args['sort_by'],
                                          request.args['sort_type'])
    else:
        to_return = all_events.create_event_list()
    return jsonify(to_return)
コード例 #13
0
    def test_collection_basic(self):
        test_event1 = Event(self.test_dict)
        self.test_dict['id'] = '2'
        test_event2 = Event(self.test_dict)
        self.test_dict['id'] = '1'
        test_collection = Collection('Tests/EmptyFile.txt')
        test_collection2 = Collection('Tests/EmptyFile.txt')
        #   append, len and getitem test
        self.assertEqual(len(test_collection), 0, 'Wrong length')
        test_collection.append(test_event1)
        self.assertEqual(len(test_collection), 1, 'Wrong length')
        test_collection.append(test_event2)
        self.assertEqual(len(test_collection), 2, 'Wrong length')

        self.assertEqual(len(test_collection2), 0, 'Should be empty')
        self.assertIs(test_collection[0], test_event1, 'Wrong object')
        self.assertIs(test_collection[1], test_event2, 'Wrong object')
        #   deletion test
        self.assertFalse(test_collection.delete_id('Wrong input'),
                         'Has to be false')
        self.assertFalse(
            test_collection2.delete_id(2),
            'Has to be false (delete id from col where it is not present)')
        self.assertTrue(
            test_collection.delete_id(2),
            'Has to be true (delete id from col where it is present)')
        self.assertFalse(
            test_collection.delete_id(2),
            'Has to be false (delete id from col where it was deleted)')
        self.assertEqual(len(test_collection), 1, 'Wrong length')
        self.assertIs(test_collection[0], test_event1, 'Wrong object')
        #   editing element test
        self.assertFalse(
            test_collection.edit_one(test_collection.find_by_id(4), 'title',
                                     'good name'), 'No such id')
        self.assertFalse(
            test_collection.edit_one(test_collection.find_by_id(2), 'title',
                                     '-abc'), 'Wrong title')
        self.assertTrue(
            test_collection.edit_one(test_collection.find_by_id(1), 'title',
                                     'good name'), 'Should edit')
コード例 #14
0
 def manage_addCollection(self, new_id, REQUEST=None):
     """Add a collection
     """
     from Collection import Collection
     col = Collection(new_id)
     self.collections._setObject(col.id, col)
     col = self.collections._getOb(col.id)
     if REQUEST:
         audit('UI.Report.AddCollection', self.id, collection=col.id)
         url = '%s/collections/%s' % (self.getPrimaryUrlPath(), new_id)
         return REQUEST['RESPONSE'].redirect(url)
     return col
コード例 #15
0
    def __init__(self):
        self.CollectionsList = []
        self.CurrentCollection = 0

        # Open maindatabase file
        try:
            SmetanaDatabase = open("Smetana.db", "r")
            for CollectionName in SmetanaDatabase:
                self.CollectionsList.append(Collection(CollectionName[:-1]))

        except:
            SmetanaDatabase = open("Smetana.db", "w")

        SmetanaDatabase.close()
コード例 #16
0
    def test_collection_searching(self):
        test_collection = Collection('Tests/SearchTest.txt')
        search_args = ['NotExists', '', '10', 'Event', '20']
        to_find = [
            '', '',
            'Event with ID 10 has ID 10\nEvent with ID 5 has price 10.5\n',
            'Event with ID 5 has title FourthEvent\nEvent with ID 10 has title firstEvent\n',
            'Event with ID 1 has starting date 2019-05-25\n'
            'Event with ID 5 has starting date 2005-11-22\n'
            'Event with ID 10 has starting date 2021-12-31\n'
        ]

        for x in range(0, len(search_args)):
            self.assertEqual(test_collection.search2(search_args[x]),
                             to_find[x])
コード例 #17
0
def print_all_and_search():
    if user_id == -1:
        return jsonify({'status': '200', 'message': 'Not logged in'})
    if 'what' in request.args:
        to_search = request.args['what']
        return jsonify(all_events.search3(to_search))
    elif 'sort_by' in request.args and 'sort_type' in request.args and 's' in request.args:
        found_events = Collection(all_events.search3(request.args['s']))
        to_return = found_events.sorting3(request.args['sort_by'],
                                          request.args['sort_type'])
    else:
        to_return = all_events.create_event_list()
    if 'limit' in request.args:
        if 'offset' in request.args:
            to_return = show_some(to_return, request.args['offset'],
                                  request.args['limit'])
        else:
            to_return = show_some(to_return, 0, request.args['limit'])
    return jsonify(to_return)
コード例 #18
0
    def test_history(self):
        test_collection = Collection('TestsHistory/ChangingFile.txt')

        def get_file_content(way):
            content_f = open(way, 'r')
            content_text = content_f.read()
            content_f.close()
            return content_text

        def compare(way):
            test_collection.rewrite()
            manual_action = get_file_content(way)
            program_action = get_file_content('TestsHistory/ChangingFile.txt')
            self.assertEqual(manual_action, program_action)

        testing_funcs = [
            test_collection.delete_id, test_collection.delete_id,
            test_collection.append, test_collection.delete_id,
            test_collection.undo, test_collection.undo, test_collection.undo,
            test_collection.redo, test_collection.redo, test_collection.undo,
            test_collection.delete_id, test_collection.redo,
            test_collection.undo, test_collection.undo, test_collection.undo,
            test_collection.undo
        ]
        args = [
            4, 1,
            Event(self.test_dict), 14, None, None, None, None, None, None, 8,
            None, None, None, None, None
        ]
        comparisons = [
            'Action1.txt', 'Action2.txt', 'Action3.txt', 'Action4.txt',
            'Action3.txt', 'Action2.txt', 'Action1.txt', 'Action2.txt',
            'Action3.txt', 'Action2.txt', 'Action3Alternative.txt',
            'Action3Alternative.txt', 'Action2.txt', 'Action1.txt',
            'Start.txt', 'Start.txt'
        ]

        for x in range(0, len(testing_funcs)):
            if args[x] is None:
                testing_funcs[x]()
            else:
                testing_funcs[x](args[x])
            compare('TestsHistory/' + comparisons[x])
コード例 #19
0
def login():
    global all_events
    global user_id
    if user_id != -1:
        return jsonify({'status': '400', 'message': 'Already logged in'})
    if 'email' not in request.args or 'password' not in request.args:
        return jsonify({'status': '400', 'message': 'Need email and password'})

    cursor.execute("Select* From users where email = \'" +
                   str(request.args['email']) + "\';")
    for x in cursor:
        salt_from_storage = x[4][:32]
        key_from_storage = x[4][32:]
        n_key = hashlib.pbkdf2_hmac(
            'sha256',
            str(request.args['password']).encode('utf-8'), salt_from_storage,
            100000)
        if key_from_storage == n_key:
            user_id = x[0]
            cursor.execute("Select* From events where user_id = " +
                           str(user_id) + ";")
            parameters = [
                'id', 'title', 'rest_name', 'date', 'time', 'duration',
                'price', 'user_id'
            ]
            collection = []
            iteration = 0
            for q in cursor:
                collection.append(dict())
                for z in range(0, len(parameters)):
                    collection[iteration][parameters[z]] = str(q[z])
                iteration += 1
            all_events = Collection(collection)
            return jsonify({
                'status': '200',
                'message': 'Successfully logged in'
            })
        else:
            return jsonify({'status': '400', 'message': 'Wrong password'})
    return jsonify({'status': '400', 'message': 'No such email'})
コード例 #20
0
    def test_collection_sort_write(self):
        test_collection = Collection('Tests/SortTest.txt')

        def get_file_content(way):
            content_f = open(way, 'r')
            content_text = content_f.read()
            content_f.close()
            return content_text

        def compare(way):
            test_collection.rewrite()
            manual_action = get_file_content(way)
            program_action = get_file_content('Tests/SortTest.txt')
            self.assertEqual(manual_action, program_action)

        arguments = ['T', 'I', 'R', 'Da', 'Ti', 'D', 'P', 'I']
        comparisons = [
            'Title', 'ID', 'RestaurantName', 'Date', 'Time', 'Duration',
            'Price', 'ID'
        ]

        for x in range(0, len(arguments)):
            test_collection.sorting2(arguments[x])
            compare('Tests/By' + comparisons[x] + '.txt')
コード例 #21
0
    print('E to edit')
    print('S to sort')
    print('F to search')
    print('P to show all')
    print('H to show last 5 actions')
    print('U to undo')
    print('R to redo')
    print('Q to quit\n')


def restaurants():
    for q in RestaurantName:
        print(q.value, '-', q.name)


all_events = Collection('')

while True:
    menu()
    action = input()
    if action == 'Q':
        break
    elif action == 'A':
        initial_dict = dict()
        initial_dict['id'] = input(
            'Enter the ID of the event (positive integer): ')
        initial_dict['title'] = input(
            'Enter the title of the event (characters "|", ":" and "-" are forbidden): '
        )
        restaurants()
        initial_dict['rest_name'] = input(
コード例 #22
0
 def __init__(self, options=[]):
     Collection.__init__(self, options)
     self.db = db()
コード例 #23
0
    print('E to edit')
    print('S to sort')
    print('F to search')
    print('P to show all')
    print('Q to quit\n')


def restaurants():
    for q in RestaurantName:
        print(q.value, '-', q.name)


file_name = input('Enter name of the file: ')
while Validation.validate_file(file_name):
    file_name = input('Wrong name of the file, try again: ')
all_events = Collection(file_name)

while True:
    menu()
    action = input()
    if action == 'Q':
        break
    elif action == 'A':
        initial_dict = dict()
        initial_dict['id'] = input(
            'Enter the ID of the event (positive integer): ')
        initial_dict['title'] = input(
            'Enter the title of the event (characters "|", ":" and "-" are forbidden): '
        )
        restaurants()
        initial_dict['rest_name'] = input(
コード例 #24
0
            for x in request.args:
                to_do.append(str(x + " = \'" + str(request.args[x]) + "\'"))
            cursor.execute("UPDATE events SET " + (', '.join(to_do)) +
                           " WHERE id = " + g_id + ";")
            db.commit()
        return jsonify(result_dict)
    else:
        return jsonify({'status': '404', 'message': 'No such ID'})


if __name__ == '__main__':

    db = MySQLdb.connect("localhost", "root", "Az27061985", "test")
    cursor = db.cursor()

    cursor.execute("Select* From Events;")

    parameters = [
        'id', 'title', 'rest_name', 'date', 'time', 'duration', 'price'
    ]
    test = []
    iteration = 0
    for q in cursor:
        test.append(dict())
        for z in range(0, len(parameters)):
            test[iteration][parameters[z]] = str(q[z])
        iteration += 1
    all_events = Collection(test)
    hello.run()
    db.close()
コード例 #25
0
from Collection import Collection
import os
'''
将本文件放入需整理的文件夹中,运行即可。
Author:zhangze
Place:WIT_636
Time:2018/1/17
function:分类音乐文件
'''
if __name__ == "__main__":
    # rootPath = "G:\\Music\\"  # 存放文件夹
    rootPath = os.path.abspath(os.path.dirname(__file__))
    copyPath = os.path.abspath(os.path.dirname(__file__))
    # copyPath = "G:\\newMusic\\"  # 整理文件夹
    loseList = []
    count = [0]
    Collection(copyPath,rootPath,loseList,count)

    while True:
        n = str(input("输入 exit 退出:"))
        if n == "exit":
            exit()

コード例 #26
0
ファイル: module1.py プロジェクト: Dardax/Elyneum
transceiver.sauver_armure(armure)
transceiver.sauver_competance(competance)
transceiver.sauver_sort(sort)
transceiver.sauver_objet(objet)

partie = Partie("aLELJD")
combat1 = Combat()
combat1.addPlayer(perso)
combat1.addPlayer(perso1)
combat1.addMonster(perso1)
combat1.addMonster(perso2)
combat1.rename("plouf")
partie.addCombat(combat1)

combat1 = ""
combat2 = Combat([], [])
combat2.addPlayer(perso)
combat2.addMonster(perso1)
combat2.addMonster(perso2)
combat2.rename("plouf2")
combat2.commencer()
partie.addCombat(combat2)

collec = Collection("Algarn")
collec.reload_perso()
collec.reload_armure()
partie.sauvegarder()
partie2 = transceiver.lire_sauvegarde("aLELJD")
partie2.nom = "testeresauv"
partie2.sauvegarder()
コード例 #27
0
            })
        else:
            return jsonify({'status': '400', 'errors': errors})

    return jsonify({'status': '404', 'message': 'No such user'})


if __name__ == '__main__':

    db = MySQLdb.connect("localhost", "root", "Az27061985", "test")
    cursor = db.cursor()
    user_id = -1
    access_level = 'user'
    cursor.execute("Select* From events;")
    parameters = [
        'id', 'title', 'rest_name', 'date', 'time', 'duration', 'price',
        'user_id', 'amount'
    ]
    collection = []
    iteration = 0
    for q in cursor:
        collection.append(dict())
        for z in range(0, len(parameters)):
            collection[iteration][parameters[z]] = str(q[z])
        iteration += 1
    all_events = Collection(collection)
    current_ord = []
    salt = os.urandom(32)
    hello.run()
    db.close()
コード例 #28
0
ファイル: control.py プロジェクト: monarin/lcls2
def main():

    # Process arguments
    parser = argparse.ArgumentParser()
    parser.add_argument('pvbase', help='EPICS PV base (e.g. DAQ:LAB2:PART:2)')
    parser.add_argument('-p',
                        type=int,
                        choices=range(0, 8),
                        default=0,
                        help='platform (default 0)')
    parser.add_argument('-C',
                        metavar='CM_HOST',
                        default='localhost',
                        help='Collection Manager host')
    parser.add_argument('-u',
                        metavar='UNIQUE_ID',
                        default='control',
                        help='Name')
    parser.add_argument('-v', action='store_true', help='be verbose')
    args = parser.parse_args()

    if args.v:
        logging.basicConfig(level=logging.DEBUG,
                            format='%(asctime)s - %(levelname)s - %(message)s')
    else:
        logging.basicConfig(level=logging.WARNING,
                            format='%(asctime)s - %(levelname)s - %(message)s')

    logging.info('control level starting')

    ctx = zmq.Context()

    coll = Collection(ctx, args.C, args.p)

    pybody = {}
    pybody['host'] = gethostname()
    pybody['pid'] = getpid()
    idbody = {}
    idbody['procInfo'] = pybody
    mainbody = {}
    mainbody['control'] = idbody
    hellomsg = CollectMsg(key=CollectMsg.HELLO, body=json.dumps(mainbody))
    partition = coll.partitionInfo(hellomsg)
    pprint.pprint(json.loads(partition.body))

    # set up our end of connections, potentially based on the information
    # about who is in the partition (e.g. number of eb/drp nodes)
    # control sockets (ephemeral ports)
    control_router_socket = ctx.socket(zmq.ROUTER)
    control_pull_socket = ctx.socket(zmq.PULL)
    control_router_socket.bind("tcp://*:*")
    control_pull_socket.bind("tcp://*:*")
    control_router_port = Collection.parse_port(
        control_router_socket.getsockopt(zmq.LAST_ENDPOINT))
    control_pull_port = Collection.parse_port(
        control_pull_socket.getsockopt(zmq.LAST_ENDPOINT))
    logging.debug('control_router_port = %d' % control_router_port)
    logging.debug('control_pull_port = %d' % control_pull_port)

    pybody = {}
    pybody['router_port'] = {
        'adrs': gethostname(),
        'port': control_router_port
    }
    pybody['pull_port'] = {'adrs': gethostname(), 'port': control_pull_port}
    connbody = {}
    connbody['connectInfo'] = pybody
    mainbody = {}
    mainbody['control'] = connbody

    portsmsg = CollectMsg(key=CollectMsg.CONNECTINFO,
                          body=json.dumps(mainbody))
    connect_info = coll.connectionInfo(portsmsg)
    pprint.pprint(json.loads(connect_info.body))

    # now make the connections and report to CM when done

    # Control state
    yy = ControlStateMachine(args.pvbase)
    logging.debug("ControlStateMachine state: %s" % yy.state())

    poller = zmq.Poller()
    poller.register(control_router_socket, zmq.POLLIN)
    poller.register(control_pull_socket, zmq.POLLIN)
    try:
        while True:
            items = dict(poller.poll(1000))

            # Handle control_pull_socket socket
            if control_pull_socket in items:
                msg = control_pull_socket.recv()
                config = dgram.Dgram(view=msg)
                # now it's in dgram.Dgram object
                ttt = config.seq.timestamp()
                print('Timestamp:', ttt)  # FIXME

            # Execute state command request
            if control_router_socket in items:
                msg = control_router_socket.recv_multipart()
                identity = msg[0]
                request = msg[1]
                logging.debug('Received <%s> from control_router_socket' %
                              request.decode())

                if request == ControlMsg.PING:
                    # Send reply to client
                    logging.debug("Sending <PONG> reply")
                    control_router_socket.send(identity, zmq.SNDMORE)
                    cmmsg = ControlMsg(key=ControlMsg.PONG)
                    cmmsg.send(control_router_socket)
                    continue

                if request == ControlMsg.PONG:
                    continue

                if request in [
                        Transition.configure, Transition.beginrun,
                        Transition.enable, Transition.disable,
                        Transition.endrun, Transition.unconfigure,
                        ControlMsg.GETSTATE
                ]:

                    if request != ControlMsg.GETSTATE:
                        oldstate = yy.state()
                        # Do transition
                        yy.on_transition(request)
                        newstate = yy.state()
                        if newstate != oldstate:
                            logging.debug("ControlStateMachine state: %s" %
                                          newstate)

                    # Send reply to client
                    control_router_socket.send(identity, zmq.SNDMORE)
                    cmmsg = ControlMsg(key=yy.state().key())
                    cmmsg.send(control_router_socket)
                    continue

                else:
                    logging.warning("Unknown msg <%s>" % request.decode())
                    # Send reply to client
                    logging.debug("Sending <HUH?> reply")
                    control_router_socket.send(identity, zmq.SNDMORE)
                    cmmsg = ControlMsg(key=ControlMsg.HUH)
                    cmmsg.send(control_router_socket)
                    continue

    except KeyboardInterrupt:
        logging.debug("Interrupt received")

    # Clean up
    logging.debug("Clean up control level")

    # Close all sockets associated with this context, and then
    # terminate the context.
    ctx.destroy(0)

    logging.info('control level exiting')
コード例 #29
0
from Collection import Collection

array_collection = Collection([0, 0, 4, 3, 0, 2, 0, 6, 7, 4, 0, 0])

simple_iterator = array_collection.iterator()
for item in simple_iterator:
    print(item, end=" ")
print()

non_zero_iterator = array_collection.non_zero_iterator()
for item in non_zero_iterator:
    print(item, end=" ")
コード例 #30
0
        """
        # Prepare data to be written in JSON file
        prepare_data = {}
        for name in self.collections:
            prepare_data[name] = self.collections[name].collection
        # Write the data
        with open(filename,mode="w") as json_file:
            json_file.truncate(0)
            json.dump(prepare_data, json_file)
            
    def close(self):
        """
        When closing the database, you must write current data to the JSON file
        for persistence
        """
        self.write_json_file(self.db_file)
    
if __name__ == "__main__":
    db = Database("file1")
    collection = db.get_collection("people")
    
    # Empty collection
    collection = Collection()
    assert collection.get_all() == []
    
    document1 = {"name":"John", "age":38, "children": {"child1":"James", "child2":"Jay"}}
    # First insertion
    collection.insert(document1)
    assert collection.get_all() == [document1]