text:
package pl.edu.icm.crmanager.model;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Transient;

import org.apache.commons.collections.CollectionUtils;
import org.hibernate.Hibernate;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import pl.edu.icm.crmanager.exception.CrmRuntimeException;
import pl.edu.icm.crmanager.utils.CrmReflectionUtil;
import pl.edu.icm.sedno.common.model.ADataObject;
import pl.edu.icm.sedno.common.model.DataObject;
import pl.edu.icm.sedno.common.util.PropertyChange;

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;

@SuppressWarnings("serial")
@Entity(name="crm_revision")
@Table(appliesTo="crm_revision", indexes=
    @Index(
            name="crm_revision_rootModPoint_idx",
            columnNames = {"root_mod_point_class", "root_mod_point_id"}
          ))
@javax.persistence.SequenceGenerator(name = "seq_crm_revision", allocationSize = 10, sequenceName = "seq_crm_revision")
public class Revision extends ADataObject {

	private static final Logger logger = LoggerFactory.getLogger(Revision.class);

	public enum RevisionStatus {TRANSIENT, NEW, ACCEPTED, CANCELLED};

	private int 				idRevision;
	private List<ChangeRequest> changeRequests;
	private RevisionStatus      revisionStatus;
	private String              authorId;
	private Date                cancelledDate;
	private String              cancelledUserId;
    private Date                acceptedDate;
    private String              acceptedUserId;

    private String              rootModPointClass;
    private int                 rootModPointId;
    @Transient
    private DataObject    	    rootModPoint;

    @Deprecated
    private Set<DataObject>     nonCrmModPoints = Sets.newHashSet();

	@Transient
	private CrmSession session;

	public Revision() {}

	@Override
	public void initialize() {
	    Hibernate.initialize(getChangeRequests());
	}

	public Revision(CrmSession session, String authorId) {
	    this.revisionStatus = RevisionStatus.TRANSIENT;
	    this.session = session;
	    this.authorId = authorId;
	    changeRequests = new ArrayList<ChangeRequest>(10);
	}

	public void cleanSession() {
		this.session = null;
	}

	/**
	 * prepare for sending via Remoting
	 */
	@Id
	@Column(name="id_revision")
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_crm_revision")
	public int getIdRevision() {
		return idRevision;
	}

	@OneToMany(mappedBy="revision", cascade=CascadeType.ALL)
	@Basic(fetch=FetchType.LAZY)
	//@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	@OrderBy("requestNo")
	public List<ChangeRequest> getChangeRequests() {
		return changeRequests;
	}

	@Column(length=150, name="root_mod_point_class")
	public String getRootModPointClass() {
        return rootModPointClass;
    }

	@Column(name="root_mod_point_id")
	public int getRootModPointId() {
        return rootModPointId;
    }

	@Transient
	public ChangeRequest getLastCR() {
	    return getChangeRequests().get(getChangeRequests().size()-1);
	}

	@Transient
	public boolean isOpen() {
		return getRevisionStatus() == RevisionStatus.NEW;
	}

	@Enumerated(EnumType.STRING)
	@Column(name="revision_status")
	public RevisionStatus getRevisionStatus() {
		return revisionStatus;
	}

	@Column(length=150, name="author_id")
	public String getAuthorId() {
        return authorId;
    }

	@Column(length=150, name="accepted_user_id")
	public String getAcceptedUserId() {
        return acceptedUserId;
    }

	@Column(length=150, name="cancelled_user_id")
	public String getCancelledUserId() {
        return cancelledUserId;
    }

	public Date getCancelledDate() {
        return cancelledDate;
    }

	public Date getAcceptedDate() {
        return acceptedDate;
    }

	public void moveToNew() {
        if (getRevisionStatus() != RevisionStatus.TRANSIENT) {
            throw new CrmRuntimeException("accept() - state error, revisionStatus != TRANSIENT)");
        }
        setRevisionStatus(RevisionStatus.NEW);
	}

	public void accept(String acceptedBy) {
        if (getRevisionStatus() != RevisionStatus.NEW && getRevisionStatus() != RevisionStatus.TRANSIENT) {
            throw new CrmRuntimeException("accept() - state error, revisionStatus not in (NEW, TRANSIENT)");
        }
	    setRevisionStatus(RevisionStatus.ACCEPTED);
	    setAcceptedDate(new Date());
	    setAcceptedUserId(acceptedBy);
	}

	public void cancel(String cancelledBy) {
        if (getRevisionStatus() != RevisionStatus.NEW) {
            throw new CrmRuntimeException("cancel() - state error, revisionStatus != NEW");
        }
        setRevisionStatus(RevisionStatus.CANCELLED);
        setCancelledDate(new Date());
        setCancelledUserId(cancelledBy);
	}

	@Transient
	public List<ChangeRequest> getChangeRequests(RecType ofType) {
	    List<ChangeRequest> ret= new ArrayList<ChangeRequest>();
        for (ChangeRequest ch : changeRequests) {
            if (ch.getRecType().equals(ofType))
                ret.add(ch);
        }
        return ret;
	}

	@Transient
	public DataObject getRootModPoint() {
		return rootModPoint;
	}

    private void appendRecord(ChangeRequest rec) {
        getChangeRequests().add(rec);

        rec.setRequestNo(getChangeRequests().size());
        rec.setRevision(this);
    }

    private void appendRecords(List<ChangeRequest> recs) {
    	for (ChangeRequest rec : recs) {
    		appendRecord(rec);
    	}
    }

    /**
     * pomocnicza kolekcja, służy do persystowania zmian na getterach z {@link CrmTransparent}
     */
    @Transient
    @Deprecated
    public Set<DataObject> getNonCrmModPoints() {
		return nonCrmModPoints;
	}

    @Deprecated
    public void addNonCrmModPoint(DataObject modPoint) {
    	getNonCrmModPoints().add(modPoint);
    }

    public void resolveTransientReferences() {
        int r = 0;
        for (ChangeRequest ch : changeRequests) {
            r += ch.tryToResolveTransientReference();
        }

        if (getRootModPoint() != null && getRootModPointId() == 0) {
        	setRootModPointId(getRootModPoint().getId());
        }

        if (r > 0) {
            logger.debug("resolveTransientReferences() : "+r + " transient reference(s) resolved");
        }
    }

    public void checkTransientReferences() {
        for (ChangeRequest ch : changeRequests) {
            if  (ch.hasTransientReference())
                throw new CrmRuntimeException("found transient reference in changeRequest, it can't be commited - "+ch.getShortDesc());
        }
    }

    public void registerDelete(DataObject deletedNode) {
    	checkCommited();

    	deletedNode.setDataObjectStatus(DataObjectStatus.DELETED);
        ChangeRequest change = ChangeRequestFactory.createForDeletedObject(deletedNode);
		appendRecord(change);
    }

    public void registerNewObject(DataObject node) {
        checkCommited();

        //already added?
        for (ChangeRequest cr : getChangeRequests()) {
            if (cr.getRecType() == RecType.NEW_OBJECT &&
                node.equals(cr.getNode__())) {
                return;
            }
        }

        node.setDataObjectStatus(DataObjectStatus.NEW);

        ChangeRequest change = ChangeRequestFactory.createForNewObject(node);
		appendRecord(change);
    }

    public void registerChildAdd(DataObject node, String getterName, DataObject child) {
        checkCommited();

        ChangeRequest change = ChangeRequestFactory.createChildAdd(node, getterName, child);
		appendRecord(change);
    }

    public void registerChildRemove(DataObject node, String getterName, DataObject child) {
        checkCommited();

        ChangeRequest change = ChangeRequestFactory.createChildRemove(node, getterName, child);
		appendRecord(change);
    }

    public void registerValueChange(DataObject node, String getterName, Object oldValue, Object newValue, Class valueClass)
    {
        if(Objects.equal(oldValue, newValue))
        	return;

    	checkCommited();

    	ValueType valueType = ValueType.determineValueType(valueClass);

    	if (valueType == ValueType.COMPLEX_STRING_EMBEDDABLE) {
    		List<ChangeRequest> changes = ChangeRequestFactory.detectChangesOnComplexEmbeddable(node, getterName, oldValue, newValue, valueClass);
    		appendRecords(changes);
    	}
    	else {
    		ChangeRequest change = ChangeRequestFactory.createChange(node, getterName, oldValue, newValue, valueClass);
    		appendRecord(change);
    	}
    }

    @Transient
    public int getChangesCount() {
        return changeRequests.size();
    }

    @Transient
    public String getShortDesc() {
        StringBuffer buf = new StringBuffer();

        buf.append("\n revision["+getIdRevision()+"] " + revisionStatus+", rootModPoint: "+getRootModPointClass()+"#"+getRootModPointId());

        if (changeRequests.size() > 0 ) {
        	buf.append("\n");
	        buf.append(". changes: \n");

	        for (ChangeRequest ch : changeRequests) {
	            buf.append(".. "+ ch.getShortDesc()+" \n");

	            if (CollectionUtils.isNotEmpty(ch.getPropertyChanges__())) {
	            	for (PropertyChange pc : ch.getPropertyChanges__()) {
	            		buf.append(".. .."+ pc +" \n");
	            	}
	            }
	        }
        } else {
        	buf.append(" no changes \n");
        }
        return buf.toString();
    }

    /**
     * true jeśli w zbiorze cr'ów jest przynajmniej jeden z {@link ChangeRequest#isChangeImportant()} == true
     */
    @Transient
    public boolean isChangeImportatnt() {
        for (ChangeRequest cr : changeRequests) {
            if (cr.isChangeImportant())
                return true;
        }

        return false;
    }

    /**
     * combo setter
     */
    public void setRootModPointCombo(DataObject node) {
        setRootModPoint__(node);

        this.rootModPointClass = getRootModPoint().getClass().getName();
        this.rootModPointId =    getRootModPoint().getId();
    }

    /**
     * this setter should be used only to initialize transient references
     */
    public void setRootModPoint__(DataObject node) {
    	Preconditions.checkState(this.rootModPoint == null);

    	DataObject ref =  (DataObject)CrmReflectionUtil.unproxyCH(node);
        this.rootModPoint = ref;
    }

    @Deprecated
    private Object unproxyCH(Object obj) {
        if (obj == null) {
            return null;
        }

        if (!(obj instanceof DataObject)) {
            return obj;
        }

        return CrmReflectionUtil.unproxyCH((DataObject)obj);
    }

    private void checkCommited() {
        if (!session.isOpened()) {
            throw new CrmRuntimeException("you can't write to commited revision");
        }
    }

    private void setRevisionStatus(RevisionStatus revisionStatus) {
        this.revisionStatus = revisionStatus;
    }

    public void setIdRevision(int idRevision) {
        this.idRevision = idRevision;
    }

    public void setAuthorId(String authorId) {
        this.authorId = authorId;
    }

    public void setChangeRequests(List<ChangeRequest> changeRequests) {
        this.changeRequests = changeRequests;
    }

    private void setCancelledDate(Date cancelledDate) {
        this.cancelledDate = cancelledDate;
    }

    private void setCancelledUserId(String cancelledUserId) {
        this.cancelledUserId = cancelledUserId;
    }

    private void setAcceptedDate(Date acceptedDate) {
        this.acceptedDate = acceptedDate;
    }

    private void setAcceptedUserId(String acceptedUserId) {
        this.acceptedUserId = acceptedUserId;
    }

    private void setRootModPointClass(String rootModPointClass) {
        this.rootModPointClass = rootModPointClass;
    }

    private void setRootModPointId(int rootModPointId) {
        this.rootModPointId = rootModPointId;
    }
}


text:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers/index';

const createStoreWithMiddleware = applyMiddleware(
  thunk
)(createStore);

const store = createStoreWithMiddleware(rootReducer);

export default store;

redpajama_set_name: RedPajamaGithub


text:
package main

type Action interface {
	Run() error
}


text:
void logistic_regression_trainer_destroy(logistic_regression_trainer_t *self) {
    if (self == NULL) return;

    if (self->feature_ids != NULL) {
        trie_destroy(self->feature_ids);
    }

    if (self->label_ids != NULL) {
        kh_destroy(str_uint32, self->label_ids);
    }

    if (self->unique_columns != NULL) {
        kh_destroy(int_uint32, self->unique_columns);
    }

    if (self->batch_columns != NULL) {
        uint32_array_destroy(self->batch_columns);
    }

    if (self->batch_weights != NULL) {
        double_matrix_destroy(self->batch_weights);
    }

    if (self->gradient != NULL) {
        double_matrix_destroy(self->gradient);
    }

    free(self);
}

static logistic_regression_trainer_t *logistic_regression_trainer_init(trie_t *feature_ids, khash_t(str_uint32) *label_ids) {
    if (feature_ids == NULL || label_ids == NULL) return NULL;

    logistic_regression_trainer_t *trainer = malloc(sizeof(logistic_regression_trainer_t));
    if (trainer == NULL) return NULL;

    trainer->feature_ids = feature_ids;
    // Add one feature for the bias unit
    trainer->num_features = trie_num_keys(feature_ids) + 1;

    trainer->label_ids = label_ids;
    trainer->num_labels = kh_size(label_ids);

    trainer->gradient = double_matrix_new_zeros(INITIAL_FEATURE_BATCH_SIZE, trainer->num_labels);
    if (trainer->gradient == NULL) {
        goto exit_trainer_created;
    }

    trainer->unique_columns = kh_init(int_uint32);
    if (trainer->unique_columns == NULL) {
        goto exit_trainer_created;
    }
    trainer->batch_columns = uint32_array_new_size(INITIAL_FEATURE_BATCH_SIZE);
    if (trainer->batch_columns == NULL) {
        goto exit_trainer_created;
    }

    trainer->batch_weights = double_matrix_new_zeros(INITIAL_FEATURE_BATCH_SIZE, trainer->num_labels);
    if (trainer->batch_weights == NULL) {
        goto exit_trainer_created;
    }

    trainer->epochs = 0;

    return trainer;

exit_trainer_created:
    logistic_regression_trainer_destroy(trainer);
    return NULL;
}

logistic_regression_trainer_t *logistic_regression_trainer_init_sgd(trie_t *feature_ids, khash_t(str_uint32) *label_ids, bool fit_intercept, regularization_type_t reg_type, double lambda, double gamma_0) {
    logistic_regression_trainer_t *trainer = logistic_regression_trainer_init(feature_ids, label_ids);
    if (trainer == NULL) {
        return NULL;
    }

    trainer->optimizer_type = LOGISTIC_REGRESSION_OPTIMIZER_SGD;
    trainer->optimizer.sgd = sgd_trainer_new(trainer->num_features, trainer->num_labels, fit_intercept, reg_type, lambda, gamma_0);
    if (trainer->optimizer.sgd == NULL) {
        logistic_regression_trainer_destroy(trainer);
        return NULL;
    }

    return trainer;
}

logistic_regression_trainer_t *logistic_regression_trainer_init_ftrl(trie_t *feature_ids, khash_t(str_uint32) *label_ids, double lambda1, double lambda2, double alpha, double beta) {
    logistic_regression_trainer_t *trainer = logistic_regression_trainer_init(feature_ids, label_ids);
    if (trainer == NULL) {
        return NULL;
    }

    trainer->optimizer_type = LOGISTIC_REGRESSION_OPTIMIZER_FTRL;
    bool fit_intercept = true;
    log_info("num_features = %zu\n", trainer->num_features);
    trainer->optimizer.ftrl = ftrl_trainer_new(trainer->num_features, trainer->num_labels, fit_intercept, alpha, beta, lambda1, lambda2);
    if (trainer->optimizer.sgd == NULL) {
        logistic_regression_trainer_destroy(trainer);
        return NULL;
    }

    return trainer;
}

bool logistic_regression_trainer_reset_params_sgd(logistic_regression_trainer_t *self, double lambda, double gamma_0) {
    if (self == NULL || self->optimizer_type != LOGISTIC_REGRESSION_OPTIMIZER_SGD || self->optimizer.sgd == NULL) return false;

    sgd_trainer_t *sgd_trainer = self->optimizer.sgd;
    return sgd_trainer_reset_params(sgd_trainer, lambda, gamma_0);
}

bool logistic_regression_trainer_reset_params_ftrl(logistic_regression_trainer_t *self, double alpha, double beta, double lambda1, double lambda2) {
    if (self == NULL || self->optimizer_type != LOGISTIC_REGRESSION_OPTIMIZER_FTRL || self->optimizer.ftrl == NULL) return false;

    ftrl_trainer_t *ftrl_trainer = self->optimizer.ftrl;
    return ftrl_trainer_reset_params(ftrl_trainer, alpha, beta, lambda1, lambda2);
}

static double logistic_regression_trainer_minibatch_cost_params(logistic_regression_trainer_t *self, feature_count_array *features, cstring_array *labels, bool regularized) {
    size_t n = self->num_labels;

    sparse_matrix_t *x = feature_matrix(self->feature_ids, features);
    uint32_array *y = label_vector(self->label_ids, labels);
    double_matrix_t *p_y = double_matrix_new_aligned(x->m, n, 16);
    double_matrix_zero(p_y);

    double cost;

    if (!sparse_matrix_add_unique_columns_alias(x, self->unique_columns, self->batch_columns)) {
        cost = -1.0;
        goto exit_cost_matrices_created;
    }

    double_matrix_t *weights = logistic_regression_trainer_get_weights(self);

    cost = logistic_regression_cost_function(weights, x, y, p_y);

    if (regularized) {
        if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_SGD) {
            sgd_trainer_t *sgd_trainer = self->optimizer.sgd;
            double reg_cost = stochastic_gradient_descent_reg_cost(sgd_trainer, self->batch_columns, x->m);
            cost += reg_cost;
        } else if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_FTRL) {
            ftrl_trainer_t *ftrl_trainer = self->optimizer.ftrl;
            double reg_cost = ftrl_reg_cost(ftrl_trainer, weights, self->batch_columns, x->m);
            cost += reg_cost;
        }
    }

exit_cost_matrices_created:
    double_matrix_destroy(p_y);
    uint32_array_destroy(y);
    sparse_matrix_destroy(x);
    return cost;
}

inline double logistic_regression_trainer_minibatch_cost(logistic_regression_trainer_t *self, feature_count_array *features, cstring_array *labels) {
    return logistic_regression_trainer_minibatch_cost_params(self, features, labels, false);
}

inline double logistic_regression_trainer_minibatch_cost_regularized(logistic_regression_trainer_t *self, feature_count_array *features, cstring_array *labels) {
    return logistic_regression_trainer_minibatch_cost_params(self, features, labels, true);
}

double logistic_regression_trainer_regularization_cost(logistic_regression_trainer_t *self, size_t m) {
    if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_SGD) {
        sgd_trainer_t *sgd_trainer = self->optimizer.sgd;
        return stochastic_gradient_descent_reg_cost(sgd_trainer, NULL, m);
    } else if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_FTRL) {
        ftrl_trainer_t *ftrl_trainer = self->optimizer.ftrl;
        double_matrix_t *weights = logistic_regression_trainer_get_weights(self);
        return ftrl_reg_cost(ftrl_trainer, weights, NULL, m);
    }
    return 0.0;
}

bool logistic_regression_trainer_train_minibatch(logistic_regression_trainer_t *self, feature_count_array *features, cstring_array *labels) {
    double_matrix_t *gradient = self->gradient;

    sparse_matrix_t *x = feature_matrix(self->feature_ids, features);
    if (x == NULL) {
        log_error("x == NULL\n");
        return false;
    }
    uint32_array *y = label_vector(self->label_ids, labels);
    if (y == NULL) {
        log_error("y == NULL\n");
        return false;
    }

    bool ret = false;

    if (!sparse_matrix_add_unique_columns_alias(x, self->unique_columns, self->batch_columns)) {
        log_error("Unique columns failed\n");
        return false;
    }

    if(!double_matrix_resize(gradient, self->batch_columns->n, self->num_labels)) {
        log_error("Gradient resize failed\n");
        return false;
    }

    double_matrix_t *weights = logistic_regression_trainer_get_weights(self);
    if (weights == NULL) {
        log_error("Error getting weights\n");
        return false;
    }
    size_t batch_size = x->m;

    double_matrix_t *p_y = double_matrix_new_aligned(batch_size, self->num_labels, 16);
    if (p_y == NULL) {
        log_error("Error allocating p_y\n");
        return false;
    }

    if (!logistic_regression_gradient(weights, gradient, x, y, p_y)) {
        log_error("Gradient failed\n");
        goto exit_matrices_created;
    }

    if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_SGD) {
        ret = stochastic_gradient_descent_update_sparse(self->optimizer.sgd, gradient, self->batch_columns, batch_size);
    } else if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_FTRL) {
        ret = ftrl_update_gradient(self->optimizer.ftrl, gradient, weights, self->batch_columns, batch_size);
        if (!ret) {
            log_error("ftrl_update_gradient failed\n");
        }
    } else {
        ret = false;
    }

exit_matrices_created:
    double_matrix_destroy(p_y);
    uint32_array_destroy(y);
    sparse_matrix_destroy(x);
    return ret;
}

double_matrix_t *logistic_regression_trainer_get_weights(logistic_regression_trainer_t *self) {
    if (self == NULL) return NULL;

    size_t m = self->batch_columns->n;
    size_t n = self->num_labels;
    double_matrix_t *batch_weights = self->batch_weights;
    if (batch_weights == NULL || !double_matrix_resize(batch_weights, m, n)) {
        return NULL;
    }
    double_matrix_zero(batch_weights);

    if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_SGD) {
        if (self->optimizer.sgd == NULL) return NULL;

        if (!stochastic_gradient_descent_set_regularized_weights(self->optimizer.sgd, self->batch_weights, self->batch_columns)) {
            return NULL;
        }

        return batch_weights;
    } else if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_FTRL) {
        if (self->optimizer.ftrl == NULL) return NULL;

        if (!ftrl_set_weights(self->optimizer.ftrl, batch_weights, self->batch_columns)) {
            return NULL;
        }

        return batch_weights;

    }
    return NULL;
}

double_matrix_t *logistic_regression_trainer_get_regularized_weights(logistic_regression_trainer_t *self) {
    if (self == NULL) return NULL;

    if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_SGD) {
        if (self->optimizer.sgd == NULL) return NULL;
        return stochastic_gradient_descent_get_weights(self->optimizer.sgd);
    } else if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_FTRL) {
        if (self->optimizer.ftrl == NULL) return NULL;
        if (!ftrl_set_weights(self->optimizer.ftrl, self->batch_weights, NULL)) {
            return NULL;
        }
        return self->batch_weights;
    }
    return NULL;
}

