Beispiel #1
0
def get_properties(ebuild):
    """Get all ebuild variables in one chunk."""
    ebuild = str(ebuild)  #just in case
    if portage.portdb.cpv_exists(ebuild):  # if in portage tree
        try:
            return Properties(
                dict(
                    list(
                        zip(keys,
                            portage.portdb.aux_get(ebuild,
                                                   portage.auxdbkeys)))))
        except IOError as e:  # Sync being performed may delete files
            dprint(" * PKGCORE_LIB: get_properties(): IOError: " + e)
            return Properties()
    else:
        vartree = portage.db['/']['vartree']
        if vartree.dbapi.cpv_exists(ebuild):  # elif in installed pkg tree
            return Properties(
                dict(
                    list(
                        zip(keys,
                            vartree.dbapi.aux_get(ebuild,
                                                  portage.auxdbkeys)))))
        else:
            return Properties()
Beispiel #2
0
    def test_python_thread_calls_to_clr(self):
        """Test calls by Python-spawned threads into managed code."""
        # This test is very likely to hang if something is wrong ;)
        import System

        done = []

        def run_thread():
            for i in range(10):
                time.sleep(0.1)
                dprint("thread %s %d" % (thread.get_ident(), i))
                mstr = System.String("thread %s %d" % (thread.get_ident(), i))
                dprint(mstr.ToString())
                done.append(None)
                dprint("thread %s %d done" % (thread.get_ident(), i))

        def start_threads(count):
            for _ in range(count):
                thread_ = threading.Thread(target=run_thread)
                thread_.start()

        start_threads(5)

        while len(done) < 50:
            dprint(len(done))
            time.sleep(0.1)
def format_table_line(items, hdg=False):
    '''take the 13 enties in "items" and return them formatted for out table'''
    dprint("*** format_table_line: items passed in (hdg=%s):" % hdg)
    dprint(items)
    # set up an array of heading vs regular format for each column
    line_fmt = [
        ('{:<10s}', '{:<10s}'),
        ('{:^7s}', '{:^7d}'),
        ('{:>9s}', '{:>9.2f}'),
        ('{:>9s}', '{:>9.2f}'),
        ('{:^6s}', '{:^6d}'),
        ('{:^7s}', '{:^7d}'),
        ('{:^10s}', '{:^10d}'),
        ('{:^5s}', '{:^5d}'),
        ('{:^5s}', '{:^5d}'),
        ('{:^5s}', '{:^5d}'),
        ('{:^8s}', '{:^+8d}'),
        ('{:^8s}', '{:^+8d}'),
        ('{:>6s}', '{:>6s}')]
    fmt_idx = 0 if hdg else 1
    for i in range(13):
        dprint("item[%d] (len %d):" % (i, len(str(items[i]))), items[i])
        dprint("format for item: '%s'" % line_fmt[i][fmt_idx])
    l = []
    for i in range(13):
        fmt_str = line_fmt[i][fmt_idx]
        l.append(fmt_str.format(items[i]))
    res = ''.join(l)
    dprint("Returning table line: /%s/" % res)
    return res
Beispiel #4
0
def solve(points, tour, currentDist):
    startTime = int(time.time())
    print("points: " + str(len(tour)) + " start tour" + str(tour))
    step = 0
    offset = lambda x: 1 if x == 1 else 0
    while True:
        # The best opt and distance.
        startStepTime = int(time.time())
        bestDist = currentDist
        bestThreeOpt = None
        tries = 0
        for i in range(1, len(tour) - 3):  
            for j in range(i + 1, len(tour) - 2):
                for k in range(j + 2, len(tour) - offset(i)):
                    #print("i: %d, j: %d, j+1: %d, k:%d" % (i, j, j +1, k))
                    tries += 1 
                    threeOpt = getBestThreeOpt(points, tour, currentDist, i, j, k)
                    if threeOpt.getEndDist() < bestDist:
                        bestDist = threeOpt.getEndDist()
                        bestThreeOpt = threeOpt
        step += 1
        utils.dprint("step: " + str(step) + ", tries: " + str(tries) + ", time: " + fpformat.fix(time.time() - startStepTime, 3))
        if bestDist == currentDist:
            # If no more improvement we are at a local minima and are done.
            print("no more improvement")
            break
        # Perform the opt.
        bestThreeOpt.swap();
        currentDist = bestDist
        if  int(time.time()) - startTime > maxTimeToRun:
            # Out of time, return the best we've got.
            print("out of time")
            break
    print("end tour" + str(tour))
    return 0, bestDist, tour
 def DateChanged(self, e):
     dprint("One of our dates has changed!", e)
     if self.DateRangeValid():
         self.results_button.Enable()
         self.SetNormalStatus("")
     else:
         self.results_button.Disable()
 def DateRangeValid(self):
     '''Is our date range valid?'''
     rd_start = self.start_rdate.GetValue()
     dprint("Date Range Valid: start=", rd_start)
     rd_stop = self.stop_rdate.GetValue()
     dprint("Date Range Valid: stop=", rd_stop)
     return rd_stop > rd_start
