예제 #1
0
def main():
    """Get user input to either add movie to collection,
     view entire collection, find movie from collection,
     or enter 'Q' to quit program.

     object: dict1 is the dictionary the movie collection is stored in.

    :return:
    """

    user_command = (input("Enter 'A' to add a movie to collection\n"
                          "Enter 'V' to view entire collection\n"
                          "Enter 'F' to find a movie from collection\n"
                          "Enter 'Q' to quit\n")).lower()

    # Continue looping through until user quits program
    while user_command in {'v', 'a', 'f'}:
        # if user input is 'a' call add function from add module and pass in dict1
        if user_command == 'a':
            add(dict1)

        # if user input is 'v' call view function from view module and pass in dict1
        elif user_command == 'v':
            view(dict1)

        # if user input is 'f' call find function from find module and pass in dict1
        elif user_command == 'f':
            find(dict1)

        user_command = (input("Enter 'A' to add a movie to collection\n"
                              "Enter 'V' to view entire collection\n"
                              "Enter 'F' to find a movie from collection\n"
                              "Enter 'Q' to quit\n")).lower()
예제 #2
0
파일: app.py 프로젝트: viru2001/contactApp
def runApp():
    while True:
        print(
            "what you want to do ?\n1.Add Contact\n2.View all Contacts\n3.Edit Contact\n4.Delete Contact\n5.Search Contact\n6.Exit"
        )
        choice = int(input())
        if choice == 1:
            name = input("Enter a name : ")
            number = input("Enter Contact number : ")
            while not isValidPhoneNumber(number):
                print("Enter a valid phone number")
                number = input("Enter Contact number : ")
            add(name, number)
            print("contact added successfully")
        elif choice == 2:
            view()
        elif choice == 3:
            name = input("Enter a name : ")
            edit(name)
        elif choice == 4:
            name = input("Enter a name : ")
            deletee(name)
        elif choice == 5:
            search()
        elif choice == 6:
            break
        print("\n")
예제 #3
0
    def get(self, query=None):

        """
        Get documentation and demo UI.
        """

        readme_view = markdown(view('../../README.md').decode())
        demo_view = view('demo.htm').decode()
        return responder((demo_view + readme_view).encode(), 'text/html')
예제 #4
0
 def _mkfull(self):
     bclass = self.__class__.__base__
     for rname, idx in self._row_index.items():
         if len(idx) == 1:
             idx = idx[0]
         rclass = bclass()
         for cnames, d in zip(self._col_groups, self._data):
             for cidx, cname in enumerate(cnames):
                 if len(d.shape) == 1:
                     rclass._overattr(cname, view(d, idx))
                 else:
                     rclass._overattr(cname, view(d, (idx, cidx)))
         self._overattr(rname, rclass)
예제 #5
0
파일: table.py 프로젝트: mfittere/pyoptics
 def _mkfull(self):
   bclass=self.__class__.__base__
   for rname,idx in self._row_index.items():
     if len(idx)==1:
       idx=idx[0]
     rclass=bclass()
     for cnames,d in zip(self._col_groups,self._data):
       for cidx,cname in enumerate(cnames):
         if len(d.shape)==1:
           rclass._overattr(cname,view(d,idx) )
         else:
           rclass._overattr(cname,view(d,(idx,cidx)) )
     self._overattr(rname,rclass)
예제 #6
0
 def __init__(self, root):
     self.model = model()
     self.model.make_guess()
     self.view = view(root, self.model.color, self.model.guess,
                      self.model.confidence)
     self.view.bw.config(command=self.white_pressed)
     self.view.bb.config(command=self.black_pressed)
예제 #7
0
    def __init__(self):

        self.M = model()
        self.V = view()

        self.M.setPaintCallback(self.Paint)
        self.M.setMessageCallback(self.systemMessage)

        self.mkLoad()
        self.mkSelect()
        self.mkFunction()
        self.mkDatabus()
        self.mkAddressbus()
        self.mkMemory()
        self.mkPGM()
        self.mkProgramControls()
        self.mkHALT()

        self.Paint()

        m = "\n\n                    WELCOME TO VIRTUAL MACHINE\n"
        m = m + "                       Memory: " + str(
            len(self.M.MEMORY.values())) + " bytes\n"
        m = m + "  ==========================================================\n"
        m = m + "Press README on left...."

        self.systemMessage(m)

        self.V.mainloop()
예제 #8
0
def main():
    mydb = db.init_db()
    s = db.select(mydb.curs)
    products = p.list_of_products()
    v = view.view(s)
    c = controller(v, s, mydb, products)
    c.main_menu_loop()
