Пример #1
0
def hyperopt_search(variant: cco.Variant,
                    data,
                    max_evals,
                    mix_algo_ratio=None,
                    random_state=None):
    timer = stopwatch.Timer()
    if variant.is_gb():
        clf_hp_gb.do_fmin(
            data,
            max_evals,
            mix_algo_ratio=mix_algo_ratio,
            max_depth_space=hp.pchoice("max_depth", [(0.40, 1), (0.60, 2)]),
            random_state=random_state,
        )
    elif variant.is_rf():
        clf_hp_rf.do_fmin(
            data,
            max_evals,
            mix_algo_ratio=mix_algo_ratio,
            max_depth_space=hp.pchoice("max_depth", [(0.45, 1), (0.55, 2)]),
            random_state=random_state,
        )
    elif variant.is_cb_native():
        pools = clf_cat_tools.make_pools(data)
        clf_hp_cb.do_fmin(
            pools,
            max_evals,
            mix_algo_ratio=mix_algo_ratio,
            random_state=random_state,
            how="native",
        )
    sec_elapsed = timer.elapsed
    cco.out("{} done for {}".format(variant.name, cco.fmt(sec_elapsed)))
Пример #2
0
def mainMenu():
    """
    """
    global language
    callid = db.getID()
    # callid = int(callid) + 1 
    tmm = stopwatch.Timer()
    debugPrint("STARTING MAIN MENU")
    language = 'hindi'
    debugPrint("LANGUAGE IS "+language)
    keyDict = newKeyDict()
    keyDict['1'] = (addComment,())
    keyDict['2'] = (playBack,('skip-post-1',))
    keyDict['3'] = (invalidDigit,(3, 'Main Menu', tmm,))
    keyDict['4'] = (invalidDigit,(4, 'Main Menu', tmm,))
    keyDict['5'] = (invalidDigit,(5, 'Main Menu', tmm,))
    keyDict['6'] = (invalidDigit,(6, 'Main Menu', tmm,))
    keyDict['7'] = (invalidDigit,(7, 'Main Menu', tmm,))
    keyDict['8'] = (invalidDigit,(8, 'Main Menu', tmm,))
    keyDict['9'] = (invalidDigit,(9, 'Main Menu', tmm,))
    try:
        playFile(PROMPTS_DIR+'welcome', keyDict)
        for i in range(1,4):
            playFile(PROMPTS_DIR+'record-1', keyDict)
            playFile(PROMPTS_DIR+'listen-2', keyDict)
            playFile(PROMPTS_DIR+'wait-5-seconds', keyDict) 
        hangup()
    except KeyPressException, e:       
        raise
    def Preprocess(self):
        LC_DBList = [
            'IRCR_LC14_313', 'IRCR_LC14_319', 'IRCR_LC14_320', 'IRCR_LC14_394',
            'IRCR_LC14_423', 'IRCR_LC14_435', 'IRCR_LC14_436', 'IRCR_LC14_440',
            'IRCR_LC14_443'
        ]
        t = stw.Timer()

        LC_train = self.Initialise_Dataset_by_Group("SGI20170607") + LC_DBList
        GBM_train = self.Initialise_Dataset_by_Group(
            "SGI20161017") + self.Initialise_Dataset_by_Group(
                "SGI20160613") + self.Initialise_Dataset_by_Group(
                    "MACROGEN_20151218")
        testList = self.Initialise_Dataset_by_Group(
            "MACROGEN_20160307") + self.Initialise_Dataset_by_Group(
                "SGI20160831") + self.Initialise_Dataset_by_Group(
                    "MACROGEN_20160516") + self.Initialise_Dataset_by_Group(
                        "TERAGEN20151119")
        labelList = self.Labeling_for_Supervised_Learning(
            LC_train, 0) + self.Labeling_for_Supervised_Learning(
                GBM_train, 1) + self.Labeling_for_Supervised_Learning(
                    testList, 1)
        DF_train = self.Merge_DataFrame(LC_train + GBM_train + testList,
                                        'ircr1')
        X = np.asarray(DF_train, dtype=float)
        y = np.asarray(labelList, dtype=int)
        t.stop()
        print "For Preprocessing, Time elapsed ", t.elapsed
        self.Divide_Training_Test(X, y)
