Convert all used annotation fields into bytes to write
495604
def calc_core_bytes(self):
        
        # The difference sample to write
        if len(self.sample) == 1:
            sampdiff = np.array([self.sample[0]])
        else:
            sampdiff = np.concatenate(([self.sample[0]], np.diff(self.sample)))

        # Create a copy of the annotation object with a
        # compact version of fields to write
        compact_annotation = copy.deepcopy(self)
        compact_annotation.compact_fields()


        # The optional fields to be written. Write if they are not None or all empty
        extra_write_fields = []

        for field in ['num', 'subtype', 'chan', 'aux_note']:
            if not isblank(getattr(compact_annotation, field)):
                extra_write_fields.append(field)

        data_bytes = []

        # Iterate across all fields one index at a time
        for i in range(len(sampdiff)):

            # Process the samp (difference) and sym items
            data_bytes.append(field2bytes('samptype', [sampdiff[i], self.symbol[i]]))

            # Process the extra optional fields
            for field in extra_write_fields:
                value = getattr(compact_annotation, field)[i]
                if value is not None:
                    data_bytes.append(field2bytes(field, value))

        # Flatten and convert to correct format
        data_bytes = np.array([item for sublist in data_bytes for item in sublist]).astype('u1')

        return data_bytes
814461
private com.google.code.siren4j.component.Field annotationToField(Siren4JActionField fieldAnno,
                                                                      EntityContext context)
            throws Siren4JException {
        FieldBuilder builder = FieldBuilder.newInstance();
        builder.setName(fieldAnno.name());
        if (ArrayUtils.isNotEmpty(fieldAnno.fieldClass())) {
            builder.setComponentClass(fieldAnno.fieldClass());
        }
        if(StringUtils.isNotBlank(fieldAnno.title())) {
            builder.setTitle(fieldAnno.title());
        }
        if (fieldAnno.max() > -1) {
            builder.setMax(fieldAnno.max());
        }
        if (fieldAnno.min() > -1) {
            builder.setMin(fieldAnno.min());
        }
        if (fieldAnno.maxLength() > -1) {
            builder.setMaxLength(fieldAnno.maxLength());
        }
        if (StringUtils.isNotBlank(fieldAnno.step())) {
            builder.setStep(fieldAnno.step());
        }
        if (fieldAnno.required()) {
            builder.setRequired(true);
        }
        if (StringUtils.isNotBlank(fieldAnno.pattern())) {
            builder.setPattern(fieldAnno.pattern());
        }
        if (StringUtils.isNotBlank(fieldAnno.type())) {
            builder.setType(FieldType.valueOf(fieldAnno.type().toUpperCase()));
        }
        if (StringUtils.isNotBlank(fieldAnno.value())) {
            builder.setValue(handleTokenReplacement(fieldAnno.value(), context));
        }
        if (ArrayUtils.isNotEmpty(fieldAnno.options())) {
            for (Siren4JFieldOption optAnno : fieldAnno.options()) {
                FieldOption opt = new FieldOption();
                if (StringUtils.isNotBlank(optAnno.title())) {
                    opt.setTitle(optAnno.title());
                }
                if (StringUtils.isNotBlank(optAnno.value())) {
                    opt.setValue(handleTokenReplacement(optAnno.value(), context));
                }
                opt.setOptionDefault(optAnno.optionDefault());
                if (ArrayUtils.isNotEmpty(optAnno.data())) {
                    for (Siren4JOptionData data : optAnno.data()) {
                        opt.putData(data.key(), handleTokenReplacement(data.value(), context));
                    }
                }
                builder.addOption(opt);
            }
        }
        if (StringUtils.isNotBlank(fieldAnno.optionsURL())) {
            builder.setOptionsURL(resolveUri(fieldAnno.optionsURL(), context, false));
        }
        if (StringUtils.isNotBlank(fieldAnno.placeHolder())) {
            builder.setPlaceholder(fieldAnno.placeHolder());
        }
        if(ArrayUtils.isNotEmpty(fieldAnno.metaData())) {
            Map<String, String> metaData = new HashMap();
            for(Siren4JMetaData mdAnno : fieldAnno.metaData()) {
                metaData.put(mdAnno.key(), handleTokenReplacement(mdAnno.value(), context));
            }
            builder.setMetaData(metaData);
        }
        return builder.build();
    }