예제 #9
0
    def __init__(self):

        self.M = model()
        self.V = view()

        self.M.setPaintCallback(self.Paint)
        self.M.setMessageCallback(self.systemMessage)

        self.mkLoad()
        self.mkSelect()
        self.mkFunction()
        self.mkDatabus()
        self.mkAddressbus()
        self.mkMemory()
        self.mkPGM()
        self.mkProgramControls()
        self.mkHALT()

        self.Paint()

        m = "\n\n                    WELCOME TO VIRTUAL MACHINE\n"
        m = m + "                       Memory: " + str(len(self.M.MEMORY.values())) + " bytes\n"
        m = m + "  ==========================================================\n"
        m = m + "Press README on left...."


        self.systemMessage(m)

        self.V.mainloop()
예제 #10
0
def fromast(ast, root=None, lcl=None, special=[], name='mad'):
    if root is None:
        root = madelem(name=name, proto=basemad)
        root.beam = madelem('beam', view({}))
    if lcl is None:
        lcl = root
    current_seq = None
    root._originalnames = {}
    root._madnames = {}
    for i, st in enumerate(ast):
        #print st
        if st is None:
            continue
        name, value = st
        nname = pyname(name)
        root._originalnames[nname] = name
        root._madnames[name] = nname
        name = nname
        kind = value[0]
        if kind == 'variable':
            if name in special:
                value = evaluate(value[1], None)
            else:
                value = evaluate(value[1], lcl)
            setattr(root, name, value)
        elif kind == 'expression':
            value = mkexpr(value[1])
            setattr(root, name, value)
        elif kind == 'element':
            value = value[
                1]  #[element, [[proto,.],[.,.]]] -> [[proto,.],[.,..]]]
            proto = value[0][1]  #can be None
            if proto:
                proto = pyname(proto)
            if name == 'endsequence':
                current_seq.n_elems = len(current_seq._elements)
                current_seq = None
                current_pos = 0
            elif name == 'return':
                pass
            else:
                if name in root:  # element already defined
                    ne = getattr(root, name)
                elif proto == 'sequence':  # special element sequence
                    ne = sequence(name)
                    ne._initseq()
                    current_seq = ne
                else:  # element not defined, therefore has proto
                    proto = getattr(root, proto)
                    ne = madelem(name, proto)
                setattr(root, name, ne)
                ne._parent = root
                fromast(value[1:],
                        root=root,
                        lcl=lcl,
                        special=['refer', 'From'])
                if current_seq is not None and current_seq is not ne:
                    current_seq._append(ne)
    return root
예제 #11
0
 def __init__(self, reddit_api):
     self.model1 = model(reddit_api)
     self.view1 = view()
     self.view1.run()
     self.model1.set_username(self.view1.user_name)
     if len(self.model1.reddit_username) == 0:
         print "Application Terminated"
         exit(1)
예제 #12
0
 def __init__(self, root):
     self.root = root
     self.programa = view(self.root)
     self.administradora = model()
     self.programa.mostrar_row_button.config(command=self.mostrar)
     self.programa.alta_button.config(command=self.agregar_info)
     self.programa.eliminar_button.config(command=self.eliminar)
     self.programa.modificar_button.config(command=self.modificar)
     self.observador = Watcher(self.administradora)
예제 #13
0
def parse_expr(data, proto):
    self = view()
    self._proto = [proto]
    for i in data.split('\n'):
        if i.strip():
            name, value, unit, desc = i.split(None, 3)
            value = expr(value, unit, desc)
            setattr(self, name, value)
    return self
예제 #14
0
파일: expr.py 프로젝트: mfittere/pyoptics
def parse_expr(data,proto):
  self=view()
  self._proto=[proto]
  for i in data.split('\n'):
    if i.strip():
      name,value,unit,desc=i.split(None,3)
      value=expr(value,unit,desc)
      setattr(self,name,value)
  return self
예제 #15
0
파일: madseq.py 프로젝트: mfittere/pyoptics
def fromast(ast,root=None,lcl=None,special=[],name='mad'):
  if root is None:
    root=madelem(name=name,proto=basemad)
    root.beam=madelem('beam',view({}))
  if lcl is None:
    lcl=root
  current_seq=None
  root._originalnames={}
  root._madnames={}
  for i,st in enumerate(ast):
    #print st
    if st is None:
      continue
    name,value=st
    nname=pyname(name)
    root._originalnames[nname]=name
    root._madnames[name]=nname
    name=nname
    kind=value[0]
    if kind=='variable':
      if name in special:
        value=evaluate(value[1],None)
      else:
        value=evaluate(value[1],lcl)
      setattr(root,name,value)
    elif kind=='expression':
      value=mkexpr(value[1])
      setattr(root,name,value)
    elif kind=='element':
      value=value[1] #[element, [[proto,.],[.,.]]] -> [[proto,.],[.,..]]]
      proto=value[0][1] #can be None
      if proto:
        proto=pyname(proto)
      if name=='endsequence':
        current_seq.n_elems=len(current_seq._elements)
        current_seq=None
        current_pos=0
      elif name=='return':
        pass
      else:
        if name in root: # element already defined
          ne=getattr(root,name)
        elif proto=='sequence': # special element sequence
          ne=sequence(name)
          ne._initseq()
          current_seq=ne
        else: # element not defined, therefore has proto
          proto=getattr(root,proto)
          ne=madelem(name,proto)
        setattr(root,name,ne)
        ne._parent=root
        fromast(value[1:],root=root,lcl=lcl,special=['refer','From'])
        if current_seq is not None and current_seq is not ne:
          current_seq._append(ne)
  return root
