rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
os.unlink(tfn)
os.unlink(tf.name)
def commit(self, entry): file = entry.file # Normalize line endings in body if '\r' in self.ui.body: self.ui.body = re.sub('\r\n?', '\n', self.ui.body) # Normalize whitespace in title self.ui.title = ' '.join(self.ui.title.split()) # Check that there were any changes if self.ui.body == entry.body and self.ui.title == entry.title: self.error("You didn't make any changes!") return
traceback.print_exc()
traceback.print_exc(file=sys.stdout)
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc() finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
("t1", [("t1", None)], "import ni"),
("t1", [("t1", None)], "import t1"),
def runtest(hier, code): root = tempfile.mktemp() mkhier(root, hier) savepath = sys.path[:] codefile = tempfile.mktemp() f = open(codefile, "w") f.write(code) f.close() try: sys.path.insert(0, root) if verbose: print "sys.path =", sys.path try: execfile(codefile, globals(), {}) except: traceback.print_exc() finally: sys.path[:] = savepath try: cleanout(root) except (os.error, IOError): pass os.remove(codefile)
test('replace', 'one!two!three!', 'one!two!three!', '!', '@', 0)
test('replace', 'one!two!three!', 'one@two@three@', '!', '@', 0)
def __getitem__(self, i): return self.seq[i]
osname = string.lower(osname)
osname = string.lower(osname) osname = string.replace(osname, '/', '')
def get_platform (): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 For non-POSIX platforms, currently just returns 'sys.platform'. """ if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha, # Mac OS is M68k or PPC, etc. return sys.platform # Try to distinguish various flavours of Unix (osname, host, release, version, machine) = os.uname() osname = string.lower(osname) if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # fall through to standard osname-release-machine representation elif osname[:4] == "irix": # could be "irix64"! return "%s-%s" % (osname, release) elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": rel_re = re.compile (r'[\d.]+') m = rel_re.match(release) if m: release = m.group() return "%s-%s-%s" % (osname, release, machine)
if isinstance(fullurl, (types.StringType, types.UnicodeType)):
if isinstance(fullurl, types.StringTypes):
def open(self, fullurl, data=None): # accept a URL or a Request object if isinstance(fullurl, (types.StringType, types.UnicodeType)): req = Request(fullurl, data) else: req = fullurl if data is not None: req.add_data(data) assert isinstance(req, Request) # really only care about interface
if isinstance(uri, (types.StringType, types.UnicodeType)):
if isinstance(uri, types.StringTypes):
def add_password(self, realm, uri, user, passwd): # uri could be a single URI or a sequence if isinstance(uri, (types.StringType, types.UnicodeType)): uri = [uri] uri = tuple(map(self.reduce_uri, uri)) if not self.passwd.has_key(realm): self.passwd[realm] = {} self.passwd[realm][uri] = (user, passwd)
debian_tcl_include = ( '/usr/include/tcl' + version ) debian_tk_include = ( '/usr/include/tk' + version ) tcl_includes = find_file('tcl.h', inc_dirs, [debian_tcl_include] ) tk_includes = find_file('tk.h', inc_dirs, [debian_tk_include] )
debian_tcl_include = [ '/usr/include/tcl' + version ] debian_tk_include = [ '/usr/include/tk' + version ] + debian_tcl_include tcl_includes = find_file('tcl.h', inc_dirs, debian_tcl_include) tk_includes = find_file('tk.h', inc_dirs, debian_tk_include)
def detect_tkinter(self, inc_dirs, lib_dirs): # The _tkinter module. # # The command for _tkinter is long and site specific. Please # uncomment and/or edit those parts as indicated. If you don't have a # specific extension (e.g. Tix or BLT), leave the corresponding line # commented out. (Leave the trailing backslashes in! If you # experience strange errors, you may want to join all uncommented # lines and remove the backslashes -- the backslash interpretation is # done by the shell's "read" command and it may not be implemented on # every system.
lexer.whitepace = ' \t'
lexer.whitespace = ' \t'
# Look for a machine, default, or macdef top-level keyword
if not line or line == '\012' and tt == '\012': lexer.whitepace = ' \t\r\n'
if not line or line == '\012': lexer.whitespace = ' \t\r\n'
# Look for a machine, default, or macdef top-level keyword
tt = line
# Look for a machine, default, or macdef top-level keyword
if toplevel == 'machine': login = account = password = None self.hosts[entryname] = {}
login = account = password = None self.hosts[entryname] = {}
# Look for a machine, default, or macdef top-level keyword
if tt=='' or tt == 'machine' or tt == 'default' or tt == 'macdef': if toplevel == 'macdef': break elif login and password:
if (tt=='' or tt == 'machine' or tt == 'default' or tt =='macdef'): if login and password:
# Look for a machine, default, or macdef top-level keyword
Assume y1 <= y2 and no funny (non-leap century) years.""" return (y2+3)/4 - (y1+3)/4
Assume y1 <= y2.""" y1 -= 1 y2 -= 1 return (y2/4 - y1/4) - (y2/100 - y1/100) + (y2/400 - y1/400)
def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2 and no funny (non-leap century) years.""" return (y2+3)/4 - (y1+3)/4
sys.stdout.write(s1.replace("\r\n", "\n"))
sys.stdout.write(normalize_output(s1))
def test_basic_pty(): try: debug("Calling master_open()") master_fd, slave_name = pty.master_open() debug("Got master_fd '%d', slave_name '%s'"%(master_fd, slave_name)) debug("Calling slave_open(%r)"%(slave_name,)) slave_fd = pty.slave_open(slave_name) debug("Got slave_fd '%d'"%slave_fd) except OSError: # " An optional feature could not be imported " ... ? raise TestSkipped, "Pseudo-terminals (seemingly) not functional." if not os.isatty(slave_fd) and sys.platform not in fickle_isatty: raise TestFailed, "slave_fd is not a tty" # IRIX apparently turns \n into \r\n. Allow that, but avoid allowing other # differences (like extra whitespace, trailing garbage, etc.) debug("Writing to slave_fd") os.write(slave_fd, TEST_STRING_1) s1 = os.read(master_fd, 1024) sys.stdout.write(s1.replace("\r\n", "\n")) debug("Writing chunked output") os.write(slave_fd, TEST_STRING_2[:5]) os.write(slave_fd, TEST_STRING_2[5:]) s2 = os.read(master_fd, 1024) sys.stdout.write(s2.replace("\r\n", "\n")) os.close(slave_fd) os.close(master_fd)
sys.stdout.write(s2.replace("\r\n", "\n"))
sys.stdout.write(normalize_output(s2))
def test_basic_pty(): try: debug("Calling master_open()") master_fd, slave_name = pty.master_open() debug("Got master_fd '%d', slave_name '%s'"%(master_fd, slave_name)) debug("Calling slave_open(%r)"%(slave_name,)) slave_fd = pty.slave_open(slave_name) debug("Got slave_fd '%d'"%slave_fd) except OSError: # " An optional feature could not be imported " ... ? raise TestSkipped, "Pseudo-terminals (seemingly) not functional." if not os.isatty(slave_fd) and sys.platform not in fickle_isatty: raise TestFailed, "slave_fd is not a tty" # IRIX apparently turns \n into \r\n. Allow that, but avoid allowing other # differences (like extra whitespace, trailing garbage, etc.) debug("Writing to slave_fd") os.write(slave_fd, TEST_STRING_1) s1 = os.read(master_fd, 1024) sys.stdout.write(s1.replace("\r\n", "\n")) debug("Writing chunked output") os.write(slave_fd, TEST_STRING_2[:5]) os.write(slave_fd, TEST_STRING_2[5:]) s2 = os.read(master_fd, 1024) sys.stdout.write(s2.replace("\r\n", "\n")) os.close(slave_fd) os.close(master_fd)
compiler = self.compiler
def build_libraries (self, libraries):
self.info = list(self.interesting_lines(1))
self.info = [(0, -1, "", False)]
def __init__(self, editwin): self.editwin = editwin self.text = editwin.text self.textfont = self.text["font"] self.label = None # Dummy line, which starts the "block" of the whole document: self.info = list(self.interesting_lines(1)) self.lastfirstline = 1 visible = idleConf.GetOption("extensions", "CodeContext", "visible", type="bool", default=False) if visible: self.toggle_code_context_event() self.editwin.setvar('<<toggle-code-context>>', True) # Start two update cycles, one for context lines, one for font changes. self.text.after(UPDATEINTERVAL, self.timer_event) self.text.after(FONTUPDATEINTERVAL, self.font_timer_event)
There is a dummy block start, with indentation -1 and text "". Return the indent level, text (including leading whitespace), and the block opening keyword.
def get_line_info(self, linenum): """Get the line indent value, text, and any block start keyword
if linenum == 0: return -1, "", True
def get_line_info(self, linenum): """Get the line indent value, text, and any block start keyword
def interesting_lines(self, firstline): """Generator which yields context lines, starting at firstline."""
def interesting_lines(self, firstline, stopline=1, stopindent=0): """ Find the context lines, starting at firstline. Will not return lines whose index is smaller than stopline or whose indentation is smaller than stopindent. stopline should always be >= 1, so the dummy block start will never be returned (This function doesn't know what to do about it.) Returns a list with the context lines, starting from the first (top), and a number which all context lines above the inspected region should have a smaller indentation than it. """ lines = []
def interesting_lines(self, firstline): """Generator which yields context lines, starting at firstline.""" # The indentation level we are currently in: lastindent = INFINITY # For a line to be interesting, it must begin with a block opening # keyword, and have less indentation than lastindent. for line_index in xrange(firstline, -1, -1): indent, text, opener = self.get_line_info(line_index) if indent < lastindent: lastindent = indent if opener in ("else", "elif"): # We also show the if statement lastindent += 1 if opener and line_index < firstline: yield line_index, text
for line_index in xrange(firstline, -1, -1):
for line_index in xrange(firstline, stopline-1, -1):
def interesting_lines(self, firstline): """Generator which yields context lines, starting at firstline.""" # The indentation level we are currently in: lastindent = INFINITY # For a line to be interesting, it must begin with a block opening # keyword, and have less indentation than lastindent. for line_index in xrange(firstline, -1, -1): indent, text, opener = self.get_line_info(line_index) if indent < lastindent: lastindent = indent if opener in ("else", "elif"): # We also show the if statement lastindent += 1 if opener and line_index < firstline: yield line_index, text
if opener and line_index < firstline: yield line_index, text
if opener and line_index < firstline and indent >= stopindent: lines.append((line_index, indent, text, opener)) if lastindent <= stopindent: break lines.reverse() return lines, lastindent
def interesting_lines(self, firstline): """Generator which yields context lines, starting at firstline.""" # The indentation level we are currently in: lastindent = INFINITY # For a line to be interesting, it must begin with a block opening # keyword, and have less indentation than lastindent. for line_index in xrange(firstline, -1, -1): indent, text, opener = self.get_line_info(line_index) if indent < lastindent: lastindent = indent if opener in ("else", "elif"): # We also show the if statement lastindent += 1 if opener and line_index < firstline: yield line_index, text
tmpstack = [] for line_index, text in self.interesting_lines(firstline): while self.info[-1][0] > line_index: del self.info[-1] if self.info[-1][0] == line_index: break tmpstack.append((line_index, text)) while tmpstack: self.info.append(tmpstack.pop())
def update_label(self): firstline = int(self.text.index("@0,0").split('.')[0]) if self.lastfirstline == firstline: return self.lastfirstline = firstline tmpstack = [] for line_index, text in self.interesting_lines(firstline): # Remove irrelevant self.info items, and when we reach a relevant # item (which must happen because of the dummy element), break. while self.info[-1][0] > line_index: del self.info[-1] if self.info[-1][0] == line_index: break tmpstack.append((line_index, text)) while tmpstack: self.info.append(tmpstack.pop()) lines = [""] * max(0, self.numlines - len(self.info)) + \ [x[1] for x in self.info[-self.numlines:]] self.label["text"] = '\n'.join(lines)
[x[1] for x in self.info[-self.numlines:]]
[x[2] for x in self.info[-self.numlines:]]
def update_label(self): firstline = int(self.text.index("@0,0").split('.')[0]) if self.lastfirstline == firstline: return self.lastfirstline = firstline tmpstack = [] for line_index, text in self.interesting_lines(firstline): # Remove irrelevant self.info items, and when we reach a relevant # item (which must happen because of the dummy element), break. while self.info[-1][0] > line_index: del self.info[-1] if self.info[-1][0] == line_index: break tmpstack.append((line_index, text)) while tmpstack: self.info.append(tmpstack.pop()) lines = [""] * max(0, self.numlines - len(self.info)) + \ [x[1] for x in self.info[-self.numlines:]] self.label["text"] = '\n'.join(lines)
self.assertEqual(sys.stdout.getvalue().splitlines(), ['0', '0.5', '0'])
if 1/2 == 0: expected = ['0', '0.5', '0'] else: expected = ['0.5', '0.5', '0.5'] self.assertEqual(sys.stdout.getvalue().splitlines(), expected)
def test_input_and_raw_input(self): self.write_testfile() fp = open(TESTFN, 'r') savestdin = sys.stdin savestdout = sys.stdout # Eats the echo try: sys.stdin = fp sys.stdout = BitBucket() self.assertEqual(input(), 2) self.assertEqual(input('testing\n'), 2) self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.') self.assertEqual(raw_input('testing\n'), 'Dear John') sys.stdin = cStringIO.StringIO("NULL\0") self.assertRaises(TypeError, input, 42, 42) sys.stdin = cStringIO.StringIO(" 'whitespace'") self.assertEqual(input(), 'whitespace') sys.stdin = cStringIO.StringIO() self.assertRaises(EOFError, input)
def message_from_string(s, _class=_Message): return _Parser(_class).parsestr(s)
def message_from_string(s, _class=_Message, strict=1): return _Parser(_class, strict=strict).parsestr(s)
def message_from_string(s, _class=_Message): return _Parser(_class).parsestr(s)
attrname = string.lower(attrname)
def parse_starttag(self, i):
def askopenfilenames(**options): """Ask for multiple filenames to open Returns a list of filenames or empty list if cancel button selected """ options["multiple"]=1 files=Open(**options).show() return files.split()
def asksaveasfilename(**options): "Ask for a filename to save as" return SaveAs(**options).show()
n_lines += 1
def write_results_file(self, path, lines, lnotab, lines_hit): """Return a coverage results file in path."""
params, method = xmlrpclib.loads(data)
def _marshaled_dispatch(self, data, dispatch_method = None): """Dispatches an XML-RPC method from marshalled (XML) data.
print self.debug
def sendsms(self):#{{{ baseURLSSL='https://www.orange.pl' baseURL='http://www.orange.pl' length = 634 - len(self.message) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # orange index#{{{ request = urllib2.Request(baseURLSSL) request.add_header('User-Agent', 'Opera/8.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'Connecting with',baseURLSSL except IOError: print 'Connection with %s failed.' % baseURLSSL#}}} # orange map#{{{ request = urllib2.Request(baseURLSSL + '/portal/map/map/') request.add_header('User-Agent', 'Opera/8.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'Connecting with www.orange.pl/portal/map/map' except IOError: print 'Connection with https://www.orange.pl/portal/map/map failed.'#}}} # orange login#{{{ parmdicta = {'_dyncharset': 'UTF-8', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.loginErrorURL': '/portal/map/map/signin', '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.loginErrorURL': ' ', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.loginSuccessURL': 'http://www.orange.pl/portal/map/map/pim', '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.loginSuccessURL': ' ', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.value.login': self.login, '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.value.login': ' ', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.value.password': self.password, '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.value.password': ' ', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.login.x': '0', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.login.y': '0', '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.login': ' ', '_DARGS': '/gear/static/login.jsp'} request = urllib2.Request(baseURLSSL + '/portal/map/map/home?_DARGS=/gear/static/login.jsp') postdata = urllib.unquote(urllib.urlencode(parmdicta)) request.add_data(postdata) request.add_header('User-Agent', 'Opera/8.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'Logged' except IOError: print 'Not logged'#}}} # orange SMS form#{{{ request = urllib2.Request(baseURL + '/portal/map/map/message_box?mbox_view=newsms&mbox_edit=new') request.add_header('User-Agent', 'Opera/8.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'Opening SMS form' except IOError: print 'Open SMS form failed.'#}}} # Send SMS#{{{ parmdictb = {'_dyncharset': 'UTF-8', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.type': 'sms', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.type' : ' ', 'enabled': 'true', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.errorURL': '/portal/map/map/message_box?mbox_view=newsms', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.errorURL': ' ', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.successURL': '/portal/map/map/message_box?mbox_view=messageslist', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.successURL': ' ', 'smscounter' : '1', 'counter': length, '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.to': self.number, '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.to': ' ', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.body': ' ', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.body': self.sender+' : '+self.message, '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.create.x': '0', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.create.y': '0', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.create': ' ', '_DARGS': '/gear/mapmessagebox/smsform.jsp'} request = urllib2.Request(baseURL + '/portal/map/map/message_box?_DARGS=/gear/mapmessagebox/smsform.jsp') postdata = urllib.unquote(urllib.urlencode(parmdictb)) request.add_data(postdata) request.add_header('User-Agent', 'Opera/8.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'SMS sended.' except IOError: print 'SMS not send.' smsy = self.zostalo(result.read()) smsy_darmowe = 0 if len(smsy) == 1: smsy_darmowe = smsy[0] smsy_doladowane = 0 if len(smsy) == 2: smsy_darmowe = smsy[0] smsy_doladowane = smsy[1]; if smsy_darmowe and self.debug: print 'Orange -> Zostalo: %s+%s SMS' % (smsy_darmowe, smsy_doladowane) #}}}
print postdata
def sendsms(self):#{{{ baseURLSSL='https://www.orange.pl' baseURL='http://www.orange.pl' length = 634 - len(self.message) cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) # orange index#{{{ request = urllib2.Request(baseURLSSL) request.add_header('User-Agent', 'Opera/9.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'Connecting with',baseURLSSL except IOError: print 'Connection with %s failed.' % baseURLSSL#}}} # orange map#{{{ request = urllib2.Request(baseURLSSL + '/portal/map/map/') request.add_header('User-Agent', 'Opera/8.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'Connecting with www.orange.pl/portal/map/map' except IOError: print 'Connection with https://www.orange.pl/portal/map/map failed.'#}}} # orange login#{{{ parmdicta = { '_dyncharset' : 'UTF-8', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.loginErrorURL' : '/portal/map/map/signin', '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.loginErrorURL' : ' ', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.loginSuccessURL' : 'http://www.orange.pl/portal/map/map/pim', '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.loginSuccessURL' : ' ', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.value.login' : self.login, '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.value.login' : ' ', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.value.password' : self.password, '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.value.password' : ' ', '_D:/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.login' : ' ', '_DARGS' : '/gear/static/home/login.jsp.loginFormId', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.login' : ' ', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.login.x' : '5', '/amg/ptk/map/core/formhandlers/AdvancedProfileFormHandler.login.y' : '5'} request = urllib2.Request(baseURLSSL + '/portal/map/map/homeo?_DARGS=/gear/static/home/login.jsp.loginFormId') postdata = urllib.unquote(urllib.urlencode(parmdicta)) request.add_data(postdata) print postdata request.add_header('User-Agent', 'Opera/8.10 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'Logged' except IOError: print 'Not logged'#}}} # orange SMS form#{{{ request = urllib2.Request(baseURL + '/portal/map/map/message_box?mbox_view=newsms&mbox_edit=new') request.add_header('User-Agent', 'Opera/8.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'Opening SMS form' except IOError: print 'Open SMS form failed.'#}}} # Send SMS#{{{ parmdictb = {'_dyncharset': 'UTF-8', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.type': 'sms', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.type' : ' ', 'enabled': 'true', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.errorURL': '/portal/map/map/message_box?mbox_view=newsms', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.errorURL': ' ', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.successURL': '/portal/map/map/message_box?mbox_view=messageslist', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.successURL': ' ', 'smscounter' : '1', 'counter': '630', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.to': self.number, '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.to': ' ', '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.body': ' ', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.body': self.sender+' : '+self.message, '_D:/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.create': ' ', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.create': 'Wylij', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.create.x': '5', '/amg/ptk/map/messagebox/formhandlers/MessageFormHandler.create.y': '5', '_DARGS': '/gear/mapmessagebox/smsform.jsp'} request = urllib2.Request(baseURL + '/portal/map/map/message_box?_DARGS=/gear/mapmessagebox/smsform.jsp') postdata = urllib.unquote(urllib.urlencode(parmdictb)) request.add_data(postdata) request.add_header('User-Agent', 'Opera/8.00 (Windows NT 5.0; U; en)') try: result = opener.open(request) if self.debug: print 'SMS sended.' except IOError: print 'SMS not send.' smsy = self.zostalo(result.read()) smsy_darmowe = 0 if len(smsy) == 1: smsy_darmowe = smsy[0] smsy_doladowane = 0 if len(smsy) == 2: smsy_darmowe = smsy[0] smsy_doladowane = smsy[1]; if smsy_darmowe and self.debug: print 'Orange -> Zostalo: %s+%s SMS' % (smsy_darmowe, smsy_doladowane) #}}}
print postdata
def sendsms(self):#{{{ baseURL='http://www.eraomnix.pl' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), moj_redirect_handler) request = urllib2.Request(baseURL + '/msg/api/do/tinker/sponsored') parametry = { 'failure' : baseURL, 'success' : baseURL, 'message' : self.message, 'login' : self.login, 'password' : self.password, 'number' : '48' + self.number, 'mms' : 'false'}
print blad
def sendsms(self):#{{{ baseURL='http://www.eraomnix.pl' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj), moj_redirect_handler) request = urllib2.Request(baseURL + '/msg/api/do/tinker/sponsored') parametry = { 'failure' : baseURL, 'success' : baseURL, 'message' : self.message, 'login' : self.login, 'password' : self.password, 'number' : '48' + self.number, 'mms' : 'false'}
print "change desc: ``%s''" % changedesc
def parse_change_desc(changedesc, result_dict): summary = "" description = "" files = [] changedesc_keys = { 'QA Notes': "", 'Testing Done': "", 'Documentation Notes': "", 'Bug Number': "", 'Reviewed by': "", 'Approved by': "", 'Breaks vmcore compatibility': "", 'Breaks vmkernel compatibility': "", 'Breaks vmkdrivers compatibility': "", 'Mailto': "", } process_summary = False process_description = False process_files = False cur_key = None print "change desc: ``%s''" % changedesc for line in changedesc.split("\n"): print ">> `%s'" % line if line == "Description:": process_summary = True continue elif line == "Files:": process_files = True continue elif line == "" or line == "\t": if process_summary: process_summary = False process_description = True continue line = "" elif line.startswith("\t"): line = line[1:] if process_files: files.append(line) elif line.find(':') != -1: key, value = line.split(':', 2) if changedesc_keys.has_key(key): process_description = False cur_key = key changedesc_keys[key] = value.lstrip() + "\n" continue line += "\n" if process_summary: summary += line elif process_description: description += line elif cur_key != None: changedesc_keys[cur_key] += line result_dict['summary'] = summary result_dict['description'] = description result_dict['testing_done'] = changedesc_keys['Testing Done'] # TODO: Normalize bug number result_dict['bugs_closed'] = changedesc_keys['Bug Number'] # This is gross. if len(files) > 0: parts = files[0].split('/') if parts[2] == "depot": result_dict['branch'] = parts[4]
print ">> `%s'" % line
def parse_change_desc(changedesc, result_dict): summary = "" description = "" files = [] changedesc_keys = { 'QA Notes': "", 'Testing Done': "", 'Documentation Notes': "", 'Bug Number': "", 'Reviewed by': "", 'Approved by': "", 'Breaks vmcore compatibility': "", 'Breaks vmkernel compatibility': "", 'Breaks vmkdrivers compatibility': "", 'Mailto': "", } process_summary = False process_description = False process_files = False cur_key = None print "change desc: ``%s''" % changedesc for line in changedesc.split("\n"): print ">> `%s'" % line if line == "Description:": process_summary = True continue elif line == "Files:": process_files = True continue elif line == "" or line == "\t": if process_summary: process_summary = False process_description = True continue line = "" elif line.startswith("\t"): line = line[1:] if process_files: files.append(line) elif line.find(':') != -1: key, value = line.split(':', 2) if changedesc_keys.has_key(key): process_description = False cur_key = key changedesc_keys[key] = value.lstrip() + "\n" continue line += "\n" if process_summary: summary += line elif process_description: description += line elif cur_key != None: changedesc_keys[cur_key] += line result_dict['summary'] = summary result_dict['description'] = description result_dict['testing_done'] = changedesc_keys['Testing Done'] # TODO: Normalize bug number result_dict['bugs_closed'] = changedesc_keys['Bug Number'] # This is gross. if len(files) > 0: parts = files[0].split('/') if parts[2] == "depot": result_dict['branch'] = parts[4]
result_dict['bugs_closed'] = changedesc_keys['Bug Number']
result_dict['bugs_closed'] = \ ", ".join(re.split(r"[, ]+", changedesc_keys['Bug Number']))
def parse_change_desc(changedesc, result_dict): summary = "" description = "" files = [] changedesc_keys = { 'QA Notes': "", 'Testing Done': "", 'Documentation Notes': "", 'Bug Number': "", 'Reviewed by': "", 'Approved by': "", 'Breaks vmcore compatibility': "", 'Breaks vmkernel compatibility': "", 'Breaks vmkdrivers compatibility': "", 'Mailto': "", } process_summary = False process_description = False process_files = False cur_key = None print "change desc: ``%s''" % changedesc for line in changedesc.split("\n"): print ">> `%s'" % line if line == "Description:": process_summary = True continue elif line == "Files:": process_files = True continue elif line == "" or line == "\t": if process_summary: process_summary = False process_description = True continue line = "" elif line.startswith("\t"): line = line[1:] if process_files: files.append(line) elif line.find(':') != -1: key, value = line.split(':', 2) if changedesc_keys.has_key(key): process_description = False cur_key = key changedesc_keys[key] = value.lstrip() + "\n" continue line += "\n" if process_summary: summary += line elif process_description: description += line elif cur_key != None: changedesc_keys[cur_key] += line result_dict['summary'] = summary result_dict['description'] = description result_dict['testing_done'] = changedesc_keys['Testing Done'] # TODO: Normalize bug number result_dict['bugs_closed'] = changedesc_keys['Bug Number'] # This is gross. if len(files) > 0: parts = files[0].split('/') if parts[2] == "depot": result_dict['branch'] = parts[4]
Bug Number: 456123\n\
Bug Number: 456123, 12873 1298371\n\
def new_review_request(request, template_name='reviews/new.html', changenum_path='changenum'): changedesc = "\
return self.bugs_closed.split(',')
bugs = self.bugs_closed.split(',') bugs.sort(cmp=lambda x,y: int(x) - int(y)) return bugs
def get_bug_list(self): return self.bugs_closed.split(',')
", ".join(re.split(r"[, ]+", changedesc_keys['Bug Number']))
", ".join(re.split(r"[, ]+", changedesc_keys['Bug Number'])).strip()
def parse_change_desc(changedesc, result_dict): summary = "" description = "" files = [] changedesc_keys = { 'QA Notes': "", 'Testing Done': "", 'Documentation Notes': "", 'Bug Number': "", 'Reviewed by': "", 'Approved by': "", 'Breaks vmcore compatibility': "", 'Breaks vmkernel compatibility': "", 'Breaks vmkdrivers compatibility': "", 'Mailto': "", } process_summary = False process_description = False process_files = False cur_key = None for line in changedesc.split("\n"): if line == "Description:": process_summary = True continue elif line == "Files:": process_files = True continue elif line == "" or line == "\t": if process_summary: process_summary = False process_description = True continue line = "" elif line.startswith("\t"): line = line[1:] if process_files: files.append(line) elif line.find(':') != -1: key, value = line.split(':', 2) if changedesc_keys.has_key(key): process_description = False cur_key = key changedesc_keys[key] = value.lstrip() + "\n" continue line += "\n" if process_summary: summary += line elif process_description: description += line elif cur_key != None: changedesc_keys[cur_key] += line result_dict['summary'] = summary result_dict['description'] = description result_dict['testing_done'] = changedesc_keys['Testing Done'] result_dict['bugs_closed'] = \ ", ".join(re.split(r"[, ]+", changedesc_keys['Bug Number'])) # This is gross. if len(files) > 0: parts = files[0].split('/') if parts[2] == "depot": result_dict['branch'] = parts[4]
changenum = request.POST['changenum'] if changenum:
if request.POST.has_key('changenum'): changenum = request.POST['changenum']
def new_review_request(request, template_name='reviews/new.html', changenum_path='changenum'): changedesc = "\
self.assertEquals(r.toString(), "SIP/2.0 200 OK\r\nFoo: bar\r\nContent-length: 4\r\n\r\n1234")
self.assertEquals(r.toString(), "SIP/2.0 200 OK\r\nFoo: bar\r\nContent-Length: 4\r\n\r\n1234")
def testResponse(self): r = sip.Response(200, "OK") r.addHeader("foo", "bar") r.addHeader("Content-Length", "4") r.bodyDataReceived("1234") self.assertEquals(r.toString(), "SIP/2.0 200 OK\r\nFoo: bar\r\nContent-length: 4\r\n\r\n1234")
Content-length: 0\r
Content-Length: 0\r
def testRegister(self): p = self.clientPort.getHost().port r = sip.Request("REGISTER", "sip:proxy.com") r.addHeader("to", "sip:[email protected]") r.addHeader("from", "sip:[email protected]") r.addHeader("contact", "sip:[email protected]:%d" % p) r.addHeader("call-id", "[email protected]") r.addHeader("CSeq", "25317 REGISTER") r.addHeader("via", sip.Via("127.0.0.1", port=p).toString()) self.clientTransport.sendRequest(r, ("127.0.0.1", self.serverPortNo)) while not len(self.client.received): reactor.iterate() self.assertEquals(len(self.client.received), 1) r = self.client.received[0] self.assertEquals(r.code, 200)
la = avatar.parent.findFirst(userbase.LoginAccount, avatars=avatar.parent.getItemByID(avatar.idInParent))
la = avatar.parent.findFirst( userbase.LoginAccount, userbase.LoginAccount.avatars == avatar.parent.getItemByID(avatar.idInParent))
def endow(self, ticket, avatar): self.endowed += 1 la = avatar.parent.findFirst(userbase.LoginAccount, avatars=avatar.parent.getItemByID(avatar.idInParent))
return [webnav.Tab('Voice', self.storeID, 0.0)]
return [webnav.Tab('Voice', self.storeID, 0.75)]
def getTabs(self): return [webnav.Tab('Voice', self.storeID, 0.0)]
self.__setBackground(bgParent)
if (self.pageCount!=-1): self.__setBackground(bgParent)
def __handlePage(self,parent,bgParent): self.__setBackground(bgParent) #set the background for this page self.pageCount=self.pageCount+1 objElem=self.document.createElement("OBJECT") #KPresenter text object objElem.setAttribute("type", "4")
paperElem.setAttribute("ptWidth", "680")
paperElem.setAttribute("ptWidth", str(PAGE_WIDTH))
def __setPaper(self,parent): paperElem=self.document.createElement("PAPER") paperElem.setAttribute("ptWidth", "680") paperElem.setAttribute("ptHeight", str(Y_OFFSET)) paperElem.setAttribute("orientation", "0") #landscape paperElem.setAttribute("format", "5") #screen paperElem.setAttribute("unit", "0") #mm
self.assert_( self.pluginobject1 )
def setUp(self): import krosstestpluginmodule self.pluginobject1 = krosstestpluginmodule.testpluginobject1() self.pluginobject2 = krosstestpluginmodule.testpluginobject2() self.assert_( self.pluginobject1 ) self.assert_( self.pluginobject2 )
print "__name = %s" % __name__
print "__name__ = %s" % __name__
#def testExpectedFailures(self): # to less arguments #self.assertRaises(ValueError, self.pluginobject1.uintfunc) #self.assert_( self.pluginobject1.uintfunc() != 8465 )
self.setCaption("Actions")
self.setCaption("Script Editor")
def __init__(self, scriptpath, parent): self.scriptpath = scriptpath self.filename = self.getFileName("myscript.py")
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount):
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount, round=True):
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount): if to_currency_id==from_currency_id: return from_amount [from_currency]=self.read(cr, uid, [from_currency_id]) [to_currency] = self.read(cr, uid, [to_currency_id]) if from_currency['rate'] == 0 or to_currency['rate'] == 0: raise osv.except_osv('Error', 'No rate found for the currency') return self.round(cr, uid, to_currency, from_amount * from_currency['rate']/to_currency['rate'])
[from_currency]=self.read(cr, uid, [from_currency_id]) [to_currency] = self.read(cr, uid, [to_currency_id])
from_currency=self.browse(cr, uid, [from_currency_id])[0] to_currency = self.browse(cr, uid, [to_currency_id])[0]
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount): if to_currency_id==from_currency_id: return from_amount [from_currency]=self.read(cr, uid, [from_currency_id]) [to_currency] = self.read(cr, uid, [to_currency_id]) if from_currency['rate'] == 0 or to_currency['rate'] == 0: raise osv.except_osv('Error', 'No rate found for the currency') return self.round(cr, uid, to_currency, from_amount * from_currency['rate']/to_currency['rate'])
return self.round(cr, uid, to_currency, from_amount * from_currency['rate']/to_currency['rate'])
if round: return self.round(cr, uid, to_currency, from_amount * from_currency.rate/to_currency.rate) else: return (from_amount * from_currency.rate/to_currency.rate)
def compute(self, cr, uid, from_currency_id, to_currency_id, from_amount): if to_currency_id==from_currency_id: return from_amount [from_currency]=self.read(cr, uid, [from_currency_id]) [to_currency] = self.read(cr, uid, [to_currency_id]) if from_currency['rate'] == 0 or to_currency['rate'] == 0: raise osv.except_osv('Error', 'No rate found for the currency') return self.round(cr, uid, to_currency, from_amount * from_currency['rate']/to_currency['rate'])
obj_pool = {} module_object_list = {}
def __init__(self, name, value, exc_type='warning'): self.name = name self.exc_type = exc_type self.value = value self.args = (exc_type,name)
print 'INDENT'
def _tag_menuitem(self, cr, rec, data_node=None): rec_id = rec.getAttribute("id").encode('ascii') m_l = map(escape, escape_re.split(rec.getAttribute("name").encode('utf8'))) pid = False for idx, menu_elem in enumerate(m_l): if pid: cr.execute('select id from ir_ui_menu where parent_id=%d and name=%s', (pid, menu_elem)) else: cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,)) res = cr.fetchone() if idx==len(m_l)-1: # we are at the last menu element/level (it's a leaf) values = {'parent_id': pid,'name':menu_elem}
print 'FILL'
def _tag_menuitem(self, cr, rec, data_node=None): rec_id = rec.getAttribute("id").encode('ascii') m_l = map(escape, escape_re.split(rec.getAttribute("name").encode('utf8'))) pid = False for idx, menu_elem in enumerate(m_l): if pid: cr.execute('select id from ir_ui_menu where parent_id=%d and name=%s', (pid, menu_elem)) else: cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,)) res = cr.fetchone() if idx==len(m_l)-1: # we are at the last menu element/level (it's a leaf) values = {'parent_id': pid,'name':menu_elem}
print 'COLOR'
def _tag_menuitem(self, cr, rec, data_node=None): rec_id = rec.getAttribute("id").encode('ascii') m_l = map(escape, escape_re.split(rec.getAttribute("name").encode('utf8'))) pid = False for idx, menu_elem in enumerate(m_l): if pid: cr.execute('select id from ir_ui_menu where parent_id=%d and name=%s', (pid, menu_elem)) else: cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,)) res = cr.fetchone() if idx==len(m_l)-1: # we are at the last menu element/level (it's a leaf) values = {'parent_id': pid,'name':menu_elem}
print values
def _tag_menuitem(self, cr, rec, data_node=None): rec_id = rec.getAttribute("id").encode('ascii') m_l = map(escape, escape_re.split(rec.getAttribute("name").encode('utf8'))) pid = False for idx, menu_elem in enumerate(m_l): if pid: cr.execute('select id from ir_ui_menu where parent_id=%d and name=%s', (pid, menu_elem)) else: cr.execute('select id from ir_ui_menu where parent_id is null and name=%s', (menu_elem,)) res = cr.fetchone() if idx==len(m_l)-1: # we are at the last menu element/level (it's a leaf) values = {'parent_id': pid,'name':menu_elem}
if not self.field_id:
if not self.field_id.get(cr.dbname):
def _field_get(self, self2, cr, uid, prop): if not self.field_id: cr.execute('select id from ir_model_fields where name=%s and model=%s', (prop, self2._name)) res = cr.fetchone() self.field_id = res and res[0] return self.field_id
self.field_id = res and res[0] return self.field_id
self.field_id[cr.dbname] = res and res[0] return self.field_id[cr.dbname]
def _field_get(self, self2, cr, uid, prop): if not self.field_id: cr.execute('select id from ir_model_fields where name=%s and model=%s', (prop, self2._name)) res = cr.fetchone() self.field_id = res and res[0] return self.field_id
q = """SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN a.atttypmod-4 ELSE a.attlen END as size FROM pg_class c,pg_attribute a,pg_type t WHERE c.relname='%s' AND a.attname='%s' AND c.oid=a.attrelid AND a.atttypid=t.oid""" % (self._table, k)
q = """SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN a.atttypmod-4 ELSE a.attlen END as size FROM pg_class c,pg_attribute a,pg_type t WHERE c.relname='%s' AND a.attname='%s' AND c.oid=a.attrelid AND a.atttypid=t.oid""" % (self._table, k.lower())
def _auto_init(self, cr):
break
continue
for state_name, state_def in obj.states.iteritems(): if 'result' in state_def: result = state_def['result'] if result['type'] != 'form': break
(opj('lib','python%s' % py_short_version, 'site-package', 'tinyerp-server', 'i18n'),
(opj('lib','python%s' % py_short_version, 'site-packagess', 'tinyerp-server', 'i18n'),
def data_files(): '''Build list of data files to be installed''' files = [(opj('share', 'man', 'man1'), ['man/tinyerp-server.1']), (opj('share', 'man', 'man5'), ['man/terp_serverrc.5']), (opj('share','doc', 'tinyerp-server-%s' % version), [f for f in glob.glob('doc/*') if os.path.isfile(f)]), (opj('lib','python%s' % py_short_version, 'site-package', 'tinyerp-server', 'i18n'), glob.glob('bin/i18n/*')), (opj('lib', 'python%s' % py_short_version, 'site-packages', 'tinyerp-server', 'addons', 'custom'), glob.glob('bin/addons/custom/*xml') + glob.glob('bin/addons/custom/*rml') + glob.glob('bin/addons/custom/*xsl'))] for addon in find_addons(): add_path = addon.replace('.', os.path.sep).replace('tinyerp-server', 'bin', 1) pathfiles = [(opj('lib', 'python%s' % py_short_version, 'site-packages', add_path.replace('bin', 'tinyerp-server', 1)), glob.glob(opj(add_path, '*xml')) + glob.glob(opj(add_path, '*csv')) + glob.glob(opj(add_path, '*sql'))), (opj('lib', 'python%s' % py_short_version, 'site-packages', add_path.replace('bin', 'tinyerp-server', 1), 'data'), glob.glob(opj(add_path, 'data', '*xml'))), (opj('lib', 'python%s' % py_short_version, 'site-packages', add_path.replace('bin', 'tinyerp-server', 1), 'report'), glob.glob(opj(add_path, 'report', '*xml')) + glob.glob(opj(add_path, 'report', '*rml')) + glob.glob(opj(add_path, 'report', '*xsl')))] files.extend(pathfiles) return files
sequence_semaphore = threading.Semaphore()
def _code_get(self, cr, uid, context={}): cr.execute('select code, name from ir_sequence_type') return cr.fetchall()
self.sequence_semaphore.acquire() cr.execute('select id,number_next,number_increment,prefix,suffix,padding from ir_sequence where '+test+' and active=True', (sequence_id,)) res = cr.dictfetchone() if res: cr.execute('update ir_sequence set number_next=number_next+number_increment where id=%d and active=True', (res['id'],)) self.sequence_semaphore.release() if res['number_next']: return self._process(res['prefix']) + '%%0%sd' % res['padding'] % res['number_next'] + self._process(res['suffix']) else: return self._process(res['prefix']) + self._process(res['suffix']) else: self.sequence_semaphore.release()
try: cr.execute('lock table ir_sequence') cr.execute('select id,number_next,number_increment,prefix,suffix,padding from ir_sequence where '+test+' and active=True', (sequence_id,)) res = cr.dictfetchone() if res: cr.execute('update ir_sequence set number_next=number_next+number_increment where id=%d and active=True', (res['id'],)) if res['number_next']: return self._process(res['prefix']) + '%%0%sd' % res['padding'] % res['number_next'] + self._process(res['suffix']) else: return self._process(res['prefix']) + self._process(res['suffix']) cr.commit() except: cr.rollback() return False
def get_id(self, cr, uid, sequence_id, test='id=%d'): self.sequence_semaphore.acquire() cr.execute('select id,number_next,number_increment,prefix,suffix,padding from ir_sequence where '+test+' and active=True', (sequence_id,)) res = cr.dictfetchone() if res: cr.execute('update ir_sequence set number_next=number_next+number_increment where id=%d and active=True', (res['id'],)) self.sequence_semaphore.release() if res['number_next']: return self._process(res['prefix']) + '%%0%sd' % res['padding'] % res['number_next'] + self._process(res['suffix']) else: return self._process(res['prefix']) + self._process(res['suffix']) else: self.sequence_semaphore.release() return False
def set(self, cr, uid, code, next_number): self.sequence_semaphore.acquire() cr.execute('update ir_sequence set number_next=%d where code=%s and active=True', (next_number, code,)) self.sequence_semaphore.release() return True
def get(self, cr, uid, code): return self.get_id(cr, uid, code, test='code=%s')
self.write(cr, uid, [module.id], {'state': newstate, 'demo':mdemo})
if module.state=='uninstalled': self.write(cr, uid, [module.id], {'state': newstate, 'demo':mdemo})
def state_change(self, cr, uid, ids, newstate, context={}, level=50): if level<1: raise 'Recursion error in modules dependencies !' demo = True for module in self.browse(cr, uid, ids): mdemo = True for dep in module.dependencies_id: ids2 = self.search(cr, uid, [('name','=',dep.name)]) mdemo = mdemo and self.state_change(cr, uid, ids2, newstate, context, level-1) if not module.dependencies_id: mdemo = module.demo self.write(cr, uid, [module.id], {'state': newstate, 'demo':mdemo}) demo = demo and mdemo return demo
ids_dest = []
demo = True
def state_change(self, cr, uid, ids, newstate, context={}, level=50): if level<1: raise 'Recursion error in modules dependencies !' ids_dest = [] for module in self.browse(cr, uid, ids): for dep in module.dependencies_id: ids2 = self.search(cr, uid, [('name','=',dep.name)]) for id in ids2: if (id not in ids_dest): ids_dest.append(id) if module.state=='uninstalled': self.write(cr, uid, [module.id], {'state': newstate}) if ids_dest: self.state_change(cr, uid, ids_dest, newstate, context, level-1)
for id in ids2: if (id not in ids_dest): ids_dest.append(id) if module.state=='uninstalled': self.write(cr, uid, [module.id], {'state': newstate}) if ids_dest: self.state_change(cr, uid, ids_dest, newstate, context, level-1) for module in self.browse(cr, uid, ids): if module.state!='installed': demo=True for dep in module.dependencies_id: ids2 = self.search(cr, uid, [('name', '=', dep.name)]) for module2 in self.browse(cr, uid, ids2): demo = demo and module2.demo self.write(cr, uid, [module.id], {'demo':demo}) return True
mdemo = mdemo and self.state_change(cr, uid, ids2, newstate, context, level-1) if not module.dependencies_id: mdemo = module.demo self.write(cr, uid, [module.id], {'state': newstate, 'demo':mdemo}) demo = demo and mdemo return demo
def state_change(self, cr, uid, ids, newstate, context={}, level=50): if level<1: raise 'Recursion error in modules dependencies !' ids_dest = [] for module in self.browse(cr, uid, ids): for dep in module.dependencies_id: ids2 = self.search(cr, uid, [('name','=',dep.name)]) for id in ids2: if (id not in ids_dest): ids_dest.append(id) if module.state=='uninstalled': self.write(cr, uid, [module.id], {'state': newstate}) if ids_dest: self.state_change(cr, uid, ids_dest, newstate, context, level-1)
self.write(cr, uid, ids, {'state': 'uninstalled'})
self.write(cr, uid, ids, {'state': 'uninstalled', 'demo':False})
def button_install_cancel(self, cr, uid, ids, context={}): self.write(cr, uid, ids, {'state': 'uninstalled'}) return True
'iban': fields.char('Account number', size=64),
'iban': fields.char('Account Number', size=64),
def gen_next_ref(self, cr, uid, ids): if len(ids) != 1: return True # compute the next number ref cr.execute("select ref from res_partner where ref is not null order by char_length(ref) desc, ref desc limit 1") res = cr.dictfetchall() ref = res and res[0]['ref'] or '0' try: nextref = int(ref)+1 except e: raise osv.except_osv('Warning', "Couldn't generate the next id because some partners have an alphabetic id !")
return interface.implementedBy(obj)
return iter(interface.implementedBy(obj)).next()
def _get_interface(self, obj): try: if issubclass(obj, interface.Interface): return obj except: pass if callable(obj): return interface.implementedBy(obj) else: return interface.providedBy(obj)
return interface.providedBy(obj)
return iter(interface.providedBy(obj)).next()
def _get_interface(self, obj): try: if issubclass(obj, interface.Interface): return obj except: pass if callable(obj): return interface.implementedBy(obj) else: return interface.providedBy(obj)
cmd=['ssh','-oPreferredAuthentications=keyboard-interactive,password','-oNoHostAuthenticationForLocalhost=yes','-F/dev/null'] cmd+=['-l',login,'localhost']
cmd=['ssh'] cmd+=['-oPreferredAuthentications=keyboard-interactive,password'] cmd+=['-oNoHostAuthenticationForLocalhost=yes'] cmd+=['-oLogLevel=FATAL'] cmd+=['-F/dev/null','-l',login,'localhost']
def create(self,w=80,h=25): pid,fd=pty.fork() if pid==0: try: fdl=[int(i) for i in os.listdir('/proc/self/fd')] except OSError: fdl=range(256) for i in [i for i in fdl if i>2]: try: os.close(i) except OSError: pass if self.cmd: cmd=['/bin/sh','-c',self.cmd] elif os.getuid()==0: cmd=['/bin/login'] else: sys.stdout.write("Login: ") login=sys.stdin.readline().strip() if re.match('^[0-9A-Za-z-_.]+$',login): cmd=['ssh','-oPreferredAuthentications=keyboard-interactive,password','-oNoHostAuthenticationForLocalhost=yes','-F/dev/null'] cmd+=['-l',login,'localhost'] else: os._exit(0) env={} env["COLUMNS"]=str(w) env["LINES"]=str(h) env["TERM"]="linux" env["PATH"]=os.environ['PATH'] os.execvpe(cmd[0],cmd,env) else: fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK) # python bug http://python.org/sf/1112949 on amd64 fcntl.ioctl(fd, struct.unpack('i',struct.pack('I',termios.TIOCSWINSZ))[0], struct.pack("HHHH",h,w,0,0)) self.proc[fd]={'pid':pid,'term':Terminal(w,h),'buf':'','time':time.time()} return fd
sys.stdin = open('/dev/null', 'r') sys.stdout = open('/dev/null', 'w') sys.stderr = open('/dev/null', 'w')
nullin = file('/dev/null', 'r') nullout = file('/dev/null', 'w') os.dup2(nullin.fileno(), sys.stdin.fileno()) os.dup2(nullout.fileno(), sys.stdout.fileno()) os.dup2(nullout.fileno(), sys.stderr.fileno()) if os.getuid()==0 and o.uid: try: os.setuid(int(o.uid)) except: os.setuid(pwd.getpwnam(o.uid).pw_uid)
def main(): parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)") parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)") parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)") parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background") parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)") (o, a) = parser.parse_args() if o.daemon: pid=os.fork() if pid == 0: #os.setsid() ? os.setpgrp() sys.stdin = open('/dev/null', 'r') sys.stdout = open('/dev/null', 'w') sys.stderr = open('/dev/null', 'w') else: pid_file = '/var/run/ajaxterm.pid' try: open(pid_file,'w+').write(str(pid)+'\n') except: print 'Cannot store pid in %s' % pid_file print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid) sys.exit(0) else: print 'AjaxTerm at http://localhost:%s/' % o.port at=AjaxTerm(o.cmd,o.index_file)
pid_file = '/var/run/ajaxterm.pid'
def main(): parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)") parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)") parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)") parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background") parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)") (o, a) = parser.parse_args() if o.daemon: pid=os.fork() if pid == 0: #os.setsid() ? os.setpgrp() sys.stdin = open('/dev/null', 'r') sys.stdout = open('/dev/null', 'w') sys.stderr = open('/dev/null', 'w') else: pid_file = '/var/run/ajaxterm.pid' try: open(pid_file,'w+').write(str(pid)+'\n') except: print 'Cannot store pid in %s' % pid_file print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid) sys.exit(0) else: print 'AjaxTerm at http://localhost:%s/' % o.port at=AjaxTerm(o.cmd,o.index_file)
open(pid_file,'w+').write(str(pid)+'\n')
file(o.pidfile,'w+').write(str(pid)+'\n')
def main(): parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)") parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)") parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)") parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background") parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)") (o, a) = parser.parse_args() if o.daemon: pid=os.fork() if pid == 0: #os.setsid() ? os.setpgrp() sys.stdin = open('/dev/null', 'r') sys.stdout = open('/dev/null', 'w') sys.stderr = open('/dev/null', 'w') else: pid_file = '/var/run/ajaxterm.pid' try: open(pid_file,'w+').write(str(pid)+'\n') except: print 'Cannot store pid in %s' % pid_file print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid) sys.exit(0) else: print 'AjaxTerm at http://localhost:%s/' % o.port at=AjaxTerm(o.cmd,o.index_file)
print 'Cannot store pid in %s' % pid_file
pass
def main(): parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)") parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)") parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)") parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background") parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)") (o, a) = parser.parse_args() if o.daemon: pid=os.fork() if pid == 0: #os.setsid() ? os.setpgrp() sys.stdin = open('/dev/null', 'r') sys.stdout = open('/dev/null', 'w') sys.stderr = open('/dev/null', 'w') else: pid_file = '/var/run/ajaxterm.pid' try: open(pid_file,'w+').write(str(pid)+'\n') except: print 'Cannot store pid in %s' % pid_file print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid) sys.exit(0) else: print 'AjaxTerm at http://localhost:%s/' % o.port at=AjaxTerm(o.cmd,o.index_file)
if (t-t0)>3600:
if (t-t0)>120:
def proc_kill(self,fd): if fd in self.proc: self.proc[fd]['time']=0 t=time.time() for i in self.proc.keys(): t0=self.proc[i]['time'] if (t-t0)>3600: try: os.close(i) os.kill(self.proc[i]['pid'],signal.SIGTERM) except (IOError,OSError): pass del self.proc[i]
if i==0:
if i==0 or i==39 or i==49 or i==27:
def csi_m(self,l): for i in l: if i==0: self.sgr=0x000700 elif i>=30 and i<=37: c=i-30 self.sgr=(self.sgr&0xff00ff)|(c<<8) elif i>=40 and i<=47: c=i-40 self.sgr=(self.sgr&0x00ffff)|(c<<16)
self.sgr=(self.sgr&0xff00ff)|(c<<8)
self.sgr=(self.sgr&0xff08ff)|(c<<8)
def csi_m(self,l): for i in l: if i==0: self.sgr=0x000700 elif i>=30 and i<=37: c=i-30 self.sgr=(self.sgr&0xff00ff)|(c<<8) elif i>=40 and i<=47: c=i-40 self.sgr=(self.sgr&0x00ffff)|(c<<16)
def dumphtml(self):
def dumphtml(self,color=1):
def dumphtml(self): h=self.height w=self.width r="" span="" span_bg=-1 span_fg=-1 for i in range(h*w): q,c=divmod(self.scr[i],256) bg,fg=divmod(q,256) if i==self.cy*w+self.cx: bg=1 fg=7 if (bg!=span_bg or fg!=span_fg or i==h*w-1): if len(span): r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml))) span="" span_bg=bg span_fg=fg span+=chr(c) if i%w==w-1: span+='\n' r='<?xml version="1.0" encoding="ISO-8859-1"?><pre class="term">%s</pre>'%r if self.last_html==r: return '<?xml version="1.0"?><idem></idem>' else: self.last_html=r
span_bg=-1 span_fg=-1
span_bg,span_fg=-1,-1
def dumphtml(self): h=self.height w=self.width r="" span="" span_bg=-1 span_fg=-1 for i in range(h*w): q,c=divmod(self.scr[i],256) bg,fg=divmod(q,256) if i==self.cy*w+self.cx: bg=1 fg=7 if (bg!=span_bg or fg!=span_fg or i==h*w-1): if len(span): r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml))) span="" span_bg=bg span_fg=fg span+=chr(c) if i%w==w-1: span+='\n' r='<?xml version="1.0" encoding="ISO-8859-1"?><pre class="term">%s</pre>'%r if self.last_html==r: return '<?xml version="1.0"?><idem></idem>' else: self.last_html=r
bg,fg=divmod(q,256)
if color: bg,fg=divmod(q,256) else: bg,fg=0,7
def dumphtml(self): h=self.height w=self.width r="" span="" span_bg=-1 span_fg=-1 for i in range(h*w): q,c=divmod(self.scr[i],256) bg,fg=divmod(q,256) if i==self.cy*w+self.cx: bg=1 fg=7 if (bg!=span_bg or fg!=span_fg or i==h*w-1): if len(span): r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml))) span="" span_bg=bg span_fg=fg span+=chr(c) if i%w==w-1: span+='\n' r='<?xml version="1.0" encoding="ISO-8859-1"?><pre class="term">%s</pre>'%r if self.last_html==r: return '<?xml version="1.0"?><idem></idem>' else: self.last_html=r
bg=1 fg=7
bg,fg=1,7
def dumphtml(self): h=self.height w=self.width r="" span="" span_bg=-1 span_fg=-1 for i in range(h*w): q,c=divmod(self.scr[i],256) bg,fg=divmod(q,256) if i==self.cy*w+self.cx: bg=1 fg=7 if (bg!=span_bg or fg!=span_fg or i==h*w-1): if len(span): r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml))) span="" span_bg=bg span_fg=fg span+=chr(c) if i%w==w-1: span+='\n' r='<?xml version="1.0" encoding="ISO-8859-1"?><pre class="term">%s</pre>'%r if self.last_html==r: return '<?xml version="1.0"?><idem></idem>' else: self.last_html=r
span_bg=bg span_fg=fg
span_bg,span_fg=bg,fg
def dumphtml(self): h=self.height w=self.width r="" span="" span_bg=-1 span_fg=-1 for i in range(h*w): q,c=divmod(self.scr[i],256) bg,fg=divmod(q,256) if i==self.cy*w+self.cx: bg=1 fg=7 if (bg!=span_bg or fg!=span_fg or i==h*w-1): if len(span): r+='<span class="f%d b%d">%s</span>'%(span_fg,span_bg,cgi.escape(span.translate(self.trhtml))) span="" span_bg=bg span_fg=fg span+=chr(c) if i%w==w-1: span+='\n' r='<?xml version="1.0" encoding="ISO-8859-1"?><pre class="term">%s</pre>'%r if self.last_html==r: return '<?xml version="1.0"?><idem></idem>' else: self.last_html=r
def dump(self,fd):
def dump(self,fd,color=1):
def dump(self,fd): try: return self.proc[fd]['term'].dumphtml() except KeyError: return False
return self.proc[fd]['term'].dumphtml()
return self.proc[fd]['term'].dumphtml(color)
def dump(self,fd): try: return self.proc[fd]['term'].dumphtml() except KeyError: return False
dump=self.multi.dump(term)
dump=self.multi.dump(term,c)
def __call__(self, environ, start_response): req = qweb.QWebRequest(environ, start_response,session=None) if req.PATH_INFO.endswith('/u'): s=req.REQUEST["s"] k=req.REQUEST["k"] if s in self.session: term=self.session[s] else: term=self.session[s]=self.multi.create() if k: self.multi.proc_write(term,k) time.sleep(0.002) dump=self.multi.dump(term) req.response_headers['Content-Type']='text/xml' if isinstance(dump,str): req.write(dump) req.response_gzencode=1 else: del self.session[s] req.write('<?xml version="1.0"?><idem></idem>')
fcntl.ioctl(fd, termios.TIOCSWINSZ , struct.pack("HHHH",h,w,0,0))
fcntl.ioctl(fd, struct.unpack('i',struct.pack('I',termios.TIOCSWINSZ))[0], struct.pack("HHHH",w,h,0,0))
def create(self,w=80,h=25): if self.cmd: cmd=['/bin/bash','-c',self.cmd] elif os.getuid()==0: cmd=['/bin/login'] else: cmd=['/usr/bin/ssh','-F/dev/null','-oPreferredAuthentications=password','-oNoHostAuthenticationForLocalhost=yes','localhost'] pid,fd=pty.fork() if pid==0: try: fdl=[int(i) for i in os.listdir('/proc/self/fd')] except OSError: fdl=range(256) for i in [i for i in fdl if i>2]: try: os.close(i) except OSError: pass env={} env["COLUMNS"]=str(w) env["LINES"]=str(h) env["TERM"]="linux" env["PATH"]=os.environ['PATH'] os.execve(cmd[0],cmd,env) else: fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK) fcntl.ioctl(fd, termios.TIOCSWINSZ , struct.pack("HHHH",h,w,0,0)) self.proc[fd]={'pid':pid,'term':Terminal(w,h),'buf':'','time':time.time()} return fd
self.zipentry[zi.filename]=Entry(zi.filename,"file",self.zipmtime,zi.file_size)
if not zi.filename.endswith('/'): self.zipentry[zi.filename]=Entry(zi.filename,"file",self.zipmtime,zi.file_size)
def __init__(self, urlroot="/", zipname="",ziproot="/", listdir=1): StaticBase.__init__(self,urlroot,listdir) self.zipfile=zipfile.ZipFile(zipname) self.zipmtime=os.path.getmtime(zipname) self.ziproot=path_clean(ziproot) self.zipdir={} self.zipentry={}
fs_path=os.path.join(self.ziproot,path)
fs_path=os.path.join(self.ziproot,path).strip('/')
def fs_stat(self,path): fs_path=os.path.join(self.ziproot,path) if fs_path in self.zipentry: return self.zipentry[fs_path] elif fs_path in self.zipdir: return Entry(path,"dir",self.zipmtime,0) else: return None
fs_path = self.ziproot[1:]+path
fs_path = os.path.join(self.ziproot,path).strip('/')
def fs_getfile(self,path): fs_path = self.ziproot[1:]+path return self.zipfile.read(fs_path)
fs_path = self.ziproot[1:]+path
fs_path = os.path.join(self.ziproot,path).strip('/')
def fs_listdir(self,path): fs_path = self.ziproot[1:]+path return self.zipdir[fs_path].values()
"\x1b[?1c": None, "\x1b[?0c": None,
"\x1b[c": self.esc_da, "\x1b[0c": self.esc_da,
def init(self): self.esc_seq={ "\x00": None, "\x05": self.esc_da, "\x07": None, "\x08": self.esc_0x08, "\x09": self.esc_0x09, "\x0a": self.esc_0x0a, "\x0b": self.esc_0x0a, "\x0c": self.esc_0x0a, "\x0d": self.esc_0x0d, "\x0e": None, "\x0f": None, "\x1b#8": None, "\x1b=": None, "\x1b>": None, "\x1b(0": None, "\x1b(A": None, "\x1b(B": None, "\x1b[?1c": None, "\x1b[?0c": None, "\x1b]R": None, "\x1b7": self.esc_save, "\x1b8": self.esc_restore, "\x1bD": None, "\x1bE": None, "\x1bH": None, "\x1bM": self.esc_ri, "\x1bN": None, "\x1bO": None, "\x1bZ": self.esc_da, "\x1ba": None, "\x1bc": self.reset, "\x1bn": None, "\x1bo": None, } for k,v in self.esc_seq.items(): if v==None: self.esc_seq[k]=self.esc_ignore # regex d={ r'\[\??([0-9;]*)([@ABCDEFGHJKLMPXacdefghlmnqrstu`])' : self.csi_dispatch, r'\]([^\x07]+)\x07' : self.esc_ignore, } self.esc_re=[] for k,v in d.items(): self.esc_re.append((re.compile('\x1b'+k),v)) # define csi sequences self.csi_seq={ '@': (self.csi_at,[1]), '`': (self.csi_G,[1]), 'J': (self.csi_J,[0]), 'K': (self.csi_K,[0]), } for i in [i[4] for i in dir(self) if i.startswith('csi_') and len(i)==5]: if not self.csi_seq.has_key(i): self.csi_seq[i]=(getattr(self,'csi_'+i),[1]) # Init 0-256 to latin1 and html translation table self.trl1="" for i in range(256): if i<32: self.trl1+=" " elif i<127 or i>160: self.trl1+=chr(i) else: self.trl1+="?" self.trhtml="" for i in range(256): if i==0x0a or (i>32 and i<127) or i>160: self.trhtml+=chr(i) elif i<=32: self.trhtml+="\xa0" else: self.trhtml+="?"
self.esc_da(0)
pass
def csi_c(self,l): self.esc_da(0)
print 'AjaxTerm serving at http://localhost:%s/'%o.port
def main(): parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)") parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)") parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)") parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background") parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)") (o, a) = parser.parse_args() print 'AjaxTerm serving at http://localhost:%s/'%o.port if o.daemon: pid=os.fork() if pid == 0: #os.setsid() ? os.setpgrp() sys.stdin = open('/dev/null', 'r') sys.stdout = open('/dev/null', 'w') sys.stderr = open('/dev/null', 'w') else: pid_file = '/var/run/ajaxterm.pid' try: open(pid_file,'w+').write(str(pid)+'\n') except: print 'Cannot store pid in %s' % pid_file print 'AjaxTerm running with pid: %d' % pid sys.exit(0) at=AjaxTerm(o.cmd,o.index_file)
print 'AjaxTerm running with pid: %d' % pid
print 'AjaxTerm at http://localhost:%s/ pid: %d' % (o.port,pid)
def main(): parser = optparse.OptionParser() parser.add_option("-p", "--port", dest="port", default="8022", help="Set the TCP port (default: 8022)") parser.add_option("-c", "--command", dest="cmd", default=None,help="set the command (default: /bin/login or ssh localhost)") parser.add_option("-l", "--log", action="store_true", dest="log",default=0,help="log requests to stderr (default: quiet mode)") parser.add_option("-d", "--daemon", action="store_true", dest="daemon", default=0, help="run as daemon in the background") parser.add_option("-i", "--index", dest="index_file", default="ajaxterm.html",help="default index file (default: ajaxterm.html)") (o, a) = parser.parse_args() print 'AjaxTerm serving at http://localhost:%s/'%o.port if o.daemon: pid=os.fork() if pid == 0: #os.setsid() ? os.setpgrp() sys.stdin = open('/dev/null', 'r') sys.stdout = open('/dev/null', 'w') sys.stderr = open('/dev/null', 'w') else: pid_file = '/var/run/ajaxterm.pid' try: open(pid_file,'w+').write(str(pid)+'\n') except: print 'Cannot store pid in %s' % pid_file print 'AjaxTerm running with pid: %d' % pid sys.exit(0) at=AjaxTerm(o.cmd,o.index_file)
compileRecipeDirs = os.popen("/bin/sh -c '. " +file+" 2> /dev/null; for i in ${compileRecipeDirs[@]}; do echo $i; done'").read().strip('\n').split() if compileRecipeDirs :
compileRecipeDirs = os.popen("/bin/sh -c '. " +file+" 2> /dev/null; for i in \"${compileRecipeDirs[@]}\"; do echo $i; done'").read().strip('\n').split('\n') if compileRecipeDirs and compileRecipeDirs[0] :
def getCompileOptions() : import os goboSettings = getGoboVariable('goboSettings') goboPrograms = getGoboVariable('goboPrograms') goboCompileDefaults = goboPrograms+'/Compile/Current/Resources/Defaults/Settings/' compileSettingsFiles = [ "~/.Settings/Compile/Compile.conf", goboSettings + "/Compile/Compile.conf", goboCompileDefaults+"/Compile/Compile.conf" ] try : compileRecipeDirs = os.environ['compileRecipeDirs'].strip('\n').split() except : for file in compileSettingsFiles : compileRecipeDirs = os.popen("/bin/sh -c '. " +file+" 2> /dev/null; for i in ${compileRecipeDirs[@]}; do echo $i; done'").read().strip('\n').split() if compileRecipeDirs : break try : getRecipeStores = os.environ['getRecipeStores'].strip('\n').split('\n') except : for file in compileSettingsFiles : getRecipeStores = os.popen("/bin/sh -c '. " + file +" 2> /dev/null; for i in ${getRecipeStores[@]}; do echo $i; done'").read().strip('\n').split() if getRecipeStores : break #import sys #sys.stderr.write(str(compileRecipeDirs)) #sys.stderr.write(str(getRecipeStores)) import os.path return (map(os.path.expanduser,compileRecipeDirs), getRecipeStores)