rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
public = private = key_reprs
public = key_reprs private = []
def _complete_dict_keys(self, text, index, hp, is_auto): """ Return (comp_prefix, public, private, is_case_insen) (string, list, list, bool). If shouldn't complete - return None. """ try: # Check whether auto-completion is really appropriate, # finding the index of the o pening bracket in the process. if is_auto: i...
rem_stdin.append(os.read(sys.stdin.fileno(), 8192))
r = os.read(sys.stdin.fileno(), 8192) if not r: break rem_stdin.append(r)
def execute(self, source): """ Get the source code to execute (a unicode string). Compile it. If there was a syntax error, return (False, (msg, line, col)). If compilation was successful, return (True, None), then run the code and then send (is_success, res_no, res_str, exception_string, rem_stdin). is_success - True i...
return abspath(join(sys.prefix, 'share'))
return abspath(join(dirname(sys.argv[0]), pardir, 'share'))
def find_data_dir(): # If there's a "share" directory near the "dreampielib" directory, use it. # Otherwise, use sys.prefix from os.path import join, dirname, isdir, pardir, abspath local_data_dir = join(dirname(__file__), pardir, pardir, 'share') if isdir(local_data_dir): return abspath(local_data_dir) else: return a...
exception_string = efile.getvalue()
exception_string = unicode(efile.getvalue())
def execute(self, source): """ Get the source code to execute (a unicode string). Compile it. If there was a syntax error, return (False, (msg, line, col)). If compilation was successful, return (True, None), then run the code and then send (is_success, res_no, res_str, exception_string, rem_stdin). is_success - True i...
return False, (unicode(e.msg), e.lineno-1, e.offset-1)
lineno = e.lineno if e.lineno is not None else 1 offset = e.offset if e.offset is not None else 1 return False, (unicode(e.msg), lineno-1, offset-1)
def compile_ast(self, source): """ Compile source into a list of code objects, updating linecache, self.gid and self.flags. Return True, codeob on success. Return False, reason on syntax error. This version uses the ast module available in Python 2.6 and Jython 2.5. This version always returns a list with one item. """...
return False, (unicode(e.msg), e.lineno-1+line_count, e.offset-1)
lineno = e.lineno if e.lineno is not None else 1 offset = e.offset if e.offset is not None else 1 return False, (unicode(e.msg), lineno-1+line_count, offset-1)
def compile_no_ast(self, source): """ This function does the same thing as compile_ast, but it works without the ast module. """ split_source = split_to_singles(source) # This added newline is because sometimes the CommandCompiler wants # more if there isn't a newline at the end split_source[-1] += '\n' line_count = 0 ...
if ' import ' not in line:
if len((line+'x').split()) == 3: res = self._complete_import(line) elif ' import ' not in line:
def show_completions(self, is_auto, complete): """ If complete is False, just show the comopletion list. If complete is True, complete as far as possible. If there's only one completion, don't show the window.
it.forward_to_tag_toggle(self.fold_message_tag) assert it.ends_tag(self.fold_message_tag)
it2.forward_to_tag_toggle(self.fold_message_tag) assert it2.ends_tag(self.fold_message_tag)
def unfold(self, typ, start_it): """ Get an iterator pointing to the beginning of an unfolded OUTPUT/COMMAND section. Unfold it. """ tb = self.textbuffer last_unfolded_it = tb.get_iter_at_mark(self.last_unfolded_mark) if start_it.compare(last_unfolded_it) > 0: tb.move_mark(self.last_unfolded_mark, start_it) it = star...
output_start.backward_to_tag_toggle(OUTPUT) assert output_start.begins_tag(OUTPUT) _before_newline, after_newline = it.backward_search( '\n', 0, output_start)
output_tag = tb.get_tag_table().lookup(OUTPUT) output_start.backward_to_tag_toggle(output_tag) assert output_start.begins_tag(output_tag) r = it.backward_search('\n', 0, output_start) if r is not None: _before_newline, after_newline = r else: after_newline = output_start
def write(self, data, tag_names, onnewline=False, addbreaks=True): """ Write data (unicode string) to the text buffer, marked with tag_names. (tag_names can be either a string or a list of strings) If onnewline is True, will add a newline if the output until now doesn't end with one. If addbreaks is True, '\r' chars wi...
is_dir = os.path.isdir(os.path.join(comp_what, name))
is_dir = os.path.isdir(os.path.join(comp_what, orig_name))
def complete_filenames(self, str_prefix, text, str_char): is_raw = 'r' in str_prefix.lower() is_unicode = 'u' in str_prefix.lower() try: # We add a space because a backslash can't be the last # char of a raw string literal comp_what = eval(str_prefix + text + ' ' + str_char)[:-1] except SyntaxError: return if comp_what...
for typ, _s, (srow, _scol), (_erow, _rcol), line in tokens_iter:
for typ, s, (srow, _scol), (_erow, _rcol), line in tokens_iter:
def split_to_singles(source): """Get a source string, and split it into several strings, each one a "single block" which can be compiled in the "single" mode. Every string which is not the last one ends with a '\n', so to convert a line number of a sub-string to a line number of the big string, add the number of '\n' c...
first_lines.append(srow)
if not had_decorator: first_lines.append(srow) else: had_decorator = False elif s == '@' and cur_indent_level == 0: had_decorator = True
def split_to_singles(source): """Get a source string, and split it into several strings, each one a "single block" which can be compiled in the "single" mode. Every string which is not the last one ends with a '\n', so to convert a line number of a sub-string to a line number of the big string, add the number of '\n' c...
"""]
@dec def f(): pass """,""" if 1: pass @dec def f(): pass """,""" class Class: @dec def method(): pass def f(): pass """ ]
def g(): a = 4
@keyhandler('Tab', 0)
def on_page_down(self): # Select the row displayed at bottom, or, if it is displayed, scroll one # page and then display the row. tv = self.treeview sel = tv.get_selection() last_row = len(self.liststore) - 1 r = tv.get_path_at_pos(0, tv.get_size_request()[1]) if r is not None: row = r[0][0] else: # nothing is displaye...
exception_string = unicode(efile.getvalue())
exception_string = efile.getvalue() if not isinstance(exception_string, unicode): exception_string = exception_string.decode('utf8', 'replace')
def execute(self, source): """ Get the source code to execute (a unicode string). Compile it. If there was a syntax error, return (False, (msg, line, col)). If compilation was successful, return (True, None), then run the code and then send (is_success, res_no, res_str, exception_string, rem_stdin). is_success - True i...
args.append(pyexec)
args.append('"%s"' % pyexec)
def create_shortcut(ws, dp_folder, ver_name, pyexec): """ Create a shortcut. ws should be a Shell COM object. dp_folder should be the folder where the shortcuts are created. If ver_name is None, the shortcut will be "DreamPie" instead of "DreamPie ({ver_name})". If pyexec is None, will start dreampie.exe with no argume...
source = source.replace(u'\xa8', '"').replace(u'\xb4', "'")
source = self.replace_gtk_quotes(source)
def execute_source(self): """Execute the source in the source buffer. """ sb = self.sourcebuffer source = self.sb_get_text(sb.get_start_iter(), sb.get_end_iter()) source = source.rstrip() # Work around GTK+ bug https://bugzilla.gnome.org/show_bug.cgi?id=610928 # in order to fix bug #525469 - replace fancy quotes with r...
obj = recv_object(self._sock) self._on_object_recv(obj)
try: obj = recv_object(self._sock) except IOError: time.sleep(1) if popen.poll() is None: raise else: self._on_object_recv(obj)
def _manage_subp(self): popen = self._popen if popen is None: # Just continue looping - there's no subprocess. return True
py2exe_data_dir = abspath(join(dirname(sys.argv[0]), 'share')) if isdir(join(py2exe_data_dir, 'dreampie')): return py2exe_data_dir else: unix_data_dir = abspath(join(dirname(sys.argv[0]), pardir, 'share')) if isdir(join(unix_data_dir, 'dreampie')): return unix_data_dir else: raise OSError("Could not find the 'share' di...
alternatives = [ join(dirname(sys.argv[0]), 'share'), join(dirname(sys.argv[0]), pardir, 'share'), '/usr/share', ] for dir in alternatives: absdir = abspath(dir) if isdir(join(absdir, 'dreampie')): return absdir else: raise OSError("Could not find the 'share' directory")
def find_data_dir(): """ Find the 'share' directory in which to find files. If we are inside the source directory, build subp zips. """ # Scenarios: # * Running from the source directory. 'share' is near 'dreampielib' # * Running from a unix installed executable. The scheme is: # prefix/bin/executable # prefix/shar...
@staticmethod def _find_constructor(class_ob):
@classmethod def _find_constructor(cls, class_ob):
def get_welcome(self): name = 'Python' if not sys.platform.startswith('java') else 'Jython' return (u'%s %s on %s\n' % (name, sys.version, sys.platform) +u'Type "copyright", "credits" or "license()" for more information.\n')
rc = _find_constructor(base)
rc = cls._find_constructor(base)
def _find_constructor(class_ob): # Given a class object, return a function object used for the # constructor (ie, __init__() ) or None if we can't find one. try: return class_ob.__init__.im_func except AttributeError: for base in class_ob.__bases__: rc = _find_constructor(base) if rc is not None: return rc return None
def handle_events(delay):
def handle_events(self, delay):
def handle_events(delay): """ This method gets the time in which to process GUI events, in seconds. If the GUI toolkit is loaded, run it for the specified delay and return True. If it isn't loaded, return False immediately. """ raise NotImplementedError("Abstract method")
self.window.modify_bg(0, gdk.color_parse('
self.window.modify_bg(gtk.STATE_NORMAL, style.bg[gtk.STATE_NORMAL])
def and_maybe_beep(): if not is_auto: beep() return None
if line.startswith(('import ', 'from ')):
if line.startswith(('import ', 'from ', 'except ')):
def add_parens(self): """ This is called if the user pressed space on the sourceview, and the subprocess is not executing commands (so is_callable_only can work.) Should return True if event-handling should stop, or False if it should continue as usual. Should be called only when is_callable_only can be called safely....
msg = e.msg if not isinstance(msg, unicode): msg = msg.decode('utf8', 'replace')
msg = unicodify(e.msg)
def compile_no_ast(self, source): """ This function does the same thing as compile_ast, but it works without the ast module. """ split_source = split_to_singles(source) # This added newline is because sometimes the CommandCompiler wants # more if there isn't a newline at the end split_source[-1] += '\n' line_count = 0 ...
exception_string = efile.getvalue() if not isinstance(exception_string, unicode): exception_string = exception_string.decode('utf8', 'replace')
exception_string = u''.join(unicodify(s) for s in efile.buflist)
def execute(self, source): """ Get the source code to execute (a unicode string). Compile it. If there was a syntax error, return (False, (msg, line, col)). If compilation was successful, return (True, None), then run the code and then send (is_success, res_no, res_str, exception_string, rem_stdin). is_success - True i...
color = str(self.fg_cbut.props.color)
color = self._format_color(self.fg_cbut.props.color)
def on_fg_cbut_color_set(self, _widget): if self.cur_tag: color = str(self.fg_cbut.props.color) self.cur_theme[self.cur_tag, FG, COLOR] = color self.theme_changed()
color = str(self.bg_cbut.props.color)
color = self._format_color(self.bg_cbut.props.color)
def on_bg_cbut_color_set(self, _widget): if self.cur_tag: color = str(self.bg_cbut.props.color) self.cur_theme[self.cur_tag, BG, COLOR] = color self.theme_changed()
lines = src.split("\n")
lines = [x+'\n' for x in src.split("\n")]
def compile_no_ast(self, source): """ This function does the same thing as compile_ast, but it works without the ast module. """ split_source = split_to_singles(source) # This added newline is because sometimes the CommandCompiler wants # more if there isn't a newline at the end split_source[-1] += '\n' line_count = 0 ...
return unicodify(inspect.cleandoc('\n'+source))
cleandoc = getattr(inspect, 'cleandoc', lambda s: s) return unicodify(cleandoc('\n'+source))
def get_func_doc(self, expr): """Get a string describing the arguments for the given object""" try: obj = eval(expr, self.locs) except Exception: return None if isinstance(obj, (types.BuiltinFunctionType, types.BuiltinMethodType)): # These don't have source code, and using pydoc will only # add something like "execfile...
return unicodify(inspect.getdoc(obj))
doc = inspect.getdoc(obj) if doc is None: return None return unicodify(doc) co_consts = getattr(getattr(obj, 'func_code', None), 'co_consts', None) __doc__ = getattr(obj, '__doc__', None) if co_consts is not None and __doc__ is not None: if __doc__ not in co_consts: return unicodify(textdoc.document(obj).strip())
def get_func_doc(self, expr): """Get a string describing the arguments for the given object""" try: obj = eval(expr, self.locs) except Exception: return None if isinstance(obj, (types.BuiltinFunctionType, types.BuiltinMethodType)): # These don't have source code, and using pydoc will only # add something like "execfile...
def allowed(self, object, obect_roles=None):
def allowed(self, object, object_roles=None):
def allowed(self, object, obect_roles=None): return 0
def doChangeUser(login, password, **kw):
def doChangeUser(user_id, password, **kw):
def doChangeUser(login, password, **kw): """ Change a user's password (differs from role) roles are set in the pas engine api for the same but are set via a role manager) """
group_id = self._verifyGroup(plugins, group_id=group_id)
def getGroupById(self, group_id, default=None): plugins = self._getPAS()._getOb('plugins')
if not group_id:
if group_id not in self.getGroupIds():
def getGroupById(self, group_id, default=None): plugins = self._getPAS()._getOb('plugins')
testvalue=safe_unicode(testvalue.lower())
testvalue=testvalue.lower()
def testMemberData(self, memberdata, criteria, exact_match=False): """Test if a memberdata matches the search criteria. """ for (key, value) in criteria.items(): testvalue=memberdata.get(key, None) if testvalue is None: return False
value=safe_unicode(value.lower())
value=value.lower()
def testMemberData(self, memberdata, criteria, exact_match=False): """Test if a memberdata matches the search criteria. """ for (key, value) in criteria.items(): testvalue=memberdata.get(key, None) if testvalue is None: return False
return a.get(key, "").lower()
return normalizeString(a.get(key, "").lower())
def key_func(a): return a.get(key, "").lower()
print "miss"
def create_cache_key(method, principal, plugins, request=None): wrapped = IAnnotations(request, None) if wrapped is None: print "miss" raise DontCache return (principal.getId(), )
testvalue=testvalue.lower()
testvalue=safe_unicode(testvalue.lower())
def testMemberData(self, memberdata, criteria, exact_match=False): """Test if a memberdata matches the search criteria. """ for (key, value) in criteria.items(): testvalue=memberdata.get(key, None) if testvalue is None: return False
value=value.lower()
value=safe_unicode(value.lower())
def testMemberData(self, memberdata, criteria, exact_match=False): """Test if a memberdata matches the search criteria. """ for (key, value) in criteria.items(): testvalue=memberdata.get(key, None) if testvalue is None: return False
kw['title'].setdefault('') kw['description'].setdefault('')
kw.setdefault('title','') kw.setdefault('description','')
def updateGroup(self, group_id, **kw): kw['title'].setdefault('') kw['description'].setdefault('') ZODBGroupManager.updateGroup(self, group_id, **kw) return True
return socket.gethostname()
h = socket.gethostname() m = re.match("(\.*[^\.]*)", h) assert m return m.group(1)
def gethostname(self): return socket.gethostname()
return self.so.recv(sz)
x = self.so.recv(sz) if 0: Es("work_stream_socket.readpkt(%d) -> %d\n" % (sz, len(x))) return x
def readpkt(self, sz): assert self.so is not None return self.so.recv(sz)
self.close()
def finish_work(self, work_idx, work, exit_status, term_sig, man_name): if exit_status is None: exit_status = "-" if term_sig is None: term_sig = "-" payload = "%d: %s %s %s\n" % (work_idx, exit_status, term_sig, man_name) msg = "%9d %s" % (len(payload), payload) if dbg>=2: Es("write notification [%s]\n" % msg) r = sel...
n_received = 0
n_received = self.server.receive_works(self, ws)
def accept_connection(self, ss): """ accept connection to receive works. create a new work_stream object out of the accepted connection. """ n_accepts,bidirectional = self.server_socks[ss] so,_ = ss.accept() if bidirectional: ws = work_stream_socket_bidirectional(self.server) else: ws = work_stream_socket(self.server) ...
return self.select_by_select(R, W, E, T)
return self.select_by_poll(R, W, E, T)
def select(self, R, W, E, T): return self.select_by_select(R, W, E, T)
"-- -l nodes=%target%")
"-- -l nodes=1:%target%:ppn=%ppn:-1%")
def __init__(self): # syntax of the following. # if the first character is non alphabetical, use # it as the separator (see ssh below, which uses :) # otherwise it uses whitespaces as the separator self.ssh = ("ssh -o StrictHostKeyChecking=no " "-o PreferredAuthentications=hostbased,publickey " "-A %target% %cm...
task = self.tasks[m.tid] task.forward_up(m, msg)
task = self.tasks.get(m.tid) if task: task.forward_up(m, msg) else: ioman.LOG("handle_msg %d bytes [%s ...] to non-existing task %s\n" \ % (len(msg), msg[0:30], m.tid))
def handle_msg(self, ch, msg): if dbg>=2: ioman.LOG("handle_msg %d bytes [%s ...]\n" \ % (len(msg), msg[0:30])) m = gxpm.parse(msg) if isinstance(m, gxpm.up): task = self.tasks[m.tid] task.forward_up(m, msg) elif isinstance(m, gxpm.syn): self.handle_syn(ch, m) elif isinstance(m, gxpm.down): task = self.register_task(m....
"work_file", "work_fd", "work_py_module", "work_server_sock", "work_proc_pipe", "work_proc_pipe2", "work_proc_sock",
"work_file", "work_fd", "work_py_module", "work_proc_pipe", "work_proc_pipe2", "work_proc_sock", "work_proc_sock2", "work_server_sock", "work_server_sock2", "work_db_type",
def token_val(self, s): """ convert a string s into an 'appropriate' python object. if it looks like an int or a float, it returns the converted number. if it looks like 1M 1.5G, etc., it returns the appropriate number. otherwise it returns the string. """ i = self.safe_atoi(s) if i is not None: return i f = self.safe_...
return run.time_start
return -run.time_start
def run_started_order_by_rev_time_start(self, run): return run.time_start
results.insert(0, (w, r))
results.append((w, r))
def list_such_runs(self, such): """ such : "long", "failed", "recent" """ # assume commit was just called runs,sort_key = self.such_runs[such] h = runs[:] # make a copy of the heap for w in self.works: for r in self.work_runs[w.work_idx]: k = sort_key(r) if k is not None: self.push_with_limit(h, (k, w, r), ...
return work_db_naive_mem(conf)
db_type = conf.work_db_type class_name = "work_db_%s" % db_type g = globals() if g.has_key(class_name): cls = g[class_name] else: Es("no such work_db_type %s, defaults to text\n" % db_type) cls = work_db_text return cls(conf)
def mk_work_db(conf): return work_db_naive_mem(conf)
"--rsh", "%(cmd)s", "--first_args_template", "--remove_self", "--first_args_template", "--continue_after_close", "--first_args_template", "--name_prefix", "--first_args_template", prefix, "--second_args_template", "--remove_self", "--second_args_template", "--continue_after_close", "--second_args_template", "--remo...
"--rsh", "%(cmd)s" ] tpx = self.opts.target_prefix if tpx is not None: argv = argv + [ "--target_prefix", tpx ] argv = argv + [ "--first_args_template", "--remove_self", "--first_args_template", "--continue_after_close", "--first_args_template", "--name_prefix", "--first_args_template", prefix, "--second_args_te...
def really_create_daemon(self): """ really create daemon """ prefix = self.generate_prefix() pid = os.fork() if pid == 0: gxp_dir = self.get_gxp_dir() inst_local_py = os.path.join(gxp_dir, "inst_local.py") os.setpgrp() # os.close(0) argv = [ sys.executable, inst_local_py, "--dont_wait", "--seq", "explore-root-gxpd", "-...
self.work_py = []
self.work_py_module = []
def __init__(self, opts): self.opts = opts self.work_file = [] # list of strings self.work_fd = [] # list of ints self.work_py = [] # list of strings self.work_server_sock = [] self.work_proc_pipe = [] self.work_proc_pipe2 = [] self.work_proc_sock = [] self.worker_prof_cmd = "${GXP_DIR}/gxpbin/worker_pr...
payload = "%d: %s %s\n" % (work_idx, exit_status, term_sig) msg = "%9d %s" % (len(payload), payload) return self.write_notification(msg) def write_notification(self, msg):
def finish_work(self, work_idx, work, exit_status, term_sig): payload = "%d: %s %s\n" % (work_idx, exit_status, term_sig) msg = "%9d %s" % (len(payload), payload) return self.write_notification(msg)
def __init__(self, server, fd): work_stream_base.__init__(self, server)
def init(self, fd):
def __init__(self, server, fd): work_stream_base.__init__(self, server) self.fd = fd
def finish_work(self, work_idx, work, exit_status, term_sig): pass
def finish_work(self, work_idx, work, exit_status, term_sig): pass
def __init__(self, server, rfd, wfd): work_stream_fd.__init__(self, server, rfd)
def init(self, rfd, wfd): work_stream_fd.init(self, rfd)
def __init__(self, server, rfd, wfd): work_stream_fd.__init__(self, server, rfd) self.wfd = wfd
def write_notification(self, msg): Es("got write notification [%s]\n" % msg)
return 0 def finish_work(self, work_idx, work, exit_status, term_sig): if exit_status is None: exit_status = "-" if term_sig is None: term_sig = "-" payload = "%d: %s %s\n" % (work_idx, exit_status, term_sig) msg = "%9d %s" % (len(payload), payload) if dbg>=2: Es("write notification to %d [%s]\n" % (self.wfd, msg))
def write_notification(self, msg): Es("got write notification [%s]\n" % msg) os.write(self.wfd, msg)
def __init__(self, server, filename): work_stream_base.__init__(self, server)
def init(self, filename):
def __init__(self, server, filename): work_stream_base.__init__(self, server) self.filename = filename self.fp = open(filename)
self.fp = open(filename)
try: self.fp = open(filename) return 0 except OSError,e: Es("error: could not open work_file %s %s\n" % (filename, e.args)) return -1
def __init__(self, server, filename): work_stream_base.__init__(self, server) self.filename = filename self.fp = open(filename)
def __init__(self, server, so): work_stream_base.__init__(self, server)
def init(self, so):
def __init__(self, server, so): work_stream_base.__init__(self, server) self.so = so
def write_notification(self, msg): if self.so: self.so.send(msg)
def finish_work(self, work_idx, work, exit_status, term_sig): if exit_status is None: exit_status = "-" if term_sig is None: term_sig = "-" payload = "%d: %s %s\n" % (work_idx, exit_status, term_sig) msg = "%9d %s" % (len(payload), payload) if dbg>=2: Es("write notification [%s]\n" % msg) self.so.send(msg)
def write_notification(self, msg): # FIXIT: when we close the socket? if self.so: self.so.send(msg)
def __init__(self, server, generator_module): work_stream_base.__init__(self, server) module_and_fun = generator_module.split(".", 1) if len(module_and_fun) == 1: [ module ] = module_and_fun fun = "gen_works" else: [ module,fun ] = module_and_fun mod = __import__(module, globals(), locals(), [], -1) f = getattr(mod, fu...
def init(self, generator_module): try: mod = __import__(generator_module, globals(), locals(), [], -1) except ImportError,e: Es("error: could not import module %s %s. did you set PYTHONPATH?\n" % (generator_module, e.args)) return -1 try: gen = getattr(mod, "gen") except AttributeError,e: Es("failed to obtain generato...
def __init__(self, server, generator_module): work_stream_base.__init__(self, server) module_and_fun = generator_module.split(".", 1) if len(module_and_fun) == 1: [ module ] = module_and_fun fun = "gen_works" else: [ module,fun ] = module_and_fun mod = __import__(module, globals(), locals(), [], -1) f = getattr(mod, fu...
cmd = self.generator_fun.next()
x = self.fun_generator.next()
def read_works(self): assert self.cur_fileno == self.readable, \ (self.cur_fileno, self.readable, self.unreadable) s = self.server works = [] for i in range(100): try: cmd = self.generator_fun.next() except StopIteration,e: self.close() self.closed = 1 break if cmd is None: # mark this unreadable self.cur_fileno = self...
if cmd is None:
if x is None:
def read_works(self): assert self.cur_fileno == self.readable, \ (self.cur_fileno, self.readable, self.unreadable) s = self.server works = [] for i in range(100): try: cmd = self.generator_fun.next() except StopIteration,e: self.close() self.closed = 1 break if cmd is None: # mark this unreadable self.cur_fileno = self...
w = Work().init(cmd, None, [], {}, { "cpu" : 1 })
pid = None dirs = [] envs = {} req = { "cpu" : 1 } if type(x) is types.StringType: cmd = x else: if type(x) is types.DictType: d = x else: d = x.__dict__ cmd = d["cmd"] pid = d.get("pid", pid) dirs = d.get("dirs", dirs) envs = d.get("envs", envs) req = d.get("req", req) w = Work().init(cmd, pid, dirs, envs, req) self.e...
def read_works(self): assert self.cur_fileno == self.readable, \ (self.cur_fileno, self.readable, self.unreadable) s = self.server works = [] for i in range(100): try: cmd = self.generator_fun.next() except StopIteration,e: self.close() self.closed = 1 break if cmd is None: # mark this unreadable self.cur_fileno = self...
self.generator_fun.fin(work_idx, work, exit_status, term_sig)
self.fun_finish(x, exit_status, term_sig)
def finish_work(self, work_idx, work, exit_status, term_sig): # mark this readable self.cur_fileno = self.readable self.generator_fun.fin(work_idx, work, exit_status, term_sig)
self.add_work_stream(work_stream_fd(self.server, r))
s = work_stream_fd(self.server) if s.init(r) == 0: self.add_work_stream(s) else: bomb
def add_proc_pipe(self, cmd, outfd): """ run 'cmd' with its outfd connected to me with a pipe. it also makes another pipe to notice its death. """ x,y = os.pipe() # pipe to detect his death r,w = os.pipe() # pipe to receive job pid = os.fork() if pid == 0: cmdline = [ "/bin/sh", "-c", cmd ] os.close(x) ...
self.add_work_stream(work_stream_fd_pair(self.server, r1, w2))
s = work_stream_fd_pair(self.server) if s.init(r1, w2) == 0: self.add_work_stream(s)
def add_proc_pipe2(self, cmd, outfd, infd): """ run 'cmd' with its outfd connected to me with a pipe. it also makes another pipe to notice its death. """ x,y = os.pipe() # pipe to detect his death r1,w1 = os.pipe() # pipe to receive job r2,w2 = os.pipe() # pipe to send notification pid = os.fork() i...
self.work_stream[idx] = (ws,w)
self.work_stream[idx] = ws,w
def read_works(self, ws): """ read works from a work_stream """ works = ws.read_works() if ws.closed: del self.streams[ws] t = self.server.cur_time() for w in works: # FIXIT: track which work came from which stream, # so we can call appropriate finish function idx = self.idx w.init2(idx, t, self.server) self.work_strea...
wkg.add_work_stream(work_stream_file(server, wf)) for mo in conf.work_py: wkg.add_work_stream(work_stream_generator(server, mo))
s = work_stream_file(server) if s.init(wf) == 0: wkg.add_work_stream(s) for mo in conf.work_py_module: s = work_stream_generator(server) if s.init(mo) == 0: wkg.add_work_stream(s)
def mk_work_generator(conf, server): wkg = work_generator(conf, server) # FIXIT. handle cases where some of them failed. # will require two step initializtion to avoid exception # handling here. # FIXIT. have a way to specify child procs (make in particular) for wf in conf.work_file: wkg.add_work_stream(work_stream_fil...
wkg.add_work_stream(work_stream_fd(server, fd))
s = work_stream_fd(server) if s.init(fd) == 0: wkg.add_work_stream(s)
def mk_work_generator(conf, server): wkg = work_generator(conf, server) # FIXIT. handle cases where some of them failed. # will require two step initializtion to avoid exception # handling here. # FIXIT. have a way to specify child procs (make in particular) for wf in conf.work_file: wkg.add_work_stream(work_stream_fil...
Es("xmake: could not make a state directory %s\n" % dire)
Es("error: could not make a state directory %s\n" % dire)
def ensure_directory(self, dire): if dire == "": return 0 try: os.mkdir(dire) except OSError,e: if e.args[0] == errno.EEXIST: pass else: raise if os.path.isdir(dire): return 0 Es("xmake: could not make a state directory %s\n" % dire) return -1
v = tok.token_val(rest)
v = tok.token_val(rest.strip())
def parse_line(self, filename, lineno, line, tok): if dbg>=2: Es("parse_line: %s:%d [%s]\n" % (filename, lineno, line)) ls = line.lstrip() if ls[:1] == "#": return if ls.rstrip() == "": return tok.init(filename, lineno, line) x = tok.s if dbg>=2: Es(" 1st token: %s\n" % x) if x == "host" or x == "job": # host REGEXP KE...
Es(" setting global attributes %s = %s\n" % (x, v))
Es(" setting global attributes %s = '%s'\n" % (x, v))
def parse_line(self, filename, lineno, line, tok): if dbg>=2: Es("parse_line: %s:%d [%s]\n" % (filename, lineno, line)) ls = line.lstrip() if ls[:1] == "#": return if ls.rstrip() == "": return tok.init(filename, lineno, line) x = tok.s if dbg>=2: Es(" 1st token: %s\n" % x) if x == "host" or x == "job": # host REGEXP KE...
self.capacity_left = None
self.capacity_left = {}
def __init__(self, man_idx, name, capacity, cur_time, server): self.man_idx = man_idx # serial number self.name = name # name (gupid) self.capacity = capacity self.capacity_left = None # set in finalize_capacity self.state = man_state.active # created time self.create_time = cur_time # last time at which I hear...
vl = self.capacity_left[k]
vl = self.capacity_left.get(k)
def __str__(self): S = [] S.append("%s" % self.name) for k,v in self.capacity.items(): vl = self.capacity_left[k] S.append(" %s: %s/%s" % (k, vl, v)) return "\n".join(S)
cl = self.capacity_left[k]
cl = self.capacity_left.get(k)
def get_td_capacity(self): C = [] keys = self.capacity.keys() keys.sort() for k in keys: c = self.capacity[k] cl = self.capacity_left[k] C.append("%s: %s / %s" % (k, cl, c)) return "<br>".join(C)
qid,_ = os.waitpid(pid, 0)
qid,status = os.waitpid(pid, 0)
def reap_child(self, r): """ called after we get EOF from file descriptor r. find pid and server sock if any associated with it and call wait on the pid, so he does not leave as a zombie. """ pid,ss = self.child_pipes[r] qid,_ = os.waitpid(pid, 0) assert (pid == qid), (pid, qid) os.close(r) del self.child_pipes[r] # ss...
def generate_html(self, finished): ct = self.cur_time() if finished or ct > self.next_update_time:
def generate_html(self, cur_time, finished): if finished or cur_time > self.next_update_time:
def generate_html(self, finished): ct = self.cur_time() if finished or ct > self.next_update_time: for run in self.runs_running.values(): run.sync(ct) self.htmlg.generate(finished) new_ct = self.cur_time() # keep the overhead below 5% time_until_next = (new_ct - ct) / 0.05 self.next_update_time = self.next_update_time ...
run.sync(ct)
run.sync(cur_time)
def generate_html(self, finished): ct = self.cur_time() if finished or ct > self.next_update_time: for run in self.runs_running.values(): run.sync(ct) self.htmlg.generate(finished) new_ct = self.cur_time() # keep the overhead below 5% time_until_next = (new_ct - ct) / 0.05 self.next_update_time = self.next_update_time ...
new_ct = self.cur_time() time_until_next = (new_ct - ct) / 0.05
return 1 else: return 0 def record_everything(self, force): t0 = self.cur_time() self.record_rss(t0, force) self.record_mem(t0, force) self.record_loadavg(t0, force) if self.generate_html(t0, force): dt = self.cur_time() - t0 overhead = self.conf.gen_html_overhead if overhead <= 0.0: time_until_next = float("inf") els...
def generate_html(self, finished): ct = self.cur_time() if finished or ct > self.next_update_time: for run in self.runs_running.values(): run.sync(ct) self.htmlg.generate(finished) new_ct = self.cur_time() # keep the overhead below 5% time_until_next = (new_ct - ct) / 0.05 self.next_update_time = self.next_update_time ...
if T is None:
if T is None or T == float("inf"):
def select_by_poll(self, R, W, E, T): d = {} for f in R: if type(f) is types.IntType: fd = f else: fd = f.fileno() d[fd] = select.POLLIN for f in W: if type(f) is types.IntType: fd = f else: fd = f.fileno() d[fd] = (d.get(fd, 0) | select.POLLOUT) for f in E: if type(f) is types.IntType: fd = f else: fd = f.fileno() d[f...
poll_result = p.poll(T*1000)
poll_result = p.poll(int(T*1000))
def select_by_poll(self, R, W, E, T): d = {} for f in R: if type(f) is types.IntType: fd = f else: fd = f.fileno() d[fd] = select.POLLIN for f in W: if type(f) is types.IntType: fd = f else: fd = f.fileno() d[fd] = (d.get(fd, 0) | select.POLLOUT) for f in E: if type(f) is types.IntType: fd = f else: fd = f.fileno() d[f...
self.record_rss(self.cur_time(), 0) self.record_mem(self.cur_time(), 0) self.record_loadavg(self.cur_time(), 0) self.generate_html(0)
self.record_everything(0)
def server_iterate(self): if self.logfp: self.LOG("server_iterate: %d runs running %d matches %d todo wkg=%s\n" % (len(self.runs_running), len(self.matches), len(self.runs_todo), self.wkg)) if self.wkg.closed() \ and len(self.runs_running) == 0 \ and len(self.matches) == 0 \ and len(self.runs_todo) == 0: if self.logfp:...
def determine_self_status(self): return 0
def determine_self_status(self): # FIXIT: determine exit status return 0
self.self_status = None
self.final_status = None
def server_main_init(self): """ real initialization """ self.sys_argv = sys.argv self.cwd = os.getcwd() self.self_pid = os.getpid() self.self_status = None # not known yet self.hostname = socket.gethostname()
self.self_status = self.determine_self_status() self.generate_html(1) return self.self_status
self.final_status = self.wkg.determine_final_status() self.record_everything(1) exit_status,term_sig = self.final_status if exit_status is None: return 1 return exit_status
def server_main_with_log(self, args): if self.logfp: self.LOG("server_main_with_log: config\n%s\n" % self.conf) if self.server_main_init() == -1: return cmd_interpreter.RET_NOT_RUN while 1: try: if self.server_iterate() == 0: break except KeyboardInterrupt: # FIXIT raise self.interrupted = self.interrupted + 1 # done. ...
return self.server_main([ "-a", 'work_proc_sock="make -j 1200"' ] + args)
make_args = [] while args: a = args.pop(0) if a == "--": break make_args.append(a) make_cmd = 'work_proc_sock="make %s"' % (" ".join(make_args)) return self.server_main([ "-a", make_cmd ] + args)
def do_make2_cmd(self, args): """ args : whatever is given after 'make2' """ # FIXIT: parse args and give them to make if self.init3() == -1: return cmd_interpreter.RET_NOT_RUN self.set_make_environ() return self.server_main([ "-a", 'work_proc_sock="make -j 1200"' ] + args)
"self_status", ]
"final_status", "gen_html_time", ] def get_td_final_status(self): if self.final_status is None: return "job_running","running" else: exit_status,term_sig = self.final_status if exit_status == 0: return "job_success",("exited 0") elif exit_status is not None: return "job_failed",("exited %d" % exit_status) else: return...
def do_make2_cmd(self, args): """ args : whatever is given after 'make2' """ # FIXIT: parse args and give them to make if self.init3() == -1: return cmd_interpreter.RET_NOT_RUN self.set_make_environ() return self.server_main([ "-a", 'work_proc_sock="make -j 1200"' ] + args)
sum(ordinal*(1+2*(i+1%2)) for i, ordinal in enumerate(ordinals)))
sum(ordinal*(1+2*((i+1)%2)) for i, ordinal in enumerate(list(ordinals))))
def upc_checksum(ordinals): """ UPC-A checksum, kind of modulus10-w3. >>> upc_checksum(translation.digits('03600029145')) 2 """ return modcomp( 10, sum(ordinal*(1+2*(i+1%2)) for i, ordinal in enumerate(ordinals)))
"""Encodes data into UPC digits.
"""Encodes data into Codabar digits.
def encode(self): """Encodes data into UPC digits.
from sys import path from os.path import abspath, dirname sys.path.insert(0, dirname(dirname(abspath('.')))) from elaphe.util import translation
import translation
def modulus_103(ordinals): """ Modulus 103, used in code128. Code should include start char and exclude stop char. >>> modulus_103(translation.code128('^105^102123456^100A1')) 35 """ return sum( (ordinal if i==0 else i*ordinal) for i, ordinal in enumerate(ordinals))%103
def spawn_link(cls, function, *args, **kwargs): g = cls.spawn(function, *args, **kwargs)
def spawn_link(cls, *args, **kwargs): g = cls.spawn(*args, **kwargs)
def spawn_link(cls, function, *args, **kwargs): g = cls.spawn(function, *args, **kwargs) g.link() return g
def spawn_link_value(cls, function, *args, **kwargs): g = cls.spawn(function, *args, **kwargs)
def spawn_link_value(cls, *args, **kwargs): g = cls.spawn(*args, **kwargs)
def spawn_link_value(cls, function, *args, **kwargs): g = cls.spawn(function, *args, **kwargs) g.link_value() return g
def spawn_link_exception(cls, function, *args, **kwargs): g = cls.spawn(function, *args, **kwargs)
def spawn_link_exception(cls, *args, **kwargs): g = cls.spawn(*args, **kwargs)
def spawn_link_exception(cls, function, *args, **kwargs): g = cls.spawn(function, *args, **kwargs) g.link_exception() return g
from gevent.hub import fork
try: from gevent.hub import fork except ImportError: return
def patch_os(): from gevent.hub import fork import os os.fork = fork
return write
def safe_write(d): if len(d): write(d) return safe_write
def start_response(status, response_headers, exc_info=None): status_code[0] = status.split()[0] if exc_info: try: if headers_sent: # Re-raise original exception if headers sent raise exc_info[0], exc_info[1], exc_info[2] finally: # Avoid dangling circular ref exc_info = None