Пример #4
0
 def define_players(self, company_name, sex):
     if self.define_players_tried:
         return self.players_defined()
     self.define_players_tried = True
     pre_live_dir.prepare_dir("matches")
     if pre_live_dir.is_data(self.pre_live_name()):
         self.load_pre_live_data()
         return self.players_defined()
     abbr_names = self.name.split(" - ")
     if len(abbr_names) == 2:
         timer = stopwatch.Timer()
         if not self.first_player:
             self.first_player = player_name_ident.identify_player(
                 company_name, sex, abbr_names[0].strip()
             )
         if not self.second_player:
             self.second_player = player_name_ident.identify_player(
                 company_name, sex, abbr_names[1].strip()
             )
         if self.first_player and self.second_player:
             self.read_ratings(sex)
             self.read_birth_date(sex)
             self.head_to_head = tennis.HeadToHead(sex, self, completed_only=True)
             self.h2h_direct = self.head_to_head.direct()
             self.fst_last_res = last_results.LastResults(
                 sex, self.first_player.ident, weeks_ago=5
             )
             self.snd_last_res = last_results.LastResults(
                 sex, self.second_player.ident, weeks_ago=5
             )
             # other features temporary removed
         self.def_plr_seconds = timer.elapsed
     return self.players_defined()
Пример #5
0
 def __start_job(self):
     """Starts up a process if the resources are available.        
     """
     if len(self._running) < self._nprocesses and len(self._queue) > 0:
         job = self._queue.pop()
         self._running.append(job)
         self.times[job.getName()] = stopwatch.Timer()
         job.start()
Пример #6
0
def playBack(intro=None):
    keyDict = newKeyDict()
    posts = db.getPostsInChannel('12345')
    if len(posts) == 0:
        return playFile(PROMPTS_DIR+'no-comments', keyDict)
    playFile(PROMPTS_DIR+'mistake-0', keyDict)
    playFile(PROMPTS_DIR+intro, keyDict)
    count = 0
    for postID in posts:
        os.system("echo %s >> /opt/swara/log.txt" %(postID))
	tpb = stopwatch.Timer()
        count = count + 1
        if (count==5):
            break
        keyDict['1'] = (skipComment,(postID, tpb))
        keyDict['3'] = (invalidDigit,(3, 'Playback', tpb,))
        keyDict['4'] = (invalidDigit,(4, 'Playback', tpb,))
        keyDict['5'] = (invalidDigit,(5, 'Playback', tpb,))
        keyDict['6'] = (invalidDigit,(6, 'Playback', tpb,))
        keyDict['7'] = (invalidDigit,(7, 'Playback', tpb,))
        keyDict['8'] = (invalidDigit,(8, 'Playback', tpb,))
        keyDict['9'] = (invalidDigit,(9, 'Playback', tpb,))
        commentFile = SOUND_DIR+str(postID)
        keyPress = playFile(commentFile, keyDict)
        if keyPress == '1': # If user presses 1, skip to next comment.
            pass
        db.addPlaybackEvent(postID, tpb, callID) #ARJUN PATCHED with CallID
    tpbm = stopwatch.Timer()
    playFile(PROMPTS_DIR+'for-older-posts')
    keyDict2 = newKeyDict()
    keyDict2['1'] = (addComment,())
    keyDict2['2'] = (playBack,('skip-post-1',))
    keyDict2['3'] = (invalidDigit,(3, 'Main Menu after Playback', tpbm,))
    keyDict2['4'] = (invalidDigit,(4, 'Main Menu after Playback', tpbm,))
    keyDict2['5'] = (invalidDigit,(5, 'Main Menu after Playback', tpbm,))
    keyDict2['6'] = (invalidDigit,(6, 'Main Menu after Playback', tpbm,))
    keyDict2['7'] = (invalidDigit,(7, 'Main Menu after Playback', tpbm,))
    keyDict2['8'] = (invalidDigit,(8, 'Main Menu after Playback', tpbm,))
    keyDict2['9'] = (invalidDigit,(9, 'Main Menu after Playback', tpbm,))
    playFile(PROMPTS_DIR+'this-cgnet-swara', keyDict2)
    for i in range(1,4):
        playFile(PROMPTS_DIR+'record-1', keyDict2)
        playFile(PROMPTS_DIR+'listen-2', keyDict2)
        playFile(PROMPTS_DIR+'wait-5-seconds', keyDict2)
    hangup()
 def TCGA_Set(self):
     t = stw.Timer()
     with open("/home/jsgene/JK1/NGS/exec_history/TCGA_rpkm.pkl",
               'r') as pp:
         DF_TCGA = pickle.load(pp)
     with open("/home/jsgene/JK1/NGS/exec_history/TCGA_array_subtype.pkl",
               'r') as p:
         ID_List = pickle.load(p)
     DF_TCGA.index = ID_List
