Пример #1
0
 def __init__(self):
     Operation.__init__(self, { "review_id": int,
                                "filters": [{ "type": set(["reviewer", "watcher"]),
                                              "user_names": Optional([str]),
                                              "user_ids": Optional([int]),
                                              "paths": Optional([str]),
                                              "file_ids": Optional([int]) }] })
Пример #2
0
    def process(self, db, user, subject, filter_id):
        if user != subject:
            Operation.requireRole(db, "administrator", user)

        cursor = db.cursor()
        cursor.execute(
            """SELECT 1
                            FROM extensionhookfilters
                           WHERE id=%s
                             AND uid=%s""", (filter_id, subject.id))

        if not cursor.fetchone():
            raise OperationFailure(
                code="invalidoperation",
                title="Invalid operation",
                message=
                "Filter to delete does not exist or belongs to another user!")

        cursor.execute(
            """DELETE
                            FROM extensionhookfilters
                           WHERE id=%s""", (filter_id, ))

        db.commit()

        return OperationResult()
Пример #3
0
 def __init__(self, perform):
     Operation.__init__(self, {
         "author_name": str,
         "extension_name": str,
         "version": Optional(str)
     })
     self.perform = perform
Пример #4
0
    def process(self, db, user, new_pw, subject=None, current_pw=None):
        if subject is None:
            subject = user

        cursor = db.cursor()

        if not auth.DATABASE.supportsPasswordChange():
            raise OperationFailure(
                code="notsupported",
                title="Not supported!",
                message="Changing password is not supported via this system.")

        if not new_pw:
            raise OperationFailure(
                code="emptypassword",
                title="Empty password!",
                message="Setting an empty password is not allowed.")

        if user != subject:
            Operation.requireRole(db, "administrator", user)

            if current_pw is None:
                # Signal that it doesn't need to be checked.
                current_pw = True

        try:
            auth.DATABASE.changePassword(db, subject, current_pw, new_pw)
        except auth.WrongPassword:
            raise OperationFailure(
                code="wrongpassword",
                title="Wrong password!",
                message="The provided current password is not correct.")

        return OperationResult()
Пример #5
0
 def __init__(self):
     Operation.__init__(self, { "filter_type": set(["reviewer", "watcher", "ignored"]),
                                "path": str,
                                "delegates": [str],
                                "repository_id": Optional(int),
                                "repository_name": Optional(str),
                                "replaced_filter_id": Optional(int) })
    def decide(self, candle_num, bits):

        ##make sure there exists adequate history for prediction, return NONE OP
        if candle_num > self.neural_model.num_past:

            ##computing what will be the input into the model
            inp = []
            for i in range(self.neural_model.num_past):
                if self.neural_model.mode == self.neural_model.CLOSE:
                    inp.append(
                        self.candles[candle_num -
                                     (self.neural_model.num_past - i)].close)
                elif self.neural_model.mode == self.neural_model.VOLUME:
                    inp.append(
                        self.candles[candle_num -
                                     (self.neural_model.num_past - i)].volume)

            ##get model prediction
            results = self.neural_model.model.predict([inp])
            result = results[0]

            if result == 1:
                return Operation(Operation.BUY_OP, self.AMOUNT)
            elif result == -1:
                return Operation(Operation.SELL_OP, self.AMOUNT)
            elif result == 0:
                return Operation(Operation.NONE_OP, 0)
        else:
            return Operation(Operation.NONE_OP, 0)
Пример #7
0
    def process(self, db, user, service_name):
        Operation.requireRole(db, "administrator", user)

        if service_name == "wsgi":
            for pid in os.listdir(configuration.paths.WSGI_PIDFILE_DIR):
                try:
                    os.kill(int(pid), signal.SIGINT)
                except:
                    pass
            return OperationResult()
        else:
            connection = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            connection.connect(
                configuration.services.SERVICEMANAGER["address"])
            connection.send(
                textutils.json_encode({
                    "command": "restart",
                    "service": service_name
                }))
            connection.shutdown(socket.SHUT_WR)

            data = ""
            while True:
                received = connection.recv(4096)
                if not received: break
                data += received

            result = textutils.json_decode(data)

            if result["status"] == "ok": return OperationResult()
            else: raise OperationError(result["error"])
