If an item with the same nonce as an item passed in already exists, it is overwritten by the item. Otherwise
a new message is added.
517061
void addPayload(Payload payload) throws Exception {
		SQLiteDatabase db = null;
		try {
			db = getWritableDatabase();
			db.beginTransaction();

			ContentValues values = new ContentValues();
			values.put(PayloadEntry.COLUMN_IDENTIFIER.name, notNull(payload.getNonce()));
			values.put(PayloadEntry.COLUMN_PAYLOAD_TYPE.name, notNull(payload.getPayloadType().name()));
			values.put(PayloadEntry.COLUMN_CONTENT_TYPE.name, notNull(payload.getHttpRequestContentType()));
			// The token is encrypted inside the payload body for authenticated conversations. In that case, don't store it here.
			if (!payload.isAuthenticated()) {
				values.put(PayloadEntry.COLUMN_AUTH_TOKEN.name, encrypt(payload.getConversationToken())); // might be null
			}
			values.put(PayloadEntry.COLUMN_CONVERSATION_ID.name, payload.getConversationId()); // might be null
			values.put(PayloadEntry.COLUMN_REQUEST_METHOD.name, payload.getHttpRequestMethod().name());
			values.put(PayloadEntry.COLUMN_PATH.name, payload.getHttpEndPoint(
				StringUtils.isNullOrEmpty(payload.getConversationId()) ? "${conversationId}" : payload.getConversationId()) // if conversation id is missing we replace it with a place holder and update it later
			);

			File dest = getPayloadBodyFile(payload.getNonce());
			ApptentiveLog.v(DATABASE, "Saving payload body to: %s", dest);
			writeToFile(dest, payload.renderData(), !payload.isAuthenticated());  // only anonymous payloads get encrypted upon write (authenticated payloads get encrypted on serialization)

			values.put(PayloadEntry.COLUMN_AUTHENTICATED.name, payload.isAuthenticated() ? TRUE : FALSE);
			values.put(PayloadEntry.COLUMN_LOCAL_CONVERSATION_ID.name, notNull(payload.getLocalConversationIdentifier()));

			db.insert(PayloadEntry.TABLE_NAME, null, values);
			db.setTransactionSuccessful();
		} finally {
			if (db != null) {
				db.endTransaction();
			}
		}

		if (ApptentiveLog.canLog(ApptentiveLog.Level.VERBOSE)) {
			printPayloadTable("Added payload");
		}
	}
44360
protected void updateOverwriteExisting() {

        if (m_overwriteExisting != null) {
            boolean move = (m_dialogMode == DialogMode.move) || (m_actionCombo.getValue() == Action.move);
            if (move) {
                m_overwriteExisting.setValue(Boolean.FALSE);
                m_overwriteExisting.setVisible(false);
            } else {
                m_overwriteExisting.setVisible(true);
            }
        }
    }
456881
def check_abbreviation_unique(self, abbreviation, newFilterPattern, targetItem):
        
        for item in self.allFolders:
            if model.TriggerMode.ABBREVIATION in item.modes:
                if abbreviation in item.abbreviations and item.filter_matches(newFilterPattern):
                    return item is targetItem, item
            
        for item in self.allItems:
            if model.TriggerMode.ABBREVIATION in item.modes:
                if abbreviation in item.abbreviations and item.filter_matches(newFilterPattern):
                    return item is targetItem, item

        return True, None
956494
public void checkNameUniqueness(String name) {
		if (usedNames.contains(name)) {
			throw new MalformedPatternException("Duplicate pattern name: " + name + ". Names must be unique.");
		}
		usedNames.add(name);
	}
38
def _put_one(self, item):
        ''' 
        '''
        # prepare values
        values = []
        for k, v in item.items():
            if k == '_id':
                continue
            if 'dblite_serializer' in item.fields[k]:
                serializer = item.fields[k]['dblite_serializer']
                v = serializer.dumps(v)
                if v is not None:
                    v = sqlite3.Binary(buffer(v))
            values.append(v)

        # check if Item is new => update it
        if '_id' in item:
            fieldnames = ','.join(['%s=?' % f for f in item if f != '_id'])
            values.append(item['_id'])
            SQL = 'UPDATE %s SET %s WHERE rowid=?;' % (self._table, fieldnames)
        # new Item
        else:
            fieldnames = ','.join([f for f in item if f != '_id'])
            fieldnames_template = ','.join(['?' for f in item if f != '_id'])
            SQL = 'INSERT INTO %s (%s) VALUES (%s);' % (self._table, fieldnames, fieldnames_template)

        try:
            self._cursor.execute(SQL, values)
        except sqlite3.OperationalError, err:
            raise RuntimeError('Item put() error, %s, SQL: %s, values: %s' % (err, SQL, values) )
        except sqlite3.IntegrityError:
            raise DuplicateItem('Duplicate item, %s' % item)
        self._do_autocommit()