Пример #8
0
def addComment():
    playFile(PROMPTS_DIR + 'mistake-0')
    cdr_id = db.getcallIDByUser(user)
    countKeyPress(1, cdr_id)
    # ignore hangup during recording
    signal.signal(signal.SIGHUP, signal.SIG_IGN)
    while True:
        commentTempFileName = recordFileNoPlayback(
            PROMPTS_DIR + 'record-message-beep', 300)
        if commentTempFileName:
            break
    #Arjun edited to add caller ID in main page
    os.system("echo %s >> /opt/swara/log.txt" % (user))
    auth = db.getAuthDetails(user)
    os.system("echo %s >> /opt/swara/log.txt" % (auth))
    if auth == 0:
        auth = db.addAuthor(user)

    # convert temp wav file to temp mp3 file
    output = os.popen("/usr/local/bin/lame -h --abr 200 " + AST_SOUND_DIR +
                      commentTempFileName + ".wav " + AST_SOUND_DIR +
                      commentTempFileName + ".mp3").read().strip()

    # test size of MP3 file
    try:
        audio = MP3(AST_SOUND_DIR + commentTempFileName + ".mp3")
        # outside of the training channel, only keep audio files that are longer than 20 seconds
        if (swaraChannel == "training" or float(audio.info.length) >= 20):
            newCommentID = db.addCommentToChannel(user, auth, '12345',
                                                  swaraChannel)
            #newCommentID = db.addCommentToChannel(user, '12345')
            os.rename(AST_SOUND_DIR + commentTempFileName + ".mp3",
                      SOUND_DIR + "web/" + str(newCommentID) + ".mp3")
            os.rename(AST_SOUND_DIR + commentTempFileName + ".wav",
                      SOUND_DIR + str(newCommentID) + ".wav")
            #os.system("/usr/local/bin/lame -h --abr 200 "+SOUND_DIR+str(newCommentID)+".wav "+SOUND_DIR+"/web/" \
            os.system("echo '%s' >> /var/log/swara.log" % (output))
            db.addMessageRecordEvent(newCommentID, callID)
    except IOError:
        os.system("IO Error processing MP3 " + AST_SOUND_DIR +
                  commentTempFileName + ".mp3 >> /var/log/swara.log")

    # process hangup again
    signal.signal(signal.SIGHUP, signal.SIG_DFL)
    # server = smtplib.SMTP('smtp.gmail.com:587')
    # server.ehlo()
    # server.starttls()
    # server.ehlo()
    # server.login(username,password)
    # server.sendmail(fromaddr, toaddrs, msg)
    # server.quit()
    trm = stopwatch.Timer()
    playFile(PROMPTS_DIR + 'thank-you-submitted')
    hangup()
    quit()
    exit()
