rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
encoding = chardet.detect(doc) loc_doc.expected_encoding = \
if not no_encoding: encoding = chardet.detect(doc) encoding["encoding"] = encoding["encoding"].upper() loc_doc.expected_encoding = \
def _parse_l10n_doc(name, doc): "Parses an L10n document." extension = name.split(".")[-1].lower() handlers = {"dtd": dtd.DTDParser, "properties": properties.PropertiesParser} # These are expected encodings for the various files. handler_formats = {"dtd": ("UTF-8", ), "properties": ("ascii", "utf-8")} if extension no...
output = {"detected_type": self.detected_type,
types = {0: "unknown", 1: "extension", 2: "theme", 3: "dictionary", 4: "langpack", 5: "search"} output = {"detected_type": types[self.detected_type],
def print_json(self): "Prints a JSON summary of the validation operation." output = {"detected_type": self.detected_type, "success": not self.failed(), "rejected": self.reject, "messages":[]} messages = output["messages"] # Copy messages to the JSON output for error in self.errors: error["type"] = "error" self._clea...
"messages":[]}
"messages":[], "errors": len(self.errors), "warnings": len(self.warnings), "infos": len(self.infos)}
def print_json(self): "Prints a JSON summary of the validation operation." output = {"detected_type": self.detected_type, "success": not self.failed(), "rejected": self.reject, "messages":[]} messages = output["messages"] # Copy messages to the JSON output for error in self.errors: error["type"] = "error" self._clea...
self.tier = 0
self.tier = 1
def __init__(self, pipe=None, no_color=False, determined=True, listed=False): """Specifying pipe allows the output of the bundler to be written to a file rather than to the screen.""" self.errors = [] self.warnings = [] self.notices = [] self.message_tree = {}
uid = uuid.uuid1().hex
uid = uuid.uuid4().hex
def _save_message(self, stack, type_, message, context=None): "Stores a message in the appropriate message stack." uid = uuid.uuid1().hex message["uid"] = uid
not err.get_resource("SPIDERMONKEY"):
err.get_resource("SPIDERMONKEY") is None:
def test_js_file(err, name, data, filename=None, line=0): "Tests a JS file by parsing and analyzing its tokens" if SPIDERMONKEY_INSTALLATION is None and \ not err.get_resource("SPIDERMONKEY"): return # The filename is if filename is None: filename = name # Get the AST tree for the JS code tree = _get_tree(name, data...
tree = _get_tree(name, data, err.get_resource("SPIDERMONKEY") or SPIDERMONKEY_INSTALLATION)
try: tree = _get_tree(name, data, err.get_resource("SPIDERMONKEY") or SPIDERMONKEY_INSTALLATION) except RuntimeError: err.error(("testcases_scripting", "test_js_file", "retrieving_tree"), "JS Syntax error prevented validation", "An error in the syntax of a JavaScript file prevented " "the file from being properly read ...
def test_js_file(err, name, data, filename=None, line=0): "Tests a JS file by parsing and analyzing its tokens" if SPIDERMONKEY_INSTALLATION is None and \ not err.get_resource("SPIDERMONKEY"): return # The filename is if filename is None: filename = name # Get the AST tree for the JS code tree = _get_tree(name, data...
print "An error was encountered while attempting to validate a script"
pass
def test_js_file(err, name, data, filename=None, line=0): "Tests a JS file by parsing and analyzing its tokens" if SPIDERMONKEY_INSTALLATION is None and \ not err.get_resource("SPIDERMONKEY"): return # The filename is if filename is None: filename = name # Get the AST tree for the JS code tree = _get_tree(name, data...
line=exc.line)
line=exc.line, context=ContextGenerator(data))
def test_js_file(err, name, data, filename=None, line=0): "Tests a JS file by parsing and analyzing its tokens" if SPIDERMONKEY_INSTALLATION is None and \ err.get_resource("SPIDERMONKEY") is None: # Default value is False return # The filename is if filename is None: filename = name # Get the AST tree for the JS cod...
debug("processing %d/%d:\t %s" % (fileno+1, total, filename))
info("processing %d/%d:\t %s" % (fileno+1, total, filename))
def apply(self): """ apply parsed patch """
debug("hunk no.%d doesn't match source file %s" % (hunkno+1, filename))
info(" hunk no.%d doesn't match source file at line %d" % (hunkno+1, lineno)) info(" expected: %s" % hunkfind[hunklineno]) info(" actual : %s" % line.rstrip("\r\n"))
def apply(self): """ apply parsed patch """
debug("file %s hunk no.%d -- is ready to be patched" % (filename, hunkno+1))
debug(" hunk no.%d for file %s -- is ready to be patched" % (hunkno+1, filename))
def apply(self): """ apply parsed patch """
from optparse import OptionParser from os.path import exists import sys
def _get_file_idx(self, filename, source=None): """ Detect index of given filename within patch.
warning("successfully patched %s" % filename)
info("successfully patched %s" % filename)
def apply(self): """ apply parsed patch """
ret = os.system("%s %s %s" % (sys.executable, patch_tool, patch_file))
ret = os.system('%s %s "%s"' % (sys.executable, patch_tool, patch_file))
def _run_test(self, testname): """ boilerplate for running *.patch file tests """
for testname in testset: setattr(cls, "test%s" % testname, lambda self, name=testname: self._run_test(name))
for filename in testset: methname = filename.replace(" ", "_") def create_closure(): name = filename return lambda self: self._run_test(name) setattr(cls, "test%s" % methname, create_closure()) if verbose: print "added test method %s to %s" % (methname, cls)
def add_test_methods(cls): """ hack to generate test* methods in target class - one for each *.patch file in tests directory """ # list testcases - every test starts with number # and add them as test* methods testptn = re.compile(r"^(?P<name>\d{2,}.+)\.(?P<ext>[^\.]+)") testset = sorted( set([testptn.match(e).group('...
opt = OptionParser(usage="%prog [options] unipatch-file", version="python-patch %s" % __version__)
opt = OptionParser(usage="1. %prog [options] unipatch-file\n" " 2. %prog [options] http://host/patch", version="python-patch %s" % __version__)
def _get_file_idx(self, filename, source=None): """ Detect index of given filename within patch.
patchfile = args[0] if not exists(patchfile) or not isfile(patchfile): sys.exit("patch file does not exist - %s" % patchfile)
def _get_file_idx(self, filename, source=None): """ Detect index of given filename within patch.
patch = fromfile(patchfile)
patchfile = args[0] urltest = patchfile.split(':')[0] if (':' in patchfile and urltest.isalpha() and len(urltest) > 1): patch = fromurl(patchfile) else: if not exists(patchfile) or not isfile(patchfile): sys.exit("patch file does not exist - %s" % patchfile) patch = fromfile(patchfile)
def _get_file_idx(self, filename, source=None): """ Detect index of given filename within patch.
""" Check if file is already patched. Not reliable, because it compares target hunks and they could match source hunks, i.e. repeated lines. @return: True, False or None
"""Makes best guess if file is already patched. It's not 100% accurate, because target hunks could match source hunks, for example, if all lines in patched file are the same. Use file size or md5 for reliable checks. :returns: True, False or None
def check_patched(self, filename): """ Check if file is already patched. Not reliable, because it compares target hunks and they could match source hunks, i.e. repeated lines. @return: True, False or None """ idx = self._get_file_idx(filename) if idx == None: return None return self._check_file_hunks(filename, self.hun...
opt.add_option("-d", action="store_true", dest="debugmode", help="debug mode")
opt.add_option("--debug", action="store_true", dest="debugmode", help="debug mode")
def _get_file_idx(self, filename): """ Detect index of given filename within patch @return: int or None """ filename = abspath(filename) for i,fnm in enumerate(self.source): if filename == abspath(fnm): return i for i,fnm in enumerate(self.target): if filename == abspath(fnm): return i
header = False
headscan = False
def parse(self, stream): """ parse unified diff """ self.source = [] self.target = [] self.hunks = [] self.hunkends = []
header = True
headscan = True
def parse(self, stream): """ parse unified diff """ self.source = [] self.target = [] self.hunks = [] self.hunkends = []
if header and line.startswith("--- "): header = False
if headscan: header = '' try: while not line.startswith("--- "): header += line lineno, line = fe.next() except StopIteration: continue self.header.append(header) print header headscan = False
def parse(self, stream): """ parse unified diff """ self.source = [] self.target = [] self.hunks = [] self.hunkends = []
print header
def parse(self, stream): """ parse unified diff """ self.header = []
for x in ( "/usr", "/usr/local/boost", "/opt/boost" ):
for x in ( "/usr", "/usr/local/boost", "/opt/boost", "/usr/incude/boost" ):
def findBoost( options ): """find location of boost.""" if not options.boost_dir: if "BOOST_ROOT" in os.environ: options.boost_dir = os.environ['BOOST_ROOT'] return for x in ( "/usr", "/usr/local/boost", "/opt/boost" ): if os.path.exists( x ): options.boost_dir = x return raise "could not find BOOST. Please specify l...
Paste.query.filter(Paste.paste_id.in_(to_mark)) \ .update(values={'handled': True}) db.session.commit()
if to_mark: Paste.query.filter(Paste.paste_id.in_(to_mark)) \ .update(values={'handled': True}) db.session.commit()
def fetch_replies(): """Get the new replies for the ower of a request and flag them as handled. """ ids = db.session.query(Paste.paste_id) \ .filter(Paste.user_hash == local.request.user_hash)
peeps = Parent.objects.filter(user__is_active=True)
peeps = Parent.objects.filter(user__is_active=True,family__student__enrolled=True)
def write_file(group,peeps=None,extra=None,extranomail=None): # Re-usable function to write text files. thefile = open(os.path.join(settings.LISTGENPATH, group + ".txt"), 'w') if peeps: for p in peeps : # Most queries give us Parent objects, but some (teahers) give us User objects. # But in all cases we want the User...
print 'parsed',self.page,'got',p,'internal links' d = urlsplit(self.page) bpl = re.subn('/','-',d.path)[0] if len(bpl) == 0: bpl = 'homepage' try: c=urllib2.urlopen(self.page) except: return False
progress('to parse: %s, last activity: %s' % (len(newpages),'+%s'%p))
def run(self): try: c=urllib2.urlopen(self.page) except: print "Could not open %s" % self.page sys.exit() dat = c.read() #parse line by line lines = re.split('\n',dat) p=0 for line in lines: if re.match('.*<a[^>]*/?>.*',line): #grab the atrib str m = re.match('.*<a([^>]*)/?>.*',line) #exclude hashtags if not full urls ...
print "Could not open %s" % self.page
def run(self): try: c=urllib2.urlopen(self.page) except: print "Could not open %s" % self.page sys.exit() dat = c.read() #parse line by line lines = re.split('\n',dat) p=0 for line in lines: if re.match('.*<a[^>]*/?>.*',line): #grab the atrib str m = re.match('.*<a([^>]*)/?>.*',line) #exclude hashtags if not full urls ...
while opts.aThreads >= mThreads:
while threadcheck() or opts.aThreads >= mThreads:
def crawl(self,pages,mThread=1): tID = 0 for page in pages: newpages.add(page) while _toparse(): ''' need to set cPages due to RuntimeError: Set changed size during iteration when multi threading ''' cPages = list(newpages) for page in cPages: tID += 1 c = child(tID,page) self.cThreads.append(c) c.start() threadcheck()...
print opts.aThreads
print opts.aThreads,mThreads
def crawl(self,pages,mThread=1): tID = 0 for page in pages: newpages.add(page) while _toparse(): ''' need to set cPages due to RuntimeError: Set changed size during iteration when multi threading ''' cPages = list(newpages) for page in cPages: tID += 1 c = child(tID,page) self.cThreads.append(c) c.start() threadcheck()...
pages = newpages for page in pages: newpages.add(page) p = 0 for page in newpages: p += 1 c = child(p,page)
cPages = list(newpages) for page in cPages: tID += 1 c = child(tID,page)
def crawl(self,pages,mThread=1): for page in pages: newpages.add(page) while _toparse(): pages = newpages for page in pages: newpages.add(page) p = 0 for page in newpages: p += 1 c = child(p,page) self.cThreads.append(c) c.start() threadcheck() while aThreads >= mThreads: print 'Reached max threads waiting on some to ...
c = urllib2.urlopen(self.page) inf = c.info() except: print 'Failed to open',self.page sys.exit(1) ''' validate varnish is running on this request ''' parseInfo(inf,self.page) ''' read the data and parse line by line ''' dat = c.read()
c=urllib2.urlopen(self.page) except: print "Could not open %s" % self.page sys.exit() dat = c.read()
def run(self): ''' try to open connection ''' try: c = urllib2.urlopen(self.page) inf = c.info() except: print 'Failed to open',self.page sys.exit(1)
print self.page
def run(self): ''' try to open connection ''' try: c = urllib2.urlopen(self.page) inf = c.info() except: print 'Failed to open',self.page sys.exit(1)
print 'parsed',self.page,'got',p,'internal links' d = urlsplit(self.page) bpl = re.subn('/','-',d.path)[0] if len(bpl) == 0: bpl = 'homepage' try: c=urllib2.urlopen(self.page) prg = os.system("ab -c 100 -n 100 -g '/root/benchwalk/%s.bpl' %s/ "%(bpl,self.page)) except: return False
def run(self): ''' try to open connection ''' try: c = urllib2.urlopen(self.page) inf = c.info() except: print 'Failed to open',self.page sys.exit(1)
def crawl(self,pages):
def crawl(self,pages,mThread=1):
def crawl(self,pages): for page in pages: newpages.add(page) while _toparse(): pages = newpages for page in pages: newpages.add(page) p = 0 for page in newpages: p += 1 c = child(p,page) self.cThreads.append(c) c.start() threadcheck() while aThreads >= 5: print 'Reached max threads waiting on some to exit' time.sleep(...
while aThreads >= 5:
while aThreads >= mThreads:
def crawl(self,pages): for page in pages: newpages.add(page) while _toparse(): pages = newpages for page in pages: newpages.add(page) p = 0 for page in newpages: p += 1 c = child(p,page) self.cThreads.append(c) c.start() threadcheck() while aThreads >= 5: print 'Reached max threads waiting on some to exit' time.sleep(...
if __name__ == "__main__":
if __name__ == '__main__': if not os.path.isdir('/root/benchwalk'): print '/root/benchwalk required, please mkdir /root/benchwalk and retry' sys.exit(1) q = 'How many threads do you want?:'
def crawl(self,pages): for page in pages: newpages.add(page) while _toparse(): pages = newpages for page in pages: newpages.add(page) p = 0 for page in newpages: p += 1 c = child(p,page) self.cThreads.append(c) c.start() threadcheck() while aThreads >= 5: print 'Reached max threads waiting on some to exit' time.sleep(...
url = raw_input(q) c = crawler()
url = raw_input(q) c = crawler() c.crawl([url])
def crawl(self,pages): for page in pages: newpages.add(page) while _toparse(): pages = newpages for page in pages: newpages.add(page) p = 0 for page in newpages: p += 1 c = child(p,page) self.cThreads.append(c) c.start() threadcheck() while aThreads >= 5: print 'Reached max threads waiting on some to exit' time.sleep(...
c.crawl([url])
def crawl(self,pages): for page in pages: newpages.add(page) while _toparse(): pages = newpages for page in pages: newpages.add(page) p = 0 for page in newpages: p += 1 c = child(p,page) self.cThreads.append(c) c.start() threadcheck() while aThreads >= 5: print 'Reached max threads waiting on some to exit' time.sleep(...
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
return open('/'.join(rnames)).read()
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
def poodleResults(self,data=False):
def poodleResults(self, data=None, print_html=True):
def poodleResults(self,data=False): """count all user votes per date will be displayed at the bottom of the table """ context = self.context.aq_inner if not data: data = context.getPoodleData() ids = data['ids'] users = data['users'].values() counted = []
counted = []
result = []
def poodleResults(self,data=False): """count all user votes per date will be displayed at the bottom of the table """ context = self.context.aq_inner if not data: data = context.getPoodleData() ids = data['ids'] users = data['users'].values() counted = []
counted.append(counter) h_value = max(counted)
result.append(counter) if not print_html: data['result']= result return data h_value = max(result)
def poodleResults(self,data=False): """count all user votes per date will be displayed at the bottom of the table """ context = self.context.aq_inner if not data: data = context.getPoodleData() ids = data['ids'] users = data['users'].values() counted = []
for v in counted:
for v in result:
def poodleResults(self,data=False): """count all user votes per date will be displayed at the bottom of the table """ context = self.context.aq_inner if not data: data = context.getPoodleData() ids = data['ids'] users = data['users'].values() counted = []
read('CHANGES.txt')
read('docs', 'HISTORY.txt')
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
+ '\n' + 'Contributors\n' '************\n' + '\n' + read('CONTRIBUTORS.txt')
def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
if not result: return ""
def poodleResults(self, data=None, print_html=True): """count all user votes per date will be displayed at the bottom of the table
dates = self.getDates()
dates = self.context.getDates()
def updateDates(self): """updates date informations """ poodledata = self.getPoodleData() dates = self.getDates() poodledata["dates"] = [i['date'] for i in dates] poodledata['ids'] = self.context.getDatesHash() return poodledata
return poodledata
if not self.getPoodleData(): self.setPoodleData(poodledata)
def updateDates(self): """updates date informations """ poodledata = self.getPoodleData() dates = self.getDates() poodledata["dates"] = [i['date'] for i in dates] poodledata['ids'] = self.context.getDatesHash() return poodledata
if not hasattr(poodledata,'users'):
if 'users' not in poodledata:
def updateUsers(self): """uddate user informations """ poodledata = self.getPoodleData() users = self.context.getUsers() choices = poodledata['ids']
return poodledata
if not self.getPoodleData(): self.setPoodleData(poodledata)
def updateUsers(self): """uddate user informations """ poodledata = self.getPoodleData() users = self.context.getUsers() choices = poodledata['ids']
self.assertTrue(review.pdf.blob == review.get_review_pdf()
self.assertTrue(review.pdf.blob == review.get_review_pdf(),
def test_review_with_custom_pdf_files(self): """Reviews / Presentations which have a custom pdf file will use that version for downloading and conversion to swf """ portal = self.layer["portal"] sample_reviews = portal["sample-reviews"] review = sample_reviews[sample_reviews.objectIds()[0]] # The sample reviews have bo...
self.assertTrue(hasattr(review, "generatedPdf")
self.assertTrue(hasattr(review, "generatedPdf"),
def test_review_with_custom_pdf_files(self): """Reviews / Presentations which have a custom pdf file will use that version for downloading and conversion to swf """ portal = self.layer["portal"] sample_reviews = portal["sample-reviews"] review = sample_reviews[sample_reviews.objectIds()[0]] # The sample reviews have bo...
default_method="get_user_lastname",
def __call__(self, value, *args, **kwargs): if value == True: return 1 site = getSite() language = getToolByName(site, 'portal_languages').getPreferredLanguage() return translate(_(u'message_ccby_license', default=u"All submitted reviews must be published under the CC-BY licence."), target_language=language)
default_method="get_user_firstname",
def __call__(self, value, *args, **kwargs): if value == True: return 1 site = getSite() language = getToolByName(site, 'portal_languages').getPreferredLanguage() return translate(_(u'message_ccby_license', default=u"All submitted reviews must be published under the CC-BY licence."), target_language=language)
u'de Roiste, Cillian: presentation of: Gerken, Patrick / Pilz, Alexander, Das neue Plone 4.0. Alles neu in 2010, in: Open Source Mag, 1, 3 (2009), http://www.syslab.com
u'de Roiste, Cillian: presentation of: Gerken, Patrick / Pilz, Alexander, Das neue Plone 4.0. Alles neu in 2010, in: Open Source Mag, 1, 3 (2009), http://www.syslab.com'
def get_citation_string(real_self): """ Either return the custom citation or the generated one >>> from mock import Mock >>> at_mock = Mock() >>> at_mock.get = lambda x: None >>> at_mock.customCitation = '' >>> at_mock.authors = [{'firstname': x[0], 'lastname' : x[1]} for x in (('Patrick', 'Gerken'), ('Alexander', 'Pil...
'publisher':u'',}
'publisher':u'', 'urn': u'testing-data-urn'}
def addExampleContent(context): portal = context.getSite() portal_id = "recensio" if "sample-reviews" not in portal.objectIds(): portal.invokeFactory("Folder", id="sample-reviews", title="Sample Reviews") reviews = portal.get("sample-reviews") pdf_file = open(os.path.join( os.path.dirname(__file__), "tests", "test_c...
if "newspapera" not in reviews.objectIds(): reviews.invokeFactory("Publication", id="newspapera",
if "newspapera" not in sample_reviews.objectIds(): sample_reviews.invokeFactory("Publication", id="newspapera",
def test_data(): """Randomise the values in certain fields """ return {'authors': [random.choice(authors_list)], 'referenceAuthors': [random.choice(referenceAuthors_list), random.choice(referenceAuthors_list)], 'ddcPlace': random.choice(ddcPlace_list), 'ddcSubject': random.choice(ddcSubject_list), 'ddcTime': random.cho...
newspapera = reviews["newspapera"]
newspapera = sample_reviews["newspapera"]
def test_data(): """Randomise the values in certain fields """ return {'authors': [random.choice(authors_list)], 'referenceAuthors': [random.choice(referenceAuthors_list), random.choice(referenceAuthors_list)], 'ddcPlace': random.choice(ddcPlace_list), 'ddcSubject': random.choice(ddcSubject_list), 'ddcTime': random.cho...
terms = [(x.value, x.title) for x in vocab]
terms = [(x.value, _languagelist[x.value][u'native']) for x in vocab]
def listSupportedLanguages(self): util = getUtility(IVocabularyFactory, u"recensio.policy.vocabularies.available_content_languages") vocab = util(self) terms = [(x.value, x.title) for x in vocab] return DisplayList(terms)
sample_reviews = portal["sample-reviews"] review = sample_reviews[sample_reviews.objectIds()[0]]
pm = portal.portal_membership sample_presentations = pm.getMembersFolder().get("fake_member") review = sample_presentations[sample_presentations.objectIds()[0]]
def test_review_with_custom_pdf_files(self): """Reviews / Presentations which have a custom pdf file will use that version for downloading and conversion to swf """ portal = self.layer["portal"] sample_reviews = portal["sample-reviews"] review = sample_reviews[sample_reviews.objectIds()[0]] # The sample reviews have bo...
def guard(func):
def guard(func, profiles):
def guard(func): def wrapper(self): if self.readDataFile('recensio.contenttypes_marker.txt') is None: return return func(self) return wrapper
if self.readDataFile('recensio.contenttypes_marker.txt') is None: return return func(self)
for profile in profiles: if self.readDataFile('recensio.contenttypes_%s_marker.txt' \ % profile) is not None: return func(self) return
def wrapper(self): if self.readDataFile('recensio.contenttypes_marker.txt') is None: return return func(self)
@guard
@guard(['exampledata'])
def wrapper(self): if self.readDataFile('recensio.contenttypes_marker.txt') is None: return return func(self)
@guard
@guard(['exampledata'])
def addExampleContent(context): add_number_of_each_review_type(context, 10)
@guard
@guard(['exampledata'])
def addExampleContent2(context): portal = context.getSite() portal_id = 'recensio' if 'reviews' not in portal.objectIds(): portal.invokeFactory('Folder', id='reviews', title='Reviews') reviews = portal.get('reviews') xls_data = XlsReader(context.openDataFile('initial.xls')).read().data keys = xls_data[0] for row in x...
@guard
@guard(['default'])
def addOneOfEachReviewType(context): add_number_of_each_review_type(context, 1)
addOneItem(containerb, rez_class, {}) item = containerb.objectValues()[0] comment = createObject('plone.Comment') IConversation(item).addComment(comment)
def test_data(): """Randomise the values in certain fields """ return {'authors': [random.choice(authors_list)], 'referenceAuthors': [random.choice(referenceAuthors_list), random.choice(referenceAuthors_list)], 'ddcPlace': random.choice(ddcPlace_list), 'ddcSubject': random.choice(ddcSubject_list), 'ddcTime': random.cho...
review_author = ('%s %s %s' % (\ self.get('reviewAuthorHonorific') ,self.get('reviewAuthorFirstname') ,self.get('reviewAuthorLastname'))).decode('utf-8').encode('utf-8') if review_author.strip(): retval.append(review_author.strip())
try: review_author = ('%s %s %s' % (\ self.reviewAuthorHonorific ,self.reviewAuthorFirstname ,self.reviewAuthorLastname )).decode('utf-8').encode('utf-8') if review_author.strip(): retval.append(review_author.strip()) except AttributeError: pass
def getAllAuthorData(self): retval = [] field_values = list(getattr(self, 'authors', [])) + \ list(getattr(self, 'referenceAuthors', [])) for data in field_values: retval.append(('%s %s' % (data['firstname'], data['lastname'])).decode('utf-8').encode('utf-8')) review_author = ('%s %s %s' % (\ self.get('reviewAuthorHono...
self.assertFalse(ImageValidator()(no_image))
self.assertFalse(ImageValidator()(no_image) == True)
def testWithInvalidImages(self): no_image = file(pkg_resources.resource_filename(__name__, 'test.txt')) self.assertFalse(ImageValidator()(no_image))
value = ", ".join(value[0])
value = ", ".join(value[0].values())
def get_citation_dict(self, citation_template): """ Parse the citation_template and using the create a dict the values to be substituted, including translation """ formatter = Formatter() # Get the keys from the citation_template string i.e. words inside {} keys = set([i[1] for i in formatter.parse(citation_template)])...
u'de Roiste, Cillian: review of: Gerken, Patrick / Pilz, Alexander, Plone 4.0. Das Benutzerhandbuch, M\\xc3\\xbcnchen: SYSLAB.COM GmbH, 2009, http://www.syslab.com'
u'de Roiste, Cillian: presentation of: Gerken, Patrick / Pilz, Alexander, Plone 4.0. Das Benutzerhandbuch, M\\xc3\\xbcnchen: SYSLAB.COM GmbH, 2009, http://www.syslab.com'
def get_citation_string(real_self): """ I think the in... part does not make sense for this content type Either return the custom citation or the generated one >>> from mock import Mock >>> at_mock = Mock() >>> at_mock.get = lambda x: None >>> at_mock.authors = [{'firstname': x[0], 'lastname' : x[1]} for x in (('Patric...
full_citation_inner = getFormatter(u': review of: ', u', ')
full_citation_inner = getFormatter(u': presentation of: ', u', ')
def get_citation_string(real_self): """ I think the in... part does not make sense for this content type Either return the custom citation or the generated one >>> from mock import Mock >>> at_mock = Mock() >>> at_mock.get = lambda x: None >>> at_mock.authors = [{'firstname': x[0], 'lastname' : x[1]} for x in (('Patric...
Check that the upload really is an image
Check that an image upload value is either an image or the command to delete the current image
def __call__(self, value, *args, **kwargs): if value == True: return 1 site = getSite() language = getToolByName(site, 'portal_languages').getPreferredLanguage() return translate( _(u'message_ccby_license', default=(u"All submitted reviews must be published under " "the CC-BY licence.") ), target_language=language)
try: Image.open(value) value.seek(0) return True except IOError, e: return _(str(e))
if value != "DELETE_IMAGE": try: Image.open(value) value.seek(0) return True except IOError, e: return _(str(e))
def __call__(self, value, *args, **kwargs): try: Image.open(value) value.seek(0) return True except IOError, e: return _(str(e))
meta = None
meta = u''
def add_meta(method, separator): """ Adds a section of metadata if it exists """ meta = None if hasattr(context, method): meta = context[method]() if meta: return separator+" "+meta
return separator+" "+meta
meta = separator+" "+meta return meta
def add_meta(method, separator): """ Adds a section of metadata if it exists """ meta = None if hasattr(context, method): meta = context[method]() if meta: return separator+" "+meta
return translate(_(u"message_exceeded_characters", default =(
return translate( _(u"message_characters_exceeded", default =(
def __call__(self, value, *args, **kwargs): html = fromstring(value) text = etree.tostring(html, method="text") character_count = len(text) if character_count <= 4000: return 1 else: return translate(_(u"message_exceeded_characters", default =( u"You have exceeded the maximum number of characters you are " "permitted t...
validators=(characterLimit(),),
def __call__(self, value, *args, **kwargs): html = fromstring(value) text = etree.tostring(html, method="text") character_count = len(text) if character_count <= 4000: return 1 else: return translate(_(u"message_exceeded_characters", default =( u"You have exceeded the maximum number of characters you are " "permitted t...
for img in [gif for gif in os.listdir(tmp_pdfin) if os.path.splitext(gif)[1] == '.gif']:
imgfiles = [gif for gif in os.listdir(tmp_pdfin) if os.path.splitext(gif)[1] == '.gif'] imgfiles.sort() for img in imgfiles:
def _getAllPageImages(self, size=(320,452)): tmp_pdfin = tmp_pdfout = tmp_gifin = None result = '' pageimg = None pages = [] logger.debug("Calling external tools for page image generation:") try: mainpub = self.context pdf = mainpub.get_review_pdf() data = pdf.open().read() if not data: return 0 tmp_pdfin = tempfile.mk...
if "Review" in self.portal_type:
if review.portal_type.startswith("Review"):
def test_review_with_custom_pdf_files(self): """Reviews / Presentations which have a custom pdf file will use that version for downloading """ portal = self.layer["portal"] pm = portal.portal_membership sample_presentations = pm.getMembersFolder().get("fake_member") review = sample_presentations[sample_presentations.ob...
self.__devtype = t
def connect_debug(self, inp, outp): self.__devtype = t self.__shakedev = pyshake.init_device_debug(inp, outp, self.__devtype) if self.__shakedev == -1: self.__lasterror = "Failed to connect" return False
self.cap_sk6[0] = int(packetbuf[5:9])
self.data.cap_sk6[0] = int(packetbuf[5:9])
def extract_ascii_packet(self, packet_type, packetbuf, playback, timestamp_packet): if packet_type == SK6_DATA_ACC: # fmt: $ACC,+dddd,+dddd,+dddd,ss*CS\r\n self.data.accx = int(packetbuf[5:10]) self.data.accy = int(packetbuf[11:16]) self.data.accz = int(packetbuf[17:22]) self.data.internal_timestamps[SHAKE_SENSOR_ACC] ...
self.cap_sk6[1] = int(packetbuf[5:9])
self.data.cap_sk6[1] = int(packetbuf[5:9])
def extract_ascii_packet(self, packet_type, packetbuf, playback, timestamp_packet): if packet_type == SK6_DATA_ACC: # fmt: $ACC,+dddd,+dddd,+dddd,ss*CS\r\n self.data.accx = int(packetbuf[5:10]) self.data.accy = int(packetbuf[11:16]) self.data.accz = int(packetbuf[17:22]) self.data.internal_timestamps[SHAKE_SENSOR_ACC] ...
self.data.internal_timestamps[SHAKE_SENSOR_GYRO] = ord(packet[9:10])
self.data.internal_timestamps[SHAKE_SENSOR_GYRO] = ord(packetbuf[9:10])
def extract_raw_packet(self, packet_type, packetbuf, has_seq): if packet_type == SK7_RAW_DATA_ACC: self.data.accx = pyshake_sk_common.convert_raw_data_value(packetbuf[3:5]) self.data.accy = pyshake_sk_common.convert_raw_data_value(packetbuf[5:7]) self.data.accz = pyshake_sk_common.convert_raw_data_value(packetbuf[7:9])...
if (trailing_byte == self.data.internal_timestamps[adjtype] + 1) or (trailing_byte == 0 and self.data.internal_timestamps[adjtype] == 255):
if (ord(trailing_byte) == self.data.internal_timestamps[adjtype] + 1) or (ord(trailing_byte) == 0 and self.data.internal_timestamps[adjtype] == 255):
def read_raw_packet(self, packet_type, packetbuf): packet_size, bytes_left, bytes_read = 0,0,0
return SHAKE_RAW_READ_ERROR
return SK6_RAW_READ_ERROR
def read_raw_packet(self, packet_type, packetbuf): packet_size, bytes_left, bytes_read = 0,0,0
testcase = xmlio.Element('robot', status=status, source=source, suite_name=suite_name, message=message)
testcase = xmlio.Element('robot', status=status.encode('utf-8'), source=source.encode('utf-8'), suite_name=suite_name.encode('utf-8'), message=message.encode('utf-8'))
def robot(ctxt, file_=None): """Extract data from a ``pybot`` report. :param ctxt: the build context :type ctxt: `Context` :param file\_: name of the file containing the pybot report """ assert file_, 'Missing required attribute "file"' results = xmlio.Fragment() for case in RobotFrameworkReportParser(ctxt.resolve(f...
if os.path.exists(config_path):
if os.path.isfile(config_path):
def _get_xdg_path(filename, data_type, default_directories=None, create_missing_dir=False): """Get the full path to a file using XDG file layout spec. Follows XDG Base Directory Specification. (http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html). Tries default_directories and DEFAULT_GOOGLECL_DIR i...
import os import subprocess
import webbrowser
def request_access(self): """Do all the steps involved with getting an OAuth access token. Return: True if access token was succesfully retrieved and set, otherwise False. """ import ConfigParser import os import subprocess # Installed applications do not have a pre-registration and so follow # directions for unregis...
browser = googlecl.CONFIG.get('GENERAL', 'auth_browser') except ConfigParser.NoOptionError: browser = os.getenv('BROWSER')
try: browser_str = googlecl.CONFIG.get('GENERAL', 'auth_browser') except ConfigParser.NoOptionError: browser = webbrowser.get() else: browser = webbrowser.get(browser_str) browser.open(auth_url) except webbrowser.Error, err: print 'Failed to launch web browser: ' + str(err)
def request_access(self): """Do all the steps involved with getting an OAuth access token. Return: True if access token was succesfully retrieved and set, otherwise False. """ import ConfigParser import os import subprocess # Installed applications do not have a pre-registration and so follow # directions for unregis...
if browser: try: subprocess.call([browser, auth_url]) except OSError, err: print 'Error using browser "' + browser + '": ' + str(err) else: print '(Hint: You can automatically launch your browser by adding ' +\ '"auth_browser = <browser>" to your config file under the ' +\ 'GENERAL section, or define the BROWSER enviro...
def request_access(self): """Do all the steps involved with getting an OAuth access token. Return: True if access token was succesfully retrieved and set, otherwise False. """ import ConfigParser import os import subprocess # Installed applications do not have a pre-registration and so follow # directions for unregis...
LOG.debug('Arguments: %s' % args)
LOG.debug('Arguments: %s' % str(args))
def retry_operation(self, *args, **kwargs): """Retries an operation if certain status codes are returned.
val = getattr(wrapped_entry, attr) or missing_field_value
val = getattr(wrapped_entry, attr.replace('-','_') or missing_field_value
def compile_entry_string(wrapped_entry, attribute_list, delimiter, missing_field_value=None, newline_replacer=' '): """Return a useful string describing a gdata.data.GDEntry. Keyword arguments: wrapped_entry: BaseEntryToStringWrapper or subclass to display. attribute_list: List of attributes to access delimiter: Strin...
xdg_home_dir = os.path.join(os.environ.get('HOME'), '.local', 'share')
xdg_home_dir = os.path.join(home_dir, '.local', 'share')
def _get_xdg_path(filename, data_type, default_directories=None, create_missing_dir=False): """Get the full path to a file using XDG file layout spec. Follows XDG Base Directory Specification. (http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html). Tries default_directories and DEFAULT_GOOGLECL_DIR i...
xdg_home_dir = os.path.join(os.environ.get('HOME'), '.config')
xdg_home_dir = os.path.join(home_dir, '.config')
def _get_xdg_path(filename, data_type, default_directories=None, create_missing_dir=False): """Get the full path to a file using XDG file layout spec. Follows XDG Base Directory Specification. (http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html). Tries default_directories and DEFAULT_GOOGLECL_DIR i...
end_datetime = end_date.local
inclusive_end_datetime = end_date.local + datetime.timedelta(hours=24)
def filter_all_day_events_outside_range(start_date, end_date, events): if start_date: if start_date.all_day: start_datetime = start_date.local else: start_datetime = datetime.datetime(year=start_date.local.year, month=start_date.local.month, day=start_date.local.day) if end_date: if end_date.all_day: end_datetime = end...
inclusive_end_datetime = end_datetime + datetime.timedelta(hours=24)
def filter_all_day_events_outside_range(start_date, end_date, events): if start_date: if start_date.all_day: start_datetime = start_date.local else: start_datetime = datetime.datetime(year=start_date.local.year, month=start_date.local.month, day=start_date.local.day) if end_date: if end_date.all_day: end_datetime = end...