For Server 2005,2008, duplicate a sequence with an identity table
188008
function GenID2008($seq='adodbseq',$start=1)
	{
		if($this->debug) ADOConnection::outp("<hr>CreateSequence($seq,$start)");
		sqlsrv_begin_transaction($this->_connectionID);
		$ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");
		if (!$ok) {
			$start -= 1;
			$this->Execute("create table $seq (id int)");//was float(53)
			$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
			if (!$ok) {
				if($this->debug) ADOConnection::outp("<hr>Error: ROLLBACK");
				sqlsrv_rollback($this->_connectionID);
				return false;
			}
		}
		$num = $this->GetOne("select id from $seq");
		sqlsrv_commit($this->_connectionID);
		return $num;
	}
736528
def _add_sequence(self, sequence):
        
        if sequence.identity not in self._sequences.keys():
            self._sequences[sequence.identity] = sequence
        else:
            raise ValueError("{} has already been defined".format(sequence.identity))
1266263
def insert_many(self, it):
        """"""
        unique_indexes = self._uniqueIndexes  # [ind for ind in self._indexes.values() if ind.is_unique]
        NO_SUCH_ATTR = object()
        new_objs = list(it)
        if unique_indexes:
            for ind in unique_indexes:
                ind_attr = ind.attr
                new_keys = dict((getattr(obj, ind_attr, NO_SUCH_ATTR), obj) for obj in new_objs)
                if not ind.accept_none and (None in new_keys or NO_SUCH_ATTR in new_keys):
                    raise KeyError("unique key cannot be None or blank for index %s" % ind_attr, 
                                    [ob for ob in new_objs if getattr(ob, ind_attr, NO_SUCH_ATTR) is None])
                if len(new_keys) < len(new_objs):
                    raise KeyError("given sequence contains duplicate keys for index %s" % ind_attr)
                for key in new_keys:
                    if key in ind:
                        obj = new_keys[key]
                        raise KeyError("duplicate unique key value '%s' for index %s" % (getattr(obj, ind_attr), ind_attr), 
                                       new_keys[key])
                    
        for obj in new_objs:
            self.obs.append(obj)
            for attr, ind in self._indexes.items():
                obval = getattr(obj, attr)
                ind[obval] = obj

        return self
1042329
def copy(self, tx_ins=None, tx_outs=None, lock_time=None,
             expiry_height=None, tx_joinsplits=None, joinsplit_pubkey=None,
             joinsplit_sig=None):
        '''
        
        '''
        return OverwinterTx(
            tx_ins=tx_ins if tx_ins is not None else self.tx_ins,
            tx_outs=tx_outs if tx_outs is not None else self.tx_outs,
            lock_time=(lock_time if lock_time is not None
                       else self.lock_time),
            expiry_height=(expiry_height if expiry_height is not None
                           else self.expiry_height),
            tx_joinsplits=(tx_joinsplits if tx_joinsplits is not None
                           else self.tx_joinsplits),
            joinsplit_pubkey=(joinsplit_pubkey if joinsplit_pubkey is not None
                              else self.joinsplit_pubkey),
            joinsplit_sig=(joinsplit_sig if joinsplit_sig is not None
                           else self.joinsplit_sig))
586731
public static List<Writable> getUniqueSequence(String columnName, Schema schema,
                    JavaRDD<List<List<Writable>>> sequenceData) {
        JavaRDD<List<Writable>> flattenedSequence = sequenceData.flatMap(new SequenceFlatMapFunction());
        return getUnique(columnName, schema, flattenedSequence);
    }
141443
def _update_digest_aliases(self, seq_id, seq):

        

        ir = bioutils.digests.seq_vmc_identifier(seq)
        seq_aliases = [
            {
                "namespace": ir["namespace"],
                "alias": ir["accession"],
            },
            {
                "namespace": "SHA1",
                "alias": bioutils.digests.seq_sha1(seq)
            },
            {
                "namespace": "MD5",
                "alias": bioutils.digests.seq_md5(seq)
            },
            {
                "namespace": "SEGUID",
                "alias": bioutils.digests.seq_seguid(seq)
            },
        ]
        for sa in seq_aliases:
            self.aliases.store_alias(seq_id=seq_id, **sa)
        return len(seq_aliases)
741984
function getUniqueIdentifier( root, libs, com ) {
  var id = root.attribs.id || ( com.name + ID++ );
  com.attr.id = id;
}
370929
def copy(self, version=None, tx_ins=None, tx_outs=None, lock_time=None,
             tx_joinsplits=None, joinsplit_pubkey=None, joinsplit_sig=None):
        '''
        
        '''
        return SproutTx(
            version=version if version is not None else self.version,
            tx_ins=tx_ins if tx_ins is not None else self.tx_ins,
            tx_outs=tx_outs if tx_outs is not None else self.tx_outs,
            lock_time=(lock_time if lock_time is not None
                       else self.lock_time),
            tx_joinsplits=(tx_joinsplits if tx_joinsplits is not None
                           else self.tx_joinsplits),
            joinsplit_pubkey=(joinsplit_pubkey if joinsplit_pubkey is not None
                              else self.joinsplit_pubkey),
            joinsplit_sig=(joinsplit_sig if joinsplit_sig is not None
                           else self.joinsplit_sig))