예제 #16
0
def studentView():
    global ctrl
    if ctrl == None:
        print("router: student view created")
        std_view = view('student')
        std_view.create_student_view()

        dbname = 'student.sqlite'
        modelname = 'teachermodel'
        ctrl = Controller.createController(dbname, modelname, std_view)
    return render_template('student.html')
예제 #17
0
def main():
    viewObj = view()

    #展示登录界面
    viewObj.showLogin()
    #验证管理员登录
    login = viewObj.loginAndExit()
    if login == -1:
        return -1

    filepath = os.path.join(os.getcwd(), "allUsers.txt")
    if os.path.isfile(filepath):
        f = open(filepath, "rb")
        allUsers = pickle.load(f)
        f.close()
    else:
        allUsers = {}

    atmObj = ATM(allUsers)
    while True:
        #展示功能界面
        viewObj.showFunction()
        option = input("请输入您的操作")
        if option == 'open':
            atmObj.createUser()
        elif option == 'search':
            atmObj.searchUser()

        elif option == 'save':
            atmObj.saveMoney()
        elif option == 'withdraw':
            atmObj.withDraw()
        elif option == 'account':
            atmObj.transferMoney()
        elif option == 'passwd':
            pass
        elif option == 'lock':
            atmObj.lockCard()
        elif option == 'unlock':
            atmObj.unlockCard()
        elif option == 'cancel':
            pass
        elif option == 'card':
            pass
        elif option == 'exit':
            if not viewObj.loginAndExit():

                f = open(filepath, "wb")
                pickle.dump(atmObj.allUsers, f)
                f.close()
                return -1

        time.sleep(2)
예제 #18
0
    def instantiate_entity(self, e, soap_client):
        """Instantiate an appropriate python class given an entity returned from a SOAP call.

        :param e: SOAP entity.
        :param soap_client: BAM SOAP client connection for the entity instance to use when accessing the API.
        :return: A type specific instance object of the SOAP entity or generic entity object. None if there is no type.
        """
        if 'type' in e:
            t = e['type']
            if t == entity.Configuration:
                return configuration(self, e, soap_client)
            elif t == entity.User:
                return user(self, e, soap_client)
            elif t == entity.Zone:
                return zone(self, e, soap_client)
            elif t == entity.View:
                return view(self, e, soap_client)
            elif t == entity.IP4Block:
                return ip4_block(self, e, soap_client)
            elif t == entity.IP4Network:
                return ip4_network(self, e, soap_client)
            elif t == entity.HostRecord:
                return host_record(self, e, soap_client)
            elif t == entity.AliasRecord:
                return alias_record(self, e, soap_client)
            elif t == entity.MXRecord:
                return mx_record(self, e, soap_client)
            elif t == entity.TXTRecord:
                return text_record(self, e, soap_client)
            elif t == entity.HINFORecord:
                return host_info_record(self, e, soap_client)
            elif t == entity.SRVRecord:
                return srv_record(self, e, soap_client)
            elif t == entity.NAPTRRecord:
                return naptr_record(self, e, soap_client)
            elif t == entity.ExternalHostRecord:
                return external_host_record(self, e, soap_client)
            elif t == entity.GenericRecord:
                return generic_record(self, e, soap_client)
            elif t == entity.EnumZone:
                return enum_zone(self, e, soap_client)
            elif t == entity.EnumNumber:
                return enum_number(self, e, soap_client)
            elif t in deployment_role.roles:
                return deployment_role(self, e, soap_client)
            elif t == entity.IP4Address:
                return ip4_address(self, e, soap_client)
            elif t == entity.Server:
                return server(self, e, soap_client)
            else:
                return entity(self, e, soap_client)
        else:
            return None
예제 #19
0
def teacherView():
    global ctrl
    if ctrl == None:
        print("router: teacher view created")
        teach_view = view('teacher')
        teach_view.create_teacher_view()

        dbname = 'student.sqlite'
        modelname = 'teachermodel'
        ctrl = Controller.createController(dbname, modelname, teach_view)
    
    return render_template('teacher.html')