Пример #9
0
 def process_view(self, request, view, args, kwargs):
     logger.info('profile wrapper called')
     timer = stopwatch.Timer()
     
     cput1 = time.clock()
     
     response = view(request, *args, **kwargs)
     
     exectime = timer.stop()
     cput2 = time.clock()
     cputime = cput2 - cput1
     
     
     if not request.session.get('ga-report-id'):
         '''
         Create Reporting Id to be injected into ga.js in process_response,
         and save it as a session variable on a day by day basis.
         
         The session data now gets passed to transmit functions
         through the request object.
         '''
         now=datetime.datetime.now()
         lifetime=( datetime.datetime(now.year, now.month, now.day +1, 0) - now ).total_seconds()
         new_user = User(creation_time=now,expiration_time=lifetime )
         new_user.save()
         
         request.session.__setitem__('ga-report-id', new_user.analytics_id)
         request.session.set_expiry( lifetime )
     
     if appsettings.BUNDLE_DATA:
         actions.TransmitBundledData(request, kwargs,
                                     simplejson.dumps(connection.queries),
                                     exectime, cputime,
                                     memory.GetAggregateMemcacheStats(),
                                     sender=view)
     else:
         if getattr(settings, 'PROFILE_QUERIES', True):
             actions.TransmitQueries(request, kwargs,
                                     queries=connection.queries,
                                     sender=view)
         
         if getattr(settings, 'PROFILE_BENCHMARKS', True):
             actions.TransmitBenchmark(request, kwargs,
                                       exectime, cputime,
                                       sender=view)
         
         if getattr(settings, 'PROFILE_MEMCACHE_STATS', True):
             actions.TransmitMemcacheStats(request, kwargs,
                                           stats=memory.GetAggregateMemcacheStats(),
                                           sender=view)
         
         if getattr(settings, 'PROFILE_USER_ACTIVITY', True):
             actions.TransmitUserActivity(request, kwargs,
                                          sender=view)
     
     return response
Пример #10
0
 def loadDTD(self):
     if self.DTD:
         return
     timerInterval = stopwatch.Timer()
     log("Loading ENML DTD", "lxml", timestamp=False, do_print=True)
     self.DTD = etree.DTD(FILES.ANCILLARY.ENML_DTD)
     log("DTD Loaded in %s\n" % str(timerInterval),
         "lxml",
         timestamp=False,
         do_print=True)
     log('    > Note Validation: ENML DTD Loaded in %s' %
         str(timerInterval))
     del timerInterval
Пример #11
0
    def BubbleSort(self, delay, draw_data):
        """ Sorts an array via swapping elements if the next is greater. """
        timer = stopwatch.Timer()
        timer.start()
        passNumber = 0

        for i in range(len(self.array)):
            passNumber += 1
            for j in range(0, len(self.array) - i - 1): # last i elements are already in place 
                if self.array[j] > self.array[j+1] :  # Swap if the element found is greater    
                    self.array[j], self.array[j+1] = self.array[j+1], self.array[j]
                    draw_data(self.array, ['green' if x == j or x == j+1 else 'red' for x in range(len(self.array))] )
                    time.sleep(delay)
        
        print(timer.stop())
Пример #12
0
    def create_evernote_notes(self,
                              evernote_guids=None,
                              use_local_db_only=False):
        """
        Create EvernoteNote objects from Evernote GUIDs using EvernoteNoteFetcher.getNote().
        Will prematurely return if fetcher.getNote fails

        :rtype : EvernoteNoteFetcherResults
        :param evernote_guids:
        :param use_local_db_only: Do not initiate API calls
        :return: EvernoteNoteFetcherResults
        """
        if not hasattr(self, 'evernote_guids') or evernote_guids:
            self.evernote_guids = evernote_guids
        if not use_local_db_only:
            self.check_ancillary_data_up_to_date()
        action_str_base = 'Create'
        action_str = 'Creation Of'
        info = stopwatch.ActionInfo(action_str,
                                    'Evernote Notes',
                                    report_if_empty=False)
        tmr = stopwatch.Timer(evernote_guids,
                              info=info,
                              label='Add\\Evernote-%sNotes' %
                              (action_str_base))
        fetcher = EvernoteNoteFetcher(self,
                                      use_local_db_only=use_local_db_only)
        if not evernote_guids:
            fetcher.results.Status = EvernoteAPIStatus.EmptyRequest
            return fetcher.results
        if in_anki():
            fetcher.evernoteQueryTags = SETTINGS.EVERNOTE.QUERY.TAGS.fetch(
            ).replace(',', ' ').split()
            fetcher.keepEvernoteTags = SETTINGS.ANKI.TAGS.KEEP_TAGS.fetch()
            fetcher.deleteQueryTags = SETTINGS.ANKI.TAGS.DELETE_EVERNOTE_QUERY_TAGS.fetch(
            )
            fetcher.tagsToDelete = SETTINGS.ANKI.TAGS.TO_DELETE.fetch(
            ).replace(',', ' ').split()
        for evernote_guid in self.evernote_guids:
            if not fetcher.getNote(evernote_guid):
                return fetcher.results
            tmr.reportSuccess()
            tmr.step(fetcher.result.Note.FullTitle)
        tmr.Report()
        return fetcher.results