def add_round(rnd, rd_list):
    '''Add the specified round and list of round details to the DB'''
    dprint("Adding to DB:", rnd)
    for rd in rd_list:
        dprint(rd)
    db_cmd_exec('''INSERT INTO rounds(num,
                                      course_num,
                                      rdate)
                   VALUES(%d,%d,"%s")''' % \
                (rnd.num,
                 rnd.course_num,
                 rnd.rdate.strftime("%m/%d/%Y")))
    for rd in rd_list:
        if rnd.num != rd.round_num:
            raise Exception("Internal Error: Round Number mismatch!")
        db_cmd_exec('''INSERT INTO round_details(round_num, player_num,
                                                 fstrokes, bstrokes,
                                                 acnt, ecnt, aecnt,
                                                 calc_fscore_numerator,
                                                 calc_fscore_denominator,
                                                 calc_bscore_numerator,
                                                 calc_bscore_denominator,
                                                 calc_oscore_numerator,
                                                 calc_oscore_denominator)
               VALUES(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)''' % \
                    (rd.round_num, rd.player_num,
                     rd.fstrokes, rd.bstrokes,
                     rd.acnt, rd.ecnt, rd.aecnt,
                     rd.calc_fscore.numerator, rd.calc_fscore.denominator,
                     rd.calc_bscore.numerator, rd.calc_bscore.denominator,
                     rd.calc_oscore.numerator, rd.calc_oscore.denominator))
 def on_session_connected(self, session_path):
         dprint("session_connected")
         #session_path = os.path.basename(session_path)
         if session_path in self.Sessions:
                 session = self.Sessions[session_path]
                 if not session.Connected:
                         session.emit("connected")
        def destroy_server(self, pattern="opp"):
                dprint("Destroy %s server" % pattern)
                def on_stopped(server):
                        dprint("server stopped")
                        try:
                                server.Close()
                        except:
                                #this is a workaround for lp:735068
                                dprint("DBus error on ODS server.Close()")
                                #force close locally
                                server.DisconnectAll()

                        gobject.source_remove(timeout)

                def on_closed(server):
                        dprint("server closed")
                        self.emit("server-destroyed", self.Servers[pattern].object_path)
                        del self.Servers[pattern]

                try:
                        s = self.Servers[pattern]
                        s.GHandle("stopped", on_stopped)
                        s.GHandle("closed", on_closed)
                        try:
                                s.Stop()
                        except:
                                #ods probably died
                                gobject.idle_add(on_closed, s)

                        timeout = gobject.timeout_add(1000, on_stopped, s)

                except KeyError:
                        pass
def main():
    dprint("Opening DB ...")
    conn = sqlite3.connect(DB_PATH)
    c = conn.cursor()
    dprint("Trying to read table: courses ...")
    for row in c.execute('''SELECT * FROM courses'''):
        print row
 def OnCommit(self, e):
     dprint("OnCommit: %s Round DB requested" % \
            ('Update' if self.for_update else 'Commit'))
     dprint("DB State: edited=%s, calc_done=%s form_up_to_date=%s, " % \
            (self.is_edited, self.calc_done, self.data_from_form_up_to_date))
     # save the date of our current round, since it can
     # change when we get data from the frame
     this_round_rdate_saved = self.this_round.rdate
     if not self.GetDataFromFrameIfNeeded():
         dprint("XXX need to diplay error status here: data invalid!")
         return
     if not self.is_edited:
         raise Exception("Internal Error: Committing non-edited list?")
     if self.for_update:
         # XXX we should check for this round having the date of a round
         # already in the database (not counting this round)
         # NOT YET IMPLEMENTED
         rdb.modify_round(self.this_round, self.round_details)
     else:
         # check for duplicate round
         for rnd in rdb.RoundList.itervalues():
             dprint("Looking at an existing:", rnd)
             if rnd.rdate == this_round_rdate_saved:
                 self.SetErrorStatus("Duplicate Round Date: Change Date")
                 return False
         rdb.add_round(self.this_round, self.round_details)
         self.SetNormalStatus("")
     rdb.commit_db()
     dprint("Updating parent GUI ...")
     pub.sendMessage("ROUND UPDATE", round_no=self.this_round)
     self.is_edited = False
     self.is_committed = True
     self.SetCommitButtonState()
