input stringlengths 11 7.65k | target stringlengths 22 8.26k |
|---|---|
def __init__(self,params,parent):
self.params=params
self.parent=parent | def add_user():
form = AddUserForm()
if form.validate_on_submit():
form.save()
flash(_("User added."), "success")
return redirect(url_for("management.users"))
return render_template("management/user_form.html", form=form,
title=_("Add User")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __getitem__(self, key):
return self._states[key or DEFAULT_DB_ALIAS] |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def banned_users():
page = request.args.get("page", 1, type=int)
search_form = UserSearchForm()
users = User.query.filter(
Group.banned == True,
Group.id == User.primary_group_id
).paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
if search_form.validate():
users = search_form.get_results().\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template("management/banned_users.html", users=users,
search_form=search_form)
return render_template("management/banned_users.html", users=users,
search_form=search_form) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def is_dirty(self, dbs):
return any(self[db].is_dirty() for db in dbs) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def ban_user(user_id=None):
if not Permission(CanBanUser, identity=current_user):
flash(_("You do not have the permissions to ban this user."), "danger")
return redirect(url_for("management.overview"))
# ajax request
if request.is_xhr:
ids = request.get_json()["ids"]
data = []
users = User.query.filter(User.id.in_(ids)).all()
for user in users:
# don't let a user ban himself and do not allow a moderator to ban
# a admin user
if (
current_user.id == user.id or
Permission(IsAdmin, identity=user) and
Permission(Not(IsAdmin), current_user)
):
continue
elif user.ban():
data.append({
"id": user.id,
"type": "ban",
"reverse": "unban",
"reverse_name": _("Unban"),
"reverse_url": url_for("management.unban_user",
user_id=user.id)
})
return jsonify(
message="{} users banned.".format(len(data)),
category="success",
data=data,
status=200
)
user = User.query.filter_by(id=user_id).first_or_404()
# Do not allow moderators to ban admins
if Permission(IsAdmin, identity=user) and \
Permission(Not(IsAdmin), identity=current_user):
flash(_("A moderator cannot ban an admin user."), "danger")
return redirect(url_for("management.overview"))
if not current_user.id == user.id and user.ban():
flash(_("User is now banned."), "success")
else:
flash(_("Could not ban user."), "danger")
return redirect(url_for("management.banned_users")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def queue_when_in_transaction(call):
if transaction_states[call.using]:
transaction_states[call.using].push((call, (), {}))
else:
return call() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def unban_user(user_id=None):
if not Permission(CanBanUser, identity=current_user):
flash(_("You do not have the permissions to unban this user."),
"danger")
return redirect(url_for("management.overview"))
# ajax request
if request.is_xhr:
ids = request.get_json()["ids"]
data = []
for user in User.query.filter(User.id.in_(ids)).all():
if user.unban():
data.append({
"id": user.id,
"type": "unban",
"reverse": "ban",
"reverse_name": _("Ban"),
"reverse_url": url_for("management.ban_user",
user_id=user.id)
})
return jsonify(
message="{} users unbanned.".format(len(data)),
category="success",
data=data,
status=200
)
user = User.query.filter_by(id=user_id).first_or_404()
if user.unban():
flash(_("User is now unbanned."), "success")
else:
flash(_("Could not unban user."), "danger")
return redirect(url_for("management.banned_users")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __enter__(self):
entering = not transaction_states[self.using]
transaction_states[self.using].begin()
self._no_monkey.__enter__(self)
if entering:
on_commit(transaction_states[self.using].commit, self.using) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def reports():
page = request.args.get("page", 1, type=int)
reports = Report.query.\
order_by(Report.id.asc()).\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template("management/reports.html", reports=reports) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __exit__(self, exc_type, exc_value, traceback):
connection = get_connection(self.using)
try:
self._no_monkey.__exit__(self, exc_type, exc_value, traceback)
except DatabaseError:
transaction_states[self.using].rollback()
else:
if not connection.closed_in_transaction and exc_type is None and \
not connection.needs_rollback:
if transaction_states[self.using]:
transaction_states[self.using].commit()
else:
transaction_states[self.using].rollback() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def unread_reports():
page = request.args.get("page", 1, type=int)
reports = Report.query.\
filter(Report.zapped == None).\
order_by(Report.id.desc()).\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template("management/unread_reports.html", reports=reports) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def callproc(self, procname, params=None):
result = self._no_monkey.callproc(self, procname, params)
if transaction_states[self.db.alias]:
transaction_states[self.db.alias].mark_dirty()
return result |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def report_markread(report_id=None):
# AJAX request
if request.is_xhr:
ids = request.get_json()["ids"]
data = []
for report in Report.query.filter(Report.id.in_(ids)).all():
report.zapped_by = current_user.id
report.zapped = time_utcnow()
report.save()
data.append({
"id": report.id,
"type": "read",
"reverse": False,
"reverse_name": None,
"reverse_url": None
})
return jsonify(
message="{} reports marked as read.".format(len(data)),
category="success",
data=data,
status=200
)
# mark single report as read
if report_id:
report = Report.query.filter_by(id=report_id).first_or_404()
if report.zapped:
flash(_("Report %(id)s is already marked as read.", id=report.id),
"success")
return redirect(url_for("management.reports"))
report.zapped_by = current_user.id
report.zapped = time_utcnow()
report.save()
flash(_("Report %(id)s marked as read.", id=report.id), "success")
return redirect(url_for("management.reports"))
# mark all as read
reports = Report.query.filter(Report.zapped == None).all()
report_list = []
for report in reports:
report.zapped_by = current_user.id
report.zapped = time_utcnow()
report_list.append(report)
db.session.add_all(report_list)
db.session.commit()
flash(_("All reports were marked as read."), "success")
return redirect(url_for("management.reports")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def execute(self, sql, params=None):
result = self._no_monkey.execute(self, sql, params)
if transaction_states[self.db.alias] and is_sql_dirty(sql):
transaction_states[self.db.alias].mark_dirty()
return result |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def groups():
page = request.args.get("page", 1, type=int)
groups = Group.query.\
order_by(Group.id.asc()).\
paginate(page, flaskbb_config['USERS_PER_PAGE'], False)
return render_template("management/groups.html", groups=groups) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def executemany(self, sql, param_list):
result = self._no_monkey.executemany(self, sql, param_list)
if transaction_states[self.db.alias] and is_sql_dirty(sql):
transaction_states[self.db.alias].mark_dirty()
return result |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def edit_group(group_id):
group = Group.query.filter_by(id=group_id).first_or_404()
form = EditGroupForm(group)
if form.validate_on_submit():
form.populate_obj(group)
group.save()
if group.guest:
Guest.invalidate_cache()
flash(_("Group updated."), "success")
return redirect(url_for("management.groups", group_id=group.id))
return render_template("management/group_form.html", form=form,
title=_("Edit Group")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def is_sql_dirty(sql):
# This should not happen as using bytes in Python 3 is against db protocol,
# but some people will pass it anyway
if isinstance(sql, bytes):
sql = sql.decode()
# NOTE: not using regex here for speed
sql = sql.lower()
for action in ('update', 'insert', 'delete'):
p = sql.find(action)
if p == -1:
continue
start, end = p - 1, p + len(action)
if (start < 0 or sql[start] not in CHARS) and (end >= len(sql) or sql[end] not in CHARS):
return True
else:
return False |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def delete_group(group_id=None):
if request.is_xhr:
ids = request.get_json()["ids"]
if not (set(ids) & set(["1", "2", "3", "4", "5"])):
data = []
for group in Group.query.filter(Group.id.in_(ids)).all():
group.delete()
data.append({
"id": group.id,
"type": "delete",
"reverse": False,
"reverse_name": None,
"reverse_url": None
})
return jsonify(
message="{} groups deleted.".format(len(data)),
category="success",
data=data,
status=200
)
return jsonify(
message=_("You cannot delete one of the standard groups."),
category="danger",
data=None,
status=404
)
if group_id is not None:
if group_id <= 5: # there are 5 standard groups
flash(_("You cannot delete the standard groups. "
"Try renaming it instead.", "danger"))
return redirect(url_for("management.groups"))
group = Group.query.filter_by(id=group_id).first_or_404()
group.delete()
flash(_("Group deleted."), "success")
return redirect(url_for("management.groups"))
flash(_("No group chosen."), "danger")
return redirect(url_for("management.groups")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def add_group():
form = AddGroupForm()
if form.validate_on_submit():
form.save()
flash(_("Group added."), "success")
return redirect(url_for("management.groups"))
return render_template("management/group_form.html", form=form,
title=_("Add Group")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def forums():
categories = Category.query.order_by(Category.position.asc()).all()
return render_template("management/forums.html", categories=categories) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def edit_forum(forum_id):
forum = Forum.query.filter_by(id=forum_id).first_or_404()
form = EditForumForm(forum)
if form.validate_on_submit():
form.save()
flash(_("Forum updated."), "success")
return redirect(url_for("management.edit_forum", forum_id=forum.id))
else:
if forum.moderators:
form.moderators.data = ",".join([
user.username for user in forum.moderators
])
else:
form.moderators.data = None
return render_template("management/forum_form.html", form=form,
title=_("Edit Forum")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def delete_forum(forum_id):
forum = Forum.query.filter_by(id=forum_id).first_or_404()
involved_users = User.query.filter(Topic.forum_id == forum.id,
Post.user_id == User.id).all()
forum.delete(involved_users)
flash(_("Forum deleted."), "success")
return redirect(url_for("management.forums")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def add_forum(category_id=None):
form = AddForumForm()
if form.validate_on_submit():
form.save()
flash(_("Forum added."), "success")
return redirect(url_for("management.forums"))
else:
form.groups.data = Group.query.order_by(Group.id.asc()).all()
if category_id:
category = Category.query.filter_by(id=category_id).first()
form.category.data = category
return render_template("management/forum_form.html", form=form,
title=_("Add Forum")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def add_category():
form = CategoryForm()
if form.validate_on_submit():
form.save()
flash(_("Category added."), "success")
return redirect(url_for("management.forums"))
return render_template("management/category_form.html", form=form,
title=_("Add Category")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def edit_category(category_id):
category = Category.query.filter_by(id=category_id).first_or_404()
form = CategoryForm(obj=category)
if form.validate_on_submit():
form.populate_obj(category)
flash(_("Category updated."), "success")
category.save()
return render_template("management/category_form.html", form=form,
title=_("Edit Category")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def delete_category(category_id):
category = Category.query.filter_by(id=category_id).first_or_404()
involved_users = User.query.filter(Forum.category_id == category.id,
Topic.forum_id == Forum.id,
Post.user_id == User.id).all()
category.delete(involved_users)
flash(_("Category with all associated forums deleted."), "success")
return redirect(url_for("management.forums")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def plugins():
plugins = get_all_plugins()
return render_template("management/plugins.html", plugins=plugins) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def enable_plugin(plugin):
plugin = get_plugin_from_all(plugin)
if plugin.enabled:
flash(_("Plugin %(plugin)s is already enabled.", plugin=plugin.name),
"info")
return redirect(url_for("management.plugins"))
try:
plugin.enable()
flash(_("Plugin %(plugin)s enabled. Please restart FlaskBB now.",
plugin=plugin.name), "success")
except OSError:
flash(_("It seems that FlaskBB does not have enough filesystem "
"permissions. Try removing the 'DISABLED' file by "
"yourself instead."), "danger")
return redirect(url_for("management.plugins")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def disable_plugin(plugin):
try:
plugin = get_plugin(plugin)
except KeyError:
flash(_("Plugin %(plugin)s not found.", plugin=plugin.name), "danger")
return redirect(url_for("management.plugins"))
try:
plugin.disable()
flash(_("Plugin %(plugin)s disabled. Please restart FlaskBB now.",
plugin=plugin.name), "success")
except OSError:
flash(_("It seems that FlaskBB does not have enough filesystem "
"permissions. Try creating the 'DISABLED' file by "
"yourself instead."), "danger")
return redirect(url_for("management.plugins")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def uninstall_plugin(plugin):
plugin = get_plugin_from_all(plugin)
if plugin.uninstallable:
plugin.uninstall()
Setting.invalidate_cache()
flash(_("Plugin has been uninstalled."), "success")
else:
flash(_("Cannot uninstall plugin."), "danger")
return redirect(url_for("management.plugins")) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def plugin(self):
return plugins.get(self.plugin_name) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def setUpModule():
base.enabledPlugins.append('provenance')
base.startServer() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __repr__(self):
return "Authorization(id={id})".format(id=self.id) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def tearDownModule():
base.stopServer() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def setUp(self):
base.TestCase.setUp(self)
# Create some test documents with an item
admin = {
'email': 'admin@email.com',
'login': 'adminlogin',
'firstName': 'Admin',
'lastName': 'Last',
'password': 'adminpassword',
'admin': True
}
self.admin = self.model('user').createUser(**admin)
user = {
'email': 'good@email.com',
'login': 'goodlogin',
'firstName': 'First',
'lastName': 'Last',
'password': 'goodpassword',
'admin': False
}
self.user = self.model('user').createUser(**user)
# Track folder, item, and setting provenance initially
self.model('setting').set(
constants.PluginSettings.PROVENANCE_RESOURCES, 'folder,setting')
coll1 = {
'name': 'Test Collection',
'description': 'test coll',
'public': True,
'creator': self.admin
}
self.coll1 = self.model('collection').createCollection(**coll1)
folder1 = {
'parent': self.coll1,
'parentType': 'collection',
'name': 'Public test folder',
'creator': self.admin
}
self.folder1 = self.model('folder').createFolder(**folder1)
self.model('folder').setUserAccess(
self.folder1, self.user, level=AccessType.WRITE, save=False)
self.model('folder').setPublic(self.folder1, True, save=True)
item1 = {
'name': 'Public object',
'creator': self.admin,
'folder': self.folder1
}
self.item1 = self.model('item').createItem(**item1) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def _checkProvenance(self, resp, item, version, user, eventType,
matches=None, fileInfo=None, resource='item'):
if resp is None:
resp = self._getProvenance(item, user, resource=resource)
self.assertStatusOk(resp)
itemProvenance = resp.json
self.assertEqual(itemProvenance['resourceId'], str(item['_id']))
provenance = itemProvenance['provenance']
self.assertEqual(provenance['eventType'], eventType)
self.assertEqual(provenance['version'], version)
self.assertEqual(str(provenance['eventUser']), str(user['_id']))
if matches:
for key in matches:
self.assertEqual(provenance[key], matches[key])
if fileInfo:
for key in fileInfo:
if isinstance(fileInfo[key], dict):
for subkey in fileInfo[key]:
self.assertEqual(provenance['file'][0][key][subkey],
fileInfo[key][subkey])
else:
self.assertEqual(provenance['file'][0][key], fileInfo[key]) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def _getProvenance(self, item, user, version=None, resource='item',
checkOk=True):
params = {}
if version is not None:
params = {'version': version}
resp = self.request(
path='/%s/%s/provenance' % (resource, item['_id']),
method='GET', user=user, type='application/json', params=params)
if checkOk:
self.assertStatusOk(resp)
return resp |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def _getProvenanceAfterMetadata(self, item, meta, user):
resp = self.request(path='/item/%s/metadata' % item['_id'],
method='PUT', user=user, body=json.dumps(meta),
type='application/json')
self.assertStatusOk(resp)
return self._getProvenance(item, user) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testProvenanceItemMetadata(self):
"""
Test item provenance endpoint with metadata and basic changes
"""
item = self.item1
user = self.user
admin = self.admin
# check that the first version of the item exists
# ensure version 1, created by admin user, with creation event
self._checkProvenance(None, item, 1, admin, 'creation')
# update meta to {x:y}
metadata1 = {'x': 'y'}
resp = self._getProvenanceAfterMetadata(item, metadata1, admin)
# ensure version 2, updated by admin user, with update event, and meta
# in provenance matches
self._checkProvenance(resp, item, 2, admin, 'update',
{'new': {'meta': metadata1}})
# update meta to {} by regular user, we have to send in the key to
# remove it but check the saved metadata against {}
metadata2 = {'x': None}
resp = self._getProvenanceAfterMetadata(item, metadata2, user)
# ensure version 3, updated by regular user, with update event, and
# meta in provenance matches
self._checkProvenance(resp, item, 3, user, 'update',
{'old': {'meta': metadata1},
'new': {'meta': {}}})
# update meta to {x:y} by regular user
metadata3 = {'x': 'y'}
resp = self._getProvenanceAfterMetadata(item, metadata3, user)
# ensure version 4, updated by regular user, with update event, and
# meta in provenance matches
self._checkProvenance(resp, item, 4, user, 'update',
{'old': {'meta': {}},
'new': {'meta': metadata3}})
# update meta to {x:z} by regular user
metadata4 = {'x': 'z'}
resp = self._getProvenanceAfterMetadata(item, metadata4, user)
# ensure version 5, updated by regular user, with update event, and
# meta in provenance matches
self._checkProvenance(resp, item, 5, user, 'update',
{'old': {'meta': metadata3},
'new': {'meta': metadata4}})
# update meta to {x:z, q:u} by regular user
metadata5 = {'x': 'z', 'q': 'u'}
resp = self._getProvenanceAfterMetadata(item, metadata5, user)
# ensure version 6, updated by regular user, with update event, and
# meta in provenance matches
self._checkProvenance(resp, item, 6, user, 'update',
{'old': {'meta': metadata4},
'new': {'meta': metadata5}})
# update meta to {q:a} by regular user
metadata6 = {'x': None, 'q': 'a'}
resp = self._getProvenanceAfterMetadata(item, metadata6, user)
# ensure version 7, updated by regular user, with update event, and
# meta in provenance matches
self._checkProvenance(resp, item, 7, user, 'update',
{'old': {'meta': metadata5},
'new': {'meta': {'q': 'a'}}})
# Change the item name and description
params = {'name': 'Renamed object', 'description': 'New description'}
resp = self.request(path='/item/%s' % item['_id'], method='PUT',
user=admin, params=params)
self.assertStatusOk(resp)
params['lowerName'] = params['name'].lower()
self._checkProvenance(None, item, 8, admin, 'update', {'new': params})
# Copy the item and check that we marked it as copied
params = {'name': 'Copied object'}
resp = self.request(path='/item/%s/copy' % item['_id'],
method='POST', user=admin, params=params)
self.assertStatusOk(resp)
newItem = resp.json
self._checkProvenance(None, newItem, 9, admin, 'copy',
{'originalId': str(item['_id'])}) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testProvenanceItemFiles(self):
"""
Test item provenance when adding, modifying, and deleting files.
"""
item = self.item1
admin = self.admin
# Test adding a new file to an existing item
fileData1 = 'Hello world'
fileData2 = 'Hello world, again'
fileName1 = 'helloWorld.txt'
fileName2 = 'helloWorldEdit.txt'
resp = self.request(
path='/file', method='POST', user=admin, params={
'parentType': 'item',
'parentId': item['_id'],
'name': fileName1,
'size': len(fileData1),
'mimeType': 'text/plain'
})
self.assertStatusOk(resp)
uploadId = resp.json['_id']
fields = [('offset', 0), ('uploadId', uploadId)]
files = [('chunk', fileName1, fileData1)]
resp = self.multipartRequest(
path='/file/chunk', user=admin, fields=fields, files=files)
self.assertStatusOk(resp)
file1 = resp.json
self._checkProvenance(None, item, 2, admin, 'fileAdded',
fileInfo={'fileId': str(file1['_id']),
'new': {'mimeType': 'text/plain',
'size': len(fileData1),
'name': fileName1}})
# Edit the file name
resp = self.request(path='/file/%s' % file1['_id'], method='PUT',
user=admin, params={'name': fileName2})
self.assertStatusOk(resp)
self._checkProvenance(None, item, 3, admin, 'fileUpdate',
fileInfo={'fileId': str(file1['_id']),
'old': {'name': fileName1},
'new': {'name': fileName2}})
# Reupload the file
resp = self.request(path='/file/%s/contents' % file1['_id'],
method='PUT', user=admin,
params={'size': len(fileData2)})
self.assertStatusOk(resp)
uploadId = resp.json['_id']
fields = [('offset', 0), ('uploadId', uploadId)]
files = [('chunk', fileName1, fileData2)]
resp = self.multipartRequest(
path='/file/chunk', user=admin, fields=fields, files=files)
self.assertStatusOk(resp)
self.assertEqual(file1['_id'], resp.json['_id'])
self._checkProvenance(None, item, 4, admin, 'fileUpdate',
fileInfo={'fileId': str(file1['_id']),
'old': {'size': len(fileData1)},
'new': {'size': len(fileData2)}})
# Delete the file
resp = self.request(path='/file/%s' % file1['_id'],
method='DELETE', user=admin)
self.assertStatusOk(resp)
self._checkProvenance(None, item, 5, admin, 'fileRemoved',
fileInfo={'fileId': str(file1['_id']),
'old': {'size': len(fileData2),
'name': fileName2}}) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testProvenanceFolder(self):
"""
Test folder provenance, including turning off and on the provenance
handling of folders.
"""
folder1 = self.folder1
user = self.admin
# check that the first version of the folder provenance exists
self._checkProvenance(None, folder1, 1, user, 'creation',
resource='folder')
# Edit the folder and check again
params1 = {'name': 'Renamed folder', 'description': 'New description'}
resp = self.request(path='/folder/%s' % folder1['_id'],
method='PUT', user=user, params=params1)
self.assertStatusOk(resp)
params1['lowerName'] = params1['name'].lower()
self._checkProvenance(None, folder1, 2, user, 'update',
{'new': params1}, resource='folder')
# Turn off folder provenance and make sure asking for it fails
self.model('setting').set(
constants.PluginSettings.PROVENANCE_RESOURCES, 'setting')
resp = self._getProvenance(folder1, user, resource='folder',
checkOk=False)
self.assertStatus(resp, 400)
# While folder provenance is off, create a second folder and edit the
# first folder
params2 = {'name': 'Renamed Again', 'description': 'Description 2'}
resp = self.request(path='/folder/%s' % folder1['_id'],
method='PUT', user=user, params=params2)
self.assertStatusOk(resp)
params2['lowerName'] = params2['name'].lower()
folder2 = {
'parent': self.coll1,
'parentType': 'collection',
'name': 'Private test folder',
'creator': self.admin
}
folder2 = self.model('folder').createFolder(**folder2)
# Turn back on folder provenance and check that it didn't record the
# changes we made.
self.model('setting').set(
constants.PluginSettings.PROVENANCE_RESOURCES, 'folder,setting')
self._checkProvenance(None, folder1, 2, user, 'update',
{'new': params1}, resource='folder')
# Changing folder1 again should now show this change, and the old value
# should show the gap in the data
params3 = {'name': 'Renamed C', 'description': 'Description 3'}
resp = self.request(path='/folder/%s' % folder1['_id'],
method='PUT', user=user, params=params3)
self.assertStatusOk(resp)
params3['lowerName'] = params3['name'].lower()
self._checkProvenance(None, folder1, 3, user, 'update',
{'old': params2, 'new': params3},
resource='folder')
# The new folder should have no provenance
resp = self._getProvenance(folder2, user, resource='folder')
self.assertEqual(resp.json['resourceId'], str(folder2['_id']))
self.assertIsNone(resp.json['provenance'])
# Edit the new folder; it should show the unknown history followed by
# the edit
params4 = {'description': 'Folder 2 Description'}
resp = self.request(path='/folder/%s' % folder2['_id'],
method='PUT', user=user, params=params4)
self.assertStatusOk(resp)
resp = self._getProvenance(folder2, user, 1, resource='folder')
self._checkProvenance(resp, folder2, 1, user, 'unknownHistory',
resource='folder')
self._checkProvenance(None, folder2, 2, user, 'update',
{'new': params4}, resource='folder')
# We should also see the initial history using negative indexing
resp = self._getProvenance(folder2, user, -2, resource='folder')
self._checkProvenance(resp, folder2, 1, user, 'unknownHistory',
resource='folder')
# We should be able to get the entire history using 'all'
resp = self._getProvenance(folder2, user, 'all', resource='folder')
self.assertEqual(resp.json['resourceId'], str(folder2['_id']))
self.assertEqual(len(resp.json['provenance']), 2)
self.assertEqual(resp.json['provenance'][0]['eventType'],
'unknownHistory')
self.assertEqual(resp.json['provenance'][1]['eventType'], 'update')
# We should get an error if we ask for a nonsense version
resp = self._getProvenance(folder2, user, 'not_a_version',
resource='folder', checkOk=False)
self.assertStatus(resp, 400) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def _rmsprop_update_numpy(self, var, g, mg, rms, mom, lr, decay, momentum,
centered):
rms_t = rms * decay + (1 - decay) * g * g
if centered:
mg_t = mg * decay + (1 - decay) * g
denom_t = rms_t - mg_t * mg_t
else:
mg_t = mg
denom_t = rms_t
mom_t = momentum * mom + lr * g / np.sqrt(denom_t, dtype=denom_t.dtype)
var_t = var - mom_t
return var_t, mg_t, rms_t, mom_t |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def _sparse_rmsprop_update_numpy(self, var, gindexs, gvalues, mg, rms, mom,
lr, decay, momentum, centered):
mg_t = copy.deepcopy(mg)
rms_t = copy.deepcopy(rms)
mom_t = copy.deepcopy(mom)
var_t = copy.deepcopy(var)
for i in range(len(gindexs)):
gindex = gindexs[i]
gvalue = gvalues[i]
rms_t[gindex] = rms[gindex] * decay + (1 - decay) * gvalue * gvalue
denom_t = rms_t[gindex]
if centered:
mg_t[gindex] = mg_t[gindex] * decay + (1 - decay) * gvalue
denom_t -= mg_t[gindex] * mg_t[gindex]
mom_t[gindex] = momentum * mom[gindex] + lr * gvalue / np.sqrt(denom_t)
var_t[gindex] = var[gindex] - mom_t[gindex]
return var_t, mg_t, rms_t, mom_t |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testDense(self, dtype, param_value):
(learning_rate, decay, momentum, epsilon, centered, use_resource) = tuple(
param_value)
with self.session(use_gpu=True):
# Initialize variables for numpy implementation.
var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)
grads0_np = np.array([0.1, 0.2], dtype=dtype.as_numpy_dtype)
var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)
grads1_np = np.array([0.01, 0.2], dtype=dtype.as_numpy_dtype)
if use_resource:
var0 = resource_variable_ops.ResourceVariable(var0_np)
var1 = resource_variable_ops.ResourceVariable(var1_np)
else:
var0 = variables.Variable(var0_np)
var1 = variables.Variable(var1_np)
grads0 = constant_op.constant(grads0_np)
grads1 = constant_op.constant(grads1_np)
opt = rmsprop.RMSPropOptimizer(
learning_rate=learning_rate,
decay=decay,
momentum=momentum,
epsilon=epsilon,
centered=centered)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
mg0 = opt.get_slot(var0, "mg")
self.assertEqual(mg0 is not None, centered)
mg1 = opt.get_slot(var1, "mg")
self.assertEqual(mg1 is not None, centered)
rms0 = opt.get_slot(var0, "rms")
self.assertIsNotNone(rms0)
rms1 = opt.get_slot(var1, "rms")
self.assertIsNotNone(rms1)
mom0 = opt.get_slot(var0, "momentum")
self.assertIsNotNone(mom0)
mom1 = opt.get_slot(var1, "momentum")
self.assertIsNotNone(mom1)
mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
rms0_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
rms1_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0.eval())
self.assertAllClose([3.0, 4.0], var1.eval())
# Run 4 steps of RMSProp
for _ in range(4):
update.run()
var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy(
var0_np, grads0_np, mg0_np, rms0_np, mom0_np, learning_rate,
decay, momentum, centered)
var1_np, mg1_np, rms1_np, mom1_np = self._rmsprop_update_numpy(
var1_np, grads1_np, mg1_np, rms1_np, mom1_np, learning_rate,
decay, momentum, centered)
# Validate updated params
if centered:
self.assertAllCloseAccordingToType(mg0_np, mg0.eval())
self.assertAllCloseAccordingToType(mg1_np, mg1.eval())
self.assertAllCloseAccordingToType(rms0_np, rms0.eval())
self.assertAllCloseAccordingToType(rms1_np, rms1.eval())
self.assertAllCloseAccordingToType(mom0_np, mom0.eval())
self.assertAllCloseAccordingToType(mom1_np, mom1.eval())
# TODO(b/117393988): Reduce tolerances for float16.
self.assertAllCloseAccordingToType(
var0_np, var0.eval(), half_rtol=3e-3, half_atol=3e-3)
self.assertAllCloseAccordingToType(
var1_np, var1.eval(), half_rtol=3e-3, half_atol=3e-3) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testMinimizeSparseResourceVariable(self, dtype):
with self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
x = constant_op.constant([[4.0], [5.0]], dtype=dtype)
pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)
loss = pred * pred
sgd_op = rmsprop.RMSPropOptimizer(
learning_rate=1.0,
decay=0.0,
momentum=0.0,
epsilon=0.0,
centered=False).minimize(loss)
variables.global_variables_initializer().run()
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], var0.eval())
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType(
[[0., 1.]], var0.eval(), atol=0.01) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testMinimizeSparseResourceVariableCentered(self, dtype):
with self.cached_session():
var0 = resource_variable_ops.ResourceVariable([[1.0, 2.0]], dtype=dtype)
x = constant_op.constant([[4.0], [5.0]], dtype=dtype)
pred = math_ops.matmul(embedding_ops.embedding_lookup([var0], [0]), x)
loss = pred * pred
sgd_op = rmsprop.RMSPropOptimizer(
learning_rate=1.0,
decay=0.1,
momentum=0.0,
epsilon=1.0,
centered=True).minimize(loss)
variables.global_variables_initializer().run()
# Fetch params to validate initial values
self.assertAllCloseAccordingToType([[1.0, 2.0]], var0.eval())
# Run 1 step of sgd
sgd_op.run()
# Validate updated params
self.assertAllCloseAccordingToType(
[[-7/3.0, -4/3.0]], var0.eval(), atol=0.01) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testSparse(self, dtype, param_value):
(learning_rate, decay, momentum, epsilon, centered, _) = tuple(
param_value)
with self.session(use_gpu=True):
# Initialize variables for numpy implementation.
var0_np = np.array([1.0, 2.0], dtype=dtype.as_numpy_dtype)
grads0_np = np.array([0.1], dtype=dtype.as_numpy_dtype)
var1_np = np.array([3.0, 4.0], dtype=dtype.as_numpy_dtype)
grads1_np = np.array([0.01], dtype=dtype.as_numpy_dtype)
var0 = variables.Variable(var0_np)
var1 = variables.Variable(var1_np)
grads0_np_indices = np.array([0], dtype=np.int32)
grads0 = ops.IndexedSlices(
constant_op.constant(grads0_np),
constant_op.constant(grads0_np_indices), constant_op.constant([1]))
grads1_np_indices = np.array([1], dtype=np.int32)
grads1 = ops.IndexedSlices(
constant_op.constant(grads1_np),
constant_op.constant(grads1_np_indices), constant_op.constant([1]))
opt = rmsprop.RMSPropOptimizer(
learning_rate=learning_rate,
decay=decay,
momentum=momentum,
epsilon=epsilon,
centered=centered)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
mg0 = opt.get_slot(var0, "mg")
self.assertEqual(mg0 is not None, centered)
mg1 = opt.get_slot(var1, "mg")
self.assertEqual(mg1 is not None, centered)
rms0 = opt.get_slot(var0, "rms")
self.assertIsNotNone(rms0)
rms1 = opt.get_slot(var1, "rms")
self.assertIsNotNone(rms1)
mom0 = opt.get_slot(var0, "momentum")
self.assertIsNotNone(mom0)
mom1 = opt.get_slot(var1, "momentum")
self.assertIsNotNone(mom1)
mg0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mg1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
rms0_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
rms1_np = np.array([epsilon, epsilon], dtype=dtype.as_numpy_dtype)
mom0_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
mom1_np = np.array([0.0, 0.0], dtype=dtype.as_numpy_dtype)
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0.eval())
self.assertAllClose([3.0, 4.0], var1.eval())
# Run 4 steps of RMSProp
for _ in range(4):
update.run()
var0_np, mg0_np, rms0_np, mom0_np = self._sparse_rmsprop_update_numpy(
var0_np, grads0_np_indices, grads0_np, mg0_np, rms0_np, mom0_np,
learning_rate, decay, momentum, centered)
var1_np, mg1_np, rms1_np, mom1_np = self._sparse_rmsprop_update_numpy(
var1_np, grads1_np_indices, grads1_np, mg1_np, rms1_np, mom1_np,
learning_rate, decay, momentum, centered)
# Validate updated params
if centered:
self.assertAllCloseAccordingToType(mg0_np, mg0.eval())
self.assertAllCloseAccordingToType(mg1_np, mg1.eval())
self.assertAllCloseAccordingToType(rms0_np, rms0.eval())
self.assertAllCloseAccordingToType(rms1_np, rms1.eval())
self.assertAllCloseAccordingToType(mom0_np, mom0.eval())
self.assertAllCloseAccordingToType(mom1_np, mom1.eval())
self.assertAllCloseAccordingToType(var0_np, var0.eval())
self.assertAllCloseAccordingToType(var1_np, var1.eval()) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testWithoutMomentum(self, dtype):
with self.session(use_gpu=True):
var0 = variables.Variable([1.0, 2.0], dtype=dtype)
var1 = variables.Variable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
opt = rmsprop.RMSPropOptimizer(
learning_rate=2.0, decay=0.9, momentum=0.0, epsilon=1.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
rms0 = opt.get_slot(var0, "rms")
self.assertIsNotNone(rms0)
rms1 = opt.get_slot(var1, "rms")
self.assertIsNotNone(rms1)
mom0 = opt.get_slot(var0, "momentum")
self.assertIsNotNone(mom0)
mom1 = opt.get_slot(var1, "momentum")
self.assertIsNotNone(mom1)
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0.eval())
self.assertAllClose([3.0, 4.0], var1.eval())
# Step 1: the rms accumulators where 1. So we should see a normal
# update: v -= grad * learning_rate
update.run()
# Check the root mean square accumulators.
self.assertAllCloseAccordingToType(
np.array([0.901, 0.901]), rms0.eval())
self.assertAllCloseAccordingToType(
np.array([0.90001, 0.90001]), rms1.eval())
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
1.0 - (0.1 * 2.0 / math.sqrt(0.901)),
2.0 - (0.1 * 2.0 / math.sqrt(0.901))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
3.0 - (0.01 * 2.0 / math.sqrt(0.90001)),
4.0 - (0.01 * 2.0 / math.sqrt(0.90001))
]), var1.eval())
# Step 2: the root mean square accumulators contain the previous update.
update.run()
# Check the rms accumulators.
self.assertAllCloseAccordingToType(
np.array([0.901 * 0.9 + 0.001, 0.901 * 0.9 + 0.001]), rms0.eval())
self.assertAllCloseAccordingToType(
np.array([0.90001 * 0.9 + 1e-5, 0.90001 * 0.9 + 1e-5]), rms1.eval())
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
1.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)),
2.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
3.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)),
4.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))
]), var1.eval()) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testWithMomentum(self, dtype):
with self.session(use_gpu=True):
var0 = variables.Variable([1.0, 2.0], dtype=dtype)
var1 = variables.Variable([3.0, 4.0], dtype=dtype)
grads0 = constant_op.constant([0.1, 0.1], dtype=dtype)
grads1 = constant_op.constant([0.01, 0.01], dtype=dtype)
opt = rmsprop.RMSPropOptimizer(
learning_rate=2.0, decay=0.9, momentum=0.5, epsilon=1.0)
update = opt.apply_gradients(zip([grads0, grads1], [var0, var1]))
variables.global_variables_initializer().run()
rms0 = opt.get_slot(var0, "rms")
self.assertIsNotNone(rms0)
rms1 = opt.get_slot(var1, "rms")
self.assertIsNotNone(rms1)
mom0 = opt.get_slot(var0, "momentum")
self.assertIsNotNone(mom0)
mom1 = opt.get_slot(var1, "momentum")
self.assertIsNotNone(mom1)
# Fetch params to validate initial values
self.assertAllClose([1.0, 2.0], var0.eval())
self.assertAllClose([3.0, 4.0], var1.eval())
# Step 1: rms = 1, mom = 0. So we should see a normal
# update: v -= grad * learning_rate
update.run()
# Check the root mean square accumulators.
self.assertAllCloseAccordingToType(
np.array([0.901, 0.901]), rms0.eval())
self.assertAllCloseAccordingToType(
np.array([0.90001, 0.90001]), rms1.eval())
# Check the momentum accumulators
self.assertAllCloseAccordingToType(
np.array([(0.1 * 2.0 / math.sqrt(0.901)),
(0.1 * 2.0 / math.sqrt(0.901))]), mom0.eval())
self.assertAllCloseAccordingToType(
np.array([(0.01 * 2.0 / math.sqrt(0.90001)),
(0.01 * 2.0 / math.sqrt(0.90001))]), mom1.eval())
# Check that the parameters.
self.assertAllCloseAccordingToType(
np.array([
1.0 - (0.1 * 2.0 / math.sqrt(0.901)),
2.0 - (0.1 * 2.0 / math.sqrt(0.901))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
3.0 - (0.01 * 2.0 / math.sqrt(0.90001)),
4.0 - (0.01 * 2.0 / math.sqrt(0.90001))
]), var1.eval())
# Step 2: the root mean square accumulators contain the previous update.
update.run()
# Check the rms accumulators.
self.assertAllCloseAccordingToType(
np.array([0.901 * 0.9 + 0.001, 0.901 * 0.9 + 0.001]), rms0.eval())
self.assertAllCloseAccordingToType(
np.array([0.90001 * 0.9 + 1e-5, 0.90001 * 0.9 + 1e-5]), rms1.eval())
self.assertAllCloseAccordingToType(
np.array([
0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)),
0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))
]), mom0.eval())
self.assertAllCloseAccordingToType(
np.array([
0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)),
0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))
]), mom1.eval())
# Check the parameters.
self.assertAllCloseAccordingToType(
np.array([
1.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
(0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001))),
2.0 - (0.1 * 2.0 / math.sqrt(0.901)) -
(0.5 * (0.1 * 2.0 / math.sqrt(0.901)) +
(0.1 * 2.0 / math.sqrt(0.901 * 0.9 + 0.001)))
]), var0.eval())
self.assertAllCloseAccordingToType(
np.array([
3.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
(0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5))),
4.0 - (0.01 * 2.0 / math.sqrt(0.90001)) -
(0.5 * (0.01 * 2.0 / math.sqrt(0.90001)) +
(0.01 * 2.0 / math.sqrt(0.90001 * 0.9 + 1e-5)))
]), var1.eval()) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __init__(self):
self.mainFrame = gui.mainFrame.MainFrame.getInstance() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def display(self, callingWindow, srcContext, mainItem):
if srcContext not in ("marketItemGroup", "marketItemMisc") or self.mainFrame.getActiveFit() is None:
return False
if mainItem is None:
return False
for attr in ("emDamage", "thermalDamage", "explosiveDamage", "kineticDamage"):
if mainItem.getAttribute(attr) is not None:
return True
return False |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def getText(self, callingWindow, itmContext, mainItem):
return "Set {} as Damage Pattern".format(itmContext if itmContext is not None else "Item") |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def activate(self, callingWindow, fullContext, mainItem, i):
fitID = self.mainFrame.getActiveFit()
Fit.getInstance().setAsPattern(fitID, mainItem)
wx.PostEvent(self.mainFrame, GE.FitChanged(fitIDs=(fitID,))) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def getBitmap(self, callingWindow, context, mainItem):
return None |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testProcessPriorTo24(self):
"""Tests the Process function on a Firefox History database file."""
# This is probably version 23 but potentially an older version.
plugin = firefox_history.FirefoxHistoryPlugin()
storage_writer = self._ParseDatabaseFileWithPlugin(
['places.sqlite'], plugin)
# The places.sqlite file contains 205 events (1 page visit,
# 2 x 91 bookmark records, 2 x 3 bookmark annotations,
# 2 x 8 bookmark folders).
# However there are three events that do not have a timestamp
# so the test file will show 202 extracted events.
number_of_events = storage_writer.GetNumberOfAttributeContainers('event')
self.assertEqual(number_of_events, 202)
number_of_warnings = storage_writer.GetNumberOfAttributeContainers(
'extraction_warning')
self.assertEqual(number_of_warnings, 0)
number_of_warnings = storage_writer.GetNumberOfAttributeContainers(
'recovery_warning')
self.assertEqual(number_of_warnings, 0)
events = list(storage_writer.GetEvents())
# Check the first page visited event.
expected_event_values = {
'data_type': 'firefox:places:page_visited',
'date_time': '2011-07-01 11:16:21.371935',
'host': 'news.google.com',
'timestamp_desc': definitions.TIME_DESCRIPTION_LAST_VISITED,
'title': 'Google News',
'url': 'http://news.google.com/',
'visit_count': 1,
'visit_type': 2}
self.CheckEventValues(storage_writer, events[0], expected_event_values)
# Check the first bookmark event.
expected_event_values = {
'data_type': 'firefox:places:bookmark',
'date_time': '2011-07-01 11:13:59.266344',
'timestamp_desc': definitions.TIME_DESCRIPTION_ADDED}
self.CheckEventValues(storage_writer, events[1], expected_event_values)
# Check the second bookmark event.
expected_event_values = {
'data_type': 'firefox:places:bookmark',
'date_time': '2011-07-01 11:13:59.267198',
'places_title': (
'folder=BOOKMARKS_MENU&folder=UNFILED_BOOKMARKS&folder=TOOLBAR&'
'sort=12&excludeQueries=1&excludeItemIfParentHasAnnotation=livemark'
'%2FfeedURI&maxResults=10&queryType=1'),
'timestamp_desc': definitions.TIME_DESCRIPTION_MODIFICATION,
'title': 'Recently Bookmarked',
'type': 'URL',
'url': (
'place:folder=BOOKMARKS_MENU&folder=UNFILED_BOOKMARKS&folder='
'TOOLBAR&sort=12&excludeQueries=1&excludeItemIfParentHasAnnotation='
'livemark%2FfeedURI&maxResults=10&queryType=1'),
'visit_count': 0}
self.CheckEventValues(storage_writer, events[2], expected_event_values)
# Check the first bookmark annotation event.
expected_event_values = {
'data_type': 'firefox:places:bookmark_annotation',
'date_time': '2011-07-01 11:13:59.267146',
'timestamp_desc': definitions.TIME_DESCRIPTION_ADDED}
self.CheckEventValues(storage_writer, events[183], expected_event_values)
# Check another bookmark annotation event.
expected_event_values = {
'content': 'RecentTags',
'data_type': 'firefox:places:bookmark_annotation',
'date_time': '2011-07-01 11:13:59.267605',
'timestamp_desc': definitions.TIME_DESCRIPTION_ADDED,
'title': 'Recent Tags',
'url': 'place:sort=14&type=6&maxResults=10&queryType=1'}
self.CheckEventValues(storage_writer, events[184], expected_event_values)
# Check the second last bookmark folder event.
expected_event_values = {
'data_type': 'firefox:places:bookmark_folder',
'date_time': '2011-03-21 10:05:01.553774',
'timestamp_desc': definitions.TIME_DESCRIPTION_ADDED}
self.CheckEventValues(storage_writer, events[200], expected_event_values)
# Check the last bookmark folder event.
expected_event_values = {
'data_type': 'firefox:places:bookmark_folder',
'date_time': '2011-07-01 11:14:11.766851',
'timestamp_desc': definitions.TIME_DESCRIPTION_MODIFICATION,
'title': 'Latest Headlines'}
self.CheckEventValues(storage_writer, events[201], expected_event_values) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def testProcessVersion25(self):
"""Tests the Process function on a Firefox History database file v 25."""
plugin = firefox_history.FirefoxHistoryPlugin()
storage_writer = self._ParseDatabaseFileWithPlugin(
['places_new.sqlite'], plugin)
# The places.sqlite file contains 84 events:
# 34 page visits.
# 28 bookmarks
# 14 bookmark folders
# 8 annotations
number_of_events = storage_writer.GetNumberOfAttributeContainers('event')
self.assertEqual(number_of_events, 84)
number_of_warnings = storage_writer.GetNumberOfAttributeContainers(
'extraction_warning')
self.assertEqual(number_of_warnings, 0)
number_of_warnings = storage_writer.GetNumberOfAttributeContainers(
'recovery_warning')
self.assertEqual(number_of_warnings, 0)
events = list(storage_writer.GetEvents())
counter = collections.Counter()
for event in events:
event_data = self._GetEventDataOfEvent(storage_writer, event)
counter[event_data.data_type] += 1
self.assertEqual(counter['firefox:places:bookmark'], 28)
self.assertEqual(counter['firefox:places:page_visited'], 34)
self.assertEqual(counter['firefox:places:bookmark_folder'], 14)
self.assertEqual(counter['firefox:places:bookmark_annotation'], 8)
expected_event_values = {
'data_type': 'firefox:places:page_visited',
'date_time': '2013-10-30 21:57:11.281942',
'host': 'code.google.com',
'url': 'http://code.google.com/p/plaso',
'visit_count': 1,
'visit_type': 2}
self.CheckEventValues(storage_writer, events[10], expected_event_values) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def each(f):
if f.body:
f.hashes = []
for hash_type, h in HashFile.extract_hashes(f.body.contents):
hash_object = Hash.get_or_create(value=h.hexdigest())
hash_object.add_source("analytics")
hash_object.save()
f.active_link_to(
hash_object,
"{} hash".format(hash_type.upper()),
"HashFile",
clean_old=False,
)
f.hashes.append({"hash": hash_type, "value": h.hexdigest()})
f.save() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __init__(self, queue, level, formatter):
super(QueueingLogHandler, self).__init__()
self._queue = queue
self.setLevel(level)
self.setFormatter(formatter) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def emit(self, record):
msg = self.format(record)
self._queue.put_nowait(msg) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def close(self):
super(QueueingLogHandler, self).close()
self._queue.put_nowait(None) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def emitted(self):
return self._queue |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __init__(self):
self._logging_handlers = set() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def test(self, logger_name, logger_level, message):
logger = logging.getLogger(logger_name)
getattr(logger, logger_level.lower())(message) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def available_loggers(self):
""" List of initalized loggers """
return logging.getLogger().manager.loggerDict.keys() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def close_log_streams(self):
""" Closes all log_stream streams. """
while self._logging_handlers:
self._logging_handlers.pop().close() |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def log_stream(self, logger_name, level_name, format_str):
""" Attaches a log handler to the specified logger and sends emitted logs
back as stream.
"""
if logger_name != "" and logger_name not in self.available_loggers():
raise ValueError("logger {0} is not available".format(logger_name))
level_name_upper = level_name.upper() if level_name else "NOTSET"
try:
level = getattr(logging, level_name_upper)
except AttributeError, e:
raise AttributeError("log level {0} is not available".format(level_name_upper)) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def create(params, env=None, headers=None):
return request.send('post', request.uri_path("plans"), params, env, headers) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def update(id, params=None, env=None, headers=None):
return request.send('post', request.uri_path("plans",id), params, env, headers) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def list(params=None, env=None, headers=None):
return request.send_list_request('get', request.uri_path("plans"), params, env, headers) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def retrieve(id, env=None, headers=None):
return request.send('get', request.uri_path("plans",id), None, env, headers) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def delete(id, env=None, headers=None):
return request.send('post', request.uri_path("plans",id,"delete"), None, env, headers) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def copy(params, env=None, headers=None):
return request.send('post', request.uri_path("plans","copy"), params, env, headers) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def wrapper%(signature)s:
with ldap3mock:
return func%(funcargs)s |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def generateUUID(): # pylint: disable=invalid-name
""" Utility function; generates UUIDs """
return str(uuid.uuid4()) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def _convert_objectGUID(item):
item = uuid.UUID("{{{0!s}}}".format(item)).bytes_le
item = escape_bytes(item)
return item |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def refund_user(self, user_id):
# Do logic here... |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __init__(self):
self._calls = [] |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def with_status_check(obj, *args, **kwargs):
if obj.status not in valid_start_statuses:
exception_msg = (
u"Error calling {} {}: status is '{}', must be one of: {}"
).format(func, obj, obj.status, valid_start_statuses)
raise VerificationException(exception_msg)
return func(obj, *args, **kwargs) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __iter__(self):
return iter(self._calls) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def expiration_datetime(self):
"""Datetime that the verification will expire. """
days_good_for = settings.VERIFY_STUDENT["DAYS_GOOD_FOR"]
return self.created_at + timedelta(days=days_good_for) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __len__(self):
return len(self._calls) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def should_display_status_to_user(self):
"""Whether or not the status from this attempt should be displayed to the user."""
return True |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __getitem__(self, idx):
return self._calls[idx] |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def active_at_datetime(self, deadline):
"""Check whether the verification was active at a particular datetime.
Arguments:
deadline (datetime): The date at which the verification was active
(created before and expiration datetime is after today).
Returns:
bool
"""
return (
self.created_at < deadline and
self.expiration_datetime > now()
) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def setdata(self, request, response):
self._calls.append(Call(request, response)) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __unicode__(self):
return 'ManualIDVerification for {name}, status: {status}'.format(
name=self.name,
status=self.status,
) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def reset(self):
self._calls = [] |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def should_display_status_to_user(self):
"""
Whether or not the status should be displayed to the user.
"""
return False |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __init__(self, connection):
self.connection = connection |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __unicode__(self):
return 'SSOIDVerification for {name}, status: {status}'.format(
name=self.name,
status=self.status,
) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def paged_search(self, **kwargs):
self.connection.search(search_base=kwargs.get("search_base"),
search_scope=kwargs.get("search_scope"),
search_filter=kwargs.get(
"search_filter"),
attributes=kwargs.get("attributes"),
paged_size=kwargs.get("page_size"),
size_limit=kwargs.get("size_limit"),
paged_cookie=None)
result = self.connection.response
if kwargs.get("generator", False):
# If ``generator=True`` is passed, ``paged_search`` should return an iterator.
result = iter(result)
return result |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __init__(self, connection):
self.standard = self.Standard(connection) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def parsed_error_msg(self):
"""
Sometimes, the error message we've received needs to be parsed into
something more human readable
The default behavior is to return the current error message as is.
"""
return self.error_msg |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def __init__(self, directory=None):
if directory is None:
directory = []
import copy
self.directory = copy.deepcopy(directory)
self.bound = False
self.start_tls_called = False
self.extend = self.Extend(self)
self.operation = {
"!" : self._search_not,
"&" : self._search_and,
"|" : self._search_or,
} |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def upload_face_image(self, img):
raise NotImplementedError |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def set_directory(self, directory):
self.directory = directory |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def upload_photo_id_image(self, img):
raise NotImplementedError |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def _find_user(self, dn):
return next(i for (i, d) in enumerate(self.directory) if d["dn"] == dn) |
def __init__(self,params,parent):
self.params=params
self.parent=parent | def mark_ready(self):
"""
Mark that the user data in this attempt is correct. In order to
succeed, the user must have uploaded the necessary images
(`face_image_url`, `photo_id_image_url`). This method will also copy
their name from their user profile. Prior to marking it ready, we read
this value directly from their profile, since they're free to change it.
This often happens because people put in less formal versions of their
name on signup, but realize they want something different to go on a
formal document.
Valid attempt statuses when calling this method:
`created`
Status after method completes: `ready`
Other fields that will be set by this method:
`name`
State Transitions:
`created` → `ready`
This is what happens when the user confirms to us that the pictures
they uploaded are good. Note that we don't actually do a submission
anywhere yet.
"""
# At any point prior to this, they can change their names via their
# student dashboard. But at this point, we lock the value into the
# attempt.
self.name = self.user.profile.name
self.status = "ready"
self.save() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.