예제 #20
0
파일: server.py 프로젝트: jschwab/iota
    def do_view(self, command):
        """View a paper from the paperdir given a docid

        iota> view docid:1
        """
        c = parse_command(command)
        try:
            sexps = view(self.database, **c)
        except TypeError:
            pass
        else:
            self.print_sexp(sexps)
예제 #21
0
def managementView():
    global ctrl
    if ctrl == None:
        print("router: management view created")
        mng_view = view('management')
        mng_view.create_management_view()

        dbname = 'student.sqlite'
        modelname = 'managementModel'
        ctrl = Controller.createController(dbname, modelname, mng_view)

    return render_template('management.html')
예제 #22
0
def http_error(status):
    """
    Create an HTTP error response.

    Arguments:
        status: string HTTP status including code number and description.

    Returns: HTTP response
    """

    error_view = view('error.htm', {'error': status})
    response = responder(error_view, 'text/html', status)
    return response
예제 #23
0
 def _add_cols(self, col_names, data=None, dtype=float):
     if not hasattr(col_names, '__iter__'): col_names = col_names.split()
     if data is None:
         ar = zeros((len(self._row_names), len(col_names)), dtype=dtype)
     else:
         ar = data
     self._data.append(ar)
     for j, n in enumerate(col_names):
         if len(ar.shape) == 1:
             idx = slice(None)
         else:
             idx = (slice(None), j)
         self._overattr(n, view(ar, idx))
     self._col_groups.append(col_names)
예제 #24
0
파일: table.py 프로젝트: mfittere/pyoptics
 def _add_cols(self,col_names,data=None,dtype=float):
   if not hasattr(col_names,'__iter__'):  col_names=col_names.split()
   if data is None:
     ar=zeros( ( len(self._row_names), len(col_names) ),dtype=dtype )
   else:
     ar=data
   self._data.append(ar)
   for j,n in enumerate(col_names):
     if len(ar.shape)==1:
       idx=slice(None)
     else:
       idx=(slice(None),j)
     self._overattr(n,view(ar, idx))
   self._col_groups.append(col_names)
예제 #25
0
def http_error(status):

    """
    Create an HTTP error response.

    Arguments:
        status: string HTTP status including code number and description.

    Returns: HTTP response
    """

    error_view = view('error.htm', {'error': status})
    response = responder(error_view, 'text/html', status)
    return response
예제 #26
0
    def post(self, query, postdata):

        """
        Posting to crawl (AKA /) requests spider(s) to crawl each of the
        specified webpages.

        Arguments:
            query: dict having optional depth=n, where the default is 2.
            postdata: form-urlencoded string must contain newline-separated URLs
                      assigned to a 'urls' variable.

        Returns: HTTP 202 Accepted or 400 Bad Request.
        """

        if 'urls' in postdata:
            urls = postdata['urls'][0].splitlines()
        else:
            return http_error('400 Bad Request')

        try:
            depth = int(query['depth'])
        except KeyError:
            depth = 2

        # Register all URLs with this job even if their results are cached.
        # This allows jobs to be stopped and resumed.
        self.webpages_model.register_job(self.job_id, urls)

        # Iterate through a copy of urls, since items may be removed from it.
        for url in urls[:]:
            status = self.webpages_model.get_status(url)
            webpage_info = self.webpages_model.get_webpage_info(url)

            if 'processing' == status and depth > webpage_info['depth']:
                self.spiders_model.stop(url)

            elif webpage_info['completion_datetime']:
                # Ignore webpages with good depth crawled less than 15 min ago.
                now = datetime.datetime.now()
                td = now - webpage_info['completion_datetime']
                if 900 > td.total_seconds() and depth <= webpage_info['depth']:
                    urls.remove(url)

        self.webpages_model.add(urls, depth=depth)
        self.spiders_model.deploy(self.job_id)

        crawl_view = view('crawl.json', {'job_id': self.job_id})
        return responder(crawl_view, 'application/json', '202 Accepted')
예제 #27
0
    def get_views(self, max_results=100):
        """Get a list of all child views (ref: split horizon DNS) of the configuration upto a maximum number.

        :param max_results: the maximum number of views that will be returned.
        """
        try:
            soap_entities = self._soap_client.service.getEntities(
                self.get_id(), entity.View, 0, max_results)
            if soap_entities.item == '':
                return []
            else:
                return [
                    view(self._api, e, self._soap_client)
                    for e in soap_entities.item
                ]
        except WebFault as e:
            raise api_exception(e.message)
