rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
gobject.idle_add (self.plugin._populate_programme_list_cb, self.tree_model, self.category_path, None)
gobject.idle_add (self.plugin._populate_programme_list_cb, self.tree_model, self.category_path, None, False)
def run (self): self.plugin.programme_download_lock.acquire ()
self.totem.action_remote(Totem.RemoteCommand.REPLACE, t['stream'])
self.totem.action_remote(Totem.RemoteCommand.REPLACE, t['stream'].encode ('UTF-8'))
def add_track_to_playlist(self, mode, t): """ Add a track to the playlist, mode can be: replace, enqueue or enqueue_and_play. """ if mode == 'replace': self.totem.action_remote(Totem.RemoteCommand.REPLACE, t['stream']) elif mode == 'enqueue': self.totem.action_remote(Totem.RemoteCommand.ENQUEUE, t['stream'])
self.totem.action_remote(Totem.RemoteCommand.ENQUEUE, t['stream'])
self.totem.action_remote(Totem.RemoteCommand.ENQUEUE, t['stream'].encode ('UTF-8'))
def add_track_to_playlist(self, mode, t): """ Add a track to the playlist, mode can be: replace, enqueue or enqueue_and_play. """ if mode == 'replace': self.totem.action_remote(Totem.RemoteCommand.REPLACE, t['stream']) elif mode == 'enqueue': self.totem.action_remote(Totem.RemoteCommand.ENQUEUE, t['stream'])
it = model.get_iter((row[0],)) else: it = model.get_iter(row) elt = model.get(it, 0)[0]
parent_iter = model.iter_parent (it) if parent_iter != None: it = parent_iter elt = model.get_value(it, 0)
def _get_selection(self, root=False): """ Shortcut method to retrieve the treeview items selected. """ ret = [] sel = self.current_treeview.get_selection() (rows, model) = sel.get_selected_rows() for row in rows: if root: it = model.get_iter((row[0],)) else: it = model.get_iter(row) elt = model.get(it, 0)[0] if elt not...
print builder
def do_create_configure_widget(self): """ Plugin config widget. This code must be independent from the rest of the plugin. FIXME: bgo#624073 """ builder = Totem.plugin_load_interface ('jamendo', 'jamendo.ui', True, None, self) print builder config_widget = builder.get_object ('config_widget') config_widget.connect ('de...
print config_widget
def do_create_configure_widget(self): """ Plugin config widget. This code must be independent from the rest of the plugin. FIXME: bgo#624073 """ builder = Totem.plugin_load_interface ('jamendo', 'jamendo.ui', True, None, self) print builder config_widget = builder.get_object ('config_widget') config_widget.connect ('de...
w.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE)
selection = w.get_selection () selection.set_mode(Gtk.SelectionMode.MULTIPLE) selection.connect ('changed', self.on_treeview_selection_changed)
def setup_treeviews(self): """ Setup the 3 treeview: result, popular and latest """ self.current_treeview = self.treeviews[0] for w in self.treeviews: w.get_selection().set_mode(Gtk.SelectionMode.MULTIPLE)
self.album_button.set_sensitive(True)
def on_treeview_row_clicked(self, tv, evt): """ Called when the user clicked on a treeview element. """ try: if evt.button.button == 3: (path, _, _, _) = tv.get_path_at_pos(int(evt.x), int(evt.y)) sel = tv.get_selection() (rows, _) = sel.get_selected_rows() if path not in rows: sel.unselect_all() sel.select_path(path)...
self.chunk_base_name = None
self.chunk_basename = None
def __init__(self, chunksize=CHUNK_SIZE, \ verbose_output_enabled=VERBOSE_OUTPUT_ENABLED, \ cp_cmd_template=SCP_CMD_TEMPLATE, \ rm_cmd_template=RM_CMD_TEMPLATE, \ cat_cmd_template=CAT_CMD_TEMPLATE): self.logger = None self.verbose = verbose_output_enabled self.username = '' self.filename = None self.filedest = None sel...
while self.procsema.acquire(blocking=False) == False: time.sleep(0.5)
def run(self): ''' start queued processes ''' while not self.killflag.isSet(): try: cmd = self.cmdq.get(timeout=0.5) while self.procsema.acquire(blocking=False) == False: time.sleep(0.5) # we have a cmd and a semaphore slot, run the cmd proc = Popen(shlex.split(cmd), stdout=PIPE, stderr=STDOUT) self.procs.append((proc,...
for proc in self.procs[0]:
for proc, vals in self.procs:
def killprocs(self): ''' stop creation of new processes and kill those that are active ''' # empty the queue and kill current procs try: while True: self.cmdq.get_nowait() except Queue.Empty: pass for proc in self.procs[0]: try: os.kill(proc.pid, 9) except Exception: pass
try: while True: self.procs.pop() self.procsema.release() except Exception: pass
def killprocs(self): ''' stop creation of new processes and kill those that are active ''' # empty the queue and kill current procs try: while True: self.cmdq.get_nowait() except Queue.Empty: pass for proc in self.procs[0]: try: os.kill(proc.pid, 9) except Exception: pass
while self.procsema.acquire(blocking=False) == False: time.sleep(0.5)
def run(self): ''' run queued commands forever ''' while not self.killflag.isSet(): try: cmd, seed, target, chunk = self.cmdq.get(timeout=0.5) while self.procsema.acquire(blocking=False) == False: # sema is full, wait for free slots time.sleep(0.5) # we have a cmd and a semaphore slot, run the cmd proc = Popen(shlex.sp...
if not self.killflag.set():
if not self.killflag.isSet():
def run(self): ''' run queued commands forever ''' while not self.killflag.isSet(): try: cmd, seed, target, chunk = self.cmdq.get(timeout=0.5) while self.procsema.acquire(blocking=False) == False: # sema is full, wait for free slots time.sleep(0.5) # we have a cmd and a semaphore slot, run the cmd proc = Popen(shlex.sp...
while not self.killflag.isSet() and not (self.finishflag.isSet() and len(self.procs) == 0):
while not self.killflag.isSet(): if self.finishflag.isSet() and len(self.procs) == 0: break
def run(self): ''' Poll processes and if they are finished, handle the output ''' while not self.killflag.isSet() and not (self.finishflag.isSet() and len(self.procs) == 0): active_procs = [] #proc, seed, target, chunk for proc, vals in self.procs: ret = proc.poll() if ret is not None: # process is done self.handle_out...
time.sleep(0.5)
time.sleep(0.1)
def run(self): ''' Poll processes and if they are finished, handle the output ''' while not self.killflag.isSet() and not (self.finishflag.isSet() and len(self.procs) == 0): active_procs = [] #proc, seed, target, chunk for proc, vals in self.procs: ret = proc.poll() if ret is not None: # process is done self.handle_out...
if self.options.verbose:
if False:
def handle_output(self, ret, proc, vals): seed, target, chunk = vals stdout, stderr = proc.communicate() # interpret output from scp command, success or failure? try: if ret == 0: if target.failcount > 0: target.resetFailCount() if seed.failcount > 0: seed.resetFailCount() # transfer succeeded if self.options.verbose: ...
self.options.chunk_base_name, self.options.filedest)
self.options.chunk_basename, self.options.filedest)
def handle_output(self, ret, proc, vals): seed, target, chunk = vals stdout, stderr = proc.communicate() # interpret output from scp command, success or failure? try: if ret == 0: if target.failcount > 0: target.resetFailCount() if seed.failcount > 0: seed.resetFailCount() # transfer succeeded if self.options.verbose: ...
if self.alive:
if self.alive == True:
def setDead(self): ''' If isAlive() failed and host is down, call this to stop attempts at using this host ''' self.lock.acquire() if self.alive: self.alive = False self.DB.incDeadHosts() self.transferslots = 0 # prevents selection for transfers self.lock.release()
if self.hostlist[self.tindex].transferslots > 0:
if self.hostlist[self.tindex].transferslots > 0 and \ self.hostlist[self.tindex].alive is True:
def getTransfer(self): ''' Returns (seed, target, chunk) which will be passed to a transfer thread ''' for q in xrange(self.hostcount): # choose a target self.tindex = (self.tindex+1) % self.hostcount # check if chosen target is alive and has an open slot if self.hostlist[self.tindex].transferslots > 0: # transfer firs...
options.chunksize, options.filename, options.chunk_base_name))
options.chunksize, options.filename, options.chunk_basename))
def run(self): options = self.options; DB = self.DB self.s = Spawn('split --verbose -b %s %s %s' % ( \ options.chunksize, options.filename, options.chunk_base_name))
curname = options.chunk_base_name + 'a'
curname = options.chunk_basename + 'a'
def run(self): options = self.options; DB = self.DB self.s = Spawn('split --verbose -b %s %s %s' % ( \ options.chunksize, options.filename, options.chunk_base_name))
host_regex = '[a-zA-Z]{1}[a-zA-Z0-9\-]' range_regex = '[0-9]+\-[0-9]+(,[0-9]+\-[0-9]+)+' regex = host_regex + '\[' + range_regex + '\]'
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
first = rng.split('-')[0] last = rng.split('-')[1]
first, last = rng.split('-')
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
options.chunk_base_name = \ os.path.join(chunkdir, os.path.split(options.filename)[-1])+ '.chunk_'
options.chunk_basename = \ os.path.join(chunkdir, os.path.split(options.filedest)[-1])+ '.chunk_'
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
procsema = threading.Semaphore(max_procs)
procsema = Semaphore(max_procs) t = threading.Thread(target=cnt_test, args=(procsema,)) t.setDaemon(True) t.start()
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
for thread in threads:
for thread in (cmdp, commandq):
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
(options.username+host.hostname, options.chunk_base_name)
(options.username+host.hostname, options.chunk_basename)
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
split_thread.start()
for thread in (split_thread, cpp, cpq): thread.start()
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
split_thread.kill()
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
cpq.kill() cpp.kill() cmdp.kill()
cpq.killprocs() for thread in (split_thread, cpq, cpp): thread.kill()
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
pass if options.cleanup is True: print 'removing chunks ...' commandq.wait_for_procs() for host in DB.hostlist: rmCmd = rm_cmd_template % \ (options.username+host.hostname, options.chunk_base_name) commandq.put(rmCmd) commandq.finish()
print '[!] Aborted chunk clean up' for thread in (split_thread, cpq, cpp): thread.kill() commandq.finish()
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
os._exit(1)
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
print 'ERROR: main() ', sys.exc_info()[1]
import traceback print 'ERROR: main() ' exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exception(exc_type, exc_value, exc_traceback, limit=4, file=sys.stdout)
def main(): # init defaults options = Options() max_procs = MAX_PROCS max_transfers_per_host = MAX_TRANSFERS_PER_HOST rm_cmd_template = RM_CMD_TEMPLATE cat_cmd_template = CAT_CMD_TEMPLATE logfile = LOG_FILE cleanonly = False # just remove chunks and exit chunkdir = CHUNK_DIR # get the command line options try: optlist...
def unknown_starttag(self, name, *args): if self.close_on_open: self._popToTag(self.close_on_open) self.close_on_open = None BeautifulStoneSoup.unknown_starttag(self, name, *args)
def test_missing_kw_in_passing_test(self): suite = self._fix_xml_and_parse('passing_kw_missing_end_tag') assert_equals(len(suite.tests), 2) self._assert_statistics(suite, 1, 1) assert_equals(len(suite.tests[0].keywords[0].keywords), 2)
def unknown_starttag(self, name, *args): if self.close_on_open: self._popToTag(self.close_on_open) self.close_on_open = None BeautifulStoneSoup.unknown_starttag(self, name, *args)
def unknown_endtag(self, name): BeautifulStoneSoup.unknown_endtag(self, name) if name == 'status': self.close_on_open = self.tagStack[-1].name else: self.close_on_open = None
def test_missing_kw_in_failing_test(self): suite = self._fix_xml_and_parse('failing_kw_missing_end_tag') assert_equals(len(suite.tests), 2) self._assert_statistics(suite, 1, 1) assert_equals(len(suite.tests[1].keywords[0].keywords), 1) def test_xml_cut_inside_keyword(self): suite = self._fix_xml_and_parse('cut_inside_...
def unknown_endtag(self, name): BeautifulStoneSoup.unknown_endtag(self, name) if name == 'status': self.close_on_open = self.tagStack[-1].name else: self.close_on_open = None
args = sys.argv[1:] if len(args) != 2: print __doc__ sys.exit(1) outfile = open(args[1], 'w') outfile.write(str(Fixml(open(args[0])))) outfile.close()
unittest.main()
def unknown_endtag(self, name): BeautifulStoneSoup.unknown_endtag(self, name) if name == 'status': self.close_on_open = self.tagStack[-1].name else: self.close_on_open = None
transaction.abort()
def tearDown(self): util.tearDown(self) transaction.abort() # just in case
if password == u['password']:
if password == str(u['password']):
def check_credentials(login, password, db_name, permission=None): """Verifies credentials for login and password. """ if login: u = users.get(login, None) if u != None: u['name'] = login if db_name == u['database']: if password == u['password']: if (permission == None) or (u['permission'] in permission): return u els...
item['balance_difference'] = str(difference)
item['balance_difference'] = str(Decimal(str(difference)))
def GET(self, db_name, _user=None): db_cnx = get_db_cnx(db_name) cur = db_cnx.cursor() data = normalize(cur.execute(self.query).fetchall(), cur.description) for status in range(0, len(TRANSACTION_STATUS_ENUM)): status_name = TRANSACTION_STATUS_ENUM[status] status_total = normalize(cur.execute(self.status_query, {'statu...
v = str(v) v = v.strip() if t == 'chart_type':
v = mf(t(str(v))) elif t == 'chart_type':
def validate(user_input, valid): d = dict(zip(valid.keys(), (None,))) for k, v in user_input.items(): if k in valid.keys(): # redundant t = valid[k] if t == bool: if v in ('false', 'False', 'FALSE', 'f', 'F', 0, 'off', 'no', 'OFF', 'No', 'n', 'N'): v = False if t == Decimal: v = str(v) v = v.strip() if t == 'chart_typ...
if t == Decimal: v = str(v) v = v.strip()
def validate(user_input, valid): d = dict(zip(valid.keys(), (None,))) for k, v in user_input.items(): if k in valid.keys(): # redundant t = valid[k] if t == bool: if v in ('false', 'False', 'FALSE', 'f', 'F', 0, 'off', 'no', 'OFF', 'No', 'n', 'N'): v = False if t == Decimal: v = str(v) v = v.strip() if t == 'chart_typ...
item['%s_total' % status_name] = str(Decimal(str(t)))
item['%s_total' % status_name] = mf(Decimal(str(t)))
def GET(self, db_name, _user=None): db_cnx = get_db_cnx(db_name) cur = db_cnx.cursor() data = normalize(cur.execute(self.query).fetchall(), cur.description) for status in range(0, len(TRANSACTION_STATUS_ENUM)): status_name = TRANSACTION_STATUS_ENUM[status] status_total = normalize(cur.execute(self.status_query, {'statu...
item['balance_difference'] = str(Decimal(str(difference)))
item['balance_difference'] = mf(Decimal(str(difference)))
def GET(self, db_name, _user=None): db_cnx = get_db_cnx(db_name) cur = db_cnx.cursor() data = normalize(cur.execute(self.query).fetchall(), cur.description) for status in range(0, len(TRANSACTION_STATUS_ENUM)): status_name = TRANSACTION_STATUS_ENUM[status] status_total = normalize(cur.execute(self.status_query, {'statu...
if Decimal(str(data['balance'])) == Decimal(str(data['transaction_total'])):
if float(mf(Decimal(str(data['balance'])))) == float(mf(Decimal(str(data['transaction_total'])))):
def POST(self, db_name, account_id, _user=None): db_cnx = get_db_cnx(db_name) cur = db_cnx.cursor() query = """ select * from Account left outer join ( select account as id, total(total) as transaction_total from ( select * from FinancialTransaction join ( select total(amount) as total, financial_transaction as id from...
available = float(item['amount'])
available = Decimal(item['amount'])
def POST(self, db_name, _user=None): user_input = web.input(data_string=None) user_data = load_formatted_data(_user["data_format"], str(user_input.data_string)) t = validate(user_data, {'name':str, 'status':int, 'date':year_month_day, 'account':int, 'items':list}) self.db_cnx = get_db_cnx(db_name) self.cur = self.db_cn...
expense_allotment = float(normalize(self.cur.execute(setting_query), self.cur.description)[0]['setting']) expense_available = available * (expense_allotment/100.0) saving_available = available * ((100.0 - expense_allotment)/100.0)
expense_allotment = Decimal(normalize(self.cur.execute(setting_query), self.cur.description)[0]['setting']) expense_available = available * (expense_allotment/Decimal('100.0')) saving_available = available * ((Decimal('100.0') - expense_allotment)/Decimal('100.0'))
def POST(self, db_name, _user=None): user_input = web.input(data_string=None) user_data = load_formatted_data(_user["data_format"], str(user_input.data_string)) t = validate(user_data, {'name':str, 'status':int, 'date':year_month_day, 'account':int, 'items':list}) self.db_cnx = get_db_cnx(db_name) self.cur = self.db_cn...
diff = float(cat['maximum']) - float(cat['balance']) cat['balance'] = str(Decimal(str(float(cat['balance'])+min(diff, available))))
diff = Decimal(cat['maximum']) - Decimal(cat['balance']) cat['balance'] = mf(Decimal(cat['balance'])+min(diff, available))
def _distribute_to_bill_categories(self, available): "Distribute between bill categories based on allotment date" bill_categories = normalize(self.cur.execute("select * from BillCategory join (select date('now') as now) where active = 1 and allotment_date < now and balance != maximum order by due;"), self.cur.descripti...
saving_allotment_total = int(normalize(self.cur.execute("select total(allotment) as total_allotment from SavingCategory where active = 1 and allotment_date < :t_date and cast(balance as numeric) < cast(maximum as numeric);", {'t_date':t_date}), self.cur.description)[0]['total_allotment'])
saving_allotment_total = Decimal(str(normalize(self.cur.execute("select total(allotment) as total_allotment from SavingCategory where active = 1 and allotment_date < :t_date and cast(balance as numeric) < cast(maximum as numeric);", {'t_date':t_date}), self.cur.description)[0]['total_allotment']))
def _distribute_to_saving_categories(self, t_date, available): "Distribute between saving categories that the current date is after the allotment date" saving_categories = normalize(self.cur.execute("select * from SavingCategory where active = 1 and allotment_date < :t_date and cast(balance as numeric) < cast(maximum a...
share = (float(cat['allotment'])/float(saving_allotment_total)) * available diff = float(cat['minimum']) - float(cat['allotment_amount']) max_diff = float(cat['maximum']) - float(cat['balance'])
share = (Decimal(cat['allotment'])/saving_allotment_total) * available diff = Decimal(cat['minimum']) - Decimal(cat['allotment_amount']) max_diff = Decimal(cat['maximum']) - Decimal(cat['balance'])
def _distribute_to_saving_categories(self, t_date, available): "Distribute between saving categories that the current date is after the allotment date" saving_categories = normalize(self.cur.execute("select * from SavingCategory where active = 1 and allotment_date < :t_date and cast(balance as numeric) < cast(maximum a...
cat['balance'] = str(Decimal(str(float(cat['balance'])+change))) cat['allotment_amount'] = str(Decimal(str(float(cat['allotment_amount'])+change))) if (float(cat['allotment_amount']) == float(cat['minimum'])): cat['allotment_amount'] = "0.00"
cat['balance'] = mf(Decimal(cat['balance'])+change) cat['allotment_amount'] = mf(Decimal(cat['allotment_amount'])+change) if (Decimal(cat['allotment_amount']) == Decimal(cat['minimum'])): cat['allotment_amount'] = mf(Decimal("0.00"))
def _distribute_to_saving_categories(self, t_date, available): "Distribute between saving categories that the current date is after the allotment date" saving_categories = normalize(self.cur.execute("select * from SavingCategory where active = 1 and allotment_date < :t_date and cast(balance as numeric) < cast(maximum a...
expense_allotment_total = int(normalize(self.cur.execute("select total(allotment) as total_allotment from ExpenseCategory where active=1;"), self.cur.description)[0]['total_allotment'])
expense_allotment_total = Decimal(str(normalize(self.cur.execute("select total(allotment) as total_allotment from ExpenseCategory where active=1;"), self.cur.description)[0]['total_allotment']))
def _distribute_to_expense_categories(self, available): "Distribute the income item between categories based on allotments" expense_categories = normalize(self.cur.execute("select * from ExpenseCategory where active=1 order by allotment desc;"), self.cur.description) expense_allotment_total = int(normalize(self.cur.exe...
if float(cat['balance']) < float(cat['minimum']): diff = float(cat['minimum']) - float(cat['balance']) cat['balance'] = str(Decimal(str(float(cat['balance'])+min(diff, available))))
if Decimal(cat['balance']) < Decimal(cat['minimum']): diff = Decimal(cat['minimum']) - Decimal(cat['balance']) cat['balance'] = mf(Decimal(cat['balance'])+min(diff, available))
def _distribute_to_expense_categories(self, available): "Distribute the income item between categories based on allotments" expense_categories = normalize(self.cur.execute("select * from ExpenseCategory where active=1 order by allotment desc;"), self.cur.description) expense_allotment_total = int(normalize(self.cur.exe...
available = 0
available = Decimal('0.00')
def _distribute_to_expense_categories(self, available): "Distribute the income item between categories based on allotments" expense_categories = normalize(self.cur.execute("select * from ExpenseCategory where active=1 order by allotment desc;"), self.cur.description) expense_allotment_total = int(normalize(self.cur.exe...
share = (float(cat['allotment'])/float(expense_allotment_total)) * available diff = float(cat['maximum']) - float(cat['balance'])
share = (Decimal(cat['allotment'])/expense_allotment_total) * available diff = Decimal(cat['maximum']) - Decimal(cat['balance'])
def _distribute_to_expense_categories(self, available): "Distribute the income item between categories based on allotments" expense_categories = normalize(self.cur.execute("select * from ExpenseCategory where active=1 order by allotment desc;"), self.cur.description) expense_allotment_total = int(normalize(self.cur.exe...
cat['balance'] = str(Decimal(str(float(cat['balance'])+change)))
cat['balance'] = mf(Decimal(cat['balance'])+change)
def _distribute_to_expense_categories(self, available): "Distribute the income item between categories based on allotments" expense_categories = normalize(self.cur.execute("select * from ExpenseCategory where active=1 order by allotment desc;"), self.cur.description) expense_allotment_total = int(normalize(self.cur.exe...
if float(cat['balance']) < float(cat['maximum']):
if Decimal(cat['balance']) < Decimal(cat['maximum']):
def _distribute_to_expense_categories(self, available): "Distribute the income item between categories based on allotments" expense_categories = normalize(self.cur.execute("select * from ExpenseCategory where active=1 order by allotment desc;"), self.cur.description) expense_allotment_total = int(normalize(self.cur.exe...
if float(cat['balance']) < float(cat['maximum']): share = (float(cat['allotment'])/float(extra_allotment_total)) * available diff = float(cat['maximum']) - float(cat['balance'])
if Decimal(cat['balance']) < Decimal(cat['maximum']): share = (Decimal(cat['allotment'])/Decimal(extra_allotment_total)) * available diff = Decimal(cat['maximum']) - Decimal(cat['balance'])
def _distribute_to_expense_categories(self, available): "Distribute the income item between categories based on allotments" expense_categories = normalize(self.cur.execute("select * from ExpenseCategory where active=1 order by allotment desc;"), self.cur.description) expense_allotment_total = int(normalize(self.cur.exe...
buff = float(normalize(self.cur.execute("select balance from ExpenseCategory where id = 1;"), self.cur.description)[0]['balance']) self.cur.execute("update ExpenseCategory set balance = :available where id = 1;", {'available':str(Decimal(str(buff+available)))})
buff = Decimal(normalize(self.cur.execute("select balance from ExpenseCategory where id = 1;"), self.cur.description)[0]['balance']) self.cur.execute("update ExpenseCategory set balance = :available where id = 1;", {'available':mf(buff+available)})
def _distribute_to_buffer(self, available): if available > 0: buff = float(normalize(self.cur.execute("select balance from ExpenseCategory where id = 1;"), self.cur.description)[0]['balance']) self.cur.execute("update ExpenseCategory set balance = :available where id = 1;", {'available':str(Decimal(str(buff+available))...
if float(item['amount']) > float(category['balance']):
item_amount = Decimal(item['amount']) category_balance = Decimal(category['balance']) if item_amount > category_balance:
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
item_amount_over = float(item['amount']) - float(category['balance'])
item_amount_over = item_amount - category_balance
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
if item_amount_over > float(buffer_category['balance']):
buffer_category_balance = Decimal(buffer_category['balance']) if item_amount_over > buffer_category_balance:
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
item_amount_over = float("-%s" % (item_amount_over))
item_amount_over = item_amount_over - item_amount_over*2
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
buffer_balance = Decimal(str(float(buffer_category['balance'])+float(item_amount_over))) self.cur.execute("update ExpenseCategory set balance = :balance where id = 1", {'balance':str(buffer_balance)})
buffer_balance = buffer_category_balance+item_amount_over self.cur.execute("update ExpenseCategory set balance = :balance where id = 1", {'balance':mf(buffer_balance)})
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
item['amount'] = category['balance']
item['amount'] = mf(category_balance) item_amount = category_balance
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
balance = Decimal(str(float(category['balance'])-float(item['amount'])))
balance = category_balance - item_amount
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
self.cur.execute(category_update, {'balance':str(balance), 'id':item['category']})
self.cur.execute(category_update, {'balance':mf(balance), 'id':item['category']})
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
self.cur.execute("update BillCategory set allotment_date = :allotment_date, due = :due, balance = :balance where id = :id", {'allotment_date':dates['allotment_date'], 'due':dates['due'], 'balance':str(balance), 'id':category['id']})
self.cur.execute("update BillCategory set allotment_date = :allotment_date, due = :due, balance = :balance where id = :id", {'allotment_date':dates['allotment_date'], 'due':dates['due'], 'balance':mf(balance), 'id':category['id']})
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
self.cur.execute("update BillCategory set active = 0, balance = :balance where id = :id", {'id':item['category'], 'balance':str(balance)})
self.cur.execute("update BillCategory set active = 0, balance = :balance where id = :id", {'id':item['category'], 'balance':mf(balance)})
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
available = float(t['available']) if available < float(data['balance']):
available = Decimal(t['available']) if available < Decimal(data['balance']):
def check_data(self, data): t = get_total_balance_data(self.cur) available = float(t['available']) if available < float(data['balance']): print "insufficient funds..." #TODO: alert user return data
available = float(t['available']) balance = float(str(data['balance']))
available = Decimal(t['available']) balance = Decimal(data['balance'])
def check_data(self, data): if 'balance' in data: t = get_total_balance_data(self.cur) available = float(t['available']) balance = float(str(data['balance'])) if available < balance: print "insufficient funds..." #TODO: alert user return data
category_total = Decimal(str(sum((float(expense_data['total']), float(bill_data['total']), float(saving_data['total']))))) data = {'expense':str(Decimal(str(expense_data['total']))), 'bill':str(Decimal(str(bill_data['total']))), 'saving':str(Decimal(str(saving_data['total']))), 'transaction':str(Decimal(str(transaction...
category_total = sum((Decimal(str(expense_data['total'])), Decimal(str(bill_data['total'])), Decimal(str(saving_data['total'])))) data = {'expense':mf(Decimal(str(expense_data['total']))), 'bill':mf(Decimal(str(bill_data['total']))), 'saving':mf(Decimal(str(saving_data['total']))), 'transaction':mf(Decimal(str(transact...
def get_total_balance_data(cur): query_expense = "select total(balance) as total from ExpenseCategory where active = 1;" query_bill = "select total(balance) as total from BillCategory where active = 1;" query_saving = "select total(balance) as total from SavingCategory where active = 1;" query_transaction = """select t...
print "splitting item amount with buffer balance"
item_amount_over = float("-%s" % (item_amount_over)) print "splitting item amount with buffer balance %s" % item_amount_over
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
buffer_balance = Decimal(str(float(buffer_category['balance'])-float(item_amount_over)))
buffer_balance = Decimal(str(float(buffer_category['balance'])+float(item_amount_over)))
def _update_category_balance(self, item): "Update the category balance from the item amount" if int(item['type']) == 1: table = "ExpenseCategory" elif int(item['type']) == 2: table = "BillCategory" elif int(item['type']) == 3: table = "SavingCategory" category_select = "select * from %s where id = :id;" % (table) categ...
oldshift = Shift.objects.filter(person=request.user, punchclock=location, outtime=None)
oldshift = Shift.objects.filter(person=request.user, outtime=None)
def time(request): """ Sign in or sign out of a shift. """ #Generate a token to protect from cross-site request forgery c = {} c.update(csrf(request)) #Check for POST, if not blank form, if true 'take in data' if request.method == 'POST': form = ShiftForm(request.POST) #Check form data for validity, if not valid, fail ...
return delta/60/60
delta = float(delta.seconds) hours = delta/60/60 return "%.02f" % hours
def length(self): if self.outtime: delta = self.outtime - self.intime return delta/60/60 else: return datetime.timedelta(0)
os.path.join(output_dir, '/p-rmcube-dirty.fits'),
os.path.join(output_dir, 'p-rmcube-dirty.fits'),
def write_rmcube(rmcube, fits_header, output_dir, force_overwrite=False): write_fits_cube(abs(rmcube), fits_header, os.path.join(output_dir, '/p-rmcube-dirty.fits'), force_overwrite=force_overwrite) write_fits_cube(rmcube.real, fits_header, os.path.join(output_dir, '/q-rmcube-dirty.fits'), force_overwrite=force_overwr...
os.path.join(output_dir, '/q-rmcube-dirty.fits'),
os.path.join(output_dir, 'q-rmcube-dirty.fits'),
def write_rmcube(rmcube, fits_header, output_dir, force_overwrite=False): write_fits_cube(abs(rmcube), fits_header, os.path.join(output_dir, '/p-rmcube-dirty.fits'), force_overwrite=force_overwrite) write_fits_cube(rmcube.real, fits_header, os.path.join(output_dir, '/q-rmcube-dirty.fits'), force_overwrite=force_overwr...
os.path.join(output_dir, '/u-rmcube-dirty.fits'),
os.path.join(output_dir, 'u-rmcube-dirty.fits'),
def write_rmcube(rmcube, fits_header, output_dir, force_overwrite=False): write_fits_cube(abs(rmcube), fits_header, os.path.join(output_dir, '/p-rmcube-dirty.fits'), force_overwrite=force_overwrite) write_fits_cube(rmcube.real, fits_header, os.path.join(output_dir, '/q-rmcube-dirty.fits'), force_overwrite=force_overwr...
def __init__(self): self.pid = _sw.PID_new()
def __init__(self, *args): self.pid = _sw.PID_new(*args)
def __init__(self): self.pid = _sw.PID_new()
except Exception, e:
except Exception:
def mouseMoved(self, x, y): if not self._painting: return
defaultValue = None, SIV = SplineImageView5):
defaultValue = None, SIV = vigra.sampling.SplineImageView5):
def __init__(self, map, originalImage, minSampleCount = 1, defaultValue = None, SIV = SplineImageView5): DynamicFaceStatistics.__init__(self, map) self.originalImage = originalImage
finds the minimum spanning tree of the map's boundary graph (None in edgeCosts is allowed and is handled as if the corresponding edge was missing). The result is a modified copy of the edgeCosts list, with all non-MST-edges set to None. This can be used for the waterfall algorithm by Meyer and Beucher, see waterfall(...
finds the minimum spanning tree of the map's region adjacency graph (None in edgeCosts is allowed and is handled as if the corresponding edge was missing). The result is a modified copy of the edgeCosts list, with all non-MST-edges set to None. This can be used for the waterfall algorithm by Meyer and Beucher, see wa...
def minimumSpanningTree(map, edgeCosts): """minimumSpanningTree(map, edgeCosts) Given a cost associated with each edge of the map, this function finds the minimum spanning tree of the map's boundary graph (None in edgeCosts is allowed and is handled as if the corresponding edge was missing). The result is a modified ...
self.d_tempUnit = cg.readEntry("tempUnit", 1) if self.d_tempUnit == 0: self.tempunit = u'℃' elif self.d_tempUnit == 1: self.tempunit = 'F' else: self.tempunit = u'℃'
self.d_tempUnit = cg.readEntry("tempUnit", 0)
def init(self): self.resize(250, 400) self.connect(Plasma.Theme.defaultTheme(), SIGNAL("themeChanged()"), self.themeChanged) #load value from default theme, make this widget suit it theme = Plasma.Theme.defaultTheme() t_textcolor = theme.color(Plasma.Theme.TextColor) #load config cg = self.config() d_refreshtime = cg...
self.chart2.setVerticalRange(0, 110)
def init(self): self.resize(250, 400) self.connect(Plasma.Theme.defaultTheme(), SIGNAL("themeChanged()"), self.themeChanged) #load value from default theme, make this widget suit it theme = Plasma.Theme.defaultTheme() t_textcolor = theme.color(Plasma.Theme.TextColor) #load config cg = self.config() d_refreshtime = cg...
temp = (float(result[3]))
temp = (float(degree))
def init(self): self.resize(250, 400) self.connect(Plasma.Theme.defaultTheme(), SIGNAL("themeChanged()"), self.themeChanged) #load value from default theme, make this widget suit it theme = Plasma.Theme.defaultTheme() t_textcolor = theme.color(Plasma.Theme.TextColor) #load config cg = self.config() d_refreshtime = cg...
self.valueLabel2.setText(result[3] + self.tempunit)
self.valueLabel2.setText(degree + self.tempunit)
def init(self): self.resize(250, 400) self.connect(Plasma.Theme.defaultTheme(), SIGNAL("themeChanged()"), self.themeChanged) #load value from default theme, make this widget suit it theme = Plasma.Theme.defaultTheme() t_textcolor = theme.color(Plasma.Theme.TextColor) #load config cg = self.config() d_refreshtime = cg...
memcl = (result[1])
memcl = (int(result[1]))
def init(self): self.resize(250, 400) self.connect(Plasma.Theme.defaultTheme(), SIGNAL("themeChanged()"), self.themeChanged) #load value from default theme, make this widget suit it theme = Plasma.Theme.defaultTheme() t_textcolor = theme.color(Plasma.Theme.TextColor) #load config cg = self.config() d_refreshtime = cg...
self.valueLabel2.setText(result[3] + self.tempunit)
if self.d_tempUnit == 1: degree = self.c2f(result[3]) self.valueLabel2.setText(degree + self.tempunit) else: self.valueLabel2.setText(result[3] + self.tempunit)
def updateTime(self): result = self.getresult() load = (int(result[2])) samples = [load,] self.chart1.addSample(samples) self.valueLabel1.setText(result[2] + '%') temp = (float(result[3])) samples = [temp,] self.chart2.addSample(samples) self.valueLabel2.setText(result[3] + self.tempunit)
pipe = _parse_pipe(json_pipe, pipe_name)
pipe = _parse_pipe(json_pipe, "anonymous")
def parse_and_build_pipe(json_pipe): pipe = _parse_pipe(json_pipe, pipe_name) pb = build_pipe(pipe) return pb
if re.search(value, item[field].search):
if re.search(value, item[field]):
def _rulepass(rule, item): field, op, value = rule #TODO: is this ok? if field in FIELD_MAP: field = FIELD_MAP[field] #map to universal feedparser's normalised names if field not in item: return True #todo check which of these should be case insensitive if op == "contains": if value.lower() in item[field].lower(): ...
kargs["%(id)s" % {'id':util.pythonise(pipe['wires'][wire]['tgt']['id'])}] = "%(secondary_module)s" % {'secondary_module':steps[util.pythonise(pipe['wires'][wire]['src']['moduleid'])]}
kargs["%(id)s" % {'id':util.pythonise(pipe['wires'][wire]['tgt']['id'])}] = steps[util.pythonise(pipe['wires'][wire]['src']['moduleid'])]
def build_pipe(pipe, verbose=False): """Convert a pipe into an executable Python pipeline Note: any subpipes must be available to import as .py files """ module_sequence = topological_sort(pipe['graph']) #First pass to find and import any required subpipelines #Note: assumes they have already been compiled to accessi...
pargs["%(id)s" % {'id':util.pythonise(pipe['wires'][wire]['tgt']['id'])}] = "%(secondary_module)s" % {'secondary_module':steps[util.pythonise(pipe['wires'][wire]['src']['moduleid'])]}
kargs["%(id)s" % {'id':util.pythonise(pipe['wires'][wire]['tgt']['id'])}] = "%(secondary_module)s" % {'secondary_module':steps[util.pythonise(pipe['wires'][wire]['src']['moduleid'])]}
def build_pipe(pipe, verbose=False): """Convert a pipe into an executable Python pipeline Note: any subpipes must be available to import as .py files """ module_sequence = topological_sort(pipe['graph']) #First pass to find and import any required subpipelines #Note: assumes they have already been compiled to accessi...
err.error(("testcases_scripting", "test_js_file", "retrieving_tree"), "JS Syntax error prevented validation", ["An error in the syntax of a JavaScript file prevented " "the file from being properly read by the Spidermonkey JS " "engine.", str(exc)], filename=filename)
str_exc = str(exc) if "SyntaxError" in str_exc: err.error(("testcases_scripting", "test_js_file", "syntax_error"), "Javascript Syntax Error", ["A syntax error in the Javascript halted validation " "of that file.", "Message: %s" % str_exc[15:-1]], filename=filename, line=exc.line) else: err.error(("testcases_scripting",...
def test_js_file(err, name, data, filename=None, line=0): "Tests a JS file by parsing and analyzing its tokens" if SPIDERMONKEY_INSTALLATION is None and \ err.get_resource("SPIDERMONKEY") is None: # Default value is False return # The filename is if filename is None: filename = name # Get the AST tree for the JS cod...
def _get_tree(name, code, shell=SPIDERMONKEY_INSTALLATION, errorbundle=None): if not code: return None encoding = None try: code = unicode(code) line_num = 1 out_code = StringIO() is_ctrl_char = lambda x:(lambda y:y >= 0 and y <= 31 and y not in (10, 13) )(ord(x)) has_warned_ctrlchar = False for line in code.spl...
def line_num(self, line_num): "Set the line number and return self for chaining" self.line = int(line_num) return self def is_ctrl_char(x): "Returns whether X is an ASCII control character" y = ord(x) return 0 <= y <= 31 and y not in (9, 10, 13) def strip_weird_chars(chardata, err=None, name=""): line_num = 1 out_cod...
def __str__(self): return repr(self.value)
fails = err.detected_type != PACKAGE_DICTIONARY
fails = err.detected_type == PACKAGE_DICTIONARY
def test_emunpack(err, package_contents, xpi_package): if err.get_resource("em:unpack") != "true": # Covers bug 597255 # Dictionaries should always be unpacked fails = err.detected_type != PACKAGE_DICTIONARY if not fails: # Search for unpack-worthy files for file_ in package_contents: if fnmatch.fnmatch(file_, "compo...
if fnmatch.fnmatch(file_, "components/*.exe") or \ fnmatch.fnmatch(file_, "*.ico"):
if fnmatch.fnmatch(file_, "*.ico"): fails = True break if fnmatch.fnmatch(file_, "components/*") and \ [x for x in executables if file_[:-len(x) - 1] == ".%s" % x]:
def test_emunpack(err, package_contents, xpi_package): if err.get_resource("em:unpack") != "true": # Covers bug 597255 # Dictionaries should always be unpacked fails = err.detected_type != PACKAGE_DICTIONARY if not fails: # Search for unpack-worthy files for file_ in package_contents: if fnmatch.fnmatch(file_, "compo...
ref_doc = _parse_l10n_doc(name, reference.read(name)) if not ref_doc.expected_encoding: results.append({"type": "unexpected_encoding", "filename": name, "expected_encoding": ref_doc.suitable_encoding, "encoding": ref_doc.found_encoding})
ref_doc = _parse_l10n_doc(name, reference.read(name), no_encoding=True)
def _compare_packages(reference, target, ref_base=None): "Compares two L10n-compatible packages to one another." ref_files = reference.get_file_data() tar_files = target.get_file_data() results = [] total_entities = 0 if isinstance(ref_base, str): ref_base = ref_base.lstrip("/") l10n_docs = ("dtd", "properties", "x...
def _parse_l10n_doc(name, doc):
def _parse_l10n_doc(name, doc, no_encoding=False):
def _parse_l10n_doc(name, doc): "Parses an L10n document." extension = name.split(".")[-1].lower() handlers = {"dtd": dtd.DTDParser, "properties": properties.PropertiesParser} # These are expected encodings for the various files. handler_formats = {"dtd": ("UTF-8", ), "properties": ("ascii", "utf-8")} if extension no...
"properties": ("ascii", "utf-8")}
"properties": ("ASCII", "UTF-8")}
def _parse_l10n_doc(name, doc): "Parses an L10n document." extension = name.split(".")[-1].lower() handlers = {"dtd": dtd.DTDParser, "properties": properties.PropertiesParser} # These are expected encodings for the various files. handler_formats = {"dtd": ("UTF-8", ), "properties": ("ascii", "utf-8")} if extension no...