rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
cmd = '/usr/bin/ffmpeg -i {0} {1} -bufsize {2} -s {3}x{4} -{5} {6} -{7} {6} -aspect {11} -ab {8} -b {9} {10}'.format(
cmd = '/usr/bin/ffmpeg -i "{0}" {1} -bufsize {2} -s {3}x{4} -{5} {6} -{7} {6} -aspect {11} -ab {8} -b {9} {10}'.format(
def process_files(files, options): if len(files) == 0: print 'Error: no valid files could be found.' sys.exit(1) return print 'Found %s files to be processed' % len(files) for f in files: print ' processing: %s' % f outfile = os.path.splitext(os.path.basename(f))[0] + '.mp4' outfile = os.path.join(options.outdir,...
p = Popen (cmd.split(), stdout=PIPE, stderr=PIPE, shell=False)
args = shlex.split(cmd) p = Popen (args, stdout=PIPE, stderr=PIPE, shell=False)
def encode(cmd, duration=0): result = '' time_f = 0 p = Popen (cmd.split(), stdout=PIPE, stderr=PIPE, shell=False) fcntl.fcntl( p.stderr.fileno(), fcntl.F_SETFL, fcntl.fcntl(p.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK, ) while True: # wait for I/O completion readx = select.select([p.stderr.fileno()], [], [])[0] ...
parser.add_argument('-i', '--iphone', action='store_true', help='utilize iphone width and height (320x480)' )
parser.add_argument('-i', '--iphone', action='store_true')
def valid_dir(string): value = str(string) if not os.path.isabs(value): value = os.path.abspath(value) if not os.path.exists(value): msg = "Nonexistent path: %s" % value raise argparse.ArgumentTypeError(msg) return value
eq_(datetime.datetime.now(), now) patched.restore()
try: eq_(datetime.datetime.now(), now) finally: patched.restore() eq_(datetime.datetime.now, orig_datetime.now) def test_patch_builtin_as_string(): import datetime orig_datetime = datetime.datetime now = datetime.datetime(2006, 11, 4, 8, 19, 11, 28778) fake_dt = fudge.Fake('datetime').provides('now').returns(now) pat...
def test_patch_builtin(): import datetime orig_datetime = datetime.datetime now = datetime.datetime(2010, 11, 4, 8, 19, 11, 28778) fake = fudge.Fake('now', callable=True).returns(now) patched = fudge.patch_object(datetime.datetime, 'now', fake) eq_(datetime.datetime.now(), now) patched.restore() eq_(datetime.datetime.n...
AssertionError: fake:system.set_status(arg.passes_test(<function is_valid at ...>)) was called unexpectedly with args ('sleep')
AssertionError: fake:system.set_status(arg.passes_test(<function is_valid at...)) was called unexpectedly with args ('sleep')
>>> def is_valid(s):
setattr(self.orig_object, self.attr_name, patched_value) except TypeError: proxy_name = 'fudge_proxy_%s_%s_%s' % (self.orig_object.__module__, self.orig_object.__name__, patched_value.__class__.__name__) self.proxy_object = type(proxy_name, (self.orig_object,), { self.attr_name: patched_value }) setattr(sys.modules[sel...
try: setattr(self.orig_object, self.attr_name, patched_value) except TypeError: proxy_name = 'fudge_proxy_%s_%s_%s' % ( self.orig_object.__module__, self.orig_object.__name__, patched_value.__class__.__name__ ) self.proxy_object = type(proxy_name, (self.orig_object,), { self.attr_name: patched_value }) setattr(sys.modu...
def patch(self, patched_value): """Set a new value for the attibute of the object.""" lock.acquire() try: setattr(self.orig_object, self.attr_name, patched_value) except TypeError: proxy_name = 'fudge_proxy_%s_%s_%s' % (self.orig_object.__module__, self.orig_object.__name__, patched_value.__class__.__name__) self.proxy...
except e:
except Exception, e:
def renameProperty(obj, path): """ Rename qSEO_canonical property into PROPERTY_LINK for obj, which use SEO """ if obj.hasProperty('qSEO_canonical'): value = obj.getProperty('qSEO_canonical') level, msg = logging.INFO, "For %(url)s object 'qSEO_canonical' "\ "property renamed to '%(name)s'." try: ICanonicalLink(obj).c...
def _toFieldValue(self, value): return filter(None, self.splitter.split(value))
def _toFieldValue(self, input): if input == self._missing: return self.context._type() else: return self.context._type(filter(None, self.splitter.split(input)))
def _toFieldValue(self, value): return filter(None, self.splitter.split(value))
return u'\r\n'.join(list(value))
if value == self.context.missing_value or value == self.context._type(): return self._missing else: return u'\r\n'.join(list(value))
def _toFormValue(self, value): return u'\r\n'.join(list(value))
meta_keywords = ''
meta_keywords = []
def getMetaKeywords(self): """ See interface. """ request = self.context.REQUEST meta_keywords = '' filtered_keywords = [] portal_props = getToolByName(self.context, 'portal_properties') seo_props = getToolByName(portal_props, 'seo_properties', None) seo_context = queryMultiAdapter((self.context, request), name='seo_co...
meta_keywords = list(seo_context.meta_keywords())
meta_keywords = list(seo_context['meta_keywords'])
def getMetaKeywords(self): """ See interface. """ request = self.context.REQUEST meta_keywords = '' filtered_keywords = [] portal_props = getToolByName(self.context, 'portal_properties') seo_props = getToolByName(portal_props, 'seo_properties', None) seo_context = queryMultiAdapter((self.context, request), name='seo_co...
return ts.utranslate(None, _(u'Keywords list is empty!'), context=self.context)
return ts.utranslate(domain='quintagroup.seoptimizer', msgid=u'Keywords list is empty!', context=self.context)
def validateKeywords(self, text): """ see interface """ ts = getToolByName(self.context, 'translation_service') # extract keywords from text if text.lower().strip(): keywords = map(lambda x: x.strip(), text.lower().strip().split('\n')) else: return ts.utranslate(None, _(u'Keywords list is empty!'), context=self.context...
return _(u'Could not find lynx browser!')
return ts.utranslate(domain='quintagroup.seoptimizer', msgid=u'Could not find lynx browser!', context=self.context)
def validateKeywords(self, text): """ see interface """ ts = getToolByName(self.context, 'translation_service') # extract keywords from text if text.lower().strip(): keywords = map(lambda x: x.strip(), text.lower().strip().split('\n')) else: return ts.utranslate(None, _(u'Keywords list is empty!'), context=self.context...
msg = ts.utranslate(None, _('number_keywords', default=u'Number of keywords at page:\n${found}\n${missing}', mapping={'missing':'\n'.join(missing), 'found': '\n'.join(finding)}), context=self.context)
msg = ts.utranslate(domain='quintagroup.seoptimizer', msgid=u'number_keywords', default=u'Number of keywords at page:\n${found}\n${missing}', mapping={'missing':'\n'.join(missing), 'found': '\n'.join(finding)}, context=self.context)
def validateKeywords(self, text): """ see interface """ ts = getToolByName(self.context, 'translation_service') # extract keywords from text if text.lower().strip(): keywords = map(lambda x: x.strip(), text.lower().strip().split('\n')) else: return ts.utranslate(None, _(u'Keywords list is empty!'), context=self.context...
self.assertEqual(hasattr(properties.aq_base, PROPERTY_SHEET), False,
self.assert_(hasattr(properties.aq_base, PROPERTY_SHEET),
def test_propertysheet_uninstall(self): properties = getToolByName(self.portal, 'portal_properties') self.assertEqual(hasattr(properties.aq_base, PROPERTY_SHEET), False, "'%s' property sheet not uninstalled" % PROPERTY_SHEET)
from Products.CMFPlone.CatalogTool import registerIndexableAttribute
def addCanonicalPathCatalogColumn(self): from Products.CMFPlone.CatalogTool import registerIndexableAttribute
def canonical_path(obj, portal, **kwargs):
@indexer(IContentish) def canonical_path(obj, **kwargs):
def canonical_path(obj, portal, **kwargs): """Return canonical_path property for the object. """ cpath = queryAdapter(obj, interface=ISEOCanonicalPath) if cpath: return cpath.canonical_path() return None
registerIndexableAttribute('canonical_path', canonical_path)
provideAdapter(canonical_path, name='canonical_path')
def canonical_path(obj, portal, **kwargs): """Return canonical_path property for the object. """ cpath = queryAdapter(obj, interface=ISEOCanonicalPath) if cpath: return cpath.canonical_path() return None
msg = ts.utranslate(domain='quintagroup.seoptimizer', msgid=_(u'number_keywords'),
msg = ts.utranslate(domain='quintagroup.seoptimizer', msgid=_(u'number_keywords',
def validateKeywords(self, text): """ see interface """ ts = getToolByName(self.context, 'translation_service') # extract keywords from text if text.lower().strip(): keywords = map(lambda x: x.strip(), text.lower().strip().split('\n')) else: return ts.utranslate(domain='quintagroup.seoptimizer', msgid=_(u'Keywords list...
mapping={'missing':'\n'.join(missing), 'found': '\n'.join(finding)},
mapping={'missing':'\n'.join(missing), 'found': '\n'.join(finding)}),
def validateKeywords(self, text): """ see interface """ ts = getToolByName(self.context, 'translation_service') # extract keywords from text if text.lower().strip(): keywords = map(lambda x: x.strip(), text.lower().strip().split('\n')) else: return ts.utranslate(domain='quintagroup.seoptimizer', msgid=_(u'Keywords list...
default_custom_metatags = Text(
default_custom_metatags = List(
def SEORadioWidget(field, request): return TypedRadioWidgetNoValue(field, field.vocabulary, request)
metatags_order = Text(
metatags_order = List(
def SEORadioWidget(field, request): return TypedRadioWidgetNoValue(field, field.vocabulary, request)
additional_keywords = Text(
additional_keywords = List(
def SEORadioWidget(field, request): return TypedRadioWidgetNoValue(field, field.vocabulary, request)
def getDefaultCustomMetatags(self): return '\n'.join(self.context.getProperty('default_custom_metatags')) def setDefaultCustomMetatags(self, value): value = value and value.strip().split('\n') or [] self.context._updateProperty('default_custom_metatags', value) def getMetatagsOrder(self): return '\n'.join(self.contex...
def getDefaultCustomMetatags(self): return '\n'.join(self.context.getProperty('default_custom_metatags'))
metatags_order = property(getMetatagsOrder, setMetatagsOrder) default_custom_metatags = property(getDefaultCustomMetatags, setDefaultCustomMetatags) additional_keywords = property(getAdditionalKeywords, setAdditionalKeywords)
def setTypesSEOEnabled(self, value): value = [t for t in self.ttool.listContentTypes() if t in value] self.context._updateProperty('content_types_with_seoproperties', value)
metatags_order = ProxyFieldProperty(ISEOConfigletSchema['metatags_order']) default_custom_metatags = ProxyFieldProperty(ISEOConfigletSchema['default_custom_metatags']) additional_keywords = ProxyFieldProperty(ISEOConfigletSchema['additional_keywords'])
def setTypesSEOEnabled(self, value): value = [t for t in self.ttool.listContentTypes() if t in value] self.context._updateProperty('content_types_with_seoproperties', value)
self.assert_(self.sp.external_keywords_test)
self.assert_(self.seo.external_keywords_test)
def test_externalKeyword_On(self): self.publish(self.save_url + '&form.external_keywords_test=on', self.basic_auth) self.assert_(self.sp.external_keywords_test)
self.assertTrue(not self.sp.external_keywords_test)
self.assertTrue(not self.seo.external_keywords_test)
def test_externalKeyword_Off(self): self.publish(self.save_url + '&form.external_keywords_test=', self.basic_auth) self.assertTrue(not self.sp.external_keywords_test)
self.basic_auth = 'portal_manager:secret' uf = self.app.acl_users uf.userFolderAddUser('portal_manager', 'secret', ['Manager'], []) user = uf.getUserById('portal_manager') if not hasattr(user, 'aq_base'): user = user.__of__(uf) newSecurityManager(None, user)
self.basic_auth = ':'.join((portal_owner,default_password)) self.loginAsPortalOwner() my_doc = self.portal.invokeFactory('Document', id='my_doc') self.my_doc = self.portal['my_doc'] self.abs_path = "/%s" % self.my_doc.absolute_url(1)
def afterSetUp(self): self.basic_auth = 'portal_manager:secret' uf = self.app.acl_users uf.userFolderAddUser('portal_manager', 'secret', ['Manager'], []) user = uf.getUserById('portal_manager') if not hasattr(user, 'aq_base'): user = user.__of__(uf) newSecurityManager(None, user)
my_doc = self.portal.invokeFactory('Document', id='my_doc') my_doc = self.portal['my_doc']
form_data = {'seo_title': 'New Title', 'seo_title_override:int': 1, 'form.submitted:int': 1}
def test_modification_date(self): """ Modification date changing on SEO properties edit """ my_doc = self.portal.invokeFactory('Document', id='my_doc') my_doc = self.portal['my_doc']
md_before = my_doc.modification_date abs_path = "/%s" % my_doc.absolute_url(1) form_data = {'seo_title': 'New Title', 'seo_title_override:int': 1, 'form.submitted:int': 1} self.publish(path=abs_path+'/@@seo-context-properties', basic=self.basic_auth, request_method='POST', stdin=StringIO(urllib.urlencode(form_data))) ...
md_before = self.my_doc.modification_date self.publish(path=self.abs_path+'/@@seo-context-properties', basic=self.basic_auth, request_method='POST', stdin=StringIO(urllib.urlencode(form_data))) md_after = self.my_doc.modification_date
def test_modification_date(self): """ Modification date changing on SEO properties edit """ my_doc = self.portal.invokeFactory('Document', id='my_doc') my_doc = self.portal['my_doc']
return keywords
return tuple(keywords)
def meta_keywords( self ): """ Generate Meta Keywords from SEO properties (global and local) with Subject, depending on the options in configlet. """ prop_name = 'qSEO_keywords' accessor = 'Subject' context = aq_inner(self.context) keywords = Set([]) pprops = getToolByName(context, 'portal_properties') sheet = getattr(...
return keywords
return tuple(keywords)
def seo_keywords( self ): """ Generate SEO Keywords from SEO properties (global merde local). """ prop_name = 'qSEO_keywords' context = aq_inner(self.context) keywords = Set([]) pprops = getToolByName(context, 'portal_properties') sheet = getattr(pprops, 'seo_properties', None)
custom_meta_tags = self.gseo.default_custom_metatags.split('\n')
custom_meta_tags = self.gseo.default_custom_metatags
def seo_globalCustomMetaTags( self ): """ Returned seo custom metatags from default_custom_metatags property in seo_properties. """ result = [] context = aq_inner(self.context) if self.gseo: custom_meta_tags = self.gseo.default_custom_metatags.split('\n') for tag in custom_meta_tags: name_value = tag.split(SEPERATOR) i...
test_class=base.FunctionalTestCase,
test_class=FunctionalTestCaseNotInstalled, globs=globals(),
def test_suite(): return unittest.TestSuite([ # Demonstrate the main content types ztc.FunctionalDocFileSuite( 'browser.txt', package='quintagroup.seoptimizer.tests', test_class=base.FunctionalTestCase, optionflags=doctest.REPORT_ONLY_FIRST_FAILURE | doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS), ])
visible=True, icon_expr=None, link_target=None,
def testMigrationActions(self): # Test migrated actions from portal_types action to seoproperties tool self.seoprops_tool.content_types_with_seoproperties = ()
atct_tool = self.portal.atct_tool
atct_tool = self.portal.portal_atct
def testSEOCanonicalAdapter4OFSFolder(self): atct_tool = self.portal.atct_tool seocan = queryAdapter(self.mydoc, ISEOCanonicalPath) self.assertTrue(seocan is not None, True "seo canonical adapter not found for 'ATCT Tool'")
self.assertTrue(seocan is not None, True
self.assertTrue(seocan is not None,
def testSEOCanonicalAdapter4OFSFolder(self): atct_tool = self.portal.atct_tool seocan = queryAdapter(self.mydoc, ISEOCanonicalPath) self.assertTrue(seocan is not None, True "seo canonical adapter not found for 'ATCT Tool'")
self.basic_auth = 'portal_manager:secret' uf = self.app.acl_users uf.userFolderAddUser('portal_manager', 'secret', ['Manager'], []) user = uf.getUserById('portal_manager') if not hasattr(user, 'aq_base'): user = user.__of__(uf) newSecurityManager(None, user)
self.basic_auth = ':'.join((portal_owner,default_password)) self.loginAsPortalOwner()
def afterSetUp(self): self.basic_auth = 'portal_manager:secret' uf = self.app.acl_users uf.userFolderAddUser('portal_manager', 'secret', ['Manager'], []) user = uf.getUserById('portal_manager') if not hasattr(user, 'aq_base'): user = user.__of__(uf) newSecurityManager(None, user)
def addCanonicalPathCatalogColumn(self):
def addIndexerOld(self): def canonical_path(obj, **kwargs): """Return canonical_path property for the object. """ cpath = queryAdapter(obj, interface=ISEOCanonicalPath) if cpath: return cpath.canonical_path() return None registerIndexableAttribute("canonical_path", test_column)
def addCanonicalPathCatalogColumn(self):
catalog = getToolByName(self.portal, 'portal_catalog') catalog.addColumn(name='canonical_path')
def canonical_path(obj, **kwargs): """Return canonical_path property for the object. """ cpath = queryAdapter(obj, interface=ISEOCanonicalPath) if cpath: return cpath.canonical_path() return None
self.addCanonicalPathCatalogColumn()
if IS_NEW: self.addIndexerNew() else: self.addIndexerOld() catalog.addColumn('canonical_path')
def testCatalogUpdated(self): purl = getToolByName(self.portal, 'portal_url') catalog = getToolByName(self.portal, 'portal_catalog') self.addCanonicalPathCatalogColumn()
resp = urllib2.urlopen(self.context.absolute_url())
def validateKeywords(self): """ see interface """ text = self.request.get('text') ts = getToolByName(self.context, 'translation_service') transforms = getUtility(IPortalTransformsTool) portal = getToolByName(self.context, 'portal_url').getPortalObject() isExternal = queryAdapter(portal, ISEOConfigletSchema).external_ke...
if 'resp' in locals().keys(): resp.close()
resp.close()
def validateKeywords(self): """ see interface """ text = self.request.get('text') ts = getToolByName(self.context, 'translation_service') transforms = getUtility(IPortalTransformsTool) portal = getToolByName(self.context, 'portal_url').getPortalObject() isExternal = queryAdapter(portal, ISEOConfigletSchema).external_ke...
elog = getToolByName(self.context, "error_log") if elog:
try: elog = aq_acquire(self.context, '__error_log__', containment=1) except AttributeError: pass else:
def validateKeywords(self): """ see interface """ text = self.request.get('text') ts = getToolByName(self.context, 'translation_service') transforms = getUtility(IPortalTransformsTool) portal = getToolByName(self.context, 'portal_url').getPortalObject() isExternal = queryAdapter(portal, ISEOConfigletSchema).external_ke...
html = None
def validateKeywords(self): """ see interface """ text = self.request.get('text') ts = getToolByName(self.context, 'translation_service') transforms = getUtility(IPortalTransformsTool) portal = getToolByName(self.context, 'portal_url').getPortalObject() isExternal = queryAdapter(portal, ISEOConfigletSchema).external_ke...
sfx = error_url and ", details at %s." % error_url or "." result.append("Problem with page retrieval" + sfx)
result.append("Problem with page retrieval.") if error_url: result.append("Details at %s." % error_url)
def validateKeywords(self): """ see interface """ text = self.request.get('text') ts = getToolByName(self.context, 'translation_service') transforms = getUtility(IPortalTransformsTool) portal = getToolByName(self.context, 'portal_url').getPortalObject() isExternal = queryAdapter(portal, ISEOConfigletSchema).external_ke...
def test_bug_24_at_plone_org(self):
class TestBug24AtPloneOrg(FunctionalTestCase): def afterSetUp(self):
def test_bug_24_at_plone_org(self): member_id = 'test_member' editor_id = 'test_editor' test_pswd = 'pswd' uf = self.portal.acl_users uf.userFolderAddUser(member_id, test_pswd, ['Member'], []) uf.userFolderAddUser(editor_id, test_pswd, ['Member','Editor'], [])
member_auth = '%s:%s'%(member_id, test_pswd) editor_auth = '%s:%s'%(editor_id, test_pswd)
self.member_auth = '%s:%s'%(member_id, test_pswd) self.editor_auth = '%s:%s'%(editor_id, test_pswd)
def test_bug_24_at_plone_org(self): member_id = 'test_member' editor_id = 'test_editor' test_pswd = 'pswd' uf = self.portal.acl_users uf.userFolderAddUser(member_id, test_pswd, ['Member'], []) uf.userFolderAddUser(editor_id, test_pswd, ['Member','Editor'], [])
portal_url = '/'.join(self.portal.getPhysicalPath())
self.portal_url = '/'.join(self.portal.getPhysicalPath())
def test_bug_24_at_plone_org(self): member_id = 'test_member' editor_id = 'test_editor' test_pswd = 'pswd' uf = self.portal.acl_users uf.userFolderAddUser(member_id, test_pswd, ['Member'], []) uf.userFolderAddUser(editor_id, test_pswd, ['Member','Editor'], [])
resp = self.publish(path=portal_url, basic=member_auth)
def test_not_break(self): """Default portal page should not breaks for any user""" resp = self.publish(path=self.portal_url) self.assertEqual(resp.getStatus(), 200) resp = self.publish(path=self.portal_url, basic=self.member_auth) self.assertEqual(resp.getStatus(), 200) resp = self.publish(path=self.portal_url, basi...
def test_bug_24_at_plone_org(self): member_id = 'test_member' editor_id = 'test_editor' test_pswd = 'pswd' uf = self.portal.acl_users uf.userFolderAddUser(member_id, test_pswd, ['Member'], []) uf.userFolderAddUser(editor_id, test_pswd, ['Member','Editor'], [])
resp = self.publish(path=portal_url, basic=editor_auth) self.assertEqual(resp.getStatus(), 200)
def test_tab_visibility(self): """Only Editor can view seo tab""" rexp = re.compile('<a\s+[^>]*' \ 'href="[a-zA-Z0-9\:\/_-]*/@@seo-context-properties"[^>]*>'\ '\s*SEO Properties\s*</a>', re.I|re.S) res = self.publish(path=self.portal_url).getBody() self.assertEqual(rexp.search(res), None) res = self.publish(path=self...
def test_bug_24_at_plone_org(self): member_id = 'test_member' editor_id = 'test_editor' test_pswd = 'pswd' uf = self.portal.acl_users uf.userFolderAddUser(member_id, test_pswd, ['Member'], []) uf.userFolderAddUser(editor_id, test_pswd, ['Member','Editor'], [])
def test_seo_context_properties_perms(self): self.portal.portal_workflow.doActionFor(self.my_doc, 'publish') resp = self.publish(path=self.mydoc_path+'/@@seo-context-properties') self.assertNotEqual(resp.getStatus(), 200)
def test_tab_access(self): """Only Editor can access 'SEO Properties' tab""" test_url = self.portal_url + '/front-page/@@seo-context-properties' headers = self.publish(path=test_url).headers self.assertEqual( headers.get('bobo-exception-type',""), 'Unauthorized', "No 'Unauthorized' exception rised for Anonymous on '@@...
def test_seo_context_properties_perms(self): # Anonymous are not allowed to access to @@seo-context-properties self.portal.portal_workflow.doActionFor(self.my_doc, 'publish') resp = self.publish(path=self.mydoc_path+'/@@seo-context-properties') self.assertNotEqual(resp.getStatus(), 200)
setup_tool.setBaselineContext('profile-%s:uninstall'%PROJECT_NAME)
def install(portal, reinstall=False): setup_tool = getToolByName(portal, 'portal_setup') setup_tool.setBaselineContext('profile-%s:uninstall'%PROJECT_NAME) if reinstall: setup_tool.setBaselineContext('profile-%s:reinstall'%PROJECT_NAME) setup_tool.runAllImportStepsFromProfile('profile-%s:reinstall'%PROJECT_NAME) return...
setup_tool.setBaselineContext('profile-%s:reinstall'%PROJECT_NAME) setup_tool.runAllImportStepsFromProfile('profile-%s:reinstall'%PROJECT_NAME) return "Ran reinstall steps."
setup_tool.runAllImportStepsFromProfile(REINSTALL) return "Ran all reinstall steps."
def install(portal, reinstall=False): setup_tool = getToolByName(portal, 'portal_setup') setup_tool.setBaselineContext('profile-%s:uninstall'%PROJECT_NAME) if reinstall: setup_tool.setBaselineContext('profile-%s:reinstall'%PROJECT_NAME) setup_tool.runAllImportStepsFromProfile('profile-%s:reinstall'%PROJECT_NAME) return...
setup_tool.setBaselineContext('profile-%s:uninstall'%PROJECT_NAME) setup_tool.runAllImportStepsFromProfile('profile-%s:default'%PROJECT_NAME)
setup_tool.runAllImportStepsFromProfile(INSTALL)
def install(portal, reinstall=False): setup_tool = getToolByName(portal, 'portal_setup') setup_tool.setBaselineContext('profile-%s:uninstall'%PROJECT_NAME) if reinstall: setup_tool.setBaselineContext('profile-%s:reinstall'%PROJECT_NAME) setup_tool.runAllImportStepsFromProfile('profile-%s:reinstall'%PROJECT_NAME) return...
if re.compile(r'\b%s\b' % meta_keyword.lower(), re.I).search(text):
if re.compile(u'\\b%s\\b' % meta_keyword.decode('utf8').lower(), re.I|re.U).search(text):
def getMetaKeywords(self): """ See interface. """ request = self.context.REQUEST meta_keywords = '' filtered_keywords = [] portal_props = getToolByName(self.context, 'portal_properties') seo_props = getToolByName(portal_props, 'seo_properties', None) seo_context = queryMultiAdapter((self.context, request), name='seo_co...
self.chunk_incref(hash) return hash, size
self.chunk_incref(id) return id, size
def add_chunk(self, data): sum = checksum(data) data = zlib.compress(data) #print 'chunk %d: %d' % (len(data), sum) id = struct.pack('I', sum) + hashlib.sha1(data).digest() if not self.seen_chunk(id): size = len(data) self.store.put(NS_CHUNKS, id, data) else: size = 0 #print 'seen chunk', hash.encode('hex') self.chunk_...
def chunk_incref(self, hash): sum = struct.unpack('I', hash[:4])[0] self.chunkmap.setdefault(hash, 0)
def chunk_incref(self, id): sum = struct.unpack('I', id[:4])[0] self.chunkmap.setdefault(id, 0)
def chunk_incref(self, hash): sum = struct.unpack('I', hash[:4])[0] self.chunkmap.setdefault(hash, 0) self.summap.setdefault(sum, 0) self.chunkmap[hash] += 1 self.summap[sum] += 1
self.chunkmap[hash] += 1
self.chunkmap[id] += 1
def chunk_incref(self, hash): sum = struct.unpack('I', hash[:4])[0] self.chunkmap.setdefault(hash, 0) self.summap.setdefault(sum, 0) self.chunkmap[hash] += 1 self.summap[sum] += 1
def chunk_decref(self, hash): self.summap[struct.unpack('I', hash[:4])[0]] -= 1 count = self.chunkmap.get(hash, 0) - 1
def chunk_decref(self, id): sum = struct.unpack('I', id[:4])[0] sumcount = self.summap[sum] - 1 count = self.chunkmap[id] - 1 assert sumcount >= 0
def chunk_decref(self, hash): self.summap[struct.unpack('I', hash[:4])[0]] -= 1 count = self.chunkmap.get(hash, 0) - 1 assert count >= 0 self.chunkmap[hash] = count if not count: print 'deleting chunk: ', hash.encode('hex') self.store.delete(NS_CHUNKS, hash) return count
self.chunkmap[hash] = count if not count: print 'deleting chunk: ', hash.encode('hex') self.store.delete(NS_CHUNKS, hash)
if sumcount: self.summap[sum] = sumcount else: del self.summap[sum] if count: self.chunkmap[id] = count else: del self.chunkmap[id] print 'deleting chunk: ', id.encode('hex') self.store.delete(NS_CHUNKS, id)
def chunk_decref(self, hash): self.summap[struct.unpack('I', hash[:4])[0]] -= 1 count = self.chunkmap.get(hash, 0) - 1 assert count >= 0 self.chunkmap[hash] = count if not count: print 'deleting chunk: ', hash.encode('hex') self.store.delete(NS_CHUNKS, hash) return count
return {'type': 'FILE', 'path': path, 'size': size, 'chunks': chunks}
return {'type': 'FILE', 'path': path, 'size': origsize, 'chunks': chunks}
def process_file(self, path, cache): print 'Adding: %s...' % path, sys.stdout.flush() with open(path, 'rb') as fd: origsize = 0 compsize = 0 chunks = [] for chunk in chunkify(fd, CHUNKSIZE, self.cache.summap): origsize += len(chunk) id, size = cache.add_chunk(chunk) compsize += size chunks.append(id) path = path.lstrip...
key = self.decrypt_key(data[41:297], self.rsa_create)
key = self._decrypt_key(data[41:297], self.rsa_create)
def decrypt(self, data): """Decrypt `data` previously encrypted by `encrypt_create` or `encrypt_read` """ type = data[0] hash = data[1:33] if self.id_hash(data[33:]) != hash: raise IntegrityError('Encryption integrity error') nonce = bytes_to_long(data[33:41]) counter = Counter.new(64, prefix='\0' * 8, initial_value=no...
logging.info('%s => %s', path, item['source'])
def extract(self, dest=None): dest = dest or os.getcwdu() for item in self.items: assert item['path'][0] not in ('/', '\\', ':') path = os.path.join(dest, item['path'].decode('utf-8')) if item['type'] == 'DIRECTORY': logging.info(path) if not os.path.exists(path): os.makedirs(path) elif item['type'] == 'SYMLINK': loggi...
os.symlink(item['source'], path)
source = item['source'] logging.info('%s -> %s', path, source) if os.path.exists(path): os.unlink(path) os.symlink(source, path) self.restore_stat(path, item, call_utime=False) elif item['type'] == 'HARDLINK': if not os.path.exists(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) source = os.path.join(dest, i...
def extract(self, dest=None): dest = dest or os.getcwdu() for item in self.items: assert item['path'][0] not in ('/', '\\', ':') path = os.path.join(dest, item['path'].decode('utf-8')) if item['type'] == 'DIRECTORY': logging.info(path) if not os.path.exists(path): os.makedirs(path) elif item['type'] == 'SYMLINK': loggi...
os.chmod(path, item['mode']) uid = user2uid(item['user']) or item['uid'] gid = group2gid(item['group']) or item['gid'] try: os.chown(path, uid, gid) except OSError: pass os.utime(path, (item['ctime'], item['mtime']))
self.restore_stat(path, item) else: raise Exception('Unknown archive item type %r' % item['type']) if dir_stat_queue and not path.startswith(dir_stat_queue[-1][0]): self.restore_stat(*dir_stat_queue.pop()) def restore_stat(self, path, item, call_utime=True): os.lchmod(path, item['mode']) uid = user2uid(item['user']) o...
def extract(self, dest=None): dest = dest or os.getcwdu() for item in self.items: assert item['path'][0] not in ('/', '\\', ':') path = os.path.join(dest, item['path'].decode('utf-8')) if item['type'] == 'DIRECTORY': logging.info(path) if not os.path.exists(path): os.makedirs(path) elif item['type'] == 'SYMLINK': loggi...
else: yield path, st
def _walk(self, path): st = os.lstat(path) if stat.S_ISDIR(st.st_mode): for f in os.listdir(path): for x in self._walk(os.path.join(path, f)): yield x else: yield path, st
self.process_link(path, st)
self.process_symlink(path, st)
def create(self, name, paths, cache): if name in cache.archives: raise NameError('Archive already exists') for path in paths: for path, st in self._walk(unicode(path)): if stat.S_ISDIR(st.st_mode): self.process_dir(path, st) elif stat.S_ISLNK(st.st_mode): self.process_link(path, st) elif stat.S_ISREG(st.st_mode): self....
self.items.append({'type': 'DIRECTORY', 'path': path}) def process_link(self, path, st):
self.items.append({ 'type': 'DIRECTORY', 'path': path, 'mode': st.st_mode, 'uid': st.st_uid, 'user': uid2user(st.st_uid), 'gid': st.st_gid, 'group': gid2group(st.st_gid), 'ctime': st.st_ctime, 'mtime': st.st_mtime, }) def process_symlink(self, path, st):
def process_dir(self, path, st): path = path.lstrip('/\\:') logging.info(path) self.items.append({'type': 'DIRECTORY', 'path': path})
logging.info('%s => %s', path, source) self.items.append({'type': 'SYMLINK', 'path': path, 'source': source})
logging.info('%s -> %s', path, source) self.items.append({ 'type': 'SYMLINK', 'path': path, 'source': source, 'mode': st.st_mode, 'uid': st.st_uid, 'user': uid2user(st.st_uid), 'gid': st.st_gid, 'group': gid2group(st.st_gid), 'ctime': st.st_ctime, 'mtime': st.st_mtime, })
def process_link(self, path, st): source = os.readlink(path) path = path.lstrip('/\\:') logging.info('%s => %s', path, source) self.items.append({'type': 'SYMLINK', 'path': path, 'source': source})
path = path.lstrip('/\\:') logging.info(path)
logging.info(safe_path)
def process_file(self, path, st): try: fd = open(path, 'rb') except IOError, e: logging.error(e) return with fd: path = path.lstrip('/\\:') logging.info(path) chunks = [] size = 0 for chunk in chunkify(fd, CHUNK_SIZE, 30): chunks.append(self.process_chunk(chunk)) size += len(chunk) self.items.append({ 'type': 'FILE', '...
'type': 'FILE', 'path': path, 'chunks': chunks, 'size': size,
'type': 'FILE', 'path': safe_path, 'chunks': chunks, 'size': size,
def process_file(self, path, st): try: fd = open(path, 'rb') except IOError, e: logging.error(e) return with fd: path = path.lstrip('/\\:') logging.info(path) chunks = [] size = 0 for chunk in chunkify(fd, CHUNK_SIZE, 30): chunks.append(self.process_chunk(chunk)) size += len(chunk) self.items.append({ 'type': 'FILE', '...
self.print_verbose(item['path'])
self.print_verbose(item['path'].decode('utf-8'))
def do_extract(self, args): store = self.open_store(args.archive) keychain = Keychain(args.keychain) archive = Archive(store, keychain, args.archive.archive) archive.get_items() dirs = [] for item in archive.items: if exclude_path(item['path'], args.patterns): continue self.print_verbose(item['path']) archive.extract_i...
return t.strftime('%d %d %Y')
return t.strftime('%b %d %Y')
def format_time(t): """Format datetime suitable for fixed length list output """ if (datetime.now() - t).days < 365: return t.strftime('%b %d %H:%M') else: return t.strftime('%d %d %Y')
cache.chunk_decref(c)
id = self.chunk_idx[c] cache.chunk_decref(id)
def delete(self, cache): self.store.delete(NS_ARCHIVES, self.name) for item in self.items: if item['type'] == 'FILE': for c in item['chunks']: cache.chunk_decref(c) self.store.commit() cache.archives.remove(self.name) cache.save()
self.summap.setdefault(sum, 1)
self.summap[sum] = self.summap.get(sum, 0) + 1
def init_chunk(self, id, sum, csize, osize): self.chunkmap[id] = (1, sum, osize, csize) self.summap.setdefault(sum, 1) return id, sum, csize, osize
self.summap = {}
def init(self): """Initializes cache by fetching and reading all archive indicies """ self.summap = {} self.chunkmap = {} self.archives = [] self.tid = self.store.tid if self.store.tid == 0: return print 'Recreating cache...' for id in self.store.list(NS_ARCHIVES): archive = cPickle.loads(zlib.decompress(self.store.get...
for id in self.store.list(NS_ARCHIVES):
for id in list(self.store.list(NS_ARCHIVES)):
def init(self): """Initializes cache by fetching and reading all archive indicies """ self.summap = {} self.chunkmap = {} self.archives = [] self.tid = self.store.tid if self.store.tid == 0: return print 'Recreating cache...' for id in self.store.list(NS_ARCHIVES): archive = cPickle.loads(zlib.decompress(self.store.get...
for id, sum, csize, osize in archive['chunks']:
for id, csize, osize in archive['chunks']:
def init(self): """Initializes cache by fetching and reading all archive indicies """ self.summap = {} self.chunkmap = {} self.archives = [] self.tid = self.store.tid if self.store.tid == 0: return print 'Recreating cache...' for id in self.store.list(NS_ARCHIVES): archive = cPickle.loads(zlib.decompress(self.store.get...
'description': '"Fertile Legacy", a photo exhibition celebrating the power and beauty of native Andean potatoes opened on August 10th in Lima, Peru. The exhibition features a sample of the exquisite variety of potatoes available in Peru, Bolivia, and Ecuador, and presents a graphic story of the tuber’s journey from fie...
'description': 'Fertile Legacy, a photo exhibition celebrating the power and beauty of native Andean potatoes opened on August 10th in Lima, Peru. The exhibition features a sample of the exquisite variety of potatoes available in Peru, Bolivia, and Ecuador, and presents a graphic story of the tubers journey from field ...
def createFolderStructure(portal): """Define which objects we want to create in the site. """ importance_children = [ { 'id': 'statistics', 'title': 'Statistics', 'description': '', 'type': 'Folder', 'layout': 'folder_listing', }, { 'id': 'nutritional-facts', 'title': 'Nutritional facts', 'description': '', 'type':...
return util.ulocalized_time(time, None, self.context, domain='plonelocales')
return util.ulocalized_time(time, context=self.context, domain='plonelocales')
def created( self ): time = self.properties.get( keys.checkout_time, DateTime() ) util = getToolByName(self.context, 'translation_service') return util.ulocalized_time(time, None, self.context, domain='plonelocales')
loader = JsonzLoader(host,port) input_file = open(path,'rb')
loader = JsonzLoader(host,int(port)) input_file = open(input_file_path,'rb')
def load_from_file(self, uuid, path): jsonz_file = gzip.open(path, 'rb') json_string = jsonz_file.read() jsonz_file.close() self.hbase_connection.create_ooid_from_jsonz(uuid,json_string)
module,filename,version,debugFilename,debugId = moduleData[:5]
try: module,filename,version,debugFilename,debugId = moduleData[:5] except ValueError: return None
def getVersionIfFlashModule(self,moduleData): """If (we recognize this module as Flash and figure out a version): Returns version; else (None or '')""" module,filename,version,debugFilename,debugId = moduleData[:5] m = ProcessorWithExternalBreakpad.flashRE.match(filename) if m: if not version: version = m.groups()[0] i...
msg = MIMEText.MIMEText(personalized_body.encode('utf-7'), _charset='utf-7')
msg = MIMETextClass(personalized_body.encode('utf-7'), _charset='utf-7')
def send_all_emails(self, contacts, subject, body): """ returns a list of email addresses which were successfully contacted """ contacted_emails = [] # this can raise SMTPHeloError, SMTPAuthenticationError, SMTPException # Error handeling... This Service Call will either work or fail. Failure comes from # SMTP, Databas...
date_processed = soc_dtutil.datetimeFromISOdateString(jsonDocument["submitted_timestamp"])
date_processed = sdt.datetimeFromISOdateString(jsonDocument["submitted_timestamp"])
def processJob (self, jobTuple): """ This function is run only by a worker thread. Given a job, fetch a thread local database connection and the json document. Use these to create the record in the 'reports' table, then start the analysis of the dump file.
threadLocalDatabaseConnection.commit()
def processJob (self, jobTuple): """ This function is run only by a worker thread. Given a job, fetch a thread local database connection and the json document. Use these to create the record in the 'reports' table, then start the analysis of the dump file.
logger.info("%s - abandoning job with rollback: %s, %s", threadName, jobId, jobUuid) threadLocalDatabaseConnection.rollback()
try: logger.info("%s - abandoning job with rollback: %s, %s", threadName, jobId, jobUuid) threadLocalDatabaseConnection.rollback() threadLocalDatabaseConnection.close() except: pass
def processJob (self, jobTuple): """ This function is run only by a worker thread. Given a job, fetch a thread local database connection and the json document. Use these to create the record in the 'reports' table, then start the analysis of the dump file.
threadLocalDatabaseConnection.rollback()
def processJob (self, jobTuple): """ This function is run only by a worker thread. Given a job, fetch a thread local database connection and the json document. Use these to create the record in the 'reports' table, then start the analysis of the dump file.
version = Processor.getJsonOrWarn(jsonDocument,'Version', processorErrorMessages,None,16)
version = Processor.getJsonOrWarn(jsonDocument,'Version', processorErrorMessages,None)
def insertReportIntoDatabase(self, threadLocalCursor, uuid, jsonDocument, jobPathname, date_processed, processorErrorMessages): """ This function is run only by a worker thread. Create the record for the current job in the 'reports' table input parameters: threadLocalCursor: a database cursor for exclusive use by the c...
try: threadLocalCursor.execute("delete from reports where uuid = '%s' and date_processed = timestamp without time zone '%s'" % (uuid, date_processed)) processorErrorMessages.append("INFO: This record is a replacement for a previous record with the same uuid") self.reportsTable.insert(threadLocalCursor, newReportRecordA...
threadLocalCursor.execute("delete from reports where uuid = '%s' and date_processed = timestamp without time zone '%s'" % (uuid, date_processed)) processorErrorMessages.append("INFO: This record is a replacement for a previous record with the same uuid") self.reportsTable.insert(threadLocalCursor, newReportRecordAsTupl...
def insertReportIntoDatabase(self, threadLocalCursor, uuid, jsonDocument, jobPathname, date_processed, processorErrorMessages): """ This function is run only by a worker thread. Create the record for the current job in the 'reports' table input parameters: threadLocalCursor: a database cursor for exclusive use by the c...
self.extensionsTable.insert(threadLocalCursor, (reportId, date_processed, i, x[0][:100], x[1]), self.databaseConnectionPool.connectToDatabase, date_processed=date_processed)
self.extensionsTable.insert(threadLocalCursor, (reportId, date_processed, i, x[0][:100], x[1][:16]), self.databaseConnectionPool.connectToDatabase, date_processed=date_processed)
def insertAdddonsIntoDatabase (self, threadLocalCursor, reportId, jsonDocument, date_processed, processorErrorMessages): jsonAddonString = Processor.getJsonOrWarn(jsonDocument, 'Add-ons', processorErrorMessages, "") if not jsonAddonString: return [] listOfAddonsForInput = [x.split(":") for x in jsonAddonString.split(',...
simplejson.dump(dumpObject,fh)
simplejson.dump(dumpObject, fh, ensure_ascii=False)
def putDumpToFile(self,ooid,dumpObject, timestamp=None): """ Given a ooid and an dumpObject, create the appropriate dump file and fill it with object's data """ fh = self.newEntry(ooid, timestamp) try: simplejson.dump(dumpObject,fh) finally: fh.close()
if legacy_processing > 0: counterIncrementList.append("counters:submitted_crash_reports_legacy_throttle_%d" % legacy_processing)
counterIncrementList.append("counters:submitted_crash_reports_legacy_throttle_%d" % legacy_processing)
def update_metrics_counters_for_submit(self, submitted_timestamp, legacy_processing, process_type,is_hang, add_to_unprocessed_queue): """ Increments a series of counters in the 'metrics' table related to CR submission """ timeLevels = [ submitted_timestamp[:16], # minute yyyy-mm-ddTHH:MM submitted_timestamp[:13], # hou...
if legacy_processing > 0:
if legacy_processing == 0:
def update_metrics_counters_for_submit(self, submitted_timestamp, legacy_processing, process_type,is_hang, add_to_unprocessed_queue): """ Increments a series of counters in the 'metrics' table related to CR submission """ timeLevels = [ submitted_timestamp[:16], # minute yyyy-mm-ddTHH:MM submitted_timestamp[:13], # hou...
return td.days * 24 * 60 * 60 + td.seconds + td.microseconds
return td.days * 24 * 60 * 60 + td.seconds \ + (float(td.microseconds) / 1000000.0)
def timeDeltaToSecondsReal(td): return td.days * 24 * 60 * 60 + td.seconds + td.microseconds
"Expected int for totalNumberOfCrashes, actual type is %s" % type(databaseParameters["totalNumberOfCrashes"])
"Expected long for totalNumberOfCrashes, actual type is %s" % type(databaseParameters["totalNumberOfCrashes"])
def getListOfTopCrashersBySignature(aCursor, databaseParameters, totalNumberOfCrashesForPeriodFunc=totalNumberOfCrashesForPeriod): """ """ databaseParameters["totalNumberOfCrashes"] = totalNumberOfCrashesForPeriodFunc(aCursor, databaseParameters) if databaseParameters["totalNumberOfCrashes"] == None: return [] assert...
"Expected int for startDate, actual type is %s" % type(databaseParameters["startDate"])
"Expected datetime.datetime for startDate, actual type is %s" % type(databaseParameters["startDate"])
def getListOfTopCrashersBySignature(aCursor, databaseParameters, totalNumberOfCrashesForPeriodFunc=totalNumberOfCrashesForPeriod): """ """ databaseParameters["totalNumberOfCrashes"] = totalNumberOfCrashesForPeriodFunc(aCursor, databaseParameters) if databaseParameters["totalNumberOfCrashes"] == None: return [] assert...
"Expected int for endDate, actual type is %s" % type(databaseParameters["endDate"])
"Expected datetime.datetime for endDate, actual type is %s" % type(databaseParameters["endDate"])
def getListOfTopCrashersBySignature(aCursor, databaseParameters, totalNumberOfCrashesForPeriodFunc=totalNumberOfCrashesForPeriod): """ """ databaseParameters["totalNumberOfCrashes"] = totalNumberOfCrashesForPeriodFunc(aCursor, databaseParameters) if databaseParameters["totalNumberOfCrashes"] == None: return [] assert...
assert type(databaseParameters["totalNumberOfCrashes"]) is int assert type(databaseParameters["startDate"]) is datetime.datetime assert type(databaseParameters["endDate"]) is datetime.datetime assert type(databaseParameters["productdims_id"]) is int assert type(databaseParameters["listSize"]) is int
assert type(databaseParameters["totalNumberOfCrashes"]) is long, type(databaseParameters["totalNumberOfCrashes"]) assert type(databaseParameters["startDate"]) is datetime.datetime, type(databaseParameters["startDate"]) assert type(databaseParameters["endDate"]) is datetime.datetime, type(databaseParameters["endDate"]) ...
def getListOfTopCrashersBySignature(aCursor, databaseParameters, totalNumberOfCrashesForPeriodFunc=totalNumberOfCrashesForPeriod): """ """ databaseParameters["totalNumberOfCrashes"] = totalNumberOfCrashesForPeriodFunc(aCursor, databaseParameters) if databaseParameters["totalNumberOfCrashes"] == None: return [] assert...