Пример #8
0
    def process(self, db, user, subject, value):
        if user != subject:
            Operation.requireRole(db, "administrator", user)

        for address in value:
            if not address.strip():
                raise OperationError("empty email address is not allowed")
            if address.count("@") != 1:
                raise OperationError("invalid email address")

        cursor = db.cursor()
        cursor.execute("SELECT email FROM usergitemails WHERE uid=%s", (subject.id,))

        current_addresses = set(address for (address,) in cursor)
        new_addresses = set(address.strip() for address in value)

        for address in (current_addresses - new_addresses):
            cursor.execute("DELETE FROM usergitemails WHERE uid=%s AND email=%s",
                           (subject.id, address))
        for address in (new_addresses - current_addresses):
            cursor.execute("INSERT INTO usergitemails (uid, email) VALUES (%s, %s)",
                           (subject.id, address))

        db.commit()

        return OperationResult()
Пример #9
0
    def process(self, db, user, email_id):
        cursor = db.cursor()
        cursor.execute("""SELECT uid, email, verified
                            FROM useremails
                           WHERE id=%s""",
                       (email_id,))

        row = cursor.fetchone()

        if not row:
            raise OperationFailure(
                code="invalidemailid",
                title="No such email address",
                message="The address might have been deleted already.")

        user_id, email, verified = row

        if verified is True:
            raise OperationFailure(
                code="alreadyverified",
                title="Address already verified",
                message="This address has already been verified.")

        if user != user_id:
            Operation.requireRole(db, "administrator", user)
            user = dbutils.User.fromId(db, user_id)

        sendVerificationMail(db, user, email_id)

        db.commit()

        return OperationResult()
Пример #10
0
    def process(self, db, user, subject, filter_id):
        if user != subject:
            Operation.requireRole(db, "administrator", user)

        cursor = db.cursor()
        cursor.execute("""SELECT 1
                            FROM extensionhookfilters
                           WHERE id=%s
                             AND uid=%s""",
                       (filter_id, subject.id))

        if not cursor.fetchone():
            raise OperationFailure(
                code="invalidoperation",
                title="Invalid operation",
                message="Filter to delete does not exist or belongs to another user!")

        cursor.execute("""DELETE
                            FROM extensionhookfilters
                           WHERE id=%s""",
                       (filter_id,))

        db.commit()

        return OperationResult()
Пример #11
0
def parse_operation(args):
    protocol_info = args[0]
    operation = Operation()

    # Timestamp
    operation.ts = (protocol_info[0] -
                    datetime.datetime(1970, 1, 1)).total_seconds()

    # Connection
    operation.orig_ip = str(protocol_info[1][0][0])
    operation.resp_ip = str(protocol_info[1][0][2])

    # Control Protocol (service)
    operation.service = str(protocol_info[2])

    # uid
    operation.uid = str(protocol_info[3])

    # Function code
    operation.fc = protocol_info[4].value

    # Function name
    operation.fn = str(protocol_info[5])

    # Is from teh originator side
    operation.is_orig = protocol_info[6]

    #print(operation)
    return operation
    def _states_added_cb(self, popup, data):
        new_state = self.newstate_entry.entry

        tmp = new_state.split(None, 1)
        if len(tmp) == 1:
            new_state = (tmp[0], 0.0)
        else:
            new_state = (tmp[0], float(tmp[1]))

        part_name = self._edit_grp.part.name
        part = self._edit_grp.part_get(part_name)
        curr_state = self._edit_grp.part.state.name

        if part.state_exist(*new_state):
            # FIXME: notify the user of it somehow
            return

        self._part_state_copy_from(part_name, curr_state, new_state)

        op = Operation("state addition")
        op.redo_callback_add(
            self._part_state_copy_from, part_name, curr_state, new_state)
        op.undo_callback_add(self._remove_state_internal, new_state)
        self._operation_stack_cb(op)

        self.close()
Пример #13
0
 def __init__(self):
     Operation.__init__(self, { "repository_id": int,
                                "source_location": str,
                                "source_name": str,
                                "target_name": str,
                                "users": [str],
                                "forced": Optional(bool) })