968642
def update_retrieved_if_new(olditem, newitem, days=180, retrieved_pid='P813'):
    
    def ref_overwrite(oldref, newref, days):
        """
        If the newref is the same as the oldref except the retrieved date is `days` newer, return True
                                                       the retrieved date is NOT `days` newer, return False
        the refs are different, return True
        """
        if len(oldref) != len(newref):
            return True
        oldref_minus_retrieved = [x for x in oldref if x.get_prop_nr() != retrieved_pid]
        newref_minus_retrieved = [x for x in newref if x.get_prop_nr() != retrieved_pid]
        if not all(x in oldref_minus_retrieved for x in newref_minus_retrieved):
            return True
        oldref_retrieved = [x for x in oldref if x.get_prop_nr() == retrieved_pid]
        newref_retrieved = [x for x in newref if x.get_prop_nr() == retrieved_pid]
        if (len(newref_retrieved) != len(oldref_retrieved)) or not (
                len(newref_retrieved) == len(oldref_retrieved) == 1):
            return True
        datefmt = '+%Y-%m-%dT%H:%M:%SZ'
        retold = list([datetime.strptime(r.get_value()[0], datefmt) for r in oldref if r.get_prop_nr() == retrieved_pid])[0]
        retnew = list([datetime.strptime(r.get_value()[0], datefmt) for r in newref if r.get_prop_nr() == retrieved_pid])[0]
        return (retnew - retold).days >= days

    newrefs = newitem.references
    oldrefs = olditem.references
    if not (len(newrefs) == len(oldrefs) == 1):
        #print("overwriting refs, not 1")
        olditem.references = copy.deepcopy(newitem.references)
        return None
    overwrite = ref_overwrite(oldrefs[0], newrefs[0], days)
    if overwrite:
        #print("updating ref")
        olditem.references = newrefs
    else:
        #print("don't change")
        pass
1230747
private void checkDuplicates() throws Failure {
        int i;
        Variable v;
        String name;

        for (i = 0; i < vars.length; i++) {
            v = vars[i];
            name = v.getName();
            if (lookup(name) != v) {
                throw new Failure("duplicate variable name: " + name);
            }
        }
    }
1138162
private boolean isUnchangedAndShouldBeRemoved(CmsResource item) {

        if (item.getState().isUnchanged()) {
            return !m_keepOriginalUnchangedResources || !m_originalResources.contains(item);
        }
        return false;
    }
1328207
private boolean keyAlreadyExists(String newKey) {

        Collection<?> itemIds = m_table.getItemIds();
        for (Object itemId : itemIds) {
            if (m_table.getItem(itemId).getItemProperty(TableProperty.KEY).getValue().equals(newKey)) {
                return true;
            }
        }
        return false;
    }
1110267
function notEqual(actual, expected, message) {
    if (actual != expected) {
      this.pass(message);
    }
    else {
      this.fail({
        actual: actual,
        expected: expected,
        message: message,
        operator: "!=",
      });
    }
  }
557457
def _bin_update_items(self, items, replace_at_most_one,
                          replacements, leftovers):
        
        for key, values in items:
            # <values> is not a list or an empty list.
            like_list_not_str = self._quacks_like_a_list_but_not_str(values)
            if not like_list_not_str or (like_list_not_str and not values):
                values = [values]

            for value in values:
                # If the value is [], remove any existing leftovers with
                # key <key> and set the list of values itself to [],
                # which in turn will later delete <key> when [] is
                # passed to omdict.setlist() in
                # omdict._update_updateall().
                if value == []:
                    replacements[key] = []
                    leftovers[:] = [l for l in leftovers if key != l[0]]
                    continue

                # If there are existing items with key <key> that have
                # yet to be marked for replacement, mark that item's
                # value to be replaced by <value> by appending it to
                # <replacements>.  TODO: Refactor for clarity
                if (key in self and
                    (key not in replacements or
                     (key in replacements and
                      replacements[key] == []))):
                    replacements[key] = [value]
                elif (key in self and not replace_at_most_one and
                      len(replacements[key]) < len(self.values(key))):
                    replacements[key].append(value)
                else:
                    if replace_at_most_one:
                        replacements[key] = [value]
                    else:
                        leftovers.append((key, value))
