rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
dist = open('/etc/issue').read().split()[0] | dist = open('/etc/issue').read().strip('\n\t ').split()[0] | def detect_platform(): if platform.system() != 'Linux': return platform.system().lower() dist = '' (maj, min, patch) = platform.python_version_tuple() if (maj * 10 + min) >= 26: dist = platform.linux_distribution()[0] else: dist = platform.dist()[0] if dist == '': try: dist = open('/etc/issue').read().split()[0] exce... |
for x in os.listdir('/proc/acpi/ac_adapter'): | try: lst = [] lst = os.listdir('/proc/acpi/ac_adapter') except: pass for x in lst: | def get_ac_adapters(): r = [] for x in os.listdir('/proc/acpi/ac_adapter'): try: a = ACAdapter() a.name = x ss = open('/proc/acpi/ac_adapter/%s/state' % x).read().split('\n') for s in ss: if s.startswith('state:'): a.present = s.endswith('on-line') r.append(a) except: pass return r |
for x in os.listdir('/proc/acpi/battery'): | try: lst = [] lst = os.listdir('/proc/acpi/battery') except: pass for x in lst: | def get_batteries(): r = [] for x in os.listdir('/proc/acpi/battery'): try: b = Battery() b.name = x b.total = 10000 b.current = 10000 ss = open('/proc/acpi/battery/%s/state' % x).read().split('\n') for s in ss: if s.startswith('present:'): b.present = s.endswith('yes') if s.startswith('remaining capacity:'): b.current... |
self.load_runtime() | pass | def load(self, file='/etc/iptables.up.rules'): self.tables = {} try: data = open(file).read().split('\n') while len(data)>0: s = data[0] data = data[1:] if s != '': if s[0] == '*': self.tables[s[1:]] = Table(s[1:]) self.tables[s[1:]].load(data) except: self.load_runtime() |
self.interfaces[name] = SuseNetworkInterface() | self.interfaces[name] = ArchNetworkInterface() | def get_iface(self, name, cls): if not self.interfaces.has_key(name): self.interfaces[name] = SuseNetworkInterface() for x in cls: try: b = self.app.grab_plugins(INetworkConfigBit, lambda p: p.cls == x)[0] b.iface = self.interfaces[name] self.interfaces[name].bits.append(b) except: pass |
f.write('\n'.join(rcconf[0:insidx]) + '\n') ifcline = 'INTERFACES=(' autos = [] for i in self.interfaces: self.interfaces[i].save(f) if self.interfaces[i].auto: autos.append(i) ifcline += ','.join(autos) + ')\n' f.write(ifcline) f.write('\n'.join(rcconf[insidx:])) | try: f.write('\n'.join(rcconf[0:insidx]) + '\n') autos = [] for i in self.interfaces: self.interfaces[i].save(f) if self.interfaces[i].auto: autos.append(i) ifcline = 'INTERFACES=(' for i in self.interfaces: ifcline += self.interfaces[i].name ifcline += ','.join(autos) + ')\n' f.write(ifcline) f.write('\n'.join(rcconf[... | def save(self): rcconf = open('/etc/rc.conf').read().split('\n') idx = 0 insidx = -1 while idx < len(rcconf): if rcconf[idx].startswith('eth'): # Drop interfaces rcconf.pop(idx) elif rcconf[idx].startswith('INTERFACES'): # Place for new config rcconf.pop(idx) insidx = idx else: idx += 1 f = open('/etc/rc.conf', 'w') f... |
class SuseNetworkInterface(NetworkInterfaceBase): | class ArchNetworkInterface(NetworkInterfaceBase): | def down(self, iface): shell('ifconfig %s down' % iface.name) time.sleep(1) self.rescan() |
'.'.join(platform.python_version_tuple()), | '.'.join([str(x) for x in platform.python_version_tuple()]), | def make_report(app, err): return (('Ajenti %s bug report\n' + '--------------------\n\n' + 'System: %s\n' + 'Detected platform: %s\n' + 'Detected distro: %s\n' + 'Python: %s\n\n' + 'Loaded plugins:\n%s\n\n' + '%s') % (version, shell('uname -a'), detect_platform(), detect_distro(), '.'.join(platform.python_version_tupl... |
self.command = ' '.join(line.split[1:]) | self.command = ' '.join(line.split[1:])\ | def __init__(self, line=''): if not line: self.m, self.h, self.dom, self.mon, self.dow = ['*'] * 5 self.command = '' elif line[0] == '@': self.special = line.split()[0] self.command = ' '.join(line.split[1:]) if line.split()[1] else '' else: params = line.split() self.m, self.h, self.dom, self.mon, self.dow = params[:5... |
path = os.path.join(self.root()+self.config_dir, 'sites-available', mod.name+'.conf') | path = os.path.join(self.root()+self.config_dir, 'mods-available', mod.name+'.conf') | def save_mod(self, mod): path = os.path.join(self.root()+self.config_dir, 'sites-available', mod.name+'.conf') self.open(path, 'w').write(mod.config) |
for s in os.listdir('/etc/init'): if len(s) > 5: s = s[:-5] svc = apis.services.Service() svc.name = s if 'start/running' in shell('service %s status' % s): svc.status = 'running' r.append(svc) found.append(s) elif 'stop/waiting' in shell('service %s status' % s): svc.status = 'stopped' r.append(svc) found.append(s) | if os.path.exists('/etc/init'): for s in os.listdir('/etc/init'): if len(s) > 5: s = s[:-5] svc = apis.services.Service() svc.name = s if 'start/running' in shell('service %s status' % s): svc.status = 'running' r.append(svc) found.append(s) elif 'stop/waiting' in shell('service %s status' % s): svc.status = 'stopped' ... | def list_all(self): r = [] found = [] for s in os.listdir('/etc/init'): if len(s) > 5: s = s[:-5] svc = apis.services.Service() svc.name = s if 'start/running' in shell('service %s status' % s): svc.status = 'running' r.append(svc) found.append(s) elif 'stop/waiting' in shell('service %s status' % s): svc.status = 'st... |
run('rm -r tmp/*') | run('rm -r tmp') | def clean(): run('rm -r tmp/*') run('mkdir tmp') |
UI.Label(text="%sM / %sM"%(ru,rt)), | UI.Label(text="%sM / %sM"%(su,st)), | def get_ui(self): ru, rt = self.get_ram() su, st = self.get_swap() w = UI.Widget( UI.LayoutTable( UI.LayoutTableRow( UI.Image(file='/dl/loadavg/widget_mem.png'), UI.Label(text='RAM:', bold=True), UI.ProgressBar(value=ru, max=rt, width=100), UI.Label(text="%sM / %sM"%(ru,rt)), spacing=4 ), UI.LayoutTableRow( UI.Image(fi... |
s += e.DumpHTML() | if e.Visible: s += e.DumpHTML() | def DumpHTML(self): s = '' if self.Visible: for e in self.Elements: s += e.DumpHTML() |
s += '<td>' + e.DumpHTML() + '</td>' | if e.Visible: s += '<td>' + e.DumpHTML() + '</td>' | def DumpHTML(self): s = '' if self.Visible: s += '<table cellspacing="0" cellpadding="0"><tr>' for e in self.Elements: s += '<td>' + e.DumpHTML() + '</td>' s += '</tr></table>' |
s += '<tr><td>' + e.DumpHTML() + '</td></tr>' | if e.Visible: s += '<tr><td>' + e.DumpHTML() + '</td></tr>' | def DumpHTML(self): s = '' if self.Visible: s += '<table cellspacing="0" cellpadding="0">' for e in self.Elements: s += '<tr><td>' + e.DumpHTML() + '</td></tr>' s += '</table>' |
s += e.DumpHTML() | if e.Visible: s += e.DumpHTML() | def DumpHTML(self): s = '' if self.Visible: s += '<table cellspacing="0" cellpadding="2">' for e in self.Rows: e.Widths = self.Widths s += e.DumpHTML() s += '</table>' |
s += '<td style="padding: 3px;"' if not self.Wide == 0: s += ' colspan="' + str(self.Wide) + '" ' s += ' width="' + str(self.Widths[i]) + '">' + e.DumpHTML() + '</td>' | if e.Visible: s += '<td style="padding: 3px;"' if not self.Wide == 0: s += ' colspan="' + str(self.Wide) + '" ' s += ' width="' + str(self.Widths[i]) + '">' + e.DumpHTML() + '</td>' | def DumpHTML(self): s = '' if self.Wide: self.Widths[0] = "auto" |
s += e.DumpHTML() | if e.Visible: s += e.DumpHTML() | def DumpHTML(self): s = '' if self.Visible: self._lblTitle.Text = self.Title s += self._lblTitle.DumpHTML() + '<br/>' s += '<table cellspacing="0" cellpadding="2" class="ui-el-table">' for e in self.Rows: e.Widths = self.Widths s += e.DumpHTML() s += '</table>' |
s += '<td class="ui-el-table-cell" ' if not self.Wide == 0: s += ' colspan="' + str(self.Wide) + '" ' s += ' width="' + str(self.Widths[i]) + '">' + e.DumpHTML() + '</td>' | if e.Visible: s += '<td class="ui-el-table-cell" ' if not self.Wide == 0: s += ' colspan="' + str(self.Wide) + '" ' s += ' width="' + str(self.Widths[i]) + '">' + e.DumpHTML() + '</td>' | def DumpHTML(self): s = '' if self.Wide: self.Widths[0] = "auto" |
__instances = {} | def __init__(self): self.__instances = {} | def implements (*interfaces): # Get parent exection frame frame = inspect.stack()[1][0] # Get locals from it locals = frame.f_locals if ((locals is frame.f_globals) or ('__module__' not in locals)): raise TypeError('implements() can only be used in class definition') if '_implements' in locals: raise TypeError('imple... |
return new_class if d.get('abstract'): | def __new__ (cls, name, bases, d): """ Create new class """ | |
self._cfg = SquidConfig() | self._cfg = SquidConfig(self.app) | def on_session_start(self): if not is_installed(): return self._tab = 0 self._cfg = SquidConfig() self._cfg.load() |
panel = UI.PluginPanel(UI.Label(text=self._log), | panel = UI.PluginPanel(UI.Label(text='%s tasks' % len(self._tasks)), | def get_ui(self): panel = UI.PluginPanel(UI.Label(text=self._log), title='Crontab', icon='/dl/filesystems/icon.png') panel.appendChild(self.get_default_ui()) return panel |
icon='/dl/filesystems/icon.png') | icon='/dl/cron/icon.png') | def get_ui(self): panel = UI.PluginPanel(UI.Label(text=self._log), title='Crontab', icon='/dl/filesystems/icon.png') panel.appendChild(self.get_default_ui()) return panel |
self._tasks, self._others = backend.read_crontab() | def get_default_ui(self): table = UI.DataTable(UI.DataTableRow( UI.Label(text='Minutes'), UI.Label(text='Hours'), UI.Label(text='Days'), UI.Label(text='Months'), UI.Label(text='DoW'), UI.Label(text='Command'), UI.Label(text=''), header=True, )) self._tasks, self._others = backend.read_crontab() for i, t in enumerate(se... | |
for x in v: n.vars[x[0]] = x[1] | try: for x in v: n.vars[x[0]] = x[1] except: pass | def __init__(self): self.nodes = [] self.vars = [] self.parts = [] if not os.path.exists(self.config_file): return ll = open(self.config_file).read().split('\n') for l in ll: if l != '': if l.startswith('node'): n = ClusterNode() tmp, n.desc, n.address, n.port, n.timestamp, v = l.split(':') v = [x.split('=') for x in ... |
tp = filter(lambda x: x[1] == a[1], self.acl_types)[0][0] | try: tp = filter(lambda x: x[1] == a[1], self.acl_types)[0][0] except: tp = a[1] | def get_ui(self): t = UI.DataTable() t.append(UI.DataTableRow(UI.Label(text='Name'), UI.Label(text='Type'), UI.Label(text='Value'), UI.Label(), header=True)) for a in self.cfg.acls: tp = filter(lambda x: x[1] == a[1], self.acl_types)[0][0] t.append( UI.DataTableRow( UI.Label(text=a[0]), UI.Label(text=tp), UI.Label(text... |
def brdequote(_, s): return dequote(s) | def iif(_, q, a, b): return a if len(q)>0 and q[0].lower() == 'true' else b | |
UI.Label(), | UI.DataTableCell(width=20), | def get_ui(self): ctl = UI.HContainer( UI.Button(text='Refresh', id='refresh'), UI.Button(text='Get lists', id='getlists'), ) panel = UI.PluginPanel(ctl, title='Package Manager', icon='/dl/pkgman/icon.png') pnl = UI.Container() panel.append(pnl) pnl.append(self.get_default_ui()) |
UI.LayoutTableCell( widht=20 | UI.DataTableCell( width=20 | def get_default_ui(self): tbl_pkgs = UI.DataTable( UI.DataTableRow( UI.LayoutTableCell( widht=20 ), UI.Label(text='Name'), UI.Label(text='Version'), UI.Label(text='Description'), UI.Label(), header=True ), width='100%', noborder=True ) if self._current == 'upgrades': for p in sorted(self._status.upgradeable.keys()): p... |
height=100 | height=300 | def get_default_ui(self): tbl_pkgs = UI.DataTable( UI.DataTableRow( UI.LayoutTableCell( widht=20 ), UI.Label(text='Name'), UI.Label(text='Version'), UI.Label(text='Description'), UI.Label(), header=True ), width='100%', noborder=True ) if self._current == 'upgrades': for p in sorted(self._status.upgradeable.keys()): p... |
UI.LayoutTableCell( UI.ScrollContainer( tbl_pkgs, height=300, width=600 ), rowspan=2 ) ), UI.LayoutTableRow( UI.LayoutTableCell( ui_misc, height=100 ) | UI.ScrollContainer( tbl_pkgs, height=300, width=500 ), ui_misc | def get_default_ui(self): tbl_pkgs = UI.DataTable( UI.DataTableRow( UI.LayoutTableCell( widht=20 ), UI.Label(text='Name'), UI.Label(text='Version'), UI.Label(text='Description'), UI.Label(), header=True ), width='100%', noborder=True ) if self._current == 'upgrades': for p in sorted(self._status.upgradeable.keys()): p... |
class PackageManagerContent(ModuleContent): module = 'pkgman' path = __file__ | def on_dialog(self, event, params, vars=None): if params[0] == 'dlgApply': self._confirm_apply = False if vars.getvalue('action', '') == 'OK': self.mgr.apply(self._status) self._in_progress = True self._status.pending = {} if params[0] == 'frmSearch': self._tab = 1 q = vars.getvalue('query','') if q != '': self._search... | |
return self.grab_plugins(iface, flt)[0] | lst = self.grab_plugins(iface, flt) | def get_backend(self, iface, flt=None): try: return self.grab_plugins(iface, flt)[0] except: print traceback.format_exc() raise BackendUnavailableException(iface.__name__, self.platform) |
return lst[0] | def get_backend(self, iface, flt=None): try: return self.grab_plugins(iface, flt)[0] except: print traceback.format_exc() raise BackendUnavailableException(iface.__name__, self.platform) | |
if filter_func: plugins = filter(filter_func, plugins) | if self.filter_func: plugins = filter(self.filter_func, plugins) | def _plugins(self, plugin): """ Returns a list of currently registered plugins for requested interface """ pm = plugin.plugin_manager plugins = pm.plugin_get(self.interface) if filter_func: plugins = filter(filter_func, plugins) return filter(None, [pm.instance_get(cls, True) for cls in plugins]) |
def match(self, uri): if re.match('^/demo',uri): return True else: return False | @url('^/demo') | def match(self, uri): if re.match('^/demo',uri): return True else: return False |
cat_selected = self.app.session.get('cat_selected', 'Dashboard') | def do_init(self): cat_selected = self.app.session.get('cat_selected', 'Dashboard') cat = None for c in self.categories: if c.get_name() == cat_selected: # initialize current plugin cat = c self.selected_category = cat cat.on_init() | |
if c.get_name() == cat_selected: | if c.get_name() == self._cat_selected: | def do_init(self): cat_selected = self.app.session.get('cat_selected', 'Dashboard') cat = None for c in self.categories: if c.get_name() == cat_selected: # initialize current plugin cat = c self.selected_category = cat cat.on_init() |
UI.OutLinkLabel(text='About', url='http://ajenti.assembla.com/wiki/show/ajenti/aLa8XiGfWr36nLeJe5cbLA'), | UI.LinkLabel(text='About', id='about'), | def process(self, req, start_response): self.do_init() |
self.app.session['cat_selected'] = params[0] | self._cat_selected = params[0] | def handle_category(self, event, params, **kw): if not isinstance(params, list): return if len(params) != 1: return |
cat = filter(lambda x: x.get_name() == self.app.session.get('cat_selected', 'Dashboard'), self.categories)[0] | cat = filter(lambda x: x.get_name() == self._cat_selected, self.categories)[0] | def handle_generic(self, req, start_response): # Iterate through the IEventDispatchers and find someone who will take care of the event # TODO: use regexp for shorter event names, ex. 'btn_clickme/click' path = req['PATH_INFO'].split('/') event = '/'.join(path[2:4]) params = path[4:] |
r.appendChild(UI.LogViewerLine(text=s)) | d += s.replace('\n', '<br/>') d = '<span style="font-family: monospace">' + d + '</span>' r.appendChild(UI.CustomHTML(d)) | def format_log(self, data): r = UI.LogViewer(width=600, height=500) for s in data.split('\n'): r.appendChild(UI.LogViewerLine(text=s)) return r |
str(app.class_list()).replace(',','\n'), | pr, | def make_report(app, err): return (('Ajenti %s bug report\n' + '--------------------\n\n' + 'System: %s\n' + 'Detected platform: %s\n' + 'Detected distro: %s\n' + 'Python: %s\n\n' + 'Loaded plugins:\n%s\n\n' + '%s') % (version, shell('uname -a'), detect_platform(), detect_distro(), '.'.join([str(x) for x in platform.py... |
tn = LogTreeNode(os.path.join(self.dir_name), self.owner) | tn = LogTreeNode(os.path.join(self.dir_name, x), self.owner) | def rescan(self): dirList = os.listdir(self.dir_name) dirList.sort() |
ajentid = AjentiDaemon('/tmp/ajenti.pid') | ajentid = AjentiDaemon('./ajenti.pid',stdout='./stdout.log',stderr='./stderr.log') | def usage(): print """ |
return dequote(s) | return dequote(s[0]) | def brdequote(_, s): return dequote(s) |
ready = False | def get_ui_available(self): lst = self._mgr.available inst = self._mgr.list_plugins() btn = UI.Button(text='Check for updates', id='update') if len(lst) == 0: btn['text'] = 'Download plugin list' tbl = UI.LayoutTable() for k in lst: same = False for p in inst: if k['id'] == p.id and k['version'] == p.version: same = ... | |
req if len(reqd)>0 else UI.Label(), | req if not ready else None, | def get_ui_available(self): lst = self._mgr.available inst = self._mgr.list_plugins() btn = UI.Button(text='Check for updates', id='update') if len(lst) == 0: btn['text'] = 'Download plugin list' tbl = UI.LayoutTable() for k in lst: same = False for p in inst: if k['id'] == p.id and k['version'] == p.version: same = ... |
) if len(reqd)==0 else None | ) if ready else None | def get_ui_available(self): lst = self._mgr.available inst = self._mgr.list_plugins() btn = UI.Button(text='Check for updates', id='update') if len(lst) == 0: btn['text'] = 'Download plugin list' tbl = UI.LayoutTable() for k in lst: same = False for p in inst: if k['id'] == p.id and k['version'] == p.version: same = ... |
def handle(self, t, e, d): self.inner.handle(t, e, d) | def dump_HTML(self): s = '<div class="ui-el-treecontainernode-inner">' + self.inner.dump_HTML() + '</div>' return s | |
UI.LayoutTableRow( UI.Label(text='Login: '), UI.TextInput(name='login') ), UI.LayoutTableRow( UI.Label(text='Password: '), UI.TextInput(name='password') | UI.LayoutTable( UI.LayoutTableRow( UI.Label(text='Login: '), UI.TextInput(name='login') ), UI.LayoutTableRow( UI.Label(text='Password: '), UI.TextInput(name='password') ) | def get_ui_sec(self): tbl = UI.DataTable( UI.DataTableRow( UI.DataTableCell(UI.Label(text='Login'), width='200px'), UI.Label(), header=True ) ) for s in self.config.options('users'): tbl.appendChild( UI.DataTableRow( UI.Label(text=s), UI.DataTableCell( UI.MiniButton(text='Delete', id='deluser/'+s), hidden=True ) ) ) o ... |
self._tab = 1 | self._tab = 2 | def on_click(self, event, params, vars=None): if params[0] == 'adduser': self._tab = 1 self._adding_user = True if params[0] == 'deluser': self._tab = 1 self.config.remove_option('users', params[1]) self.config.save() |
self.users[s][l.split(':')[0]] = l.split(':')[1].strip() | def load(self): self.shares = {} ss = open('/etc/samba/smb.conf', 'r').read().split('\n') cs = '' for s in ss: s = s.strip() try: if s[0] != '#' and s[0] != ';': if s[0] == '[': cs = s[1:-1] self.shares[cs] = self.new_share() if cs != 'global' else self.general_defaults.copy() else: s = s.split('=') self.shares[cs][s[0... | |
UI.ProgressBar(value=ru, max=rt, width="100"), | UI.ProgressBar(value=ru, max=rt, width="100") if rt != '0' else None, | def get_ui(self): ru, rt = self.get_swap() w = UI.Widget( UI.HContainer( UI.Image(file='/dl/loadavg/widget_swap.png'), UI.Label(text='Swap:', bold=True), UI.ProgressBar(value=ru, max=rt, width="100"), UI.Label(text="%sM / %sM"%(ru,rt)) ) ) return w |
if e.tag == 'layouttablecell': self.append(e) else: c = UI.LayoutTableCell(e) c['spacing'] = self['spacing'] self.append(c) | if isinstance(e, Element): if e.tag == 'layouttablecell': self.append(e) else: c = UI.LayoutTableCell(e) c['spacing'] = self['spacing'] self.append(c) | def __init__(self, *args, **kwargs): Element.__init__(self, 'layouttablerow', **kwargs) for e in args: if e.tag == 'layouttablecell': self.append(e) else: c = UI.LayoutTableCell(e) c['spacing'] = self['spacing'] self.append(c) |
plugin_manager.instance_set(cls, self) | if not self.multi_instance: plugin_manager.instance_set(cls, self) | def maybe_init(self, plugin_manager, init=init, cls=new_class): if plugin_manager.instance_get(cls) is None: # Plugin is just created if init: try: init(self) except: raise plugin_manager.instance_set(cls, self) |
self = plugin_manager.instance_get(cls) | if not cls.multi_instance: self = plugin_manager.instance_get(cls) | def __new__(cls, *args, **kwargs): """ Returns a class instance, If it already instantiated, return it otherwise return new instance """ if issubclass(cls, PluginManager): # If we also a PluginManager, just create and return self = super(Plugin, cls).__new__(cls) self.plugin_manager = self return self |
for path in find('/tmp').filter(name='*.py'): | for path in find('/tmp').filter(name='*.py', file=True).exclude(mtime__day=13): | def __call__(self, name, stat): dt = getattr(stat, self.type) if not self.op or self.op == 'exact': if isinstance(self.time, datetime.date): return self.render(dt.year == self.time.year and dt.month == self.time.month and dt.day == self.time.day) return self.render(dt == self.time) if isinstance(self.time, datetime.dat... |
self.rules.append(FindTimeRule(n, op, value, exclude=exclude)) | self.rules.append(_FindTimeRule(n, op, value, exclude=exclude)) | def _add_rule(self, data, exclude=False): for name, value in data.items(): n, p, op = name.partition('__') if n == 'name': self.rules.append(_FindNameRule(value, exclude=exclude)) elif n == 'directory': self.rules.append(_FindDirectoryRule(value, exclude=exclude)) elif n == 'file': self.rules.append(_FindFileRule(value... |
opsutils.pushd(self.path1) self.check_path(self.path1) | opsutils.pushd(self.path3) self.check_path(self.path3) | def test_function(self): self.check_path(self.path0) opsutils.pushd(self.path1) self.check_path(self.path1) |
def func(): self.assertEqual(len(opsutils.dirs()), 0) opsutils.pushd(self.path3) func() self.assertEqual(len(opsutils.dirs()), 1) opsutils.pushd(self.path2) self.check_path(self.path2) opsutils.popd() self.check_path(self.path1) | def func(): self.assertEqual(len(opsutils.dirs()), 0) opsutils.pushd(self.path3) | |
self.o = utils.Objectify() | self.o = utils.objectify() | def setUp(self): self.o = utils.Objectify() |
o = utils.Objectify(copy.deepcopy(d)) | o = utils.objectify(copy.deepcopy(d)) | def test_dict(self): d = {'hello': 'world', 'thanks': 'mom'} o = utils.Objectify(copy.deepcopy(d)) self.assertEqual(len(o), len(d)) for key, value in d.items(): self.assertEqual(o[key], value) self.assertEqual(getattr(o, key), value) self.assertEqual(unicode(o), unicode(d)) self.assertEqual(str(o), str(d)) |
if self.no_peek and not self.top_now: | if self.no_peek and not self.top_down: | def __iter__(self): if self.no_peek and not self.top_now: s = stat(self.path) s._directory, s._file = True, False if self._match(self.path, s): yield self.path for root_path, dir_list, file_list in os.walk(self.path): if self.no_peek and not self.top_down: for d in dir_list: path = os.path.join(root_path, d) s = stat(p... |
print locals['self'] | def popd(no_class=False): """Remove last path from the stack and make it the current working directory. By default popd will look for the stack variable in self if in a method and the local scope if in a function. The class behaviour can be disabled by passing no_class=True. popd() """ # Get locals from caller curfram... | |
msg = sys.stdin.readline().rstrip('\r\n') bot.stdio_message(msg) | msg = sys.stdin.read(4096) readbuf += msg splitted = readbuf.split("\r") if len(splitted) > 1: for item in splitted[:-1]: bot.stdio_message(item) readbuf = items[-1] | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
cl=xmpp.Client(jid.getDomain(),debug=["dispatcher"]) | cl=xmpp.Client(jid.getDomain(),debug=['always', 'nodebuilder']) | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
print "Syntax: xtalk configfile JID port callwithssid nodenamewithssid [UNIXEOL]" | print "Syntax: ax25xmpp configfile JID port callwithssid nodenamewithssid [UNIXEOL]" | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
self.jabber.send(m) | self.jabber.send(filter(lambda x: x >= ' ', m)) | def stdio_message(self, message): m = xmpp.protocol.Message(to=self.remotejid,body=message,typ='chat') self.jabber.send(m) pass |
cl=xmpp.Client(jid.getDomain(),debug=[]) | cl=xmpp.Client(jid.getDomain(),debug=["dispatcher"]) | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
m = xmpp.protocol.Message(to=self.remotejid,body=message,typ='chat') | def stdio_message(self, message): m = xmpp.protocol.Message(to=self.remotejid,body=message,typ='chat') # Filter out control characters to avoid not-well-formed errors self.jabber.send(filter(lambda x: x >= ' ', m)) pass | |
self.jabber.send(filter(lambda x: x >= ' ', m)) | txmessage = filter(lambda x: x >= ' ', message) m = xmpp.protocol.Message(to=self.remotejid,body=txmessage,typ='chat') self.jabber.send(m) | def stdio_message(self, message): m = xmpp.protocol.Message(to=self.remotejid,body=message,typ='chat') # Filter out control characters to avoid not-well-formed errors self.jabber.send(filter(lambda x: x >= ' ', m)) pass |
readbuf = items[-1] | readbuf = item[-1] | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
sys.stdout.write("Connection closed.\r\n") | sys.stdout.write("Connection closed.\r") | def xmpp_message(self, con, event): type = event.getType() fromjid = event.getFrom().getStripped() if type in ['message', 'chat', None] and fromjid == self.remotejid: if event.getBody() == '!EX': sys.stdout.write("Connection closed.\r\n") sys.exit(0) if not self.hasresponded: sys.stdout.write("Sysop has responded.\r\n"... |
sys.stdout.write("Sysop has responded.\r\n") | sys.stdout.write("Sysop has responded.\r") | def xmpp_message(self, con, event): type = event.getType() fromjid = event.getFrom().getStripped() if type in ['message', 'chat', None] and fromjid == self.remotejid: if event.getBody() == '!EX': sys.stdout.write("Connection closed.\r\n") sys.exit(0) if not self.hasresponded: sys.stdout.write("Sysop has responded.\r\n"... |
sys.stdout.write(event.getBody() + '\r\n') | sys.stdout.write(event.getBody() + '\r') | def xmpp_message(self, con, event): type = event.getType() fromjid = event.getFrom().getStripped() if type in ['message', 'chat', None] and fromjid == self.remotejid: if event.getBody() == '!EX': sys.stdout.write("Connection closed.\r\n") sys.exit(0) if not self.hasresponded: sys.stdout.write("Sysop has responded.\r\n"... |
sys.stderr.write('could not connect!\r\n') | sys.stderr.write('could not connect!\r') | def xmpp_connect(self): con=self.jabber.connect() if not con: sys.stderr.write('could not connect!\r\n') return False sys.stdout.write("Paging sysop.\r\n") #sys.stderr.write('connected with %s\n'%con) auth=self.jabber.auth(jid.getNode(),jidparams['password'],resource=jid.getResource()) if not auth: sys.stderr.write('co... |
sys.stdout.write("Paging sysop.\r\n") | sys.stdout.write("Paging sysop.\r") | def xmpp_connect(self): con=self.jabber.connect() if not con: sys.stderr.write('could not connect!\r\n') return False sys.stdout.write("Paging sysop.\r\n") #sys.stderr.write('connected with %s\n'%con) auth=self.jabber.auth(jid.getNode(),jidparams['password'],resource=jid.getResource()) if not auth: sys.stderr.write('co... |
sys.stdout.write("ax25xmpp bridge (c) 2010 John Goerzen, 2003-2008 Alexey Nezhdanov\r\n") sys.stdout.write("bridge ready.\r\n") | sys.stdout.write("ax25xmpp bridge (c) 2010 John Goerzen, 2003-2008 Alexey Nezhdanov\r") sys.stdout.write("bridge ready.\r") | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
sys.stderr.write("Could not connect to server, or password mismatch!\r\n") | sys.stderr.write("Could not connect to server, or password mismatch!\r") | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
sys.stdout.write("Connection closed." + EOL) | sys.stdout.write("Connection closed by sysop." + EOL) | def xmpp_message(self, con, event): type = event.getType() fromjid = event.getFrom().getStripped() if type in ['message', 'chat', None] and fromjid == self.remotejid: if event.getBody() == '!EX': sys.stdout.write("Connection closed." + EOL) sys.stdout.flush() sys.exit(0) if not self.hasresponded: sys.stdout.write("Syso... |
if len(sys.argv) < 5: print "Syntax: xtalk configfile JID port callwithssid nodenamewithssid" | if len(sys.argv) < 6: print "Syntax: xtalk configfile JID port callwithssid nodenamewithssid [UNIXEOL]" | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
sys.stdout.write("bridge ready." + EOL) | sys.stdout.write("Bridge ready. Type !EX to close session." + EOL) | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
readbuf = item[-1] | readbuf = splitted[-1] | def xmpp_presence(self, conn, presence_node): #print presence_node if presence_node.getFrom().bareMatch(self.remotejid): if presence_node.getType() == 'subscribe': replypres=xmpp.Presence(typ='subscribed',to=presence_node.getFrom()) conn.send(replypres) replypres.setType('subscribe') conn.send(replypres) elif presence_... |
queryindex = self.queries.index(q) code = q['code'] subj = q['subj'] type = q['type'] req = SRURequest(wskey = self.apikey) req.args['query'] = query try: self.log("Executing query %s of %s '%s'" % (len(self.results)+1, len(self.queries)+1, query)) responsedata = req.get_response().data except urllib2.HTTPError: respon... | if len(recs) != 0: query = self._build_query(q) self.results.append({'code':q['code'],'subj':q['subj'],'type':q['type'],'query':query,'records':recs}) self.queries[self.queries.index(q)]['harvested'] = True elif self._stopped: self._stopped = False self.log("Query limit exceeded. Stopping at %s of %s. Try again tomor... | def harvest(self): if len(self.results) > 0: self.log("Resuming harvest at query %d" % (len(self.results)+1)) for q in self.queries: #q = self.queries.pop() if 'harvested' not in q: # if this query has not been harvested query = self._build_query(q) queryindex = self.queries.index(q) code = q['code'] subj = q['subj'] t... |
self._wait() | def harvest(self): if len(self.results) > 0: self.log("Resuming harvest at query %d" % (len(self.results)+1)) for q in self.queries: #q = self.queries.pop() if 'harvested' not in q: # if this query has not been harvested query = self._build_query(q) queryindex = self.queries.index(q) code = q['code'] subj = q['subj'] t... | |
vars = dict() vars['oclcnum'] = rec['001'].value() vars['title'] = rec['245'].value() htmlfile.write(htmlRecordTemplate.substitute(vars)) | shortrecs[rec['245'].value()] = { 'title':rec['245'].value(), 'oclcnum':rec['001'].value() } for t in sorted(shortrecs): htmlfile.write(htmlRecordTemplate.substitute(shortrecs[t])) | def make_olac_repo(self, templatePrefix, filename): repofile = codecs.open(filename, 'w', 'utf-8') |
def inc(var, dict): if var in dict: dict[var] += 1 else: dict[var] = 1 | def inc(var, dict): if var in dict: dict[var] += 1 else: dict[var] = 1 | |
inc(r['type'], typetotals) inc(r['subj'], subjtotals) | type = r['type'] if type == '': type = '[no type]' subj = r['subj'] if type not in typetotals: typetotals[type] = len(r['records']) else: typetotals[type] += len(r['records']) if subj not in subjtotals: subjtotals[subj] = len(r['records']) else: subjtotals[subj] += len(r['records']) | def inc(var, dict): if var in dict: dict[var] += 1 else: dict[var] = 1 |
for subj in subjtotals: if subjtotals[subj] == 0: subjzeros.append(subj) else: report.write("%s %s\n" % (subj, subjtotals[subj])) | for pair in sorted(subjtotals.items(), reverse=True, key=itemgetter(1)): if pair[1] == 0: subjzeros.append(pair[0]) else: report.write("%s %s\n" % (pair[0], pair[1])) | def inc(var, dict): if var in dict: dict[var] += 1 else: dict[var] = 1 |
report.write("\n\nThe following subject languages returned no results:\n") | report.write("\n\nThe following %s subject languages returned no results:\n" % len(subjzeros)) | def inc(var, dict): if var in dict: dict[var] += 1 else: dict[var] = 1 |
outputFilename = 'worldcat_static.xml' | outputFilename = 'worldcat_repository.xml' | def load_pickle(filename): try: return pickle.load(open(filename)) except: return False |
lowerBound = int(secondsPerQuery / 2) upperBound = int(secondsPerQuery * 1.5) | lowerBound = 0 upperBound = int(secondsPerQuery * 2) | def load_pickle(filename): try: return pickle.load(open(filename)) except: return False |
q = {'code':line[0], 'subj':line[1], 'type':''} | q = {'code':line[0], 'subj':line[1], 'type':'all_types'} | def load_pickle(filename): try: return pickle.load(open(filename)) except: return False |
harvester.make_hit_report('hitreport.txt') print "Hit report written to '%s'" % 'hitreport.txt' | hitreportFilename = '%s_hitreport.txt' % outputFilename harvester.make_hit_report(hitreportFilename) print "Hit report written to '%s'" % hitreportFilename | def load_pickle(filename): try: return pickle.load(open(filename)) except: return False |
slqs = [ | sqls = [ | def check_redundant_identifier(con, archive_id=None): if archive_id is None: slqs = [ "delete from INTEGRITY_CHECK where PROBLEM_CODE='RID'", """ insert into INTEGRITY_CHECK (Object_ID, Value, Problem_Code) select distinct ai.Item_ID, '', 'RID' from ARCHIVED_ITEM ai, METADATA_ELEM me where ai.Item_ID = me.Item_ID and ... |
except urllib2.HTTPError: | except (urllib2.HTTPError, urllib2.URLError), errstr: | def _sru_request(self, query, startNum = 1): # wait a random amount of time self._wait() |
code = q['code'] | def _get_records(self, q): records = [] query = self._build_query(q) code = q['code'] subj = q['subj'] type = q['type'] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.