Пример #14
0
    def _remove_cb(self, obj, emission, source):
        def anim_restore(anim_save):
            name = anim_save.name
            if self._edit_grp.animation_add(name):
                anim_save.apply_to(self._edit_grp)

        def sigs_restore(anim_name, sigs_save):
            curr_sig = self._edit_grp.signal.name
            self._edit_grp.signal.name = None

            pname = "@%[email protected]" % anim_name

            for sig in sigs_save:
                prog = self._edit_grp.program_get(sig)
                prog.afters_clear()
                prog.after_add(pname)

            self._edit_grp.signal.name = curr_sig

        def relative_signals_anim_clear(anim_name):
            sigs = []

            curr_sig = self._edit_grp.signal.name
            self._edit_grp.signal.name = None

            pname = "@%[email protected]" % anim_name

            for sig in self._edit_grp.signals:
                prog = self._edit_grp.program_get(sig)
                afters = prog.afters
                if afters and pname != afters[0]:
                    continue

                prog.afters_clear()
                sigs.append(sig)

            self._edit_grp.signal.name = curr_sig

            return sigs

        for s in self.selected:
            anim_name = s[0]
            pname = "@%s@stop" % anim_name
            stop_prog = self._edit_grp.edje.program_get(pname)
            anim_data = objects_data.Animation(stop_prog)

            r = self._edit_grp.animation_del(anim_name)
            if not r:
                del anim_data
                continue

            sigs_save = relative_signals_anim_clear(anim_name)

            op = Operation("animation deletion: %s" % anim_name)
            op.redo_callback_add(relative_signals_anim_clear, anim_name)
            op.redo_callback_add(self._edit_grp.animation_del, anim_name)
            op.undo_callback_add(anim_restore, anim_data)
            op.undo_callback_add(sigs_restore, anim_name, sigs_save)

            self._operation_stack_cb(op)
Пример #15
0
    def process(self, db, user, new_pw, subject=None, current_pw=None):
        import auth

        if subject is None:
            user_id = user.id
        elif isinstance(subject, basestring):
            user_id = dbutils.User.fromName(db, subject).id
        else:
            user_id = subject

        if user.id != user_id or current_pw is None:
            Operation.requireRole(db, "administrator", user)

        subject = dbutils.User.fromId(db, user_id)

        if current_pw is not None:
            try: auth.checkPassword(db, subject.name, current_pw)
            except auth.WrongPassword:
                raise OperationFailure(code="wrongpassword",
                                       title="Wrong password!",
                                       message="The provided current password is not correct.")

        if not new_pw:
            raise OperationFailure(code="emptypassword",
                                   title="Empty password!",
                                   message="Setting an empty password is not allowed.")

        cursor = db.cursor()
        cursor.execute("UPDATE users SET password=%s WHERE id=%s", (auth.hashPassword(new_pw), user_id))

        db.commit()

        return OperationResult()
Пример #16
0
    def process(self, db, user, item_id, text):
        Operation.requireRole(db, "newswriter", user)

        db.cursor().execute("UPDATE newsitems SET text=%s WHERE id=%s", (text, item_id))
        db.commit()

        return OperationResult()
Пример #17
0
 def __init__(self):
     Operation.__init__(
         self, {
             "review": Review,
             "new_upstream": Optional(str),
             "branch": Optional(str)
         })
Пример #18
0
    def _add(self):
        def add_internal(name, edje_type, ext_name=""):
            if not self._edit_grp.part_add(name, edje_type, ext_name,
                                           init=self._partsetup.apply_to):
                self.notify("Error adding new part.")
                return False
            return True

        self._part_name = self._part_name_entry.entry
        if self._type == edje.EDJE_PART_TYPE_EXTERNAL:
            ext_name = self._ext_list.type
        else:
            ext_name = ""

        if self._type == edje.EDJE_PART_TYPE_IMAGE:
            ImageSelectionWizard(self._parent, self._image_set,
                    self._new_img_cb, self._img_list_get_cb,
                    self._img_id_get_cb, self._workfile_name_get_cb).show()
        else:
            if add_internal(self._part_name, self._type, ext_name):
                op = Operation("part addition")
                op.redo_callback_add(
                    add_internal, self._part_name, self._type, ext_name)
                op.undo_callback_add(self._edit_grp.part_del, self._part_name)
                self._operation_stack_cb(op)

            self.close()
Пример #19
0
    def __init__(self, param_dict):
        Operation.__init__(self)
        self.original = param_dict

        observation = param_dict['observation']
        x, y = observation.split("d")
        y = y.lstrip("0")
        self.observation_degree = int(x)
        self.observation_minute = float(y)

        if "height" in param_dict:
            self.height = float(param_dict['height'])
        else:
            self.height = self.DEFAULT_HEIGHT

        if "pressure" in param_dict:
            self.pressure = int(param_dict['pressure'])
        else:
            self.pressure = self.DEFAULT_PRESSURE

        if "temperature" in param_dict:
            self.temperature = int(param_dict['temperature'])
        else:
            self.temperature = self.DEFAULT_TEMP

        if "horizon" in param_dict:
            self.horizon = param_dict['horizon']
        else:
            self.horizon = self.DEFAULT_HORIZON
