text:
package org.apache.accumulo.core.client.impl;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.MultiTableBatchWriter;
import org.apache.accumulo.core.client.MutationsRejectedException;
import org.apache.accumulo.core.client.TableNotFoundException;
import org.apache.accumulo.core.client.TableOfflineException;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.core.security.thrift.TCredentials;
import org.apache.accumulo.core.util.ArgumentChecker;
import org.apache.log4j.Logger;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.util.concurrent.UncheckedExecutionException;

public class MultiTableBatchWriterImpl implements MultiTableBatchWriter {
  public static final long DEFAULT_CACHE_TIME = 200;
  public static final TimeUnit DEFAULT_CACHE_TIME_UNIT = TimeUnit.MILLISECONDS;

  static final Logger log = Logger.getLogger(MultiTableBatchWriterImpl.class);
  private AtomicBoolean closed;
  private AtomicLong cacheLastState;

  private class TableBatchWriter implements BatchWriter {

    private String table;

    TableBatchWriter(String table) {
      this.table = table;
    }

    @Override
    public void addMutation(Mutation m) throws MutationsRejectedException {
      ArgumentChecker.notNull(m);
      bw.addMutation(table, m);
    }

    @Override
    public void addMutations(Iterable<Mutation> iterable) throws MutationsRejectedException {
      bw.addMutation(table, iterable.iterator());
    }

    @Override
    public void close() {
      throw new UnsupportedOperationException("Must close all tables, can not close an individual table");
    }

    @Override
    public void flush() {
      throw new UnsupportedOperationException("Must flush all tables, can not flush an individual table");
    }

  }

  /**
   * CacheLoader which will look up the internal table ID for a given table name.
   */
  private class TableNameToIdLoader extends CacheLoader<String,String> {

    @Override
    public String load(String tableName) throws Exception {
      String tableId = Tables.getNameToIdMap(instance).get(tableName);

      if (tableId == null)
        throw new TableNotFoundException(tableId, tableName, null);

      if (Tables.getTableState(instance, tableId) == TableState.OFFLINE)
        throw new TableOfflineException(instance, tableId);

      return tableId;
    }

  }

  private TabletServerBatchWriter bw;
  private ConcurrentHashMap<String,BatchWriter> tableWriters;
  private Instance instance;
  private final LoadingCache<String,String> nameToIdCache;

  public MultiTableBatchWriterImpl(Instance instance, TCredentials credentials, BatchWriterConfig config) {
    this(instance, credentials, config, DEFAULT_CACHE_TIME, DEFAULT_CACHE_TIME_UNIT);
  }

  public MultiTableBatchWriterImpl(Instance instance, TCredentials credentials, BatchWriterConfig config, long cacheTime, TimeUnit cacheTimeUnit) {
    ArgumentChecker.notNull(instance, credentials, config, cacheTimeUnit);
    this.instance = instance;
    this.bw = new TabletServerBatchWriter(instance, credentials, config);
    tableWriters = new ConcurrentHashMap<String,BatchWriter>();
    this.closed = new AtomicBoolean(false);
    this.cacheLastState = new AtomicLong(0);

    // Potentially up to ~500k used to cache names to IDs with "segments" of (maybe) ~1000 entries
    nameToIdCache = CacheBuilder.newBuilder().expireAfterWrite(cacheTime, cacheTimeUnit).concurrencyLevel(10).maximumSize(10000).initialCapacity(20)
        .build(new TableNameToIdLoader());
  }

  public boolean isClosed() {
    return this.closed.get();
  }

  public void close() throws MutationsRejectedException {
    this.closed.set(true);
    bw.close();
  }

  /**
   * Warning: do not rely upon finalize to close this class. Finalize is not guaranteed to be called.
   */
  @Override
  protected void finalize() {
    if (!closed.get()) {
      log.warn(MultiTableBatchWriterImpl.class.getSimpleName() + " not shutdown; did you forget to call close()?");
      try {
        close();
      } catch (MutationsRejectedException mre) {
        log.error(MultiTableBatchWriterImpl.class.getSimpleName() + " internal error.", mre);
        throw new RuntimeException("Exception when closing " + MultiTableBatchWriterImpl.class.getSimpleName(), mre);
      }
    }
  }

  /**
   * Returns the table ID for the given table name.
   *
   * @param tableName
   *          The name of the table which to find the ID for
   * @return The table ID, or null if the table name doesn't exist
   */
  private String getId(String tableName) throws TableNotFoundException {
    try {
      return nameToIdCache.get(tableName);
    } catch (UncheckedExecutionException e) {
      Throwable cause = e.getCause();

      log.error("Unexpected exception when fetching table id for " + tableName);

      if (null == cause) {
        throw new RuntimeException(e);
      } else if (cause instanceof TableNotFoundException) {
        throw (TableNotFoundException) cause;
      } else if (cause instanceof TableOfflineException) {
        throw (TableOfflineException) cause;
      }

      throw e;
    } catch (ExecutionException e) {
      Throwable cause = e.getCause();

      log.error("Unexpected exception when fetching table id for " + tableName);

      if (null == cause) {
        throw new RuntimeException(e);
      } else if (cause instanceof TableNotFoundException) {
        throw (TableNotFoundException) cause;
      } else if (cause instanceof TableOfflineException) {
        throw (TableOfflineException) cause;
      }

      throw new RuntimeException(e);
    }
  }

  @Override
  public BatchWriter getBatchWriter(String tableName) throws AccumuloException, AccumuloSecurityException, TableNotFoundException {
    ArgumentChecker.notNull(tableName);

    while (true) {
      long cacheResetCount = Tables.getCacheResetCount();

      // cacheResetCount could change after this point in time, but I think thats ok because just want to ensure this methods sees changes
      // made before it was called.

      long internalResetCount = cacheLastState.get();

      if (cacheResetCount > internalResetCount) {
        if (!cacheLastState.compareAndSet(internalResetCount, cacheResetCount)) {
          continue; // concurrent operation, lets not possibly move cacheLastState backwards in the case where a thread pauses for along time
        }

        nameToIdCache.invalidateAll();
        break;
      }

      break;
    }

    String tableId = getId(tableName);

    BatchWriter tbw = tableWriters.get(tableId);
    if (tbw == null) {
      tbw = new TableBatchWriter(tableId);
      tableWriters.put(tableId, tbw);
    }
    return tbw;
  }

