rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
if True:
|
if first:
|
def init(self, first=False): """ set main things up """ self.parser = XMLParser(join(self.configdir, "gui.xml"), join(self.path, "module", "config", "gui_default.xml")) lang = self.parser.xml.elementsByTagName("language").item(0).toElement().text() if not lang: parser = XMLParser(join(self.path, "module", "config", "gui_default.xml")) lang = parser.xml.elementsByTagName("language").item(0).toElement().text()
|
print os.uname()
|
def main(): print "##### System Information #####" print "" print "Platform:", sys.platform print "Operating System:", os.name print "Python:", sys.version.replace("\n", "") print os.uname() print "" try: import pycurl print "pycurl:", pycurl.version except: print "pycurl:", "missing" try: import Crypto print "py-crypto:", Crypto.__version__ except: print "py-crypto:", "missing" try: import OpenSSL print "OpenSSL:", OpenSSL.version.__version__ except: print "OpenSSL:", "missing" try: import Image print "image libary:", Image.VERSION except: print "image libary:", "missing" try: import django print "django:", django.get_version() except: print "django:", "missing" try: import PyQt4.QtCore print "pyqt:", PyQt4.QtCore.PYQT_VERSION_STR except: print "pyqt:", "missing" print "" print "" print "##### System Status #####" print "" print "## pyLoadCore ##" core_err = [] if sys.version_info > (2, 7): core_err.append("Your python version is to new, Please use Python 2.6") if sys.version_info < (2, 5): core_err.append("Your python version is to old, Please use at least Python 2.5") try: import pycurl except: core_err.append("Please install py-curl to use pyLoad.") try: import Image except: core_err.append("Please install py-imaging/pil to use Hoster, which uses captchas.") pipe = subprocess.PIPE try: p = subprocess.call(["tesseract"], stdout=pipe, stderr=pipe) except: core_err.append("Please install tesseract to use Hoster, which uses captchas.") try: p = subprocess.call(["gocr"], stdout=pipe, stderr=pipe) except: core_err.append("Install gocr to use some Hoster, which uses captchas.") try: import OpenSSL except: core_err.append("Install OpenSSL if you want to create a secure connection to the core.") if core_err: print "The system check has detected some errors:" print "" for err in core_err: print err else: print "No Problems detected, pyLoadCore should work fine." print "" print "## pyLoadGui ##" gui_err = [] try: import PyQt4 except: gui_err.append("GUI won't work without pyqt4 !!") if gui_err: print "The system check has detected some errors:" print "" for err in gui_err: print err else: print "No Problems detected, pyLoadGui should work fine." print "" print "## Webinterface ##" web_err = [] try: import django if django.VERSION < (1, 1): web_err.append("Your django version is to old, please upgrade to django 1.1") elif django.VERSION > (1, 2): web_err.append("Your django version is to new, please use django 1.1") except: web_err.append("Webinterface won't work without django !!") if not exists(join(dirname(__file__), "module", "web", "pyload.db")): web_err.append("You dont have created database yet.") web_err.append("Please run: python %s syncdb" % join(dirname(__file__), "module", "web", "manage.py")) if web_err: print "The system check has detected some errors:" print "" for err in web_err: print err else: print "No Problems detected, Webinterface should work fine."
|
|
"status": fields[4], "shorthost": fields[5], "checksum": fields[6].strip().lower(), "mirror": "http://rs%(serverid)s%(shorthost)s.rapidshare.com/files/%(fileid)s/%(filename)s" % self.api_data}
|
"status": fields[4], "shorthost": fields[5], "checksum": fields[6].strip().lower()} self.api_data["mirror"] = "http://rs%(serverid)s%(shorthost)s.rapidshare.com/files/%(fileid)s/%(filename)s" % self.api_data
|
def download_api_data(self, force=False): """ http://images.rapidshare.com/apidoc.txt """ if self.api_data and not force: return api_url_base = "http://api.rapidshare.com/cgi-bin/rsapi.cgi" api_param_file = {"sub": "checkfiles_v1", "files": "", "filenames": "", "incmd5": "1", "files": self.id, "filenames": self.name} src = self.load(api_url_base, cookies=False, get=api_param_file).strip() self.log.debug("RS INFO API: %s" % src) if src.startswith("ERROR"): return fields = src.split(",") """ status codes: 0=File not found 1=File OK (Downloading possible without any logging) 2=File OK (TrafficShare direct download without any logging) 3=Server down 4=File marked as illegal 5=Anonymous file locked, because it has more than 10 downloads already 6=File OK (TrafficShare direct download with enabled logging) """ self.api_data = {"fileid": fields[0], "filename": fields[1], "size": int(fields[2]), "serverid": fields[3], "status": fields[4], "shorthost": fields[5], "checksum": fields[6].strip().lower(), "mirror": "http://rs%(serverid)s%(shorthost)s.rapidshare.com/files/%(fileid)s/%(filename)s" % self.api_data}
|
self.html_old = None
|
def __init__(self, parent): Plugin.__init__(self, parent) props = {} props['name'] = "RapidshareCom" props['type'] = "hoster" props['pattern'] = r"http://[\w\.]*?rapidshare.com/files/(\d*?)/(.*)" props['version'] = "1.0" props['description'] = """Rapidshare.com Download Plugin""" props['author_name'] = ("spoob", "RaNaN", "mkaay") props['author_mail'] = ("[email protected]", "[email protected]", "[email protected]") self.props = props self.parent = parent self.html = [None, None] self.html_old = None #time() where loaded the HTML self.time_plus_wait = None #time() + wait in seconds self.want_reconnect = False self.no_slots = True self.api_data = None self.url = self.parent.url self.read_config() if self.config['premium']: self.multi_dl = True self.req.canContinue = True else: self.multi_dl = False
|
|
self.html_old = time()
|
def download_html(self): """ gets the url from self.parent.url saves html in self.html and parses """ self.html[0] = self.req.load(self.url, cookies=True) self.html_old = time()
|
|
self.html_old = time()
|
def get_wait_time(self): """downloads html with the important informations """ file_server_url = re.search(r"<form action=\"(.*?)\"", self.html[0]).group(1) self.html[1] = self.req.load(file_server_url, cookies=True, post={"dl.start": "Free"}) self.html_old = time()
|
|
self.time_plus_wait = time() + 60 * int(wait_minutes)
|
self.time_plus_wait = time() + 60 * int(wait_minutes) + 60 self.no_slots = True
|
def get_wait_time(self): """downloads html with the important informations """ file_server_url = re.search(r"<form action=\"(.*?)\"", self.html[0]).group(1) self.html[1] = self.req.load(file_server_url, cookies=True, post={"dl.start": "Free"}) self.html_old = time()
|
self.sock.connect((self.getConf("host"), self.getConf("port"))) nick = self.getConf("nick")
|
host = self.getConfig("host") self.sock.connect((host, self.getConfig("port"))) nick = self.getConfig("nick")
|
def run(self): # connect to IRC etc. self.sock = socket.socket() self.sock.connect((self.getConf("host"), self.getConf("port"))) nick = self.getConf("nick") self.sock.send("NICK %s\r\n" % nick) self.sock.send("USER %s %s bla :%s\r\n" % (nick, self.getConf("host"), nick)) for t in self.getConf("owner").split(): if t.strip().startswith("#"): self.sock.send("JOIN %s\r\n" % t.strip()) self.log.info("pyLoadIRC: Connected to %s!" % self.host) self.log.info("pyLoadIRC: Switching to listening mode!") try: self.main_loop() except IRCError, ex: self.sock.send("QUIT :byebye\r\n") print_exc() self.sock.close()
|
self.sock.send("USER %s %s bla :%s\r\n" % (nick, self.getConf("host"), nick)) for t in self.getConf("owner").split():
|
self.sock.send("USER %s %s bla :%s\r\n" % (nick, host, nick)) for t in self.getConfig("owner").split():
|
def run(self): # connect to IRC etc. self.sock = socket.socket() self.sock.connect((self.getConf("host"), self.getConf("port"))) nick = self.getConf("nick") self.sock.send("NICK %s\r\n" % nick) self.sock.send("USER %s %s bla :%s\r\n" % (nick, self.getConf("host"), nick)) for t in self.getConf("owner").split(): if t.strip().startswith("#"): self.sock.send("JOIN %s\r\n" % t.strip()) self.log.info("pyLoadIRC: Connected to %s!" % self.host) self.log.info("pyLoadIRC: Switching to listening mode!") try: self.main_loop() except IRCError, ex: self.sock.send("QUIT :byebye\r\n") print_exc() self.sock.close()
|
self.log.info("pyLoadIRC: Connected to %s!" % self.host)
|
self.log.info("pyLoadIRC: Connected to %s!" % host)
|
def run(self): # connect to IRC etc. self.sock = socket.socket() self.sock.connect((self.getConf("host"), self.getConf("port"))) nick = self.getConf("nick") self.sock.send("NICK %s\r\n" % nick) self.sock.send("USER %s %s bla :%s\r\n" % (nick, self.getConf("host"), nick)) for t in self.getConf("owner").split(): if t.strip().startswith("#"): self.sock.send("JOIN %s\r\n" % t.strip()) self.log.info("pyLoadIRC: Connected to %s!" % self.host) self.log.info("pyLoadIRC: Switching to listening mode!") try: self.main_loop() except IRCError, ex: self.sock.send("QUIT :byebye\r\n") print_exc() self.sock.close()
|
if msg["origin"].split("!", 1)[0] != self.owner: return if msg["target"].split("!", 1)[0] != self.nick:
|
if not msg["origin"].split("!", 1)[0] in self.getConfig("owner").split(): return if msg["target"].split("!", 1)[0] != self.getConfig("nick"):
|
def handle_events(self, msg): if msg["origin"].split("!", 1)[0] != self.owner: return if msg["target"].split("!", 1)[0] != self.nick: return if msg["action"] != "PRIVMSG": return # HANDLE CTCP ANTI FLOOD/BOT PROTECTION if msg["text"] == "\x01VERSION\x01": self.log.debug("Sending CTCP VERSION.") self.sock.send("NOTICE %s :%s\r\n" % (msg['origin'], "pyLoad! IRC Interface")) return elif msg["text"] == "\x01TIME\x01": self.log.debug("Sending CTCP TIME.") self.sock.send("NOTICE %s :%d\r\n" % (msg['origin'], time.time())) return elif msg["text"] == "\x01LAG\x01": self.log.debug("Received CTCP LAG.") # don't know how to answer return trigger = "pass" args = None temp = msg["text"].split() trigger = temp[0] if len(temp) > 1: args = temp[1:] handler = getattr(self, "event_%s" % trigger, self.event_pass) try: res = handler(args) for line in res: self.response(line, msg["origin"]) except Exception, e: self.log.error("pyLoadIRC: "+ repr(e))
|
for t in self.getConf("owner").split():
|
for t in self.getConfig("owner").split():
|
def response(self, msg, origin=""): if origin == "": for t in self.getConf("owner").split(): self.sock.send("PRIVMSG %s :%s\r\n" % (t.strip(), msg)) else: self.sock.send("PRIVMSG %s :%s\r\n" % (origin.split("!", 1)[0], msg))
|
self.occ_plugins.remove(pyfile.modul.__name__)
|
self.occ_plugins.remove(pyfile.plugin.__name__)
|
def jobFinished(self, pyfile): """manage completing download""" self.lock.acquire()
|
p = os.path.relpath(path)
|
p = relpath(path)
|
def path_make_relative(path): p = os.path.relpath(path) if p[-1] == os.path.sep: return p else: return p + os.path.sep
|
size = re.search(r'<span style="float: left;"><strong>(.*?) MB</strong>', html).group(1) size = int(float(size)*1024*1024)
|
def getInfo(urls): result = [] for url in urls: html = getURL(url) if re.search(r'<h1>File not available</h1>', html): result.append((url, 0, 1, url)) continue size = re.search(r'<span style="float: left;"><strong>(.*?) MB</strong>', html).group(1) size = int(float(size)*1024*1024) name = re.search('<h1>(.*?)<br/></h1>', html).group(1) result.append((name, size, 2, url)) yield result
|
|
try: self.setWait(int(wait)+3) except: self.setWait(int(wait[-2:]))
|
wait = wait.decode("UTF-8").encode("ascii", "ignore") self.setWait(int(wait)+3)
|
def handleFree(self): if r'<div id="captchaArea" style="display:none;">' in self.html or \ r'/showCaptcha\(\);' in self.html: # we got a captcha id = re.search(r"var reCAPTCHA_publickey='(.*?)';", self.html).group(1) recaptcha = ReCaptcha(self) challenge, code = recaptcha.challenge(id) shortencode = re.search(r'name="recaptcha_shortencode_field" value="(.*?)"', self.html).group(1)
|
self.req = pyfile.m.core.requestFactory.getRequest(self.__name__)
|
def __init__(self, pyfile): self.config = pyfile.m.core.config self.core = pyfile.m.core
|
|
langNode = self.parser.xml.elementsByTagName("language").item(0).toElement() translation = gettext.translation("pyLoadGui", join(dirname(__file__), "locale"), languages=[str(langNode.text())])
|
lang = self.parser.xml.elementsByTagName("language").item(0).toElement().text() if not lang: parser = XMLParser("module/config/gui_default.xml") lang = parser.xml.elementsByTagName("language").item(0).toElement().text() translation = gettext.translation("pyLoadGui", join(dirname(__file__), "locale"), languages=[str(lang)])
|
def init(self, first=False): """ set main things up """ self.parser = XMLParser("module/config/gui.xml", "module/config/gui_default.xml") langNode = self.parser.xml.elementsByTagName("language").item(0).toElement() translation = gettext.translation("pyLoadGui", join(dirname(__file__), "locale"), languages=[str(langNode.text())]) translation.install(unicode=False if sys.getdefaultencoding() == "ascii" else True) self.mainWindow = MainWindow() self.pwWindow = PWInputWindow() self.connWindow = ConnectionManager() self.connector = connector() self.mainloop = self.Loop(self) self.connectSignals() self.checkClipboard = False default = self.refreshConnections() self.connData = None self.captchaProcessing = False if not first: self.connWindow.show() else: self.connWindow.edit.setData(default) data = self.connWindow.edit.getData() self.slotConnect(data)
|
elif self.config['quality'] == "hq":
|
elif self.config['quality'] == "hd" and self.hd_available: quality = "&fmt=22" else:
|
def get_file_url(self): """ returns the absolute downloadable filepath """ if self.html == None: self.download_html()
|
elif self.config['quality'] == "hd": quality = "&fmt=22"
|
def get_file_url(self): """ returns the absolute downloadable filepath """ if self.html == None: self.download_html()
|
|
down_script = re.search(r'name="down_script" value="(.*?)"', self.html).group(1)
|
down_script = re.search(r'name="down_script" value="(.*?)"', self.html)
|
def doDownload(self): """ returns the absolute downloadable filepath """ if self.html is None: self.download_html()
|
"down_script" : down_script
|
def doDownload(self): """ returns the absolute downloadable filepath """ if self.html is None: self.download_html()
|
|
self.cmd = [join(pypath, "UnRAR.exe")] else: self.cmd = ["unrar"]
|
self.cmd = join(pypath, "UnRAR.exe") else: self.cmd = "unrar"
|
def __init__(self, archive, tmpdir=None, ramSize=0, cpu=0): """ archive should be be first or only part """ self.archive = archive self.pattern = None m = re.match("^(.*).part(\d+).rar$", archive) if m: self.pattern = "%s.part*.rar" % m.group(1) else: #old style self.pattern = "%s.r*" % archive.replace(".rar", "") if os.name == "nt": self.cmd = [join(pypath, "UnRAR.exe")] else: self.cmd = ["unrar"] self.encrypted = None self.headerEncrypted = None self.smallestFiles = None self.password = None if not tmpdir: self.tmpdir = mkdtemp() else: self.tmpdir = tmpdir +"_" + basename(archive).replace(".rar", "").replace(".","")
|
Popen(["renice", self.cpu, p.pid], stdout=PIPE, bufsize=-1)
|
Popen(["renice", str(self.cpu), str(p.pid)], stdout=PIPE, stderr=PIPE,bufsize=-1)
|
def renice(self, p): """ renice process """ if os.name != "nt" and self.cpu: try: Popen(["renice", self.cpu, p.pid], stdout=PIPE, bufsize=-1) except: try: Popen(["busybox", "renice", self.cpu, p.pid], stdout=PIPE, bufsize=-1) except: print "Renice failed"
|
try: Popen(["busybox", "renice", self.cpu, p.pid], stdout=PIPE, bufsize=-1) except: print "Renice failed"
|
print "Renice failed"
|
def renice(self, p): """ renice process """ if os.name != "nt" and self.cpu: try: Popen(["renice", self.cpu, p.pid], stdout=PIPE, bufsize=-1) except: try: Popen(["busybox", "renice", self.cpu, p.pid], stdout=PIPE, bufsize=-1) except: print "Renice failed"
|
args = self.cmd + ["v"]
|
args = [self.cmd, "v"]
|
def listContent(self, password=None): """ returns a list with all infos to the files in the archive dict keys: name, version, method, crc, attributes, time, date, ratio, size_packed, size @return list(dict, dict, ...) """ f = self.archive if self.pattern: f = self.pattern args = self.cmd + ["v"] if password: args.append("-p%s" % password) else: args.append("-p-") args.append(f) p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=-1) ret = p.wait() if ret == 3: self.headerEncrypted = True raise WrongPasswordError() elif ret in (0,1) and password: self.headerEncrypted = False o = p.stdout.read() inList = False infos = {} nameLine = False name = "" for line in o.splitlines(): if line == "-"*79: inList = not inList continue if inList: nameLine = not nameLine if nameLine: name = line if name[0] == "*": #check for pw indicator name = name[1:] self.encrypted = True name = name.strip() continue s = line.split(" ") s = [e for e in s if e] s.reverse() d = {} for k, v in zip(["version", "method", "crc", "attributes", "time", "date", "ratio", "size_packed", "size"], s[0:9]): d[k] = v #if d["crc"] == "00000000" and len(d["method"]) == 2: if re.search("d", d["attributes"].lower()): #directory continue d["name"] = name d["size_packed"] = int(d["size_packed"]) d["size"] = int(d["size"]) if infos.has_key(name): infos[name]["size_packed"] = infos[name]["size_packed"] + d["size_packed"] infos[name]["crc"].append(d["crc"]) else: infos[name] = d infos[name]["crc"] = [d["crc"]] infos = infos.values() return infos
|
args = self.cmd + ["t", "-p%s" % password, f]
|
args = [self.cmd, "t", "-p%s" % password, f]
|
def checkPassword(self, password, statusFunction=None): """ check if password is okay @return bool """ if not self.needPassword(): return True f = self.archive if self.pattern: f = self.pattern args = self.cmd + ["t", "-p%s" % password, f] try: args.append(self.getSmallestFile(password)["name"]) except WrongPasswordError: return False p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=-1) self.renice(p) (ret, out) = self.processOutput(p, statusFunction) if ret == 3: raise False elif ret in (0,1): return True else: raise UnknownError()
|
args = self.cmd
|
args = [self.cmd]
|
def extract(self, password=None, fullPath=True, files=[], exclude=[], destination=None, overwrite=False, statusFunction=None): """ extract the archive @return bool: extract okay? raises WrongPasswordError or CommandError """ f = self.archive if self.pattern: f = self.pattern args = self.cmd if fullPath: args.append("x") else: args.append("e") if not password: password = "-" if overwrite: args.append("-o+") else: args.append("-o-") args.append("-p%s" % password) args.append(f) if files: args.extend([e for e in files]) if exclude: args.extend(["-x%s" % e for e in exclude]) if destination: args.append(destination) p = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE, bufsize=-1) self.renice(p) (ret, out) = self.processOutput(p, statusFunction) if ret == 3: raise WrongPasswordError() elif ret in (0,1): return True else: raise CommandError(ret=ret, stdout=out, stderr=p.stderr.read())
|
with open("sobiz_dump.html", "w") as f: f.write(self.html)
|
def downloadHTML(self): self.html = self.load(self.pyfile.url, cookies=True) with open("sobiz_dump.html", "w") as f: f.write(self.html) if not self.account: html = self.load("%s/free/" % self.pyfile.url, post={"dl_free":"1"}, cookies=True) if re.search(r"/failure/full/1", self.req.lastEffectiveURL): self.setWait(120) self.log.debug("%s: no free slots, waiting 120 seconds" % (self.__name__)) self.wait() self.retry() captcha = self.decryptCaptcha("http://www.share-online.biz/captcha.php", get={"rand":"0.%s" % random.randint(10**15,10**16)}, cookies=True) self.log.debug("%s Captcha: %s" % (self.__name__, captcha)) sleep(3) html = self.load(self.pyfile.url, post={"captchacode": captcha}, cookies=True) if re.search(r"Der Download ist Ihnen zu langsam", html): #m = re.search("var timeout='(\d+)';", self.html[1]) #self.waitUntil = time() + int(m.group(1)) if m else 30 return True
|
|
if line.endswith(":"):
|
if line.endswith(":") and line.count(":") == 1:
|
def loadAccounts(self): """loads all accounts available""" if not exists("accounts.conf"): f = open("accounts.conf", "wb") f.write("version: " + str(ACC_VERSION)) f.close() f = open("accounts.conf", "rb") content = f.readlines() version = content.pop(0) version = version.split(":")[1].strip()
|
if self.do_kill or not self.checkPidFile():
|
if self.do_kill or (not self.checkPidFile() and not self.daemon):
|
def start(self, xmlrpc=True, web=True): """ starts the fun :D """ if not exists("pyload.conf"): from module.setup import Setup
|
print self.server_methods.get_config_data()
|
def start(self): """ starts the machine"""
|
|
remove(f)
|
remove(dl)
|
def postCheck(self, dl):
|
if self.config["permission"]["change_group"]: if os.name != "nt": try: from grp import getgrnam group = getgrnam(self.config["permission"]["group"]) os.setgid(group[2]) except Exception, e: print _("Failed changing group: %s") % e
|
def start(self, xmlrpc=True, web=True): """ starts the fun :D """
|
|
out = subprocess.Popen([join(self.folder, 'download_finished', script), pyfile.plugin.props['name'], pyfile.url, pyfile.status.name, \ join(self.core.path,self.core.config['general']['download_folder'], pyfile.folder, pyfile.status.name)], stdout=subprocess.PIPE)
|
out = subprocess.Popen([join(self.folder, 'download_finished', script), pyfile.plugin.props['name'], pyfile.url, pyfile.status.filename, \ join(self.core.path,self.core.config['general']['download_folder'], pyfile.folder, pyfile.status.filename)], stdout=subprocess.PIPE)
|
def downloadFinished(self, pyfile): for script in self.scripts['download_finished']: try: out = subprocess.Popen([join(self.folder, 'download_finished', script), pyfile.plugin.props['name'], pyfile.url, pyfile.status.name, \ join(self.core.path,self.core.config['general']['download_folder'], pyfile.folder, pyfile.status.name)], stdout=subprocess.PIPE) except: pass
|
self.occ_plugins.append(pyfile.modul.__name__)
|
self.occ_plugins.append(pyfile.plugin.__name__)
|
def getJob(self): """return job if suitable, otherwise send thread idle"""
|
if pyfile.plugin.props['type'] == "container":
|
if pyfile.plugin.__type__ == "container":
|
def isDecryptWaiting(self): pyfiles = self.list.getDownloadList(self.occ_plugins) for pyfile in pyfiles: if pyfile.plugin.props['type'] == "container": return True return False
|
return str(self._Proxy__subject).replace(os.sep, Sep)
|
return str(self._subject).replace(os.sep, Sep)
|
def __str__(self): return str(self._Proxy__subject).replace(os.sep, Sep)
|
python_expr = _python_.replace('\\', '\\\\') act = TestSCons.re_escape('%s build.py \$foo \$TARGET \$SOURCES' % python_expr)
|
def build(num, target, source): file = open(str(target), 'wb') file.write('%s\n'%num) for s in source: file.write(open(str(s), 'rb').read())
|
|
\tbut they appear to have the same action: %s """ % act) + TestSCons.file_expr
|
\tbut they appear to have the same action: %s build.py .foo .TARGET .SOURCES """ % _python_) + TestSCons.file_expr
|
def build(num, target, source): file = open(str(target), 'wb') file.write('%s\n'%num) for s in source: file.write(open(str(s), 'rb').read())
|
def __init__(self, node):
|
def __init__(self, node=None):
|
def __init__(self, node): # Create an object attribute from the class attribute so it ends up # in the pickled data in the .sconsign file. self._version_id = self.current_version_id
|
def __init__(self, node):
|
def __init__(self, node=None):
|
def __init__(self, node): # Create an object attribute from the class attribute so it ends up # in the pickled data in the .sconsign file. self._version_id = self.current_version_id self.bsourcesigs = [] self.bdependsigs = [] self.bimplicitsigs = [] self.bactsig = None
|
if seen[include[1]] == 1: continue
|
already_seen = seen[include[1]]
|
def scan_recurse(self, node, path=()): """ do a recursive scan of the top level target file This lets us search for included files based on the directory of the main file just as latex does"""
|
assert s == test.workpath('0.out'), s
|
t = os.path.normcase(test.workpath('0.out')) assert os.path.normcase(s) == t, s
|
def func(target, source, env): open(str(target[0]), "w") if (len(source) == 1 and len(target) == 1): env['CNT'][0] = env['CNT'][0] + 1
|
assert s == test.workpath('1.out'), s
|
t = os.path.normcase(test.workpath('1.out')) assert os.path.normcase(s) == t, s
|
def func(target, source, env): open(str(target[0]), "w") if (len(source) == 1 and len(target) == 1): env['CNT'][0] = env['CNT'][0] + 1
|
s = str(tgts) expect = str([test.workpath('2.out'), test.workpath('3.out')]) assert s == expect, s
|
s = map(str, tgts) expect = [test.workpath('2.out'), test.workpath('3.out')] expect = map(os.path.normcase, expect) assert map(os.path.normcase, s) == expect, s
|
def func(target, source, env): open(str(target[0]), "w") if (len(source) == 1 and len(target) == 1): env['CNT'][0] = env['CNT'][0] + 1
|
if SCons.Util.is_List(d) or isinstance(d, tuple):
|
if d is None: continue elif SCons.Util.is_List(d) or isinstance(d, tuple):
|
def processDefines(defs): """process defines, resolving strings, lists, dictionaries, into a list of strings """ if SCons.Util.is_List(defs): l = [] for d in defs: if SCons.Util.is_List(d) or isinstance(d, tuple): if len(d) >= 2: l.append(str(d[0]) + '=' + str(d[1])) else: l.append(str(d[0])) elif SCons.Util.is_Dict(d): for macro,value in d.iteritems(): if value is not None: l.append(str(macro) + '=' + str(value)) else: l.append(str(macro)) elif SCons.Util.is_String(d): l.append(str(d)) else: raise elif SCons.Util.is_Dict(defs): # The items in a dictionary are stored in random order, but # if the order of the command-line options changes from # invocation to invocation, then the signature of the command # line will change and we'll get random unnecessary rebuilds. # Consequently, we have to sort the keys to ensure a # consistent order... l = [] for k,v in sorted(defs.items()): if v is None: l.append(str(k)) else: l.append(str(k) + '=' + str(v)) else: l = [str(defs)] return l
|
raise
|
raise SCons.Errors.UserError("DEFINE %s is not a list, dict, string or None."%repr(d))
|
def processDefines(defs): """process defines, resolving strings, lists, dictionaries, into a list of strings """ if SCons.Util.is_List(defs): l = [] for d in defs: if SCons.Util.is_List(d) or isinstance(d, tuple): if len(d) >= 2: l.append(str(d[0]) + '=' + str(d[1])) else: l.append(str(d[0])) elif SCons.Util.is_Dict(d): for macro,value in d.iteritems(): if value is not None: l.append(str(macro) + '=' + str(value)) else: l.append(str(macro)) elif SCons.Util.is_String(d): l.append(str(d)) else: raise elif SCons.Util.is_Dict(defs): # The items in a dictionary are stored in random order, but # if the order of the command-line options changes from # invocation to invocation, then the signature of the command # line will change and we'll get random unnecessary rebuilds. # Consequently, we have to sort the keys to ensure a # consistent order... l = [] for k,v in sorted(defs.items()): if v is None: l.append(str(k)) else: l.append(str(k) + '=' + str(v)) else: l = [str(defs)] return l
|
env.Clean(aFile_base + '.aux',target[0])
|
env.Clean(target[0],aFile_base + '.aux')
|
def tex_emitter_core(target, source, env, graphics_extensions): """An emitter for TeX and LaTeX sources. For LaTeX sources we try and find the common created files that are needed on subsequent runs of latex to finish tables of contents, bibliographies, indices, lists of figures, and hyperlink references. """ basename = SCons.Util.splitext(str(source[0]))[0] basefile = os.path.split(str(basename))[1] targetdir = os.path.split(str(target[0]))[0] targetbase = os.path.join(targetdir, basefile) basedir = os.path.split(str(source[0]))[0] abspath = os.path.abspath(basedir) target[0].attributes.path = abspath # # file names we will make use of in searching the sources and log file # emit_suffixes = ['.aux', '.log', '.ilg', '.blg', '.nls', '.nlg', '.gls', '.glg', '.alg'] + all_suffixes auxfilename = targetbase + '.aux' logfilename = targetbase + '.log' flsfilename = targetbase + '.fls' env.SideEffect(auxfilename,target[0]) env.SideEffect(logfilename,target[0]) env.SideEffect(flsfilename,target[0]) if Verbose: print "side effect :",auxfilename,logfilename,flsfilename env.Clean(target[0],auxfilename) env.Clean(target[0],logfilename) env.Clean(target[0],flsfilename) content = source[0].get_text_contents() idx_exists = os.path.exists(targetbase + '.idx') nlo_exists = os.path.exists(targetbase + '.nlo') glo_exists = os.path.exists(targetbase + '.glo') acr_exists = os.path.exists(targetbase + '.acn') # set up list with the regular expressions # we use to find features used file_tests_search = [auxfile_re, makeindex_re, bibliography_re, tableofcontents_re, listoffigures_re, listoftables_re, hyperref_re, makenomenclature_re, makeglossary_re, makeglossaries_re, makeacronyms_re, beamer_re ] # set up list with the file suffixes that need emitting # when a feature is found file_tests_suff = [['.aux'], ['.idx', '.ind', '.ilg'], ['.bbl', '.blg'], ['.toc'], ['.lof'], ['.lot'], ['.out'], ['.nlo', '.nls', '.nlg'], ['.glo', '.gls', '.glg'], ['.glo', '.gls', '.glg'], ['.acn', '.acr', '.alg'], ['.nav', '.snm', '.out', '.toc'] ] # build the list of lists file_tests = [] for i in range(len(file_tests_search)): file_tests.append( [None, file_tests_suff[i]] ) # TO-DO: need to add a way for the user to extend this list for whatever # auxiliary files they create in other (or their own) packages # get path list from both env['TEXINPUTS'] and env['ENV']['TEXINPUTS'] savedpath = modify_env_var(env, 'TEXINPUTS', abspath) paths = env['ENV']['TEXINPUTS'] if SCons.Util.is_List(paths): pass else: # Split at os.pathsep to convert into absolute path # TODO(1.5) #paths = paths.split(os.pathsep) paths = string.split(paths, os.pathsep) # now that we have the path list restore the env if savedpath is _null: try: del env['ENV']['TEXINPUTS'] except KeyError: pass # was never set else: env['ENV']['TEXINPUTS'] = savedpath if Verbose: print "search path ",paths aux_files = [] file_tests = ScanFiles(source[0], target, paths, file_tests, file_tests_search, env, graphics_extensions, targetdir, aux_files) for (theSearch,suffix_list) in file_tests: if theSearch: for suffix in suffix_list: env.SideEffect(targetbase + suffix,target[0]) if Verbose: print "side effect :",targetbase + suffix env.Clean(target[0],targetbase + suffix) for aFile in aux_files: aFile_base = SCons.Util.splitext(aFile)[0] env.SideEffect(aFile_base + '.aux',target[0]) if Verbose: print "side effect :",aFile_base + '.aux' env.Clean(aFile_base + '.aux',target[0]) # read fls file to get all other files that latex creates and will read on the next pass # remove files from list that we explicitly dealt with above if os.path.exists(flsfilename): content = open(flsfilename, "rb").read() out_files = openout_re.findall(content) myfiles = [auxfilename, logfilename, flsfilename, targetbase+'.dvi',targetbase+'.pdf'] for filename in out_files[:]: if filename in myfiles: out_files.remove(filename) env.SideEffect(out_files,target[0]) if Verbose: print "side effect :",out_files env.Clean(target[0],out_files) return (target, source)
|
super(io.StringIO, self).write(unicode(s))
|
super(_StringIO, self).write(unicode(s))
|
def write(self, s): super(io.StringIO, self).write(unicode(s))
|
sys.stdout = StringIOClass()
|
sys.stdout = StringIO()
|
def write(self, s): super(io.StringIO, self).write(unicode(s))
|
return sorted(uniquify(versions))
|
def keyfunc(str): """Given a dot-separated version string, return a tuple of ints representing it.""" return [int(x) for x in str.split('.')] return sorted(uniquify(versions), key=keyfunc, reverse=True)
|
def get_all_compiler_versions(): """Returns a sorted list of strings, like "70" or "80" or "9.0" with most recent compiler version first. """ versions=[] if is_windows: if is_win64: keyname = 'Software\\WoW6432Node\\Intel\\Compilers\\C++' else: keyname = 'Software\\Intel\\Compilers\\C++' try: k = SCons.Util.RegOpenKeyEx(SCons.Util.HKEY_LOCAL_MACHINE, keyname) except WindowsError: return [] i = 0 versions = [] try: while i < 100: subkey = SCons.Util.RegEnumKey(k, i) # raises EnvironmentError # Check that this refers to an existing dir. # This is not 100% perfect but should catch common # installation issues like when the compiler was installed # and then the install directory deleted or moved (rather # than uninstalling properly), so the registry values # are still there. ok = False for try_abi in ('IA32', 'IA32e', 'IA64', 'EM64T'): try: d = get_intel_registry_value('ProductDir', subkey, try_abi) except MissingRegistryError: continue # not found in reg, keep going if os.path.exists(d): ok = True if ok: versions.append(subkey) else: try: # Registry points to nonexistent dir. Ignore this # version. value = get_intel_registry_value('ProductDir', subkey, 'IA32') except MissingRegistryError, e: # Registry key is left dangling (potentially # after uninstalling). print \ "scons: *** Ignoring the registry key for the Intel compiler version %s.\n" \ "scons: *** It seems that the compiler was uninstalled and that the registry\n" \ "scons: *** was not cleaned up properly.\n" % subkey else: print "scons: *** Ignoring "+str(value) i = i + 1 except EnvironmentError: # no more subkeys pass elif is_linux: for d in glob.glob('/opt/intel_cc_*'): # Typical dir here is /opt/intel_cc_80. m = re.search(r'cc_(.*)$', d) if m: versions.append(m.group(1)) for d in glob.glob('/opt/intel/cc*/*'): # Typical dir here is /opt/intel/cc/9.0 for IA32, # /opt/intel/cce/9.0 for EMT64 (AMD64) m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) for d in glob.glob('/opt/intel/Compiler/*'): # Typical dir here is /opt/intel/Compiler/11.1 m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) elif is_mac: for d in glob.glob('/opt/intel/cc*/*'): # Typical dir here is /opt/intel/cc/9.0 for IA32, # /opt/intel/cce/9.0 for EMT64 (AMD64) m = re.search(r'([0-9][0-9.]*)$', d) if m: versions.append(m.group(1)) return sorted(uniquify(versions)) # remove dups
|
if out not in (sys.stdout, None):
|
if close_out:
|
def do_revisions(cr, opts, branch, revisions, scripts): """ Time the SCons branch specified scripts through a list of revisions. We assume we're in a (temporary) directory in which we can check out the source for the specified revisions. """ stdout = sys.stdout stderr = sys.stderr status = 0 if opts.logsdir and not opts.no_exec and len(scripts) > 1: for script in scripts: subdir = os.path.basename(os.path.dirname(script)) logsubdir = os.path.join(opts.origin, opts.logsdir, subdir) if not os.path.exists(logsubdir): os.makedirs(logsubdir) for this_revision in revisions: if opts.logsdir and not opts.no_exec: log_name = '%s.log' % this_revision log_file = os.path.join(opts.origin, opts.logsdir, log_name) stdout = open(log_file, 'w') stderr = None commands = [ ['svn', 'co', '-q', '-r', str(this_revision), branch, '.'], ] if int(this_revision) < int(TimeSCons_revision): commands.append(['svn', 'up', '-q', '-r', str(TimeSCons_revision)] + TimeSCons_pieces) commands.extend(prepare_commands()) s = cr.run_list(commands, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue for script in scripts: if opts.logsdir and not opts.no_exec and len(scripts) > 1: subdir = os.path.basename(os.path.dirname(script)) lf = os.path.join(opts.origin, opts.logsdir, subdir, log_name) out = open(lf, 'w') err = None else: out = stdout err = stderr s = cr.run(script_command(script), stdout=out, stderr=err) if s and status == 0: status = s if out not in (sys.stdout, None): out.close() out = None if int(this_revision) < int(TimeSCons_revision): # "Revert" the pieces that we previously updated to the # TimeSCons_revision, so the update to the next revision # works cleanly. command = (['svn', 'up', '-q', '-r', str(this_revision)] + TimeSCons_pieces) s = cr.run(command, stdout=stdout, stderr=stderr) if s: if status == 0: status = s continue if stdout not in (sys.stdout, None): stdout.close() stdout = None return status
|
t = msvc_version.split(".")
|
msvc_ver_numeric = string.join(filter(lambda x: x in string.digits + ".", msvc_version), '') t = msvc_version_numeric.split(".")
|
def msvc_version_to_maj_min(msvc_version): t = msvc_version.split(".") if not len(t) == 2: raise ValueError("Unrecognized version %s" % msvc_version) try: maj = int(t[0]) min = int(t[1]) return maj, min except ValueError, e: raise ValueError("Unrecognized version %s" % msvc_version)
|
d[types.InstanceType] = _semi_deepcopy_inst
|
d[InstanceType] = _semi_deepcopy_inst
|
def _semi_deepcopy_inst(x): if hasattr(x, '__semi_deepcopy__'): return x.__semi_deepcopy__() elif isinstance(x, UserDict): return x.__class__(_semi_deepcopy_dict(x)) elif isinstance(x, UserList): return x.__class__(_semi_deepcopy_list(x)) else: return x
|
if hasattr(obj, '__class__') and obj.__class__ != types.TypeType:
|
if hasattr(obj, '__class__') and obj.__class__ is not type:
|
def f(self, x, y): self.z = x + y
|
def f_local(target, source, env, for_signature):
|
def f_local(target, source, env, for_signature, LocalFunc=LocalFunc):
|
def f_local(target, source, env, for_signature): return SCons.Action.Action(LocalFunc)
|
def f_local(target, source, env, for_signature):
|
def f_local(target, source, env, for_signature, LocalFunc=LocalFunc):
|
def f_local(target, source, env, for_signature): return SCons.Action.Action(LocalFunc, varlist=['XYZ'])
|
search = [os.path.dirname(sys.argv[0])] if search[0] == '': search[0] = '.'
|
search = [script_dir]
|
def must_copy(dst, src): if not os.path.exists(dst): return 1 return open(dst, 'rb').read() != open(src, 'rb').read()
|
if hasattr(x, '__semi_deepcopy__'):
|
if hasattr(x, '__semi_deepcopy__') and callable(x.__semi_deepcopy__):
|
def semi_deepcopy(x): copier = _semi_deepcopy_dispatch.get(type(x)) if copier: return copier(x) else: if hasattr(x, '__semi_deepcopy__'): return x.__semi_deepcopy__() elif isinstance(x, UserDict): return x.__class__(_semi_deepcopy_dict(x)) elif isinstance(x, UserList): return x.__class__(_semi_deepcopy_list(x)) return x
|
if self.remove_this(fname, fpath): result.remove(fname) elif self.search_this(fpath): body = open(path, 'r').read()
|
if self.search_this(fpath) and not self.remove_this(fname, fpath): body = open(fpath, 'r').read()
|
def find_missing(self): result = [] for dirpath, dirnames, filenames in os.walk(self.directory): for fname in filenames: fpath = os.path.join(dirpath, fname) if self.remove_this(fname, fpath): result.remove(fname) elif self.search_this(fpath): body = open(path, 'r').read() for expr in self.expressions: if not expr.search(body): msg = '%s: missing %s' % (path, repr(expr.pattern)) result.append(msg) return result
|
msg = '%s: missing %s' % (path, repr(expr.pattern))
|
msg = '%s: missing %s' % (fpath, repr(expr.pattern))
|
def find_missing(self): result = [] for dirpath, dirnames, filenames in os.walk(self.directory): for fname in filenames: fpath = os.path.join(dirpath, fname) if self.remove_this(fname, fpath): result.remove(fname) elif self.search_this(fpath): body = open(path, 'r').read() for expr in self.expressions: if not expr.search(body): msg = '%s: missing %s' % (path, repr(expr.pattern)) result.append(msg) return result
|
os.execve(sys.executable, args, os.environ)
|
sys.exit(subprocess.Popen(args, env=os.environ).wait())
|
def find(file, search=search): for dir in search: f = os.path.join(dir, file) if os.path.exists(f): return os.path.normpath(f) sys.stderr.write("could not find `%s' in search path:\n" % file) sys.stderr.write("\t" + "\n\t".join(search) + "\n") sys.exit(2)
|
debug("sdk.py: get_sdk_vc_script():arch_string:%s host_arch:%s target_arch:%s"%(arch_string, host_arch, target_arch))
|
def get_sdk_vc_script(self,host_arch, target_arch): """ Return the script to initialize the VC compiler installed by SDK """ arch_string=target_arch if (host_arch != target_arch): arch_string='%s_%s'%(host_arch,target_arch) #print "arch_string:%s host_arch:%s target_arch:%s"%(arch_string, # host_arch, # target_arch) file=self.vc_setup_scripts.get(arch_string,None) #print "FILE:%s"%file return file
|
|
debug("sdk.py: get_sdk_vc_script():file:%s"%file)
|
def get_sdk_vc_script(self,host_arch, target_arch): """ Return the script to initialize the VC compiler installed by SDK """ arch_string=target_arch if (host_arch != target_arch): arch_string='%s_%s'%(host_arch,target_arch) #print "arch_string:%s host_arch:%s target_arch:%s"%(arch_string, # host_arch, # target_arch) file=self.vc_setup_scripts.get(arch_string,None) #print "FILE:%s"%file return file
|
|
debug('trying to find SDK %s' % sdk.version)
|
debug('MSCommon/sdk.py: trying to find SDK %s' % sdk.version)
|
def get_installed_sdks(): global InstalledSDKList global InstalledSDKMap if InstalledSDKList is None: InstalledSDKList = [] InstalledSDKMap = {} for sdk in SupportedSDKList: debug('trying to find SDK %s' % sdk.version) if sdk.get_sdk_dir(): debug('found SDK %s' % sdk.version) InstalledSDKList.append(sdk) InstalledSDKMap[sdk.version] = sdk return InstalledSDKList
|
debug('found SDK %s' % sdk.version)
|
debug('MSCommon/sdk.py:found SDK %s' % sdk.version)
|
def get_installed_sdks(): global InstalledSDKList global InstalledSDKMap if InstalledSDKList is None: InstalledSDKList = [] InstalledSDKMap = {} for sdk in SupportedSDKList: debug('trying to find SDK %s' % sdk.version) if sdk.get_sdk_dir(): debug('found SDK %s' % sdk.version) InstalledSDKList.append(sdk) InstalledSDKMap[sdk.version] = sdk return InstalledSDKList
|
def __call__(self, target, source, env, *args, **kw): args = (self, target, source, env) + args c = self.get_parent_class(env) return c.__call__(*args, **kw)
|
def __call__(self, *args, **kw): c = self.get_parent_class(args[2]) return c.__call__(self, *args, **kw)
|
def __call__(self, target, source, env, *args, **kw): args = (self, target, source, env) + args c = self.get_parent_class(env) #TODO(1.5) return c.__call__(*args, **kw) return c.__call__(*args, **kw)
|
0 0.00[012] 1 0.00[012]
|
0 \d.\d\d\d 1 \d.\d\d\d
|
def _main(): pass
|
msvc_ver_numeric = string.join(filter(lambda x: x in string.digits + ".", msvc_version), '') t = msvc_version_numeric.split(".")
|
t = msvc_version.split(".")
|
def msvc_version_to_maj_min(msvc_version): msvc_ver_numeric = string.join(filter(lambda x: x in string.digits + ".", msvc_version), '') t = msvc_version_numeric.split(".") if not len(t) == 2: raise ValueError("Unrecognized version %s" % msvc_version) try: maj = int(t[0]) min = int(t[1]) return maj, min except ValueError, e: raise ValueError("Unrecognized version %s" % msvc_version)
|
_is_win64 = has_reg(r"Software\Wow6432Node")
|
_is_win64 = False if os.environ.get('PROCESSOR_ARCHITECTURE','x86') != 'x86': _is_win64 = True if os.environ.get('PROCESSOR_ARCHITEW6432'): _is_win64 = True if os.environ.get('ProgramW6432'): _is_win64 = True
|
def is_win64(): """Return true if running on windows 64 bits. Works whether python itself runs in 64 bits or 32 bits.""" # Unfortunately, python does not provide a useful way to determine # if the underlying Windows OS is 32-bit or 64-bit. Worse, whether # the Python itself is 32-bit or 64-bit affects what it returns, # so nothing in sys.* or os.* help. So we go to the registry to # look directly for a clue from Windows, caching the result to # avoid repeated registry calls. global _is_win64 if _is_win64 is None: _is_win64 = has_reg(r"Software\Wow6432Node") return _is_win64
|
scons: \\*\\*\\* .* is not a Builder\\.
|
scons: *** 1 is not a Builder.
|
def mkdir(env, target, source): return None
|
status=2, match=TestSCons.match_re)
|
status=2)
|
def mkdir(env, target, source): return None
|
p = SCons.Util.Proxy(f1)
|
class MyProxy(SCons.Util.Proxy): __str__ = SCons.Util.Delegate('__str__') p = MyProxy(f1)
|
def test_proxy(self): """Test a Node.FS object wrapped in a proxy instance""" f1 = self.fs.File('fff') p = SCons.Util.Proxy(f1) f2 = self.fs.Entry(p) assert f1 is f2, (f1, f2)
|
assert f1 is f2, (f1, f2)
|
assert f1 is f2, (f1, str(f1), f2, str(f2))
|
def test_proxy(self): """Test a Node.FS object wrapped in a proxy instance""" f1 = self.fs.File('fff') p = SCons.Util.Proxy(f1) f2 = self.fs.Entry(p) assert f1 is f2, (f1, f2)
|
SConstruct_file_line = test.python_file_line(test.workpath('SConstruct'), 17)[:-1]
|
SConstruct_file_line = test.python_file_line(test.workpath('SConstruct'), 16)[:-1]
|
def cat(env, source, target): target = str(target[0]) f = open(target, "wb") for src in source: f.write(open(str(src), "rb").read()) f.close()
|
setattr(obj, name, types.MethodType(function, obj, cls))
|
setattr(obj, name, types.MethodType(function, obj, obj.__class__))
|
def f(self, x, y): self.z = x + y
|
global TimeStamp
|
global TimeStampDefault
|
def Trace(msg, file=None, mode='w', tstamp=None): """Write a trace message to a file. Whenever a file is specified, it becomes the default for the next call to Trace().""" global TraceDefault global TimeStamp global PreviousTime if file is None: file = TraceDefault else: TraceDefault = file if tstamp is None: tstamp = TimeStampDefault else: TimeStampDefault = tstamp try: fp = TraceFP[file] except KeyError: try: fp = TraceFP[file] = open(file, mode) except TypeError: # Assume we were passed an open file pointer. fp = file if tstamp: now = time.time() fp.write('%8.4f %8.4f: ' % (now - StartTime, now - PreviousTime)) PreviousTime = now fp.write(msg) fp.flush()
|
return string.replace(str(self._Proxy__subject), os.sep, Sep)
|
return str(self._Proxy__subject).replace(os.sep, Sep)
|
def __str__(self): return string.replace(str(self._Proxy__subject), os.sep, Sep)
|
return map(lambda x: string.replace(str(x), os.sep, Sep), orig_RDirs(self, pathlist))
|
return [str(x).replace(os.sep, Sep) for x in orig_RDirs(self, pathlist)]
|
def my_RDirs(self, pathlist, orig_RDirs=orig_RDirs): return map(lambda x: string.replace(str(x), os.sep, Sep), orig_RDirs(self, pathlist))
|
result.append(string.join(map(str, cmd))) return string.join(result, '\\n')
|
result.append(' '.join(map(str, cmd))) return '\\n'.join(result)
|
def Str(target, source, env, cmd=""): result = [] for cmd in env.subst_list(cmd, target=target, source=source): result.append(string.join(map(str, cmd))) return string.join(result, '\\n')
|
filter_tools = string.split('%(tools)s')
|
filter_tools = '%(tools)s'.split()
|
def JarCom(target, source, env): target = str(target[0]) class_files = [] for src in map(str, source): os.path.walk(src, find_class_files, class_files) f = open(target, "wb") for cf in class_files: f.write(open(cf, "rb").read()) f.close()
|
output = f.data[:i+1].replace('__ROOT__', '') output = output.replace('<', '<') output = output.replace('>', '>')
|
output = self.for_display(f.data[:i+1])
|
def end_scons_example(self): e = self.e files = [f for f in e.files if f.printme] if files: self.outfp.write('<programlisting>') for f in files: if f.printme: i = len(f.data) - 1 while f.data[i] == ' ': i = i - 1 output = f.data[:i+1].replace('__ROOT__', '') output = output.replace('<', '<') output = output.replace('>', '>') self.outfp.write(output) if e.data and e.data[0] == '\n': e.data = e.data[1:] self.outfp.write(e.data + '</programlisting>') delattr(self, 'e') self.afunclist = self.afunclist[:-1]
|
content = content.replace('<', '<') content = content.replace('>', '>')
|
content = self.for_display(content)
|
def end_scons_output(self): # The real raison d'etre for this script, this is where we # actually execute SCons to fetch the output. o = self.o e = o.e t = TestCmd.TestCmd(workdir='', combine=1) if o.preserve: t.preserve() t.subdir('ROOT', 'WORK') t.rootpath = t.workpath('ROOT').replace('\\', '\\\\')
|
output = f.data.replace('__ROOT__', '')
|
output = self.for_display(f.data)
|
def end_sconstruct(self): f = self.f self.outfp.write('<programlisting>') output = f.data.replace('__ROOT__', '') self.outfp.write(output + '</programlisting>') delattr(self, 'f') self.afunclist = self.afunclist[:-1]
|
for c in ['.', '[', ']', '(', ')', '*', '+', '?']:
|
for c in '.[]()*+?\\':
|
def re_escape(str): for c in ['.', '[', ']', '(', ')', '*', '+', '?']: # Not an exhaustive list. str = str.replace(c, '\\' + c) return str
|
cmd = ['gcc', '-v']
|
cmd = 'gcc -v'
|
def gccFortranLibs(): """Test which gcc Fortran startup libraries are required. This should probably move into SCons itself, but is kind of hacky. """ libs = ['g2c'] cmd = ['gcc', '-v'] try: import subprocess except ImportError: try: import popen2 stderr = popen2.popen3(cmd)[2].read() except OSError: return libs else: stderr = subprocess.Popen(cmd, stderr=subprocess.PIPE).communicate()[1] m = re.search('gcc version (\d\.\d)', stderr) if m: gcc_version = m.group(1) if re.match('4.[^0]', gcc_version): libs = ['gfortranbegin'] elif gcc_version in ('3.1', '4.0'): libs = ['frtbegin'] + libs return libs
|
stderr = subprocess.Popen(cmd, stderr=subprocess.PIPE).communicate()[1]
|
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE) stderr = p.stderr.read()
|
def gccFortranLibs(): """Test which gcc Fortran startup libraries are required. This should probably move into SCons itself, but is kind of hacky. """ libs = ['g2c'] cmd = ['gcc', '-v'] try: import subprocess except ImportError: try: import popen2 stderr = popen2.popen3(cmd)[2].read() except OSError: return libs else: stderr = subprocess.Popen(cmd, stderr=subprocess.PIPE).communicate()[1] m = re.search('gcc version (\d\.\d)', stderr) if m: gcc_version = m.group(1) if re.match('4.[^0]', gcc_version): libs = ['gfortranbegin'] elif gcc_version in ('3.1', '4.0'): libs = ['frtbegin'] + libs return libs
|
t = msvc_version.split(".") if not len(t) == 2: raise ValueError("Unrecognized version %s" % msvc_version) try: maj = int(t[0]) min = int(t[1]) return maj, min except ValueError, e: raise ValueError("Unrecognized version %s" % msvc_version)
|
msvc_ver_numeric = string.join(filter(lambda x: x in string.digits + ".", msvc_version), '') t = msvc_version_numeric.split(".") if not len(t) == 2: raise ValueError("Unrecognized version %s" % msvc_version) try: maj = int(t[0]) min = int(t[1]) return maj, min except ValueError, e: raise ValueError("Unrecognized version %s" % msvc_version)
|
def msvc_version_to_maj_min(msvc_version): t = msvc_version.split(".") if not len(t) == 2: raise ValueError("Unrecognized version %s" % msvc_version) try: maj = int(t[0]) min = int(t[1]) return maj, min except ValueError, e: raise ValueError("Unrecognized version %s" % msvc_version)
|
def __call__(self, *args, **kw): c = self.get_parent_class(args[2]) return c.__call__(self, *args, **kw)
|
def __call__(self, target, source, env, *args, **kw): c = self.get_parent_class(env) return c.__call__(self, target, source, env, *args, **kw)
|
def __call__(self, *args, **kw): c = self.get_parent_class(args[2]) # args[2] is env return c.__call__(self, *args, **kw)
|
else:
|
elif not vc_script and not sdk_script:
|
def msvc_setup_env(env): debug('msvc_setup_env()') version = get_default_version(env) if version is None: warn_msg = "No version of Visual Studio compiler found - C/C++ " \ "compilers most likely not set correctly" SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) return None debug('msvc_setup_env: using specified MSVC version %s\n' % repr(version)) # XXX: we set-up both MSVS version for backward # compatibility with the msvs tool env['MSVC_VERSION'] = version env['MSVS_VERSION'] = version env['MSVS'] = {} try: (vc_script,sdk_script) = find_batch_file(env,version) except VisualCException, e: msg = str(e) debug('Caught exception while looking for batch file (%s)' % msg) warn_msg = "VC version %s not installed. " + \ "C/C++ compilers are most likely not set correctly.\n" + \ " Installed versions are: %s" warn_msg = warn_msg % (version, cached_get_installed_vcs()) SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) return None use_script = env.get('MSVC_USE_SCRIPT', True) if SCons.Util.is_String(use_script): debug('use_script 1 %s\n' % repr(use_script)) d = script_env(use_script) elif use_script: host_platform, target_platform = get_host_target(env) host_target = (host_platform, target_platform) if not is_host_target_supported(host_target, version): warn_msg = "host, target = %s not supported for MSVC version %s" % \ (host_target, version) SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) arg = _HOST_TARGET_ARCH_TO_BAT_ARCH[host_target] debug('use_script 2 %s, args:%s\n' % (repr(vc_script), arg)) if vc_script: try: d = script_env(vc_script, args=arg) except BatchFileExecutionError, e: debug('use_script 3: failed running VC script %s: %s: Error:%s'%(repr(vc_script),arg,e)) vc_script=None if not vc_script and sdk_script: debug('use_script 4: trying sdk script: %s %s'%(sdk_script,arg)) try: d = script_env(sdk_script,args=[]) except BatchFileExecutionError,e: debug('use_script 5: failed running SDK script %s: Error:%s'%(repr(sdk_script),e)) return None else: debug('use_script 6: Neither VC script nor SDK script found') return None else: debug('MSVC_USE_SCRIPT set to False') warn_msg = "MSVC_USE_SCRIPT set to False, assuming environment " \ "set correctly." SCons.Warnings.warn(SCons.Warnings.VisualCMissingWarning, warn_msg) return None for k, v in d.items(): env.PrependENVPath(k, v, delete_existing=True)
|
host = _ARCH_TO_CANONICAL[host_platform]
|
host = _ARCH_TO_CANONICAL[host_platform.lower()]
|
def get_host_target(env): debug('vc.py:get_host_target()') host_platform = env.get('HOST_ARCH') if not host_platform: host_platform = platform.machine() # TODO(2.5): the native Python platform.machine() function returns # '' on all Python versions before 2.6, after which it also uses # PROCESSOR_ARCHITECTURE. if not host_platform: host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '') # Retain user requested TARGET_ARCH req_target_platform = env.get('TARGET_ARCH') debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform) if req_target_platform: # If user requested a specific platform then only try that one. target_platform = req_target_platform else: target_platform = host_platform try: host = _ARCH_TO_CANONICAL[host_platform] except KeyError, e: msg = "Unrecognized host architecture %s" raise ValueError(msg % repr(host_platform)) try: target = _ARCH_TO_CANONICAL[target_platform] except KeyError, e: raise ValueError("Unrecognized target architecture %s" % target_platform) return (host, target,req_target_platform)
|
target = _ARCH_TO_CANONICAL[target_platform]
|
target = _ARCH_TO_CANONICAL[target_platform.lower()]
|
def get_host_target(env): debug('vc.py:get_host_target()') host_platform = env.get('HOST_ARCH') if not host_platform: host_platform = platform.machine() # TODO(2.5): the native Python platform.machine() function returns # '' on all Python versions before 2.6, after which it also uses # PROCESSOR_ARCHITECTURE. if not host_platform: host_platform = os.environ.get('PROCESSOR_ARCHITECTURE', '') # Retain user requested TARGET_ARCH req_target_platform = env.get('TARGET_ARCH') debug('vc.py:get_host_target() req_target_platform:%s'%req_target_platform) if req_target_platform: # If user requested a specific platform then only try that one. target_platform = req_target_platform else: target_platform = host_platform try: host = _ARCH_TO_CANONICAL[host_platform] except KeyError, e: msg = "Unrecognized host architecture %s" raise ValueError(msg % repr(host_platform)) try: target = _ARCH_TO_CANONICAL[target_platform] except KeyError, e: raise ValueError("Unrecognized target architecture %s" % target_platform) return (host, target,req_target_platform)
|
print "Key: %s, Value: %s, pre: %s, trans: %s" % ( key, value, pre, self.translate( pre, l10n ) )
|
def templatize( self, file, type, locale, l10n=None ): with codecs.open( file, 'rU', 'utf-8' ) as f: src = f.read() newsrc = [] blocks = re.split( r'{% blocktrans (?:with "((?:\\"|[^"])*)" as (\w+) )?%}|<blocktrans>|<!-- blocktrans -->|/\* blocktrans \*/', src )
|
|
line += " " line += "%.2f%%" % (percentage * 100)
|
line += "-" line += "] %.2f%%" % (percentage * 100)
|
def bar(percentage): length = 25 bar_length = length * percentage
|
lines.append(Context.Line("`%4d:%6d " % (score, count) + bar(percentage), color=Color.BLUE, face=Face.MONOSPACE))
|
lines.append(Context.Line("`%4d:%6d " % (score, count) + bar(percentage), Color.BLUE, Face.MONOSPACE))
|
def bar(percentage): length = 33 bar_length = int(length * percentage)
|
lines.append(Formatter.Line("%s%3d:%s%3d " % (header, score, gen_indent(1), count) + bar(percentage), color=Color.BLUE, font=Font.MONOSPACE))
|
lines.append(Formatter.Line("`%s%3d:%s%3d " % (header, score, gen_indent(1), count) + bar(percentage), color=Color.BLUE, font=Font.MONOSPACE))
|
def bar(percentage): length = 33 bar_length = int(length * percentage)
|
self.add_line("Left Team: MaxWinRate %.2f%%, MinWinRate %.2f%%" % (self.max_win_rate * 100, self.min_win_rate * 100), Color.GRAY)
|
if self.left_count > 0: self.add_line("Left Team: MaxWinRate %.2f%%, MinWinRate %.2f%%" % (self.max_win_rate * 100, self.min_win_rate * 100), Color.GRAY)
|
def do_some_formatting(self): self.add_line(self.title, color=Color.BLUE) self.add_newline()
|
total_game.dump(" ")
|
total_game.dump(header)
|
def dump(self, header): game_count = float(self.count)
|
print "Only Valid Game" valid_game.dump(" ")
|
if header: print "Only Valid Game:" valid_game.dump(header)
|
def dump(self, header): game_count = float(self.count)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.