예제 #28
0
파일: cpm.py 프로젝트: peternara/tf-pose
def train_single():
    from view import view

    image_batch, heatmap_batch, center_map_batch = read_and_decode(
        ['{}.tfrecords'.format(i) for i in xrange(3)], batch_size)

    inputs = tf.placeholder(tf.float32, shape=[batch_size, None, None, 3])
    gt_heatmap = tf.placeholder(tf.float32,
                                shape=[batch_size, None, None, joints_num])
    center_map = tf.placeholder(tf.float32, shape=[batch_size, None, None, 1])
    output = cpm(inputs, center_map)
    loss = tf.nn.l2_loss(gt_heatmap - output)
    interm_loss = tf.reduce_sum(
        tf.stack([
            tf.nn.l2_loss(gt_heatmap - o)
            for o in tf.get_collection('heatmaps')
        ]))

    total_loss = loss + interm_loss

    optimizer = tf.train.AdamOptimizer(1e-4).minimize(total_loss)

    with tf.Session() as sess:

        saver = tf.train.Saver()
        sess.run(tf.global_variables_initializer())
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)

        iter_time = time.time()

        images, heatmaps, c_map = sess.run(
            [image_batch, heatmap_batch, center_map_batch])

        view(images[0, :, :, :], heatmaps[0, :, :, :], show_max=False)
        for iters in xrange(150):

            _, e = sess.run([optimizer, loss],
                            feed_dict={
                                inputs: images,
                                center_map: c_map,
                                gt_heatmap: heatmaps
                            })
            print iters, e

        pred = sess.run(output, feed_dict={inputs: images, center_map: c_map})
        view(images[0, :, :, :], pred[0, :, :, :], show_max=True)
        view(images[0, :, :, :], pred[0, :, :, :], show_max=False)
        coord.request_stop()
        coord.join(threads)
        sess.close()
예제 #29
0
 def get_view(self, name):
     """Get a named view (ref: split horizon DNS) out of a configuration. An exception is raised if the
        view doesn't exist.
     """
     try:
         soap_entities = self._soap_client.service.getEntitiesByName(
             self.get_id(), name, entity.View, 0, 10)
     except WebFault as e:
         raise api_exception(e.message)
     if not hasattr(soap_entities, 'item') or len(soap_entities.item) == 0:
         raise api_exception(
             'No view named %s found under configuration %s.' %
             (name, self.get_name()))
     elif len(soap_entities.item) == 1:
         return view(self._api, soap_entities.item[0], self._soap_client)
     else:
         raise api_exception(
             'More than 1 view called %s found under configuration %s.' %
             (name, self.get_name()))
예제 #30
0
    def get(self, query=None):
        """
        Get a list of result images from a given web crawl.

        Arguments:
            query values:
                job_id: integer job id.

        Returns: JSON list of URLs referencing found image files.
        """

        if not 'job_id' in query and not 'url' in query:
            return http_error('400 Bad Request')

        if int == type(query['job_id']):
            images = self.images_model.get_by_job_id(query['job_id'])
        else:
            images = self.images_model.get_by_url(query['url'])

        result_view = view('result.json', {'images': json.dumps(images)})
        return responder(result_view, 'application/json')
예제 #31
0
    def get(self, query=None):

        """
        Get the status of crawling a given URL.

        Arguments:
            query: Integer job_id, job_id=<JOB_ID> assignment, or
                   url=<URL> assignment.
        Returns: JSON spider status
        """

        url = query['url'] if 'url' in query else None
        job_id = query['job_id'] if 'job_id' in query else None
        job_id_specified = int == type(job_id)
        webpage_id = None
        if url:
            webpage_id = self.webpages_model.get_webpage_info(url)['id']

        if not url and not job_id_specified:
            return http_error('400 Bad Request')

        if job_id_specified and not self.jobs_model.job_exists(job_id):
            return http_error('404 Not Found')
        elif url and not webpage_id:
            return http_error('404 Not Found')

        if job_id_specified:
            urls = json.dumps(self.jobs_model.get_init_urls(job_id))
            job_status = json.dumps(self.jobs_model.get_status(job_id))
        else:
            urls = json.dumps([url])
            get_status = self.jobs_model.get_status
            job_ids = self.webpages_model.get_job_ids(url)
            job_status_list = [get_status(job_id) for job_id in job_ids]
            job_status_list = [status for status in job_status_list if status]
            job_status = json.dumps(job_status_list)

        status_view = view('status.json', {'urls': urls,
                                           'job_status': job_status})
        return responder(status_view)
예제 #32
0
    def get(self, query=None):

        """
        Get a list of result images from a given web crawl.

        Arguments:
            query values:
                job_id: integer job id.

        Returns: JSON list of URLs referencing found image files.
        """

        if not 'job_id' in query and not 'url' in query:
            return http_error('400 Bad Request')

        if int == type(query['job_id']):
            images = self.images_model.get_by_job_id(query['job_id'])
        else:
            images = self.images_model.get_by_url(query['url'])

        result_view = view('result.json', {'images': json.dumps(images)})
        return responder(result_view, 'application/json')