Beispiel #12
0
 def on_session_closed(self, session_path):
     dprint("__Session Closed__")
     #session_path = os.path.basename(session_path)
     if session_path in self.Sessions:
         self.Sessions[session_path].DisconnectAll()
         del self.Sessions[session_path]
         self.emit("session-destroyed", session_path)
def get_max_round_no():
    #global RoundList
    # try it an alternative way
    rnd_nos = [rnd.num for rnd in RoundList.itervalues()]
    max_rnd_no = max(rnd_nos)
    dprint("Max Round No: %d" % max_rnd_no)
    return max_rnd_no
Beispiel #14
0
    def destroy_server(self, pattern="opp"):
        dprint("Destroy %s server" % pattern)

        def on_stopped(server):
            dprint("server stopped")
            try:
                server.Close()
            except:
                #this is a workaround for lp:735068
                dprint("DBus error on ODS server.Close()")
                #force close locally
                server.DisconnectAll()

            gobject.source_remove(timeout)

        def on_closed(server):
            dprint("server closed")
            self.emit("server-destroyed", self.Servers[pattern].object_path)
            del self.Servers[pattern]

        try:
            s = self.Servers[pattern]
            s.GHandle("stopped", on_stopped)
            s.GHandle("closed", on_closed)
            try:
                s.Stop()
            except:
                #ods probably died
                gobject.idle_add(on_closed, s)

            timeout = gobject.timeout_add(1000, on_stopped, s)

        except KeyError:
            pass
Beispiel #15
0
 def on_session_connected(self, session_path):
     dprint("session_connected")
     #session_path = os.path.basename(session_path)
     if session_path in self.Sessions:
         session = self.Sessions[session_path]
         if not session.Connected:
             session.emit("connected")
Beispiel #16
0
def sort(list):
    """sort in alphabetic instead of ASCIIbetic order"""
    dprint("PKGCORE_LIB: sort()")
    spam = [(x[0].upper(), x) for x in list]
    spam.sort()
    dprint("PKGCORE_LIB: sort(); finished")
    return [x[1] for x in spam]
Beispiel #17
0
def distance(frames_src, frames_target):
    '''
    Args:
        frames_src(FeaturePatch): a single FeaturePatch from the source video
        frames_target(FeaturePatch): a single FeaturePatch from a target video from the database

    Returns:
        int: the distance between the given FeaturePatch in optical flow space
    '''

    if type(frames_target) == list:
        utils.dprint("FOUND A LIST IN DISTANCE")
        return sys.float_info.max

    dist = 0
    for i in range(len(frames_target.features)):

        if namespace.FEATURES_ARE_VECTORS and not namespace.WEIGHTED_AVG_DIR:
            # If we stored features as Optical Flow Vector

            if (type(frames_src.features[i]) != list or type(frames_target.features[i])):
                # Something wonky happened with features.
                utils.dprint("Odd feature")
                continue

            # Compute distance
            mag_src = math.sqrt((frames_src.features[i][0] + frames_src.features[i][1])**2)
            mag_target = math.sqrt((frames_target.features[i][0] + frames_target.features[i][1])**2)
            dist += abs((mag_src - mag_target))
        else:
            # If we stored features as magnitudes of optical flow
            dist += abs((frames_src.features[i] - frames_target.features[i]))
    return dist
 def land(self):
     utils.dprint("", 'Landing')
     self.at(at_ref, False)
     # TODO: implement check for landed
     self.move(0.0, 0.0, 0.0, 0.0, False)
     self.sleep_time = 1.0
     self.__set_landed(True)