Пример #13
0
def addComment():
    playFile(PROMPTS_DIR+'mistake-0')
    while True:
        commentTempFileName = recordFileNoPlayback(PROMPTS_DIR+'record-message-beep',300)
        if commentTempFileName:
            break
    os.system("echo %s >> /opt/swara/log.txt" %(user))
    auth=db.getAuthDetails(user)
    os.system("echo %s >> /opt/swara/log.txt" %(auth))
    if auth == 0:
        auth=db.addAuthor(user)
    newCommentID = db.addCommentToChannel(user, auth,'12345')
    os.rename(AST_SOUND_DIR+commentTempFileName+".wav", SOUND_DIR+str(newCommentID)+".wav")
    #os.system("/usr/local/bin/lame -h --abr 200 "+SOUND_DIR+str(newCommentID)+".wav "+SOUND_DIR+"/web/" \
    output=os.popen("/usr/local/bin/lame -h --abr 200 "+SOUND_DIR+str(newCommentID)+".wav "+SOUND_DIR+"/web/" \
                                                             + str(newCommentID)+".mp3").read().strip()
    os.system("echo '%s' >> /var/log/swara.log" %(output))
    db.addMessageRecordEvent(newCommentID, callID)
    # server = smtplib.SMTP('smtp.gmail.com:587')
    # server.ehlo()
    # server.starttls()
    # server.ehlo()
    # server.login(username,password)
    # server.sendmail(fromaddr, toaddrs, msg)
    # server.quit()
    trm = stopwatch.Timer()
    playFile(PROMPTS_DIR+'thank-you-submitted')
    keyDict2 = newKeyDict()
    keyDict2['1'] = (addComment,())
    keyDict2['2'] = (playBack,('skip-post-1',))
    keyDict2['3'] = (invalidDigit,(3, 'Main Menu after Recording', trm,))
    keyDict2['4'] = (invalidDigit,(4, 'Main Menu after Recording', trm,))
    keyDict2['5'] = (invalidDigit,(5, 'Main Menu after Recording', trm,))
    keyDict2['6'] = (invalidDigit,(6, 'Main Menu after Recording', trm,))
    keyDict2['7'] = (invalidDigit,(7, 'Main Menu after Recording', trm,))
    keyDict2['8'] = (invalidDigit,(8, 'Main Menu after Recording', trm,))
    keyDict2['9'] = (invalidDigit,(9, 'Main Menu after Recording', trm,))
    for i in range(1,4):
        playFile(PROMPTS_DIR+'this-cgnet-swara', keyDict2)
        playFile(PROMPTS_DIR+'record-1', keyDict2)
        playFile(PROMPTS_DIR+'listen-2', keyDict2)
        playFile(PROMPTS_DIR+'wait-5-seconds', keyDict2)
    hangup()
Пример #14
0
    def wrapped(request, *args, **kwargs):
        logger.info('profile wrapper called')
        timer = stopwatch.Timer()
        cput1 = time.clock()

        response = fn(request, *args, **kwargs)
        exectime = timer.stop()
        cput2 = time.clock()

        cputime = cput2 - cput1

        if appsettings.BUNDLE_DATA:
            actions.TransmitBundledData(request,
                                        kwargs,
                                        simplejson.dumps(connection.queries),
                                        exectime,
                                        cputime,
                                        memory.GetAggregateMemcacheStats(),
                                        sender=fn)
        else:
            if getattr(settings, 'PROFILE_QUERIES', True):
                actions.TransmitQueries(request,
                                        kwargs,
                                        queries=connection.queries,
                                        sender=fn)

            if getattr(settings, 'PROFILE_BENCHMARKS', True):
                actions.TransmitBenchmark(request,
                                          kwargs,
                                          exectime=exectime,
                                          cputime=cputime,
                                          sender=fn)

            if getattr(settings, 'PROFILE_MEMCACHE_STATS', True):
                actions.TransmitMemcacheStats(request,
                                              kwargs,
                                              stats=memory.GetMemcacheStats(),
                                              sender=fn)

            if getattr(settings, 'PROFILE_USER_ACTIVITY', True):
                actions.TransmitUserActivity(request, kwargs, sender=fn)

        return response