260520
public static <X> String createFieldId(Field field, Collection<Annotation> annotations) {
        StringBuilder builder = new StringBuilder();
        builder.append(field.getDeclaringClass().getName());
        builder.append('.');
        builder.append(field.getName());
        builder.append(createAnnotationCollectionId(annotations));
        return builder.toString();
    }
178635
public AbstractBuilder getAnnotationTypeFieldsBuilder(
            AnnotationTypeWriter annotationTypeWriter)
    throws Exception {
        return AnnotationTypeFieldBuilder.getInstance(context,
            annotationTypeWriter.getAnnotationTypeDoc(),
            writerFactory.getAnnotationTypeFieldWriter(
                annotationTypeWriter));
    }
910129
public AbstractBuilder getAnnotationTypeFieldsBuilder(
            AnnotationTypeWriter annotationTypeWriter) {
        return AnnotationTypeFieldBuilder.getInstance(context,
                annotationTypeWriter.getAnnotationTypeElement(),
                writerFactory.getAnnotationTypeFieldWriter(annotationTypeWriter));
    }
936236
def convertfields(key_comm, obj, inblock=None):
    """"""
    # f_ stands for field_
    convinidd = ConvInIDD()
    if not inblock:
        inblock = ['does not start with N'] * len(obj)
    for i, (f_comm, f_val, f_iddname) in enumerate(zip(key_comm, obj, inblock)):
        if i == 0:
            # inblock[0] is the iddobject key. No conversion here
            pass
        else:
            obj[i] = convertafield(f_comm, f_val, f_iddname)
    return obj
1157562
def convert_to_annotation(file, output):
    """"""
    resource = parse_bel_resource(file)

    write_annotation(
        keyword=resource['Namespace']['Keyword'],
        values={k: '' for k in resource['Values']},
        citation_name=resource['Citation']['NameString'],
        description=resource['Namespace']['DescriptionString'],
        file=output
    )
217172
private static void writeField(final OutputStream out, final byte[] bytes)
      throws IOException {
    // All protocol messages are prefixed with their length in bytes, encoded
    // as a 32 bit unsigned integer.
    final ByteBuffer buffer = ByteBuffer.allocate(INT_BYTES + bytes.length);
    buffer.putInt(bytes.length);
    buffer.put(bytes);
    out.write(buffer.array());
    out.flush();
  }
371830
def write(self, f):
        
        rdf = ET.Element(NS('rdf', 'RDF'), nsmap=XML_NS)

        # TODO: TopLevel Annotations
        sequence_values = sorted(self._sequences.values(), key=lambda x: x.identity)
        self._add_to_root(rdf, sequence_values)
        component_values = sorted(self._components.values(), key=lambda x: x.identity)
        self._add_to_root(rdf, component_values)
        model_values = sorted(self._models.values(), key=lambda x: x.identity)
        self._add_to_root(rdf, model_values)
        module_values = sorted(self._modules.values(), key=lambda x: x.identity)
        self._add_to_root(rdf, module_values)
        collection_values = sorted(self._collections.values(), key=lambda x: x.identity)
        self._add_to_root(rdf, collection_values)
        annotation_values = sorted(self._annotations.values(), key=lambda x: x.identity)
        self._add_to_root(rdf, annotation_values)

        f.write(ET.tostring(rdf,
                            pretty_print=True,
                            xml_declaration=True,
                            encoding='utf-8'))