  @Override
  public void flush() throws MutationsRejectedException {
    bw.flush();
  }

}


text:
using content::OpenURLParams;
using content::Referrer;

namespace {

SkBitmap GetGAIAPictureForNTP(const gfx::Image& image) {
  // This value must match the width and height value of login-status-icon
  // in new_tab.css.
  const int kLength = 27;
  SkBitmap bmp = skia::ImageOperations::Resize(*image.ToSkBitmap(),
      skia::ImageOperations::RESIZE_BEST, kLength, kLength);

  gfx::Canvas canvas(gfx::Size(kLength, kLength), 1.0f, false);
  canvas.DrawImageInt(gfx::ImageSkia::CreateFrom1xBitmap(bmp), 0, 0);

  // Draw a gray border on the inside of the icon.
  SkColor color = SkColorSetARGB(83, 0, 0, 0);
  canvas.DrawRect(gfx::Rect(0, 0, kLength - 1, kLength - 1), color);

  return canvas.ExtractImageRep().sk_bitmap();
}

// Puts the |content| into an element with the given CSS class.
base::string16 CreateElementWithClass(const base::string16& content,
                                      const std::string& tag_name,
                                      const std::string& css_class,
                                      const std::string& extends_tag) {
  base::string16 start_tag = base::ASCIIToUTF16("<" + tag_name +
      " class='" + css_class + "' is='" + extends_tag + "'>");
  base::string16 end_tag = base::ASCIIToUTF16("</" + tag_name + ">");
  return start_tag + net::EscapeForHTML(content) + end_tag;
}

}  // namespace

AppLauncherLoginHandler::AppLauncherLoginHandler() {}

AppLauncherLoginHandler::~AppLauncherLoginHandler() {}