Пример #15
0
        def inner_decorator(request, *args, **kwargs):
            ls = map(lambda x: x.lower(), components)

            sql = 'sql' in ls or 'query' in ls or 'queries' in ls
            benchmark = 'benchmark' in ls or 'benchmarks' in ls
            memcache = 'memcached' in ls or 'memcache' in ls
            useractivity = 'useractivity' in ls or 'user activity' in ls

            if benchmark and getattr(settings, 'PROFILE_BENCHMARKS', True):
                timer = stopwatch.Timer()
                cput1 = time.clock()
                response = func(request, *args, **kwargs)
                exectime = timer.stop()
                cput2 = time.clock()

                cputime = cput2 - cput1

                actions.TransmitBenchmark(request,
                                          kwargs,
                                          exectime=exectime,
                                          cputime=cputime,
                                          sender=func)

            else:
                response = func(request, *args, **kwargs)

            if sql and getattr(settings, 'PROFILE_QUERIES', True):
                actions.TransmitQueries(request,
                                        kwargs,
                                        queries=connection.queries,
                                        sender=func)

            if memcache and getattr(settings, 'PROFILE_MEMCACHE_STATS', True):
                actions.TransmitMemcacheStats(request,
                                              kwargs,
                                              stats=memory.GetMemcacheStats(),
                                              sender=func)

            if useractivity and getattr(settings, 'PROFILE_USER_ACTIVITY',
                                        True):
                actions.TransmitUserActivity(request, kwargs, sender=func)

            return response
Пример #16
0
    def countdown(self, extent, n_of_products):
        del self.u_arr[:]
        del self.d_arr[:]

        time = stopwatch.Timer()
        self.fill_arrs()
        print
        print "Elapsed time for fill_ars = ", time.elapsed
        print "Number of item(s) compared: ", len(
            self.u_arr), "Number of items in the dataset: ", len(self.d_arr)
        mark = time.elapsed
        self.compare_products(self.u_arr, self.d_arr)
        print "Elapsed time for compare_products = ", time.elapsed - mark
        mark = time.elapsed
        self.filter_products(extent)
        print "Elapsed time for filter_products = ", time.elapsed - mark
        time.stop()
        print "Elapsed time for 1 product = ", time.elapsed
        print "Elapsed time for ", n_of_products, " products = ", time.elapsed * n_of_products
        print
Пример #17
0
 def run(self):
     self.runtime = stopwatch.Timer()
     try:
         while len(self._queue) > 0 or len(self._running) > 0:
             # currently asymmetric (multiple jobs can be removed,
             # only a single one can be started within a loop
             self.__handle_finished()
             self.__start_job()
     except (KeyboardInterrupt, SystemExit):
         # make sure to kill processes to avoid runaways
         for job in self._running:
             try:
                 job.terminate()
             except:
                 # ignore
                 pass
             self.times[job.getName()].stop()
         raise
     finally:
         self.__finished = True
         self.runtime.stop()
Пример #18
0
def countKeyPress(key, callID):
    t = stopwatch.Timer()
    # keyDict = newKeyDict()
    # keyDict['8'] = (countKeyPress,(8,callID))
    debugPrint("From main_menu.py User pressed %c " % (chr(int(key))))
    db.recordKeyPress(key, user, callID)
Пример #19
0
            return self.recursive(n-1) + self.recursive(n-2)
 
    def dynamic(self, n):
        """
        This method will calculate the fibonacci value of n using dynamic programming
        Will determine fib for every number up to n and use stored answers for previously calculated numbers
        The higher n is the more efficient this method is compared to recursion
        """
        if n < 2:
            # print(f"Returning {n}")
            return n
        else:
            # add to the list for every number up to n
            # we know 0 and 1, start at 2
            for i in range(2, n):
                # print(f"Appending ({self.f[i-1]}) + ({self.f[i-2]})")
                self.f.append(self.f[i-1] + self.f[i-2])
            # the answer will be the sum of the last 2 list items
            return self.f[-1] + self.f[-2]