double_matrix_t *logistic_regression_trainer_final_weights(logistic_regression_trainer_t *self) {
    if (self == NULL) return NULL;

    if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_SGD) {
        if (self->optimizer.sgd == NULL) return NULL;
        double_matrix_t *weights = stochastic_gradient_descent_get_weights(self->optimizer.sgd);
        self->optimizer.sgd->theta = NULL;
        return weights;
    } else if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_FTRL) {
        if (self->optimizer.ftrl == NULL) return NULL;
        return ftrl_weights_finalize(self->optimizer.ftrl);
    }
    return NULL;
}

sparse_matrix_t *logistic_regression_trainer_final_weights_sparse(logistic_regression_trainer_t *self) {
    if (self == NULL) return NULL;

    if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_SGD) {
        if (self->optimizer.sgd == NULL) return NULL;
        return stochastic_gradient_descent_get_weights_sparse(self->optimizer.sgd);
    } else if (self->optimizer_type == LOGISTIC_REGRESSION_OPTIMIZER_FTRL) {
        if (self->optimizer.ftrl == NULL) return NULL;
        return ftrl_weights_finalize_sparse(self->optimizer.ftrl);
    }

    return NULL;
}


text:
package org.clulab.processors.corenlp

import java.util
import org.clulab.processors.{Document, Sentence}
import org.clulab.struct._
import edu.stanford.nlp.ling.CoreAnnotations.{IndexAnnotation, TokensAnnotation}
import edu.stanford.nlp.ling.CoreLabel
import edu.stanford.nlp.pipeline.Annotation
import edu.stanford.nlp.semgraph.SemanticGraph
import edu.stanford.nlp.trees.SemanticHeadFinder
import edu.stanford.nlp.trees.TreeCoreAnnotations.{BinarizedTreeAnnotation, TreeAnnotation}
import edu.stanford.nlp.util.{ArrayCoreMap, CoreMap}

import edu.stanford.nlp.trees.{Tree => StanfordTree}
import org.clulab.processors.clu.tokenizer.TokenizerStepNormalization

import scala.collection.JavaConverters._

/**
 * Utilities for manipulating CoreNLP data structures
 * User: mihais
 * Date: 2/25/15
 * Last Modified: Update for Scala 2.12: java converters.
 */
object CoreNLPUtils {

  private def setWord(w:CoreLabel, label:String): Unit = {
    w.setWord(label)
    w.setLemma(label)
    w.setValue(label)
  }

  def parensToSymbols(words:java.util.List[CoreLabel]):java.util.List[CoreLabel] = {
    val processedWords = new util.ArrayList[CoreLabel]()
    for(w <- words.asScala) {
      val nw = new CoreLabel(w)
      if(TokenizerStepNormalization.PARENS.contains(nw.word())) {
        setWord(nw, TokenizerStepNormalization.PARENS(nw.word()))
      }
      processedWords.add(nw)
    }
    processedWords
  }

  def toDirectedGraph(sg: SemanticGraph, interning: (String) => String, preferredSize: Option[Int] = None, debug: Boolean = false): DirectedGraph[String] = {

    def mkEdges(): List[Edge[String]] = {
      // Using list.distinct instead of Set.toList will preserve the order of edges.
      // Set can be sorted in different ways even on different runs with the same data.
      sg.edgeIterable().asScala.toList.map { edge =>
        val head: Int = edge.getGovernor.get(classOf[IndexAnnotation])
        val modifier: Int = edge.getDependent.get(classOf[IndexAnnotation])
        val specOpt = Option(edge.getRelation.getSpecific)
        val label = edge.getRelation.getShortName + specOpt.map("_" + _).getOrElse("")
        if (debug)
          println(s"Adding the following dependency: (${head - 1}, ${modifier - 1}, $label)")
        // Of the Edge, the source is head - 1, the destination is modifier - 1.
        Edge(head - 1, modifier - 1, interning(label))
      }.distinct
      // An extra distinct needs to be called on edges because CoreNLP sometimes duplicates the enhanced deps it creates.
    }

    val edges = mkEdges()
    val dg = new DirectedGraph[String](edges, preferredSize)
    //println(dg)
    dg
  }

  def toTree(stanfordTree:StanfordTree,
             headFinder: SemanticHeadFinder,
             position:MutableNumber[Int]):Tree = {
    assert(stanfordTree != null)

    if (stanfordTree.isLeaf) {
      val tree = Terminal(stanfordTree.label.value())
      tree.setIndex(position.value)
      position.value += 1
      return tree
    }

    // println("Converting tree: " + stanfordTree.toString)
    val children = new Array[Tree](stanfordTree.numChildren())
    for (i <- 0 until stanfordTree.numChildren()) {
      children(i) = toTree(stanfordTree.getChild(i), headFinder, position)
    }
    val value = stanfordTree.label.value()
    val start = children(0).startOffset
    val end = children(children.length - 1).endOffset

    val headDaughter = headFinder.determineHead(stanfordTree)
    var head = -1
    var i = 0
    while(i < stanfordTree.numChildren() && head == -1) {
      if (headDaughter == stanfordTree.getChild(i)) {
        head = i
      }
      i += 1
    }

    val nt = NonTerminal(value, children)
    nt.setStartEndIndices(start, end)
    nt.setHead(head)
    nt
  }

  /**
   * Create an Annotation from a Sentence
   */
  def sentenceToAnnotation(s: Sentence): Annotation = {

    val coreLabels: Seq[CoreLabel] = for {
      (w: String, i: Int) <- s.words.zipWithIndex
    } yield {
      val crtTok = new CoreLabel()
      // set word
      crtTok.setWord(w)
      crtTok.setValue(w)
      // set lemma
      if (s.lemmas.nonEmpty) crtTok.setLemma(s.lemmas.get(i))
      // set ner
      if (s.entities.nonEmpty) crtTok.setNER(s.entities.get(i))
      // set positions
      crtTok.setBeginPosition(s.startOffsets(i))
      crtTok.setEndPosition(s.endOffsets(i))
      crtTok.setIndex(i + 1) // Stanford counts tokens starting from 1
      crtTok.setSentIndex(i) // Stanford counts sentences starting from 0...
      crtTok
    }

    // attach the CoreLabels
    val sa: CoreMap = new ArrayCoreMap()
    sa.set(classOf[TokensAnnotation], coreLabels.toList.asJava)

    // TODO attach parse to sa

    // make Annotation
    val sas: util.List[CoreMap] = List(sa).asJava
    val annotation = new Annotation(sas)

    annotation
  }

  /**
   * Create an Annotation from a Document
   */
  def docToAnnotations(doc: Document): Seq[Annotation] = for {
    s <- doc.sentences
  } yield sentenceToAnnotation(s)
}


text:
from django.contrib import admin
from adminlinks.models import Link

# Settings for admin link
class LinkAdmin(admin.ModelAdmin):

  # Fields to list
  list_display = ('short_link', 'url', 'clicks', 'last_click')
  # Filter by
  list_filter = ('short_link', 'url', 'clicks', 'last_click')
  # Fields to order by
  ordering = ('-last_click', 'short_link')

# Add links to admin panel
admin.site.register(Link, LinkAdmin)


text:
#pragma once

#include "CX/C/Platform.h"

#ifdef __cplusplus
extern "C" {
#endif

#include "CX/C/Types.h"
#include "CX/C/APIDefs.h"

CX_API void *CX_MemAlloc(CX_Size cbSize);

CX_API void *CX_MemRealloc(void *pPtr, CX_Size cbSize);

CX_API void CX_MemFree(void *pPtr);

#ifdef __cplusplus
}
#endif


text:
.class public Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;
.super Ljava/lang/Object;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "Builder"
.end annotation

# instance fields
.field private mShowCancelButton:Z

.field private zzSn:Z

# direct methods
.method public constructor <init>()V
    .registers 2

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-boolean v0, p0, Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;->zzSn:Z

    const/4 v0, 0x1

    iput-boolean v0, p0, Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;->mShowCancelButton:Z

    return-void
.end method

.method static synthetic zza(Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;)Z
    .registers 2

    iget-boolean v0, p0, Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;->zzSn:Z

    return v0
.end method

.method static synthetic zzb(Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;)Z
    .registers 2

    iget-boolean v0, p0, Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;->mShowCancelButton:Z

    return v0
.end method

# virtual methods
.method public build()Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig;
    .registers 3

    new-instance v0, Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig;

    const/4 v1, 0x0

    invoke-direct {v0, p0, v1}, Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig;-><init>(Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$1;)V

    return-object v0
.end method

.method public setShowAddAccountButton(Z)Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;
    .registers 2
    .param p1, "showAddAccountButton"    # Z

    .prologue
    iput-boolean p1, p0, Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;->zzSn:Z

    return-object p0
.end method

.method public setShowCancelButton(Z)Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;
    .registers 2
    .param p1, "showCancelButton"    # Z

    .prologue
    iput-boolean p1, p0, Lcom/google/android/gms/auth/api/credentials/CredentialPickerConfig$Builder;->mShowCancelButton:Z

    return-object p0
.end method


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace WebLab.Profesionales {

    public partial class ProfesionalEdit {

        /// <summary>
        /// txtApellido control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtApellido;

        /// <summary>
        /// rfvApellido control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator rfvApellido;

        /// <summary>
        /// txtNombre control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtNombre;

        /// <summary>
        /// rfvNombre control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.RequiredFieldValidator rfvNombre;

        /// <summary>
        /// txtNumeroDocumento control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.HtmlControls.HtmlInputText txtNumeroDocumento;

        /// <summary>
        /// cvDni control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CompareValidator cvDni;

        /// <summary>
        /// txtMatricula control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox txtMatricula;

        /// <summary>
        /// chkActivo control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox chkActivo;

        /// <summary>
        /// lnkRegresar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.LinkButton lnkRegresar;

        /// <summary>
        /// btnGuardar control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Button btnGuardar;

        /// <summary>
        /// ValidationSummary1 control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.ValidationSummary ValidationSummary1;
    }
}


text:
typedef BOOL(APIENTRY* DllMainProc) (DWORD hModule, DWORD ul_reason_for_call, LPVOID lpReserved);
typedef struct StubParams
{
  char stub[0x200];  // 0x100 is approximate size of the stub_startDll routine. NOTE: this MUST be the first parameter of StubParams!!
  DWORD dllBase;
  DllMainProc entryPoint;
  ULONG_PTR pGetModuleHandle;
  ULONG_PTR pGetProcAddress;
  ULONG_PTR pVirtualProtect;
  char extraData[0x1000];

  // internal Loader Function addressed
  ULONG_PTR NewZwQInfoProcess;
  ULONG_PTR TrampZwQInfoProcess;

  // runtime data
  ULONG_PTR pZwQueryInformationProcess;
}StubParams, *PStubParams;


text:
#ifndef _NET_SOCKETS_PRIV_H_
#define _NET_SOCKETS_PRIV_H_

#include "net_sockets.h"

#ifdef WIN32
#include "net_sockets_win32.h"
#else
#include "net_sockets_bsd.h"
#endif

#ifdef __cplusplus
extern "C" {
#endif

typedef enum
{
   STREAM_CLIENT = 0,   /**< TCP client */
   STREAM_SERVER,       /**< TCP server */
   DATAGRAM_SENDER,     /**< UDP sender */
   DATAGRAM_RECEIVER    /**< UDP receiver */
} vc_container_net_type_t;

/** Perform implementation-specific per-socket initialization.
 *
 * \return VC_CONTAINER_NET_SUCCESS or one of the error codes on failure. */
vc_container_net_status_t vc_container_net_private_init( void );

/** Perform implementation-specific per-socket deinitialization.
 * This function is always called once for each successful call to socket_private_init(). */
void vc_container_net_private_deinit( void );

/** Return the last error from the socket implementation. */
vc_container_net_status_t vc_container_net_private_last_error( void );

/** Implementation-specific internal socket close.
 *
 * \param sock Internal socket to be closed. */
void vc_container_net_private_close( SOCKET_T sock );

/** Enable or disable socket address reusability.
 *
 * \param sock Internal socket to be closed.
 * \param enable True to enable reusability, false to clear it. */
void vc_container_net_private_set_reusable( SOCKET_T sock, bool enable );

/** Query the maximum datagram size for the socket.
 *
 * \param sock The socket to query.
 * \return The maximum supported datagram size on the socket. */
size_t vc_container_net_private_maximum_datagram_size( SOCKET_T sock );

#ifdef __cplusplus
}
#endif

