rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
otitle_runtime = re.compile(r'<span class="gray">(.*?)</span>').findall(content) if otitle_runtime[0]: otitle_runtime = otitle_runtime[0].split(', ') otitle = ', '.join(otitle_runtime[:-1]) runtime = otitle_runtime[-1:][0]
|
otitle = re.compile(r'<span class="gray">(.*?)</span>').findall(content) if otitle[0]: otitle = otitle[0] runtime = None if otitle and otitle.find(', ') != -1: otitle_list = otitle.split(', ') otitle = ', '.join(otitle_list[:-1]) runtime = otitle_list[-1:][0]
|
def parse(self, object, content): ''' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray">Title original original, 90 мин</span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime 90 >>> m.year 1952 >>> m.title_original u'Title original original' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray"></span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime >>> m.title_original >>> m.year 1952 ''' link = re.compile(r'<p class="name"><a href="/level/1/film/(\d+)/[^"]*">(.+?)</a>').findall(content) if link: object.id = self.prepare_int(link[0][0]) object.title = self.prepare_str(link[0][1])
|
>>> movies = Movie.objects.search('Redacted') >>> len(movies) == 1 True >>> m = movies[0] >>> m.id 278229 >>> m.year 2007 >>> m.title u'\u0411\u0435\u0437 \u0446\u0435\u043d\u0437\u0443\u0440\u044b' >>> m.title_original u'Redacted' >>> m.plot u'\u0412 \u0446\u0435\u043d\u0442\u0440\u0435 \u043a\u0430\u0440\u0442\u0438\u043d\u044b - \u043d\u0435\u0431\u043e\u043b\u044c\u0448\u043e\u0439 \u043e\u0442\u0440\u044f\u0434 \u0430\u043c\u0435\u0440\u0438\u043a\u0430\u043d\u0441\u043a\u0438\u0445 \u0441\u043e\u043b\u0434\u0430\u0442 \u043d\u0430 \u043a\u043e\u043d\u0442\u0440\u043e\u043b\u044c\u043d\u043e-\u043f\u0440\u043e\u043f\u0443\u0441\u043a\u043d\u043e\u043c \u043f\u0443\u043d\u043a\u0442\u0435 \u0432 \u0418\u0440\u0430\u043a\u0435. \u041f\u0440\u0438\u0447\u0451\u043c \u0432\u043e\u0441\u043f\u0440\u0438\u044f\u0442\u0438\u0435 \u0438\u0445 \u0438\u0441\u0442\u043e\u0440\u0438\u0438 \u043f\u043e\u0441\u0442\u043e\u044f\u043d\u043d\u043e \u043c\u0435\u043d\u044f\u0435\u0442\u0441\u044f. \u041c\u044b \u0432\u0438\u0434\u0438\u043c \u0441\u043e\u0431\u044b\u0442\u0438\u044f \u0433\u043b\u0430\u0437\u0430\u043c\u0438 \u0441\u0430\u043c\u0438\u0445 \u0441\u043e\u043b\u0434\u0430\u0442, \u043f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u0438\u0442\u0435\u043b\u0435\u0439 \u0421\u041c\u0418, \u0438\u0440\u0430\u043a\u0446\u0435\u0432, \u0438 \u043f\u043e\u043d\u0438\u043c\u0430\u0435\u043c, \u043a\u0430\u043a \u043d\u0430 \u043a\u0430\u0436\u0434\u043e\u0433\u043e \u0438\u0437 \u043d\u0438\u0445 \u0432\u043b\u0438\u044f\u0435\u0442 \u043f\u0440\u043e\u0438\u0441\u0445\u043e\u0434\u044f\u0449\u0435\u0435, \u0438\u0445 \u0432\u0441\u0442\u0440\u0435\u0447\u0438 \u0438 \u0441\u0442\u043e\u043b\u043a\u043d\u043e\u0432\u0435\u043d\u0438\u044f \u0434\u0440\u0443\u0433 \u0441 \u0434\u0440\u0443\u0433\u043e\u043c.' >>> m.runtime u'90 \u043c\u0438\u043d.' >>> m.tagline u'"\u0424\u0438\u043b\u044c\u043c, \u0437\u0430\u043f\u0440\u0435\u0449\u0435\u043d\u043d\u044b\u0439 \u043a \u043f\u0440\u043e\u043a\u0430\u0442\u0443 \u0432\u043e \u043c\u043d\u043e\u0433\u0438\u0445 \u0441\u0442\u0440\u0430\u043d\u0430\u0445"' >>> movies = Movie.objects.search('pulp fiction') >>> len(movies) > 1 True >>> m = movies[0] >>> m.id 342 >>> m.title u'\u041a\u0440\u0438\u043c\u0438\u043d\u0430\u043b\u044c\u043d\u043e\u0435 \u0447\u0442\u0438\u0432\u043e' >>> m.year 1994 >>> m.title_original u'Pulp Fiction'
|
def get_posters(self): title = self.title.replace(' ', '-') if self.title else 'Title' return ['http://st3.kinopoisk.ru/im/poster/1/1/1/kinopoisk.ru-%s-%d.jpg' % (title, id) for id in self.posters]
|
|
content_results = content[content.find(u'<!-- результаты поиска -->'):content.find(u'<!-- /результаты поиска -->')]
|
content_results = content[content.find('<table cellspacing=0 cellpadding=0 width=100% border=0>'):content.find('<div style="margin-left: -20px">')]
|
def search(self, query): url, params = self.get_url_with_params(query) request = UrlRequest(url, params) content = request.read() # request is redirected to main page of objec if request.is_redirected: object = self.kinopoisk_object() object.parse('main_page', content) return [object] else: content_results = content[content.find(u'<!-- результаты поиска -->'):content.find(u'<!-- /результаты поиска -->')] if content_results: soup_results = BeautifulSoup(content_results) tds = soup_results.findAll('td', attrs={'class': 'news'}) if not tds: raise ValueError('No objects found in search results by request "%s"', request.url) objects = [] for td in tds: link_str = unicode(td.parent) + unicode(td.parent.nextSibling.nextSibling) object = self.kinopoisk_object() object.parse('link', link_str) if object.id: objects += [object] return objects
|
>>> m.parse('link', u'<div class="element width_2"> \ <span class="gray"></span> \ </div>')
|
>>> m.parse('link', u'<div class="element width_2"><span class="gray"></span></div>')
|
def parse(self, object, content): ''' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray">Title original original, 90 мин</span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime 90 >>> m.year 1952 >>> m.title_original u'Title original original' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray"></span> \ </div>') >>> m.runtime >>> m.title_original >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray">Ultimate Taboo</span> \ </div>') >>> m.runtime >>> m.title_original u'Ultimate Taboo' ''' link = re.compile(r'<p class="name"><a href="/level/1/film/(\d+)/[^"]*">(.+?)</a>').findall(content) if link: object.id = self.prepare_int(link[0][0]) object.title = self.prepare_str(link[0][1])
|
>>> m.parse('link', u'<div class="element width_2"> \ <span class="gray">Ultimate Taboo</span> \ </div>')
|
>>> m.parse('link', u'<div class="element width_2"><span class="gray">Zdar Buh, hosi!</span></div>')
|
def parse(self, object, content): ''' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray">Title original original, 90 мин</span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime 90 >>> m.year 1952 >>> m.title_original u'Title original original' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray"></span> \ </div>') >>> m.runtime >>> m.title_original >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray">Ultimate Taboo</span> \ </div>') >>> m.runtime >>> m.title_original u'Ultimate Taboo' ''' link = re.compile(r'<p class="name"><a href="/level/1/film/(\d+)/[^"]*">(.+?)</a>').findall(content) if link: object.id = self.prepare_int(link[0][0]) object.title = self.prepare_str(link[0][1])
|
u'Ultimate Taboo'
|
u'Zdar Buh, hosi!'
|
def parse(self, object, content): ''' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray">Title original original, 90 мин</span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime 90 >>> m.year 1952 >>> m.title_original u'Title original original' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray"></span> \ </div>') >>> m.runtime >>> m.title_original >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray">Ultimate Taboo</span> \ </div>') >>> m.runtime >>> m.title_original u'Ultimate Taboo' ''' link = re.compile(r'<p class="name"><a href="/level/1/film/(\d+)/[^"]*">(.+?)</a>').findall(content) if link: object.id = self.prepare_int(link[0][0]) object.title = self.prepare_str(link[0][1])
|
otitle = re.compile(r'<span class="gray">(.*?)</span>').findall(content)
|
otitle = re.compile(r'<span class="gray">([^<]*?)(?:, (\d+) [^<]+)?</span>').findall(content)
|
def parse(self, object, content): ''' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray">Title original original, 90 мин</span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime 90 >>> m.year 1952 >>> m.title_original u'Title original original' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray"></span> \ </div>') >>> m.runtime >>> m.title_original >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray">Ultimate Taboo</span> \ </div>') >>> m.runtime >>> m.title_original u'Ultimate Taboo' ''' link = re.compile(r'<p class="name"><a href="/level/1/film/(\d+)/[^"]*">(.+?)</a>').findall(content) if link: object.id = self.prepare_int(link[0][0]) object.title = self.prepare_str(link[0][1])
|
otitle = otitle[0] runtime = None if otitle and otitle.find(', ') != -1: otitle_list = otitle.split(', ') otitle = ', '.join(otitle_list[:-1]) runtime = otitle_list[-1:][0] if otitle: object.title_original = self.prepare_str(otitle) if runtime: object.runtime = self.prepare_int(re.sub(r'^(\d+) .+$', r'\1', runtime))
|
if otitle[0][0]: object.title_original = self.prepare_str(otitle[0][0]) if otitle[0][1]: object.runtime = self.prepare_int(otitle[0][1])
|
def parse(self, object, content): ''' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray">Title original original, 90 мин</span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime 90 >>> m.year 1952 >>> m.title_original u'Title original original' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray"></span> \ </div>') >>> m.runtime >>> m.title_original >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <span class="gray">Ultimate Taboo</span> \ </div>') >>> m.runtime >>> m.title_original u'Ultimate Taboo' ''' link = re.compile(r'<p class="name"><a href="/level/1/film/(\d+)/[^"]*">(.+?)</a>').findall(content) if link: object.id = self.prepare_int(link[0][0]) object.title = self.prepare_str(link[0][1])
|
<p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \
|
<p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year">1952</span></p> \
|
def parse(self, object, content): ''' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray">Title original original, 90 мин</span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime 90 >>> m.year 1952 >>> m.title_original u'Title original original' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"><span class="gray"></span></div>') >>> m.runtime >>> m.title_original >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"><span class="gray">Zdar Buh, hosi!</span></div>') >>> m.runtime >>> m.title_original u'Zdar Buh, hosi!' ''' link = re.compile(r'<p class="name"><a href="/level/1/film/(\d+)/[^"]*">(.+?)</a>').findall(content) if link: object.id = self.prepare_int(link[0][0]) object.title = self.prepare_str(link[0][1])
|
year = re.compile(r'<a href="/level/10/m_act\[year\]/(\d{4})/"').findall(content)
|
year = re.compile(r'<span class="year">(\d{4})</span>').findall(content)
|
def parse(self, object, content): ''' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"> \ <p class="pic"><a href="/level/1/film/179805/sr/1/"><img src="/images/sm_film/6505.jpg" alt="Title" title="Title" /></a></p> \ <div class="info"> \ <p class="name"><a href="/level/1/film/179805/sr/1/">Title</a>, <span class="year"><a href="/level/10/m_act[year]/1952/">1952</a></span></p> \ <span class="gray">Title original original, 90 мин</span> \ <span class="gray">США, <i class="director">реж. <a class="lined" href="/level/4/people/28795/">Эрик Бросс</a></i> \ <br />(триллер, комедия) \ </span> \ <span class="gray"><a class="lined" href="/level/4/people/28798/">МакКензи Эстин</a>, <a class="lined" href="/level/4/people/3497/">Тодд Филд</a></span> \ </div>') >>> m.title u'Title' >>> m.id 179805 >>> m.runtime 90 >>> m.year 1952 >>> m.title_original u'Title original original' >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"><span class="gray"></span></div>') >>> m.runtime >>> m.title_original >>> m = Movie() >>> m.parse('link', u'<div class="element width_2"><span class="gray">Zdar Buh, hosi!</span></div>') >>> m.runtime >>> m.title_original u'Zdar Buh, hosi!' ''' link = re.compile(r'<p class="name"><a href="/level/1/film/(\d+)/[^"]*">(.+?)</a>').findall(content) if link: object.id = self.prepare_int(link[0][0]) object.title = self.prepare_str(link[0][1])
|
ignores_i = anythnig("Which factoid requets should the bot always ignore?", default=', '.join(Encyclopedia.ignores._default)) for name in re.split(r',?\s', +ignore_i):
|
ignores_i = anything("Which factoid requets should the bot always ignore?", default=', '.join(Encyclopedia.ignores._default)) for name in re.split(r',?\s', ignores_i):
|
def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default)
|
curStabel = something("What is short name of the current stable release?", default=Encyclopedia.curStable._default)
|
curStable = something("What is short name of the current stable release?", default=Encyclopedia.curStable._default)
|
def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default)
|
curLTSong = something("What is long name of the current LTS release?", default=Encyclopedia.curLTSLoong._default)
|
curLTSLong = something("What is long name of the current LTS release?", default=Encyclopedia.curLTSLong._default)
|
def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default)
|
curStabel = Encyclopedia.curStable._default
|
curStable = Encyclopedia.curStable._default
|
def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default)
|
con.begin()
|
def anything(prompt, default=None): """Because supybot is pure fail""" from supybot.questions import expect return expect(prompt, [], default=default)
|
|
def __init__(self, function, timeout=MAX_TIMEOUT):
|
def __init__(self, function, timeout=CON_TIMEOUT):
|
def __init__(self, function, timeout=MAX_TIMEOUT):
|
self.log.debug("Connection to the server failed/other error:%s" %sys.exc_info())
|
self.log.debug("Connection to the server failed/other error:%s",sys.exc_info())
|
def _connect(self, server, proxy): try: if proxy: self.log.debug("Trying proxied connection... (%r)"% proxy) self.proxied_transport = ProxiedTransport() self.proxied_transport.set_proxy(proxy) self.xmlrpc_server = ServerProxy(server, transport=self.proxied_transport, allow_none=True) #self.ServerInfo() self.log.debug("...connected") return True elif test_connection(server): self.log.debug("Trying direct connection...") self.xmlrpc_server = ServerProxy(server, allow_none=True) #self.ServerInfo() self.log.debug("...connected") return True else: self.log.debug("...failed") self.log.error("Unable to connect. Try setting a proxy.") return False
|
login = TimeoutFunction(self._login) try:
|
try: login = TimeoutFunction(self._login)
|
def login(self, username="", password=""): login = TimeoutFunction(self._login) try: return login(username, password) except TimeoutFunctionException: self.log.error("login timed out")
|
self.log.debug("Login ended in %s with status: %s"% (info['seconds'], info['status']))
|
self._token = None return False
|
def _login(self, username="", password=""): """Login to the Server using username/password, empty parameters means an anonymously login Returns True if login sucessful, and False if not. """ self.log.debug("----------------") self.log.debug("Logging in (username: %s)..."% username)
|
logout = TimeoutFunction(self._logout) try:
|
try: logout = TimeoutFunction(self._logout)
|
def logout(self): logout = TimeoutFunction(self._logout) try: return logout() except TimeoutFunctionException: self.log.error("logout timed out")
|
info = self.xmlrpc_server.LogOut(self._token) self.log.debug("Logout ended in %s with status: %s"% (info['seconds'], info['status'])) self._token = None
|
try: info = self.xmlrpc_server.LogOut(self._token) self.log.debug("Logout ended in %s with status: %s"% (info['seconds'], info['status'])) except xmlrpclib.ProtocolError, e: self.log.debug("error in HTTP/HTTPS transport layer") raise e except xmlrpclib.Fault, e: self.log.debug("error in xml-rpc server") raise e except: self.log.debug("Connection to the server failed/other error:%s",sys.exc_info()) raise e finally: self._token = None
|
def _logout(self): """Logout from current session(token) This functions doesn't return any boolean value, since it can 'fail' for anonymous logins """ self.log.debug("Logging out from session ID: %s"% self._token) info = self.xmlrpc_server.LogOut(self._token) self.log.debug("Logout ended in %s with status: %s"% (info['seconds'], info['status'])) # force token reset self._token = None
|
info = self.xmlrpc_server.GetSubLanguages(language) self.log.debug("GetSubLanguages complete in %s"% info['seconds']) if language: for lang in info['data']: if lang['ISO639'] == language: return lang['SubLanguageID'] return info['data']
|
try: info = self.xmlrpc_server.GetSubLanguages(language) self.log.debug("GetSubLanguages complete in %s"% info['seconds']) if language: for lang in info['data']: if lang['ISO639'] == language: return lang['SubLanguageID'] return info['data'] except xmlrpclib.ProtocolError, e: self.log.debug("error in HTTP/HTTPS transport layer") raise e except xmlrpclib.Fault, e: self.log.debug("error in xml-rpc server") raise e except: self.log.debug("Connection to the server failed/other error:%s",sys.exc_info()) raise e
|
def _GetSubLanguages(self, language): """Return all suported subtitles languages in a dictionary If language var is set, returns SubLanguageID for it """ self.log.debug("----------------") self.log.debug("GetSubLanguages RPC method starting...") if language == "all": # return result right away if no 'translation' needed return "all" info = self.xmlrpc_server.GetSubLanguages(language) self.log.debug("GetSubLanguages complete in %s"% info['seconds']) if language: for lang in info['data']: if lang['ISO639'] == language: return lang['SubLanguageID'] return info['data']
|
info = self.xmlrpc_server.CheckSubHash(self._token,hashes) self.log.debug("CheckSubHash ended in %s with status: %s"% (info['seconds'], info['status'])) result = {} for hash in hashes: result[hash] = info['data'][hash] return result
|
try: info = self.xmlrpc_server.CheckSubHash(self._token,hashes) self.log.debug("CheckSubHash ended in %s with status: %s"% (info['seconds'], info['status'])) result = {} for hash in hashes: result[hash] = info['data'][hash] return result except xmlrpclib.ProtocolError, e: self.log.debug("error in HTTP/HTTPS transport layer") raise e except xmlrpclib.Fault, e: self.log.debug("error in xml-rpc server") raise e except: self.log.debug("Connection to the server failed/other error:%s",sys.exc_info()) raise e
|
def _CheckSubHash(self, hashes): """ @hashes = list of subtitle hashes or video object returns: dictionary like { hash: subID } This method returns !IDSubtitleFile, if Subtitle Hash exists. If not exists, it returns '0'. """ self.log.debug("----------------") self.log.debug("CheckSubHash RPC method starting...") if isinstance(hashes, videofile.VideoFile): self.log.debug("Video object parameter detected. Extracting hashes...") video = hashes hashes = [] for sub in video.getSubtitles(): hashes.append(sub.getHash()) self.log.debug("...done") info = self.xmlrpc_server.CheckSubHash(self._token,hashes) self.log.debug("CheckSubHash ended in %s with status: %s"% (info['seconds'], info['status'])) result = {} for hash in hashes: result[hash] = info['data'][hash]
|
answer = self.xmlrpc_server.DownloadSubtitles(self._token, subtitles_to_download.keys()) self.log.debug("DownloadSubtitles finished in %s with status %s."% (answer['seconds'], answer['status'])) if answer.has_key("data"): if answer['data'] == False: self.log.info("Error downloading subtitle.")
|
try: answer = self.xmlrpc_server.DownloadSubtitles(self._token, subtitles_to_download.keys()) self.log.debug("DownloadSubtitles finished in %s with status %s."% (answer['seconds'], answer['status'])) except xmlrpclib.ProtocolError, e: self.log.debug("error in HTTP/HTTPS transport layer") raise e except xmlrpclib.Fault, e: self.log.debug("error in xml-rpc server") raise e except: self.log.debug("Connection to the server failed/other error:%s",sys.exc_info()) raise e else: if answer.has_key("data"): if answer['data'] == False: self.log.info("Error downloading subtitle.") return False self.log.debug("Got %i subtitles from server. Uncompressing data..."% len(answer['data'])) for sub in answer['data']: self.BaseToFile(sub['data'], subtitles_to_download[sub['idsubtitlefile']]) return answer['data'] else: self.log.info("Server sent no subtitles to me.")
|
def _DownloadSubtitles(self, subtitles): #TODO: decide wheter this should save the subtitle (as it does atm) or just return the encoded data #Note ivan: in my GUI before I replace the file I'll show a confirmation code """ Download subtitles by there id's @subtitles: dictionary with subtitle id's and their path - { id: "path_to_save", ...} Returns: BASE64 encoded gzipped !IDSubtitleFile(s). You need to BASE64 decode and ungzip 'data' to get its contents. """ self.log.debug("----------------") self.log.debug("DownloadSubtitles RPC method starting...") subtitles_to_download = subtitles self.log.debug("Acting in: %r"% subtitles) if len(subtitles_to_download): self.log.debug("Communicating with server...") self.log.debug("xmlrpc_server.DownloadSubtitles(%s,%r)" %(self._token, subtitles_to_download.keys())) answer = self.xmlrpc_server.DownloadSubtitles(self._token, subtitles_to_download.keys()) self.log.debug("DownloadSubtitles finished in %s with status %s."% (answer['seconds'], answer['status'])) if answer.has_key("data"): if answer['data'] == False: #TODO support passing the reason of the erorr to be shown in the GUI self.log.info("Error downloading subtitle.") return False self.log.debug("Got %i subtitles from server. Uncompressing data..."% len(answer['data'])) for sub in answer['data']: #self.log.info("%s -> %s"% (subtitles_to_download[sub['idsubtitlefile']]['subtitle_path'], subtitles_to_download[sub['idsubtitlefile']]['video'].getFileName())) self.BaseToFile(sub['data'], subtitles_to_download[sub['idsubtitlefile']]) return answer['data'] else: self.log.info("Server sent no subtitles to me.") return False
|
self.log.debug("Got %i subtitles from server. Uncompressing data..."% len(answer['data'])) for sub in answer['data']: self.BaseToFile(sub['data'], subtitles_to_download[sub['idsubtitlefile']]) return answer['data'] else: self.log.info("Server sent no subtitles to me.") return False
|
def _DownloadSubtitles(self, subtitles): #TODO: decide wheter this should save the subtitle (as it does atm) or just return the encoded data #Note ivan: in my GUI before I replace the file I'll show a confirmation code """ Download subtitles by there id's @subtitles: dictionary with subtitle id's and their path - { id: "path_to_save", ...} Returns: BASE64 encoded gzipped !IDSubtitleFile(s). You need to BASE64 decode and ungzip 'data' to get its contents. """ self.log.debug("----------------") self.log.debug("DownloadSubtitles RPC method starting...") subtitles_to_download = subtitles self.log.debug("Acting in: %r"% subtitles) if len(subtitles_to_download): self.log.debug("Communicating with server...") self.log.debug("xmlrpc_server.DownloadSubtitles(%s,%r)" %(self._token, subtitles_to_download.keys())) answer = self.xmlrpc_server.DownloadSubtitles(self._token, subtitles_to_download.keys()) self.log.debug("DownloadSubtitles finished in %s with status %s."% (answer['seconds'], answer['status'])) if answer.has_key("data"): if answer['data'] == False: #TODO support passing the reason of the erorr to be shown in the GUI self.log.info("Error downloading subtitle.") return False self.log.debug("Got %i subtitles from server. Uncompressing data..."% len(answer['data'])) for sub in answer['data']: #self.log.info("%s -> %s"% (subtitles_to_download[sub['idsubtitlefile']]['subtitle_path'], subtitles_to_download[sub['idsubtitlefile']]['video'].getFileName())) self.BaseToFile(sub['data'], subtitles_to_download[sub['idsubtitlefile']]) return answer['data'] else: self.log.info("Server sent no subtitles to me.") return False
|
|
info = self.xmlrpc_server.CheckSoftwareUpdates(app) self.log.debug("Latest SubDownloader Version Found: %s"% info['latest_version']) return info
|
try: info = self.xmlrpc_server.CheckSoftwareUpdates(app) except xmlrpclib.ProtocolError, e: self.log.debug("error in HTTP/HTTPS transport layer") raise e except xmlrpclib.Fault, e: self.log.debug("error in xml-rpc server") raise e except Exception,e: self.log.debug("Connection to the server failed/other error:%s",sys.exc_info()) raise e else: self.log.debug("Latest SubDownloader Version Found: %s"% info['latest_version']) return info
|
def _CheckSoftwareUpdates(self, app=None): """Returns latest info on the given application if available """ self.log.debug("----------------") self.log.debug("CheckSoftwareUpdates RPC method starting...") if not app: app = APP_TITLE.lower() info = self.xmlrpc_server.CheckSoftwareUpdates(app)
|
NoOperation = TimeoutFunction(self._NoOperation) try:
|
try: NoOperation = TimeoutFunction(self._NoOperation)
|
def NoOperation(self, token=None): NoOperation = TimeoutFunction(self._NoOperation) try: return NoOperation() except TimeoutFunctionException: self.log.error("NoOperation timed out")
|
info = self.xmlrpc_server.NoOperation(self._token) self.log.debug("NoOperation finished in %s with status %s."% (info['seconds'], info['status'])) self.log.debug("----------------") if info['status'] != "200 OK": return False return True
|
noop=False try: info = self.xmlrpc_server.NoOperation(self._token) self.log.debug("NoOperation finished in %s with status %s."% (info['seconds'], info['status'])) self.log.debug("----------------") if info['status'] == "200 OK": return True else: return noop except xmlrpclib.ProtocolError, e: self.log.debug("error in HTTP/HTTPS transport layer") raise e except xmlrpclib.Fault, e: self.log.debug("error in xml-rpc server") raise e except: self.log.debug("Connection to the server failed/other error:%s",sys.exc_info()) raise e
|
def _NoOperation(self): """This method should be called every 15 minutes after last request to xmlrpc. It's used to keep current session alive. Returns True if current session token is valid and False if not. """ self.log.debug("----------------") self.log.debug("NoOperation RPC method starting...") info = self.xmlrpc_server.NoOperation(self._token) self.log.debug("NoOperation finished in %s with status %s."% (info['seconds'], info['status'])) self.log.debug("----------------") if info['status'] != "200 OK": return False return True
|
info = self.xmlrpc_server.SearchToMail(self._token, languages, video_array) self.log.debug("SearchToMail finished in %s with status %s."% (info['seconds'], info['status']))
|
try: info = self.xmlrpc_server.SearchToMail(self._token, languages, video_array) self.log.debug("SearchToMail finished in %s with status %s."% (info['seconds'], info['status'])) except xmlrpclib.ProtocolError, e: self.log.debug("error in HTTP/HTTPS transport layer") raise e except xmlrpclib.Fault, e: self.log.debug("error in xml-rpc server") raise e except: self.log.debug("Connection to the server failed/other error:%s",sys.exc_info()) raise e
|
def _SearchToMail(self, videos, languages): """Register user email to be noticed when given video subtitles are available to download @videos: video objects - list @languages: language id codes - list """ self.log.debug("----------------") self.log.debug("SearchToMail RPC method starting...") video_array = [] for video in videos: array = {'moviehash': video.getHash(), 'moviesize': video.getSize()} video_array.append(array) info = self.xmlrpc_server.SearchToMail(self._token, languages, video_array) self.log.debug("SearchToMail finished in %s with status %s."% (info['seconds'], info['status']))
|
print(' File "$DIST_DIR\\luaui.lua"')
|
print(' File "${DIST_DIR}\\luaui.lua"')
|
print('!ifdef INSTALL')
|
print(' File "$DIST_DIR\\' + osName(d) + osName(f) + '"')
|
print(' File "${DIST_DIR}\\' + osName(d) + osName(f) + '"')
|
print('!ifdef INSTALL')
|
addr2line = Popen([ADDR2LINE, '-e', tempfile.name], stdin = PIPE, stdout = PIPE, stderr = PIPE)
|
addr2line = Popen([ADDR2LINE, '-j', '.text', '-e', tempfile.name], stdin = PIPE, stdout = PIPE, stderr = PIPE)
|
def translate_module_addresses(module, debugfile, addresses): '''\ Translate addresses in a module to (module, address, filename, lineno) tuples by invoking addr2line exactly once on the debugging symbols for that module. ''' with NamedTemporaryFile() as tempfile: log.info('\tExtracting debug symbols for module %s from archive %s...' % (module, os.path.basename(debugfile))) # e = extract without path, -so = write output to stdout, -y = yes to all questions sevenzip = Popen([SEVENZIP, 'e', '-so', '-y', debugfile], stdout = tempfile, stderr = PIPE) stdout, stderr = sevenzip.communicate() if stderr: log.debug('%s stderr: %s' % (SEVENZIP, stderr)) if sevenzip.returncode != 0: fatal('%s exited with status %s' % (SEVENZIP, sevenzip.returncode)) log.info('\t\t[OK]') log.info('\tTranslating addresses for module %s...' % module) addr2line = Popen([ADDR2LINE, '-e', tempfile.name], stdin = PIPE, stdout = PIPE, stderr = PIPE) if addr2line.poll() == None: stdout, stderr = addr2line.communicate('\n'.join(addresses)) else: stdout, stderr = addr2line.communicate() if stderr: log.debug('%s stderr: %s' % (ADDR2LINE, stderr)) if addr2line.returncode != 0: fatal('%s exited with status %s' % (ADDR2LINE, addr2line.returncode)) log.info('\t\t[OK]') def fixup(addr, file, line): for psu in PATH_STRIP_UNTIL: if psu in file: file = file[file.index(psu)+len(psu):] break return module, addr, file, int(line) return [fixup(addr, *line.split(':')) for addr, line in zip(addresses, stdout.splitlines())]
|
distDirCandidates = [sys.argv[1], 'dist', 'game', 'cont']
|
if len(sys.argv) > 1: baseDir = sys.argv[1] else: baseDir = os.path.join(sys.path[0], '..') distDirCandidates = ['dist', 'game', 'cont'] luaUIDir = 'LuaUI' distBase = '${DIST_DIR}' instBase = '${INSTDIR}' os.chdir(sys.path[0]) os.chdir('..')
|
# !ifdef INSTALL
|
os.chdir(distDir)
|
os.chdir(os.path.join(distDir, luaUIDir))
|
# !ifdef INSTALL
|
distDir = os.path.join('..', distDir) try: os.chdir(distDir) break except OSError: distDir = "" continue
|
distDir = ""
|
# !ifdef INSTALL
|
sys.exit(1); top = 'LuaUI/'
|
sys.exit(1) else: os.chdir(os.path.join(baseDir, distDir))
|
# !ifdef INSTALL
|
dirs[path] = [] filelist = os.listdir(path) for f in filelist: fullname = path + f if os.path.isdir(fullname): if (f != 'Config') and (f != '.git'): fullname = fullname + '/' GetDirs(fullname, dirs) else: dirs[path].append(f)
|
dirs[path] = [] filelist = os.listdir(path) for f in filelist: fullname = os.path.join(path, f) if os.path.isdir(fullname): if (f != 'Config') and (f != '.git'): GetDirs(fullname, dirs) else: dirs[path].append(f)
|
def GetDirs(path, dirs): dirs[path] = [] filelist = os.listdir(path) for f in filelist: fullname = path + f if os.path.isdir(fullname): if (f != 'Config') and (f != '.git'): fullname = fullname + '/' GetDirs(fullname, dirs) else: dirs[path].append(f)
|
def osName(path): return path.replace('/', '\\')
|
def toWinPath(path): return path.replace('/', '\\')
|
def osName(path): return path.replace('/', '\\')
|
GetDirs(top, dirs)
|
GetDirs(luaUIDir, dirs)
|
def osName(path): return path.replace('/', '\\')
|
print(' SetOutPath "$INSTDIR"') print(' File "${DIST_DIR}\\luaui.lua"')
|
print(' ; Purge old file from 0.75 install.') print(' Delete "' + instBase + '\LuaUI\unitdefs.lua"') print('') print(' SetOutPath "' + instBase + '"') print(' File "' + toWinPath(os.path.join(distBase, distDir, 'luaui.lua')) + '"')
|
print('!ifdef INSTALL')
|
print(' SetOutPath "$INSTDIR\\' + osName(d) + '"') for f in dirs[d]: print(' File "${DIST_DIR}\\' + osName(d) + osName(f) + '"')
|
print(' SetOutPath "' + toWinPath(os.path.join(instBase, d)) + '"') for f in dirs[d]: print(' File "' + toWinPath(os.path.join(distBase, distDir, d, f)) + '"')
|
print('!ifdef INSTALL')
|
print(' Delete "$INSTDIR\\luaui.lua"')
|
print(' Delete "' + toWinPath(os.path.join(instBase, 'luaui.lua')) + '"')
|
print('!ifdef INSTALL')
|
for f in dirs[d]: print(' Delete "$INSTDIR\\' + osName(d) + osName(f) + '"') print(' RmDir "$INSTDIR\\' + osName(d) + '"')
|
for f in dirs[d]: print(' Delete "' + toWinPath(os.path.join(instBase, d, f)) + '"') print(' RmDir "' + toWinPath(os.path.join(instBase, d)) + '"')
|
print('!ifdef INSTALL')
|
print(' RmDir "$INSTDIR\\LuaUI"')
|
print(' RmDir "' + toWinPath(os.path.join(instBase, luaUIDir)) + '"')
|
print('!ifdef INSTALL')
|
instBase = '${INSTDIR}'
|
instBase = '$INSTDIR'
|
# !ifdef INSTALL
|
def common_suffix_length(a, b): '''\ Compute the length of the common suffix of a and b, considering / and \ equal. >>> common_suffix_length('/foo/bar/baz', '\\\\other\\\\bar\\\\baz') 8 >>> common_suffix_length('bar', 'foo/bar') 3 >>> common_suffix_length('bar', 'bar') 3 ''' a = a.replace('\\', '/') b = b.replace('\\', '/') min_length = min(len(a), len(b)) for i in range(-1, -min_length - 1, -1): if a[i] != b[i]: return -i - 1 return min_length
|
def common_suffix_length(a, b): '''\ Compute the length of the common suffix of a and b, considering / and \ equal. >>> common_suffix_length('/foo/bar/baz', '\\\\other\\\\bar\\\\baz') 8 >>> common_suffix_length('bar', 'foo/bar') 3 >>> common_suffix_length('bar', 'bar') 3 ''' a = a.replace('\\', '/') b = b.replace('\\', '/') min_length = min(len(a), len(b)) for i in range(-1, -min_length - 1, -1): if a[i] != b[i]: return -i - 1 return min_length
|
|
Unfortunately if the correct module isn't available the closest match can be wrong: >>> best_matching_module('c:/Program Files/Spring/AI/Skirmish/UnknownAI/SkirmishAI.dll', modules)
|
>>> best_matching_module('c:/Spring/NullAI/0.0.1/SkirmishAI.dll', modules)
|
def best_matching_module(needle, haystack): '''\ Choose the best matching module, based on longest common suffix. This way it ignores the install location of Spring: >>> modules = ['spring.exe', 'AI/Skirmish/NullAI/SkirmishAI.dll'] >>> best_matching_module('c:/Program Files/Spring/spring.exe', modules) 'spring.exe' Unfortunately if the correct module isn't available the closest match can be wrong: >>> best_matching_module('c:/Program Files/Spring/AI/Skirmish/UnknownAI/SkirmishAI.dll', modules) 'AI/Skirmish/NullAI/SkirmishAI.dll' ''' longest_csl = 0 best_match = None for module in haystack: csl = common_suffix_length(needle, module) if csl > longest_csl: longest_csl = csl best_match = module return best_match
|
''' longest_csl = 0 best_match = None
|
If the correct module isn't available nothing is returned: >>> best_matching_module('c:/Program Files/Spring/AI/Skirmish/UnknownAI/0.0.1/SkirmishAI.dll', modules) ''' parts = needle.replace('\\', '/').split('/') if parts[-1] == 'SkirmishAI.dll': needle = '%s/SkirmishAI.dll' % parts[-3] else: needle = parts[-1] log.debug('best_matching_module: looking for %s', needle)
|
def best_matching_module(needle, haystack): '''\ Choose the best matching module, based on longest common suffix. This way it ignores the install location of Spring: >>> modules = ['spring.exe', 'AI/Skirmish/NullAI/SkirmishAI.dll'] >>> best_matching_module('c:/Program Files/Spring/spring.exe', modules) 'spring.exe' Unfortunately if the correct module isn't available the closest match can be wrong: >>> best_matching_module('c:/Program Files/Spring/AI/Skirmish/UnknownAI/SkirmishAI.dll', modules) 'AI/Skirmish/NullAI/SkirmishAI.dll' ''' longest_csl = 0 best_match = None for module in haystack: csl = common_suffix_length(needle, module) if csl > longest_csl: longest_csl = csl best_match = module return best_match
|
csl = common_suffix_length(needle, module) if csl > longest_csl: longest_csl = csl best_match = module return best_match
|
if module.endswith(needle): log.debug('best_matching_module: found %s', module) return module log.debug('best_matching_module: module not found') return None
|
def best_matching_module(needle, haystack): '''\ Choose the best matching module, based on longest common suffix. This way it ignores the install location of Spring: >>> modules = ['spring.exe', 'AI/Skirmish/NullAI/SkirmishAI.dll'] >>> best_matching_module('c:/Program Files/Spring/spring.exe', modules) 'spring.exe' Unfortunately if the correct module isn't available the closest match can be wrong: >>> best_matching_module('c:/Program Files/Spring/AI/Skirmish/UnknownAI/SkirmishAI.dll', modules) 'AI/Skirmish/NullAI/SkirmishAI.dll' ''' longest_csl = 0 best_match = None for module in haystack: csl = common_suffix_length(needle, module) if csl > longest_csl: longest_csl = csl best_match = module return best_match
|
addr2line = Popen([ADDR2LINE, '-j', '.text', '-e', tempfile.name], stdin = PIPE, stdout = PIPE, stderr = PIPE)
|
cmd = [ADDR2LINE, '-j', '.text', '-e', tempfile.name] log.debug('\tCommand line: ' + ' '.join(cmd)) addr2line = Popen(cmd, stdin = PIPE, stdout = PIPE, stderr = PIPE)
|
def translate_module_addresses(module, debugfile, addresses): '''\ Translate addresses in a module to (module, address, filename, lineno) tuples by invoking addr2line exactly once on the debugging symbols for that module. ''' with NamedTemporaryFile() as tempfile: log.info('\tExtracting debug symbols for module %s from archive %s...' % (module, os.path.basename(debugfile))) # e = extract without path, -so = write output to stdout, -y = yes to all questions sevenzip = Popen([SEVENZIP, 'e', '-so', '-y', debugfile], stdout = tempfile, stderr = PIPE) stdout, stderr = sevenzip.communicate() if stderr: log.debug('%s stderr: %s' % (SEVENZIP, stderr)) if sevenzip.returncode != 0: fatal('%s exited with status %s' % (SEVENZIP, sevenzip.returncode)) log.info('\t\t[OK]') log.info('\tTranslating addresses for module %s...' % module) addr2line = Popen([ADDR2LINE, '-j', '.text', '-e', tempfile.name], stdin = PIPE, stdout = PIPE, stderr = PIPE) if addr2line.poll() == None: stdout, stderr = addr2line.communicate('\n'.join(addresses)) else: stdout, stderr = addr2line.communicate() if stderr: log.debug('%s stderr: %s' % (ADDR2LINE, stderr)) if addr2line.returncode != 0: fatal('%s exited with status %s' % (ADDR2LINE, addr2line.returncode)) log.info('\t\t[OK]') def fixup(addr, file, line): for psu in PATH_STRIP_UNTIL: if psu in file: file = file[file.index(psu)+len(psu):] break return module, addr, file, int(line) return [fixup(addr, *line.split(':')) for addr, line in zip(addresses, stdout.splitlines())]
|
log.setLevel(logging.INFO)
|
log.setLevel(logging.DEBUG)
|
def run_xmlrpc_server(): '''Run an XMLRPC server that publishes the translate_stacktrace function.''' from DocXMLRPCServer import DocXMLRPCServer as XMLRPCServer logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') with open(PIDFILE, 'w') as pidfile: pidfile.write('%s' % os.getpid()) try: # Create server server = XMLRPCServer(LISTEN_ADDR) server.register_function(translate_stacktrace) # Run the server's main loop try: server.serve_forever() except KeyboardInterrupt: pass finally: os.remove(PIDFILE)
|
match = RE_VERSION_DETAILS.match(version)
|
match = RE_VERSION_DETAILS.match(version + ' ')
|
def detect_version_details(infolog): '''\ Detect config, branch, rev from version string(s) in infolog. >>> detect_version_details('Spring 0.81+.0.0 (0.81.2.1-1059-g7937d00) has crashed.') ('default', 'master', '0.81.2.1-1059-g7937d00') >>> detect_version_details('Hang detection triggered for Spring 0.81+.0.0 ([debug2]{pyAiInt}0.81.2.1-1059-g7937d00).') ('debug2', 'pyAiInt', '0.81.2.1-1059-g7937d00') ''' log.info('Detecting version details...') version = None for re_version_line in RE_VERSION_LINES: match = re_version_line.search(infolog) if match: version = match.group(1) break else: fatal('Unable to find detailed version in infolog') match = RE_VERSION_DETAILS.match(version) if not match: fatal('Unable to parse detailed version string "%s"' % version) config, branch, rev = match.groups() if not config: config = 'default' if not branch: branch = 'master' log.info('\t[OK] config = %s, branch = %s, rev = %s', config, branch, rev) return config, branch, rev
|
d += [Dependency(['openal', 'openal32', 'OpenAL32'], ['AL/al.h'])]
|
d += [Dependency(['openal', 'openal32', 'OpenAL32', 'soft_oal'], ['AL/al.h'])]
|
def CheckHeadersAndLibraries(env, conf): print "\nChecking headers and libraries" boost_common = Dependency([], ['boost/cstdint.hpp']) boost_thread = Dependency(['boost_thread'], ['boost/thread.hpp']) boost_regex = Dependency(['boost_regex'], ['boost/regex.hpp']) boost_serial = Dependency([], ['boost/serialization/split_member.hpp']) boost_po = Dependency(['boost_program_options'], ['boost/program_options.hpp']) boost_system = Dependency(['boost_system'], ['boost/system/error_code.hpp']) boost_signals = Dependency(['boost_signals'], ['boost/signal.hpp']) if env.Dictionary('CC').find('gcc') != -1: gcc = True else: gcc = False for boost in (boost_thread, boost_regex, boost_po, boost_system, boost_signals): l = boost.libraries[0] if gcc: boost.libraries = [l+'-gcc-mt', l+'-mt', l+'-gcc', l] else: boost.libraries = [l+'-mt', l] d = [boost_common, boost_regex, boost_serial, boost_thread, boost_po, boost_system, boost_signals] d += [Dependency(['GL', 'opengl32'], ['GL/gl.h'])] d += [Dependency(['GLU', 'glu32'], ['GL/glu.h'])] d += [Dependency(['GLEW', 'glew32'], ['GL/glew.h'])] d += [Dependency(['zlib', 'zlib1', 'z'], ['zlib.h'])] d += [Dependency(['freetype6', 'freetype'], ['ft2build.h'])] d += [Dependency(['IL', 'devil'], ['IL/il.h'])] d += [Dependency(['ILU', 'ilu'], ['IL/ilu.h'])] d += [Dependency(['openal', 'openal32', 'OpenAL32'], ['AL/al.h'])] if env['platform'] == 'windows': d += [Dependency(['imagehlp'], [])] d += [Dependency(['gdi32'], [])] d += [Dependency(['winmm'], [])] d += [Dependency(['wsock32'], [])] d += [Dependency(['ole32'], [])] d += [Dependency(['mingw32'], [])] d += [Dependency(['SDLmain'], [])] d += [Dependency(['ws2_32'], [])] else: d += [Dependency(['Xcursor'], ['X11/Xcursor/Xcursor.h'])] d += [Dependency(['X11'], ['X11/X.h'])] d += [Dependency(['vorbisfile'], ['vorbis/vorbisfile.h'])] d += [Dependency(['vorbis'], [])] d += [Dependency(['ogg'], ['ogg/ogg.h'])] d += [Dependency(['SDL', 'SDL-1.1'], ['SDL/SDL.h', 'SDL11/SDL.h'])] d += [Dependency([], ['jni.h'])] if env['use_tcmalloc']: d += [Dependency(['tcmalloc'], [])] all_succes = True for c in d: if not c.CheckHeaders(conf) or not c.CheckLibraries(conf): all_succes = False if not all_succes: print "Not all tests finished successfully. You are probably missing one of the" print "build dependencies. See config.log for details." env.Exit(1)
|
print(' File "' + toWinPath(os.path.join(distBase, distDir, 'luaui.lua')) + '"')
|
print(' File "' + toWinPath(os.path.join(distBase, 'luaui.lua')) + '"')
|
print('!ifdef INSTALL')
|
print(' File "' + toWinPath(os.path.join(distBase, distDir, d, f)) + '"')
|
print(' File "' + toWinPath(os.path.join(distBase, d, f)) + '"')
|
print('!ifdef INSTALL')
|
import os
|
import os, sys
|
# !ifdef INSTALL
|
try: os.chdir('dist') except OSError: os.chdir('../dist')
|
distDirCandidates = [sys.argv[1], 'dist', 'game', 'cont'] distDir = "" for d in distDirCandidates: distDir = d try: os.chdir(distDir) break except OSError: distDir = os.path.join('..', distDir) try: os.chdir(distDir) break except OSError: distDir = "" continue if distDir == "": sys.exit(1);
|
# !ifdef INSTALL
|
if (f != 'Config') and (f != '.svn'):
|
if (f != 'Config') and (f != '.git'):
|
def GetDirs(path, dirs): dirs[path] = [] filelist = os.listdir(path) for f in filelist: fullname = path + f if os.path.isdir(fullname): if (f != 'Config') and (f != '.svn'): fullname = fullname + '/' GetDirs(fullname, dirs) else: dirs[path].append(f)
|
print(' File "..\\dist\\luaui.lua"')
|
print(' File "$DIST_DIR\\luaui.lua"')
|
print('!ifdef INSTALL')
|
print(' File "..\\dist\\' + osName(d) + osName(f) + '"')
|
print(' File "$DIST_DIR\\' + osName(d) + osName(f) + '"')
|
print('!ifdef INSTALL')
|
color = (npair[0] < len(DEV_NAME_COLORS) and DEV_NAME_COLORS[ npair[0] ]) or "F00F00" nname = npair[1] nline = (LOG_LINE_PREFIX % (color, nname)) + line[match.span()[1]: ] + '\n'
|
color = (npair[0] < len(DEV_NAME_COLORS) and DEV_NAME_COLORS[npair[0]]) or "F00F00" nline = (LOG_LINE_PREFIX % (color, "<" + npair[1] + ">")) + line[match.span()[1]: ] + '\n'
|
def ProcessLines(lines): random.shuffle(DEV_NAME_COLORS) nlines = "" onames = {} for line in lines: match = re.search(DEV_NAME_PATTERN, line) if (match == None): continue oname = match.group(0) oname = oname[1: -1] if (not onames.has_key(oname)): nname = oname for n in DEV_NAME_LIST: if (oname.find(n) >= 0): nname = n; break onames[oname] = (len(onames), nname) npair = onames[oname] color = (npair[0] < len(DEV_NAME_COLORS) and DEV_NAME_COLORS[ npair[0] ]) or "F00F00" nname = npair[1] nline = (LOG_LINE_PREFIX % (color, nname)) + line[match.span()[1]: ] + '\n' nlines += nline return nlines
|
return nlines
|
gmtime = time.gmtime() pcolor = "000000" prefix += "%s: %d-%d-%d\n" % (((LOG_LINE_PREFIX % (pcolor, "Date")), gmtime[2], gmtime[1], gmtime[0])) prefix += "%s: " % (LOG_LINE_PREFIX % (pcolor, "Present")) knames = onames.keys() for k in xrange(len(knames)): oname = knames[k] npair = onames[oname] color = DEV_NAME_COLORS[npair[0]] prefix += (LOG_LINE_PREFIX % (color, npair[1])) prefix += (((k < len(knames) - 1) and ", ") or "") return (prefix + "\n\n" + nlines)
|
def ProcessLines(lines): random.shuffle(DEV_NAME_COLORS) nlines = "" onames = {} for line in lines: match = re.search(DEV_NAME_PATTERN, line) if (match == None): continue oname = match.group(0) oname = oname[1: -1] if (not onames.has_key(oname)): nname = oname for n in DEV_NAME_LIST: if (oname.find(n) >= 0): nname = n; break onames[oname] = (len(onames), nname) npair = onames[oname] color = (npair[0] < len(DEV_NAME_COLORS) and DEV_NAME_COLORS[ npair[0] ]) or "F00F00" nname = npair[1] nline = (LOG_LINE_PREFIX % (color, nname)) + line[match.span()[1]: ] + '\n' nlines += nline return nlines
|
ntracks = 20
|
ntracks = 100
|
def testCaching( self ):
|
l = 100
|
l = 10
|
def testPValueComputation( self ): annotation_size = 100 workspace_size = 1000 segment_size = 10
|
samples = [0] * y + [1] * (l - y)
|
samples = [1] * y + [0] * (l - y)
|
def testPValueComputation( self ): annotation_size = 100 workspace_size = 1000 segment_size = 10
|
self.assert_( fpr >= g.pvalue, "fdr (%f) != pvalue (%f): y=%i, x=%i, s=%i, t=%i" % \
|
self.assert_( fpr >= g.pvalue - 0.0001, "fpr (%f) != pvalue (%f): y=%i, x=%i, s=%i, t=%i" % \
|
def testPValueComputation( self ): annotation_size = 100 workspace_size = 1000 segment_size = 10
|
self.assert_( r.qvalue > 0.5 )
|
self.assert_( r.qvalue > 0.5, "%f" % r.qvalue )
|
def testStats( self ): annotation_size = 100 workspace_size = 1000 segment_size = 10
|
dumpStats( segments, "stats_segments_raw" )
|
dumpStats( segments, "stats_segments_normed" )
|
def dumpStats( coll, section ): if section in options.output_stats or "all" in options.output_stats: coll.outputStats( E.openOutputFile( section ) )
|
help="filename with segments. Also accepts a glob in parantheses [default=%default]." )
|
help="filename with segments. Also accepts a glob in parentheses [default=%default]." )
|
def main( argv = None ): """script main. parses command line options in sys.argv, unless *argv* is given. """ if not argv: argv = sys.argv # setup command line parser parser = optparse.OptionParser( version = "%prog version: $Id: script_template.py 2871 2010-03-03 10:20:44Z andreas $", usage = globals()["__doc__"] ) parser.add_option("-a", "--annotation-file", dest="annotation_files", type="string", action="append", help="filename with annotations [default=%default]." ) parser.add_option("-s", "--segment-file", dest="segment_files", type="string", action="append", help="filename with segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-w", "--workspace-file", dest="workspace_files", type="string", action="append", help="filename with workspace segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-i", "--isochore-file", dest="isochore_files", type="string", action="append", help="filename with isochore segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-l", "--sample-file", dest="sample_files", type="string", action="append", help="filename with sample files. Start processing from samples [default=%default]." ) parser.add_option("-c", "--counter", dest="counter", type="choice", choices=("nucleotide-overlap", "nucleotide-density", "segment-overlap", ), help="quantity to test [default=%default]." ) parser.add_option("-n", "--num-samples", dest="num_samples", type="int", help="number of samples to compute [default=%default]." ) parser.add_option("-e", "--cache", dest="cache", type="string", help="filename for caching samples [default=%default]." ) parser.add_option("-o", "--order", dest="output_order", type="choice", choices = ( "track", "annotation", "fold", "pvalue", "qvalue" ), help="order results in output by fold, track, etc. [default=%default]." ) parser.add_option("-p", "--pvalue-method", dest="pvalue_method", type="choice", choices = ( "empirical", "norm", ), help="type of pvalue reported [default=%default]." ) parser.add_option("-q", "--qvalue-method", dest="qvalue_method", type="choice", choices = ( "storey", ), help="method to perform multiple testing correction by controlling the fdr [default=%default]." ) parser.add_option( "--qvalue-lambda", dest="qvalue_lambda", type="float", help="fdr computation: lambda [default=%default]." ) parser.add_option( "--qvalue-pi0-method", dest="qvalue_pi0_method", type="choice", choices = ("smoother", "bootstrap" ), help="fdr computation: method for estimating pi0 [default=%default]." ) parser.add_option( "--counts-file", dest="input_filename_counts", type="string", help="start processing from counts - no segments required [default=%default]." ) parser.add_option( "--output-plots-pattern", dest="output_plots_pattern", type="string", help="output pattern for plots [default=%default]" ) parser.add_option( "--output-samples-pattern", dest="output_samples_pattern", type="string", help="output pattern for samples. Samples are stored in bed format, one for " " each segment [default=%default]" ) parser.add_option( "--bucket-size", dest="bucket_size", type="int", help="size of a bin for histogram of segment lengths [default=%default]" ) parser.add_option( "--nbuckets", dest="nbuckets", type="int", help="number of bins for histogram of segment lengths [default=%default]" ) parser.set_defaults( annotation_files = [], segment_files = [], workspace_files = [], sample_files = [], num_samples = 1000, nbuckets = 100000, bucket_size = 1, counter = "nucleotide-overlap", output_stats = "all", output_counts = True, output_order = "fold", cache = None, input_filename_counts = None, pvalue_method = "empirical", output_plots_pattern = None, output_samples_pattern = None, qvalue_method = "storey", qvalue_lambda = None, qvalue_pi0_method = "smoother", ) ## add common options (-h/--help, ...) and parse command line (options, args) = E.Start( parser, argv = argv, add_output_options = True ) ################################################## if options.input_filename_counts: annotator_results = gat.fromCounts( options.input_filename_counts ) else: annotator_results = fromSegments( options, args ) if options.pvalue_method != "empirical": E.info("updating pvalues to %s" % options.pvalue_method ) gat.updatePValues( gat.iterator_results(annotator_results), options.pvalue_method ) ################################################## ################################################## ################################################## ## compute global fdr ################################################## E.info( "computing FDR statistics" ) gat.updateQValues( list(gat.iterator_results(annotator_results)), method = options.qvalue_method, vlambda = options.qvalue_lambda, pi0_method = options.qvalue_pi0_method ) ################################################## # plot histograms if options.output_plots_pattern and HASPLOT: E.info("plotting sample stats" ) for r in gat.iterator_results(annotator_results): plt.figure() key = "%s-%s" % (r.track, r.annotation) s = r.samples hist, bins = numpy.histogram( s, new = True, normed = True, bins = numpy.arange( s.min(), s.max() + 1, 1.0) ) plt.plot( bins[:-1], hist, label = key ) sigma = r.stddev mu = r.expected plt.plot(bins, 1.0/(sigma * numpy.sqrt(2 * numpy.pi)) * numpy.exp( - (bins - mu)**2 / (2 * sigma**2) ), label = "fit", linewidth=2, color='r' ) plt.legend() filename = re.sub(options.output_plots_pattern, "%s", key) plt.savefig( filename ) ################################################## ################################################## ## output ################################################## outfile = sys.stdout outfile.write("\t".join( gat.AnnotatorResult.headers ) + "\n" ) output = list( gat.iterator_results( annotator_results ) ) if options.output_order == "track": output.sort( key = lambda x: (x.track, x.annotation) ) elif options.output_order == "annotation": output.sort( key = lambda x: (x.annotation, x.track) ) elif options.output_order == "fold": output.sort( key = lambda x: x.fold ) elif options.output_order == "pvalue": output.sort( key = lambda x: x.pvalue ) elif options.output_order == "qvalue": output.sort( key = lambda x: x.qvalue ) else: raise ValueError("unknown sort order %s" % options.output_order ) for result in output: outfile.write( str(result) + "\n" ) ## write footer and output benchmark information. E.Stop()
|
help="filename with workspace segments. Also accepts a glob in parantheses [default=%default]." )
|
help="filename with workspace segments. Also accepts a glob in parentheses [default=%default]." )
|
def main( argv = None ): """script main. parses command line options in sys.argv, unless *argv* is given. """ if not argv: argv = sys.argv # setup command line parser parser = optparse.OptionParser( version = "%prog version: $Id: script_template.py 2871 2010-03-03 10:20:44Z andreas $", usage = globals()["__doc__"] ) parser.add_option("-a", "--annotation-file", dest="annotation_files", type="string", action="append", help="filename with annotations [default=%default]." ) parser.add_option("-s", "--segment-file", dest="segment_files", type="string", action="append", help="filename with segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-w", "--workspace-file", dest="workspace_files", type="string", action="append", help="filename with workspace segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-i", "--isochore-file", dest="isochore_files", type="string", action="append", help="filename with isochore segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-l", "--sample-file", dest="sample_files", type="string", action="append", help="filename with sample files. Start processing from samples [default=%default]." ) parser.add_option("-c", "--counter", dest="counter", type="choice", choices=("nucleotide-overlap", "nucleotide-density", "segment-overlap", ), help="quantity to test [default=%default]." ) parser.add_option("-n", "--num-samples", dest="num_samples", type="int", help="number of samples to compute [default=%default]." ) parser.add_option("-e", "--cache", dest="cache", type="string", help="filename for caching samples [default=%default]." ) parser.add_option("-o", "--order", dest="output_order", type="choice", choices = ( "track", "annotation", "fold", "pvalue", "qvalue" ), help="order results in output by fold, track, etc. [default=%default]." ) parser.add_option("-p", "--pvalue-method", dest="pvalue_method", type="choice", choices = ( "empirical", "norm", ), help="type of pvalue reported [default=%default]." ) parser.add_option("-q", "--qvalue-method", dest="qvalue_method", type="choice", choices = ( "storey", ), help="method to perform multiple testing correction by controlling the fdr [default=%default]." ) parser.add_option( "--qvalue-lambda", dest="qvalue_lambda", type="float", help="fdr computation: lambda [default=%default]." ) parser.add_option( "--qvalue-pi0-method", dest="qvalue_pi0_method", type="choice", choices = ("smoother", "bootstrap" ), help="fdr computation: method for estimating pi0 [default=%default]." ) parser.add_option( "--counts-file", dest="input_filename_counts", type="string", help="start processing from counts - no segments required [default=%default]." ) parser.add_option( "--output-plots-pattern", dest="output_plots_pattern", type="string", help="output pattern for plots [default=%default]" ) parser.add_option( "--output-samples-pattern", dest="output_samples_pattern", type="string", help="output pattern for samples. Samples are stored in bed format, one for " " each segment [default=%default]" ) parser.add_option( "--bucket-size", dest="bucket_size", type="int", help="size of a bin for histogram of segment lengths [default=%default]" ) parser.add_option( "--nbuckets", dest="nbuckets", type="int", help="number of bins for histogram of segment lengths [default=%default]" ) parser.set_defaults( annotation_files = [], segment_files = [], workspace_files = [], sample_files = [], num_samples = 1000, nbuckets = 100000, bucket_size = 1, counter = "nucleotide-overlap", output_stats = "all", output_counts = True, output_order = "fold", cache = None, input_filename_counts = None, pvalue_method = "empirical", output_plots_pattern = None, output_samples_pattern = None, qvalue_method = "storey", qvalue_lambda = None, qvalue_pi0_method = "smoother", ) ## add common options (-h/--help, ...) and parse command line (options, args) = E.Start( parser, argv = argv, add_output_options = True ) ################################################## if options.input_filename_counts: annotator_results = gat.fromCounts( options.input_filename_counts ) else: annotator_results = fromSegments( options, args ) if options.pvalue_method != "empirical": E.info("updating pvalues to %s" % options.pvalue_method ) gat.updatePValues( gat.iterator_results(annotator_results), options.pvalue_method ) ################################################## ################################################## ################################################## ## compute global fdr ################################################## E.info( "computing FDR statistics" ) gat.updateQValues( list(gat.iterator_results(annotator_results)), method = options.qvalue_method, vlambda = options.qvalue_lambda, pi0_method = options.qvalue_pi0_method ) ################################################## # plot histograms if options.output_plots_pattern and HASPLOT: E.info("plotting sample stats" ) for r in gat.iterator_results(annotator_results): plt.figure() key = "%s-%s" % (r.track, r.annotation) s = r.samples hist, bins = numpy.histogram( s, new = True, normed = True, bins = numpy.arange( s.min(), s.max() + 1, 1.0) ) plt.plot( bins[:-1], hist, label = key ) sigma = r.stddev mu = r.expected plt.plot(bins, 1.0/(sigma * numpy.sqrt(2 * numpy.pi)) * numpy.exp( - (bins - mu)**2 / (2 * sigma**2) ), label = "fit", linewidth=2, color='r' ) plt.legend() filename = re.sub(options.output_plots_pattern, "%s", key) plt.savefig( filename ) ################################################## ################################################## ## output ################################################## outfile = sys.stdout outfile.write("\t".join( gat.AnnotatorResult.headers ) + "\n" ) output = list( gat.iterator_results( annotator_results ) ) if options.output_order == "track": output.sort( key = lambda x: (x.track, x.annotation) ) elif options.output_order == "annotation": output.sort( key = lambda x: (x.annotation, x.track) ) elif options.output_order == "fold": output.sort( key = lambda x: x.fold ) elif options.output_order == "pvalue": output.sort( key = lambda x: x.pvalue ) elif options.output_order == "qvalue": output.sort( key = lambda x: x.qvalue ) else: raise ValueError("unknown sort order %s" % options.output_order ) for result in output: outfile.write( str(result) + "\n" ) ## write footer and output benchmark information. E.Stop()
|
help="filename with isochore segments. Also accepts a glob in parantheses [default=%default]." )
|
help="filename with isochore segments. Also accepts a glob in parentheses [default=%default]." )
|
def main( argv = None ): """script main. parses command line options in sys.argv, unless *argv* is given. """ if not argv: argv = sys.argv # setup command line parser parser = optparse.OptionParser( version = "%prog version: $Id: script_template.py 2871 2010-03-03 10:20:44Z andreas $", usage = globals()["__doc__"] ) parser.add_option("-a", "--annotation-file", dest="annotation_files", type="string", action="append", help="filename with annotations [default=%default]." ) parser.add_option("-s", "--segment-file", dest="segment_files", type="string", action="append", help="filename with segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-w", "--workspace-file", dest="workspace_files", type="string", action="append", help="filename with workspace segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-i", "--isochore-file", dest="isochore_files", type="string", action="append", help="filename with isochore segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-l", "--sample-file", dest="sample_files", type="string", action="append", help="filename with sample files. Start processing from samples [default=%default]." ) parser.add_option("-c", "--counter", dest="counter", type="choice", choices=("nucleotide-overlap", "nucleotide-density", "segment-overlap", ), help="quantity to test [default=%default]." ) parser.add_option("-n", "--num-samples", dest="num_samples", type="int", help="number of samples to compute [default=%default]." ) parser.add_option("-e", "--cache", dest="cache", type="string", help="filename for caching samples [default=%default]." ) parser.add_option("-o", "--order", dest="output_order", type="choice", choices = ( "track", "annotation", "fold", "pvalue", "qvalue" ), help="order results in output by fold, track, etc. [default=%default]." ) parser.add_option("-p", "--pvalue-method", dest="pvalue_method", type="choice", choices = ( "empirical", "norm", ), help="type of pvalue reported [default=%default]." ) parser.add_option("-q", "--qvalue-method", dest="qvalue_method", type="choice", choices = ( "storey", ), help="method to perform multiple testing correction by controlling the fdr [default=%default]." ) parser.add_option( "--qvalue-lambda", dest="qvalue_lambda", type="float", help="fdr computation: lambda [default=%default]." ) parser.add_option( "--qvalue-pi0-method", dest="qvalue_pi0_method", type="choice", choices = ("smoother", "bootstrap" ), help="fdr computation: method for estimating pi0 [default=%default]." ) parser.add_option( "--counts-file", dest="input_filename_counts", type="string", help="start processing from counts - no segments required [default=%default]." ) parser.add_option( "--output-plots-pattern", dest="output_plots_pattern", type="string", help="output pattern for plots [default=%default]" ) parser.add_option( "--output-samples-pattern", dest="output_samples_pattern", type="string", help="output pattern for samples. Samples are stored in bed format, one for " " each segment [default=%default]" ) parser.add_option( "--bucket-size", dest="bucket_size", type="int", help="size of a bin for histogram of segment lengths [default=%default]" ) parser.add_option( "--nbuckets", dest="nbuckets", type="int", help="number of bins for histogram of segment lengths [default=%default]" ) parser.set_defaults( annotation_files = [], segment_files = [], workspace_files = [], sample_files = [], num_samples = 1000, nbuckets = 100000, bucket_size = 1, counter = "nucleotide-overlap", output_stats = "all", output_counts = True, output_order = "fold", cache = None, input_filename_counts = None, pvalue_method = "empirical", output_plots_pattern = None, output_samples_pattern = None, qvalue_method = "storey", qvalue_lambda = None, qvalue_pi0_method = "smoother", ) ## add common options (-h/--help, ...) and parse command line (options, args) = E.Start( parser, argv = argv, add_output_options = True ) ################################################## if options.input_filename_counts: annotator_results = gat.fromCounts( options.input_filename_counts ) else: annotator_results = fromSegments( options, args ) if options.pvalue_method != "empirical": E.info("updating pvalues to %s" % options.pvalue_method ) gat.updatePValues( gat.iterator_results(annotator_results), options.pvalue_method ) ################################################## ################################################## ################################################## ## compute global fdr ################################################## E.info( "computing FDR statistics" ) gat.updateQValues( list(gat.iterator_results(annotator_results)), method = options.qvalue_method, vlambda = options.qvalue_lambda, pi0_method = options.qvalue_pi0_method ) ################################################## # plot histograms if options.output_plots_pattern and HASPLOT: E.info("plotting sample stats" ) for r in gat.iterator_results(annotator_results): plt.figure() key = "%s-%s" % (r.track, r.annotation) s = r.samples hist, bins = numpy.histogram( s, new = True, normed = True, bins = numpy.arange( s.min(), s.max() + 1, 1.0) ) plt.plot( bins[:-1], hist, label = key ) sigma = r.stddev mu = r.expected plt.plot(bins, 1.0/(sigma * numpy.sqrt(2 * numpy.pi)) * numpy.exp( - (bins - mu)**2 / (2 * sigma**2) ), label = "fit", linewidth=2, color='r' ) plt.legend() filename = re.sub(options.output_plots_pattern, "%s", key) plt.savefig( filename ) ################################################## ################################################## ## output ################################################## outfile = sys.stdout outfile.write("\t".join( gat.AnnotatorResult.headers ) + "\n" ) output = list( gat.iterator_results( annotator_results ) ) if options.output_order == "track": output.sort( key = lambda x: (x.track, x.annotation) ) elif options.output_order == "annotation": output.sort( key = lambda x: (x.annotation, x.track) ) elif options.output_order == "fold": output.sort( key = lambda x: x.fold ) elif options.output_order == "pvalue": output.sort( key = lambda x: x.pvalue ) elif options.output_order == "qvalue": output.sort( key = lambda x: x.qvalue ) else: raise ValueError("unknown sort order %s" % options.output_order ) for result in output: outfile.write( str(result) + "\n" ) ## write footer and output benchmark information. E.Stop()
|
outfile = sys.stdout
|
outfile = options.stdout
|
def main( argv = None ): """script main. parses command line options in sys.argv, unless *argv* is given. """ if not argv: argv = sys.argv # setup command line parser parser = optparse.OptionParser( version = "%prog version: $Id: script_template.py 2871 2010-03-03 10:20:44Z andreas $", usage = globals()["__doc__"] ) parser.add_option("-a", "--annotation-file", dest="annotation_files", type="string", action="append", help="filename with annotations [default=%default]." ) parser.add_option("-s", "--segment-file", dest="segment_files", type="string", action="append", help="filename with segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-w", "--workspace-file", dest="workspace_files", type="string", action="append", help="filename with workspace segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-i", "--isochore-file", dest="isochore_files", type="string", action="append", help="filename with isochore segments. Also accepts a glob in parantheses [default=%default]." ) parser.add_option("-l", "--sample-file", dest="sample_files", type="string", action="append", help="filename with sample files. Start processing from samples [default=%default]." ) parser.add_option("-c", "--counter", dest="counter", type="choice", choices=("nucleotide-overlap", "nucleotide-density", "segment-overlap", ), help="quantity to test [default=%default]." ) parser.add_option("-n", "--num-samples", dest="num_samples", type="int", help="number of samples to compute [default=%default]." ) parser.add_option("-e", "--cache", dest="cache", type="string", help="filename for caching samples [default=%default]." ) parser.add_option("-o", "--order", dest="output_order", type="choice", choices = ( "track", "annotation", "fold", "pvalue", "qvalue" ), help="order results in output by fold, track, etc. [default=%default]." ) parser.add_option("-p", "--pvalue-method", dest="pvalue_method", type="choice", choices = ( "empirical", "norm", ), help="type of pvalue reported [default=%default]." ) parser.add_option("-q", "--qvalue-method", dest="qvalue_method", type="choice", choices = ( "storey", ), help="method to perform multiple testing correction by controlling the fdr [default=%default]." ) parser.add_option( "--qvalue-lambda", dest="qvalue_lambda", type="float", help="fdr computation: lambda [default=%default]." ) parser.add_option( "--qvalue-pi0-method", dest="qvalue_pi0_method", type="choice", choices = ("smoother", "bootstrap" ), help="fdr computation: method for estimating pi0 [default=%default]." ) parser.add_option( "--counts-file", dest="input_filename_counts", type="string", help="start processing from counts - no segments required [default=%default]." ) parser.add_option( "--output-plots-pattern", dest="output_plots_pattern", type="string", help="output pattern for plots [default=%default]" ) parser.add_option( "--output-samples-pattern", dest="output_samples_pattern", type="string", help="output pattern for samples. Samples are stored in bed format, one for " " each segment [default=%default]" ) parser.add_option( "--bucket-size", dest="bucket_size", type="int", help="size of a bin for histogram of segment lengths [default=%default]" ) parser.add_option( "--nbuckets", dest="nbuckets", type="int", help="number of bins for histogram of segment lengths [default=%default]" ) parser.set_defaults( annotation_files = [], segment_files = [], workspace_files = [], sample_files = [], num_samples = 1000, nbuckets = 100000, bucket_size = 1, counter = "nucleotide-overlap", output_stats = "all", output_counts = True, output_order = "fold", cache = None, input_filename_counts = None, pvalue_method = "empirical", output_plots_pattern = None, output_samples_pattern = None, qvalue_method = "storey", qvalue_lambda = None, qvalue_pi0_method = "smoother", ) ## add common options (-h/--help, ...) and parse command line (options, args) = E.Start( parser, argv = argv, add_output_options = True ) ################################################## if options.input_filename_counts: annotator_results = gat.fromCounts( options.input_filename_counts ) else: annotator_results = fromSegments( options, args ) if options.pvalue_method != "empirical": E.info("updating pvalues to %s" % options.pvalue_method ) gat.updatePValues( gat.iterator_results(annotator_results), options.pvalue_method ) ################################################## ################################################## ################################################## ## compute global fdr ################################################## E.info( "computing FDR statistics" ) gat.updateQValues( list(gat.iterator_results(annotator_results)), method = options.qvalue_method, vlambda = options.qvalue_lambda, pi0_method = options.qvalue_pi0_method ) ################################################## # plot histograms if options.output_plots_pattern and HASPLOT: E.info("plotting sample stats" ) for r in gat.iterator_results(annotator_results): plt.figure() key = "%s-%s" % (r.track, r.annotation) s = r.samples hist, bins = numpy.histogram( s, new = True, normed = True, bins = numpy.arange( s.min(), s.max() + 1, 1.0) ) plt.plot( bins[:-1], hist, label = key ) sigma = r.stddev mu = r.expected plt.plot(bins, 1.0/(sigma * numpy.sqrt(2 * numpy.pi)) * numpy.exp( - (bins - mu)**2 / (2 * sigma**2) ), label = "fit", linewidth=2, color='r' ) plt.legend() filename = re.sub(options.output_plots_pattern, "%s", key) plt.savefig( filename ) ################################################## ################################################## ## output ################################################## outfile = sys.stdout outfile.write("\t".join( gat.AnnotatorResult.headers ) + "\n" ) output = list( gat.iterator_results( annotator_results ) ) if options.output_order == "track": output.sort( key = lambda x: (x.track, x.annotation) ) elif options.output_order == "annotation": output.sort( key = lambda x: (x.annotation, x.track) ) elif options.output_order == "fold": output.sort( key = lambda x: x.fold ) elif options.output_order == "pvalue": output.sort( key = lambda x: x.pvalue ) elif options.output_order == "qvalue": output.sort( key = lambda x: x.qvalue ) else: raise ValueError("unknown sort order %s" % options.output_order ) for result in output: outfile.write( str(result) + "\n" ) ## write footer and output benchmark information. E.Stop()
|
os.system("update-locale LANG=\"%s\"" % self.locale)
|
os.system("update-locale LANG=\"%s.UTF-8\"" % self.locale)
|
def install(self):
|
path = self.device_node device = parted.getDevice(path) disk = parted.Disk(device) partition = disk.getFirstPartition() last_added_partition = Partition(partition) partitions.append(last_added_partition) partition = partition.nextPartition() while (partition is not None): if last_added_partition.partition.number == -1 and partition.number == -1: last_added_partition.add_partition(partition) else: last_added_partition = Partition(partition) partitions.append(last_added_partition) if partition.number != -1 and "swap" not in last_added_partition.type: if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') if (partition.path not in commands.getoutput('mount')): os.system("mount %s /tmp/live-installer/tmpmount" % partition.path) if (partition.path in commands.getoutput('mount')): last_added_partition.used_space = commands.getoutput("df | grep %s | awk {'print $5'}" % partition.path) if "%" in last_added_partition.used_space: used_space_pct = int(last_added_partition.used_space.replace("%", "").strip()) last_added_partition.free_space = int(float(last_added_partition.size) * (float(100) - float(used_space_pct)) / float(100)) mount_point = commands.getoutput("df | grep %s | awk {'print $6'}" % partition.path) if os.path.exists(os.path.join(mount_point, 'etc/lsb-release')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/lsb-release') + " | grep DISTRIB_DESCRIPTION").replace('DISTRIB_DESCRIPTION', '').replace('=', '').replace('"', '').strip() elif os.path.exists(os.path.join(mount_point, 'etc/issue')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/issue')).replace('\\n', '').replace('\l', '').strip() elif os.path.exists(os.path.join(mount_point, 'Windows/servicing/Version')): version = commands.getoutput("ls %s" % os.path.join(mount_point, 'Windows/servicing/Version')) if version.startswith("6.1"): last_added_partition.description = "Windows 7" elif version.startswith("6.0"): last_added_partition.description = "Windows Vista" elif version.startswith("5.1") or version.startswith("5.2"): last_added_partition.description = "Windows XP" elif version.startswith("5.0"): last_added_partition.description = "Windows 2000" elif version.startswith("4.90"): last_added_partition.description = "Windows Me" elif version.startswith("4.1"): last_added_partition.description = "Windows 98" elif version.startswith("4.0.1381"): last_added_partition.description = "Windows NT" elif version.startswith("4.0.950"): last_added_partition.description = "Windows 95" elif os.path.exists(os.path.join(mount_point, 'Boot/BCD')): if os.system("grep -qs \"V.i.s.t.a\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Vista bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .7\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows 7 bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .R.e.c.o.v.e.r.y. .E.n.v.i.r.o.n.m.e.n.t\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows recovery" elif os.system("grep -qs \"W.i.n.d.o.w.s. .S.e.r.v.e.r. .2.0.0.8\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Server 2008 bootloader" else: last_added_partition.description = "Windows bootloader" elif os.path.exists(os.path.join(mount_point, 'Windows/System32')): last_added_partition.description = "Windows" if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount')
|
try: path = self.device_node device = parted.getDevice(path) disk = parted.Disk(device) partition = disk.getFirstPartition() last_added_partition = Partition(partition) partitions.append(last_added_partition)
|
def build_partitions(self): gtk.gdk.threads_enter() self.window.set_sensitive(False) # "busy" cursor. cursor = gtk.gdk.Cursor(gtk.gdk.WATCH) self.window.window.set_cursor(cursor) from progress import ProgressDialog dialog = ProgressDialog() dialog.show(title=_("Installer"), label=_("Scanning disk %s for partitions") % self.device_node) gtk.gdk.threads_leave() from screen import Partition os.popen('mkdir -p /tmp/live-installer/tmpmount')
|
out = open("/tmp/install_grub.sh", "w") out.write(" out.write("mount --bind /dev/ /target/dev\n") out.write("mount --bind /dev/pts /target/dev/shm\n") out.write("mount --bind /dev/shm /target/dev/shm\n") out.write("mount --bind /proc /target/proc\n") out.write("mount --bind /sys /target/sys\n") out.write("chroot /target/ grub-install %s\n" % self.grub_device) out.write("chroot /target/ grub-mkconfig -o /boot/grub/grub.cfg\n") out.write("umount --force /target/dev/pts\n") out.write("umount --force /target/dev/shm\n") out.write("umount --force /target/dev\n") out.write("umount --force /target/proc\n") out.write("umount --force /target/sys\n") out.close() os.system("chmod +x /tmp/install_grub.sh") os.system("/tmp/install_grub.sh") os.system("rm -rf /tmp/install_grub.sh")
|
os.system("chroot /target/ /bin/sh -c \"grub-install %s\"" % self.grub_device) os.system("chroot /target/ /bin/sh -c \"grub-mkconfig -o /boot/grub/grub.cfg\"").
|
def install(self):
|
self.run_in_chroot("useradd -s %s -c \"%s\" -G sudo -m %s" % ("/bin/bash", user.realname, user.username))
|
self.run_in_chroot("useradd -s %s -c \'%s\' -G sudo -m %s" % ("/bin/bash", user.realname, user.username))
|
def install(self): ''' Install this baby to disk ''' # mount the media location. print " --> Installation started" try: if(not os.path.exists("/target")): os.mkdir("/target") if(not os.path.exists("/source")): os.mkdir("/source") # find the squashfs.. root = self.media root_type = self.media_type if(not os.path.exists(root)): print "Base filesystem does not exist! Critical error (exiting)." sys.exit(1) # change to report root_device = None # format partitions as appropriate for item in self.fstab.get_entries(): if(item.mountpoint == "/"): root_device = item item.format = True if(item.format): # well now, we gets to nuke stuff. # report it. should grab the total count of filesystems to be formatted .. self.update_progress(total=4, current=1, pulse=True, message=_("Formatting %s as %s..." % (item.device, item.filesystem))) self.format_device(item.device, item.filesystem) # mount filesystem print " --> Mounting partitions" self.update_progress(total=4, current=2, message=_("Mounting %s on %s") % (root, "/source/")) self.do_mount(root, "/source/", root_type, options="loop") self.update_progress(total=4, current=3, message=_("Mounting %s on %s") % (root_device.device, "/target/")) self.do_mount(root_device.device, "/target", root_device.filesystem, None) # walk root filesystem. we're too lazy though :P SOURCE = "/source/" DEST = "/target/" directory_times = [] our_total = 0 our_current = -1 os.chdir(SOURCE) # index the files print " --> Indexing files" for top,dirs,files in os.walk(SOURCE, topdown=False): our_total += len(dirs) + len(files) self.update_progress(pulse=True, message=_("Indexing files to be copied..")) our_total += 1 # safenessness print " --> Copying files" for top,dirs,files in os.walk(SOURCE): # Sanity check. Python is a bit schitzo dirpath = top if(dirpath.startswith(SOURCE)): dirpath = dirpath[len(SOURCE):] for name in dirs + files: # following is hacked/copied from Ubiquity rpath = os.path.join(dirpath, name) sourcepath = os.path.join(SOURCE, rpath) targetpath = os.path.join(DEST, rpath) st = os.lstat(sourcepath) mode = stat.S_IMODE(st.st_mode)
|
self.style.apply_default_background(self.window, True, gtk.STATE_NORMAL, None, 0, 0, width, height) cr.set_source_rgba(0, 0, 0, 0.0)
|
def draw(self, cr, width, height): #self.style.apply_default_background(self.window, True, gtk.STATE_NORMAL, None, 0, 0, width, height) #cr.set_source_rgba(0, 0, 0, 0.0) self.width = width # for add_label self.height = height # for add_label height /= 2 width -= 40 #cr.rectangle(0, 0, width, height) #cr.fill()
|
|
cr.rectangle(0, 0, width, height) cr.fill()
|
def draw(self, cr, width, height): #self.style.apply_default_background(self.window, True, gtk.STATE_NORMAL, None, 0, 0, width, height) #cr.set_source_rgba(0, 0, 0, 0.0) self.width = width # for add_label self.height = height # for add_label height /= 2 width -= 40 #cr.rectangle(0, 0, width, height) #cr.fill()
|
|
if partition.partition.number == -1: border_color = (0.6, 0.6, 0.6) fill_color = (0.2, 0.2, 0.6) else: border_color = self.colors[partition.partition.number % len(self.colors)] fill_color = (0.9, 0.9, 0.9)
|
if partition.size > 0.5: if partition.partition.number == -1: border_color = (0.6, 0.6, 0.6) fill_color = (0.6, 0.6, 0.6) else: border_color = self.colors[partition.partition.number % len(self.colors)] fill_color = (0.9, 0.9, 0.9)
|
def draw(self, cr, width, height): #self.style.apply_default_background(self.window, True, gtk.STATE_NORMAL, None, 0, 0, width, height) #cr.set_source_rgba(0, 0, 0, 0.0) self.width = width # for add_label self.height = height # for add_label height /= 2 width -= 40 #cr.rectangle(0, 0, width, height) #cr.fill()
|
self.window.resize(width, height) self.window.realize()
|
def __init__(self): self.resource_dir = '/usr/share/live-installer/' #self.glade = 'interface.glade' self.glade = os.path.join(self.resource_dir, 'interface.glade') self.wTree = gtk.glade.XML(self.glade, 'main_window')
|
|
self.window.set_title(DISTRIBUTION_NAME + " " + _("Installer"))
|
if "--debug" in sys.argv: self.window.set_title((_("%s Installer") % DISTRIBUTION_NAME) + " (debug)") else: self.window.set_title(_("%s Installer") % DISTRIBUTION_NAME)
|
def __init__(self): self.resource_dir = '/usr/share/live-installer/' #self.glade = 'interface.glade' self.glade = os.path.join(self.resource_dir, 'interface.glade') self.wTree = gtk.glade.XML(self.glade, 'main_window')
|
pro = subprocess.Popen("parted -lms", stdout=subprocess.PIPE, shell=True) last_name = "" for line in pro.stdout: line = line.rstrip("\r\n") if ":" in line: split = line.split(":") if(len(split) <= 3): continue if(line.startswith("/dev")): last_name = split[0] model2.append([last_name]) continue sections = line.split(" ") device = "%s%s" % (last_name, split[0]) filesystem = split[4] if(filesystem.startswith("linux-swap")): filesystem = "swap" size_ = split[3] if(len(split) > 5): boot = split[6] if(boot == "boot;"): model.append([device, filesystem, False, None, size_, True])
|
if "--debug" in sys.argv: model.append(["/dev/debug", "debug", False, None, 0, True]) else: pro = subprocess.Popen("parted -lms", stdout=subprocess.PIPE, shell=True) last_name = "" for line in pro.stdout: line = line.rstrip("\r\n") if ":" in line: split = line.split(":") if(len(split) <= 3): continue if(line.startswith("/dev")): last_name = split[0] model2.append([last_name]) continue sections = line.split(" ") device = "%s%s" % (last_name, split[0]) filesystem = split[4] if(filesystem.startswith("linux-swap")): filesystem = "swap" size_ = split[3] if(len(split) > 5): boot = split[6] if(boot == "boot;"): model.append([device, filesystem, False, None, size_, True]) else: model.append([device, filesystem, False, None, size_, False])
|
def build_disk_list(self): model = gtk.ListStore(str,str,bool,str,str,bool) model2 = gtk.ListStore(str) pro = subprocess.Popen("parted -lms", stdout=subprocess.PIPE, shell=True) last_name = "" for line in pro.stdout: line = line.rstrip("\r\n") if ":" in line: split = line.split(":") if(len(split) <= 3): continue if(line.startswith("/dev")): last_name = split[0] model2.append([last_name]) continue # device list sections = line.split(" ") device = "%s%s" % (last_name, split[0]) filesystem = split[4] # hack. love em eh? ... if(filesystem.startswith("linux-swap")): filesystem = "swap" size_ = split[3] if(len(split) > 5): boot = split[6] if(boot == "boot;"): model.append([device, filesystem, False, None, size_, True]) else: model.append([device, filesystem, False, None, size_, False]) else: model.append([device, filesystem, False, None, size_, False]) print "%s - %s" % (device, filesystem) self.wTree.get_widget("treeview_disks").set_model(model) self.wTree.get_widget("combobox_grub").set_model(model2) self.wTree.get_widget("combobox_grub").set_active(0)
|
else: model.append([device, filesystem, False, None, size_, False]) print "%s - %s" % (device, filesystem)
|
print "%s - %s" % (device, filesystem)
|
def build_disk_list(self): model = gtk.ListStore(str,str,bool,str,str,bool) model2 = gtk.ListStore(str) pro = subprocess.Popen("parted -lms", stdout=subprocess.PIPE, shell=True) last_name = "" for line in pro.stdout: line = line.rstrip("\r\n") if ":" in line: split = line.split(":") if(len(split) <= 3): continue if(line.startswith("/dev")): last_name = split[0] model2.append([last_name]) continue # device list sections = line.split(" ") device = "%s%s" % (last_name, split[0]) filesystem = split[4] # hack. love em eh? ... if(filesystem.startswith("linux-swap")): filesystem = "swap" size_ = split[3] if(len(split) > 5): boot = split[6] if(boot == "boot;"): model.append([device, filesystem, False, None, size_, True]) else: model.append([device, filesystem, False, None, size_, False]) else: model.append([device, filesystem, False, None, size_, False]) print "%s - %s" % (device, filesystem) self.wTree.get_widget("treeview_disks").set_model(model) self.wTree.get_widget("combobox_grub").set_model(model2) self.wTree.get_widget("combobox_grub").set_active(0)
|
sys.exit(0)
|
def do_install(self): ''' Actually perform the installation .. ''' inst = self.installer # Create fstab files = fstab() model = self.wTree.get_widget("treeview_disks").get_model() for row in model: if(row[2] or row[3] is not None): # format or mountpoint specified. files.add_mount(device=row[0], mountpoint=row[3], filesystem=row[1], format=row[2]) inst.fstab = files # need to add set_fstab() to InstallerEngine # set up the system user username = self.wTree.get_widget("entry_username").get_text() password = self.wTree.get_widget("entry_userpass1").get_text() realname = self.wTree.get_widget("entry_your_name").get_text() hostname = self.wTree.get_widget("entry_hostname").get_text() user = SystemUser(username=username, password=password, realname=realname) inst.set_main_user(user) inst.set_hostname(hostname) # set language inst.set_locale(self.locale) # set keyboard inst.set_keyboard_options(layout=self.keyboard_layout, model=self.keyboard_model)
|
|
self.run_in_chroot("echo \"
|
os.system("echo \"
|
def install(self): ''' Install this baby to disk ''' # mount the media location. try: if(not os.path.exists("/target")): os.mkdir("/target") if(not os.path.exists("/source")): os.mkdir("/source") # find the squashfs.. root = self.media root_type = self.media_type if(not os.path.exists(root)): print _("Base filesystem does not exist! Bailing") sys.exit(1) # change to report root_device = None # format partitions as appropriate for item in self.fstab.get_entries(): if(item.mountpoint == "/"): root_device = item item.format = True if(item.format): # well now, we gets to nuke stuff. # report it. should grab the total count of filesystems to be formatted .. self.update_progress(total=4, current=1, pulse=True, message=_("Formatting %s as %s..." % (item.device, item.filesystem))) self.format_device(item.device, item.filesystem) # mount filesystem self.update_progress(total=4, current=2, message=_("Mounting %s on %s") % (root, "/source/")) self.do_mount(root, "/source/", root_type, options="loop") self.update_progress(total=4, current=3, message=_("Mounting %s on %s") % (root_device.device, "/target/")) self.do_mount(root_device.device, "/target", root_device.filesystem, None) # walk root filesystem. we're too lazy though :P SOURCE = "/source/" DEST = "/target/" directory_times = [] our_total = 0 our_current = -1 os.chdir(SOURCE) # index the files for top,dirs,files in os.walk(SOURCE, topdown=False): our_total += len(dirs) + len(files) self.update_progress(pulse=True, message=_("Indexing files to be copied..")) our_total += 1 # safenessness for top,dirs,files in os.walk(SOURCE): # Sanity check. Python is a bit schitzo dirpath = top if(dirpath.startswith(SOURCE)): dirpath = dirpath[len(SOURCE):] for name in dirs + files: # following is hacked/copied from Ubiquity rpath = os.path.join(dirpath, name) sourcepath = os.path.join(SOURCE, rpath) targetpath = os.path.join(DEST, rpath) st = os.lstat(sourcepath) mode = stat.S_IMODE(st.st_mode)
|
self.run_in_chroot("echo \"%s.UTF-8 UTF-8\" >> /etc/locale.gen" % self.locale)
|
os.system("echo \"%s.UTF-8 UTF-8\" >> /target/etc/locale.gen" % self.locale)
|
def install(self): ''' Install this baby to disk ''' # mount the media location. try: if(not os.path.exists("/target")): os.mkdir("/target") if(not os.path.exists("/source")): os.mkdir("/source") # find the squashfs.. root = self.media root_type = self.media_type if(not os.path.exists(root)): print _("Base filesystem does not exist! Bailing") sys.exit(1) # change to report root_device = None # format partitions as appropriate for item in self.fstab.get_entries(): if(item.mountpoint == "/"): root_device = item item.format = True if(item.format): # well now, we gets to nuke stuff. # report it. should grab the total count of filesystems to be formatted .. self.update_progress(total=4, current=1, pulse=True, message=_("Formatting %s as %s..." % (item.device, item.filesystem))) self.format_device(item.device, item.filesystem) # mount filesystem self.update_progress(total=4, current=2, message=_("Mounting %s on %s") % (root, "/source/")) self.do_mount(root, "/source/", root_type, options="loop") self.update_progress(total=4, current=3, message=_("Mounting %s on %s") % (root_device.device, "/target/")) self.do_mount(root_device.device, "/target", root_device.filesystem, None) # walk root filesystem. we're too lazy though :P SOURCE = "/source/" DEST = "/target/" directory_times = [] our_total = 0 our_current = -1 os.chdir(SOURCE) # index the files for top,dirs,files in os.walk(SOURCE, topdown=False): our_total += len(dirs) + len(files) self.update_progress(pulse=True, message=_("Indexing files to be copied..")) our_total += 1 # safenessness for top,dirs,files in os.walk(SOURCE): # Sanity check. Python is a bit schitzo dirpath = top if(dirpath.startswith(SOURCE)): dirpath = dirpath[len(SOURCE):] for name in dirs + files: # following is hacked/copied from Ubiquity rpath = os.path.join(dirpath, name) sourcepath = os.path.join(SOURCE, rpath) targetpath = os.path.join(DEST, rpath) st = os.lstat(sourcepath) mode = stat.S_IMODE(st.st_mode)
|
self.run_in_chroot("echo \"\" > /etc/default/locale")
|
os.system("echo \"\" > /target/etc/default/locale")
|
def install(self): ''' Install this baby to disk ''' # mount the media location. try: if(not os.path.exists("/target")): os.mkdir("/target") if(not os.path.exists("/source")): os.mkdir("/source") # find the squashfs.. root = self.media root_type = self.media_type if(not os.path.exists(root)): print _("Base filesystem does not exist! Bailing") sys.exit(1) # change to report root_device = None # format partitions as appropriate for item in self.fstab.get_entries(): if(item.mountpoint == "/"): root_device = item item.format = True if(item.format): # well now, we gets to nuke stuff. # report it. should grab the total count of filesystems to be formatted .. self.update_progress(total=4, current=1, pulse=True, message=_("Formatting %s as %s..." % (item.device, item.filesystem))) self.format_device(item.device, item.filesystem) # mount filesystem self.update_progress(total=4, current=2, message=_("Mounting %s on %s") % (root, "/source/")) self.do_mount(root, "/source/", root_type, options="loop") self.update_progress(total=4, current=3, message=_("Mounting %s on %s") % (root_device.device, "/target/")) self.do_mount(root_device.device, "/target", root_device.filesystem, None) # walk root filesystem. we're too lazy though :P SOURCE = "/source/" DEST = "/target/" directory_times = [] our_total = 0 our_current = -1 os.chdir(SOURCE) # index the files for top,dirs,files in os.walk(SOURCE, topdown=False): our_total += len(dirs) + len(files) self.update_progress(pulse=True, message=_("Indexing files to be copied..")) our_total += 1 # safenessness for top,dirs,files in os.walk(SOURCE): # Sanity check. Python is a bit schitzo dirpath = top if(dirpath.startswith(SOURCE)): dirpath = dirpath[len(SOURCE):] for name in dirs + files: # following is hacked/copied from Ubiquity rpath = os.path.join(dirpath, name) sourcepath = os.path.join(SOURCE, rpath) targetpath = os.path.join(DEST, rpath) st = os.lstat(sourcepath) mode = stat.S_IMODE(st.st_mode)
|
self.run_in_chroot("echo \"%s\" > /etc/timezone" % self.timezone_code) self.run_in_chroot("cp /usr/share/zoneinfo/%s /etc/localtime" % self.timezone)
|
os.system("echo \"%s\" > /target/etc/timezone" % self.timezone_code) os.system("cp /target/usr/share/zoneinfo/%s /target/etc/localtime" % self.timezone)
|
def install(self): ''' Install this baby to disk ''' # mount the media location. try: if(not os.path.exists("/target")): os.mkdir("/target") if(not os.path.exists("/source")): os.mkdir("/source") # find the squashfs.. root = self.media root_type = self.media_type if(not os.path.exists(root)): print _("Base filesystem does not exist! Bailing") sys.exit(1) # change to report root_device = None # format partitions as appropriate for item in self.fstab.get_entries(): if(item.mountpoint == "/"): root_device = item item.format = True if(item.format): # well now, we gets to nuke stuff. # report it. should grab the total count of filesystems to be formatted .. self.update_progress(total=4, current=1, pulse=True, message=_("Formatting %s as %s..." % (item.device, item.filesystem))) self.format_device(item.device, item.filesystem) # mount filesystem self.update_progress(total=4, current=2, message=_("Mounting %s on %s") % (root, "/source/")) self.do_mount(root, "/source/", root_type, options="loop") self.update_progress(total=4, current=3, message=_("Mounting %s on %s") % (root_device.device, "/target/")) self.do_mount(root_device.device, "/target", root_device.filesystem, None) # walk root filesystem. we're too lazy though :P SOURCE = "/source/" DEST = "/target/" directory_times = [] our_total = 0 our_current = -1 os.chdir(SOURCE) # index the files for top,dirs,files in os.walk(SOURCE, topdown=False): our_total += len(dirs) + len(files) self.update_progress(pulse=True, message=_("Indexing files to be copied..")) our_total += 1 # safenessness for top,dirs,files in os.walk(SOURCE): # Sanity check. Python is a bit schitzo dirpath = top if(dirpath.startswith(SOURCE)): dirpath = dirpath[len(SOURCE):] for name in dirs + files: # following is hacked/copied from Ubiquity rpath = os.path.join(dirpath, name) sourcepath = os.path.join(SOURCE, rpath) targetpath = os.path.join(DEST, rpath) st = os.lstat(sourcepath) mode = stat.S_IMODE(st.st_mode)
|
self.window.window.set_cursor(cursor) gtk.gdk.threads_leave()
|
self.window.window.set_cursor(cursor)
|
def build_partitions(self): gtk.gdk.threads_enter() self.window.set_sensitive(False) # "busy" cursor. cursor = gtk.gdk.Cursor(gtk.gdk.WATCH) self.window.window.set_cursor(cursor) gtk.gdk.threads_leave() from progress import ProgressDialog dialog = ProgressDialog() dialog.show(title=_("Installer"), label=_("Scanning disk %s for partitions") % self.device_node) import parted, commands from screen import Partition os.popen('mkdir -p /tmp/live-installer/tmpmount') # disks that you can install grub to grub_model = gtk.ListStore(str) hdd_descriptions = [] inxi = commands.getoutput("inxi -D -c 0") parts = inxi.split(":") partitions = [] path = self.device_node # i.e. /dev/sda grub_model.append([path]) device = parted.getDevice(path) disk = parted.Disk(device) partition = disk.getFirstPartition() last_added_partition = Partition(partition) partitions.append(last_added_partition) partition = partition.nextPartition() while (partition is not None): if last_added_partition.partition.number == -1 and partition.number == -1: last_added_partition.add_partition(partition) else: last_added_partition = Partition(partition) partitions.append(last_added_partition) if partition.number != -1 and "swap" not in last_added_partition.type: #Umount temp folder if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') #Mount partition if not mounted if (partition.path not in commands.getoutput('mount')): os.system("mount %s /tmp/live-installer/tmpmount" % partition.path) #Identify partition's description and used space if (partition.path in commands.getoutput('mount')): last_added_partition.used_space = commands.getoutput("df | grep %s | awk {'print $5'}" % partition.path) mount_point = commands.getoutput("df | grep %s | awk {'print $6'}" % partition.path) if os.path.exists(os.path.join(mount_point, 'etc/lsb-release')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/lsb-release') + " | grep DISTRIB_DESCRIPTION").replace('DISTRIB_DESCRIPTION', '').replace('=', '').replace('"', '').strip() elif os.path.exists(os.path.join(mount_point, 'etc/issue')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/issue')).replace('\\n', '').replace('\l', '').strip() elif os.path.exists(os.path.join(mount_point, 'Windows/servicing/Version')): version = commands.getoutput("ls %s" % os.path.join(mount_point, 'Windows/servicing/Version')) if version.startswith("6.1"): last_added_partition.description = "Windows 7" elif version.startswith("6.0"): last_added_partition.description = "Windows Vista" elif version.startswith("5.1") or version.startswith("5.2"): last_added_partition.description = "Windows XP" elif version.startswith("5.0"): last_added_partition.description = "Windows 2000" elif version.startswith("4.90"): last_added_partition.description = "Windows Me" elif version.startswith("4.1"): last_added_partition.description = "Windows 98" elif version.startswith("4.0.1381"): last_added_partition.description = "Windows NT" elif version.startswith("4.0.950"): last_added_partition.description = "Windows 95" elif os.path.exists(os.path.join(mount_point, 'Boot/BCD')): if os.system("grep -qs \"V.i.s.t.a\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Vista bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .7\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows 7 bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .R.e.c.o.v.e.r.y. .E.n.v.i.r.o.n.m.e.n.t\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows recovery" elif os.system("grep -qs \"W.i.n.d.o.w.s. .S.e.r.v.e.r. .2.0.0.8\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Server 2008 bootloader" else: last_added_partition.description = "Windows bootloader" elif os.path.exists(os.path.join(mount_point, 'Windows/System32')): last_added_partition.description = "Windows" #Umount temp folder if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') partition = partition.nextPartition() from screen import Screen gtk.gdk.threads_enter() myScreen = Screen(partitions) self.part_screen = myScreen kids = self.wTree.get_widget("vbox_cairo").get_children() if(kids is not None): for sprog in kids: self.wTree.get_widget("vbox_cairo").remove(sprog) self.wTree.get_widget("vbox_cairo").add(myScreen) self.wTree.get_widget("vbox_cairo").show_all() color = self.wTree.get_widget("notebook1").style.bg[gtk.STATE_ACTIVE] self.part_screen.modify_bg(gtk.STATE_NORMAL, color) gtk.gdk.threads_leave() model = gtk.ListStore(str,str,bool,str,str,bool, str, str, str) model2 = gtk.ListStore(str) for partition in partitions: if partition.size > 0.5: if partition.partition.number == -1: model.append(["<small><span foreground='#555555'>" + partition.name + "</span></small>", partition.type, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.used_space]) elif partition.real_type == parted.PARTITION_EXTENDED: print "Extended partition" model.append(["<small><span foreground='#555555'>extended partition</span></small>", None, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.used_space]) else: if partition.description != "": model.append([partition.name, "%s (%s)" % (partition.description, partition.type), False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.used_space]) else: model.append([partition.name, partition.type, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.used_space]) gtk.gdk.threads_enter() self.wTree.get_widget("treeview_disks").set_model(model) self.wTree.get_widget("combobox_grub").set_model(grub_model) self.wTree.get_widget("combobox_grub").set_active(0) gtk.gdk.threads_leave() dialog.hide() gtk.gdk.threads_enter() self.window.set_sensitive(True) self.window.window.set_cursor(None) gtk.gdk.threads_leave()
|
section = line.split(":")[2].strip(" ") if("/dev/" in section): device = section.split(" ")[0].replace(" ","") self.disks[device] = section if(parent is None): self.device_node = device radio = gtk.RadioButton(None) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(section) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) parent = radio else: radio = gtk.RadioButton(parent) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(section) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False)
|
sections = line.split(":") for section in sections: section = section.strip() if("/dev/" in section): device = section.split(" ")[0].replace(" ","") self.disks[device] = section if(parent is None): self.device_node = device radio = gtk.RadioButton(None) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(section) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) parent = radio else: radio = gtk.RadioButton(parent) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(section) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False)
|
def build_disks(self): import subprocess self.disks = {} inxi = subprocess.Popen("inxi -c0 -D", shell=True, stdout=subprocess.PIPE) parent = None for line in inxi.stdout: line = line.rstrip("\r\n") if(line.startswith("Disks:")): line = line.replace("Disks:", "") device = None section = line.split(":")[2].strip(" ") if("/dev/" in section): device = section.split(" ")[0].replace(" ","") self.disks[device] = section if(parent is None): self.device_node = device radio = gtk.RadioButton(None) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(section) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) parent = radio else: radio = gtk.RadioButton(parent) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(section) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) self.wTree.get_widget("vbox_disks").show_all()
|
our_total = 9
|
our_total = 10
|
def install(self): ''' Install this baby to disk ''' # mount the media location. print " --> Installation started" try: if(not os.path.exists("/target")): os.mkdir("/target") if(not os.path.exists("/source")): os.mkdir("/source") # find the squashfs.. root = self.media root_type = self.media_type if(not os.path.exists(root)): print "Base filesystem does not exist! Critical error (exiting)." sys.exit(1) # change to report root_device = None # format partitions as appropriate for item in self.fstab.get_entries(): if(item.mountpoint == "/"): root_device = item item.format = True if(item.format): # well now, we gets to nuke stuff. # report it. should grab the total count of filesystems to be formatted .. self.update_progress(total=4, current=1, pulse=True, message=_("Formatting %s as %s..." % (item.device, item.filesystem))) self.format_device(item.device, item.filesystem) # mount filesystem print " --> Mounting partitions" self.update_progress(total=4, current=2, message=_("Mounting %s on %s") % (root, "/source/")) self.do_mount(root, "/source/", root_type, options="loop") self.update_progress(total=4, current=3, message=_("Mounting %s on %s") % (root_device.device, "/target/")) self.do_mount(root_device.device, "/target", root_device.filesystem, None) # walk root filesystem. we're too lazy though :P SOURCE = "/source/" DEST = "/target/" directory_times = [] our_total = 0 our_current = -1 os.chdir(SOURCE) # index the files print " --> Indexing files" for top,dirs,files in os.walk(SOURCE, topdown=False): our_total += len(dirs) + len(files) self.update_progress(pulse=True, message=_("Indexing files to be copied..")) our_total += 1 # safenessness print " --> Copying files" for top,dirs,files in os.walk(SOURCE): # Sanity check. Python is a bit schitzo dirpath = top if(dirpath.startswith(SOURCE)): dirpath = dirpath[len(SOURCE):] for name in dirs + files: # following is hacked/copied from Ubiquity rpath = os.path.join(dirpath, name) sourcepath = os.path.join(SOURCE, rpath) targetpath = os.path.join(DEST, rpath) st = os.lstat(sourcepath) mode = stat.S_IMODE(st.st_mode)
|
self.device_node = device
|
def build_disks(self): gtk.gdk.threads_enter() import subprocess self.disks = {} inxi = subprocess.Popen("inxi -c0 -D", shell=True, stdout=subprocess.PIPE) parent = None for line in inxi.stdout: line = line.rstrip("\r\n") if(line.startswith("Disks:")): line = line.replace("Disks:", "") device = None sections = line.split(":") for section in sections: section = section.strip() if("/dev/" in section): device = None elements = section.split() for element in elements: if "/dev/" in element: device = element if elements[len(elements) -1].endswith("GB") or elements[elements[len(elements) -1]].endswith("GB"): size = elements[len(elements) -1] section = section.replace(size, "(%s)" % size) if device is not None: description = section.replace(device, "").strip() description = description.replace(" ", " ") self.disks[device] = description if(parent is None): self.device_node = device radio = gtk.RadioButton(None) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) parent = radio else: radio = gtk.RadioButton(parent) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) self.wTree.get_widget("vbox_disks").show_all() gtk.gdk.threads_leave()
|
|
radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False)
|
def build_disks(self): gtk.gdk.threads_enter() import subprocess self.disks = {} inxi = subprocess.Popen("inxi -c0 -D", shell=True, stdout=subprocess.PIPE) parent = None for line in inxi.stdout: line = line.rstrip("\r\n") if(line.startswith("Disks:")): line = line.replace("Disks:", "") device = None sections = line.split(":") for section in sections: section = section.strip() if("/dev/" in section): device = None elements = section.split() for element in elements: if "/dev/" in element: device = element if elements[len(elements) -1].endswith("GB") or elements[elements[len(elements) -1]].endswith("GB"): size = elements[len(elements) -1] section = section.replace(size, "(%s)" % size) if device is not None: description = section.replace(device, "").strip() description = description.replace(" ", " ") self.disks[device] = description if(parent is None): self.device_node = device radio = gtk.RadioButton(None) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) parent = radio else: radio = gtk.RadioButton(parent) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) self.wTree.get_widget("vbox_disks").show_all() gtk.gdk.threads_leave()
|
|
radio = gtk.RadioButton(parent) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False)
|
radio = gtk.RadioButton(parent) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) grub_model.append([device])
|
def build_disks(self): gtk.gdk.threads_enter() import subprocess self.disks = {} inxi = subprocess.Popen("inxi -c0 -D", shell=True, stdout=subprocess.PIPE) parent = None for line in inxi.stdout: line = line.rstrip("\r\n") if(line.startswith("Disks:")): line = line.replace("Disks:", "") device = None sections = line.split(":") for section in sections: section = section.strip() if("/dev/" in section): device = None elements = section.split() for element in elements: if "/dev/" in element: device = element if elements[len(elements) -1].endswith("GB") or elements[elements[len(elements) -1]].endswith("GB"): size = elements[len(elements) -1] section = section.replace(size, "(%s)" % size) if device is not None: description = section.replace(device, "").strip() description = description.replace(" ", " ") self.disks[device] = description if(parent is None): self.device_node = device radio = gtk.RadioButton(None) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) parent = radio else: radio = gtk.RadioButton(parent) radio.connect("clicked", self.select_disk_cb, device) radio.set_label(description) self.wTree.get_widget("vbox_disks").pack_start(radio, expand=False, fill=False) self.wTree.get_widget("vbox_disks").show_all() gtk.gdk.threads_leave()
|
grub_model = gtk.ListStore(str)
|
def build_partitions(self): gtk.gdk.threads_enter() self.window.set_sensitive(False) # "busy" cursor. cursor = gtk.gdk.Cursor(gtk.gdk.WATCH) self.window.window.set_cursor(cursor) from progress import ProgressDialog dialog = ProgressDialog() dialog.show(title=_("Installer"), label=_("Scanning disk %s for partitions") % self.device_node) gtk.gdk.threads_leave() from screen import Partition os.popen('mkdir -p /tmp/live-installer/tmpmount') # disks that you can install grub to grub_model = gtk.ListStore(str) partitions = [] path = self.device_node # i.e. /dev/sda grub_model.append([path]) device = parted.getDevice(path) disk = parted.Disk(device) partition = disk.getFirstPartition() last_added_partition = Partition(partition) partitions.append(last_added_partition) partition = partition.nextPartition() while (partition is not None): if last_added_partition.partition.number == -1 and partition.number == -1: last_added_partition.add_partition(partition) else: last_added_partition = Partition(partition) partitions.append(last_added_partition) if partition.number != -1 and "swap" not in last_added_partition.type: #Umount temp folder if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') #Mount partition if not mounted if (partition.path not in commands.getoutput('mount')): os.system("mount %s /tmp/live-installer/tmpmount" % partition.path) #Identify partition's description and used space if (partition.path in commands.getoutput('mount')): last_added_partition.used_space = commands.getoutput("df | grep %s | awk {'print $5'}" % partition.path) if "%" in last_added_partition.used_space: used_space_pct = int(last_added_partition.used_space.replace("%", "").strip()) last_added_partition.free_space = int(float(last_added_partition.size) * (float(100) - float(used_space_pct)) / float(100)) mount_point = commands.getoutput("df | grep %s | awk {'print $6'}" % partition.path) if os.path.exists(os.path.join(mount_point, 'etc/lsb-release')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/lsb-release') + " | grep DISTRIB_DESCRIPTION").replace('DISTRIB_DESCRIPTION', '').replace('=', '').replace('"', '').strip() elif os.path.exists(os.path.join(mount_point, 'etc/issue')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/issue')).replace('\\n', '').replace('\l', '').strip() elif os.path.exists(os.path.join(mount_point, 'Windows/servicing/Version')): version = commands.getoutput("ls %s" % os.path.join(mount_point, 'Windows/servicing/Version')) if version.startswith("6.1"): last_added_partition.description = "Windows 7" elif version.startswith("6.0"): last_added_partition.description = "Windows Vista" elif version.startswith("5.1") or version.startswith("5.2"): last_added_partition.description = "Windows XP" elif version.startswith("5.0"): last_added_partition.description = "Windows 2000" elif version.startswith("4.90"): last_added_partition.description = "Windows Me" elif version.startswith("4.1"): last_added_partition.description = "Windows 98" elif version.startswith("4.0.1381"): last_added_partition.description = "Windows NT" elif version.startswith("4.0.950"): last_added_partition.description = "Windows 95" elif os.path.exists(os.path.join(mount_point, 'Boot/BCD')): if os.system("grep -qs \"V.i.s.t.a\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Vista bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .7\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows 7 bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .R.e.c.o.v.e.r.y. .E.n.v.i.r.o.n.m.e.n.t\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows recovery" elif os.system("grep -qs \"W.i.n.d.o.w.s. .S.e.r.v.e.r. .2.0.0.8\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Server 2008 bootloader" else: last_added_partition.description = "Windows bootloader" elif os.path.exists(os.path.join(mount_point, 'Windows/System32')): last_added_partition.description = "Windows" #Umount temp folder if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') partition = partition.nextPartition() from screen import Screen gtk.gdk.threads_enter() myScreen = Screen(partitions) self.part_screen = myScreen kids = self.wTree.get_widget("vbox_cairo").get_children() if(kids is not None): for sprog in kids: self.wTree.get_widget("vbox_cairo").remove(sprog) self.wTree.get_widget("vbox_cairo").add(myScreen) self.wTree.get_widget("vbox_cairo").show_all() color = self.wTree.get_widget("notebook1").style.bg[gtk.STATE_ACTIVE] self.part_screen.modify_bg(gtk.STATE_NORMAL, color) gtk.gdk.threads_leave() model = gtk.ListStore(str,str,bool,str,str,bool, str, str, str, bool, object) model2 = gtk.ListStore(str) extended_sectors = [-1, -1] colors = [ "#010510", "#000099", "#009999", "#009900", "#999999", "#990000" ] for partition in partitions: if partition.size > 0.5: color = colors[partition.partition.number % len(colors)] if partition.real_type == parted.PARTITION_LOGICAL: display_name = " " + partition.name else: display_name = partition.name if partition.partition.number == -1: model.append(["<small><span foreground='#555555'>" + display_name + "</span></small>", partition.type, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, False, partition]) elif partition.real_type == parted.PARTITION_EXTENDED: model.append(["<small><span foreground='#555555'>extended partition</span></small>", None, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, False, partition]) else: if partition.description != "": model.append(["<span foreground='" + color + "'>" + display_name + "</span>", "%s (%s)" % (partition.description, partition.type), False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, True, partition]) else: model.append(["<span foreground='" + color + "'>" + display_name + "</span>", partition.type, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, True, partition]) gtk.gdk.threads_enter() self.wTree.get_widget("treeview_disks").set_model(model) self.wTree.get_widget("combobox_grub").set_model(grub_model) self.wTree.get_widget("combobox_grub").set_active(0) gtk.gdk.threads_leave() dialog.hide() gtk.gdk.threads_enter() self.window.set_sensitive(True) self.window.window.set_cursor(None) gtk.gdk.threads_leave()
|
|
path = self.device_node grub_model.append([path])
|
path = self.device_node
|
def build_partitions(self): gtk.gdk.threads_enter() self.window.set_sensitive(False) # "busy" cursor. cursor = gtk.gdk.Cursor(gtk.gdk.WATCH) self.window.window.set_cursor(cursor) from progress import ProgressDialog dialog = ProgressDialog() dialog.show(title=_("Installer"), label=_("Scanning disk %s for partitions") % self.device_node) gtk.gdk.threads_leave() from screen import Partition os.popen('mkdir -p /tmp/live-installer/tmpmount') # disks that you can install grub to grub_model = gtk.ListStore(str) partitions = [] path = self.device_node # i.e. /dev/sda grub_model.append([path]) device = parted.getDevice(path) disk = parted.Disk(device) partition = disk.getFirstPartition() last_added_partition = Partition(partition) partitions.append(last_added_partition) partition = partition.nextPartition() while (partition is not None): if last_added_partition.partition.number == -1 and partition.number == -1: last_added_partition.add_partition(partition) else: last_added_partition = Partition(partition) partitions.append(last_added_partition) if partition.number != -1 and "swap" not in last_added_partition.type: #Umount temp folder if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') #Mount partition if not mounted if (partition.path not in commands.getoutput('mount')): os.system("mount %s /tmp/live-installer/tmpmount" % partition.path) #Identify partition's description and used space if (partition.path in commands.getoutput('mount')): last_added_partition.used_space = commands.getoutput("df | grep %s | awk {'print $5'}" % partition.path) if "%" in last_added_partition.used_space: used_space_pct = int(last_added_partition.used_space.replace("%", "").strip()) last_added_partition.free_space = int(float(last_added_partition.size) * (float(100) - float(used_space_pct)) / float(100)) mount_point = commands.getoutput("df | grep %s | awk {'print $6'}" % partition.path) if os.path.exists(os.path.join(mount_point, 'etc/lsb-release')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/lsb-release') + " | grep DISTRIB_DESCRIPTION").replace('DISTRIB_DESCRIPTION', '').replace('=', '').replace('"', '').strip() elif os.path.exists(os.path.join(mount_point, 'etc/issue')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/issue')).replace('\\n', '').replace('\l', '').strip() elif os.path.exists(os.path.join(mount_point, 'Windows/servicing/Version')): version = commands.getoutput("ls %s" % os.path.join(mount_point, 'Windows/servicing/Version')) if version.startswith("6.1"): last_added_partition.description = "Windows 7" elif version.startswith("6.0"): last_added_partition.description = "Windows Vista" elif version.startswith("5.1") or version.startswith("5.2"): last_added_partition.description = "Windows XP" elif version.startswith("5.0"): last_added_partition.description = "Windows 2000" elif version.startswith("4.90"): last_added_partition.description = "Windows Me" elif version.startswith("4.1"): last_added_partition.description = "Windows 98" elif version.startswith("4.0.1381"): last_added_partition.description = "Windows NT" elif version.startswith("4.0.950"): last_added_partition.description = "Windows 95" elif os.path.exists(os.path.join(mount_point, 'Boot/BCD')): if os.system("grep -qs \"V.i.s.t.a\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Vista bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .7\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows 7 bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .R.e.c.o.v.e.r.y. .E.n.v.i.r.o.n.m.e.n.t\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows recovery" elif os.system("grep -qs \"W.i.n.d.o.w.s. .S.e.r.v.e.r. .2.0.0.8\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Server 2008 bootloader" else: last_added_partition.description = "Windows bootloader" elif os.path.exists(os.path.join(mount_point, 'Windows/System32')): last_added_partition.description = "Windows" #Umount temp folder if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') partition = partition.nextPartition() from screen import Screen gtk.gdk.threads_enter() myScreen = Screen(partitions) self.part_screen = myScreen kids = self.wTree.get_widget("vbox_cairo").get_children() if(kids is not None): for sprog in kids: self.wTree.get_widget("vbox_cairo").remove(sprog) self.wTree.get_widget("vbox_cairo").add(myScreen) self.wTree.get_widget("vbox_cairo").show_all() color = self.wTree.get_widget("notebook1").style.bg[gtk.STATE_ACTIVE] self.part_screen.modify_bg(gtk.STATE_NORMAL, color) gtk.gdk.threads_leave() model = gtk.ListStore(str,str,bool,str,str,bool, str, str, str, bool, object) model2 = gtk.ListStore(str) extended_sectors = [-1, -1] colors = [ "#010510", "#000099", "#009999", "#009900", "#999999", "#990000" ] for partition in partitions: if partition.size > 0.5: color = colors[partition.partition.number % len(colors)] if partition.real_type == parted.PARTITION_LOGICAL: display_name = " " + partition.name else: display_name = partition.name if partition.partition.number == -1: model.append(["<small><span foreground='#555555'>" + display_name + "</span></small>", partition.type, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, False, partition]) elif partition.real_type == parted.PARTITION_EXTENDED: model.append(["<small><span foreground='#555555'>extended partition</span></small>", None, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, False, partition]) else: if partition.description != "": model.append(["<span foreground='" + color + "'>" + display_name + "</span>", "%s (%s)" % (partition.description, partition.type), False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, True, partition]) else: model.append(["<span foreground='" + color + "'>" + display_name + "</span>", partition.type, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, True, partition]) gtk.gdk.threads_enter() self.wTree.get_widget("treeview_disks").set_model(model) self.wTree.get_widget("combobox_grub").set_model(grub_model) self.wTree.get_widget("combobox_grub").set_active(0) gtk.gdk.threads_leave() dialog.hide() gtk.gdk.threads_enter() self.window.set_sensitive(True) self.window.window.set_cursor(None) gtk.gdk.threads_leave()
|
self.wTree.get_widget("treeview_disks").set_model(model) self.wTree.get_widget("combobox_grub").set_model(grub_model) self.wTree.get_widget("combobox_grub").set_active(0)
|
self.wTree.get_widget("treeview_disks").set_model(model)
|
def build_partitions(self): gtk.gdk.threads_enter() self.window.set_sensitive(False) # "busy" cursor. cursor = gtk.gdk.Cursor(gtk.gdk.WATCH) self.window.window.set_cursor(cursor) from progress import ProgressDialog dialog = ProgressDialog() dialog.show(title=_("Installer"), label=_("Scanning disk %s for partitions") % self.device_node) gtk.gdk.threads_leave() from screen import Partition os.popen('mkdir -p /tmp/live-installer/tmpmount') # disks that you can install grub to grub_model = gtk.ListStore(str) partitions = [] path = self.device_node # i.e. /dev/sda grub_model.append([path]) device = parted.getDevice(path) disk = parted.Disk(device) partition = disk.getFirstPartition() last_added_partition = Partition(partition) partitions.append(last_added_partition) partition = partition.nextPartition() while (partition is not None): if last_added_partition.partition.number == -1 and partition.number == -1: last_added_partition.add_partition(partition) else: last_added_partition = Partition(partition) partitions.append(last_added_partition) if partition.number != -1 and "swap" not in last_added_partition.type: #Umount temp folder if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') #Mount partition if not mounted if (partition.path not in commands.getoutput('mount')): os.system("mount %s /tmp/live-installer/tmpmount" % partition.path) #Identify partition's description and used space if (partition.path in commands.getoutput('mount')): last_added_partition.used_space = commands.getoutput("df | grep %s | awk {'print $5'}" % partition.path) if "%" in last_added_partition.used_space: used_space_pct = int(last_added_partition.used_space.replace("%", "").strip()) last_added_partition.free_space = int(float(last_added_partition.size) * (float(100) - float(used_space_pct)) / float(100)) mount_point = commands.getoutput("df | grep %s | awk {'print $6'}" % partition.path) if os.path.exists(os.path.join(mount_point, 'etc/lsb-release')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/lsb-release') + " | grep DISTRIB_DESCRIPTION").replace('DISTRIB_DESCRIPTION', '').replace('=', '').replace('"', '').strip() elif os.path.exists(os.path.join(mount_point, 'etc/issue')): last_added_partition.description = commands.getoutput("cat " + os.path.join(mount_point, 'etc/issue')).replace('\\n', '').replace('\l', '').strip() elif os.path.exists(os.path.join(mount_point, 'Windows/servicing/Version')): version = commands.getoutput("ls %s" % os.path.join(mount_point, 'Windows/servicing/Version')) if version.startswith("6.1"): last_added_partition.description = "Windows 7" elif version.startswith("6.0"): last_added_partition.description = "Windows Vista" elif version.startswith("5.1") or version.startswith("5.2"): last_added_partition.description = "Windows XP" elif version.startswith("5.0"): last_added_partition.description = "Windows 2000" elif version.startswith("4.90"): last_added_partition.description = "Windows Me" elif version.startswith("4.1"): last_added_partition.description = "Windows 98" elif version.startswith("4.0.1381"): last_added_partition.description = "Windows NT" elif version.startswith("4.0.950"): last_added_partition.description = "Windows 95" elif os.path.exists(os.path.join(mount_point, 'Boot/BCD')): if os.system("grep -qs \"V.i.s.t.a\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Vista bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .7\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows 7 bootloader" elif os.system("grep -qs \"W.i.n.d.o.w.s. .R.e.c.o.v.e.r.y. .E.n.v.i.r.o.n.m.e.n.t\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows recovery" elif os.system("grep -qs \"W.i.n.d.o.w.s. .S.e.r.v.e.r. .2.0.0.8\" " + os.path.join(mount_point, 'Boot/BCD')) == 0: last_added_partition.description = "Windows Server 2008 bootloader" else: last_added_partition.description = "Windows bootloader" elif os.path.exists(os.path.join(mount_point, 'Windows/System32')): last_added_partition.description = "Windows" #Umount temp folder if ('/tmp/live-installer/tmpmount' in commands.getoutput('mount')): os.popen('umount /tmp/live-installer/tmpmount') partition = partition.nextPartition() from screen import Screen gtk.gdk.threads_enter() myScreen = Screen(partitions) self.part_screen = myScreen kids = self.wTree.get_widget("vbox_cairo").get_children() if(kids is not None): for sprog in kids: self.wTree.get_widget("vbox_cairo").remove(sprog) self.wTree.get_widget("vbox_cairo").add(myScreen) self.wTree.get_widget("vbox_cairo").show_all() color = self.wTree.get_widget("notebook1").style.bg[gtk.STATE_ACTIVE] self.part_screen.modify_bg(gtk.STATE_NORMAL, color) gtk.gdk.threads_leave() model = gtk.ListStore(str,str,bool,str,str,bool, str, str, str, bool, object) model2 = gtk.ListStore(str) extended_sectors = [-1, -1] colors = [ "#010510", "#000099", "#009999", "#009900", "#999999", "#990000" ] for partition in partitions: if partition.size > 0.5: color = colors[partition.partition.number % len(colors)] if partition.real_type == parted.PARTITION_LOGICAL: display_name = " " + partition.name else: display_name = partition.name if partition.partition.number == -1: model.append(["<small><span foreground='#555555'>" + display_name + "</span></small>", partition.type, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, False, partition]) elif partition.real_type == parted.PARTITION_EXTENDED: model.append(["<small><span foreground='#555555'>extended partition</span></small>", None, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, False, partition]) else: if partition.description != "": model.append(["<span foreground='" + color + "'>" + display_name + "</span>", "%s (%s)" % (partition.description, partition.type), False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, True, partition]) else: model.append(["<span foreground='" + color + "'>" + display_name + "</span>", partition.type, False, None, '%.0f' % round(partition.size, 0), False, partition.start, partition.end, partition.free_space, True, partition]) gtk.gdk.threads_enter() self.wTree.get_widget("treeview_disks").set_model(model) self.wTree.get_widget("combobox_grub").set_model(grub_model) self.wTree.get_widget("combobox_grub").set_active(0) gtk.gdk.threads_leave() dialog.hide() gtk.gdk.threads_enter() self.window.set_sensitive(True) self.window.window.set_cursor(None) gtk.gdk.threads_leave()
|
cr.set_source_rgba(0, 0, 0, 0) cr.rectangle(event.area.x, event.area.y, event.area.width, event.area.height) cr.clip()
|
def do_expose_event(self, event):
|
|
top = model.append(None) model.set(top, 0, "Filesystem operations")
|
def show_overview(self): ''' build the summary page ''' model = gtk.TreeStore(str) top = model.append(None) model.set(top, 0, "Filesystem operations") top = model.append(None) model.set(top, 0, _("Localization")) iter = model.append(top) model.set(iter, 0, "Language: <b>%s</b>" % self.locale) iter = model.append(top) model.set(iter, 0, "Keyboard layout: <b>%s</b>" % self.keyboard_layout_desc) iter = model.append(top) model.set(iter, 0, "Keyboard model: <b>%s</b>" % self.keyboard_model_desc) top = model.append(None) model.set(top, 0, _("User settings")) username = self.wTree.get_widget("entry_username").get_text() realname = self.wTree.get_widget("entry_your_name").get_text() iter = model.append(top) model.set(iter, 0, "Real name: <b>%s</b>" % realname) iter = model.append(top) model.set(iter, 0, "Username: <b>%s</b>" % username) top = model.append(None) model.set(top, 0, _("System settings")) iter = model.append(top) model.set(iter, 0, "Hostname: <b>%s</b>" % self.wTree.get_widget("entry_hostname").get_text()) install_grub = self.wTree.get_widget("checkbutton_grub").get_active() grub_box = self.wTree.get_widget("combobox_grub") grub_active = grub_box.get_active() grub_model = grub_box.get_model() iter = model.append(top) if(install_grub): model.set(iter, 0, _("Install bootloader to %s" % ("<b>%s</b>" % grub_model[grub_active][0]))) else: model.set(iter, 0, _("Do not install bootloader")) disks = self.wTree.get_widget("treeview_disks").get_model() for item in disks: if(item[2]): # format it iter = model.append(top) model.set(iter, 0, "<b>%s</b>" % (_("Format %s (%s) as %s" % (item[0], item[4], item[1])))) if(item[3] is not None and item[3] is not ""): # mount point iter = model.append(top) model.set(iter, 0, "<b>%s</b>" % (_("Mount %s as %s" % (item[0], item[3])))) self.wTree.get_widget("treeview_overview").set_model(model)
|
|
model.set(iter, 0, "Language: <b>%s</b>" % self.locale)
|
model.set(iter, 0, _("Language: ") + "<b>%s</b>" % self.locale)
|
def show_overview(self): ''' build the summary page ''' model = gtk.TreeStore(str) top = model.append(None) model.set(top, 0, "Filesystem operations") top = model.append(None) model.set(top, 0, _("Localization")) iter = model.append(top) model.set(iter, 0, "Language: <b>%s</b>" % self.locale) iter = model.append(top) model.set(iter, 0, "Keyboard layout: <b>%s</b>" % self.keyboard_layout_desc) iter = model.append(top) model.set(iter, 0, "Keyboard model: <b>%s</b>" % self.keyboard_model_desc) top = model.append(None) model.set(top, 0, _("User settings")) username = self.wTree.get_widget("entry_username").get_text() realname = self.wTree.get_widget("entry_your_name").get_text() iter = model.append(top) model.set(iter, 0, "Real name: <b>%s</b>" % realname) iter = model.append(top) model.set(iter, 0, "Username: <b>%s</b>" % username) top = model.append(None) model.set(top, 0, _("System settings")) iter = model.append(top) model.set(iter, 0, "Hostname: <b>%s</b>" % self.wTree.get_widget("entry_hostname").get_text()) install_grub = self.wTree.get_widget("checkbutton_grub").get_active() grub_box = self.wTree.get_widget("combobox_grub") grub_active = grub_box.get_active() grub_model = grub_box.get_model() iter = model.append(top) if(install_grub): model.set(iter, 0, _("Install bootloader to %s" % ("<b>%s</b>" % grub_model[grub_active][0]))) else: model.set(iter, 0, _("Do not install bootloader")) disks = self.wTree.get_widget("treeview_disks").get_model() for item in disks: if(item[2]): # format it iter = model.append(top) model.set(iter, 0, "<b>%s</b>" % (_("Format %s (%s) as %s" % (item[0], item[4], item[1])))) if(item[3] is not None and item[3] is not ""): # mount point iter = model.append(top) model.set(iter, 0, "<b>%s</b>" % (_("Mount %s as %s" % (item[0], item[3])))) self.wTree.get_widget("treeview_overview").set_model(model)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.