Пример #20
0
    def _state_entry_changed_cb(self, st_widget, *args, **kwargs):

        def state_rename(part_name, old_name, new_name):
            # select 1st
            if self.e.part.name != part_name:
                self.e.part.name = part_name
            self.e.part.state.name = old_name[0]

            part = self.e.part_get(part_name)

            if (part.state_exist(*new_name)) or old_name == ["default", 0.0]:
                return False

            # rename later
            return self.e.part.state.rename(*new_name)

        part = self.e.part.name
        old_name = self.e.part.state.name

        new_name = st_widget.value.split(None, 1)
        if len(new_name) == 1:
            new_name[1] = 0.0
        else:
            new_name[1] = float(new_name[1])

        if state_rename(part, old_name, new_name):
            op = Operation("state renaming")

            op.redo_callback_add(state_rename, part, old_name, new_name)
            op.undo_callback_add(state_rename, part, new_name, old_name)
            self._operation_stack_cb(op)
        else:
            # TODO: notify the user of renaming failure
            st_widget.value = "%s %.2f" % old_name
Пример #21
0
    def _check_changed_cb(self, obj, part):
        if obj.state:
            self._part_add(part, self._edit_grp.animation.name)

            op = Operation("part (%s) addition into animation (%s)" % \
                                (part, self._edit_grp.animation.name))
            op.redo_callback_add(self._part_add, part,
                                 self._edit_grp.animation.name)
            op.undo_callback_add(self._part_remove, part,
                                 self._edit_grp.animation.name)
            self._operation_stack_cb(op)
        else:
            # FIXME: Take the confirmation out of this function
            self._notification = ErrorNotify(
                self, elementary.ELM_NOTIFY_ORIENT_CENTER)
            self._notification.title = "Part Removal"
            lb = elementary.Label(self._notification)
            lb.text_set("Are you sure you want to remove<br>"
                         "this part from the animation?")
            lb.show()
            self._notification.pack_end(lb)
            self._notification.action_add("Remove",
                                          self._confirm_remove_cb, data=part)
            self._notification.action_add("Cancel",
                                          self._cancel_remove_cb, data=obj)
            self._notification.show()
Пример #22
0
    def process(self, db, user, email_id):
        cursor = db.cursor()
        cursor.execute("""SELECT uid
                            FROM useremails
                           WHERE id=%s""",
                       (email_id,))

        row = cursor.fetchone()

        if not row:
            raise OperationFailure(
                code="invalidemailid",
                title="No such email address",
                message="The address might have been deleted already.")

        user_id, = row

        if user != user_id:
            Operation.requireRole(db, "administrator", user)

        cursor.execute("""UPDATE users
                             SET email=%s
                           WHERE id=%s""",
                       (email_id, user_id))

        db.commit()

        return OperationResult()
Пример #23
0
 def __init__(self):
     Operation.__init__(self, {
         "req": Request,
         "fields": {
             str: str
         }
     },
                        accept_anonymous_user=True)
Пример #24
0
 def __init__(self):
     Operation.__init__(self, { "review_id": int,
                                "origin": set(["old", "new"]),
                                "parent_id": int,
                                "child_id": int,
                                "file_id": int,
                                "offset": int,
                                "count": int })
Пример #25
0
 def __init__(self):
     Operation.__init__(self, { "repository_id": int,
                                "commit_ids": [int],
                                "reviewfilters": [{ "username": str,
                                                    "type": set(["reviewer", "watcher"]),
                                                    "path": str }],
                                "applyfilters": bool,
                                "applyparentfilters": bool })
Пример #26
0
 def __init__(self, parent, main_window, params={}):
     Operation.__init__(self, params)
     global main
     main = main_window
     self.set_as_path_only()
     self.__init_ctrls(parent)
     self.__init_sizer(parent)
     self.update_parameters(self.directoryToolsPanel.params)
Пример #27
0
 def __init__(self):
     Operation.__init__(self, { "repository_id": int,
                                "path": str,
                                "sha1": str,
                                "ranges": [{ "offset": int,
                                             "count": int,
                                             "context": bool }],
                                "tabify": bool })
Пример #28
0
	def decide(self, time, bits):
		if time % 6 == 2:
			return Operation(Operation.BUY_OP, self.AMOUNT)
		elif time % 6 == 5:
			return Operation(Operation.SELL_OP, self.AMOUNT)
		else:
			##do nothing rest of the time
			return Operation(Operation.NONE_OP, 0)