Beispiel #19
0
def reload_portage():
    dprint('PKGCORE_LIB: reloading portage')
    reload(pkgcore.config)
    reload(pkgcore.const)
    reload(pkgcore.util.file.read_bash)
    reload(portage)
    reload(portage_const)
 def HasPage(self, page_num):
     """
     This function is called to determine if the specified page exists.
     """
     res = len(self.GetPageText(page_num))
     dprint("HasPage(%d): returning '%d > 0'" % (page_num, res))
     return res > 0
    def PreviewText(self, lines, doc_name):
        """
        This function displays the preview window for the text with the given header.
        """
        try:
            self.doc_name = doc_name
            self.doc_lines = lines

            #Destructor fix by Peter Milliken --
            print1 = MyPrintout(self.frame, lines=self.doc_lines)
            print2 = MyPrintout(self.frame, lines=self.doc_lines)
            preview = wx.PrintPreview(print1, print2, self.printer_config)
            if not preview.Ok():
                wx.MessageBox("Unable to display preview of document.")
                return
            preview_window = wx.PreviewFrame(preview, self.frame, \
                                             "Print Preview - %s" % doc_name)
            preview_window.Initialize()
            preview_window.SetPosition(self.frame.GetPosition())
            preview_window.SetSize(self.frame.GetSize())
            preview_window.MakeModal(True)
            preview_window.GetControlBar().SetZoomControl(100)
            preview_window.Show(True)
        except Exception, e:
            dprint("oh oh -- something failed:", e)
            wx.MessageBox(GetErrorText())
Beispiel #22
0
    def step(self,seconds=0.1):
        """ Step function 1) senses, 2) executes all layered resources (which tell "body"
        which actions to engage, then 3) executes simulator for X seconds (defined by 
        'seconds' variable."""

        self.age += 1
        # tell the terminal how old you are
        print "Step %i" % (self.age)
        
        state_1 = [x for x in self.all_resources if x.is_on]
        self.sense() # sense the world which returns perceptions, 
        #print "ALL resources", self.all_resources
        for r in self.all_resources:
            if r.is_on: print "+", r.name

        self.execute_all_resources()
        #self.execute_reactive_resources()
        #self.execute_deliberative_resources()
        #self.execute_reflective_resources()
        state_2 = [x for x in self.all_resources if x.is_on]
        self.turned_on = set(state_2)-set(state_1)
        self.turned_off = set(state_1)-set(state_2)
        for resource in self.turned_on:
            dprint(x.name,"ON: ")
        for resource in self.turned_off:
            dprint(x.name,"OFF: ")
            
        self.env.do('step_simulation',{'seconds':seconds, 'agent':self.name}) # simulator is paused by default, run for X seconds
        time.sleep(seconds+(self.delay*2)) # make sure agent waits as long as simulator
        return True
Beispiel #23
0
    def step(self, seconds=0.1):
        """ Step function 1) senses, 2) executes all layered resources (which tell "body"
        which actions to engage, then 3) executes simulator for X seconds (defined by 
        'seconds' variable."""

        self.age += 1
        # tell the terminal how old you are
        print "Step %i" % (self.age)

        state_1 = [x for x in self.all_resources if x.is_on]
        self.sense()  # sense the world which returns perceptions,
        #print "ALL resources", self.all_resources
        for r in self.all_resources:
            if r.is_on: print "+", r.name

        self.execute_all_resources()
        #self.execute_reactive_resources()
        #self.execute_deliberative_resources()
        #self.execute_reflective_resources()
        state_2 = [x for x in self.all_resources if x.is_on]
        self.turned_on = set(state_2) - set(state_1)
        self.turned_off = set(state_1) - set(state_2)
        for resource in self.turned_on:
            dprint(x.name, "ON: ")
        for resource in self.turned_off:
            dprint(x.name, "OFF: ")

        self.env.do('step_simulation', {
            'seconds': seconds,
            'agent': self.name
        })  # simulator is paused by default, run for X seconds
        time.sleep(
            seconds +
            (self.delay * 2))  # make sure agent waits as long as simulator
        return True
 def on_session_closed(self, session_path):
         dprint("__Session Closed__")
         #session_path = os.path.basename(session_path)
         if session_path in self.Sessions:
                 self.Sessions[session_path].DisconnectAll()
                 del self.Sessions[session_path]
                 self.emit("session-destroyed", session_path)
Beispiel #25
0
 def load_oc_config(self, coin, oc_type):
     try:
         copyfile('./' + str(coin) + '/' + str(oc_type) + '/local.conf',
                  './')
         os.system('ethos-overclock')
     except IOError:
         self.send_mail(self.notification_add, 'load_oc_config fail')
         dprint('load_oc_config fail')