#endif   /* _NET_SOCKETS_PRIV_H_ */


text:
package com.chupacadabra.evolution;

import com.chupacadabra.evolution.pool.CandidatePool;

/**
 * The random differentiation policy.
 *

 * Trial candidates of the ith parent vector are constructed
 * according to the formula:

 * $$\vec{u}_{i} = \vec{x}_{best} + F \cdot \sum_{j =
 * 0}^{p}{(\vec{x}_{r^{j}_{2}} - \vec{x}_{r^{j}_{3}})}$$

 * Here, p > 0 is the vector count and F is the
 * weight. The randomly chosen candidate vectors are neither the parent nor the
 * best candidate.
 *

 * By default, we choose p = 1 and use a
 * {@linkplain DitheringWeightPolicy dithering weight policy}.
 */
public final class BestDifferentiationPolicy implements DifferentiationPolicy {

    /**
     * Default count.
     */
    public static final int DEFAULT_COUNT = 1;

    /**
     * The count.
     */
    private final int count;

    /**
     * The weight policy.
     */
    private final WeightPolicy weightPolicy;

    /**
     * Default constructor.
     *

     * This constructor uses:
     *

     *
{@linkplain #DEFAULT_COUNT The default count.}

     *
{@linkplain DitheringWeightPolicy The default dithering weight
     * policy.}

     *

     */
    public BestDifferentiationPolicy() {
        this(DEFAULT_COUNT, new DitheringWeightPolicy());
    }

    /**
     * Constructor.
     *
     * @param count The count.
     * @param weightPolicy The weight policy.
     */
    public BestDifferentiationPolicy(final int count, final WeightPolicy weightPolicy) {
        this.count = count;
        this.weightPolicy = weightPolicy;
    }

    /**
     * @see com.chupacadabra.evolution.DifferentiationPolicy#differentiate(com.chupacadabra.evolution.DifferentialEvolutionState,
     *      RandomSource, int, com.chupacadabra.evolution.pool.CandidatePool)
     */
    @Override
    public double[] differentiate(final DifferentialEvolutionState state, final RandomSource randomSource, final int parentIndex, final CandidatePool pool) {
        // the trial vector starts at the current best candidate.
        int bestIndex = pool.getBestCandidateIndex();
        Candidate best = pool.getCandidate(bestIndex);
        double[] trial = best.getParameters();

        // select the desired number of random candidates, excluding the parent
        // and best candidate.
        int total = 2 * count;
        Candidate[] candidates = pool.selectCandidates(randomSource, total, parentIndex, bestIndex);

        // grab a weight.
        double f = weightPolicy.getWeight(state, randomSource);

        // sum up the parameters.
        PairwiseWeightedParameterSum.computeInPlace(f, trial, 0, candidates);

        return trial;
    }

}


text:
namespace aikido {
namespace planner {
namespace dart {

//==============================================================================
ConfigurationToEndEffectorOffset::ConfigurationToEndEffectorOffset(
    statespace::dart::ConstMetaSkeletonStateSpacePtr stateSpace,
    ::dart::dynamics::ConstMetaSkeletonPtr metaSkeleton,
    ::dart::dynamics::ConstBodyNodePtr endEffectorBodyNode,
    const Eigen::Vector3d& direction,
    const double signedDistance,
    constraint::ConstTestablePtr constraint)
  : Problem(stateSpace, std::move(constraint))
  , mMetaSkeletonStateSpace(stateSpace)
  , mMetaSkeleton(std::move(metaSkeleton))
  , mStartState(mMetaSkeletonStateSpace->createState())
  , mEndEffectorBodyNode(std::move(endEffectorBodyNode))
  , mDirection(direction)
  , mDistance(signedDistance)
{
  if (mDirection.get().isZero())
    throw std::invalid_argument("direction shouldn't be a zero vector.");
}

//==============================================================================
ConfigurationToEndEffectorOffset::ConfigurationToEndEffectorOffset(
    statespace::dart::ConstMetaSkeletonStateSpacePtr stateSpace,
    const statespace::dart::MetaSkeletonStateSpace::State* startState,
    ::dart::dynamics::ConstBodyNodePtr endEffectorBodyNode,
    const Eigen::Vector3d& direction,
    double signedDistance,
    constraint::ConstTestablePtr constraint)
  : Problem(stateSpace, std::move(constraint))
  , mMetaSkeletonStateSpace(stateSpace)
  , mMetaSkeleton(nullptr)
  , mStartState(stateSpace->cloneState(startState))
  , mEndEffectorBodyNode(std::move(endEffectorBodyNode))
  , mDirection(direction)
  , mDistance(signedDistance)
{
  if (mDirection.get().isZero())
    throw std::invalid_argument("direction shouldn't be a zero vector.");
}

//==============================================================================
ConfigurationToEndEffectorOffset::ConfigurationToEndEffectorOffset(
    statespace::dart::ConstMetaSkeletonStateSpacePtr stateSpace,
    ::dart::dynamics::ConstMetaSkeletonPtr metaSkeleton,
    ::dart::dynamics::ConstBodyNodePtr endEffectorBodyNode,
    double signedDistance,
    constraint::ConstTestablePtr constraint)
  : Problem(stateSpace, std::move(constraint))
  , mMetaSkeletonStateSpace(stateSpace)
  , mMetaSkeleton(std::move(metaSkeleton))
  , mStartState(mMetaSkeletonStateSpace->createState())
  , mEndEffectorBodyNode(std::move(endEffectorBodyNode))
  , mDirection(boost::none)
  , mDistance(signedDistance)
{
  // Do nothing.
}

//==============================================================================
ConfigurationToEndEffectorOffset::ConfigurationToEndEffectorOffset(
    statespace::dart::ConstMetaSkeletonStateSpacePtr stateSpace,
    const statespace::dart::MetaSkeletonStateSpace::State* startState,
    ::dart::dynamics::ConstBodyNodePtr endEffectorBodyNode,
    double signedDistance,
    constraint::ConstTestablePtr constraint)
  : Problem(stateSpace, std::move(constraint))
  , mMetaSkeletonStateSpace(stateSpace)
  , mMetaSkeleton(nullptr)
  , mStartState(stateSpace->cloneState(startState))
  , mEndEffectorBodyNode(std::move(endEffectorBodyNode))
  , mDirection(boost::none)
  , mDistance(signedDistance)
{
  // Do nothing.
}

//==============================================================================
const std::string& ConfigurationToEndEffectorOffset::getType() const
{
  return getStaticType();
}

//==============================================================================
const std::string& ConfigurationToEndEffectorOffset::getStaticType()
{
  static std::string name("ConfigurationToEndEffectorOffset");
  return name;
}

//==============================================================================
::dart::dynamics::ConstBodyNodePtr
ConfigurationToEndEffectorOffset::getEndEffectorBodyNode() const
{
  return mEndEffectorBodyNode;
}

//==============================================================================
const statespace::dart::MetaSkeletonStateSpace::State*
ConfigurationToEndEffectorOffset::getStartState() const
{
  // Take start state from MetaSkeleton if passed. Store in the ScopedState
  // instance variable to avoid dangling pointers.
  if (mMetaSkeleton)
    mMetaSkeletonStateSpace->getState(mMetaSkeleton.get(), mStartState);

  return mStartState;
}

//==============================================================================
Eigen::Vector3d ConfigurationToEndEffectorOffset::getDirection() const
{
  if (!mDirection)
  {
    return util::getEndEffectorDirection(mEndEffectorBodyNode);
  }

  return mDirection.get().normalized();
}

//==============================================================================
double ConfigurationToEndEffectorOffset::getDistance() const
{
  return mDistance;
}

} // namespace dart
} // namespace planner
} // namespace aikido


text:
=head1 LICENSE

Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

=head1 CONTACT

  Please email comments or questions to the public Ensembl
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.

  Questions may also be sent to the Ensembl help desk at
  <http://www.ensembl.org/Help/Contact>.

=head1 NAME

Bio::EnsEMBL::Compara::Production::DnaFragChunkSet

=head1 SYNOPSIS

=head1 DESCRIPTION

An object to hold a set or group of DnaFragChunk objects.  Used in production to reduce
overhead of feeding sequences into alignment programs like (b)lastz and exonerate.

=head1 APPENDIX

The rest of the documentation details each of the object methods. Internal methods are usually preceded with a _

=cut

package Bio::EnsEMBL::Compara::Production::DnaFragChunkSet;

use strict;
use Bio::EnsEMBL::Compara::Production::DnaFragChunk;
use Bio::EnsEMBL::Utils::Exception;
use Bio::EnsEMBL::Utils::Argument;
use Time::HiRes qw(time gettimeofday tv_interval);

sub new {
  my ($class, @args) = @_;

  my $self = {};
  bless $self,$class;

  $self->{'_cached_chunk_list'} = undef;
  $self->{'_total_basepairs'} = 0;

  if (scalar @args) {
    #do this explicitly.
    my ($dbid, $description, $adaptor, $dna_collection_id) = rearrange([qw(DBID NAME ADAPTOR DNA_COLLECTION_ID)], @args);

    $self->dbID($dbid)                           if($dbid);
    $self->description($description)             if($description);
    $self->adaptor($adaptor)                     if($adaptor);
    $self->dna_collection_id($dna_collection_id) if($dna_collection_id);
  }
  return $self;
}

=head2 adaptor

 Title   : adaptor
 Usage   :
 Function: getter/setter of the adaptor for this object
 Example :
 Returns :
 Args    :

=cut

sub adaptor {
  my $self = shift;
  $self->{'_adaptor'} = shift if(@_);
  return $self->{'_adaptor'};
}

=head2 dbID

  Arg [1]    : int $dbID (optional)
  Example    :
  Description:
  Returntype :
  Exceptions :
  Caller     :

=cut

sub dbID {
  my $self = shift;
  $self->{'_dbID'} = shift if(@_);
  return $self->{'_dbID'};
}

=head2 description

  Arg [1]    : string $description (optional)
  Example    :
  Description:
  Returntype : string
  Exceptions :
  Caller     :

=cut

sub description {
  my $self = shift;
  $self->{'_description'} = shift if(@_);
  return $self->{'_description'};
}

=head2 dna_collection

  Arg [1]    :  Bio::EnsEMBL::Compara::Production::DnaCollection $dna_collection (optional)
  Example    :
  Description:
  Returntype : string
  Exceptions :
  Caller     :

=cut

sub dna_collection {
  my ($self, $dna_collection) = @_;

  if (defined $dna_collection) {
      $self->{'_dna_collection'} = $dna_collection;
  } elsif (!defined ($self->{'_dna_collection'})) {
      #Try to get from other sources...
      if (defined ($self->{'_adaptor'}) and defined($self->{'_dna_collection_id'})) {
          $self->{'_dna_collection'} = $self->adaptor->db->get_DnaCollectionAdaptor->fetch_by_dbID($self->dna_collection_id);
      }
  }

  return $self->{'_dna_collection'};
}