예제 #33
0
def main():
    event_handler = view()
    trans = translator()
    announcer = voice()
    mode = 'eng'
    button_init(event_handler)  # start button thread

    while True:
        voc_event = event_handler.voice_flag
        cap_event = event_handler.capture_flag
        ret_val, cam_img = event_handler.handle_capture()
        event_handler.show_img(cam_img)  # show image for testing

        if voc_event:
            # cap_img = event_handler.handle_voice()
            cap_img = cam_img
            # cap_img = cv2.imread('./test/img/test1-eng.jpg')
            # cv2.imshow('gray', cap_img)
            # cv2.waitKey(0)
            paragraph_list, is_eng = preprocess_img(cap_img, mode=mode)

            # if is_eng:
            #     paragraph_list = trans.translate(paragraph_list, 'ko')
            paragraph_list = paragraph_list.split('\n')
            print(paragraph_list)

            ptr_voice = announcer.store_voice(paragraph_list)  # default en

            success = event_handler.print_voice(ptr_voice)

            if not success:
                event_handler.print_error()

            event_handler.set_voice_flag = False

        if cap_event:
            event_handler.handle_capture()

        time.sleep(1)
예제 #34
0
 def fromMatchList(matches,im_i,im_j,
     kp_i=None,kp_j=None,ft_i=None,ft_j=None,Fij=None):
     tr=transitiveclosure()
     if matches is None or len(matches)<12:
         return tr
     has_kp=(type(kp_i)==np.ndarray) and (type(kp_j)==np.ndarray)
     has_ft=(type(ft_i)==np.ndarray) and (type(ft_j)==np.ndarray)
     if has_kp and has_ft:
         for ei,e in enumerate(matches):
             i,j=e
             _kp_i=kp_i[i]
             _kp_j=kp_j[j]
             _ft_i=ft_i[i]
             _ft_j=ft_j[j]
             v1=view(im_i,i,_kp_i[0],_kp_i[1])
             v2=view(im_j,j,_kp_j[0],_kp_j[1])
             v1.feature(f=_ft_i)
             v2.feature(f=_ft_j)
             tr.add_edge(v1,v2)
     elif has_kp:
         for ei,e in enumerate(matches):
             i,j=e
             _kp_i=kp_i[i]
             _kp_j=kp_j[j]
             v1=view(im_i,i,_kp_i[0],_kp_i[1])
             v2=view(im_j,j,_kp_j[0],_kp_j[1])
             tr.add_edge(v1,v2)
     else:
         for ei,e in enumerate(matches):
             i,j=e
             v1=view(im_i,i,-1,-1)
             v2=view(im_j,j,-1,-1) 
             tr.add_edge(v1,v2)
     #tr.assert_every_point_indexed_exist()
     if type(Fij) is np.ndarray:
         print len(tr.points) , "2 view tracks to be filtered"
         filtered_tr=transitiveclosure()
         for track in tr.points.values():
             for new_track in simpleFilter(track,im_i,im_j,Fij,radius=16.):
                 filtered_tr.newPoint(new_track.allViews())
         return filtered_tr
     else:
         return tr
예제 #35
0
            if res:
                break
            res = parse_element(st)
            if res:
                break
            break
        if res is None:
            res = (('class', 'statement'), ('value', st))
        yield res


def parse(fh):
    return parses(fh.read())


base = view(dict(name='mad', l=0))


class madelem(view):
    def __init__(self, name='mad', proto=base, **kwargs):
        self._data = {}
        self._proto = [proto]
        self._lcl = self
        self.name = name
        self._data.update(kwargs)

    def _bind(self, obj, name):
        self.name = name
        self._lcl = obj
        return self