Beispiel #26
0
def db_setup():
    commands = nlp_schema.schema
    with postgres() as db:
        dprint("Creating Main DB Tables - Ignore permanent connection message")
        for command in commands:
            #dprint(command)
            db.commit(command)
            time.sleep(1)
 def MyStart(self, start_rdate, stop_rdate):
     dprint("ScoreResultsFrame:MyStart(%s, %s): entering" % \
            (start_rdate, stop_rdate))
     self.start_rdate = wxdate.wxdt_to_dt(start_rdate)
     self.stop_rdate = wxdate.wxdt_to_dt(stop_rdate)
     dprint("Report on reults from", start_rdate, "to", stop_rdate)
     self.GenerateResultsList()
     self.InitUI()
Beispiel #28
0
    def open(self, args, extra_args):
        url = args[0]

        if 'http' not in url:
            url = 'http://' + url

        utils.dprint(url)
        webbrowser.open(url, autoraise=True)
Beispiel #29
0
    def test_simple_callback_to_python(self):
        """Test a call to managed code that then calls back into Python."""
        from Python.Test import ThreadTest

        dprint("thread %s SimpleCallBack" % thread.get_ident())
        result = ThreadTest.CallEchoString("spam")
        self.assertTrue(result == "spam")
        dprint("thread %s SimpleCallBack ret" % thread.get_ident())
Beispiel #30
0
def set_make_conf(prefs,
                  property,
                  add='',
                  remove='',
                  replace='',
                  callback=None):
    """
    Sets a variable in make.conf.
    If remove: removes elements of <remove> from variable string.
    If add: adds elements of <add> to variable string.
    If replace: replaces entire variable string with <replace>.

    if remove contains the variable name, the whole variable is removed.

    e.g. set_make_conf('USE', add=['gtk', 'gtk2'], remove=['-gtk', '-gtk2'])
    e.g. set_make_conf('ACCEPT_KEYWORDS', remove='ACCEPT_KEYWORDS')
    e.g. set_make_conf('PORTAGE_NICENESS', replace='15')
    """
    dprint("PKGCORE_LIB: set_make_conf()")
    command = ''
    file = 'make.conf'
    if isinstance(add, list):
        add = ' '.join(add)
    if isinstance(remove, list):
        remove = ' '.join(remove)
    if isinstance(replace, list):
        replace = ' '.join(replace)
    config_path = portage_const.USER_CONFIG_PATH
    if not os.access(portage_const.MAKE_CONF_FILE, os.W_OK):
        command = (''.join([
            prefs.globals.su, ' "python ', prefs.DATA_PATH,
            'set_config.py -d -f ', file
        ]))
        command = command + '-p ' + property + ' '
        if add != '':
            command = command + "-a '" + add + "' '"
        if remove != '':
            command = command + "-r '" + remove + "'"
        command = command + '"'
        dprint(" * PKGCORE_LIB: set_make_conf(); command = " + command)
        if not callback: callback = reload_portage
        app = SimpleTerminal(command,
                             False,
                             dprint_output='SET_MAKE_CONF CHILD APP: ',
                             callback=Dispatcher(callback))
        app._run()
    else:
        add = add.split()
        remove = remove.split()
        set_config.set_make_conf(property, add, remove, replace)
        if callback: callback()
        else: reload_portage()
    # This is slow, but otherwise portage doesn't notice the change.
    #reload_portage()
    # Note: could perhaps just update portage.settings.
    # portage.settings.pmaskdict, punmaskdict, pkeywordsdict, pusedict
    # or portage.portdb.mysettings ?
    return True
Beispiel #31
0
 def get_stats(self):
     os.system('date > ' + str(self.stats_file))
     time.sleep(1)
     try:
         dprint("Get stats file")
         os.system('/opt/ethos/bin/stats >>' + str(self.stats_file))
     except:
         dprint('can not add stats to file')
         time.sleep(5)
 def AddMoneyRoundResults(self, mrd):
     '''
     The second heart of summarizing results: the money
     '''
     dprint("*** Adding in money results for pnum=%d:" % self.pnum, mrd)
     if self.pnum != mrd.player_num:
         raise Exception("Internal Error: Player Number Mismatch")
     self.money_won += mrd.GetMoney()
     dprint("Added $%s, total now $%s" % (mrd.GetMoney(), self.money_won))
 def commitPosition(self, p: Position) -> bool:
     try:
         self.cursor.execute(f"INSERT OR REPLACE INTO positions {p.package()}")
         self.connection.commit()
         return True
     except Exception as e:
         utils.dprint(e)
     
     return False
