rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
self.dirtree = DirTreeCtrl(self, self, toplevel=toplevel, filter=filter) self.dirtree.SetTopLevel() | self.dirtree = DirTreeCtrl(self, self, filter=filter) self.dirtree.SetTopLevel(toplevel) | def __init__(self, parent, size=wx.DefaultSize, message="", path="", select_path=""): from dirtree import DirTreeCtrl, DirTreeFilter, DirNode style = wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER if size == wx.DefaultSize: size = wx.Size(450, 600) wx.Dialog.__init__(self, parent, size=size, title=message, style=style) top... |
if node.type == 'd': | if node.type == 'd' and node.state == NODE_UNPOPULATED: | def OnItemExpanding(self, evt): node = self.GetEventNode(evt) if node.type == 'd': self.ExpandNode(node) |
yield node.expand(self, self.monitor, self.filter) | yield self.PopulateNode(node) | def ExpandNode(self, node): if node.state == NODE_UNPOPULATED: yield node.expand(self, self.monitor, self.filter) if node.state != NODE_POPULATING: self.Expand(node.item) |
self.ExpandNode(rootnode) if isinstance(self.toplevel[0], SimpleNode): self.ExpandNode(self.toplevel[0]) | self._InitialExpand(rootnode) | def InitializeTree(self): self.DeleteAllItems() if len(self.toplevel) == 1: rootitem = self.AddRoot(self.toplevel[0].label) rootnode = self.toplevel[0] else: rootitem = self.AddRoot("") rootnode = SimpleNode("", self.toplevel) self.SetItemNode(rootitem, rootnode) self.ExpandNode(rootnode) if isinstance(self.toplevel[0]... |
for field in ("text_name", "text_accel", "text_cmdline"): ctrl = getattr(self, field) value = ctrl.Value.strip() if not value: | for field_name, getter_method in self._fields: ctrl = getattr(self, field_name) try: value = getter_method(self, ctrl) except Exception, e: | def OnOK(self, evt): command = [] for field in ("text_name", "text_accel", "text_cmdline"): ctrl = getattr(self, field) value = ctrl.Value.strip() if not value: ctrl.SetFocus() dialogs.error(self, "Field is required") return if ctrl is self.text_accel: try: value = parse_accelerator(value) except Exception, e: ctrl.Set... |
dialogs.error(self, "Field is required") | dialogs.error(self, "Error: %s" % e) | def OnOK(self, evt): command = [] for field in ("text_name", "text_accel", "text_cmdline"): ctrl = getattr(self, field) value = ctrl.Value.strip() if not value: ctrl.SetFocus() dialogs.error(self, "Field is required") return if ctrl is self.text_accel: try: value = parse_accelerator(value) except Exception, e: ctrl.Set... |
if ctrl is self.text_accel: try: value = parse_accelerator(value) except Exception, e: ctrl.SetFocus() dialogs.error(self, "Error: %s" % e) return | def OnOK(self, evt): command = [] for field in ("text_name", "text_accel", "text_cmdline"): ctrl = getattr(self, field) value = ctrl.Value.strip() if not value: ctrl.SetFocus() dialogs.error(self, "Field is required") return if ctrl is self.text_accel: try: value = parse_accelerator(value) except Exception, e: ctrl.Set... | |
print dlg.command | def OnAdd(self, evt): dlg = EditCommandDialog(self) try: if dlg.ShowModal() == wx.ID_OK: print dlg.command self.cmdlist.Append(dlg.command.name, dlg.command) finally: dlg.Destroy() | |
command = self.cmdlist.GetClientData(selection) | command = self._GetCommand(selection) | def OnEdit(self, evt): selection = self.cmdlist.GetSelection() if selection != wx.NOT_FOUND: command = self.cmdlist.GetClientData(selection) dlg = EditCommandDialog(self, name = command.name, accel = unparse_accelerator(*command.accel), cmdline = command.cmdline) try: if dlg.ShowModal() == wx.ID_OK: print dlg.comm... |
print dlg.command | self._SetCommand(selection, dlg.command) | def OnEdit(self, evt): selection = self.cmdlist.GetSelection() if selection != wx.NOT_FOUND: command = self.cmdlist.GetClientData(selection) dlg = EditCommandDialog(self, name = command.name, accel = unparse_accelerator(*command.accel), cmdline = command.cmdline) try: if dlg.ShowModal() == wx.ID_OK: print dlg.comm... |
yield self.Save() yield True | yield (yield self.Save()) | def TryClose(self): if self.changed: result = dialogs.ask_save_changes(self, self.path) if result == wx.ID_YES: try: yield self.Save() yield True except Exception: yield False else: yield result == wx.ID_NO else: yield True |
yield async_call(shutil.copystat, path, temp) | try: yield async_call(shutil.copystat, path, temp) except OSError: pass | def SaveFile(self, path): text = self.GetText().encode("utf-8") temp = os.path.join(os.path.dirname(path), ".tmpsave." + os.path.basename(path)) try: with (yield async_call(open, temp, "wb")) as out: yield async_call(shutil.copystat, path, temp) yield async_call(out.write, text) except IOError: yield async_call(os.remo... |
yield async_call(os.remove, temp) | try: yield async_call(os.remove, temp) except OSError: pass | def SaveFile(self, path): text = self.GetText().encode("utf-8") temp = os.path.join(os.path.dirname(path), ".tmpsave." + os.path.basename(path)) try: with (yield async_call(open, temp, "wb")) as out: yield async_call(shutil.copystat, path, temp) yield async_call(out.write, text) except IOError: yield async_call(os.remo... |
path = dialogs.get_file_to_open(self) | path = dialogs.get_file_to_save(self) | def SaveAs(self): path = dialogs.get_file_to_open(self) if path: try: yield self.SaveFile(path) except Exception, exn: dialogs.error(self, "Error saving file '%s'\n\n%s" % (path, exn)) raise else: self.path = path self.sig_title_changed.signal(self) |
dialogs.error(self, "Error saving file '%s'\n\n%s" % (path, exn)) | dialogs.error(self, "Error saving file '%s'\n\n%s" % (self.path, exn)) | def Save(self): if self.path: try: yield self.SaveFile(self.path) except Exception, exn: dialogs.error(self, "Error saving file '%s'\n\n%s" % (path, exn)) raise else: yield self.SaveAs() |
yield self.SaveAs() | yield (yield self.SaveAs()) | def Save(self): if self.path: try: yield self.SaveFile(self.path) except Exception, exn: dialogs.error(self, "Error saving file '%s'\n\n%s" % (path, exn)) raise else: yield self.SaveAs() |
expanded = tree.IsExpanded(self.item) | def expand(self, tree, monitor, filter): if not self.populated: self.populated = True self.watch = monitor.add_dir_watch(self.path, user=self) expanded = tree.IsExpanded(self.item) dirs = [] files = [] for filename in sorted_filenames((yield async_call(os.listdir, self.path))): if not filter.filter_by_name(filename): c... | |
if not expanded: tree.Expand(self.item) expanded = True | def expand(self, tree, monitor, filter): if not self.populated: self.populated = True self.watch = monitor.add_dir_watch(self.path, user=self) expanded = tree.IsExpanded(self.item) dirs = [] files = [] for filename in sorted_filenames((yield async_call(os.listdir, self.path))): if not filter.filter_by_name(filename): c... | |
f = node.expand(self, self.monitor, self.filter) if isinstance(f, Future): yield f | if not node.populated: f = node.expand(self, self.monitor, self.filter) if isinstance(f, Future): yield f | def ExpandNode(self, node): f = node.expand(self, self.monitor, self.filter) if isinstance(f, Future): yield f self.Expand(node.item) |
def _ExpandPathNodes(self, item, paths): node = self.GetPyData(item) if node.type == 'd' and (node.path in paths or not node.path): yield self.ExpandNode(node) for child_item in iter_tree_children(self, item): yield self._ExpandPathNodes(child_item, paths) | def _ExpandPathNodes(self, node, paths): yield self.ExpandNode(node) for item in iter_tree_children(self, node.item): node = self.GetPyData(item) if node.type == 'd' and (node.path in paths or not node.path): paths.discard(node.path) yield self._ExpandPathNodes(node, paths) if not paths: break | def _ExpandPathNodes(self, item, paths): node = self.GetPyData(item) if node.type == 'd' and (node.path in paths or not node.path): yield self.ExpandNode(node) for child_item in iter_tree_children(self, item): yield self._ExpandPathNodes(child_item, paths) |
return self._ExpandPathNodes(self.GetRootItem(), paths) | rootnode = self.GetPyData(self.GetRootItem()) paths = set(paths) paths.discard(rootnode.path) if paths: return self._ExpandPathNodes(rootnode, paths) | def ExpandPathNodes(self, paths): return self._ExpandPathNodes(self.GetRootItem(), paths) |
def changed(self, evt, tree, monitor): | def add(self, name, tree, monitor): | def changed(self, evt, tree, monitor): if self.populated: path = os.path.join(self.path, evt.name) if evt.action in (fsmonitor.FSEVT_CREATE, fsmonitor.FSEVT_MOVE_TO): type, image = (yield async_call(get_file_type_and_image, path)) if type: item = dirtree_insert(tree, self.item, evt.name, image) node = FSNode(path, type... |
path = os.path.join(self.path, evt.name) if evt.action in (fsmonitor.FSEVT_CREATE, fsmonitor.FSEVT_MOVE_TO): type, image = (yield async_call(get_file_type_and_image, path)) if type: item = dirtree_insert(tree, self.item, evt.name, image) node = FSNode(path, type) tree.SetPyData(item, node) if type == 'd': tree.SetItemH... | path = os.path.join(self.path, name) type, image = (yield async_call(get_file_type_and_image, path)) if type: item = dirtree_insert(tree, self.item, name, image) node = FSNode(path, type) tree.SetPyData(item, node) if type == 'd': tree.SetItemHasChildren(item, True) def remove(self, name, tree, monitor): if self.popul... | def changed(self, evt, tree, monitor): if self.populated: path = os.path.join(self.path, evt.name) if evt.action in (fsmonitor.FSEVT_CREATE, fsmonitor.FSEVT_MOVE_TO): type, image = (yield async_call(get_file_type_and_image, path)) if type: item = dirtree_insert(tree, self.item, evt.name, image) node = FSNode(path, type... |
yield evt.userobj.changed(evt, self, self.monitor) | if evt.action in (fsmonitor.FSEVT_CREATE, fsmonitor.FSEVT_MOVE_TO): yield evt.userobj.add(evt.name, self, self.monitor) elif evt.action in (fsmonitor.FSEVT_DELETE, fsmonitor.FSEVT_MOVE_FROM): evt.userobj.remove(evt.name, self, self.monitor) | def OnFileSystemChanged(self): with self.fsevts_lock: evts = self.fsevts self.fsevts = [] for evt in evts: yield evt.userobj.changed(evt, self, self.monitor) |
return message_dialog(parent, | return self.message_dialog(parent, | def ask_overwrite(self, parent, path): return message_dialog(parent, "A file named '%s' already exists. Overwrite?" % path, "Confirm Overwrite", wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) == wx.ID_YES |
return message_dialog(parent, | return self.message_dialog(parent, | def ask_delete(self, parent, path): return message_dialog(parent, "Are you sure you want to delete '%s'?" % path, "Confirm Delete", wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION) == wx.ID_YES |
self.AddPage(editor) | def OpenEditor(self, path): realpath = os.path.realpath(path) editor = self.FindEditor(realpath) if editor is not None: i = self.notebook.GetPageIndex(editor) if i != wx.NOT_FOUND: self.notebook.SetSelection(i) else: with frozen_window(self.notebook): editor = Editor(self, self.env, realpath) editor.Show(False) self.Ad... | |
self.editors.append(editor) | self.AddPage(editor) | def OpenEditor(self, path): realpath = os.path.realpath(path) editor = self.FindEditor(realpath) if editor is not None: i = self.notebook.GetPageIndex(editor) if i != wx.NOT_FOUND: self.notebook.SetSelection(i) else: with frozen_window(self.notebook): editor = Editor(self, self.env, realpath) editor.Show(False) self.Ad... |
self.StyleClearAll() | def SetNullSyntax(self): self.SetLexer(wx.stc.STC_LEX_NULL) self.SetKeyWords(0, "") self.StyleClearAll() self.StyleSetFontAttr(wx.stc.STC_STYLE_DEFAULT, 10, fontface, False, False, False) self.StyleSetSpec(wx.stc.STC_STYLE_DEFAULT, "") self.SetIndent(4) self.SetTabWidth(8) self.SetUseTabs(False) | |
self.sig_title_changed.signal(self) | def LoadFile(self, path): self.SetReadOnly(True) self.Disable() try: self.sig_title_changed.signal(self) with (yield async_call(open, path)) as f: text = (yield async_call(f.read)) try: text = text.decode("utf-8") except UnicodeDecodeError: text = text.decode("iso-8859-1") self.SetReadOnly(False) self.SetSyntaxFromFile... | |
def expand(self, tree, rootitem, monitor): tree.SetItemImage(rootitem, IM_FOLDER) | self.item = None def expand(self, tree, monitor): tree.SetItemImage(self.item, IM_FOLDER) | def __init__(self, label, children): self.label = label self.children = children self.populated = False |
item = tree.AppendItem(rootitem, node.label, IM_FOLDER) | item = tree.AppendItem(self.item, node.label, IM_FOLDER) | def expand(self, tree, rootitem, monitor): tree.SetItemImage(rootitem, IM_FOLDER) for node in self.children: item = tree.AppendItem(rootitem, node.label, IM_FOLDER) tree.SetItemNode(item, node) tree.SetItemHasChildren(item, True) |
self.__clear_handlers() | def cancel(self): with self.__cond: if self.__status != WAITING: return self.__status = CANCELLED self.__clear_handlers() self.__cond.notify_all() _global_scheduler.post_call(self.__finish) | |
wx.CallLater(10, self.OnFileSystemChanged, evt) | with self.fsevts_lock: called = bool(self.fsevts) self.fsevts.append(evt) if not called: wx.CallAfter(lambda: wx.CallLater(200, self.OnFileSystemChanged)) | def _OnFileSystemChanged(self, evt): wx.CallLater(10, self.OnFileSystemChanged, evt) |
def OnFileSystemChanged(self, evt): yield evt.userobj.changed(evt, self, self.monitor) | def OnFileSystemChanged(self): with self.fsevts_lock: evts = self.fsevts self.fsevts = [] for evt in evts: yield evt.userobj.changed(evt, self, self.monitor) | def OnFileSystemChanged(self, evt): yield evt.userobj.changed(evt, self, self.monitor) |
self.StyleResetDefault() | def SetSyntaxFromFilename(self, path): m = filename_syntax_re.match(os.path.basename(path)) if m: syntax = syntax_dict[m.lastgroup] self.StyleResetDefault() self.ClearDocumentStyle() self.SetLexer(syntax.lexer) self.SetKeyWords(0, syntax.keywords) self.StyleClearAll() for style_num, spec in syntax.stylespecs: self.Styl... | |
self.StyleSetFontAttr(style_num, 10, fontface, False, False, False) | def SetSyntaxFromFilename(self, path): m = filename_syntax_re.match(os.path.basename(path)) if m: syntax = syntax_dict[m.lastgroup] self.StyleResetDefault() self.ClearDocumentStyle() self.SetLexer(syntax.lexer) self.SetKeyWords(0, syntax.keywords) self.StyleClearAll() for style_num, spec in syntax.stylespecs: self.Styl... | |
yield self.SaveSession() | if not (yield self.SaveSession()): yield False | def SaveProject(self): self.fmon.Stop() if self.session_filename: try: yield self.SaveSession() except Exception, e: dialogs.error(self, "Error saving session:\n\n%s" % e) yield False if self.project_filename: try: yield async_call(write_settings, self.project_filename, self.project) except Exception, e: dialogs.error(... |
indent = self.GetLineIndentation(self.GetCurrentLine()) pos = self.GetCurrentPos() if self.GetUseTabs(): indent //= self.GetTabWidth() self.InsertText(pos, "\n" + "\t" * indent) else: self.InsertText(pos, "\n" + " " * indent) self.GotoPos(pos + indent + 1) | self.OnReturnKeyDown(evt) | def OnKeyDown(self, evt): key = evt.GetKeyCode() mod = evt.GetModifiers() if mod == wx.MOD_NONE: if key in (wx.WXK_RETURN, wx.WXK_NUMPAD_ENTER): indent = self.GetLineIndentation(self.GetCurrentLine()) pos = self.GetCurrentPos() if self.GetUseTabs(): indent //= self.GetTabWidth() self.InsertText(pos, "\n" + "\t" * inden... |
def _ShowLoadProjectError(self, exn): | def _ShowLoadProjectError(self, exn, filename): | def _ShowLoadProjectError(self, exn): self.Show() if isinstance(exn, IOError) and exn.errno == errno.ENOENT: dialogs.error(self, "Project file not found:\n\n" + filename) else: dialogs.error(self, "Error loading session:\n\n%s" % traceback.format_exc()) |
self._ShowLoadProjectError(e) | self._ShowLoadProjectError(e, filename) | def OpenProject(self, filename): try: project = (yield self._OpenProject(filename)) except Exception, e: self._ShowLoadProjectError(e) |
self._ShowLoadProjectError(e) | self._ShowLoadProjectError(e, filename) | def OpenDefaultProject(self): filename = os.path.join(self.config_dir, "session") try: yield self._OpenProject(filename) except Exception: try: yield self.LoadProject(Project(filename=filename)) self.Show() except Exception, e: self._ShowLoadProjectError(e) |
yield editor.PositionFromLine(line), editor.GetLine(line)[:-1] | yield editor.PositionFromLine(line), editor.GetLine(line) | def _IterFindLines(self, editor, wrap=True): init_pos = editor.GetSelection()[1] init_line = editor.LineFromPosition(init_pos) last_line = editor.LineFromPosition(editor.GetTextLength()) |
if last >= 0 and menu.FindItemByPosition(last).GetKind() == wx.ITEM_SEPARATOR: menu.Delete(last) | if last >= 0: item = menu.FindItemByPosition(last) if item.GetKind() == wx.ITEM_SEPARATOR: menu.DeleteItem(item) | def Create(self, **hooks): menu = wx.Menu() for item in self.items: item.Build(menu, hooks) last = menu.GetMenuItemCount() - 1 if last >= 0 and menu.FindItemByPosition(last).GetKind() == wx.ITEM_SEPARATOR: menu.Delete(last) return menu |
if self.updated_paths: | if self.updated_paths or self.deleted_paths: | def NotifyUpdatedPaths(self): if (self.updated_paths or self.deleted_paths) and not self.reloading: try: self.reloading = True to_reload = [] to_unload = [] for editor in self.editors: if editor.path in self.updated_paths: to_reload.append(editor) elif editor.path in self.deleted_paths: to_unload.append(editor) self.up... |
def _IterFindLines(self, editor): | def _IterFindLines(self, editor, wrap=True): | def _IterFindLines(self, editor): init_pos = editor.GetSelection()[1] init_line = editor.LineFromPosition(init_pos) last_line = editor.LineFromPosition(editor.GetTextLength()) |
for line in xrange(0, init_line): yield editor.PositionFromLine(line), editor.GetLine(line)[:-1] | if wrap: for line in xrange(0, init_line): yield editor.PositionFromLine(line), editor.GetLine(line)[:-1] | def _IterFindLines(self, editor): init_pos = editor.GetSelection()[1] init_line = editor.LineFromPosition(init_pos) last_line = editor.LineFromPosition(editor.GetTextLength()) |
def Find(self, editor): | def Find(self, editor, wrap=True): | def Find(self, editor): ptn = self._GetFindPattern(editor) if ptn: for pos, line in self._IterFindLines(editor): m = ptn.search(line) if m and m.start() != m.end(): editor.SetSelection(pos + m.start(), pos + m.end()) return True return False |
for pos, line in self._IterFindLines(editor): | for pos, line in self._IterFindLines(editor, wrap): | def Find(self, editor): ptn = self._GetFindPattern(editor) if ptn: for pos, line in self._IterFindLines(editor): m = ptn.search(line) if m and m.start() != m.end(): editor.SetSelection(pos + m.start(), pos + m.end()) return True return False |
self._ReplaceSelected(editor) | ptn = self._GetFindPattern(editor) if ptn.match(editor.GetSelectedText()): self._ReplaceSelected(editor) | def Replace(self, editor): self._ReplaceSelected(editor) return self.Find(editor) |
count = 0 | def ReplaceAll(self, editor): ptn = self._GetFindPattern(editor) count = 0 if ptn: editor.SetSelection(0, 0) for pos, line in self._IterFindLines(editor): m = ptn.search(line) if m and m.start() != m.end(): editor.SetSelection(pos + m.start(), pos + m.end()) self._ReplaceSelected(editor) count += 1 return count | |
for pos, line in self._IterFindLines(editor): m = ptn.search(line) if m and m.start() != m.end(): editor.SetSelection(pos + m.start(), pos + m.end()) self._ReplaceSelected(editor) count += 1 | m = True while m: for pos, line in self._IterFindLines(editor, wrap=False): m = ptn.search(line) if m and m.start() != m.end(): editor.SetSelection(pos + m.start(), pos + m.end()) self._ReplaceSelected(editor) count += 1 break | def ReplaceAll(self, editor): ptn = self._GetFindPattern(editor) count = 0 if ptn: editor.SetSelection(0, 0) for pos, line in self._IterFindLines(editor): m = ptn.search(line) if m and m.start() != m.end(): editor.SetSelection(pos + m.start(), pos + m.end()) self._ReplaceSelected(editor) count += 1 return count |
if ask_delete_file(get_top_window(), path): | if ask_delete_file(path): | def shell_remove(path): if ask_delete_file(get_top_window(), path): try: yield async_call(remove, path) except Exception, e: dialogs.error(get_top_window(), "Error deleting file:\n\n%s" % e) |
if ask_copy_file(get_top_window(), srcpath, dstpath): | if ask_copy_file(srcpath, dstpath): | def shell_copy(srcpath, dstpath): if destination_is_same(srcpath, dstpath): return if ask_copy_file(get_top_window(), srcpath, dstpath): shell.SHFileOperation( (0, shellcon.FO_COPY, srcpath, dstpath, shellcon.FOF_ALLOWUNDO, None, None)) |
if ask_move_file(get_top_window(), srcpath, dstpath): | if ask_move_file(srcpath, dstpath): | def shell_move(srcpath, dstpath): if destination_is_same(srcpath, dstpath): return if ask_move_file(get_top_window(), srcpath, dstpath): shell.SHFileOperation( (0, shellcon.FO_MOVE, srcpath, dstpath, shellcon.FOF_ALLOWUNDO, None, None)) |
sys.stdout = sys.__stdout__ | sys.stdout = saveout | def parse_dot_data(dotdata): """Wrapper for pydot.graph_from_dot_data Redirects error messages to the log. """ saveout = sys.stdout fsock = StringIO() sys.stdout = fsock #graph = pydot.graph_from_dot_data(dotdata) parser = dotparsing.DotDataParser() graph = parser.parse_dot_data(dotdata) del(parser) log.debug('Output ... |
self.pool.get('company.employee').clear.reset() | self.pool.get('company.employee').clear() | def delete(self, ids): self.pool.get('company.employee').clear.reset() return super(EmployeeCostPrice , self).delete(ids) |
self.pool.get('company.employee').clear.reset() | self.pool.get('company.employee').clear() | def create(self, vals): self.pool.get('company.employee').clear.reset() return super(EmployeeCostPrice , self).create(vals) |
self.pool.get('company.employee').clear.reset() | self.pool.get('company.employee').clear() | def write(self, ids, vals): self.pool.get('company.employee').clear.reset() return super(EmployeeCostPrice , self).write(ids, vals) |
self.assertRaises(Exception, test_view('project_revenue')) | test_view('project_revenue') | def test0005views(self): ''' Test views. ''' self.assertRaises(Exception, test_view('project_revenue')) |
return self.module_main(*args) | result = self.module_main(*args) if type(result) is float: result = '{0:f}'.format(result) return result | def execute_module(self, host, *args): args = [arg == '$hostname' and host or arg for arg in args] logging.debug('calling {0}.main({1})'.format(self.module_main.__module__, ','.join(args))) return self.module_main(*args) |
for arg in args: if arg == '$hostname': arg = host | args = [arg == '$hostname' and host or arg for arg in args] logging.debug('calling {0}.main({1})'.format(self.module_main.__module__, ','.join(args))) | def execute_module(self, host, *args): for arg in args: if arg == '$hostname': arg = host return self.module_main(*args) |
logging.debug('executing script {0}[{1},{2}]'.format(self.script.key, host, ','.join(self.args))) | logging.debug('executing script {0}[{2}] for host {1}'.format(self.script.key, host, ','.join(self.args))) | def check(self, host): self.last_check = time.time() logging.debug('executing script {0}[{1},{2}]'.format(self.script.key, host, ','.join(self.args))) return self.script.execute(host, *self.args) |
def __init__(self, interval, script, args): | def __init__(self, key, interval, script, args): self.key = key self.interval = interval | def __init__(self, interval, script, args): self.script = script self.args = args self.interval = interval self.last_check = 0 |
self.interval = interval | def __init__(self, interval, script, args): self.script = script self.args = args self.interval = interval self.last_check = 0 | |
item_re = re.compile('^(.+?)(\[(.+)\])?$') | item_re = re.compile('^((.+?)(\[(.+)\])?)$') | def __init__(self, name, server, update_interval, scripts): self.name = name self.update_interval = update_interval self.scripts = scripts self.trapper = trapper(name, server) self.last_update = 0 self.items = [] |
key, args = self.item_re.match(raw_key).group(1, 3) | key, bare_key, args = self.item_re.match(raw_key).group(1, 2, 4) | def update_active_checks(self): logging.info('updating item list for host {0}'.format(self.name)) self.items = [] self.last_update = time.time() for raw_key, interval in self.trapper.get_active_checks(): key, args = self.item_re.match(raw_key).group(1, 3) for script in self.scripts: if script.key == key: self.items.app... |
if script.key == key: self.items.append(item(interval, script, args and args.split(',') or [])) | if script.key == bare_key: self.items.append(item(key, interval, script, args and args.split(',') or [])) | def update_active_checks(self): logging.info('updating item list for host {0}'.format(self.name)) self.items = [] self.last_update = time.time() for raw_key, interval in self.trapper.get_active_checks(): key, args = self.item_re.match(raw_key).group(1, 3) for script in self.scripts: if script.key == key: self.items.app... |
self.trapper.update_item(item.script.key, item.check(self.name)) | self.trapper.update_item(item.key, item.check(self.name)) | def update(self, item): if item == self: self.update_active_checks() else: try: self.trapper.update_item(item.script.key, item.check(self.name)) except BaseException, e: logging.warning('failed to update item {0}[{2}] for host {1}: {3}'.format(item.script.key, self.name, ','.join(item.args), e)) |
logging.debug('executing script {0}[{1}, {2}]'.format(self.script.key, host, self.args)) | logging.debug('executing script {0}[{1},{2}]'.format(self.script.key, host, ','.join(self.args))) | def check(self, host): self.last_check = time.time() logging.debug('executing script {0}[{1}, {2}]'.format(self.script.key, host, self.args)) return self.script.execute(host, *self.args) |
self.items.append(item(interval, script, args or [] and args.split(','))) | self.items.append(item(interval, script, args and args.split(',') or [])) | def update_active_checks(self): logging.info('updating item list for host {0}'.format(self.name)) self.items = [] self.last_update = time.time() for raw_key, interval in self.trapper.get_active_checks(): key, args = self.item_re.match(raw_key).group(1, 3) for script in self.scripts: if script.key == key: self.items.app... |
self.module_main(*args) | return self.module_main(*args) | def execute_module(self, host, *args): for arg in args: if arg == '$hostname': arg = host self.module_main(*args) |
open(f+'~', 'w').write(contents) open(f, 'w').write(fix_includes(contents)) | new = fix_includes(contents) if new <> contents: open(f+'~', 'w').write(contents) open(f, 'w').write(fix_includes(contents)) | def fix_includes(bulk): eol = re.search("[\r\n]+", bulk).group() for heading, keywords in data: if bulk.find(heading) == -1: for word in keywords: if bulk.find(word) <> -1: bulk = "#include <%s>%s%s" % (heading, eol, bulk) break return bulk |
get = bot.fetch | get = MoodleBot().fetch | def get_mails(url): """Retrieve user E-mails from a page (eg. grader report).""" from HTMLParser import HTMLParser as HP from urllib import unquote from re import findall get = bot.fetch unesc = HP().unescape retr = lambda url: unesc(get(url).decode('utf-8')) user_links = sorted(set(findall('user/view[^"]+', retr(url))... |
except TemplateNotFound: | except jinja2.TemplateNotFound: | def render(self, values, template_name): """Render a Jinja2 Template""" global jinja2 if not jinja2: import jinja2 env = jinja2.Environment(loader=jinja2.FileSystemLoader(config.template_dirs)) try: template = env.get_template(template_name) except TemplateNotFound: raise jinja2.TemplateNotFound(template_name) myval = ... |
def create(cls, tenant=None, user=None, uid=None, text='', email=None): | def create(cls, tenant='_unknown', user=None, uid=None, text='', email=None): | def create(cls, tenant=None, user=None, uid=None, text='', email=None): """Creates a credential Object generating a random secret and a random uid if needed.""" # secret hopfully contains about 64 bits of entropy - more than most passwords data = "%s%s%s%s%s" % (user, uuid.uuid1(), uid, text, email) secret = str(base64... |
resultList.append(resu.contents[0]) | resultList.append(resu.getText().encode("utf-8")) | def fetchResults(self): requestType = 0 if (self.request.get('type') != None): requestType = self.request.get('type') page = urllib2.urlopen("http://buscon.rae.es/draeI/SrvltGUIBusUsual?LEMA="+self.request.get('query')+"&origen=RAE&TIPO_BUS="+requestType) soup = BeautifulSoup(page) resultList = [] #for resu in soup.bo... |
page = urllib2.urlopen("http://buscon.rae.es/draeI/SrvltGUIBusUsual?LEMA="+query+"&origen=RAE&TIPO_BUS="+requestType) soup = BeautifulSoup(page) resultList = [] for resu in soup.body.findAll("span","eAcep"): resultList.append(resu.getText().encode("utf-8")) | def fetchResults(self): query = "" #>print self.request.path #/json fetchString = re.search("/w/(json|xml)/(.*)",self.request.path) if (fetchString != None): query = fetchString.group(2) #group(1) is either XML or JSON else: query = self.request.get('query') requestType = 0 if (self.request.get('type') != None): reques... | |
parser = optparse.OptionParser(usage=usage.strip()) | parser = optparse.OptionParser(usage=usage.strip(), option_class=CfxOption) | def parse_args(arguments, parser_options, usage, parser_groups=None, defaults=None): parser = optparse.OptionParser(usage=usage.strip()) for names, opts in parser_options.items(): parser.add_option(*names, **opts) if parser_groups: for group_info in parser_groups.values(): group = optparse.OptionGroup(parser, group_i... |
print "%s:\n %s" % (name, contents) | print "%s:\n %s" % (normpath(name), contents) | def document_zip_file(path): zip = zipfile.ZipFile(path, 'r') for name in zip.namelist(): contents = zip.read(name) lines = contents.splitlines() if len(lines) == 1 and name.endswith('.json') and len(lines[0]) > 75: # Ideally we would json-decode this, but it results # in an annoying 'u' before every string literal, # ... |
print "%s:" % relfilename | print "%s:" % normpath(relfilename) | def document_dir_files(path): for dirpath, dirnames, filenames in os.walk(path): relpath = dirpath[len(path)+1:] for filename in filenames: abspath = os.path.join(dirpath, filename) contents = open(abspath, 'r').read() contents = "\n ".join(contents.splitlines()) relfilename = os.path.join(relpath, filename) print "%s... |
print "File does not exist: %s" % local_json sys.exit(1) | if name == "default": return [] else: print "File does not exist: %s" % local_json sys.exit(1) | def get_config_args(name, env_root): local_json = os.path.join(env_root, "local.json") if not (os.path.exists(local_json) and os.path.isfile(local_json)): print "File does not exist: %s" % local_json sys.exit(1) local_json = packaging.load_json_file(local_json) if 'configs' not in local_json: print "'configs' key not f... |
print "No config found for '%s'." % name sys.exit(1) | if name == "default": return [] else: print "No config found for '%s'." % name sys.exit(1) | def get_config_args(name, env_root): local_json = os.path.join(env_root, "local.json") if not (os.path.exists(local_json) and os.path.isfile(local_json)): print "File does not exist: %s" % local_json sys.exit(1) local_json = packaging.load_json_file(local_json) if 'configs' not in local_json: print "'configs' key not f... |
zf.writestr(zipfile.ZipInfo(base_arcpath + "/"), "") | dirinfo = zipfile.ZipInfo(base_arcpath + "/") dirinfo.external_attr = 0755 << 16L zf.writestr(dirinfo, "") | def filter_filenames(filenames): for filename in filenames: if filename in IGNORED_FILES: continue if any([filename.endswith(suffix) for suffix in IGNORED_FILE_SUFFIXES]): continue yield filename |
def get_configs(pkg_name): pkg_path = os.path.join(static_files_path, 'packages', pkg_name) if not (os.path.exists(pkg_path) and os.path.isdir(pkg_path)): raise Exception('path does not exist: %s' % pkg_path) target_cfg = packaging.get_config_in_dir(pkg_path) pkg_cfg = packaging.build_config(static_files_path, target_c... | expected_xpi_files = [ 'install.rdf', 'components/harness.js', 'resources/testing-bar-lib/bar-module.js', 'resources/testing-foo-lib/main.js', 'resources/testing-jetpack-core-lib/loader.js', 'harness-options.json' ] | def get_configs(pkg_name): pkg_path = os.path.join(static_files_path, 'packages', pkg_name) if not (os.path.exists(pkg_path) and os.path.isdir(pkg_path)): raise Exception('path does not exist: %s' % pkg_path) target_cfg = packaging.get_config_in_dir(pkg_path) pkg_cfg = packaging.build_config(static_files_path, target_c... |
class PackagingTests(unittest.TestCase): | expected_options = { u"main": u"main", u"resourcePackages": { u"testing-bar-lib": u"bar", u"testing-foo-lib": u"foo", u"testing-jetpack-core-lib": u"jetpack-core" }, u"packageData": {}, u"rootPaths": [u"resource://testing-jetpack-core-lib/", u"resource://testing-bar-lib/", u"resource://testing-foo-lib/"], u"resources":... | def get_configs(pkg_name): pkg_path = os.path.join(static_files_path, 'packages', pkg_name) if not (os.path.exists(pkg_path) and os.path.isdir(pkg_path)): raise Exception('path does not exist: %s' % pkg_path) target_cfg = packaging.get_config_in_dir(pkg_path) pkg_cfg = packaging.build_config(static_files_path, target_c... |
configs = get_configs('foo') packages = configs.pkg_cfg.packages | configs = test_packaging.get_configs('foo') options = {'main': configs.target_cfg.main} options.update(configs.build) xpiname = 'test-xpi.xpi' fake_manifest = '<RDF>This is a fake install.rdf.</RDF>' xpi.build_xpi(template_root_dir=xpi_template_path, manifest=fake_manifest, xpi_name=xpiname, harness_options=options, xp... | def test_basic(self): configs = get_configs('foo') packages = configs.pkg_cfg.packages |
self.assertTrue('jetpack-core' in packages) self.assertTrue('foo' in packages) self.assertTrue('jetpack-core' in packages.foo.dependencies) self.assertEqual(packages['jetpack-core'].loader, 'lib/loader.js') self.assertTrue(packages.foo.main == 'main') | zip = zipfile.ZipFile(xpiname, 'r') self.assertEqual(zip.namelist(), expected_xpi_files) self.assertEqual(zip.read('install.rdf'), fake_manifest) self.assertEqual(json.loads(zip.read('harness-options.json')), expected_options) zip.close() os.remove(xpiname) | def test_basic(self): configs = get_configs('foo') packages = configs.pkg_cfg.packages |
info = os.stat(fullpath) data[filename] = dict(size=info.st_size) | try: info = os.stat(fullpath) data[filename] = dict(size=info.st_size) except OSError: pass | def _get_files_in_dir(self, path): data = {} files = os.listdir(path) for filename in files: fullpath = os.path.join(path, filename) if os.path.isdir(fullpath): data[filename] = self._get_files_in_dir(fullpath) else: info = os.stat(fullpath) data[filename] = dict(size=info.st_size) return data |
print "%s:" % normpath(relfilename) print " %s" % contents | filename_contents_tuples.append((normpath(relfilename), contents)) filename_contents_tuples.sort() for filename, contents in filename_contents_tuples: print "%s:" % filename print " %s" % contents | def document_dir_files(path): for dirpath, dirnames, filenames in os.walk(path): relpath = dirpath[len(path)+1:] for filename in filenames: abspath = os.path.join(dirpath, filename) contents = open(abspath, 'r').read() contents = "\n ".join(contents.splitlines()) relfilename = os.path.join(relpath, filename) print "%s... |
if not os.path.samefile(otherpkg.root_dir, path): | if not _is_same_file(otherpkg.root_dir, path): | def add_packages_from_config(pkgconfig): if 'packages' in pkgconfig: for package_dir in resolve_dirs(pkgconfig, pkgconfig.packages): dirs_to_scan.append(package_dir) |
if jid.startswith("jid0-anonymous-"): | if jid.startswith("anonid0-"): | def check_for_privkey(keydir, jid, stderr): if jid.startswith("jid0-anonymous-"): return None keypath = os.path.join(keydir, jid) if not os.path.isfile(keypath): msg = """\ |
if desc and desc.attrib.has_key('{http://www.mozilla.org/2004/em-rdf | if len(desc) and desc.attrib.has_key('{http://www.mozilla.org/2004/em-rdf | def install_addon(self, addon): """Installs the given addon in the profile.""" tmpdir = None if addon.endswith('.xpi'): tmpdir = tempfile.mkdtemp(suffix = "." + os.path.split(addon)[-1]) compressed_file = zipfile.ZipFile(addon, "r") for name in compressed_file.namelist(): if name.endswith('/'): makedirs(os.path.join(tm... |
elif desc and desc.find('.//{http://www.mozilla.org/2004/em-rdf | elif len(desc) and desc.find('.//{http://www.mozilla.org/2004/em-rdf | def install_addon(self, addon): """Installs the given addon in the profile.""" tmpdir = None if addon.endswith('.xpi'): tmpdir = tempfile.mkdtemp(suffix = "." + os.path.split(addon)[-1]) compressed_file = zipfile.ZipFile(addon, "r") for name in compressed_file.namelist(): if name.endswith('/'): makedirs(os.path.join(tm... |
if len(about) is 0: | if len(about) == 0: | def install_addon(self, addon): """Installs the given addon in the profile.""" tmpdir = None if addon.endswith('.xpi'): tmpdir = tempfile.mkdtemp(suffix = "." + os.path.split(addon)[-1]) compressed_file = zipfile.ZipFile(addon, "r") for name in compressed_file.namelist(): if name.endswith('/'): makedirs(os.path.join(tm... |
print "File does not exist: %s" % local_json | print >>sys.stderr, "File does not exist: %s" % local_json | def get_config_args(name, env_root): local_json = os.path.join(env_root, "local.json") if not (os.path.exists(local_json) and os.path.isfile(local_json)): if name == "default": return [] else: print "File does not exist: %s" % local_json sys.exit(1) local_json = packaging.load_json_file(local_json) if 'configs' not in ... |
print "'configs' key not found in local.json." | print >>sys.stderr, "'configs' key not found in local.json." | def get_config_args(name, env_root): local_json = os.path.join(env_root, "local.json") if not (os.path.exists(local_json) and os.path.isfile(local_json)): if name == "default": return [] else: print "File does not exist: %s" % local_json sys.exit(1) local_json = packaging.load_json_file(local_json) if 'configs' not in ... |
print "No config found for '%s'." % name | print >>sys.stderr, "No config found for '%s'." % name | def get_config_args(name, env_root): local_json = os.path.join(env_root, "local.json") if not (os.path.exists(local_json) and os.path.isfile(local_json)): if name == "default": return [] else: print "File does not exist: %s" % local_json sys.exit(1) local_json = packaging.load_json_file(local_json) if 'configs' not in ... |
print "Config for '%s' must be a list of strings." % name | print >>sys.stderr, "Config for '%s' must be a list of strings." % name | def get_config_args(name, env_root): local_json = os.path.join(env_root, "local.json") if not (os.path.exists(local_json) and os.path.isfile(local_json)): if name == "default": return [] else: print "File does not exist: %s" % local_json sys.exit(1) local_json = packaging.load_json_file(local_json) if 'configs' not in ... |
if otherpkg.root_dir != path: | if not os.path.samefile(otherpkg.root_dir, path): | def add_packages_from_config(pkgconfig): if 'packages' in pkgconfig: for package_dir in resolve_dirs(pkgconfig, pkgconfig.packages): dirs_to_scan.append(package_dir) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.