433124
public static final void convertAnnotations(Tree config, Annotation[] annotations)
			throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		for (Annotation annotation : annotations) {

			// Create entry for annotation
			String annotationName = annotation.toString();
			int i = annotationName.lastIndexOf('.');
			if (i > -1) {
				annotationName = annotationName.substring(i + 1);
			}
			i = annotationName.indexOf('(');
			if (i > -1) {
				annotationName = annotationName.substring(0, i);
			}
			if (annotationName.length() > 1) {
				annotationName = Character.toLowerCase(annotationName.charAt(0)) + annotationName.substring(1);
			} else {
				annotationName = annotationName.toLowerCase();
			}
			if ("name".equals(annotationName) || "override".equals(annotationName)) {
				continue;
			}
			Tree annotationMap = config.putMap(annotationName);

			// Add annotation values
			Class<? extends Annotation> type = annotation.annotationType();
			Method[] members = type.getDeclaredMethods();
			for (Method member : members) {
				member.setAccessible(true);
				String propName = member.getName();
				Object propValue = member.invoke(annotation);
				annotationMap.putObject(propName, propValue);
				Tree newChild = annotationMap.get(propName);
				if (newChild.size() < 1) {
					newChild.remove();
				}
			}
			int size = annotationMap.size();
			if (size == 0) {
				annotationMap.remove();
			} else if (size == 1) {
				Tree value = annotationMap.getFirstChild();
				if (value != null && "value".equals(value.getName())) {
					annotationMap.setObject(value.asObject());
				}
			}
		}
	}
600912
int writeJavaAnnotations(List<Attribute.Compound> attrs) {
        if (attrs.isEmpty()) return 0;
        ListBuffer<Attribute.Compound> visibles = new ListBuffer<Attribute.Compound>();
        ListBuffer<Attribute.Compound> invisibles = new ListBuffer<Attribute.Compound>();
        for (Attribute.Compound a : attrs) {
            switch (types.getRetention(a)) {
            case SOURCE: break;
            case CLASS: invisibles.append(a); break;
            case RUNTIME: visibles.append(a); break;
            default: ;// /* fail soft */ throw new AssertionError(vis);
            }
        }

        int attrCount = 0;
        if (visibles.length() != 0) {
            int attrIndex = writeAttr(names.RuntimeVisibleAnnotations);
            databuf.appendChar(visibles.length());
            for (Attribute.Compound a : visibles)
                writeCompoundAttribute(a);
            endAttr(attrIndex);
            attrCount++;
        }
        if (invisibles.length() != 0) {
            int attrIndex = writeAttr(names.RuntimeInvisibleAnnotations);
            databuf.appendChar(invisibles.length());
            for (Attribute.Compound a : invisibles)
                writeCompoundAttribute(a);
            endAttr(attrIndex);
            attrCount++;
        }
        return attrCount;
    }
547358
def convertallfields(data, commdct, block=None):
    """"""
    # import pdbdb; pdb.set_trace()
    for key in list(data.dt.keys()):
        objs = data.dt[key]
        for i, obj in enumerate(objs):
            key_i = data.dtls.index(key)
            key_comm = commdct[key_i]
            try:
                inblock = block[key_i]
            except TypeError as e:
                inblock = None
            obj = convertfields(key_comm, obj, inblock)
            objs[i] = obj
658657
def serialize(self, obj, fields):
        

        data = {}
        remaining_fields = []
        for field in fields:
            if callable(field):  # Callable
                data[field.__name__] = field(obj)
            elif hasattr(self, field) and callable(getattr(self, field)):  # Method on the view
                data[field] = getattr(self, field)(obj)
            elif hasattr(obj, field):  # Callable/property/field on the model
                attr = getattr(obj, field)
                if isinstance(attr, Model):
                    data[field] = attr.pk
                elif isinstance(attr, Manager):
                    data[field] = [item['pk'] for item in attr.values('pk')]
                elif callable(attr):  # Callable on the model
                    data[field] = attr()
                else:
                    remaining_fields.append(field)
            else:
                raise AttributeError('Invalid field: %s' % field)

        # Add on db fields
        serializer = Serializer()
        serializer.serialize([obj], fields=list(remaining_fields))
        data.update(serializer.getvalue()[0]['fields'])

        # Any remaining fields should be properties on the model
        remaining_fields = set(remaining_fields) - set(data.keys())

        for field in remaining_fields:
            data[field] = getattr(obj, field)

        return data