Beispiel #34
0
 def query(self, query, params=''): # used only for retrieving data
     try:
         self._db_cur.execute(query,params)
     except Exception as error:
         dprint('Error execting query "{}", error: {}'.format(query, error))
         return None
     else:
         result = self._db_cur.fetchall()
         return result
Beispiel #35
0
 def commit(self, query, params=''): #used only for comitting data to db
     try:
         result = self._db_cur.execute(query,params)
         self._db_connection.commit()
     except Exception as error:
         dprint('Error execting query "{}", error: {}'.format(query, error))
         return None
     else:
         return result
def wxdt_to_dt(wxdt_dt):
    '''
    return a wx.datetime for the supplied datetime
    '''
    dt_dt = dt.datetime(wxdt_dt.GetYear(),
                        wxdt_dt.GetMonth()+1,
                        wxdt_dt.GetDay())
    dprint("Converted wx:", wxdt_dt, "to dt:", dt_dt)
    return dt_dt
Beispiel #37
0
 def get_versions(self, include_masked = True):
     """Returns all available ebuilds for the package"""
     if self.full_name == "None":
         return ''
     vers = list(TREE.versions[self.full_name])
     for x in range(0,len(vers)):
         vers[x] = self.full_name + '-' + vers[x]
     dprint("PKGCORE_LIB: Package.get_versions() vers = " + str(vers))
     return vers
def initialize_db(skip_preload_flag):
    dprint("Creating DB: %s/%s ..." % (_DB_DIR, _DB_FILE))
    conn = sqlite3.connect("%s/%s" % (_DB_DIR, _DB_FILE))
    c = conn.cursor()
    initialize_players(c, skip_preload_flag)
    initialize_courses(c, skip_preload_flag)
    initialize_rounds(c, skip_preload_flag)
    dprint("Commiting new database ...")
    conn.commit()
Beispiel #39
0
def get_properties(ebuild):
    """Get all ebuild variables in one chunk."""
    ebuild = str(ebuild) #just in case
    if portage.portdb.cpv_exists(ebuild): # if in portage tree
        try:
            return Properties(dict(zip(keys, portage.portdb.aux_get(ebuild, portage.auxdbkeys))))
        except IOError, e: # Sync being performed may delete files
            dprint(" * PKGCORE_LIB: get_properties(): IOError: " + e)
            return Properties()
Beispiel #40
0
def insert_current_coin_values(db):
    dprint("Adding current coin values to db")
    coin_symbol_list = get_coin_symbol_list(db)
    ticker_json = requests.get("https://api.coinmarketcap.com/v1/ticker/").text
    ticker = json.loads(ticker_json)
    for tick in ticker:
        if tick['symbol'] in coin_symbol_list:
            db.commit(
                'INSERT INTO coin_history (coin_type_id,price) VALUES (%s,%s)',
                (tick['symbol'], tick['price_usd']))
Beispiel #41
0
def get_full_name(ebuild):
    """Extract category/package from some ebuild identifier"""
    if ebuild.endswith("*"): ebuild = ebuild[:-1]
    cplist = portage.catpkgsplit(ebuild) or portage.catsplit(ebuild)
    if not cplist or len(cplist) < 2:
        dprint("PKGCORE_LIB get_full_name(): issues with '%s'" % ebuild)
        return ''
    cp = cplist[0] + "/" + cplist[1]
    while cp[0] in ["<",">","=","!","*"]: cp = cp[1:]
    return str(cp) # hmm ... unicode keeps appearing :(
 def OnListEdited(self, evt):
     dprint("OnListEdited: Col=%d: %s" % (evt.col, evt.message))
     # was editing in the front9/back9 columns?
     if evt.col in [1, 2]:
         dprint("XXX Need to update mzkitty amount(s)!!!")
     # but any change means we need to save the changes
     self.is_edited = True
     self.SetCommitButtonState()
     # flag that we need to update data from our form
     self.data_from_form_up_to_date = False
 def take_off(self):
     utils.dprint("", 'Taking off!')
     self.at(at_ftrim)
     self.at(at_ftrim)
     self.at(at_ftrim)
     self.sleep_time = 0.02
     self.at(at_config, "control:altitude_max", "40000")
     self.at(at_ref, True)
     # TODO: implement check for takeoff
     self.__set_landed(False)