예제 #36
0
def main():

    #    print ("The values are....", roll.roll(min, max), roll.roll(min, max))
    #    print ("The values are....", roll.sum_rolls(3))
    #    print ("Compared to 4 ....", roll.compare_rolls(2, 4))
    #    group = [[1,2],[3,4],[5,6]]
    #    val = roll.sum_rolls(1)
    #    print ("Roll",val,"Matches group",roll.find_group(val, group));
    #    t = team.team(1)
    #    print (t)
    #    t2 = team.team(1)
    #    print (t2)

    #    with open('data.pickle', 'wb') as f:
    # Pickle the 'data' dictionary using the highest protocol available.
    #        pickle.dump(t2, f, pickle.HIGHEST_PROTOCOL)
    #        f.close()

    #    with open('data.pickle', 'rb') as g:
    # The protocol version used is detected automatically, so we do not
    # have to specify it.
    #        data = pickle.load(g)
    #        g.close()

    #    print (data)
    ssn = season.season(2020)

    with open('data.2020', 'wb') as f:
        pickle.dump(ssn, f, pickle.HIGHEST_PROTOCOL)
        f.close()
    with open('data.2020', 'rb') as g:
        data = pickle.load(g)
        g.close()

    print(data)
    f = field.field(int((1800 / 2) - (1598 / 2)), int((900 / 2) - (821 / 2)))
    m = match.match(f)
    #    v = view.view(1598,821)
    v = view.view(1800, 900)
    playing = True

    last = time.time() * 1000
    while (playing == True):
        new = time.time() * 1000
        elapsed = new - last
        if (elapsed >= 20):
            last = new
            v.view_refresh(v.window, f)
            if (m.do_tick() == 0):
                # playing = False
                playing = True

            events = sdl2.ext.get_events()
            for event in events:
                if event.type == sdl2.SDL_QUIT:
                    running = False
                    break
                if event.type == sdl2.SDL_MOUSEBUTTONDOWN:
                    print("Mouse Button Down", event.button.button,
                          event.button.x, event.button.y, event.button.state,
                          event.button.clicks)
                    f.add_ball(event.button.x, event.button.y)
                    # draw_rect(windowsurface, event.button.x, event.button.y, 10, 10)
                    break
                if event.type == sdl2.SDL_MOUSEBUTTONUP:
                    print("Mouse Button Up", event.button.button,
                          event.button.x, event.button.y, event.button.state,
                          event.button.clicks)
                    break
                if event.type == sdl2.SDL_MOUSEMOTION:
                    print("Mouse Motion", event.motion.which,
                          event.motion.state, event.motion.x, event.motion.y,
                          event.motion.xrel, event.motion.yrel)
                    break
                if event.type == sdl2.SDL_MOUSEWHEEL:
                    print("Mouse Wheel", event.wheel.x, event.wheel.y,
                          event.wheel.direction)
                    break
                if event.type == sdl2.SDL_KEYDOWN:
                    print("Key Down: ", event.key.state)
                    if (event.key.keysym.sym == sdl2.SDLK_UP):
                        print("Up Arrow")
                    if (event.key.keysym.sym == sdl2.SDLK_DOWN):
                        print("DOWN Arrow")
                    if (event.key.keysym.sym == sdl2.SDLK_a):
                        print("a")
                    break
예제 #37
0
    def __init__(self):
        self._main_box_ = Tk(className="Gavin")
        self._main_box_.geometry("500x300")
        self.setip()
        self._main_box_.mainloop()

    def setip(self):

        pass

    pass


debug = True
#gui = gun()
# 获取配置文件
cf = configparser.ConfigParser()
path = os.getcwd()
config_file = os.path.join(path, 'data', 'config.ini')
cf.read(config_file)
conf_sections = cf.sections()
url = cf.get('vpn', 'url')

# 初始化VPN
v = vpn(url, debug)
user_agent_object = user_agent()
link_object = links(debug)
view = view(user_agent_object, link_object, v)
view.run(1)
예제 #38
0
파일: madseq.py 프로젝트: nbiancac/pyoptics
      if res:
        break
      res=parse_element(st)
      if res:
        break
      break
    if res is None:
      res=(('class','statement'),('value',st))
    yield res

def parse(fh):
  return parses(fh.read())



base=view(dict(name='mad',l=0))

class madelem(view):
  def __init__(self,name='mad',proto=base,**kwargs):
    self._data={}
    self._proto=[proto]
    self._lcl=self
    self.name=name
    self._data.update(kwargs)
  def _bind(self,obj,name):
    self.name=name
    self._lcl=obj
    return self
  def __setitem__(self,k,v):
    self._data[k]=v
    if isinstance(v,expr):
예제 #39
0
파일: madseq.py 프로젝트: mfittere/pyoptics
      if res:
        break
      res=parse_element(st)
      if res:
        break
      break
    if res is None:
      res=(('class','statement'),('value',st))
    yield res

def parse(fh):
  return parses(fh.read())



base=view(dict(name='mad',l=0))

class madelem(view):
  def __init__(self,name='mad',proto=base,**kwargs):
    self._data={}
    self._proto=[proto]
    self._lcl=self
    self.name=name
    self._data.update(kwargs)
  def _bind(self,obj,name):
    self.name=name
    self._lcl=obj
    return self
  def __setitem__(self,k,v):
    self._data[k]=v
    if hasattr(v,'_bind'):
예제 #40
0
    def __init__(self):

        self.model = model.model()
        self.view = view.view(self.model.game_state)
        self.view_output = self.view.update(([],None,[],self.model.MAX_TIME,self.model.GAME_TIME_LENGTH,0,[0,0]))
예제 #41
0
                if op.lower() == 'yes':
                    viewChangeRequests(cnx, cursor, id)

                    while 1:
                        temp = input("Perform another operation? Yes or No\n")

                        if temp.lower() == 'yes' or temp.lower() == 'no':
                           break
                    if temp.lower() == 'no':
                        break
                    else:
                        continue



            view(cursor)


        elif operation.lower() == 'change':
            changerequest(cnx, cursor, id)

        while 1:
            temp = input("Perform another operation?\n")

            if temp.lower() == 'yes' or temp.lower() == 'no':
                break

        if temp.lower() == "no":
            cnx.commit()
            cnx.close()
            sys.exit()