564002
def before_insert(mapper, conn, target):
        """"""

        # from identity import ObjectNumber
        # assert not target.fk_vid or not ObjectNumber.parse(target.fk_vid).revision

        if target.sequence_id is None:
            from ambry.orm.exc import DatabaseError
            raise DatabaseError('Must have sequence_id before insertion')

        # Check that the id column is always sequence id 1
        assert (target.name == 'id') == (target.sequence_id == 1), (target.name, target.sequence_id)

        Column.before_update(mapper, conn, target)
1184229
def new_unique_object(self, table_class, sequence_id=None, force_query=False, **kwargs):
        """"""
        from sqlalchemy.exc import IntegrityError
        from sqlalchemy.orm.exc import FlushError

        # If a sequence ID was specified, the caller is certain
        #  that there is no potential for conflicts,
        # so there is no need to commit here.
        if not sequence_id:
            commit = True
            sequence_id = self.next_sequence_id(table_class, force_query=force_query)
        else:
            commit = False

        o = table_class(
            d_vid=self.vid,
            **kwargs
        )

        o.update_id(sequence_id)

        if commit is False:
            return o

        self.commit()

        if self._database.driver == 'sqlite':
            # The Sqlite database can't have concurrency, so there no problem.
            self.session.add(o)
            self.commit()
            return o
        else: # Postgres. Concurrency is a bitch.
            table_name = table_class.__tablename__
            child_sequence_id = table_class.sequence_id.property.columns[0].name

        try:

            self.session.add(o)
            self.commit()
            return o

        except (IntegrityError, FlushError) as e:
            self.rollback()
            self.session.merge(self)
            print 'Failed'
            return None

        return
        # This is horrible, but it's the only thing that has worked for both
        # Sqlite and Postgres in both single processes and multiprocesses.
        d_vid = self.vid
        while True:
            try:
                self.session.add(o)
                self.commit()
                return o

            except (IntegrityError, FlushError) as e:

                self.rollback()

                self.session.expunge_all()
                ds = self._database.dataset(d_vid)
                sequence_id = ds.next_sequence_id(table_class, force_query=True)

                o.update_id(sequence_id)

            except Exception as e:

                print('Completely failed to get a new {} sequence_id; {}'.format(table_class, e))
                self.rollback()
                import traceback

                # This bit is helpful in a multiprocessing run.
                tb = traceback.format_exc()

                print(tb)
                raise
170479
function getChainIndexById(id, sequence){
    return sequence.map(function(el){
      return el._id;
    }).indexOf(id);
  }
662775
def add_sequence(self, sequence_id, sequence, ignore_bad_chains = False):
        ''''''

        # This is a sanity check. ClustalO allows ':' in the chain ID but ClustalW replaces ':' with '_' which breaks our parsing
        # All callers to add_sequence now need to replace ':' with '_' so that we can use ClustalW
        assert(sequence_id.find(':') == -1)

        if sequence_id in self.sequence_ids.values():
            raise Exception("Sequence IDs must be unique")
        if list(set(sequence)) == ['X']:
            if ignore_bad_chains:
                return
            else:
                raise MalformedSequenceException('The sequence contains only X characters. This will crash Clustal Omega.')
        self.records.append(">%s\n%s" % (sequence_id, "\n".join([sequence[i:i+80] for i in range(0, len(sequence), 80)])))
        self.sequence_ids[len(self.sequence_ids) + 1] = sequence_id
948858
def track_sequence(self, name, checkpoints, description='', max_rows=None):
        
        if name in self._tables:
            raise TableConflictError(name)
        if max_rows is None:
            max_rows = AnonymousUsageTracker.MAX_ROWS_PER_TABLE
        self.register_table(name, self.uuid, 'Sequence', description)
        self._tables[name] = Sequence(name, self, checkpoints, max_rows=max_rows)
770634
def tablecopy(tablename, newtablename, deep=False, valuecopy=False, dminfo={},
              endian='aipsrc', memorytable=False, copynorows=False):
    
    t = table(tablename, ack=False)
    return t.copy(newtablename, deep=deep, valuecopy=valuecopy,
                  dminfo=dminfo, endian=endian, memorytable=memorytable,
                  copynorows=copynorows)
419800
def copy(self):
        """"""
        other = Version(None)
        other.tokens = self.tokens[:]
        other.seps = self.seps[:]
        return other
940434
def dedup_sequence(sequence)
      sequence.uniq { |item| [item.class, item.middleware, item.config] }
    end
713156
function CreateSequence2008($seq='adodbseq',$start=1)
	{
		if($this->debug) ADOConnection::outp("<hr>CreateSequence($seq,$start)");
		sqlsrv_begin_transaction($this->_connectionID);
		$start -= 1;
		$this->Execute("create table $seq (id int)");//was float(53)
		$ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
		if (!$ok) {
			if($this->debug) ADOConnection::outp("<hr>Error: ROLLBACK");
			sqlsrv_rollback($this->_connectionID);
			return false;
		}
		sqlsrv_commit($this->_connectionID);
		return true;
	}