Пример #29
0
 def __init__(self):
     Operation.__init__(
         self, {
             "review_id": int,
             "reviewed": bool,
             "changeset_ids": [int],
             "file_ids": [int]
         })
Пример #30
0
 def __init__(self):
     Operation.__init__(self, { "repository_id": int,
                                "changeset_id": int,
                                "files": [{ "id": int,
                                            "blocks": [{ "first": int,
                                                         "last": int }]
                                            }]
                                })
Пример #31
0
 def __init__(self):
     Operation.__init__(
         self, {
             "review_id": int,
             "new_summary": Optional(str),
             "new_description": Optional(str),
             "new_owners": Optional([str])
         })
Пример #32
0
 def __init__(self):
     Operation.__init__(self, {
         "repository_name": str,
         "remote": str,
         "branch": str,
         "upstream": Optional(str)
     },
                        accept_anonymous_user=True)
Пример #33
0
 def __init__(self):
     Operation.__init__(self, { "review": Review,
                                "origin": set(["old", "new"]),
                                "parent": Optional(Commit),
                                "child": Commit,
                                "file": File,
                                "offset": PositiveInteger,
                                "count": PositiveInteger })
Пример #34
0
 def __init__(self, parent, main_window, params={}):
     Operation.__init__(self, params)
     global main
     main = main_window
     self.set_as_path_only()
     self.__init_ctrls(parent)
     self.__init_sizer(parent)
     self.update_parameters(self.directoryToolsPanel.params)
Пример #35
0
 def __init__(self):
     Operation.__init__(self, { "subject": typechecker.User,
                                "extension": typechecker.Extension,
                                "repository": typechecker.Repository,
                                "filterhook_name": str,
                                "path": str,
                                "data": Optional(str),
                                "replaced_filter_id": Optional(int) })
Пример #36
0
    def process(self, db, user, text):
        Operation.requireRole(db, "newswriter", user)

        cursor = db.cursor()
        cursor.execute("INSERT INTO newsitems (text) VALUES (%s) RETURNING id", (text,))
        item_id = cursor.fetchone()[0]
        db.commit()

        return OperationResult(item_id=item_id)
Пример #37
0
    def __init__(self,core,design,type):
        Operation.__init__(self,core)

        self.type = type

        self.design = self.core.session.query(Design).filter(Design.name==design).one_or_none()

        if self.design is None:
            raise ValueError("No design named %s"%design)
Пример #38
0
 def __init__(self):
     Operation.__init__(
         self, {
             "review_id": int,
             "new_head_sha1": str,
             "new_upstream_sha1": Optional(str),
             "branch": Optional(str),
             "new_trackedbranch": Optional(str)
         })
Пример #39
0
    def _down_cb(self, obj, emission, source):
        r = self._restack_below(self._edit_grp.part.name)
        if not r:
            return

        op = Operation("part re-stacking (below)")
        op.redo_callback_add(self._restack_below, self._edit_grp.part.name)
        op.undo_callback_add(self._restack_above, self._edit_grp.part.name)
        self._operation_stack_cb(op)
Пример #40
0
 def __init__(self, parent, main_window, params={}):
     Operation.__init__(self, params)
     global main
     main = main_window
     self.__init_ctrls(parent)
     self.__init_sizer()
     self.activate_options(0)
     self.moveRE = False
     self.regExpPanel.activatedField = self.replMoveTextValue
Пример #41
0
    def __init__(self, param_dict):
        Operation.__init__(self)
        self.original = param_dict

        self.lat = param_dict['lat']
        self.longitude = param_dict['long']
        self.altitude = param_dict['altitude']
        self.assumed_lat = param_dict['assumedLat']
        self.assumed_long = param_dict['assumedLong']
Пример #42
0
 def __init__(self):
     Operation.__init__(
         self,
         {
             "single": Optional({"repository_name": str, "path": str}),
             "multiple": Optional([int]),
             "user_id": Optional(int),
         },
     )
Пример #43
0
 def __init__(self):
     Operation.__init__(
         self, {
             "repository_id": int,
             "source_location": str,
             "source_name": str,
             "target_name": str,
             "users": [str]
         })
Пример #44
0
 def __init__(self):
     Operation.__init__(
         self, {
             "review_id": int,
             "file_id": int,
             "sha1": str,
             "offset": int,
             "count": int
         })