예제 #42
0
def pbView(v):
    return view(v.image,v.keypoint,v.u,v.v)
예제 #43
0
import view

from Numeric import *

x = arange(-3, 6, .04)
y = arange(-12, 12, .08)
y = sin(y)*exp(-y*y/18.0)
z = x * y[:,NewAxis]
view.view(z)
raw_input()
예제 #44
0
from model import model
from view import view

MODEL = model()
VIEW = view()
request = 0
while request != "3":
    print("1 Dang nhap")
    print("2 Dang ky")
    print("3 thoat chuong trinh")
    print("ban chon chuc nang nao")
    request = input()
    if request == "1":
        status = MODEL.SignIn()
        VIEW.signIn(status)
        if status == 1:
            request1 = "chua ro"
            while request1 != "9":
                print("1 ket ban")
                print("2 Hien thi danh sach ban be")
                print("3 xoa ban be")
                print("4 Chan")
                print("5 loi moi ket ban")
                print("6 Hien thi thong tin chi tiet cua 1 nguoi ban")
                print("7 gui tin nhan")
                print("8 hien thi danh sach tin nhan")
                print("9 thoat")
                request1 = input()
                if request1 == "1":
                    MODEL.addFriendDefault()
                if request1 == "2":
예제 #45
0
파일: root.py 프로젝트: poyhsiao/lzweb
	def config_web(cfg={}):
		# override Cherrypy's default session behaviour

		application_conf = {
			'/' : {
				'tools.staticdir.root': _curdir,
				'tools.staticdir.on' : True,
				'tools.staticdir.dir' : ".",
				'tools.sessions.on'  : True,
				'tools.sessions.storage_type' : "file",
				'tools.sessions.storage_path' : "/tmp/",
				'tools.sessions.timeout' : 60,
				'tools.sessions.locking' : 'explicit',
				'tools.auth.on': True,
				'tools.encode.on' : True,
				'tools.encode.encoding': "utf-8"
			},
			'/favicon.ico' : {
				'tools.staticfile.on' : True,
				'tools.staticfile.filename' : os.path.join(_curdir,'/image/favicon.ico')
			},
			'/css' : {
				'tools.staticdir.on' : True,
				'tools.staticdir.dir' : "css"
			},
			'/script' : {
				'tools.staticdir.on' : True,
				'tools.staticdir.dir' : "script"
			},
			'/image' : {
				'tools.staticdir.on' : True,
				'tools.staticdir.dir' : "image"
			},
		}

		#No Root controller as we provided all our own.
		#cherrypy.tree.mount(root=None, config=config)
		root = Login()
		root.logout = AuthController().logout
		root.xteralink = Interface()
		root.system = summary()
		root.system.summary = summary()
		root.system.dns = dns()
		root.system.network_header = network_header()
		root.system.network = network()
		root.system.wan_detection = wan_detection()
		root.system.fqdn = fqdn()
		root.system.ip_group = ip_group()
		root.system.service_group = service_group()
		root.system.diagnostic_tools = diagnostic_tools()
		root.system.arp_table = arp_table()
		root.system.date_time = date_time()
		root.system.ddns = ddns()
		root.system.administration = administration()
		root.service = dhcp_lan()
		root.service.dhcp_lan = dhcp_lan()
		root.service.dhcp_dmz = dhcp_dmz()
		root.service.virtual_server = virtual_server()
		root.service.firewall = firewall()
		root.service.connection_limit = connection_limit()
		root.service.auto_routing = auto_routing()
		root.service.nat = nat()
		root.service.snmp = snmp()
		root.statistics = stat_bandwidth_utilization()
		root.statistics.stat_bandwidth_utilization = stat_bandwidth_utilization()
		root.statistics.stat_wan_detection = stat_wan_detection()
		root.statistics.stat_dhcp_lan = stat_dhcp_lan()
		root.statistics.stat_dhcp_dmz = stat_dhcp_dmz()
		root.statistics.stat_fqdn = stat_fqdn()
		root.log = view();
		root.log.view = view();
		root.log.syslog = syslog();
		cherrypy.tree.mount(root, "/", config=application_conf)

		cherrypy.server.unsubscribe()
		server1 = cherrypy._cpserver.Server()
		server1.socket_port = 443
		server1._socket_host = '0.0.0.0'
		server1.ssl_certificate = '/usr/local/conf/server.crt'
		server1.ssl_private_key = '/usr/local/conf/server.key'
		server1.subscribe()

		server2 = cherrypy._cpserver.Server()
		server2.socket_port = 80
		server2._socket_host = "0.0.0.0"
		server2.subscribe()