rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
return outheader,out
return str(outheader),str(out)
def htmlparse(self,data): ''' Input: can be html code or raw JavaScript code Output: an array of [headers, raw JavaScript] ''' outheader, out = '', '' data = re.sub('\x00','',data) soup = BeautifulSoup.BeautifulSoup(data) for tag,attrib,invals,format,outvals in self.html_parse_rules: for htm in soup.findAll(tag,attrib...
print '[debug] average seconds per call is %.02f\n' % (js.rooturl[url].dbgobj.totalJsTime()/js.rooturl[url].dbgobj.numberTotalLaunches())
if js.rooturl[url].dbgobj.numberTotalLaunches() > 0: print '[debug] average seconds per call is %.02f\n' % (js.rooturl[url].dbgobj.totalJsTime()/js.rooturl[url].dbgobj.numberTotalLaunches())
def main(): global ENABLE_NIDS global ENABLE_MAGIC socket.setdefaulttimeout(10) #network capable only if -a (--active) parameter specified message = '\n\t./jsunpackn.py [fileName]\n\t./jsunpackn.py -i [interfaceName]\n\tjsunpack-network version %s' % (jsunpack.version) if not ENABLE_NIDS: message += '\n\t[warning] py...
out += 'info.%s = String(\'%s\');\n' % (property,value)
out += 'info.%s = String(\'%s\'); this.%s = info.%s;\n' % (property,value,property,property)
def getJavaScript(self): out = '' pagenow = 0 for jskey in self.list_obj: #(self.objects.keys()): if self.objects[jskey].staticScript: out += self.objects[jskey].staticScript
pass if self.OPTIONS.debug: self.rooturl[self.url].create_sha1file(self.OPTIONS.outdir, to_write,'debug')
to_write_headers, to_write = '', ''
def decodeJS(self,content,isPDF): #return values are: #(decoded scripts) try: to_write_headers, to_write = self.hparser.htmlparse(content) except Exception, e: pass #print 'Error in htmlparsing', str(e)
try: ip = struct.unpack('L',socket.inet_aton(ipin))[0] except: ip = socket.inet_aton(ipin)
ip = struct.unpack('=L',socket.inet_aton(ipin))[0]
def internal_addr(self,ipin): '''returns True if 127.*, or other internal addr''' #ip = socket.inet_aton(ip) try: ip = struct.unpack('L',socket.inet_aton(ipin))[0] except: #is this a python 2.6 problem where inet_aton return value is integer? ip = socket.inet_aton(ipin)
try: ipnet = struct.unpack('L',socket.inet_aton(block))[0] & (2L<<n-1) - 1 except: ipnet = socket.inet_aton(block) & (2L<<n-1) - 1
ipnet = struct.unpack('=L',socket.inet_aton(block))[0] & (2L<<n-1) - 1
def internal_addr(self,ipin): '''returns True if 127.*, or other internal addr''' #ip = socket.inet_aton(ip) try: ip = struct.unpack('L',socket.inet_aton(ipin))[0] except: #is this a python 2.6 problem where inet_aton return value is integer? ip = socket.inet_aton(ipin)
print 'newfile: runtime_last', runningTime, 'redoevaltime:', self.OPTIONS.redoevaltime
def decodeVersions(self,to_write,isPDF): decodings = [] #there may be multiple decodings if we get different results for version strings duration = 0 #total elapsed time runningTime = 0 #previous evaluation time
self.objects[key].staticScript += 'info.%s = String(\'%s\');\n' % (k.lower(),value)
self.objects[key].staticScript += 'info.%s = String(\'%s\'); this.%s = info.%s;\n' % (k.lower(),value,k.lower(),k.lower())
def parse(self):
attachments=None, charset=None):
Date=None, attachments=None, charset=None):
def __init__(self, To=None, From=None, Subject=None, Body=None, Html=None, attachments=None, charset=None): self.attachments = [] if attachments: for attachment in attachments: if isinstance(attachment, basestring): self.attachments.append((attachment, None)) else: try: filename, cid = attachment except (TypeError, Ind...
server = smtplib.SMTP(self.host, self.port) if self._usr and self._pwd: server.login(self._usr, self._pwd)
if 'gmail.com' in self.host or 'googlemail.com' in self.host: server = self._get_gmail_server() else: server = self._get_mailserver()
def send(self, msg): """ Send one message or a sequence of messages.
def _get_mailserver(self): mailserver = smtplib.SMTP(self.host) if self._usr and self._pwd: server.login(self._usr, self._pwd) return mailserver def _get_gmail_server(self): if not self._usr and self._pwd: err = 'Cannot send through %s without a name and password.' raise ValueError(err % self.host) mailserver = smtpli...
def send(self, msg): """ Send one message or a sequence of messages.
def __init__(self, host="localhost", port=0):
def __init__(self, host="localhost", port=25, useTls=False):
def __init__(self, host="localhost", port=0): self.host = host self.port = port self._usr = None self._pwd = None
if 'gmail.com' in self.host or 'googlemail.com' in self.host: server = self._get_gmail_server() else: server = self._get_mailserver()
server = smtplib.SMTP(self.host, self.port) if self.useTls: server.ehlo() server.starttls() server.ehlo() if self._usr and self._pwd: server.login(self._usr, self._pwd)
def send(self, msg): """ Send one message or a sequence of messages.
def _get_mailserver(self): mailserver = smtplib.SMTP(self.host) if self._usr and self._pwd: server.login(self._usr, self._pwd) return mailserver def _get_gmail_server(self): if not self._usr and self._pwd: err = 'Cannot send through %s without a name and password.' raise ValueError(err % self.host) mailserver = smtpli...
def send(self, msg): """ Send one message or a sequence of messages.
def __init__(self, host="localhost", port=0):
def __init__(self, host="localhost", port=0, use_tls=False, usr=None, pwd=None):
def __init__(self, host="localhost", port=0): self.host = host self.port = port self._usr = None self._pwd = None
self._usr = None self._pwd = None
self.use_tls = use_tls self._usr = usr self._pwd = pwd
def __init__(self, host="localhost", port=0): self.host = host self.port = port self._usr = None self._pwd = None
you = [msg.To] else: you = list(msg.To)
to = [msg.To] else: to = list(msg.To) cc = [] if msg.CC: if isinstance(msg.CC, basestring): cc = [msg.CC] else: cc = list(msg.CC) bcc = [] if msg.BCC: if isinstance(msg.BCC, basestring): bcc = [msg.BCC] else: bcc = list(msg.BCC) you = to + cc + bcc
def _send(self, server, msg): """ Sends a single message using the server we created in send() """ me = msg.From if isinstance(msg.To, basestring): you = [msg.To] else: you = list(msg.To) server.sendmail(me, you, msg.as_string())
return self.STATUS_TABLE[task.status]
return self.STATUS_TABLE[self.status]
def status_string(self): ''' Display the status (probably a computed field based on tasks: "Scan scheduled", "Scan in progress" ''' return self.STATUS_TABLE[task.status]
max = 50
max = 100
def _wait_until(self, key, event): max = 50 # 5 seconds max while not exists(join(self.tempdir, key + event)) and max: time.sleep(0.1) max -= 1 if not max: self.fail("Timeout")
self.fail("Timeout")
self.fail("Timeout on key=%s, event=%s" % (key, event))
def _wait_until(self, key, event): max = 50 # 5 seconds max while not exists(join(self.tempdir, key + event)) and max: time.sleep(0.1) max -= 1 if not max: self.fail("Timeout")
logging.basicConfig(level=logging.INFO)
logging.getLogger().addHandler(logging.StreamHandler()) logging.getLogger().setLevel(logging.INFO)
def run_function_task(self): function = _to_function(self.function_name) return function()
with LogCheck(self, "INFO: Cancelling task " + str(task.pk) + "...\nINFO: Task " + str(task.pk) + " finished with status \"cancelled\"\nINFO: ...Task 1 cancelled.\n"):
with LogCheck(self, "INFO: Cancelling task " + str(task.pk) + "...\nINFO: Task " + str(task.pk) + " finished with status \"cancelled\"\nINFO: ...Task " + str(task.pk) + " cancelled.\n"):
def test_tasks_run_cancel_scheduled(self): task = self._create_task(TestModel.run_something_long, join(self.tempdir, 'key1')) with LogCheck(self): Task.objects._do_schedule() Task.objects.run_task(task.pk) Task.objects.cancel_task(task.pk) with LogCheck(self, "INFO: Cancelling task " + str(task.pk) + "...\nINFO: Task "...
with LogCheck(self, 'WARNING: Failed to change status from "scheduled" to "running" for task 1\n'):
with LogCheck(self, 'WARNING: Failed to change status from "scheduled" to "running" for task %d\n' % task.pk):
def test_tasks_exception_in_thread(self): task = self._create_task(TestModel.run_something_long, join(self.tempdir, 'key1')) Task.objects.run_task(task.pk) task = self._create_task(TestModel.run_something_long, join(self.tempdir, 'key1')) task_delete = self._create_task(TestModel.run_something_long, join(self.tempdir, ...
titles = titles.disticnt()
titles = titles.distinct()
def titles_in_state(request, state, page_number=1, order='name_normal'): state = unpack_url_path(state) page_title = "Titles in State: %s" % state titles = models.Title.objects.all() if state: titles = titles.filter(places__state__iexact=state) titles = titles.order_by(order) titles = titles.disticnt() if titles.count...
def handle(self, flickr_key, **options):
def handle(self, key, **options):
def handle(self, flickr_key, **options): _log.debug("looking for chronam page content on flickr") for flickr_url, chronam_url in flickr_chronam_links(flickr_key): _log.info("found flickr/chronam link: %s, %s" % (flickr_url, chronam_url)) path = urlparse(chronam_url).path page = Page.lookup(path) if page: f, created = F...
for flickr_url, chronam_url in flickr_chronam_links(flickr_key):
create_count = 0 for flickr_url, chronam_url in flickr_chronam_links(key):
def handle(self, flickr_key, **options): _log.debug("looking for chronam page content on flickr") for flickr_url, chronam_url in flickr_chronam_links(flickr_key): _log.info("found flickr/chronam link: %s, %s" % (flickr_url, chronam_url)) path = urlparse(chronam_url).path page = Page.lookup(path) if page: f, created = F...
if page: f, created = FlickrUrl.objects.get_or_create(value=flickr_url, page=page) if created: f.save() _log.info("updated page (%s) with flickr url (%s)" % (page, flickr_url)) else: _log.info("already knew about %s" % flickr_url)
if not page: _log.error("page for %s not found" % chronam_url) continue f, created = FlickrUrl.objects.get_or_create(value=flickr_url, page=page) if created: create_count += 1 f.save() _log.info("updated page (%s) with flickr url (%s)" % (page, flickr_url))
def handle(self, flickr_key, **options): _log.debug("looking for chronam page content on flickr") for flickr_url, chronam_url in flickr_chronam_links(flickr_key): _log.info("found flickr/chronam link: %s, %s" % (flickr_url, chronam_url)) path = urlparse(chronam_url).path page = Page.lookup(path) if page: f, created = F...
_log.error("Page for %s not found" % chronam_url) def newspaper_photo_ids(flickr_key): u = 'http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=%s&photoset_id=72157619452486566&format=json&nojsoncallback=1' % settings.FLICKR_KEY
_log.info("already knew about %s" % flickr_url) _log.info("created %s flickr urls" % create_count) def newspaper_photo_ids(key): """ Fetches JSON info for all the images in the Flickr newspaper set. """ u = 'http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=%s&photoset_id=721576194524865...
def handle(self, flickr_key, **options): _log.debug("looking for chronam page content on flickr") for flickr_url, chronam_url in flickr_chronam_links(flickr_key): _log.info("found flickr/chronam link: %s, %s" % (flickr_url, chronam_url)) path = urlparse(chronam_url).path page = Page.lookup(path) if page: f, created = F...
def chronam_url(photo_id): u = 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=%s&photo_id=%s&format=json&nojsoncallback=1' % (settings.FLICKR_KEY, photo_id)
def chronam_url(photo_id, key): """ Looks at complete information for a Flickr image, and tries to find the first chroniclingamerica.loc.gov identifier in the machine tags. """ u = 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=%s&photo_id=%s&format=json&nojsoncallback=1' % (key, photo_id)
def chronam_url(photo_id): u = 'http://api.flickr.com/services/rest/?method=flickr.photos.getInfo&api_key=%s&photo_id=%s&format=json&nojsoncallback=1' % (settings.FLICKR_KEY, photo_id) j = json.loads(urllib.urlopen(u).read()) for tag in j['photo']['tags']['tag']: if 'chroniclingamerica.loc.gov' in tag['raw']: return ta...
start = page_num * rows - 10
start = rows * (page_num - 1)
def __init__(self, query): self.query = query.copy()
start = page * rows - 50
start = rows * (page - 1)
def __init__(self, query): self.query = query.copy()
t.load_file('web/test-data/sn86069873.xml')
t.load_file(abs_filename('./test-data/sn86069873.xml'))
def test_oclc_num(self): t = TitleLoader() t.load_file('web/test-data/sn86069873.xml') t = Title.objects.get(lccn='sn86069873') self.assertEqual(t.oclc, '13528482')
loader.load_file('web/test-data/bib-with-vague-dates.xml')
filename = abs_filename('./test-data/bib-with-vague-dates.xml') loader.load_file(filename)
def test_vague_dates(self): loader = TitleLoader() loader.load_file('web/test-data/bib-with-vague-dates.xml') t = Title.objects.get(lccn='00062183') self.assertEqual(t.start_year_int, 1900) self.assertEqual(t.end_year_int, 1999)
loader.load_file('web/test-data/etitle.xml')
loader.load_file(abs_filename('./test-data/etitle.xml'))
def test_etitle(self): # we shouldn't load in [electronic resource] records for # chronicling america titles, since they muddle up search results # https://rdc.lctl.gov/trac/ndnp/ticket/375 loader = TitleLoader() loader.load_file('web/test-data/etitle.xml') self.assertRaises(Title.DoesNotExist, Title.objects.get, lccn=...
return os.path.join(STORAGE, self.awardee.org_code,
return os.path.join(settings.STORAGE, self.awardee.org_code,
def path(self): """Absolute path of batch directory""" return os.path.join(STORAGE, self.awardee.org_code, self.name, "data")
print >> postactivate, "export DJANGO_SETTINGS_MODULE=%s" % DJANGO_SETTINGS_MODULE print >> postactivate, "export PROJECT_ROOT=%s" % DJANGO_PROJECT_ROOT
cmd = "export DJANGO_SETTINGS_MODULE=%s" % DJANGO_SETTINGS_MODULE print >> postactivate, cmd cmd = "export PROJECT_ROOT=%s" % DJANGO_PROJECT_ROOT print >> postactivate, cmd
def setup_virtual_env(): if not os.path.exists(VIRTUAL_ENV) or new_requirements(): print "Initializing virtualenv at %s" % VIRTUAL_ENV try: subprocess.check_call( ['virtualenv', '--quiet', '--no-site-packages', VIRTUAL_ENV]) subprocess.check_call([ os.path.join(VIRTUAL_ENV, 'bin', 'easy_install'), '--quiet', 'pip']) ...
page_title = '%s Newspapers' % titles[0].country.name
state = titles[0].country.name page_title = '%s Newspapers' % state
def newspapers(request, state=None, format='html'): titles = models.Title.objects.distinct().filter(issues__isnull=False) if state: template = 'newspapers_state' state = unpack_url_path(state) if state is None: raiseHttp404 titles = titles.filter(country__name__iexact=state) if titles.count() == 0: raise Http404 page_t...
msg = "processed %s pages" % batch.page_count()
msg = "processed %s pages" % batch.page_count
def load_batch(self, batch_name, strict=True): """Load a batch, and return a Batch instance for the batch that was loaded.
for loc, last_mod in sitemap_urls():
for loc, last_mod, newspaper, pub_date, title in sitemap_urls():
def write_sitemaps(): """ This function will write a sitemap index file that references individual sitemaps for all the batches, issues, pages and titles that have been loaded. """ sitemap_index = open( os.path.join(settings.DOCUMENT_ROOT, 'sitemap.xml'), 'w') sitemap_index.write('<?xml version="1.0" encoding="UTF-8"?>...
sitemap = open( os.path.join(settings.DOCUMENT_ROOT, sitemap_file), 'w') sitemap.write('<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n')
sitemap = open(os.path.join(settings.DOCUMENT_ROOT, sitemap_file), 'w') sitemap.write('<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="http://www.google.com/schemas/sitemap-news/0.9">\n')
def write_sitemaps(): """ This function will write a sitemap index file that references individual sitemaps for all the batches, issues, pages and titles that have been loaded. """ sitemap_index = open( os.path.join(settings.DOCUMENT_ROOT, 'sitemap.xml'), 'w') sitemap_index.write('<?xml version="1.0" encoding="UTF-8"?>...
sitemap.write("<url><loc>http://chroniclingamerica.loc.gov%s</loc><lastmod>%s</lastmod></url>\n" % (loc, rfc3339(last_mod)))
if newspaper and pub_date and title: sitemap.write("<url><loc>http://chroniclingamerica.loc.gov%s</loc><lastmod>%s</lastmod><news:publication><news:name>%s</news:name><news:language>en</news:language></news:publication><news:publication_date>%s</news:publication_date><news:title>%s</news:title></url>\n" % (loc, rfc3339...
def write_sitemaps(): """ This function will write a sitemap index file that references individual sitemaps for all the batches, issues, pages and titles that have been loaded. """ sitemap_index = open( os.path.join(settings.DOCUMENT_ROOT, 'sitemap.xml'), 'w') sitemap_index.write('<?xml version="1.0" encoding="UTF-8"?>...
org_text = html.escape(note.text)
def title(request, lccn): title = get_object_or_404(models.Title, lccn=lccn) page_title = "About this Newspaper: %s" % unicode(title.name) # we call these here, because the query the db, they are not # cached by django's ORM, and we have some conditional logic # in the template that would result in them getting called ...
r'<a class="external" href="\1">\1</a>', note.text) if text != note.text:
r'<a class="external" href="\1">\1</a>', org_text) if text != org_text:
def title(request, lccn): title = get_object_or_404(models.Title, lccn=lccn) page_title = "About this Newspaper: %s" % unicode(title.name) # we call these here, because the query the db, they are not # cached by django's ORM, and we have some conditional logic # in the template that would result in them getting called ...
sitemap.write("<url><loc>http://chroniclingamerica.loc.gov%s</loc><lastmod>%s</lastmod><news:news><news:publication><news:name>%s</news:name><news:language>en</news:language></news:publication><news:publication_date>%s</news:publication_date><news:title>%s</news:title></news:news></url>\n" % (loc, rfc3339(last_mod), fo...
url = "<url><loc>http://chroniclingamerica.loc.gov%s</loc><lastmod>%s</lastmod><news:news><news:publication><news:name>%s</news:name><news:language>en</news:language></news:publication><news:publication_date>%s</news:publication_date><news:title>%s</news:title></news:news></url>\n" % (loc, rfc3339(last_mod), force_esca...
def write_sitemaps(): """ This function will write a sitemap index file that references individual sitemaps for all the batches, issues, pages and titles that have been loaded. """ sitemap_index = open( os.path.join(settings.DOCUMENT_ROOT, 'sitemap.xml'), 'w') sitemap_index.write('<?xml version="1.0" encoding="UTF-8"?>...
sitemap.write("<url><loc>http://chroniclingamerica.loc.gov%s</loc><lastmod>%s</lastmod></url>\n" % (loc, rfc3339(last_mod)))
url = "<url><loc>http://chroniclingamerica.loc.gov%s</loc><lastmod>%s</lastmod></url>\n" % (loc, rfc3339(last_mod)) sitemap.write(url.encode("utf-8"))
def write_sitemaps(): """ This function will write a sitemap index file that references individual sitemaps for all the batches, issues, pages and titles that have been loaded. """ sitemap_index = open( os.path.join(settings.DOCUMENT_ROOT, 'sitemap.xml'), 'w') sitemap_index.write('<?xml version="1.0" encoding="UTF-8"?>...
for flickr_url, chronam_url in flickr_chronam_links():
for flickr_url, chronam_url in flickr_chronam_links(flickr_key):
def handle(self, flickr_key, **options): _log.debug("looking for chronam page content on flickr") for flickr_url, chronam_url in flickr_chronam_links(): _log.info("found flickr/chronam link: %s, %s" % (flickr_url, chronam_url)) path = urlparse(chronam_url).path page = Page.lookup(path) if page: f, created = FlickrUrl.o...
if not (models.Title.objects.all().count() and \ models.Holding.objects.all().count() and \ models.Essay.objects.all().count() and \ models.Batch.objects.all().count() and \ models.Issue.objects.all().count() and \ models.Page.objects.all().count() and \ index.page_count() and \ index.title_count()):
if not (models.Title.objects.all().count()==0 and \ models.Holding.objects.all().count()==0 and \ models.Essay.objects.all().count()==0 and \ models.Batch.objects.all().count()==0 and \ models.Issue.objects.all().count()==0 and \ models.Page.objects.all().count()==0 and \ index.page_count()==0 and \ index.title_count()...
def handle(self, **options): if not (models.Title.objects.all().count() and \ models.Holding.objects.all().count() and \ models.Essay.objects.all().count() and \ models.Batch.objects.all().count() and \ models.Issue.objects.all().count() and \ models.Page.objects.all().count() and \ index.page_count() and \ index.title...
from hedge.tools import plot_1d
def test_kv_predictors(): from pyrticle.distribution import \ ChargelessKVRadiusPredictor, KVRadiusPredictor kv_env_exact = ChargelessKVRadiusPredictor(2.5e-3, 5e-6) kv_env_num = KVRadiusPredictor(2.5e-3, 5e-6) from hedge.tools import plot_1d steps = 50 for i in range(steps): s = kv_env_num.dt/7*i a_exact = kv_env_ex...
("rho_grid", rec.deposit_grid_rho()), ("j_grid", rec.deposit_grid_j(method.velocities(state))), ("rho_resid", rec.remap_residual(rec.deposit_grid_rho())),
("rho_grid", rec.deposit_grid_rho(state)), ("j_grid", rec.deposit_grid_j(state, method.velocities(state))), ("rho_resid", rec.remap_residual(rec.deposit_grid_rho(state))),
def set_radius(r): method.depositor.set_shape_function( state, method.get_shape_function_class() (r, method.mesh_data.dimensions, exponent,))
self.backend.average_groups.extend(ag)
self.backend.average_groups.extend( [int(ag_i) for ag_i in ag])
def prepare_average_groups(self): discr = self.method.discretization
inv_s_diag[:len(s),:len(s)] = numpy.diag(1/s)
inv_s_diag[:len(s),:len(s)] = numpy.diag(inv_s)
def make_pointwise_interpolation_matrix(self, eog, eg, el, ldis, svd, scaled_vdm, basis_subset=None): u, s, vt = svd
if len(basis) > len(points) or s[0]/s[-1] > 10:
if len(basis) > len(points) or numpy.abs(s[0]/s[-1]) > 10:
def prepare_with_pointwise_projection_and_basis_reduction(self): discr = self.method.discretization backend = self.backend
print "element %d: el.id, ldis.node_count(), len(basis),)
print "element %d: el.id, ldis.node_count(), ldis.node_count()-len(basis),)
def prepare_with_pointwise_projection_and_basis_reduction(self): discr = self.method.discretization backend = self.backend
return self.remap_grid_to_mesh(self.deposit_grid_j( state, velocities, pslice))
grid_j = self.deposit_grid_j(state, velocities, pslice) return self.remap_grid_to_mesh(grid_j)
def _deposit_j(self, state, velocities, pslice): return self.remap_grid_to_mesh(self.deposit_grid_j( state, velocities, pslice))
from meshpy.tet import MeshInfo, EXT_CLOSED_IN_RZ, \
from meshpy.tet import MeshInfo from meshpy.geometry import EXT_CLOSED_IN_RZ, \
def make_inverse_mesh_info(rz, radial_subdiv): # chop off points with zero radius while rz[0][0] == 0: rz.pop(0) while rz[-1][0] == 0: rz.pop(-1) # construct outer cylinder ((min_r, max_r), (min_z, max_z)) = bounding_box(rz) if rz[0][1] < rz[-1][1]: # built in positive z direction rz.extend([ (max_r+2, max_z), (max_r...
method="simplex_reduce")
submethod="simplex_reduce")
def run_kv3d(): O = ConstructorPlaceholder timestamp = get_timestamp() for chi in [None, 2]: for rec in [ O("DepShape"), O("DepGrid", O("FineCoreBrickGenerator", core_axis=2), #el_tolerance=0.1, method="simplex_reduce") ]: job = BatchJob( "kv3d-$DATE/%s-chi%s" % (cn(rec), chi), "-m pyrticle.driver", aux_files=["kv3d....
return -hyp_local_operator + InverseMassOperator() * ( flux_op * w + flux_op * BoundaryPair(w, pec_bc, pec_tag) )
return -hyp_local_operator + InverseMassOperator()( flux_op(w) + flux_op(BoundaryPair(w, pec_bc, pec_tag)))
def op_template(self): from hedge.tools import join_fields from hedge.optemplate import Field, make_vector_field, BoundaryPair, \ BoundarizeOperator, make_normal, get_flux_operator, \ make_nabla, InverseMassOperator
def __init__(self):
def __init__(self, name=None):
def __init__(self): _internal.NumberShiftListener.__init__(self) from weakref import WeakKeyDictionary self.subscribers = WeakKeyDictionary()
from hedge.timestep import RK4TimeStepper self.forward_stepper = RK4TimeStepper() self.backward_stepper = RK4TimeStepper()
from hedge.timestep.runge_kutta import LSRK4TimeStepper self.forward_stepper = LSRK4TimeStepper() self.backward_stepper = LSRK4TimeStepper()
def __init__(self, t0, y0, dt): self.t = [t0] self.y = [y0] self.dt = dt
("j", method.deposit_j(state)),
def set_radius(r): method.depositor.set_shape_function( state, method.get_shape_function_class() (r, method.mesh_data.dimensions, exponent,))
from hedge.mesh import make_conformal_mesh return make_conformal_mesh(mesh.points, mesh.elements,
vertices = numpy.asarray(mesh.points, dtype=float, order="C") from hedge.mesh import make_conformal_mesh_ext from hedge.mesh.element import Tetrahedron return make_conformal_mesh_ext( vertices, [Tetrahedron(i, el_idx, vertices) for i, el_idx in enumerate(mesh.elements)],
def zper_boundary_tagger(fvi, el, fn, points): face_marker = fvi2fm[frozenset(fvi)] if face_marker == MINUS_Z_MARKER: return ["minus_z"] elif face_marker == PLUS_Z_MARKER: return ["plus_z"] else: return ["shell"]
return self.search_package_directories(qualified_name, pxd_suffixes, pos)
print "Pyrex.Compiler.Main.find_pxd_file:" print "...qualified_name =", qualified_name print "...pos =", pos result = self.search_package_directories(qualified_name, pxd_suffixes, pos) print "Pyrex.Compiler.Main.find_pxd_file: result =", result return result
def find_pxd_file(self, qualified_name, pos): # Search include path for the .pxd file corresponding to the # given fully-qualified module name. # Will find either a dotted filename or a file in a # package directory. If a source file position is given, # the directory containing the source file is searched first #...
return self.search_package_directories(qualified_name, pyx_suffixes, pos)
print "Pyrex.Compiler.Main.find_pyx_file:", qualified_name, pos result = self.search_package_directories(qualified_name, pyx_suffixes, pos) print "Pyrex.Compiler.Main.find_pyx_file: result =", result return result
def find_pyx_file(self, qualified_name, pos): # Search include path for the .pyx file corresponding to the # given fully-qualified module name, as for find_pxd_file(). return self.search_package_directories(qualified_name, pyx_suffixes, pos)
if self.is_package_dir(dir): return dir
if not self.is_package_dir(dir): return return dir
def descend_to_package_dir(self, root_dir, package_names): # Starting from the given root directory, look for a nested # succession of package directories. Returns the full pathname # of the innermost one, or None. dir = root_dir for name in package_names: dir = os.path.join(dir, name) if self.is_package_dir(dir): r...
self.c_file = None self.h_file = None self.i_file = None self.api_file = None self.listing_file = None self.object_file = None self.extension_file = None
def __init__(self, source, options): self.c_file = None self.h_file = None self.i_file = None self.api_file = None self.listing_file = None self.object_file = None self.extension_file = None cwd = os.getcwd() source = os.path.join(cwd, source) if options.use_listing_file: self.listing_file = replace_suffix(source, ".li...
def any_results(self): return bool(self.c_file or self.h_file or self.i_file or self.api_file or self.listing_file or self.object_file or self.extension_file or self.num_errors)
def __init__(self, source, options): self.c_file = None self.h_file = None self.i_file = None self.api_file = None self.listing_file = None self.object_file = None self.extension_file = None cwd = os.getcwd() source = os.path.join(cwd, source) if options.use_listing_file: self.listing_file = replace_suffix(source, ".li...
if result.any_results(): results.add(source, result)
results.add(source, result)
def compile_multiple(sources, options): """ compile_multiple(sources, options) Compiles the given sequence of Pyrex implementation files and returns a CompilationResultSet. Performs timestamp checking and/or recursion if these are specified in the options. """ sources = [os.path.abspath(source) for source in sources] ...
"offsetof(%s, %s)" % (objstruct, entry.name),
"offsetof(%s, %s)" % (objstruct, entry.cname),
def generate_member_table(self, env, code): #print "ModuleNode.generate_member_table: scope =", env ### if env.public_attr_entries: code.putln("") code.putln( "static struct PyMemberDef %s[] = {" % env.member_table_cname) type = env.parent_type if type.typedef_flag: objstruct = type.objstruct_cname else: objstruct = "s...
if attr.beginswith("__") and attr.endswith("__"):
if attr.startswith("__") and attr.endswith("__"):
def compile_time_value(self, denv): attr = self.attribute if attr.beginswith("__") and attr.endswith("__"): self.error("Invalid attribute name '%s' in compile-time expression" % attr) return None obj = self.arg.compile_time_value(denv) try: return getattr(obj, attr) except Exception, e: self.compile_time_value_error(e)
return self.same_as(src_type)
return self.same_as(src_type) or src_type is error_type
def assignable_from_resolved_type(self, src_type): return self.same_as(src_type)
return src_type.is_int or src_type.is_enum or src_type is error_type
return src_type.is_int or src_type.is_enum \ or CNumericType.assignable_from_resolved_type(self, src_type)
def assignable_from_resolved_type(self, src_type): return src_type.is_int or src_type.is_enum or src_type is error_type
return src_type.is_numeric or src_type is error_type
return src_type.is_numeric \ or CNumericType.assignable_from_resolved_type(self, src_type)
def assignable_from_resolved_type(self, src_type): return src_type.is_numeric or src_type is error_type
if base_entry.is_type and base_entry.type.is_struct_or_union \ and base_entry.type.scope.is_cplus: base_scopes.append(base_entry.type.scope)
if not base_entry.is_type: self.base_error(base, "is not a type") elif not base_entry.type.is_struct_or_union: self.base_error(base, "is not a struct") elif not base_entry.type.scope: self.base_error(base, "is incomplete") elif not base_entry.type.scope.is_cplus: self.base_error(base, "is not a C++ struct")
def analyse_declarations(self, env): scope = None base_scopes = [] for base in self.bases: base_entry = env.find_qualified_name(base, self.pos) if base_entry: if base_entry.is_type and base_entry.type.is_struct_or_union \ and base_entry.type.scope.is_cplus: base_scopes.append(base_entry.type.scope) else: error(self.pos...
error(self.pos, "Base type '%s' is not a C++ struct" % ".".join(base[0] + [base[1]]))
base_scopes.append(base_entry.type.scope)
def analyse_declarations(self, env): scope = None base_scopes = [] for base in self.bases: base_entry = env.find_qualified_name(base, self.pos) if base_entry: if base_entry.is_type and base_entry.type.is_struct_or_union \ and base_entry.type.scope.is_cplus: base_scopes.append(base_entry.type.scope) else: error(self.pos...
obj = self.arg.compile_time_value(denv)
obj = self.obj.compile_time_value(denv)
def compile_time_value(self, denv): attr = self.attribute if attr.startswith("__") and attr.endswith("__"): self.error("Invalid attribute name '%s' in compile-time expression" % attr) return None obj = self.arg.compile_time_value(denv) try: return getattr(obj, attr) except Exception, e: self.compile_time_value_error(e)
print "Pyrex.Compiler.Main.find_pxd_file:" print "...qualified_name =", qualified_name print "...pos =", pos result = self.search_package_directories(qualified_name, pxd_suffixes, pos) print "Pyrex.Compiler.Main.find_pxd_file: result =", result return result
return self.search_package_directories(qualified_name, pxd_suffixes, pos)
def find_pxd_file(self, qualified_name, pos): # Search include path for the .pxd file corresponding to the # given fully-qualified module name. # Will find either a dotted filename or a file in a # package directory. If a source file position is given, # the directory containing the source file is searched first #...
print "Pyrex.Compiler.Main.find_pyx_file:", qualified_name, pos result = self.search_package_directories(qualified_name, pyx_suffixes, pos) print "Pyrex.Compiler.Main.find_pyx_file: result =", result return result
return self.search_package_directories(qualified_name, pyx_suffixes, pos)
def find_pyx_file(self, qualified_name, pos): # Search include path for the .pyx file corresponding to the # given fully-qualified module name, as for find_pxd_file(). print "Pyrex.Compiler.Main.find_pyx_file:", qualified_name, pos ### result = self.search_package_directories(qualified_name, pyx_suffixes, pos) print ...
print "Pyrex.Compiler.Main.search_package_directories:" print "...qualified_name =", qualified_name print "...suffixes =", suffixes print "...pos =", pos
def search_package_directories(self, qualified_name, suffixes, pos): print "Pyrex.Compiler.Main.search_package_directories:" ### print "...qualified_name =", qualified_name ### print "...suffixes =", suffixes ### print "...pos =", pos ### dotted_filenames = [qualified_name + suffix for suffix in suffixes] if pos: here ...
print "...root package dir =", here
def search_package_directories(self, qualified_name, suffixes, pos): print "Pyrex.Compiler.Main.search_package_directories:" ### print "...qualified_name =", qualified_name ### print "...suffixes =", suffixes ### print "...pos =", pos ### dotted_filenames = [qualified_name + suffix for suffix in suffixes] if pos: here ...
print "...package names =", package_names print "...module name =", module_name print "...filenames =", filenames
def search_package_directories(self, qualified_name, suffixes, pos): print "Pyrex.Compiler.Main.search_package_directories:" ### print "...qualified_name =", qualified_name ### print "...suffixes =", suffixes ### print "...pos =", pos ### dotted_filenames = [qualified_name + suffix for suffix in suffixes] if pos: here ...
print "...looking in root", root
def search_package_directories(self, qualified_name, suffixes, pos): print "Pyrex.Compiler.Main.search_package_directories:" ### print "...qualified_name =", qualified_name ### print "...suffixes =", suffixes ### print "...pos =", pos ### dotted_filenames = [qualified_name + suffix for suffix in suffixes] if pos: here ...
print "......package dir =", dir
def search_package_directories(self, qualified_name, suffixes, pos): print "Pyrex.Compiler.Main.search_package_directories:" ### print "...qualified_name =", qualified_name ### print "...suffixes =", suffixes ### print "...pos =", pos ### dotted_filenames = [qualified_name + suffix for suffix in suffixes] if pos: here ...
print "......looking for path", path
def search_package_directories(self, qualified_name, suffixes, pos): print "Pyrex.Compiler.Main.search_package_directories:" ### print "...qualified_name =", qualified_name ### print "...suffixes =", suffixes ### print "...pos =", pos ### dotted_filenames = [qualified_name + suffix for suffix in suffixes] if pos: here ...
def generate_dynamic_cast_code(self):
def generate_dynamic_cast_code(self, is_first = True):
def generate_dynamic_cast_code(self): global objects_by_name source = ""
source += objects_by_name[extended_by].generate_dynamic_cast_code()
source += objects_by_name[extended_by].generate_dynamic_cast_code(False)
def generate_dynamic_cast_code(self): global objects_by_name source = ""
if self.features & Object.FEATURE__DESERIALIZE: source += "/* esxVI_%s_Deserialize */\n" % self.name source += "ESX_VI__TEMPLATE__DESERIALIZE(%s,\n" % self.name source += "{\n" source += self.generate_deserialize_code() source += "})\n\n" if self.features & Object.FEATURE__LIST: source += "/* esxVI_%s_DeserializeLis...
if self.extended_by is None: if self.features & Object.FEATURE__DESERIALIZE: source += "/* esxVI_%s_Deserialize */\n" % self.name source += "ESX_VI__TEMPLATE__DESERIALIZE(%s,\n" % self.name source += "{\n" source += self.generate_deserialize_code() source += "})\n\n" if self.features & Object.FEATURE__LIST: source +...
def generate_source(self): source = "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" source += " * VI Type: %s\n" % self.name
source += "ESX_VI__TEMPLATE__CAST_FROM_ANY_TYPE(%s)\n" % self.name
source += "ESX_VI__TEMPLATE__CAST_FROM_ANY_TYPE(%s,\n" % self.name if self.extended_by is None: source += "{\n" source += "})\n\n" else: source += "{\n" for extended_by in self.extended_by: source += " ESX_VI__TEMPLATE__DISPATCH__CAST_FROM_ANY_TYPE(%s)\n" % extended_by source += "})\n\n"
def generate_source(self): source = "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" source += " * VI Type: %s\n" % self.name
cb(self, virDomain(self, _obj=dom), opaque)
cb(self, virDomain(self, _obj=dom), srcPath, devAlias, opaque) return 0 except AttributeError: pass def dispatchDomainEventIOErrorReasonCallback(self, dom, srcPath, devAlias, action, reason, cbData): """Dispatches events to python user domain IO error event callbacks """ try: cb = cbData["cb"] opaque = cbData["opaque"...
def dispatchDomainEventIOErrorCallback(self, dom, srcPath, devAlias, action, cbData): """Dispatches events to python user domain IO error event callbacks """ try: cb = cbData["cb"] opaque = cbData["opaque"]
'virDomainSnapshotListNames',
'virDomainRevertToSnapshot',
def enum(type, name, value): if not enums.has_key(type): enums[type] = {} enums[type][name] = value
"virConnect" : True
"virConnect" : True, "virDomainSnapshot": True,
def buildStubs(): global py_types global py_return_types global unknown_types try: f = open(os.path.join(srcPref,"libvirt-api.xml")) data = f.read() (parser, target) = getparser() parser.feed(data) parser.close() except IOError, msg: try: f = open(os.path.join(srcPref,"..","docs","libvirt-api.xml")) data = f.read() (...
and file != "python_accessor":
and file != "python_accessor" and not name in function_skip_index_one:
def buildWrappers(): global ctypes global py_types global py_return_types global unknown_types global functions global function_classes global classes_type global classes_list global converter_type global primary_classes global converter_type global classes_ancestor global converter_type global primary_classes global c...
source += " esxVI_%s_Free(&item->_next);\n\n" % self.name
if self.extends is not None: source += " esxVI_%s_Free((esxVI_%s **)&item->_next);\n\n" % (self.extends, self.extends) else: source += " esxVI_%s_Free(&item->_next);\n\n" % self.name
def generate_source(self): source = "/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n" source += " * VI Type: %s\n" % self.name
"HostDatastoreBrowserSearchResults" : Object.FEATURE__ANY_TYPE,
"HostDatastoreBrowserSearchResults" : Object.FEATURE__LIST | Object.FEATURE__ANY_TYPE,
def open_and_print(filename): if filename.startswith("./"): print " GEN " + filename[2:] else: print " GEN " + filename return open(filename, "wb")
string += "%s*%s)%s" % (self.get_type_string(), self.name, end_of_line)
string += "%s%s)%s" % (self.get_type_string(True), self.name, end_of_line)
def generate_return(self, offset = 0, end_of_line = ";"): if self.occurrence == OCCURRENCE__IGNORED: raise ValueError("invalid function parameteroccurrence value '%s'" % self.occurrence) else: string = " " string += " " * offset string += "%s*%s)%s" % (self.get_type_string(), self.name, end_of_line)
def get_type_string(self):
def get_type_string(self, as_return_value = False): string = ""
def get_type_string(self): if self.type == "String" and \ self.occurrence not in [OCCURRENCE__REQUIRED_LIST, OCCURRENCE__OPTIONAL_LIST]: return "const char *" elif self.is_enum(): return "esxVI_%s " % self.type else: return "esxVI_%s *" % self.type
return "const char *"
if as_return_value: string += "char *" else: string += "const char *"
def get_type_string(self): if self.type == "String" and \ self.occurrence not in [OCCURRENCE__REQUIRED_LIST, OCCURRENCE__OPTIONAL_LIST]: return "const char *" elif self.is_enum(): return "esxVI_%s " % self.type else: return "esxVI_%s *" % self.type
return "esxVI_%s " % self.type else: return "esxVI_%s *" % self.type
string += "esxVI_%s " % self.type else: string += "esxVI_%s *" % self.type if as_return_value: string += "*" return string
def get_type_string(self): if self.type == "String" and \ self.occurrence not in [OCCURRENCE__REQUIRED_LIST, OCCURRENCE__OPTIONAL_LIST]: return "const char *" elif self.is_enum(): return "esxVI_%s " % self.type else: return "esxVI_%s *" % self.type
source += " void, None,\n" else: source += " %s, %s,\n" % (self.returns.type, self.returns.get_occurrence_short_enum())
source += " void, /* nothing */, None,\n" elif self.returns.type == "String": source += " String, Value, %s,\n" % self.returns.get_occurrence_short_enum() else: source += " %s, /* nothing */, %s,\n" % (self.returns.type, self.returns.get_occurrence_short_enum())
def generate_source(self): source = "/* esxVI_%s */\n" % self.name source += "ESX_VI__METHOD(%s," % self.name
"""Dispatches events to python user domain event callbacks
"""Dispatches events to python user domain lifecycle event callbacks
def dispatchDomainEventLifecycleCallback(self, dom, event, detail, cbData): """Dispatches events to python user domain event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"]
"""Dispatches events to python user domain event callbacks
"""Dispatches events to python user domain generic event callbacks
def dispatchDomainEventGenericCallback(self, dom, cbData): """Dispatches events to python user domain event callbacks """ try: cb = cbData["cb"] opaque = cbData["opaque"]