Beispiel #44
0
 def get_min_hash(self):
     self.coin = self.config_file("NowMiningCoin", "get")
     self.num_of_gpu = self.config_file("NumOfGpus", "get")
     if self.coin == "ZEC":
         self.rig_min_hash = 420 * int(self.num_of_gpu)
     elif self.coin == "ETH" or self.coin == "ETC":
         self.rig_min_hash = 26 * int(self.num_of_gpu)
     else:
         dprint("Can not init rig min hash.")
     return self.rig_min_hash
 def SetScoreButtonState(self):
     '''Set appropriate state for the "Score" Button'''
     dprint("%d players selected" % \
            self.player_list.item_check_count)
     if self.player_list.item_check_count > 0:
         self.start_button.Enable()
         self.SetNormalStatus("")
     else:
         self.start_button.Disable()
         self.SetNormalStatus("Please choose money players")
 def OnNewRoundExists(self, round_no):
     '''A "NEW ROUND" or "NEW MONEY ROUND" message has been received'''
     dprint("ScoreResultsFrame: A 'NEW ROUND' Message we received!")
     # re-read the database rounds and round_details into our
     # internal structures, since they have changed
     rdb.init_rounds()
     # re-generate our report results and data, then display them
     self.GenerateResultsList()
     self.results_list.SetupListItems(self.item_data)
     self.Show(True)
 def OnCourseChosen(self, evt):
     '''A course has been choosen'''
     dprint("A Course has been choosen:", evt)
     course_num = self.course_choice.GetSelection()
     if course_num > 0 and \
        course_num != self.this_round.course_num:
         dprint("A Valid and new course choosen: %d" % course_num)
         self.is_edited = True
         self.data_from_form_up_to_date = False
     self.SetCommitButtonState()
Beispiel #48
0
        def on_stopped(server):
            dprint("server stopped")
            try:
                server.Close()
            except:
                #this is a workaround for lp:735068
                dprint("DBus error on ODS server.Close()")
                #force close locally
                server.DisconnectAll()

            gobject.source_remove(timeout)
                def on_stopped(server):
                        dprint("server stopped")
                        try:
                                server.Close()
                        except:
                                #this is a workaround for lp:735068
                                dprint("DBus error on ODS server.Close()")
                                #force close locally
                                server.DisconnectAll()

                        gobject.source_remove(timeout)
Beispiel #50
0
 def reset_rig(self):
     if self.config_file("RigResetWhenGpuFail", "get") == "true":
         dprint("Reset rig, RIG UP TIME was " + str(self.rig_up_time))
         time.sleep(1)
         # Ethos reset.
         os.system('/opt/ethos/bin/r')
         # Ubuntu reset just in case.
         time.sleep(5)
         os.system('sudo reboot')
     else:
         dprint("Can not reset rig, check RigResetWhenGpuFail fleg")
 def OnCheckItem(self, data, flag=None):
     if flag is None:
         dprint("Skipping item checked: no item!")
         return
     dprint("Setting items_checked[%d] = %s" % (data, flag))
     self.items_checked[data] = flag
     if flag:
         self.item_check_count += 1
     else:
         self.item_check_count -= 1
     pub.sendMessage("ITEM CHECK UPDATE", count=self.item_check_count)
 def CheckEditEnd(self, evt):
     dprint("*** Finished editing col=%d, text=%s" % (evt.m_col, evt.Text))
     self.after_edit = evt.Text
     if self.before_edit != self.after_edit:
         dprint("Sending a a custom event: list edited!")
         new_evt = ListEditedEvt(self.GetId(),
                                 message='list edited',
                                 col=evt.m_col)
         wx.PostEvent(self.GetParent(), new_evt)
     # allow all edits -- XXX probably not needed
     evt.Allow()
    def check(self):
        self.cursor.execute("SELECT * FROM users")
        rows = self.cursor.fetchall()
        for row in rows:
            utils.dprint(row)
        
        self.cursor.execute("SELECT * FROM positions")
        rows = self.cursor.fetchall()

        for row in rows:
            utils.dprint(rows)