Fibonacci1 = Fibonacci(int(input("Find fibonacci of: ")))  #Creates object
timer = stopwatch.Timer()
timer2 = stopwatch.Timer()
timer.start()
print(Fibonacci1.recursive(Fibonacci1.n))
print(f"{timer.stop()}")
print("===========================================================")
timer2.start()
print(Fibonacci1.dynamic(Fibonacci1.n))
print(f"{timer2.stop()}")
Пример #20
0
def playBackImpact(intro=None):
    keyDict = newKeyDict()
    cdr_id = db.getcallIDByUser(user)
    countKeyPress(3, cdr_id)
    # temporary fix so that incoming calls have a user
    posts = db.getImpactPostsInChannel('12345', swaraChannel, user)
    if len(posts) == 0:
        return playFile(PROMPTS_DIR + 'no-comments', keyDict)
    playFile(PROMPTS_DIR + 'mistake-0', keyDict)
    playFile(PROMPTS_DIR + intro, keyDict)
    count = 0
    for postID in posts:
        tpb = stopwatch.Timer()
        count = count + 1
        if (count == 5):
            break
        keyDict['1'] = (skipComment, (postID, tpb))
        keyDict['3'] = (invalidDigit, (
            3,
            'Playback',
            tpb,
        ))
        keyDict['4'] = (invalidDigit, (
            4,
            'Playback',
            tpb,
        ))
        keyDict['5'] = (invalidDigit, (
            5,
            'Playback',
            tpb,
        ))
        keyDict['6'] = (invalidDigit, (
            6,
            'Playback',
            tpb,
        ))
        keyDict['7'] = (invalidDigit, (
            7,
            'Playback',
            tpb,
        ))
        keyDict['8'] = (countKeyPress, (8, cdr_id))
        keyDict['9'] = (invalidDigit, (
            9,
            'Playback',
            tpb,
        ))
        commentFile = SOUND_DIR + str(postID)
        keyPress = '8'
        while keyPress == '8':
            keyPress = playFile(commentFile, keyDict)

        if keyPress == '1':  # If user presses 1, skip to next comment.
            pass

        db.addImpactPlaybackEvent(postID, tpb,
                                  callID)  #ARJUN PATCHED with CallID
    tpbm = stopwatch.Timer()
    playFile(PROMPTS_DIR + 'for-older-posts')
    keyDict2 = newKeyDict()
    keyDict2['1'] = (addComment, ())
    keyDict2['2'] = (playBack, ('skip-post-1', ))
    keyDict2['3'] = (playBackImpact, ('skip-post-1', ))
    keyDict2['4'] = (invalidDigit, (
        4,
        'Main Menu after Playback',
        tpbm,
    ))
    keyDict2['5'] = (invalidDigit, (
        5,
        'Main Menu after Playback',
        tpbm,
    ))
    keyDict2['6'] = (invalidDigit, (
        6,
        'Main Menu after Playback',
        tpbm,
    ))
    keyDict2['7'] = (invalidDigit, (
        7,
        'Main Menu after Playback',
        tpbm,
    ))
    keyDict2['8'] = (invalidDigit, (
        8,
        'Main Menu after Playback',
        tpbm,
    ))
    keyDict2['9'] = (invalidDigit, (
        9,
        'Main Menu after Playback',
        tpbm,
    ))
    playFile(PROMPTS_DIR + 'this-cgnet-swara', keyDict2)
    for i in range(1, 4):
        playFile(PROMPTS_DIR + 'record-1', keyDict2)
        playFile(PROMPTS_DIR + 'listen-2', keyDict2)
        playFile(PROMPTS_DIR + 'impact-3', keyDict)
        playFile(PROMPTS_DIR + 'wait-5-seconds', keyDict2)
    hangup()