1340538
def devaluate(actual, expected)
      same = (Set.new(expected) == Set.new(actual))
      same ? fail(expected_message.elements(expected).not_to_match(actual)) : pass(new_message.has_same_elements_as(expected))
    end
326971
def modified_created(instance):
    
    if 'modified' in instance and 'created' in instance and \
            instance['modified'] < instance['created']:
        msg = "'modified' (%s) must be later or equal to 'created' (%s)"
        return JSONError(msg % (instance['modified'], instance['created']),
                         instance['id'])
1286284
function(widget_config, storage_name, item_name, value) {

		if (!(storage_name in widget_config)) widget_config[storage_name] = {};
		if (Lava.schema.DEBUG && (item_name in widget_config[storage_name])) Lava.t("Duplicate item in storage: " + item_name);
		widget_config[storage_name][item_name] = value;

	}
639105
def add(self, item):
        
        if self._is_stringable(item) or self._is_qstring(item):
            self.items.append(PlainText(item))
        elif isinstance(item, MessageElement):
            self.items.append(item)
        elif item is None or (hasattr(item, 'isNull') and item.isNull()):
            self.items.append(PlainText(
                tr('Null (None) found from the data.')))
        elif isinstance(item, tuple) or isinstance(item, list):
            for i in item:
                # Recursive call
                self.add(i)
        else:
            raise InvalidMessageItemError(item, item.__class__)
454727
function(message) {
		var identifier = _makeIdentifier(message);
		if (typeof _filter[identifier] !== 'undefined' && _filter[identifier] < ((+new Date()) + 10 * 60000)) {
			console.error('duplicated error', identifier, message);
			return _filter[identifier];
		}

		_filter[identifier] = +new Date();
		return false;
	}
736984
public function onBeforeWrite()
    {
        // If a member with the same "unique identifier" already exists with a different ID, don't allow merging.
        // Note: This does not a full replacement for safeguards in the controller layer (e.g. in a registration form),
        // but rather a last line of defense against data inconsistencies.
        $identifierField = Member::config()->get('unique_identifier_field');
        if ($this->$identifierField) {
            // Note: Same logic as Member_Validator class
            $filter = [
                "\"Member\".\"$identifierField\"" => $this->$identifierField
            ];
            if ($this->ID) {
                $filter[] = array('"Member"."ID" <> ?' => $this->ID);
            }
            $existingRecord = DataObject::get_one(Member::class, $filter);

            if ($existingRecord) {
                throw new ValidationException(_t(
                    __CLASS__ . '.ValidationIdentifierFailed',
                    'Can\'t overwrite existing member #{id} with identical identifier ({name} = {value}))',
                    'Values in brackets show "fieldname = value", usually denoting an existing email address',
                    array(
                        'id' => $existingRecord->ID,
                        'name' => $identifierField,
                        'value' => $this->$identifierField
                    )
                ));
            }
        }

        // We don't send emails out on dev/tests sites to prevent accidentally spamming users.
        // However, if TestMailer is in use this isn't a risk.
        // @todo some developers use external tools, so emailing might be a good idea anyway
        if ((Director::isLive() || Injector::inst()->get(Mailer::class) instanceof TestMailer)
            && $this->isChanged('Password')
            && $this->record['Password']
            && static::config()->get('notify_password_change')
            && $this->isInDB()
        ) {
            Email::create()
                ->setHTMLTemplate('SilverStripe\\Control\\Email\\ChangePasswordEmail')
                ->setData($this)
                ->setTo($this->Email)
                ->setSubject(_t(
                    __CLASS__ . '.SUBJECTPASSWORDCHANGED',
                    "Your password has been changed",
                    'Email subject'
                ))
                ->send();
        }

        // The test on $this->ID is used for when records are initially created. Note that this only works with
        // cleartext passwords, as we can't rehash existing passwords. Checking passwordChangesToWrite prevents
        // recursion between changePassword and this method.
        if (!$this->ID || ($this->isChanged('Password') && !$this->passwordChangesToWrite)) {
            $this->changePassword($this->Password, false);
        }

        // save locale
        if (!$this->Locale) {
            $this->Locale = i18n::config()->get('default_locale');
        }

        parent::onBeforeWrite();
    }