=head2 dna_collection_id

  Arg [1]    : int $dna_collection_id (optional)
  Example    :
  Description:
  Returntype :
  Exceptions :
  Caller     :

=cut

sub dna_collection_id {
  my $self = shift;
  $self->{'_dna_collection_id'} = shift if(@_);
  return $self->{'_dna_collection_id'};
}

=head2 add_DnaFragChunk

  Arg [1]    : Bio::EnsEMBL::Compara::Production::DnaFragChunk $chunk
  Example    : $dnafrag_chunk_set->add_DnaFragChunk($chunk)
  Description: Add a Bio::EnsEMBL::Compara::Production::DnaFragChunk object to the _cached_chunk_list parameter
  Returntype :
  Exceptions : throw if $chunk is not defined or if $chunk is not a Bio::EnsEMBL::Compara::Production::DnaFragChunk
  Caller     :

=cut

sub add_DnaFragChunk {
  my ($self, $chunk) = @_;

  unless(defined($chunk) and
         $chunk->isa('Bio::EnsEMBL::Compara::Production::DnaFragChunk'))
  {
    $self->throw(
      "chunk arg must be a [Bio::EnsEMBL::Compara::Production::DnaFragChunk] ".
      "not a [$chunk]");
  }

  $self->{'_cached_chunk_list'} = []
    unless(defined($self->{'_cached_chunk_list'}));

  push @{$self->{'_cached_chunk_list'}}, $chunk;
  $self->{'_total_basepairs'}=0; #reset so will be recalculated
}

=head2 get_all_DnaFragChunks

  Example    : @chunks = @{$chunkSet->get_all_DnaFragChunks};
  Description: returns array reference to all the DnaFragChunk objects in this set
               will lazy load the set if it was not previously loaded
  Returntype : reference to array of Bio::EnsEMBL::Compara::Production::DnaFragChunk objects
  Exceptions :
  Caller     :

=cut

sub get_all_DnaFragChunks {
  my $self = shift;

  if(!defined($self->{'_cached_chunk_list'}) and defined($self->adaptor)) {
    #lazy load all the DnaFragChunk objects
    $self->{'_cached_chunk_list'} = $self->adaptor->db->get_DnaFragChunkAdaptor->fetch_all_by_DnaFragChunkSet($self);

    $self->{'_total_basepairs'}=0; #reset so it's recalculated in
  }

  return $self->{'_cached_chunk_list'};
}

=head2 count

  Example    : $count = $chunkSet->count;
  Description: returns count of DnaFragChunks in this set
  Returntype : int
  Exceptions :
  Caller     :

=cut

sub count {
  my $self = shift;

  if (!$self->{'_cached_chunk_list'}) {
      return 0;
  }

  return scalar(@{$self->{'_cached_chunk_list'}});
}

=head2 total_basepairs

  Example    : $size = $chunkSet->total_basepairs;
  Description: returns summed length of all DnaFragChunks in this set
  Returntype : int
  Exceptions :
  Caller     :

=cut

sub total_basepairs {
  my $self = shift;

  unless($self->{'_total_basepairs'}) {
    $self->{'_total_basepairs'} =0;
    if($self->get_all_DnaFragChunks) {
      foreach my $chunk (@{$self->get_all_DnaFragChunks}) {
        $self->{'_total_basepairs'} += $chunk->length;
      }
    }
  }
  return $self->{'_total_basepairs'};
}

1;


text:
package com.planet_ink.coffee_mud.Abilities.Druid;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class Chant_AnimalFriendship extends Chant
{
	@Override public String ID() { return "Chant_AnimalFriendship"; }
	private final static String localizedName = CMLib.lang()._("Animal Friendship");
	@Override public String name() { return localizedName; }
	private final static String localizedStaticDisplay = CMLib.lang()._("(Animal Friendship)");
	@Override public String displayText() { return localizedStaticDisplay; }
	@Override public int classificationCode(){return Ability.ACODE_CHANT|Ability.DOMAIN_ANIMALAFFINITY;}
	@Override public int abstractQuality(){return Ability.QUALITY_OK_SELF;}

	@Override
	public boolean okMessage(final Environmental myHost, final CMMsg msg)
	{
		if(((msg.targetMajor()&CMMsg.MASK_MALICIOUS)>0)
		&&(!CMath.bset(msg.sourceMajor(),CMMsg.MASK_ALWAYS))
		&&((msg.amITarget(affected)))
		&&(CMLib.flags().isAnimalIntelligence(msg.source())))
		{
			final MOB target=(MOB)msg.target();
			if((!target.isInCombat())
			&&(msg.source().location()==target.location())
			&&(msg.source().getVictim()!=target))
			{
				msg.source().tell(_("You feel too friendly towards @x1",target.name(msg.source())));
				if(target.getVictim()==msg.source())
				{
					target.makePeace();
					target.setVictim(null);
				}
				return false;
			}
		}
		return super.okMessage(myHost,msg);
	}

	@Override
	public void unInvoke()
	{
		// undo the affects of this spell
		if(!(affected instanceof MOB))
			return;
		final MOB mob=(MOB)affected;
		super.unInvoke();

		if(canBeUninvoked())
			mob.tell(_("You seem less animal friendly."));
	}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		MOB target=mob;
		if((auto)&&(givenTarget!=null)&&(givenTarget instanceof MOB))
			target=(MOB)givenTarget;

		if(target.fetchEffect(this.ID())!=null)
		{
			mob.tell(target,null,null,_("<S-NAME> <S-IS-ARE> already friendly to animals."));
			return false;
		}

		// the invoke method for spells receives as
		// parameters the invoker, and the REMAINING
		// command line parameters, divided into words,
		// and added as String objects to a vector.
		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			// it worked, so build a copy of this ability,
			// and add it to the affects list of the
			// affected MOB.  Then tell everyone else
			// what happened.
			invoker=mob;
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?_("<T-NAME> become(s) animal friendly!"):_("^S<S-NAME> chant(s) for animal friendship.^?"));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				beneficialAffect(mob,target,asLevel,0);
			}
		}
		else
			return beneficialWordsFizzle(mob,null,_("<S-NAME> chant(s), the magic fades."));

		// return whether it worked
		return success;
	}
}


text:
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Game.Rulesets.Judgements;
using osu.Game.Rulesets.Scoring;

namespace osu.Game.Rulesets.Mania.Judgements
{
    public class ManiaJudgement : Judgement
    {
        protected override int NumericResultFor(HitResult result)
        {
            switch (result)
            {
                default:
                    return 0;
                case HitResult.Meh:
                    return 50;
                case HitResult.Ok:
                    return 100;
                case HitResult.Good:
                    return 200;
                case HitResult.Great:
                case HitResult.Perfect:
                    return 300;
            }
        }
    }
}


text: <manifest package="com.kerneladiutor.library" />


text:
import json
import logging
import os
import threading
import time
import queue

import sqlalchemy
from sqlalchemy.engine import CreateEnginePlugin
from sqlalchemy import event

# https://docs.sqlalchemy.org/en/14/core/connections.html?
# highlight=createengineplugin#sqlalchemy.engine.CreateEnginePlugin

LOG = logging.getLogger(__name__)

# The theory of operation here is that we register this plugin with
# sqlalchemy via an entry_point. It gets loaded by virtue of plugin=
# being in the database connection URL, which gives us an opportunity
# to hook the engines that get created.
#
# We opportunistically spawn a thread, which we feed "hits" to over a
# queue, and which occasionally writes those hits to a special
# database called 'stats'. We access that database with the same user,
# pass, and host as the main connection URL for simplicity.

class LogCursorEventsPlugin(CreateEnginePlugin):
    def __init__(self, url, kwargs):
        self.db_name = url.database
        LOG.info('Registered counter for database %s' % self.db_name)
        new_url = sqlalchemy.engine.URL.create(url.drivername,
                                               url.username,
                                               url.password,
                                               url.host,
                                               url.port,
                                               'stats')

        self.engine = sqlalchemy.create_engine(new_url)
        self.queue = queue.Queue()
        self.thread = None

    def engine_created(self, engine):
        """Hook the engine creation process.

        This is the plug point for the sqlalchemy plugin. Using
        plugin=$this in the URL causes this method to be called when
        the engine is created, giving us a chance to hook it below.
        """
        event.listen(engine, "before_cursor_execute", self._log_event)

    def ensure_writer_thread(self):
        self.thread = threading.Thread(target=self.stat_writer, daemon=True)
        self.thread.start()

    def _log_event(self, conn, cursor, statement, parameters, context,
                   executemany):
        """Queue a "hit" for this operation to be recorded.

        Attepts to determine the operation by the first word of the
        statement, or 'OTHER' if it cannot be determined.
        """

        # Start our thread if not running. If we were forked after the
        # engine was created and this plugin was associated, our
        # writer thread is gone, so respawn.
        if not self.thread or not self.thread.is_alive():
            self.ensure_writer_thread()

        try:
            op = statement.strip().split(' ', 1)[0] or 'OTHER'
        except Exception:
            op = 'OTHER'

        self.queue.put((self.db_name, op))

    def do_incr(self, db, op, count):
        """Increment the counter for (db,op) by count."""

        query = ('INSERT INTO queries (db, op, count) '
                 '  VALUES (%s, %s, %s) '
                 '  ON DUPLICATE KEY UPDATE count=count+%s')
        try:
            with self.engine.begin() as conn:
                r = conn.execute(query, (db, op, count, count))
        except Exception as e:
            LOG.error('Failed to account for access to database %r: %s',
                      db, e)

    def stat_writer(self):
        """Consume messages from the queue and write them in batches.

        This reads "hists" from from a queue fed by _log_event() and
        writes (db,op)+=count stats to the database after ten seconds
        of no activity to avoid triggering a write for every SELECT
        call. Write no less often than every thirty seconds and/or 100
        pending hits to avoid being starved by constant activity.
        """
        LOG.debug('[%i] Writer thread running' % os.getpid())
        while True:
            to_write = {}
            total = 0
            last = time.time()
            while time.time() - last < 30 and total < 100:
                try:
                    item = self.queue.get(timeout=10)
                    to_write.setdefault(item, 0)
                    to_write[item] += 1
                    total += 1
                except queue.Empty:
                    break

            if to_write:
                LOG.debug('[%i] Writing DB stats %s' % (
                    os.getpid(),
                    ','.join(['%s:%s=%i' % (db, op, count)
                              for (db, op), count in to_write.items()])))

            for (db, op), count in to_write.items():
                self.do_incr(db, op, count)


text:
//  ----------------------------------------------------------------------------------
//  Copyright Microsoft Corporation
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//  http://www.apache.org/licenses/LICENSE-2.0
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
//  ----------------------------------------------------------------------------------

namespace DurableTask.ServiceBus.Tests
{
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using DurableTask.Core;
    using DurableTask.Core.Common;
    using DurableTask.Core.Exceptions;
    using DurableTask.Core.History;
    using DurableTask.Core.Serializing;
    using DurableTask.ServiceBus.Settings;
    using DurableTask.ServiceBus.Tracking;
    using DurableTask.Core.Tests;

    [TestClass]
    public class RuntimeStateStreamConverterTest
    {
        const int sessionOverflowThresholdInBytes = 2 * 1024;
        const int sessionMaxSizeInBytes = 10 * 1024;
        const string sessionId = "session123";
        ServiceBusSessionSettings serviceBusSessionSettings = new ServiceBusSessionSettings(sessionOverflowThresholdInBytes, sessionMaxSizeInBytes);