Beispiel #54
0
 def config_file(self, key, value):
     json_file = open(self.cfg_file, "r+")
     data = json.load(json_file)
     try:
         if value == 'get':  # Get value.
             return str(data[str(key)])
         else:  # Set value.
             data[str(key)] = str(value)
             json_file.seek(0)  # rewind
             json.dump(data, json_file, sort_keys=True, indent=4)
             json_file.truncate()
     except:
         dprint("Can not set value on cfg file.")
Beispiel #55
0
def get_sets_list( filename ):
    """Get the package list file and turn it into a tuple
       attributes: pkgs[key = full_name] = [atoms, version]"""
    pkgs = {}
    try:
        set_list = pkgcore.util.file.read_bash(filename)
    except:
        dprint("PKGCORE_LIB: get_sets_list(); Failure to locate/read file: " + filename)
        return None
    # split the atoms from the pkg name and any trailing attributes if any
    for item in set_list:
        parts = self.split_atom_pkg(item)
        pkgs[parts[0]] = parts[1:]
    return pkgs
Beispiel #56
0
def get_digest(ebuild):
    """Returns digest of an ebuild"""
    mydigest = portage.db['/']['porttree'].dbapi.finddigest(ebuild)
    digest_file = []
    try:
        myfile = open(mydigest, "r")
        for line in myfile.readlines():
            digest_file.append(line.split(" "))
        myfile.close()
    except SystemExit as e:
        raise  # Needed else can't exit
    except Exception as e:
        dprint("PKGCORE_LIB: get_digest(): Exception: " + e)
    return digest_file
Beispiel #57
0
 def __init__(self):
     self.rig_up_time = 0
     self.rig_hash = 0
     self.rig_name = ""
     self.num_of_gpu = ""
     self.coin = ""
     self.rig_min_hash = self.get_min_hash()
     # Get notification addresses.
     self.notification_addr = self.config_file("NotificationAddr",
                                               "get").split(',')
     # Enable notification.
     self.config_file("NotificationEnable", "true")
     # Init min rig hash.
     dprint("Coin=" + self.coin + " NumOfGpu=" + self.num_of_gpu + " " +
            "RigMinHash=" + str(self.rig_min_hash))
Beispiel #58
0
def find_posts_to_be_processed(db):
    unprocessed_posts = db.query('SELECT * FROM posts WHERE post_processed=False')
    possibles = globals().copy()
    for unprocessed in unprocessed_posts:
        id = unprocessed[0]
        url = unprocessed[1]
        date = unprocessed[2]
        source_id = unprocessed[3]
        coin_focus = unprocessed[4]
        source = db.query('SELECT source_name FROM sources WHERE source_id = %s',(source_id,))[0][0]

        scraper = possibles.get(source)
        if not scraper:
            dprint("No article scraper implemented for - " + source)
        else:
            scraper(db,id,url)
Beispiel #59
0
 def get_properties(self, specific_ebuild = None):
     """ Returns properties of specific ebuild.
         If no ebuild specified, get latest ebuild. """
     #dprint("PKGCORE_LIB: Package:get_properties()")
     if self.full_name == "None":
         return ''
     if specific_ebuild == None:
         ebuild = self.get_default_ebuild()
         if not ebuild:
             dprint("PKGCORE_LIB; get_properties(): No ebuild found for " + self.full_name + "!")
             #raise Exception(_('No ebuild found.'))
     else:
         #dprint("PKGCORE_LIB get_properties(): Using specific ebuild")
         ebuild = specific_ebuild
     if not ebuild in self.properties:
         #dprint("PKGCORE_LIB: geting properties for '%s'" % str(ebuild))
         self.properties[ebuild] = get_properties(ebuild)
     return self.properties[ebuild]
Beispiel #60
0
def split_atom_pkg( pkg ):
    """Extract [category/package, atoms, version] from some ebuild identifier"""
    atoms = []
    version = ''
    if pkg.endswith("*"): pkg = pkg[:-1]
    cplist = portage.catpkgsplit(pkg) or portage.catsplit(pkg)
    if not cplist or len(cplist) < 2:
        dprint("PKGCORE_LIB split_pkg(): issues with '%s'" % pkg)
        return ['', '', '']
    cp = cplist[0] + "/" + cplist[1]
    while cp[0] in ["<",">","=","!","*"]:
        atoms.append(cp[0])
        cp = cp[1:]
    if cplist:
        version = cplist[2]
        if cplist[3] != 'r0':
            version += '-' + cplist[3]
    return [str(cp), atoms.join(), version] # hmm ... unicode keeps appearing :(