Пример #45
0
 def __init__(self, parent, main_window, params={}):
     Operation.__init__(self, params)
     global main
     main = main_window
     self.__init_ctrls(parent)
     self.__init_sizer()
     self.activate_options(0)
     self.moveRE = False
     self.regExpPanel.activatedField = self.replMoveTextValue
Пример #46
0
def test_jump():
    algorithm = Algorithm()
    op = Operation()
    im = op.screen_cap()
    start_x, start_y, end_x, end_y = algorithm.find_point(im)
    start_point = (start_x, start_y)
    end_point = (end_x, end_y)
    distance = algorithm.euclidean_distance(start_point, end_point)
    press_time = algorithm.distance_to_time(distance)
    op.jump(start_point, end_point, press_time)
Пример #47
0
 def __init__(self):
     Operation.__init__(
         self, {
             "name": str,
             "path": str,
             "remote": Optional({
                 "url": str,
                 "branch": str
             })
         })
Пример #48
0
 def __init__(self):
     Operation.__init__(
         self, {
             "filter_type": set(["reviewer", "watcher", "ignored"]),
             "path": str,
             "delegates": [str],
             "repository_id": Optional(int),
             "repository_name": Optional(str),
             "replaced_filter_id": Optional(int)
         })
Пример #49
0
 def __init__(self):
     Operation.__init__(
         self, {
             "single": Optional({
                 "repository_name": str,
                 "path": str
             }),
             "multiple": Optional([int]),
             "user_id": Optional(int)
         })
Пример #50
0
 def __init__(self):
     Operation.__init__(
         self, {
             "review_id": int,
             "what": {
                 "approval": bool,
                 "comments": bool,
                 "metacomments": bool
             }
         })
Пример #51
0
    def __init__(self,core, directory, data='data.csv', experimentalDesign='meta.csv',**kwargs):
        Operation.__init__(self, core)

        while directory[-1] == '/':
            directory = directory[:-1]
        self.directory = directory

        _,self.name = os.path.split(self.directory)

        self.datafile = data
        self.metafile = experimentalDesign
Пример #52
0
 def agree(bt, notification):
     self._remove_time_point(t, anim_name, anim_frame)
     notification.hide()
     notification.delete()
     op = Operation("animation (%s) frame (%s) deletion" % \
                        (anim_name, t))
     op.redo_callback_add(self._remove_time_point, t, anim_name,
                          anim_frame)
     op.undo_callback_add(
         self._frame_readd, t, anim_name, saved_states, trans)
     self._operation_stack_cb(op)
Пример #53
0
    def process(self, db, user, user_id, value):
        if user.id != user_id:
            Operation.requireRole(db, "administrator", user)

        if not value.strip():
            raise OperationError("empty display name is not allowed")

        db.cursor().execute("UPDATE users SET fullname=%s WHERE id=%s", (value.strip(), user_id))
        db.commit()

        return OperationResult()
Пример #54
0
 def __init__(self):
     Operation.__init__(
         self, {
             "review_id": int,
             "origin": set(["old", "new"]),
             "parent_id": int,
             "child_id": int,
             "file_id": int,
             "offset": int,
             "count": int
         })
Пример #55
0
    def process(self, db, user, email_id):
        cursor = db.cursor()
        cursor.execute("""SELECT uid
                            FROM useremails
                           WHERE id=%s""",
                       (email_id,))

        row = cursor.fetchone()

        if not row:
            raise OperationFailure(
                code="invalidemailid",
                title="No such email address",
                message="The address might have been deleted already.")

        subject_id, = row

        if user != subject_id:
            Operation.requireRole(db, "administrator", user)

        cursor.execute("""SELECT useremails.id, users.email IS NOT NULL
                            FROM useremails
                 LEFT OUTER JOIN users ON (users.email=useremails.id)
                           WHERE useremails.uid=%s""",
                       (subject_id,))

        emails = dict(cursor)

        # Reject if the user has more than one email address registered and is
        # trying to delete the selected one.  The UI checks this too, but that
        # check is not 100 % reliable since it checks the state at the time the
        # page was loaded, not necessarily the current state.
        if len(emails) > 1 and emails[email_id]:
            raise OperationFailure(
                code="notallowed",
                title="Will not delete current address",
                message=("This email address is your current address.  Please "
                         "select one of the other addresses as your current "
                         "address before deleting it."))

        cursor.execute("""UPDATE users
                             SET email=NULL
                           WHERE id=%s
                             AND email=%s""",
                       (subject_id, email_id))

        cursor.execute("""DELETE FROM useremails
                                WHERE id=%s""",
                       (email_id,))

        db.commit()

        return OperationResult()