        AzureTableInstanceStore azureTableInstanceStore;
        AzureStorageBlobStore azureStorageBlobStore;

        [TestInitialize]
        public void TestInitialize()
        {
            azureTableInstanceStore = TestHelpers.CreateAzureTableInstanceStore();
            azureStorageBlobStore = TestHelpers.CreateAzureStorageBlobStore();
        }

        [TestCleanup]
        public void TestCleanup()
        {
            azureTableInstanceStore.DeleteStoreAsync().Wait();
            azureStorageBlobStore.DeleteStoreAsync().Wait();
        }

        [TestMethod]
        public async Task SmallRuntimeStateConverterTest()
        {
            string smallInput = "abc";

            OrchestrationRuntimeState newOrchestrationRuntimeStateSmall = generateOrchestrationRuntimeState(smallInput);
            OrchestrationRuntimeState runtimeState = new OrchestrationRuntimeState();
            DataConverter dataConverter = new JsonDataConverter();

            // a small runtime state doesn't need external storage.
            Stream rawStreamSmall = await RuntimeStateStreamConverter.OrchestrationRuntimeStateToRawStream(
                newOrchestrationRuntimeStateSmall,
                runtimeState,
                dataConverter,
                true,
                serviceBusSessionSettings,
                azureStorageBlobStore,
                sessionId);
            OrchestrationRuntimeState convertedRuntimeStateSmall = await RuntimeStateStreamConverter.RawStreamToRuntimeState(rawStreamSmall, "sessionId", azureStorageBlobStore, dataConverter);
            verifyEventInput(smallInput, convertedRuntimeStateSmall);

            // test for un-compress case
            Stream rawStreamSmall2 = await RuntimeStateStreamConverter.OrchestrationRuntimeStateToRawStream(
                newOrchestrationRuntimeStateSmall,
                runtimeState,
                dataConverter,
                false,
                serviceBusSessionSettings,
                azureStorageBlobStore,
                sessionId);
            OrchestrationRuntimeState convertedRuntimeStateSmall2 = await RuntimeStateStreamConverter.RawStreamToRuntimeState(rawStreamSmall2, "sessionId", azureStorageBlobStore, dataConverter);
            verifyEventInput(smallInput, convertedRuntimeStateSmall2);

            // test for backward comp: ok for an un-implemented (or null) IBlobStorage for small runtime states
            Stream rawStreamSmall3 = await RuntimeStateStreamConverter.OrchestrationRuntimeStateToRawStream(
                newOrchestrationRuntimeStateSmall,
                runtimeState,
                dataConverter,
                true,
                serviceBusSessionSettings,
                null,
                sessionId);
            OrchestrationRuntimeState convertedRuntimeStateSmall3 = await RuntimeStateStreamConverter.RawStreamToRuntimeState(rawStreamSmall3, "sessionId", null, dataConverter);
            verifyEventInput(smallInput, convertedRuntimeStateSmall3);
        }

        [TestMethod]
        public async Task LargeRuntimeStateConverterTest()
        {
            string largeInput = TestUtils.GenerateRandomString(5 * 1024);
            OrchestrationRuntimeState newOrchestrationRuntimeStateLarge = generateOrchestrationRuntimeState(largeInput);
            OrchestrationRuntimeState runtimeState = new OrchestrationRuntimeState();
            DataConverter dataConverter = new JsonDataConverter();

            // a large runtime state that needs external storage.
            Stream rawStreamLarge = await RuntimeStateStreamConverter.OrchestrationRuntimeStateToRawStream(
                newOrchestrationRuntimeStateLarge,
                runtimeState,
                dataConverter,
                true,
                serviceBusSessionSettings,
                azureStorageBlobStore,
                sessionId);
            OrchestrationRuntimeState convertedRuntimeStateLarge = await RuntimeStateStreamConverter.RawStreamToRuntimeState(rawStreamLarge, "sessionId", azureStorageBlobStore, dataConverter);
            verifyEventInput(largeInput, convertedRuntimeStateLarge);

            // test for un-compress case
            string largeInput2 = TestUtils.GenerateRandomString(3 * 1024);
            OrchestrationRuntimeState newOrchestrationRuntimeStateLarge2 = generateOrchestrationRuntimeState(largeInput2);
            Stream rawStreamLarge2 = await RuntimeStateStreamConverter.OrchestrationRuntimeStateToRawStream(
                newOrchestrationRuntimeStateLarge2,
                runtimeState,
                dataConverter,
                false,
                serviceBusSessionSettings,
                azureStorageBlobStore,
                sessionId);
            OrchestrationRuntimeState convertedRuntimeStateLarge2 = await RuntimeStateStreamConverter.RawStreamToRuntimeState(rawStreamLarge2, "sessionId", azureStorageBlobStore, dataConverter);
            verifyEventInput(largeInput2, convertedRuntimeStateLarge2);

            // test for an un-implemented (or null) IBlobStorage for large runtime states: should throw exception
            try
            {
                await
                    RuntimeStateStreamConverter.OrchestrationRuntimeStateToRawStream(
                        newOrchestrationRuntimeStateLarge,
                        runtimeState,
                        dataConverter,
                        true,
                        serviceBusSessionSettings,
                        null,
                        sessionId);
                Assert.Fail("ArgumentException must be thrown");
            }
            catch (OrchestrationException e)
            {
                // expected
                Assert.IsTrue(e.Message.Contains("IOrchestrationServiceBlobStore"), "Exception must contain IOrchestrationServiceBlobStore.");
            }
        }

        [TestMethod]
        public async Task VeryLargeRuntimeStateConverterTest()
        {
            string veryLargeInput = TestUtils.GenerateRandomString(20 * 1024);
            OrchestrationRuntimeState newOrchestrationRuntimeStateLarge = generateOrchestrationRuntimeState(veryLargeInput);
            OrchestrationRuntimeState runtimeState = new OrchestrationRuntimeState();
            DataConverter dataConverter = new JsonDataConverter();

            // test for very large size rumtime state that cannot be saved externally: should throw exception
            try
            {
                Stream rawStreamVeryLarge = await RuntimeStateStreamConverter.OrchestrationRuntimeStateToRawStream(
                    newOrchestrationRuntimeStateLarge,
                    runtimeState,
                    dataConverter,
                    true,
                    serviceBusSessionSettings,
                    azureStorageBlobStore,
                    sessionId);
                Assert.Fail("ArgumentException must be thrown");
            }
            catch (OrchestrationException e)
            {
                // expected
                Assert.IsTrue(e.Message.Contains("exceeded"), "Exception must contain exceeded.");
            }
        }

        [TestMethod]
        public async Task ConverterCompatabilityTest()
        {
            string smallInput = "abc";
            OrchestrationRuntimeState newOrchestrationRuntimeStateSmall = generateOrchestrationRuntimeState(smallInput);
            OrchestrationRuntimeState runtimeState = new OrchestrationRuntimeState();
            DataConverter dataConverter = new JsonDataConverter();

            // deserialize a OrchestrationRuntimeState object, with both compression and not compression
            Stream stream = serializeToStream(dataConverter, newOrchestrationRuntimeStateSmall, true);
            OrchestrationRuntimeState convertedRuntimeStateSmall = await RuntimeStateStreamConverter.RawStreamToRuntimeState(stream, "sessionId", null, dataConverter);
            verifyEventInput(smallInput, convertedRuntimeStateSmall);

            stream = serializeToStream(dataConverter, newOrchestrationRuntimeStateSmall, false);
            convertedRuntimeStateSmall = await RuntimeStateStreamConverter.RawStreamToRuntimeState(stream, "sessionId", null, dataConverter);
            verifyEventInput(smallInput, convertedRuntimeStateSmall);

            // deserialize a IList<HistoryEvent> object, with both compression and not compression
            Stream stream2 = serializeToStream(dataConverter, newOrchestrationRuntimeStateSmall.Events, true);
            OrchestrationRuntimeState convertedRuntimeStateSmall2 = await RuntimeStateStreamConverter.RawStreamToRuntimeState(stream2, "sessionId", null, dataConverter);
            verifyEventInput(smallInput, convertedRuntimeStateSmall2);

            stream2 = serializeToStream(dataConverter, newOrchestrationRuntimeStateSmall.Events, false);
            convertedRuntimeStateSmall2 = await RuntimeStateStreamConverter.RawStreamToRuntimeState(stream2, "sessionId", null, dataConverter);
            verifyEventInput(smallInput, convertedRuntimeStateSmall2);
        }

        private Stream serializeToStream(DataConverter dataConverter, OrchestrationRuntimeState orchestrationRuntimeState, bool shouldCompress)
        {
            string serializedState = dataConverter.Serialize(orchestrationRuntimeState);
            long originalStreamSize = 0;
            return Utils.WriteStringToStream(
                serializedState,
                shouldCompress,
                out originalStreamSize);
        }

        private Stream serializeToStream(DataConverter dataConverter, IList<HistoryEvent> events, bool shouldCompress)
        {
            string serializedState = dataConverter.Serialize(events);
            long originalStreamSize = 0;
            return Utils.WriteStringToStream(
                serializedState,
                shouldCompress,
                out originalStreamSize);
        }

        OrchestrationRuntimeState generateOrchestrationRuntimeState(string input)
        {
            IList<HistoryEvent> historyEvents = new List<HistoryEvent>();
            ExecutionStartedEvent historyEvent = new ExecutionStartedEvent(1, input);
            historyEvents.Add(historyEvent);
            OrchestrationRuntimeState newOrchestrationRuntimeState = new OrchestrationRuntimeState(historyEvents);

            return newOrchestrationRuntimeState;
        }

        void verifyEventInput(string expectedHistoryEventInput, OrchestrationRuntimeState runtimeState)
        {
            ExecutionStartedEvent executionStartedEvent = runtimeState.Events[0] as ExecutionStartedEvent;
            Assert.AreEqual(expectedHistoryEventInput, executionStartedEvent.Input);
        }
    }
}


text:
def test_imports():
    from pycobertura import Cobertura
    from pycobertura import CoberturaDiff
    from pycobertura import TextReporter
    from pycobertura import TextReporterDelta


text:
const utils = require('../../utils');

module.exports = utils.addTable('temp_member_analytic_events', {
    id: {type: 'string', maxlength: 24, nullable: false, primary: true},
    event_name: {type: 'string', maxlength: 50, nullable: false},
    created_at: {type: 'dateTime', nullable: false},
    member_id: {type: 'string', maxlength: 24, nullable: false},
    member_status: {type: 'string', maxlength: 50, nullable: false},
    entry_id: {type: 'string', maxlength: 24, nullable: true},
    source_url: {type: 'string', maxlength: 2000, nullable: true},
    metadata: {type: 'string', maxlength: 191, nullable: true}
});


text:
// Copyright 2018 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package libcontainer

import (
	"bufio"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path"
	"strconv"
	"strings"
	"time"

	"github.com/google/cadvisor/container"
	info "github.com/google/cadvisor/info/v1"

	"bytes"
	"github.com/opencontainers/runc/libcontainer"
	"github.com/opencontainers/runc/libcontainer/cgroups"
	"k8s.io/klog"
)

/*
#include <unistd.h>
*/
import "C"

type Handler struct {
	cgroupManager   cgroups.Manager
	rootFs          string
	pid             int
	includedMetrics container.MetricSet
	pidMetricsCache map[int]*info.CpuSchedstat
}