684972
def encode_annotation(obj):
    """"""
    warnings.warn("deprecated. Please use bioc.biocxml.encoder.encode_annotation",
                  DeprecationWarning)
    return bioc.biocxml.encoder.encode_annotation(obj)
1191774
function serializeStringFields(fields) {
  let length = 0;
  fields.forEach((field) => {
    length += (field.length + 4);
  });
  let buffer = new Buffer(4 + length);
  let offset = base_serializers.uint32(length, buffer, 0);

  fields.forEach((field) => {
    offset = base_serializers.string(field, buffer, offset);
  });
  return buffer;
}
517588
function transferAnnotations (doc, path, offset, newPath, newOffset) {
  var index = doc.getIndex('annotations')
  var annotations = index.get(path, offset)
  for (let i = 0; i < annotations.length; i++) {
    let a = annotations[i]
    var isInside = (offset > a.start.offset && offset < a.end.offset)
    var start = a.start.offset
    var end = a.end.offset
    // 1. if the cursor is inside an annotation it gets either split or truncated
    if (isInside) {
      // create a new annotation if the annotation is splittable
      if (a.canSplit()) {
        let newAnno = a.toJSON()
        newAnno.id = uuid(a.type + '_')
        newAnno.start.path = newPath
        newAnno.start.offset = newOffset
        newAnno.end.path = newPath
        newAnno.end.offset = newOffset + a.end.offset - offset
        doc.create(newAnno)
      }
      // in either cases truncate the first part
      let newStartOffset = a.start.offset
      let newEndOffset = offset
      // if after truncate the anno is empty, delete it
      if (newEndOffset === newStartOffset) {
        doc.delete(a.id)
      // ... otherwise update the range
      } else {
        // TODO: Use coordintate ops!
        if (newStartOffset !== start) {
          doc.set([a.id, 'start', 'offset'], newStartOffset)
        }
        if (newEndOffset !== end) {
          doc.set([a.id, 'end', 'offset'], newEndOffset)
        }
      }
    // 2. if the cursor is before an annotation then simply transfer the annotation to the new node
    } else if (a.start.offset >= offset) {
      // TODO: Use coordintate ops!
      // Note: we are preserving the annotation so that anything which is connected to the annotation
      // remains valid.
      doc.set([a.id, 'start', 'path'], newPath)
      doc.set([a.id, 'start', 'offset'], newOffset + a.start.offset - offset)
      doc.set([a.id, 'end', 'path'], newPath)
      doc.set([a.id, 'end', 'offset'], newOffset + a.end.offset - offset)
    }
  }

  // TODO: fix support for container annotations
  // // same for container annotation anchors
  // index = doc.getIndex('container-annotation-anchors');
  // var anchors = index.get(path);
  // var containerAnnoIds = [];
  // forEach(anchors, function(anchor) {
  //   containerAnnoIds.push(anchor.id);
  //   var start = anchor.offset;
  //   if (offset <= start) {
  //     // TODO: Use coordintate ops!
  //     let coor = anchor.isStart?'start':'end'
  //     doc.set([anchor.id, coor, 'path'], newPath);
  //     doc.set([anchor.id, coor, 'offset'], newOffset + anchor.offset - offset);
  //   }
  // });
  // // check all anchors after that if they have collapsed and remove the annotation in that case
  // forEach(uniq(containerAnnoIds), function(id) {
  //   var anno = doc.get(id);
  //   var annoSel = anno.getSelection();
  //   if(annoSel.isCollapsed()) {
  //     // console.log("...deleting container annotation because it has collapsed" + id);
  //     doc.delete(id);
  //   }
  // });
}
368255
private void writeObjectToField(String fieldname, Object value, Object object, Object alternative)
        throws Exception {
        Object target = object != null ? object : alternative;
        try {
            FieldUtils.writeField(target, fieldname, value, true);
        } catch (Exception e) {
            throw new IllegalArgumentException(String.format("Unable to write value '%s' to field '%s' of object %s",
                value.toString(), fieldname, target.getClass().getName()));
        }
    }