Пример #21
0
        def cleanAndReturnListofEtfs():
            fundList = []
            name = askopenfilename(filetypes=(("Excel", "*.xlsx"),
                                              ("All files", "*.*")))
            workbook = xlrd.open_workbook(name)
            worksheet = workbook.sheet_by_name('Sheet1')
            num_rows = worksheet.nrows - 1
            num_cells = worksheet.ncols - 1
            curr_row = -1
            while curr_row < num_rows:
                curr_row += 1
                row = worksheet.row(curr_row)
                #print 'Row:', curr_row
                curr_cell = -1
                while curr_cell < num_cells:
                    curr_cell += 1
                    # Cell Types: 0=Empty, 1=Text, 2=Number, 3=Date, 4=Boolean, 5=Error, 6=Blank
                    cell_type = worksheet.cell_type(curr_row, curr_cell)
                    cell_value = worksheet.cell_value(curr_row, curr_cell)
                    cell_value = str(cell_value)
                    fundList.append(cell_value)

            self.rootURLStr = StringVar()

            self.rootURLNum = self.rootURLNum.get()
            if (self.rootURLNum == 1):
                self.rootURLStr = "http://www.etf.com/"
            elif (self.rootURLNum == 2):
                self.rootURLStr = "http://www.maxfunds.com/funds/data.php?ticker="
            elif (self.rootURLNum == 3):
                self.rootURLStr = "http://www.marketwatch.com/investing/Fund/"

            row = 0
            t = stopwatch.Timer()

            for etfSymbol in fundList:
                row += 1
                #self.progress.set(etfList.index(etfSymbol))
                myEtf = ETFDataCollector(etfSymbol, row, self.rootURLStr)
                myEtf.parseTargetWebPage()
                #use an if statement to find out which website we are scraping
                if (self.rootURLStr == "http://www.etf.com/"):
                    try:
                        myEtf.etfDotComInfo()
                    except:
                        e = sys.exc_info()[0]
                        self.ETFInfoToWrite = [etfSymbol]
                        ETFInfoToWrite = self.ETFInfoToWrite
                        excel = excelSetup(ETFInfoToWrite, row)
                        excel.etfInfoSetup()
                        e = ""
                    else:
                        pass
                elif (self.rootURLStr ==
                      "http://www.maxfunds.com/funds/data.php?ticker="):
                    try:
                        myEtf.maxfundsDotComInfo()
                    except:
                        e = sys.exc_info()[0]
                        self.ETFInfoToWrite = [etfSymbol]
                        ETFInfoToWrite = self.ETFInfoToWrite
                        excel = excelSetup(ETFInfoToWrite, row)
                        excel.maxfundsSetup()
                        e = ""
                    else:
                        pass
                elif (self.rootURLStr ==
                      "http://www.marketwatch.com/investing/Fund/"):
                    try:
                        myEtf.smartmoneyDotComInfo()
                    except:
                        e = sys.exc_info()[0]
                        self.ETFInfoToWrite = [etfSymbol]
                        ETFInfoToWrite = self.ETFInfoToWrite
                        excel = excelSetup(ETFInfoToWrite, row)
                        excel.smartmoneySetup()
                        e = ""
                    else:
                        pass
            t.stop()
            print str(t.elapsed) + " elapsed time"
            #close the window
            master.destroy()
Пример #22
0
	textpos = text.get_rect(centerx=background.get_width() / 2, centery=background.get_height() / 2)

	screen.blit(background, (0, 0))
	screen.blit(text, textpos)
	pygame.display.flip()

	
	while running:
		screen.fill(pygame.Color("black"))
		serialInput = ser.readline()
		serialInput = serialInput.strip()

		print serialInput

		if serialInput == "start":
			timer = stopwatch.Timer()
			start_timer()

		elif serialInput == "stop":	
			if timer:
				timer.stop()
				start = format_time(timer.elapsed)

				text = fontLarge.render(start, 1, fontColorGreen)
				textpos = text.get_rect(centerx=background.get_width() / 2, centery=background.get_height() / 2)

				screen.fill(pygame.Color("black"))
				screen.blit(background, (0, 0))
				screen.blit(text, textpos)

				pygame.display.flip()
Пример #23
0
 def setUp(self):
     self.timer = stopwatch.Timer()