func NewHandler(cgroupManager cgroups.Manager, rootFs string, pid int, includedMetrics container.MetricSet) *Handler {
	return &Handler{
		cgroupManager:   cgroupManager,
		rootFs:          rootFs,
		pid:             pid,
		includedMetrics: includedMetrics,
		pidMetricsCache: make(map[int]*info.CpuSchedstat),
	}
}

// Get cgroup and networking stats of the specified container
func (h *Handler) GetStats() (*info.ContainerStats, error) {
	cgroupStats, err := h.cgroupManager.GetStats()
	if err != nil {
		return nil, err
	}
	libcontainerStats := &libcontainer.Stats{
		CgroupStats: cgroupStats,
	}
	stats := newContainerStats(libcontainerStats, h.includedMetrics)

	if h.includedMetrics.Has(container.ProcessSchedulerMetrics) {
		pids, err := h.cgroupManager.GetAllPids()
		if err != nil {
			klog.V(4).Infof("Could not get PIDs for container %d: %v", h.pid, err)
		} else {
			stats.Cpu.Schedstat, err = schedulerStatsFromProcs(h.rootFs, pids, h.pidMetricsCache)
			if err != nil {
				klog.V(4).Infof("Unable to get Process Scheduler Stats: %v", err)
			}
		}
	}

	// If we know the pid then get network stats from /proc/<pid>/net/dev
	if h.pid == 0 {
		return stats, nil
	}
	if h.includedMetrics.Has(container.NetworkUsageMetrics) {
		netStats, err := networkStatsFromProc(h.rootFs, h.pid)
		if err != nil {
			klog.V(4).Infof("Unable to get network stats from pid %d: %v", h.pid, err)
		} else {
			stats.Network.Interfaces = append(stats.Network.Interfaces, netStats...)
		}
	}
	if h.includedMetrics.Has(container.NetworkTcpUsageMetrics) {
		t, err := tcpStatsFromProc(h.rootFs, h.pid, "net/tcp")
		if err != nil {
			klog.V(4).Infof("Unable to get tcp stats from pid %d: %v", h.pid, err)
		} else {
			stats.Network.Tcp = t
		}

		t6, err := tcpStatsFromProc(h.rootFs, h.pid, "net/tcp6")
		if err != nil {
			klog.V(4).Infof("Unable to get tcp6 stats from pid %d: %v", h.pid, err)
		} else {
			stats.Network.Tcp6 = t6
		}
	}
	if h.includedMetrics.Has(container.NetworkUdpUsageMetrics) {
		u, err := udpStatsFromProc(h.rootFs, h.pid, "net/udp")
		if err != nil {
			klog.V(4).Infof("Unable to get udp stats from pid %d: %v", h.pid, err)
		} else {
			stats.Network.Udp = u
		}

		u6, err := udpStatsFromProc(h.rootFs, h.pid, "net/udp6")
		if err != nil {
			klog.V(4).Infof("Unable to get udp6 stats from pid %d: %v", h.pid, err)
		} else {
			stats.Network.Udp6 = u6
		}
	}
	if h.includedMetrics.Has(container.ProcessMetrics) {
		paths := h.cgroupManager.GetPaths()
		path, ok := paths["cpu"]
		if !ok {
			klog.V(4).Infof("Could not find cgroups CPU for container %d", h.pid)
		} else {
			stats.Processes, err = processStatsFromProcs(h.rootFs, path)
			if err != nil {
				klog.V(4).Infof("Unable to get Process Stats: %v", err)
			}
		}
	}

	// For backwards compatibility.
	if len(stats.Network.Interfaces) > 0 {
		stats.Network.InterfaceStats = stats.Network.Interfaces[0]
	}

	return stats, nil
}

func processStatsFromProcs(rootFs string, cgroupPath string) (info.ProcessStats, error) {
	var fdCount uint64
	filePath := path.Join(cgroupPath, "cgroup.procs")
	out, err := ioutil.ReadFile(filePath)
	if err != nil {
		return info.ProcessStats{}, fmt.Errorf("couldn't open cpu cgroup procs file %v : %v", filePath, err)
	}

	pids := strings.Split(string(out), "\n")

	// EOL is also treated as a new line while reading "cgroup.procs" file with ioutil.ReadFile.
	// The last value is an empty string "". Ex: pids = ["22", "1223", ""]
	// Trim the last value
	if len(pids) != 0 && pids[len(pids)-1] == "" {
		pids = pids[:len(pids)-1]
	}

	for _, pid := range pids {
		dirPath := path.Join(rootFs, "/proc", pid, "fd")
		fds, err := ioutil.ReadDir(dirPath)
		if err != nil {
			klog.V(4).Infof("error while listing directory %q to measure fd count: %v", dirPath, err)
			continue
		}
		fdCount += uint64(len(fds))
	}

	processStats := info.ProcessStats{
		ProcessCount: uint64(len(pids)),
		FdCount:      fdCount,
	}

	return processStats, nil
}

func schedulerStatsFromProcs(rootFs string, pids []int, pidMetricsCache map[int]*info.CpuSchedstat) (info.CpuSchedstat, error) {
	for _, pid := range pids {
		f, err := os.Open(path.Join(rootFs, "proc", strconv.Itoa(pid), "schedstat"))
		if err != nil {
			return info.CpuSchedstat{}, fmt.Errorf("couldn't open scheduler statistics for process %d: %v", pid, err)
		}
		defer f.Close()
		contents, err := ioutil.ReadAll(f)
		if err != nil {
			return info.CpuSchedstat{}, fmt.Errorf("couldn't read scheduler statistics for process %d: %v", pid, err)
		}
		rawMetrics := bytes.Split(bytes.TrimRight(contents, "\n"), []byte(" "))
		if len(rawMetrics) != 3 {
			return info.CpuSchedstat{}, fmt.Errorf("unexpected number of metrics in schedstat file for process %d", pid)
		}
		cacheEntry, ok := pidMetricsCache[pid]
		if !ok {
			cacheEntry = &info.CpuSchedstat{}
			pidMetricsCache[pid] = cacheEntry
		}
		for i, rawMetric := range rawMetrics {
			metric, err := strconv.ParseUint(string(rawMetric), 10, 64)
			if err != nil {
				return info.CpuSchedstat{}, fmt.Errorf("parsing error while reading scheduler statistics for process: %d: %v", pid, err)
			}
			switch i {
			case 0:
				cacheEntry.RunTime = metric
			case 1:
				cacheEntry.RunqueueTime = metric
			case 2:
				cacheEntry.RunPeriods = metric
			}
		}
	}
	schedstats := info.CpuSchedstat{}
	for _, v := range pidMetricsCache {
		schedstats.RunPeriods += v.RunPeriods
		schedstats.RunqueueTime += v.RunqueueTime
		schedstats.RunTime += v.RunTime
	}
	return schedstats, nil
}

func networkStatsFromProc(rootFs string, pid int) ([]info.InterfaceStats, error) {
	netStatsFile := path.Join(rootFs, "proc", strconv.Itoa(pid), "/net/dev")

	ifaceStats, err := scanInterfaceStats(netStatsFile)
	if err != nil {
		return []info.InterfaceStats{}, fmt.Errorf("couldn't read network stats: %v", err)
	}

	return ifaceStats, nil
}

var (
	ignoredDevicePrefixes = []string{"lo", "veth", "docker"}
)

func isIgnoredDevice(ifName string) bool {
	for _, prefix := range ignoredDevicePrefixes {
		if strings.HasPrefix(strings.ToLower(ifName), prefix) {
			return true
		}
	}
	return false
}

func scanInterfaceStats(netStatsFile string) ([]info.InterfaceStats, error) {
	file, err := os.Open(netStatsFile)
	if err != nil {
		return nil, fmt.Errorf("failure opening %s: %v", netStatsFile, err)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)

	// Discard header lines
	for i := 0; i < 2; i++ {
		if b := scanner.Scan(); !b {
			return nil, scanner.Err()
		}
	}

	stats := []info.InterfaceStats{}
	for scanner.Scan() {
		line := scanner.Text()
		line = strings.Replace(line, ":", "", -1)

		fields := strings.Fields(line)
		// If the format of the  line is invalid then don't trust any of the stats
		// in this file.
		if len(fields) != 17 {
			return nil, fmt.Errorf("invalid interface stats line: %v", line)
		}

		devName := fields[0]
		if isIgnoredDevice(devName) {
			continue
		}

		i := info.InterfaceStats{
			Name: devName,
		}

		statFields := append(fields[1:5], fields[9:13]...)
		statPointers := []*uint64{
			&i.RxBytes, &i.RxPackets, &i.RxErrors, &i.RxDropped,
			&i.TxBytes, &i.TxPackets, &i.TxErrors, &i.TxDropped,
		}

		err := setInterfaceStatValues(statFields, statPointers)
		if err != nil {
			return nil, fmt.Errorf("cannot parse interface stats (%v): %v", err, line)
		}

		stats = append(stats, i)
	}

	return stats, nil
}

func setInterfaceStatValues(fields []string, pointers []*uint64) error {
	for i, v := range fields {
		val, err := strconv.ParseUint(v, 10, 64)
		if err != nil {
			return err
		}
		*pointers[i] = val
	}
	return nil
}

func tcpStatsFromProc(rootFs string, pid int, file string) (info.TcpStat, error) {
	tcpStatsFile := path.Join(rootFs, "proc", strconv.Itoa(pid), file)

	tcpStats, err := scanTcpStats(tcpStatsFile)
	if err != nil {
		return tcpStats, fmt.Errorf("couldn't read tcp stats: %v", err)
	}

	return tcpStats, nil
}

func scanTcpStats(tcpStatsFile string) (info.TcpStat, error) {

	var stats info.TcpStat

	data, err := ioutil.ReadFile(tcpStatsFile)
	if err != nil {
		return stats, fmt.Errorf("failure opening %s: %v", tcpStatsFile, err)
	}

	tcpStateMap := map[string]uint64{
		"01": 0, //ESTABLISHED
		"02": 0, //SYN_SENT
		"03": 0, //SYN_RECV
		"04": 0, //FIN_WAIT1
		"05": 0, //FIN_WAIT2
		"06": 0, //TIME_WAIT
		"07": 0, //CLOSE
		"08": 0, //CLOSE_WAIT
		"09": 0, //LAST_ACK
		"0A": 0, //LISTEN
		"0B": 0, //CLOSING
	}

	reader := strings.NewReader(string(data))
	scanner := bufio.NewScanner(reader)

	scanner.Split(bufio.ScanLines)

	// Discard header line
	if b := scanner.Scan(); !b {
		return stats, scanner.Err()
	}

	for scanner.Scan() {
		line := scanner.Text()

		state := strings.Fields(line)
		// TCP state is the 4th field.
		// Format: sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt  uid timeout inode
		tcpState := state[3]
		_, ok := tcpStateMap[tcpState]
		if !ok {
			return stats, fmt.Errorf("invalid TCP stats line: %v", line)
		}
		tcpStateMap[tcpState]++
	}

	stats = info.TcpStat{
		Established: tcpStateMap["01"],
		SynSent:     tcpStateMap["02"],
		SynRecv:     tcpStateMap["03"],
		FinWait1:    tcpStateMap["04"],
		FinWait2:    tcpStateMap["05"],
		TimeWait:    tcpStateMap["06"],
		Close:       tcpStateMap["07"],
		CloseWait:   tcpStateMap["08"],
		LastAck:     tcpStateMap["09"],
		Listen:      tcpStateMap["0A"],
		Closing:     tcpStateMap["0B"],
	}

	return stats, nil
}