void AppLauncherLoginHandler::RegisterMessages() {
  profile_info_watcher_.reset(new ProfileInfoWatcher(
      Profile::FromWebUI(web_ui()),
      base::Bind(&AppLauncherLoginHandler::UpdateLogin,
                 base::Unretained(this))));

  web_ui()->RegisterMessageCallback("initializeSyncLogin",
      base::Bind(&AppLauncherLoginHandler::HandleInitializeSyncLogin,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("showSyncLoginUI",
      base::Bind(&AppLauncherLoginHandler::HandleShowSyncLoginUI,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("loginMessageSeen",
      base::Bind(&AppLauncherLoginHandler::HandleLoginMessageSeen,
                 base::Unretained(this)));
  web_ui()->RegisterMessageCallback("showAdvancedLoginUI",
      base::Bind(&AppLauncherLoginHandler::HandleShowAdvancedLoginUI,
                 base::Unretained(this)));
}

void AppLauncherLoginHandler::HandleInitializeSyncLogin(
    const base::ListValue* args) {
  UpdateLogin();
}

void AppLauncherLoginHandler::HandleShowSyncLoginUI(
    const base::ListValue* args) {
  Profile* profile = Profile::FromWebUI(web_ui());
  if (!signin::ShouldShowPromo(profile))
    return;

  std::string username = SigninManagerFactory::GetForProfile(profile)
                             ->GetAuthenticatedAccountInfo()
                             .email;
  if (!username.empty())
    return;

  content::WebContents* web_contents = web_ui()->GetWebContents();
  Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
  if (!browser)
    return;

  // The user isn't signed in, show the sign in promo.
  signin_metrics::AccessPoint access_point =
      web_contents->GetURL().spec() == chrome::kChromeUIAppsURL
          ? signin_metrics::AccessPoint::ACCESS_POINT_APPS_PAGE_LINK
          : signin_metrics::AccessPoint::ACCESS_POINT_NTP_LINK;
  chrome::ShowBrowserSignin(browser, access_point);
  RecordInHistogram(NTP_SIGN_IN_PROMO_CLICKED);
}

void AppLauncherLoginHandler::RecordInHistogram(int type) {
  // Invalid type to record.
  if (type < NTP_SIGN_IN_PROMO_VIEWED ||
      type > NTP_SIGN_IN_PROMO_CLICKED) {
    NOTREACHED();
  } else {
    UMA_HISTOGRAM_ENUMERATION("SyncPromo.NTPPromo", type,
                              NTP_SIGN_IN_PROMO_BUCKET_BOUNDARY);
  }
}

void AppLauncherLoginHandler::HandleLoginMessageSeen(
    const base::ListValue* args) {
  Profile::FromWebUI(web_ui())->GetPrefs()->SetBoolean(
      prefs::kSignInPromoShowNTPBubble, false);
}

void AppLauncherLoginHandler::HandleShowAdvancedLoginUI(
    const base::ListValue* args) {
  content::WebContents* web_contents = web_ui()->GetWebContents();
  Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
  if (!browser)
    return;
  signin_metrics::AccessPoint access_point =
      web_contents->GetURL().spec() == chrome::kChromeUIAppsURL
          ? signin_metrics::AccessPoint::ACCESS_POINT_APPS_PAGE_LINK
          : signin_metrics::AccessPoint::ACCESS_POINT_NTP_LINK;
  chrome::ShowBrowserSignin(browser, access_point);
}

void AppLauncherLoginHandler::UpdateLogin() {
  std::string username = profile_info_watcher_->GetAuthenticatedUsername();
  base::string16 header, sub_header;
  std::string icon_url;
  Profile* profile = Profile::FromWebUI(web_ui());
  if (!username.empty()) {
    ProfileAttributesStorage& storage =
        g_browser_process->profile_manager()->GetProfileAttributesStorage();
    ProfileAttributesEntry* entry;
    if (storage.GetProfileAttributesWithPath(profile->GetPath(), &entry)) {
      // Only show the profile picture and full name for the single profile
      // case. In the multi-profile case the profile picture is visible in the
      // title bar and the full name can be ambiguous.
      if (storage.GetNumberOfProfiles() == 1) {
        base::string16 name = entry->GetGAIAName();
        if (!name.empty())
          header = CreateElementWithClass(name, "span", "profile-name", "");
        const gfx::Image* image = entry->GetGAIAPicture();
        if (image)
          icon_url = webui::GetBitmapDataUrl(GetGAIAPictureForNTP(*image));
      }
      if (header.empty()) {
        header = CreateElementWithClass(base::UTF8ToUTF16(username), "span",
                                        "profile-name", "");
      }
    }
  } else {
#if !defined(OS_CHROMEOS)
    // Chromeos does not show this status header.
    SigninManager* signin = SigninManagerFactory::GetForProfile(
        profile->GetOriginalProfile());
    if (!profile->IsLegacySupervised() && signin->IsSigninAllowed()) {
      base::string16 signed_in_link = l10n_util::GetStringUTF16(
          IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_LINK);
      signed_in_link =
          CreateElementWithClass(signed_in_link, "a", "", "action-link");
      header = l10n_util::GetStringFUTF16(
          IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_HEADER,
          l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));
      sub_header = l10n_util::GetStringFUTF16(
          IDS_SYNC_PROMO_NOT_SIGNED_IN_STATUS_SUB_HEADER, signed_in_link);

      content::RecordAction(
          web_ui()->GetWebContents()->GetURL().spec() ==
                  chrome::kChromeUIAppsURL
              ? base::UserMetricsAction("Signin_Impression_FromAppsPageLink")
              : base::UserMetricsAction("Signin_Impression_FromNTP"));
      // Record that the user was shown the promo.
      RecordInHistogram(NTP_SIGN_IN_PROMO_VIEWED);
    }
#endif
  }

  base::StringValue header_value(header);
  base::StringValue sub_header_value(sub_header);
  base::StringValue icon_url_value(icon_url);
  base::FundamentalValue is_user_signed_in(!username.empty());
  web_ui()->CallJavascriptFunction("ntp.updateLogin",
      header_value, sub_header_value, icon_url_value, is_user_signed_in);
}

// static
bool AppLauncherLoginHandler::ShouldShow(Profile* profile) {
#if defined(OS_CHROMEOS)
  // For now we don't care about showing sync status on Chrome OS. The promo
  // UI and the avatar menu don't exist on that platform.
  return false;
#else
  SigninManager* signin = SigninManagerFactory::GetForProfile(profile);
  return !profile->IsOffTheRecord() && signin && signin->IsSigninAllowed();
#endif
}

// static
void AppLauncherLoginHandler::GetLocalizedValues(
    Profile* profile, base::DictionaryValue* values) {
  PrefService* prefs = profile->GetPrefs();
  bool hide_sync = !prefs->GetBoolean(prefs::kSignInPromoShowNTPBubble);

  base::string16 message = hide_sync ? base::string16() :
      l10n_util::GetStringFUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_MESSAGE,
          l10n_util::GetStringUTF16(IDS_SHORT_PRODUCT_NAME));

  values->SetString("login_status_message", message);
  values->SetString("login_status_url",
      hide_sync ? std::string() : chrome::kSyncLearnMoreURL);
  values->SetString("login_status_advanced",
      hide_sync ? base::string16() :
      l10n_util::GetStringUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_ADVANCED));
  values->SetString("login_status_dismiss",
      hide_sync ? base::string16() :
      l10n_util::GetStringUTF16(IDS_SYNC_PROMO_NTP_BUBBLE_OK));
}

redpajama_set_name: RedPajamaGithub


text:
package eu.amidst.core.exponentialfamily;

import eu.amidst.core.distribution.ConditionalLinearGaussian;
import eu.amidst.core.utils.Vector;
import eu.amidst.core.variables.Assignment;
import eu.amidst.core.variables.Variable;
import org.apache.commons.math.linear.*;

import java.io.Serializable;
import java.util.*;
import java.util.stream.IntStream;

/**
 *
 * This class extends the abstract class {@link EF_ConditionalDistribution} and defines a Conditional Linear Gaussian (CLG) distribution in exponential family canonical form.
 *
 *
 For further details about how exponential family models are considered in this toolbox, take a look at the following paper:
 * Representation, Inference and Learning of Bayesian Networks as Conjugate Exponential Family Models. Technical Report.
 * (pdf)

 */
public class EF_Normal_NormalParents extends EF_ConditionalDistribution  {

    /** Represents the size of the sufficient statistics in this EF_Normal_NormalParents distribution. */
    int sizeSS;

    /** Represents the number of parents. */
    int nOfParents;

    /** Represents the vector of beta values (without beta0)*/
    double[] betas;

    /** Represents the beta0 value*/
    double beta0;

    /** Represents the variance */
    double variance;

    /**
     * Creates a new EF_Normal_NormalParents distribution.
     * @param var_ the main variable.
     * @param parents_ the list of Normal parent variables.
     */
    public EF_Normal_NormalParents(Variable var_, List<Variable> parents_) {

        this.var = var_;
        this.parents = parents_;

        if (!var_.isNormal())
            throw new UnsupportedOperationException("Creating a Normal|Normal EF distribution for a non-gaussian child variable.");

        for (Variable v : parents) {
            if (!v.isNormal())
                throw new UnsupportedOperationException("Creating a Normal|Normal EF distribution for a non-gaussian parent variable.");
        }

        nOfParents = parents.size();
        sizeSS = nOfParents*nOfParents + 3 * nOfParents + 2 ; // (n+1)^2 (covariance matrix of YX) + n (E(Y)) + 1 (E(X))

        this.var=var_;
        this.momentParameters = null;//this.createEmtpyCompoundVector();
        this.naturalParameters = null;//this.createEmtpyCompoundVector();

        this.beta0 = 0;
        this.variance = 0;
        this.betas = new double[parents.size()];
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void updateNaturalFromMomentParameters() {

        /*
         * First step: means and covariances
         */
        CompoundVector globalMomentParam = (CompoundVector)this.momentParameters;
        double mean_X = globalMomentParam.getXYbaseMatrix().getEntry(0);
        RealVector mean_Y = globalMomentParam.getTheta_beta0BetaRV();

        double cov_XX = globalMomentParam.getcovbaseMatrix().getEntry(0, 0) - mean_X*mean_X;
        RealMatrix cov_YY = globalMomentParam.getcovbaseMatrix().getSubMatrix(1, nOfParents, 1, nOfParents).
                subtract(mean_Y.outerProduct(mean_Y));
        RealVector cov_XY = globalMomentParam.getcovbaseMatrix().getSubMatrix(0, 0, 1, nOfParents).getRowVector(0).
                subtract(mean_Y.mapMultiply(mean_X));
        //RealVector cov_YX = cov_XY; //outerProduct transposes the vector automatically

        /*
         * Second step: betas and variance
         */
        RealMatrix cov_YYInverse = new LUDecompositionImpl(cov_YY).getSolver().getInverse();
        RealVector beta = cov_YYInverse.preMultiply(cov_XY);

        this.betas = new double[beta.getDimension()];
        for (int i = 0; i<beta.getDimension(); i++){
            this.betas[i] = beta.getEntry(i);
        }
        this.beta0 = mean_X - beta.dotProduct(mean_Y);
        this.variance = cov_XX - beta.dotProduct(cov_XY);

    }

    public void setBetas(double[] betas) {
        this.betas = betas;
    }

    public void setBeta0(double beta0) {
        this.beta0 = beta0;
    }

    public void setVariance(double variance) {
        this.variance = variance;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void updateMomentFromNaturalParameters() {
        //throw new UnsupportedOperationException("Method not implemented yet!");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public NaturalParameters getNaturalParameters(){

        CompoundVector naturalParametersCompound = this.createEmtpyCompoundVector();

        /* 1) theta_0  */
        double theta_0 = beta0 / variance;
        naturalParametersCompound.setThetaBeta0_NatParam(theta_0);

        /* 2) theta_0Theta */
        double variance2Inv =  1.0/(2*variance);
        //IntStream.range(0,coeffParents.length).forEach(i-> coeffParents[i]*=(beta_0*variance2Inv));
        double[] theta0_beta = Arrays.stream(betas).map(w->-w*beta0/variance).toArray();
        naturalParametersCompound.setThetaBeta0Beta_NatParam(theta0_beta);

        /* 3) theta_Minus1 */
        double theta_Minus1 = -variance2Inv;

        /* 4) theta_beta & 5) theta_betaBeta */
        naturalParametersCompound.setThetaCov_NatParam(theta_Minus1,betas, variance2Inv);

        this.naturalParameters = naturalParametersCompound;

        return this.naturalParameters;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SufficientStatistics getSufficientStatistics(Assignment data) {
        CompoundVector vectorSS = this.createEmtpyCompoundVector();

        double[] Xarray = {data.getValue(this.var)};

        double[] Yarray = this.parents.stream()
                .mapToDouble(w->data.getValue(w))
                .toArray();
        RealVector XYRealVector = new ArrayRealVector(Xarray,Yarray);
        vectorSS.setXYbaseVector(XYRealVector);

        RealMatrix covRealmatrix = XYRealVector.outerProduct(XYRealVector);

        vectorSS.setcovbaseVector(covRealmatrix);

        return vectorSS;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int sizeOfSufficientStatistics() {
        return sizeSS;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double computeLogBaseMeasure(Assignment dataInstance) {
        return -0.5*Math.log(2*Math.PI);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double computeLogNormalizer() {
        return (beta0*beta0)/(2*variance) + 0.5*Math.log(variance);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CompoundVector createZeroVector() {
        return new CompoundVector(nOfParents);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SufficientStatistics createInitSufficientStatistics() {
        CompoundVector vectorSS = this.createEmtpyCompoundVector();

        double[] Xarray = {0.0};

        double[] Yarray = this.parents.stream()
                .mapToDouble(w-> 0.0)
                .toArray();
        RealVector XYRealVector = new ArrayRealVector(Xarray,Yarray);
        vectorSS.setXYbaseVector(XYRealVector);

        RealMatrix covRealmatrix = new Array2DRowRealMatrix(Yarray.length + 1,Yarray.length + 1);

        //We perform the "laplace" correction in that way to break symmetric covariance matrixes.
        Random rand = new Random(0);
        for (int i = 0; i < Yarray.length + 1; i++) {
            for (int j = 0; j < Yarray.length + 1; j++) {
                covRealmatrix.addToEntry(i,j,rand.nextDouble()+0.01);
            }
        }
        //covRealmatrix = covRealmatrix.scalarAdd(1.0);

        vectorSS.setcovbaseVector(covRealmatrix);

        return vectorSS;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double getExpectedLogNormalizer(Variable parent, Map<Variable, MomentParameters> momentChildCoParents) {
        throw new UnsupportedOperationException("No Implemented. This method is no really needed");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public double getExpectedLogNormalizer(Map<Variable, MomentParameters> momentParents) {
        int nOfBetas = this.betas.length;

        //From Beta_0, Beta, gamma and Y parents to variable X.
        double beta0Squared;
        double invVariance;
        double dotProductBetaY = 0;
        double sumSquaredMoments=0;
        double sumSquaredMeanMoments=0;

        for (int i = 0; i < nOfBetas; i++) {
            dotProductBetaY += momentParents.get(this.parents.get(i)).get(0) *
                    betas[i];
            sumSquaredMoments += betas[i]*betas[i]*
                    momentParents.get(this.parents.get(i)).get(1);

            sumSquaredMeanMoments += Math.pow(betas[i] *
                    momentParents.get(this.parents.get(i)).get(0), 2);
        }

        beta0Squared = beta0*beta0;
        invVariance = 1/variance;
        double logVar = Math.log(variance);

        return -0.5*logVar +  0.5*invVariance*(beta0Squared + dotProductBetaY*dotProductBetaY - sumSquaredMeanMoments + sumSquaredMoments + 2*beta0*dotProductBetaY);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public NaturalParameters getExpectedNaturalFromParents(Map<Variable, MomentParameters> momentParents) {
        int nOfBetas = this.betas.length;

        double dotProductBetaY = 0;

        for (int i = 0; i < nOfBetas; i++) {
            dotProductBetaY += momentParents.get(this.parents.get(i)).get(0) *
                    betas[i];
        }

        NaturalParameters naturalParameters = new EF_Normal.ArrayVectorParameter(2);

        naturalParameters.set(0, this.beta0 + dotProductBetaY);
        naturalParameters.set(1, 1/variance);

        return naturalParameters;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public NaturalParameters getExpectedNaturalToParent(Variable parent, Map<Variable, MomentParameters> momentChildCoParents) {

        int parentID=this.parents.indexOf(parent);

        if (betas[parentID]==0){
            NaturalParameters naturalParameters = new EF_Normal.ArrayVectorParameter(2);
            naturalParameters.set(0,0);
            naturalParameters.set(1,0);

            return naturalParameters;
        }

        int nOfBetas = this.betas.length;

        double dotProductBetaY = 0;

        for (int i = 0; i < nOfBetas; i++) {
            dotProductBetaY += momentChildCoParents.get(this.parents.get(i)).get(0) *
                    betas[i];
        }

        double X = momentChildCoParents.get(var).get(0);

        double beta_iSquared = betas[parentID]*betas[parentID];
        double beta_i = betas[parentID];
        double Y_i = momentChildCoParents.get(this.parents.get(parentID)).get(0);
        double invVariance = 1/variance;

        double factor = beta_i/beta_iSquared;

        double mean = factor*(-beta0 + X - (dotProductBetaY-beta_i*Y_i));
        double precision = beta_iSquared*invVariance;

        NaturalParameters naturalParameters = new EF_Normal.ArrayVectorParameter(2);
        naturalParameters.set(0,mean);
        naturalParameters.set(1,precision);

        return naturalParameters;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public ConditionalLinearGaussian toConditionalDistribution() {
        ConditionalLinearGaussian normal_normal = new ConditionalLinearGaussian(this.getVariable(), this.getConditioningVariables());

        normal_normal.setIntercept(beta0);
        normal_normal.setCoeffParents(Arrays.copyOfRange(betas, 0, betas.length));
        normal_normal.setVariance(this.variance);

        return normal_normal;
    }

    /**
     * Creates an empty compound parameter vector.
     * @return a {@link CompoundVector} object.
     */
    public CompoundVector createEmtpyCompoundVector() {
        return new CompoundVector(nOfParents);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public List<EF_ConditionalDistribution> toExtendedLearningDistribution(ParameterVariables variables, String nameSuffix) {
        List<EF_ConditionalDistribution> conditionalDistributions = new ArrayList<>();

        Variable varGamma = variables.newGammaParameter(this.var.getName() + "_Gamma_Parameter_"+nameSuffix+"_" + variables.getNumberOfVars());

        conditionalDistributions.add(varGamma.getDistributionType().newEFUnivariateDistribution());

        Variable normalBeta0 = variables.newGaussianParameter(this.var.getName() + "_alpha_Parameter_"+nameSuffix+"_"+variables.getNumberOfVars());

        conditionalDistributions.add(normalBeta0.getDistributionType().newEFUnivariateDistribution());

        List<Variable> betas = new ArrayList<>();
        for (int i = 0; i < this.parents.size(); i++) {
            Variable normalBetai = variables.newGaussianParameter(this.var.getName() + "_beta"+ (i+1) + "_Parameter_"+nameSuffix+"_"+variables.getNumberOfVars());
            betas.add(normalBetai);
            conditionalDistributions.add(normalBetai.getDistributionType().newEFUnivariateDistribution());
        }

        EF_Normal_Normal_Gamma condDist = new EF_Normal_Normal_Gamma(this.var,this.parents,normalBeta0, betas, varGamma);

        conditionalDistributions.add(condDist);

        return conditionalDistributions;
    }

    public static class CompoundVector implements SufficientStatistics, MomentParameters, NaturalParameters, Serializable {

        /** Represents the serial version ID for serializing the object. */
        private static final long serialVersionUID = -3436599636425587512L;

        int size;
        int nOfParents;
        RealVector XYbaseVector;
        RealMatrix covbaseVector;

        public CompoundVector(int nOfParents_) {

            nOfParents = nOfParents_;

            // E(XY) - Index {0, ..., noParents+1}
            XYbaseVector = new ArrayRealVector(nOfParents+1);

            // E(XY) - Index (i * (noParents+1) ) + j (+ noParents + 1)
            covbaseVector = new Array2DRowRealMatrix(nOfParents+1,nOfParents+1);

            size = nOfParents*nOfParents + 3 * nOfParents + 2;

        }

        public void setXYbaseVector(RealVector XYbaseVector_){
            XYbaseVector = XYbaseVector_;
        }

        public void setcovbaseVector(RealMatrix covbaseVector_){
            covbaseVector = covbaseVector_;
        }

        public void setMatrixByPosition(int position, RealMatrix vec) {
            switch (position){
                case 0: XYbaseVector = vec.getRowVector(0);
                case 1: covbaseVector = vec;
                default:
                    throw new IndexOutOfBoundsException("There are only two components (indexes 0 for XY and 1 for the" +
                            " cov. matrix) in a normal|normal EF distribution.");

            }
        }

        public RealVector getXYbaseMatrix(){
            return XYbaseVector;
        }

        public RealMatrix getcovbaseMatrix(){
            return covbaseVector;
        }

        public RealMatrix getMatrixByPosition(int position) {
            switch (position){
                case 0: return new Array2DRowRealMatrix(XYbaseVector.getData());//column RealMatrix
                case 1: return covbaseVector;
                default:
                    throw new IndexOutOfBoundsException("There are only two components (indexes 0 for XY and 1 for the" +
                            " cov. matrix) in a normal|normal EF distribution.");

            }
        }

        private static boolean isBetween(int x, int lower, int upper) {
            return lower <= x && x <= upper;
        }

        @Override
        public double get(int i) {
            if(i==0) {
                return XYbaseVector.getEntry(0);
            }else if(isBetween(i,1,nOfParents)) {
                return XYbaseVector.getEntry(i);
            }else{
                i = i-(nOfParents+1);
                int row = i/(nOfParents+1);
                int column = i - row*(nOfParents+1);
                return covbaseVector.getEntry(row, column);
            }
        }

        @Override
        public void set(int i, double val) {
            if(i==0) {
                XYbaseVector.setEntry(0, val);
            }else if(isBetween(i,1,nOfParents)) {
                XYbaseVector.setEntry(i, val);
            }else{
                i = i-(nOfParents+1);
                int row = i/(nOfParents+1);
                int column = i - row*(nOfParents+1);
                covbaseVector.setEntry(row, column, val);
            }
        }

        public void setThetaBeta0_NatParam(double val){
            XYbaseVector.setEntry(0,val);
        }

        public void setThetaBeta0Beta_NatParam(double[] val) {
            XYbaseVector.setSubVector(1,val);
        }

        public void setThetaCov_NatParam(double theta_Minus1, double[] beta, double variance2Inv){
            double[] theta_Minus1array = {theta_Minus1};
            double[] theta_beta = Arrays.stream(beta).map(w -> w * variance2Inv).toArray();
            RealVector covXY = new ArrayRealVector(theta_Minus1array, theta_beta);
            covbaseVector.setColumnVector(0, covXY);
            covbaseVector.setRowVector(0, covXY);

            RealVector betaRV = new ArrayRealVector(beta);
            RealMatrix theta_betaBeta = betaRV.outerProduct(betaRV).scalarMultiply(-variance2Inv);
            covbaseVector.setSubMatrix(theta_betaBeta.getData(),1,1);
        }

        public double getTheta_beta0(){
            return XYbaseVector.getEntry(0);
        }

        public double[] getTheta_beta0Beta(){
            return getXYbaseMatrix().getSubVector(1,nOfParents).toArray();

        }

        public double getTheta_Minus1(){
            return getcovbaseMatrix().getEntry(0,0);
        }

        public double[] getTheta_Beta(){
            return getcovbaseMatrix().getSubMatrix(0,0,1,nOfParents).getRow(0);
        }

        public double[][] getTheta_BetaBeta(){
            return getcovbaseMatrix().getSubMatrix(1,nOfParents,1,nOfParents).getData();
        }

        public RealVector getTheta_beta0BetaRV(){
            return getXYbaseMatrix().getSubVector(1,nOfParents);
        }

        public RealVector getTheta_BetaRV(){
            return getcovbaseMatrix().getSubMatrix(0,0,1,nOfParents).getRowVector(0);
        }

        public RealMatrix getTheta_BetaBetaRM(){
            return getcovbaseMatrix().getSubMatrix(1, nOfParents, 1, nOfParents);
        }

        @Override
        public int size() {
            return size;
        }

        @Override
        public void sum(Vector vector) {
            this.sum((CompoundVector)vector);
        }

        @Override
        public void copy(Vector vector) {
            this.copy((CompoundVector)vector);
        }

        @Override
        public void divideBy(double val) {
            //TODO Try to find a self based operation for efficiency
            XYbaseVector.mapDivideToSelf(val);
            covbaseVector = covbaseVector.scalarMultiply(1.0/val);
        }

        @Override
        public double dotProduct(Vector vec) {
            return this.dotProduct((CompoundVector)vec);
        }

        public double dotProduct(CompoundVector vec) {
            double result = this.getXYbaseMatrix().dotProduct(vec.getXYbaseMatrix()); //theta1
            result += IntStream.range(0,nOfParents+1).mapToDouble(p ->
                    this.getcovbaseMatrix().getRowVector(p).dotProduct(vec.getcovbaseMatrix().getRowVector(p))).sum();
            return result;
        }

        public void copy(CompoundVector vector) {
            XYbaseVector = vector.getXYbaseMatrix().copy();
            covbaseVector = vector.getcovbaseMatrix().copy();

        }

        public void sum(CompoundVector vector) {
            //TODO Try to find a self based operation for efficiency
            XYbaseVector = XYbaseVector.add(vector.getXYbaseMatrix());
            covbaseVector = covbaseVector.add(vector.getcovbaseMatrix());
        }

    }

}


text:
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;

namespace ArcGISRuntimeSDKDotNet_DesktopSamples
{
	public partial class SdkInstallNeeded : UserControl
	{
		public SdkInstallNeeded()
		{
			InitializeComponent();
		}

		private void DeveloperSiteLink_Click(object sender, RoutedEventArgs e)
		{
			Process.Start(new ProcessStartInfo("http://esriurl.com/dotnetsdk"));
		}

		private void ReadMore_Click(object sender, RoutedEventArgs e)
		{
			Process.Start(new ProcessStartInfo("https://github.com/Esri/arcgis-runtime-samples-dotnet/blob/master/README.md"));
		}
	}
}


text:
var structAppLayerProtoDetectProbingParserPort__ =
[
    [ "alproto_mask", "structAppLayerProtoDetectProbingParserPort__.html#a05eb419b18f1bef3e1e1cbd8293b4275", null ],
    [ "dp", "structAppLayerProtoDetectProbingParserPort__.html#a09c66e929791ff758187949571c06071", null ],
    [ "dp_max_depth", "structAppLayerProtoDetectProbingParserPort__.html#a2c3125fc9ddd8411ccffe70acb51b0ff", null ],
    [ "next", "structAppLayerProtoDetectProbingParserPort__.html#af0efe6ef4cbd512d2911b6c2a90158cd", null ],
    [ "port", "structAppLayerProtoDetectProbingParserPort__.html#a13c2b2dccdf8c822bf042d3c51eb8107", null ],
    [ "sp", "structAppLayerProtoDetectProbingParserPort__.html#ad65ef654e1969c5fa6fbc3c66398ba24", null ],
    [ "sp_max_depth", "structAppLayerProtoDetectProbingParserPort__.html#ac023d22795cbc0dc6679fbf8b8d39b16", null ]
];


text:
from __future__ import unicode_literals

from operator import attrgetter

from django.db import connection
from django.db.models import Value
from django.db.models.functions import Lower
from django.test import (
    TestCase, override_settings, skipIfDBFeature, skipUnlessDBFeature,
)

from .models import (
    Country, NoFields, Pizzeria, ProxyCountry, ProxyMultiCountry,
    ProxyMultiProxyCountry, ProxyProxyCountry, Restaurant, State, TwoFields,
)

class BulkCreateTests(TestCase):
    def setUp(self):
        self.data = [
            Country(name="United States of America", iso_two_letter="US"),
            Country(name="The Netherlands", iso_two_letter="NL"),
            Country(name="Germany", iso_two_letter="DE"),
            Country(name="Czech Republic", iso_two_letter="CZ")
        ]

    def test_simple(self):
        created = Country.objects.bulk_create(self.data)
        self.assertEqual(len(created), 4)
        self.assertQuerysetEqual(Country.objects.order_by("-name"), [
            "United States of America", "The Netherlands", "Germany", "Czech Republic"
        ], attrgetter("name"))

        created = Country.objects.bulk_create([])
        self.assertEqual(created, [])
        self.assertEqual(Country.objects.count(), 4)

    @skipUnlessDBFeature('has_bulk_insert')
    def test_efficiency(self):
        with self.assertNumQueries(1):
            Country.objects.bulk_create(self.data)

    def test_multi_table_inheritance_unsupported(self):
        expected_message = "Can't bulk create a multi-table inherited model"
        with self.assertRaisesMessage(ValueError, expected_message):
            Pizzeria.objects.bulk_create([
                Pizzeria(name="The Art of Pizza"),
            ])
        with self.assertRaisesMessage(ValueError, expected_message):
            ProxyMultiCountry.objects.bulk_create([
                ProxyMultiCountry(name="Fillory", iso_two_letter="FL"),
            ])
        with self.assertRaisesMessage(ValueError, expected_message):
            ProxyMultiProxyCountry.objects.bulk_create([
                ProxyMultiProxyCountry(name="Fillory", iso_two_letter="FL"),
            ])

    def test_proxy_inheritance_supported(self):
        ProxyCountry.objects.bulk_create([
            ProxyCountry(name="Qwghlm", iso_two_letter="QW"),
            Country(name="Tortall", iso_two_letter="TA"),
        ])
        self.assertQuerysetEqual(ProxyCountry.objects.all(), {
            "Qwghlm", "Tortall"
        }, attrgetter("name"), ordered=False)

        ProxyProxyCountry.objects.bulk_create([
            ProxyProxyCountry(name="Netherlands", iso_two_letter="NT"),
        ])
        self.assertQuerysetEqual(ProxyProxyCountry.objects.all(), {
            "Qwghlm", "Tortall", "Netherlands",
        }, attrgetter("name"), ordered=False)

    def test_non_auto_increment_pk(self):
        State.objects.bulk_create([
            State(two_letter_code=s)
            for s in ["IL", "NY", "CA", "ME"]
        ])
        self.assertQuerysetEqual(State.objects.order_by("two_letter_code"), [
            "CA", "IL", "ME", "NY",
        ], attrgetter("two_letter_code"))

    @skipUnlessDBFeature('has_bulk_insert')
    def test_non_auto_increment_pk_efficiency(self):
        with self.assertNumQueries(1):
            State.objects.bulk_create([
                State(two_letter_code=s)
                for s in ["IL", "NY", "CA", "ME"]
            ])
        self.assertQuerysetEqual(State.objects.order_by("two_letter_code"), [
            "CA", "IL", "ME", "NY",
        ], attrgetter("two_letter_code"))

    @skipIfDBFeature('allows_auto_pk_0')
    def test_zero_as_autoval(self):
        """
        Zero as id for AutoField should raise exception in MySQL, because MySQL
        does not allow zero for automatic primary key.
        """
        valid_country = Country(name='Germany', iso_two_letter='DE')
        invalid_country = Country(id=0, name='Poland', iso_two_letter='PL')
        with self.assertRaises(ValueError):
            Country.objects.bulk_create([valid_country, invalid_country])

    def test_batch_same_vals(self):
        # Sqlite had a problem where all the same-valued models were
        # collapsed to one insert.
        Restaurant.objects.bulk_create([
            Restaurant(name='foo') for i in range(0, 2)
        ])
        self.assertEqual(Restaurant.objects.count(), 2)

    def test_large_batch(self):
        with override_settings(DEBUG=True):
            connection.queries_log.clear()
            TwoFields.objects.bulk_create([
                TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)
            ])
        self.assertEqual(TwoFields.objects.count(), 1001)
        self.assertEqual(
            TwoFields.objects.filter(f1__gte=450, f1__lte=550).count(),
            101)
        self.assertEqual(TwoFields.objects.filter(f2__gte=901).count(), 101)

    @skipUnlessDBFeature('has_bulk_insert')
    def test_large_single_field_batch(self):
        # SQLite had a problem with more than 500 UNIONed selects in single
        # query.
        Restaurant.objects.bulk_create([
            Restaurant() for i in range(0, 501)
        ])

    @skipUnlessDBFeature('has_bulk_insert')
    def test_large_batch_efficiency(self):
        with override_settings(DEBUG=True):
            connection.queries_log.clear()
            TwoFields.objects.bulk_create([
                TwoFields(f1=i, f2=i + 1) for i in range(0, 1001)
            ])
            self.assertLess(len(connection.queries), 10)

    def test_large_batch_mixed(self):
        """
        Test inserting a large batch with objects having primary key set
        mixed together with objects without PK set.
        """
        with override_settings(DEBUG=True):
            connection.queries_log.clear()
            TwoFields.objects.bulk_create([
                TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
                for i in range(100000, 101000)])
        self.assertEqual(TwoFields.objects.count(), 1000)
        # We can't assume much about the ID's created, except that the above
        # created IDs must exist.
        id_range = range(100000, 101000, 2)
        self.assertEqual(TwoFields.objects.filter(id__in=id_range).count(), 500)
        self.assertEqual(TwoFields.objects.exclude(id__in=id_range).count(), 500)

    @skipUnlessDBFeature('has_bulk_insert')
    def test_large_batch_mixed_efficiency(self):
        """
        Test inserting a large batch with objects having primary key set
        mixed together with objects without PK set.
        """
        with override_settings(DEBUG=True):
            connection.queries_log.clear()
            TwoFields.objects.bulk_create([
                TwoFields(id=i if i % 2 == 0 else None, f1=i, f2=i + 1)
                for i in range(100000, 101000)])
            self.assertLess(len(connection.queries), 10)

    def test_explicit_batch_size(self):
        objs = [TwoFields(f1=i, f2=i) for i in range(0, 4)]
        TwoFields.objects.bulk_create(objs, 2)
        self.assertEqual(TwoFields.objects.count(), len(objs))
        TwoFields.objects.all().delete()
        TwoFields.objects.bulk_create(objs, len(objs))
        self.assertEqual(TwoFields.objects.count(), len(objs))

    def test_empty_model(self):
        NoFields.objects.bulk_create([NoFields() for i in range(2)])
        self.assertEqual(NoFields.objects.count(), 2)

    @skipUnlessDBFeature('has_bulk_insert')
    def test_explicit_batch_size_efficiency(self):
        objs = [TwoFields(f1=i, f2=i) for i in range(0, 100)]
        with self.assertNumQueries(2):
            TwoFields.objects.bulk_create(objs, 50)
        TwoFields.objects.all().delete()
        with self.assertNumQueries(1):
            TwoFields.objects.bulk_create(objs, len(objs))

    @skipUnlessDBFeature('has_bulk_insert')
    def test_bulk_insert_expressions(self):
        Restaurant.objects.bulk_create([
            Restaurant(name="Sam's Shake Shack"),
            Restaurant(name=Lower(Value("Betty's Beetroot Bar")))
        ])
        bbb = Restaurant.objects.filter(name="betty's beetroot bar")
        self.assertEqual(bbb.count(), 1)


text:
package com.pcalouche.spat.exception;

import org.springframework.http.HttpStatus;

public class ApiForbiddenException extends ApiException {
    public static final String DEFAULT_MESSAGE = "Resource access, creation, or modification is forbidden.";

    public ApiForbiddenException() {
        this(DEFAULT_MESSAGE);
    }

    public ApiForbiddenException(String message) {
        super(message, HttpStatus.FORBIDDEN);
    }
}


text:
package main

import (
	"fmt"
	"os"
	"code.google.com/p/gcfg" // https://code.google.com/p/gcfg/
)

type Config struct {
        Neurio struct {
                NeurioClientID string
                NeurioClientSecret string
        }
}

func main() {
	var cfg Config
	err := gcfg.ReadFileInto(&cfg, "config.gcfg")
	if err != nil {
  		fmt.Println("error:", err)
  		pwd, err2 := os.Getwd()
    	if err2 != nil {
	        fmt.Println(err)
        	os.Exit(1)
    	}
    	fmt.Println("You should place the file config.gcfg in this directory:",pwd)
  		os.Exit(1)
	}
	fmt.Println("Values from config.gcfg: Neurioclientid =", cfg.Neurio.NeurioClientID,"Neurioclientsecret =",cfg.Neurio.NeurioClientSecret)
	fmt.Println("Neurio Webservice API Version reported: ", NeurioAPIVersion() )

	token, err1 := NeurioAccessToken(cfg.Neurio.NeurioClientID,cfg.Neurio.NeurioClientSecret)
    if err1 != nil {
        fmt.Println("Error!", err1)
        fmt.Println("Neurio2Go failed to get an access token for the clientID and clientSecret provided.")
        var appuri = "https://my.neur.io/#settings/applications/"+cfg.Neurio.NeurioClientID
        fmt.Println("Check if your App exists by opening:", appuri)
        fmt.Println("or create a new app and update your config file: https://my.neur.io/#settings/applications/register")
        os.Exit(1)
    } else {
        fmt.Println("Access Token: ", token )
    }

   var NeurioCurrentUserGlobal UserItem
   ncuerr := NeurioCurrentUserRaw(token, &NeurioCurrentUserGlobal)
   if ncuerr != nil {
        fmt.Println("Error! ", ncuerr)
        os.Exit(1)
    }

   fmt.Println("Your UserID is",NeurioCurrentUserGlobal.Id)

   fmt.Println("Your Sensor ID is",NeurioCurrentUserGlobal.Locations[0].Sensors[0].Channels[3].SensorId)
   fmt.Println("Your last power usage sample is",NeurioLastSample(token,NeurioCurrentUserGlobal.Locations[0].Sensors[0].SensorId),"w")

   var NeurioAppliances ApplianceList
   nalerr := myNeurioAppliances(token, NeurioCurrentUserGlobal.Locations[0].Sensors[0].LocationId, &NeurioAppliances)
   if nalerr != nil {
        fmt.Println("Error! ", nalerr)
        os.Exit(1)
    }

   for i, n := range NeurioAppliances {
   		fmt.Println("Your appliance", i, n.Label, "has the name", n.Name  )
   }
}


text:
package fr.univnantes.termsuite.api;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

import com.google.common.base.Preconditions;
import com.google.common.collect.ComparisonChain;

import fr.univnantes.termsuite.model.Property;
import fr.univnantes.termsuite.model.PropertyHolder;
import fr.univnantes.termsuite.model.PropertyHolderBase;

public abstract class Ordering<T extends Enum<T> & Property<?>, U extends PropertyHolder<T>, Z> {

	protected class Direction {
		private T property;
		private boolean ascending;
		private Direction(T property, boolean ascending) {
			super();
			Preconditions.checkNotNull(property);
			this.property = property;
			this.ascending = ascending;
		}
		protected T getProperty() {
			return property;
		}
		protected boolean isAscending() {
			return ascending;
		}
		@Override
		public String toString() {
			return String.format("%s %s", property.getJsonField(), ascending ? "asc" : "desc");
		}
	}

	protected List<Direction> directions = new ArrayList<>();

	@SuppressWarnings("unchecked")
	public Z asc(T property) {
		directions.add(new Direction(property, true));
		return (Z)this;
	}

	@SuppressWarnings("unchecked")
	public Z addSortingProperty(T property, boolean asc) {
		directions.add(new Direction(property, asc));
		return (Z)this;
	}

	@SuppressWarnings("unchecked")
	public Z desc(T property) {
		directions.add(new Direction(property, false));
		return (Z)this;
	}

	public Comparator<U> toComparator() {
		for(Direction d:directions)
			PropertyHolderBase.checkComparable(d.getProperty().getRange(), d.getProperty());

		return new Comparator<U>() {
			@Override
			public int compare(U o1, U o2) {
				ComparisonChain chain = ComparisonChain.start();
				Comparable<?> v1, v2;
				for(Direction d:directions) {
					v1 = (Comparable<?>)o1.getPropertyValueUnchecked(d.getProperty());
					v2 = (Comparable<?>)o2.getPropertyValueUnchecked(d.getProperty());
					if(d.isAscending()) {
						if(v1 != null && v2 != null)
							chain = chain.compare(v1,v2);
						else if(v1 == null && v2 != null)
							return -1;
						else if(v1 != null && v2 == null)
							return 1;

					} else {

						if(v1 != null && v2 != null)
							chain = chain.compare(v2,v1);
						else if(v1 == null && v2 != null)
							return 1;
						else if(v1 != null && v2 == null)
							return -1;

					}
				}
				int result = chain.result();
				return result;
			}
		};
	}

}