func udpStatsFromProc(rootFs string, pid int, file string) (info.UdpStat, error) {
	var err error
	var udpStats info.UdpStat

	udpStatsFile := path.Join(rootFs, "proc", strconv.Itoa(pid), file)

	r, err := os.Open(udpStatsFile)
	if err != nil {
		return udpStats, fmt.Errorf("failure opening %s: %v", udpStatsFile, err)
	}

	udpStats, err = scanUdpStats(r)
	if err != nil {
		return udpStats, fmt.Errorf("couldn't read udp stats: %v", err)
	}

	return udpStats, nil
}

func scanUdpStats(r io.Reader) (info.UdpStat, error) {
	var stats info.UdpStat

	scanner := bufio.NewScanner(r)
	scanner.Split(bufio.ScanLines)

	// Discard header line
	if b := scanner.Scan(); !b {
		return stats, scanner.Err()
	}

	listening := uint64(0)
	dropped := uint64(0)
	rxQueued := uint64(0)
	txQueued := uint64(0)

	for scanner.Scan() {
		line := scanner.Text()
		// Format: sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt  uid timeout inode ref pointer drops

		listening++

		fs := strings.Fields(line)
		if len(fs) != 13 {
			continue
		}

		rx, tx := uint64(0), uint64(0)
		fmt.Sscanf(fs[4], "%X:%X", &rx, &tx)
		rxQueued += rx
		txQueued += tx

		d, err := strconv.Atoi(string(fs[12]))
		if err != nil {
			continue
		}
		dropped += uint64(d)
	}

	stats = info.UdpStat{
		Listen:   listening,
		Dropped:  dropped,
		RxQueued: rxQueued,
		TxQueued: txQueued,
	}

	return stats, nil
}

func (h *Handler) GetProcesses() ([]int, error) {
	pids, err := h.cgroupManager.GetPids()
	if err != nil {
		return nil, err
	}
	return pids, nil
}

func minUint32(x, y uint32) uint32 {
	if x < y {
		return x
	}
	return y
}

// var to allow unit tests to stub it out
var numCpusFunc = getNumberOnlineCPUs

// Convert libcontainer stats to info.ContainerStats.
func setCpuStats(s *cgroups.Stats, ret *info.ContainerStats, withPerCPU bool) {
	ret.Cpu.Usage.User = s.CpuStats.CpuUsage.UsageInUsermode
	ret.Cpu.Usage.System = s.CpuStats.CpuUsage.UsageInKernelmode
	ret.Cpu.Usage.Total = s.CpuStats.CpuUsage.TotalUsage
	ret.Cpu.CFS.Periods = s.CpuStats.ThrottlingData.Periods
	ret.Cpu.CFS.ThrottledPeriods = s.CpuStats.ThrottlingData.ThrottledPeriods
	ret.Cpu.CFS.ThrottledTime = s.CpuStats.ThrottlingData.ThrottledTime

	if !withPerCPU {
		return
	}
	if len(s.CpuStats.CpuUsage.PercpuUsage) == 0 {
		// libcontainer's 'GetStats' can leave 'PercpuUsage' nil if it skipped the
		// cpuacct subsystem.
		return
	}

	numPossible := uint32(len(s.CpuStats.CpuUsage.PercpuUsage))
	// Note that as of https://patchwork.kernel.org/patch/8607101/ (kernel v4.7),
	// the percpu usage information includes extra zero values for all additional
	// possible CPUs. This is to allow statistic collection after CPU-hotplug.
	// We intentionally ignore these extra zeroes.
	numActual, err := numCpusFunc()
	if err != nil {
		klog.Errorf("unable to determine number of actual cpus; defaulting to maximum possible number: errno %v", err)
		numActual = numPossible
	}
	if numActual > numPossible {
		// The real number of cores should never be greater than the number of
		// datapoints reported in cpu usage.
		klog.Errorf("PercpuUsage had %v cpus, but the actual number is %v; ignoring extra CPUs", numPossible, numActual)
	}
	numActual = minUint32(numPossible, numActual)
	ret.Cpu.Usage.PerCpu = make([]uint64, numActual)

	for i := uint32(0); i < numActual; i++ {
		ret.Cpu.Usage.PerCpu[i] = s.CpuStats.CpuUsage.PercpuUsage[i]
	}

}

// Copied from
// https://github.com/moby/moby/blob/8b1adf55c2af329a4334f21d9444d6a169000c81/daemon/stats/collector_unix.go#L73
// Apache 2.0, Copyright Docker, Inc.
func getNumberOnlineCPUs() (uint32, error) {
	i, err := C.sysconf(C._SC_NPROCESSORS_ONLN)
	// According to POSIX - errno is undefined after successful
	// sysconf, and can be non-zero in several cases, so look for
	// error in returned value not in errno.
	// (https://sourceware.org/bugzilla/show_bug.cgi?id=21536)
	if i == -1 {
		return 0, err
	}
	return uint32(i), nil
}

func setDiskIoStats(s *cgroups.Stats, ret *info.ContainerStats) {
	ret.DiskIo.IoServiceBytes = DiskStatsCopy(s.BlkioStats.IoServiceBytesRecursive)
	ret.DiskIo.IoServiced = DiskStatsCopy(s.BlkioStats.IoServicedRecursive)
	ret.DiskIo.IoQueued = DiskStatsCopy(s.BlkioStats.IoQueuedRecursive)
	ret.DiskIo.Sectors = DiskStatsCopy(s.BlkioStats.SectorsRecursive)
	ret.DiskIo.IoServiceTime = DiskStatsCopy(s.BlkioStats.IoServiceTimeRecursive)
	ret.DiskIo.IoWaitTime = DiskStatsCopy(s.BlkioStats.IoWaitTimeRecursive)
	ret.DiskIo.IoMerged = DiskStatsCopy(s.BlkioStats.IoMergedRecursive)
	ret.DiskIo.IoTime = DiskStatsCopy(s.BlkioStats.IoTimeRecursive)
}

func setMemoryStats(s *cgroups.Stats, ret *info.ContainerStats) {
	ret.Memory.Usage = s.MemoryStats.Usage.Usage
	ret.Memory.MaxUsage = s.MemoryStats.Usage.MaxUsage
	ret.Memory.Failcnt = s.MemoryStats.Usage.Failcnt

	if s.MemoryStats.UseHierarchy {
		ret.Memory.Cache = s.MemoryStats.Stats["total_cache"]
		ret.Memory.RSS = s.MemoryStats.Stats["total_rss"]
		ret.Memory.Swap = s.MemoryStats.Stats["total_swap"]
		ret.Memory.MappedFile = s.MemoryStats.Stats["total_mapped_file"]
	} else {
		ret.Memory.Cache = s.MemoryStats.Stats["cache"]
		ret.Memory.RSS = s.MemoryStats.Stats["rss"]
		ret.Memory.Swap = s.MemoryStats.Stats["swap"]
		ret.Memory.MappedFile = s.MemoryStats.Stats["mapped_file"]
	}
	if v, ok := s.MemoryStats.Stats["pgfault"]; ok {
		ret.Memory.ContainerData.Pgfault = v
		ret.Memory.HierarchicalData.Pgfault = v
	}
	if v, ok := s.MemoryStats.Stats["pgmajfault"]; ok {
		ret.Memory.ContainerData.Pgmajfault = v
		ret.Memory.HierarchicalData.Pgmajfault = v
	}

	workingSet := ret.Memory.Usage
	if v, ok := s.MemoryStats.Stats["total_inactive_file"]; ok {
		if workingSet < v {
			workingSet = 0
		} else {
			workingSet -= v
		}
	}
	ret.Memory.WorkingSet = workingSet
}

func setNetworkStats(libcontainerStats *libcontainer.Stats, ret *info.ContainerStats) {
	ret.Network.Interfaces = make([]info.InterfaceStats, len(libcontainerStats.Interfaces))
	for i := range libcontainerStats.Interfaces {
		ret.Network.Interfaces[i] = info.InterfaceStats{
			Name:      libcontainerStats.Interfaces[i].Name,
			RxBytes:   libcontainerStats.Interfaces[i].RxBytes,
			RxPackets: libcontainerStats.Interfaces[i].RxPackets,
			RxErrors:  libcontainerStats.Interfaces[i].RxErrors,
			RxDropped: libcontainerStats.Interfaces[i].RxDropped,
			TxBytes:   libcontainerStats.Interfaces[i].TxBytes,
			TxPackets: libcontainerStats.Interfaces[i].TxPackets,
			TxErrors:  libcontainerStats.Interfaces[i].TxErrors,
			TxDropped: libcontainerStats.Interfaces[i].TxDropped,
		}
	}

	// Add to base struct for backwards compatibility.
	if len(ret.Network.Interfaces) > 0 {
		ret.Network.InterfaceStats = ret.Network.Interfaces[0]
	}
}

func newContainerStats(libcontainerStats *libcontainer.Stats, includedMetrics container.MetricSet) *info.ContainerStats {
	ret := &info.ContainerStats{
		Timestamp: time.Now(),
	}

	if s := libcontainerStats.CgroupStats; s != nil {
		setCpuStats(s, ret, includedMetrics.Has(container.PerCpuUsageMetrics))
		if includedMetrics.Has(container.DiskIOMetrics) {
			setDiskIoStats(s, ret)
		}
		setMemoryStats(s, ret)
	}
	if len(libcontainerStats.Interfaces) > 0 {
		setNetworkStats(libcontainerStats, ret)
	}
	return ret
}


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="48dp"
    android:height="48dp"
    android:viewportWidth="48"
    android:viewportHeight="48"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M18.45,36V32.95H42V36ZM18.45,25.5V22.5H42V25.5ZM6,15V12H42V15Z"/>
</vector>


text:
package org.sakaiproject.cmprovider.data;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * Represents a membership
 * @see org.sakaiproject.coursemanagement.api.Membership
 *
 * Example json:
 * { "userId": "crs142",
 *   "role": "student",
 *   "status": "active",
 *   "containerEid": "term1.CS101.1" }
 *
 * @author Christopher Schauer
 */
public class MembershipData {
  @NotNull
  @Size(min=1)
  public String userId;

  public String role;
  public String status;

  @NotNull
  @Size(min=1)
  public String memberContainer;

  public String getId() { return userId + "," + memberContainer; }

  public MembershipData() {}
}


text:
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;

namespace Stratis.SmartContracts.CLR.Validation
{
    /// <summary>
    /// Validates whether a type defines any fields
    /// </summary>
    public class FieldDefinitionValidator : ITypeDefinitionValidator
    {
         public IEnumerable<ValidationResult> Validate(TypeDefinition type)
         {
             // Don't apply to nested enums or structs
             if (type.IsNested && type.IsValueType)
                 return Enumerable.Empty<TypeDefinitionValidationResult>();

            var errors = new List<TypeDefinitionValidationResult>();

             foreach (FieldDefinition field in type.Fields)
             {
                 if (field.HasConstant) continue;

                errors.Add(new FieldDefinitionValidationResult(
                     "",
                    "Field usage",
                    $"Non-constant field {field.Name} defined in Type \"{type.Name}\". Fields are not persisted and may change values between calls."
                 ));
             }

             return errors;
         }

        public class FieldDefinitionValidationResult : TypeDefinitionValidationResult
        {
            public FieldDefinitionValidationResult(TypeDefinition type, FieldDefinition field)
                : base("", "Field usage", $"Non-constant field {field.Name} defined in Type \"{type.Name}\". Fields are not persisted and may change values between calls.")
            {
            }

            public FieldDefinitionValidationResult(string subjectName, string validationType, string message)
                : base(subjectName, validationType, message)
            {
            }
        }
    }
}