text:
#ifndef PROTEIN_H
#define PROTEIN_H

#include <avogadro/global.h>

#include <QObject>
#include <QVector>

namespace Avogadro {

  class Atom;
  class Residue;
  class Molecule;

  class ProteinPrivate;
  /**
   * @class Protein protein.h <avogadro/protein.h>
   * @brief Representation of a protein, including secondary structure
   *
   * The Protein class helps other parts of the library or plugins to work
   * with proteins. If the molecule was read from a pdb file, an attempt
   * will be made to get the secondary structure information from the HELIX
   * and SHEET lines. If this fails, a simplified version of the DSSP
   * algorithm is used.
   *
   * http://en.wikipedia.org/wiki/Secondary_structure#The_DSSP_code
   *
   * The secondary structure is assigned based on hydrogen bonding
   * patterns. There are eight types of secondary structure that
   * DSSP defines:
   *
   * * G = 3-turn helix (310 helix). Min length 3 residues.
   * * H = 4-turn helix (α helix). Min length 4 residues.
   * * I = 5-turn helix (π helix). Min length 5 residues.
   * * T = hydrogen bonded turn (3, 4 or 5 turn)
   * * E = extended strand in parallel and/or anti-parallel β-sheet conformation. Min length 2 residues.
   * * B = residue in isolated β-bridge (single pair β-sheet hydrogen bond formation)
   * * S = bend (the only non-hydrogen-bond based assignment)
   *
   * Amino acid residues which are not in any of the above
   * conformations are assigned as the eighth type '-' = Coil.
   * The helices (G,H and I) and sheet conformations are all required
   * to have a reasonable length. This means that 2 adjacent residues
   * in the primary structure must form the same hydrogen bonding
   * pattern. If the helix or sheet hydrogen bonding pattern is too
   * short they are designated as T or B, respectively.
   */
  class A_EXPORT Protein : public QObject
  {
    Q_OBJECT

    public:
      /**
       * Constructor.
       * @param molecule The object parent.
       */
      Protein(Molecule *molecule);
      /**
       * Destructor.
       */
      virtual ~Protein();

      //! @name Chains
      //@{
      /**
       * @return All the residues in the protein ordered by chain.
       */
      const QVector<QVector<Residue*> >& chains() const;
      /**
       * @return the number of chains in this protein
       */
      int numChains() const;
      /**
       * @return All atom ids for chain with @p index.
       */
      QList<unsigned long> chainAtoms(int index) const;
      /**
       * @return All residue ids for chain with @p index.
       */
      QList<unsigned long> chainResidues(int index) const;
      //@}

      //! @name Secondary structure
      //@{
      /**
       * @return QByteArray with codes for the protein's secondary structure.
       */
      QByteArray secondaryStructure() const;
      /**
       * @return True if the residue is part of a sheet.
       */
      bool isHelix(Residue *residue) const;
      /**
       * @return True if the residue is part of a sheet.
       */
      bool isSheet(Residue *residue) const;
      //@}

    private:
      bool extractFromPDB();

      void sortResiduesByChain();
      void iterateForward(Atom *prevCA, Atom *currN, QVector<bool> &visited);
      void iterateBackward(Atom *prevN, Atom *currCA, QVector<bool> &visited);

      void detectHBonds();

      void detectStructure();
      void extendHelix(char c, int turn, Residue *residue, const QVector<Residue*> &residues);
      void extendSheet(int delta, Residue *residue, const QVector<Residue*> &residues);
      void clearShortPatterns();
      void clearShortPatterns(char c, int min);

      int residueIndex(Residue *residue) const;

      int numHelixes(char c) const;
      QList<unsigned long> helixBackboneAtoms(char c, int index);

      ProteinPrivate * const d;
  };

} // End namespace Avogadro

#endif


text:
/*global navigator, Camera */
define(['app', 'list_view'], function(App, View) {
    'use strict';
    App.module('ImagesApp.List', function(List, App, Backbone, Marionette, $, _) {
        List.Controller = {
            name: 'List Controller',
            list: function() {

                require(['common/views', 'entities_images'], function(CommonViews) {

                    App.mainRegion.show(new CommonViews.Loading());

                    var fetchingImages = App.request('images:entities');

                    var imagesListLayout = new View.Layout();

                    var imagesCollection; // the main collection for this page.

                    // require(['entities/common'], function() {
                    imagesListLayout.on('image:snap', function() {
                        // imagesListLayout.panelRegion.show(contactsListPanel);
                        // imagesListLayout.imagesRegion.show(imagesListView);

                        require(['list_view'], function(ListView) {
                            var newImage = App.request('images:entity:new');

                            if (navigator.camera) { // if cordova
                                navigator.camera.getPicture(
                                    function onSuccess(imageData) {
                                        newImage.set('src', 'data:image/jpeg;base64,' + imageData);
                                        // newImage.set('src', imageData);
                                        imagesCollection.add(newImage);
                                    },
                                    function onFail(message) {
                                        console.log('Failed because: ' + message);
                                    },
                                    {
                                        quality: 50,
                                        destinationType: navigator.camera.DestinationType.DATA_URL
                                        // destinationType: navigator.camera.DestinationType.FILE_URI
                                    }
                                );
                            } else { // else if testing mode
                                newImage.set('src', 'images/fake.png');
                                imagesCollection.add(newImage);
                            }

                            // var newImageView = new ListView.Image({
                            //   model: newImage
                            // });

                            imagesListLayout.flash('success');
                        });
                    });

                    // when initial image fetching is done (ie: initial page load)
                    $.when(fetchingImages).done(function(images) {
                        imagesCollection = images;
                        // App.log('Fetched all image datas', 'App', 1);
                        // make a collection to show
                        var imagesListView = new View.Images({
                            collection: imagesCollection
                        });

                        //   imagesListView.on('itemview:image:show', function(childView, model){
                        //     // App.trigger('images:show', model.get('id'));
                        //   });

                        imagesListView.on('itemview:image:delete', function(childView, model) {
                            // auto magically call's remove in the view.
                            model.destroy();
                        });

                        // when the data is here, show it in this region
                        imagesListLayout.imagesRegion.show(imagesListView);

                    });

                    // show the whole layout
                    App.mainRegion.show(imagesListLayout);
                });
            }
        };
    });
    return App.ImagesApp.List.Controller;
});

redpajama_set_name: RedPajamaGithub


text:
package com.huixinpn.dionysus.dto;

import com.huixinpn.dionysus.domain.AbstractDionysusPersistable;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Page;

import java.util.Collection;

@Data
@NoArgsConstructor
public class EntityPageData<T extends EntityData> {
  private static int defaultPageSize = 20;
  private Collection<T> content;
  private long totalElements;
  private int totalPages;
  private int number;
  private int size;
  public EntityPageData(Page<? extends AbstractDionysusPersistable> page,Class<T> klass){
    this.totalElements = page.getTotalElements();
    this.totalPages = page.getTotalPages();
    this.number = page.getNumber();
    this.size = page.getSize();
    this.content = new EntityCollectionData<T>(page.getContent(),klass).toDTOCollection();
  }
}


text:
package org.bitcoinj.core;

import org.coinj.dash.MasternodeData;
import org.coinj.dash.MasternodeManager;
import org.coinj.dash.VerificationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;

/**
 * Date: 5/21/15
 * Time: 5:35 AM
 *
 * @author Mikhail Kulikov
 */
public class MasternodeScanningError extends Message implements Hashable, Serializable {

    private static final long serialVersionUID = 1L;

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

    public static final int SCANNING_SUCCESS = 1;
    public static final int SCANNING_ERROR_NO_RESPONSE = 2;
    public static final int SCANNING_ERROR_IX_NO_RESPONSE = 3;
    public static final int SCANNING_ERROR_MAX = 3;

    /**
     * 1% of the network is scanned every 2.5 minutes, making a full
     * round of scanning take about 4.16 hours. We're targeting about
     * a day of proof-of-service errors for complete removal from the
     * masternode system.
     */
    public static final int MASTERNODE_SCANNING_ERROR_THRESHOLD = 6;

    private TransactionInput txInMasternodeA;
    private TransactionInput txInMasternodeB;
    private int errorType;
    private int expiration;
    private int blockHeight;
    private byte[] signature;

    private Sha256Hash hashCache;

    public MasternodeScanningError(NetworkParameters params, byte[] payload) {
        super(params, payload, 0, false, false, payload.length);
    }

    public MasternodeScanningError(TransactionInput txInMasternodeB, int errorType, int blockHeight) {
        super(txInMasternodeB.getParams());
        this.txInMasternodeA = new TransactionInput(params, null, new byte[] {});
        this.txInMasternodeB = txInMasternodeB;
        this.errorType = errorType;
        this.expiration = (int) Utils.currentTimeSeconds() + 60 * 60;
        this.blockHeight = blockHeight;
    }

    @Override
    protected void parseLite() throws ProtocolException {}

    @Override
    void parse() throws ProtocolException {
        cursor = offset;

        txInMasternodeA = new TransactionInput(params, null, payload, cursor, parseLazy, parseRetain);
        long scriptLen = readVarInt(TransactionOutPoint.MESSAGE_LENGTH);
        cursor += scriptLen + 4;
        txInMasternodeB = new TransactionInput(params, null, payload, cursor, parseLazy, parseRetain);
        scriptLen = readVarInt(TransactionOutPoint.MESSAGE_LENGTH);
        cursor += scriptLen + 4;

        errorType = (int) readUint32();
        expiration = (int) readUint32();
        blockHeight = (int) readUint32();
        signature = readByteArray();
    }

    @Override
    void bitcoinSerializeToStream(OutputStream stream) throws IOException {
        txInMasternodeA.bitcoinSerialize(stream);
        txInMasternodeB.bitcoinSerialize(stream);
        Utils.uint32ToByteStreamLE(errorType, stream);
        Utils.uint32ToByteStreamLE(expiration, stream);
        Utils.uint32ToByteStreamLE(blockHeight, stream);
        stream.write(new VarInt(signature.length).encode());
        stream.write(signature);
    }

    @Override
    public Sha256Hash getHash() {
        if (hashCache == null) {
            hashCache = Sha256Hash.createDouble(bitcoinSerialize());
        }
        return hashCache;
    }

    public boolean isValid() {
        return (errorType > 0 && errorType <= SCANNING_ERROR_MAX);
    }

    public int getBlockHeight() {
        return blockHeight;
    }

    public int getErrorType() {
        return errorType;
    }

    public TransactionInput getTxInMasternodeA() {
        return txInMasternodeA;
    }

    public TransactionInput getTxInMasternodeB() {
        return txInMasternodeB;
    }

    public boolean isSignatureValid(MasternodeManager manager) {
        final StringBuilder strMessage = new StringBuilder();
        appendTxIn(strMessage, txInMasternodeA);
        appendTxIn(strMessage, txInMasternodeB)
                .append(blockHeight)
                .append(errorType);

        final MasternodeData pmn = manager.find(txInMasternodeA);

        if (pmn == null) {
            logger.info("MasternodeScanningError.isSignatureValid(MasternodeManager) - Unknown Masternode");
            return false;
        }

        if (!VerificationUtils.verifyMessage(pmn.getPubKey2(), signature, strMessage.toString(), params)) {
            logger.info("MasternodeScanningError.isSignatureValid(MasternodeManager) - Verify message failed");
            return false;
        }

        return true;
    }

    private static StringBuilder appendTxIn(StringBuilder builder, TransactionInput txIn) {
        final TransactionOutPoint outpoint = txIn.getOutpoint();
        builder.append("CTxIn(")
                .append("COutPoint(")
                .append(outpoint.getHash())
                .append(", ")
                .append(outpoint.getIndex())
                .append(')');
        if (txIn.isCoinBase()) {
            builder.append(", coinbase ")
                    .append(Utils.HEX.encode(txIn.getScriptBytes()));
        } else {
            final String str = txIn.getScriptSig().satoshiStyleToString();
            builder.append(", scriptSig=")
                    .append(str.length() > 24 ? str.substring(0, 24) : str);
        }
        if (txIn.hasSequence()) {
            builder.append(", nSequence=")
                    .append(txIn.getSequenceNumber());
        }
        builder.append(')');
        return builder;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        MasternodeScanningError that = (MasternodeScanningError) o;

        return blockHeight == that.blockHeight
                && expiration == that.expiration
                && !(txInMasternodeA != null ? !txInMasternodeA.equals(that.txInMasternodeA) : that.txInMasternodeA != null)
                && !(txInMasternodeB != null ? !txInMasternodeB.equals(that.txInMasternodeB) : that.txInMasternodeB != null);
    }

    @Override
    public int hashCode() {
        int result = txInMasternodeA != null ? txInMasternodeA.hashCode() : 0;
        result = 31 * result + (txInMasternodeB != null ? txInMasternodeB.hashCode() : 0);
        result = 31 * result + expiration;
        result = 31 * result + blockHeight;
        return result;
    }

}


text:
require 'rubygems'
require 'mocha'
require File.join(File.dirname(__FILE__), 'test_helper')

Geokit::Geocoders::provider_order = [:google, :us]

# Uses defaults
class Company < ActiveRecord::Base #:nodoc: all
  has_many :locations
end

# Configures everything.
class Location < ActiveRecord::Base #:nodoc: all
  belongs_to :company
  acts_as_mappable
end

# for auto_geocode
class Store < ActiveRecord::Base
  acts_as_mappable :auto_geocode => true
end

# Uses deviations from conventions.
class CustomLocation < ActiveRecord::Base #:nodoc: all
  belongs_to :company
  acts_as_mappable :distance_column_name => 'dist',
                   :default_units => :kms,
                   :default_formula => :flat,
                   :lat_column_name => 'latitude',
                   :lng_column_name => 'longitude'

  def to_s
    "lat: #{latitude} lng: #{longitude} dist: #{dist}"
  end
end

# Used by :through
class MockAddress < ActiveRecord::Base #:nodoc: all
  belongs_to :addressable, :polymorphic => true
  acts_as_mappable
end

# Uses :through
class MockOrganization < ActiveRecord::Base #:nodoc: all
  has_one :mock_address, :as => :addressable
  acts_as_mappable :through => :mock_address
end

# Uses :through => {}
class MockHouse < ActiveRecord::Base
  acts_as_mappable
end

class MockFamily < ActiveRecord::Base
  belongs_to :mock_house
end

class MockPerson < ActiveRecord::Base
  belongs_to :mock_family
  acts_as_mappable :through => { :mock_family => :mock_house }
end

class ActsAsMappableTest < ActiveSupport::TestCase #:nodoc: all

  LOCATION_A_IP = "217.10.83.5"

  self.fixture_path = File.dirname(__FILE__) + '/fixtures'
  self.use_transactional_fixtures = true
  self.use_instantiated_fixtures  = false
  self.pre_loaded_fixtures = true
  fixtures :all

  def setup
    @location_a = GeoKit::GeoLoc.new
    @location_a.lat = 32.918593
    @location_a.lng = -96.958444
    @location_a.city = "Irving"
    @location_a.state = "TX"
    @location_a.country_code = "US"
    @location_a.success = true

    @sw = GeoKit::LatLng.new(32.91663,-96.982841)
    @ne = GeoKit::LatLng.new(32.96302,-96.919495)
    @bounds_center=GeoKit::LatLng.new((@sw.lat+@ne.lat)/2,(@sw.lng+@ne.lng)/2)

    @starbucks = companies(:starbucks)
    @loc_a = locations(:a)
    @custom_loc_a = custom_locations(:a)
    @loc_e = locations(:e)
    @custom_loc_e = custom_locations(:e)

    @barnes_and_noble = mock_organizations(:barnes_and_noble)
    @address = mock_addresses(:address_barnes_and_noble)
  end

  def test_override_default_units_the_hard_way
    Location.default_units = :kms
    locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 3.97")
    assert_equal 5, locations.size
    locations = Location.count(:origin => @loc_a, :conditions => "distance < 3.97")
    assert_equal 5, locations
    Location.default_units = :miles
  end

  def test_include
    locations = Location.find(:all, :origin => @loc_a, :include => :company, :conditions => "company_id = 1")
    assert !locations.empty?
    assert_equal 1, locations[0].company.id
    assert_equal 'Starbucks', locations[0].company.name
  end

  def test_distance_between_geocoded
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a)
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("San Francisco, CA").returns(@location_a)
    assert_equal 0, Location.distance_between("Irving, TX", "San Francisco, CA")
  end

  def test_distance_to_geocoded
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a)
    assert_equal 0, @custom_loc_a.distance_to("Irving, TX")
  end

  def test_distance_to_geocoded_error
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(GeoKit::GeoLoc.new)
    assert_raise(GeoKit::Geocoders::GeocodeError) { @custom_loc_a.distance_to("Irving, TX")  }
  end

  def test_custom_attributes_distance_calculations
    assert_equal 0, @custom_loc_a.distance_to(@loc_a)
    assert_equal 0, CustomLocation.distance_between(@custom_loc_a, @loc_a)
  end

  def test_distance_column_in_select
    locations = Location.find(:all, :origin => @loc_a, :order => "distance ASC")
    assert_equal 6, locations.size
    assert_equal 0, @loc_a.distance_to(locations.first)
    assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01
  end

  def test_find_with_distance_condition
    locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 3.97")
    assert_equal 5, locations.size
    locations = Location.count(:origin => @loc_a, :conditions => "distance < 3.97")
    assert_equal 5, locations
  end

  def test_find_with_distance_condition_with_units_override
    locations = Location.find(:all, :origin => @loc_a, :units => :kms, :conditions => "distance < 6.387")
    assert_equal 5, locations.size
    locations = Location.count(:origin => @loc_a, :units => :kms, :conditions => "distance < 6.387")
    assert_equal 5, locations
  end

  def test_find_with_distance_condition_with_formula_override
    locations = Location.find(:all, :origin => @loc_a, :formula => :flat, :conditions => "distance < 6.387")
    assert_equal 6, locations.size
    locations = Location.count(:origin => @loc_a, :formula => :flat, :conditions => "distance < 6.387")
    assert_equal 6, locations
  end

  def test_find_within
    locations = Location.find_within(3.97, :origin => @loc_a)
    assert_equal 5, locations.size
    locations = Location.count_within(3.97, :origin => @loc_a)
    assert_equal 5, locations
  end

  def test_find_within_with_token
    locations = Location.find(:all, :within => 3.97, :origin => @loc_a)
    assert_equal 5, locations.size
    locations = Location.count(:within => 3.97, :origin => @loc_a)
    assert_equal 5, locations
  end

  def test_find_within_with_coordinates
    locations = Location.find_within(3.97, :origin =>[@loc_a.lat,@loc_a.lng])
    assert_equal 5, locations.size
    locations = Location.count_within(3.97, :origin =>[@loc_a.lat,@loc_a.lng])
    assert_equal 5, locations
  end

  def test_find_with_compound_condition
    locations = Location.find(:all, :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'")
    assert_equal 2, locations.size
    locations = Location.count(:origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'")
    assert_equal 2, locations
  end

  def test_find_with_secure_compound_condition
    locations = Location.find(:all, :origin => @loc_a, :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
    assert_equal 2, locations.size
    locations = Location.count(:origin => @loc_a, :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
    assert_equal 2, locations
  end

  def test_find_beyond
    locations = Location.find_beyond(3.95, :origin => @loc_a)
    assert_equal 1, locations.size
    locations = Location.count_beyond(3.95, :origin => @loc_a)
    assert_equal 1, locations
  end

  def test_find_beyond_with_token
    locations = Location.find(:all, :beyond => 3.95, :origin => @loc_a)
    assert_equal 1, locations.size
    locations = Location.count(:beyond => 3.95, :origin => @loc_a)
    assert_equal 1, locations
  end

  def test_find_beyond_with_coordinates
    locations = Location.find_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng])
    assert_equal 1, locations.size
    locations = Location.count_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng])
    assert_equal 1, locations
  end

  def test_find_range_with_token
    locations = Location.find(:all, :range => 0..10, :origin => @loc_a)
    assert_equal 6, locations.size
    locations = Location.count(:range => 0..10, :origin => @loc_a)
    assert_equal 6, locations
  end

  def test_find_range_with_token_with_conditions
    locations = Location.find(:all, :origin => @loc_a, :range => 0..10, :conditions => ["city = ?", 'Coppell'])
    assert_equal 2, locations.size
    locations = Location.count(:origin => @loc_a, :range => 0..10, :conditions => ["city = ?", 'Coppell'])
    assert_equal 2, locations
  end

  def test_find_range_with_token_with_hash_conditions
    locations = Location.find(:all, :origin => @loc_a, :range => 0..10, :conditions => {:city => 'Coppell'})
    assert_equal 2, locations.size
    locations = Location.count(:origin => @loc_a, :range => 0..10, :conditions => {:city => 'Coppell'})
    assert_equal 2, locations
  end

  def test_find_range_with_token_excluding_end
    locations = Location.find(:all, :range => 0...10, :origin => @loc_a)
    assert_equal 6, locations.size
    locations = Location.count(:range => 0...10, :origin => @loc_a)
    assert_equal 6, locations
  end

  def test_find_nearest
    assert_equal @loc_a, Location.find_nearest(:origin => @loc_a)
  end

  def test_find_nearest_through_find
     assert_equal @loc_a, Location.find(:nearest, :origin => @loc_a)
  end

  def test_find_nearest_with_coordinates
    assert_equal @loc_a, Location.find_nearest(:origin =>[@loc_a.lat, @loc_a.lng])
  end

  def test_find_farthest
    assert_equal @loc_e, Location.find_farthest(:origin => @loc_a)
  end

  def test_find_farthest_through_find
    assert_equal @loc_e, Location.find(:farthest, :origin => @loc_a)
  end

  def test_find_farthest_with_coordinates
    assert_equal @loc_e, Location.find_farthest(:origin =>[@loc_a.lat, @loc_a.lng])
  end

  def test_scoped_distance_column_in_select
    locations = @starbucks.locations.find(:all, :origin => @loc_a, :order => "distance ASC")
    assert_equal 5, locations.size
    assert_equal 0, @loc_a.distance_to(locations.first)
    assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01
  end

  def test_scoped_find_with_distance_condition
    locations = @starbucks.locations.find(:all, :origin => @loc_a, :conditions => "distance < 3.97")
    assert_equal 4, locations.size
    locations = @starbucks.locations.count(:origin => @loc_a, :conditions => "distance < 3.97")
    assert_equal 4, locations
  end

  def test_scoped_find_within
    locations = @starbucks.locations.find_within(3.97, :origin => @loc_a)
    assert_equal 4, locations.size
    locations = @starbucks.locations.count_within(3.97, :origin => @loc_a)
    assert_equal 4, locations
  end

  def test_scoped_find_with_compound_condition
    locations = @starbucks.locations.find(:all, :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'")
    assert_equal 2, locations.size
    locations = @starbucks.locations.count( :origin => @loc_a, :conditions => "distance < 5 and city = 'Coppell'")
    assert_equal 2, locations
  end

  def test_scoped_find_beyond
    locations = @starbucks.locations.find_beyond(3.95, :origin => @loc_a)
    assert_equal 1, locations.size
    locations = @starbucks.locations.count_beyond(3.95, :origin => @loc_a)
    assert_equal 1, locations
  end

  def test_scoped_find_nearest
    assert_equal @loc_a, @starbucks.locations.find_nearest(:origin => @loc_a)
  end

  def test_scoped_find_farthest
    assert_equal @loc_e, @starbucks.locations.find_farthest(:origin => @loc_a)
  end

  def test_ip_geocoded_distance_column_in_select
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.find(:all, :origin => LOCATION_A_IP, :order => "distance ASC")
    assert_equal 6, locations.size
    assert_equal 0, @loc_a.distance_to(locations.first)
    assert_in_delta 3.97, @loc_a.distance_to(locations.last, :units => :miles, :formula => :sphere), 0.01
  end

  def test_ip_geocoded_find_with_distance_condition
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => "distance < 3.97")
    assert_equal 5, locations.size
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.count(:origin => LOCATION_A_IP, :conditions => "distance < 3.97")
    assert_equal 5, locations
  end

  def test_ip_geocoded_find_within
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.find_within(3.97, :origin => LOCATION_A_IP)
    assert_equal 5, locations.size
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.count_within(3.97, :origin => LOCATION_A_IP)
    assert_equal 5, locations
  end

  def test_ip_geocoded_find_with_compound_condition
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => "distance < 5 and city = 'Coppell'")
    assert_equal 2, locations.size
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.count(:origin => LOCATION_A_IP, :conditions => "distance < 5 and city = 'Coppell'")
    assert_equal 2, locations
  end

  def test_ip_geocoded_find_with_secure_compound_condition
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.find(:all, :origin => LOCATION_A_IP, :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
    assert_equal 2, locations.size
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.count(:origin => LOCATION_A_IP, :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
    assert_equal 2, locations
  end

  def test_ip_geocoded_find_beyond
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.find_beyond(3.95, :origin => LOCATION_A_IP)
    assert_equal 1, locations.size
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    locations = Location.count_beyond(3.95, :origin => LOCATION_A_IP)
    assert_equal 1, locations
  end

  def test_ip_geocoded_find_nearest
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    assert_equal @loc_a, Location.find_nearest(:origin => LOCATION_A_IP)
  end

  def test_ip_geocoded_find_farthest
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with(LOCATION_A_IP).returns(@location_a)
    assert_equal @loc_e, Location.find_farthest(:origin => LOCATION_A_IP)
  end

  def test_ip_geocoder_exception
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with('127.0.0.1').returns(GeoKit::GeoLoc.new)
    assert_raises GeoKit::Geocoders::GeocodeError do
      Location.find_farthest(:origin => '127.0.0.1')
    end
  end

  def test_address_geocode
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with('Irving, TX').returns(@location_a)
    locations = Location.find(:all, :origin => 'Irving, TX', :conditions => ["distance < ? and city = ?", 5, 'Coppell'])
    assert_equal 2, locations.size
  end

  def test_find_with_custom_distance_condition
    locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => "dist < 3.97")
    assert_equal 5, locations.size
    locations = CustomLocation.count(:origin => @loc_a, :conditions => "dist < 3.97")
    assert_equal 5, locations
  end

  def test_find_with_custom_distance_condition_using_custom_origin
    locations = CustomLocation.find(:all, :origin => @custom_loc_a, :conditions => "dist < 3.97")
    assert_equal 5, locations.size
    locations = CustomLocation.count(:origin => @custom_loc_a, :conditions => "dist < 3.97")
    assert_equal 5, locations
  end

  def test_find_within_with_custom
    locations = CustomLocation.find_within(3.97, :origin => @loc_a)
    assert_equal 5, locations.size
    locations = CustomLocation.count_within(3.97, :origin => @loc_a)
    assert_equal 5, locations
  end

  def test_find_within_with_coordinates_with_custom
    locations = CustomLocation.find_within(3.97, :origin =>[@loc_a.lat, @loc_a.lng])
    assert_equal 5, locations.size
    locations = CustomLocation.count_within(3.97, :origin =>[@loc_a.lat, @loc_a.lng])
    assert_equal 5, locations
  end

  def test_find_with_compound_condition_with_custom
    locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => "dist < 5 and city = 'Coppell'")
    assert_equal 1, locations.size
    locations = CustomLocation.count(:origin => @loc_a, :conditions => "dist < 5 and city = 'Coppell'")
    assert_equal 1, locations
  end

  def test_find_with_secure_compound_condition_with_custom
    locations = CustomLocation.find(:all, :origin => @loc_a, :conditions => ["dist < ? and city = ?", 5, 'Coppell'])
    assert_equal 1, locations.size
    locations = CustomLocation.count(:origin => @loc_a, :conditions => ["dist < ? and city = ?", 5, 'Coppell'])
    assert_equal 1, locations
  end

  def test_find_beyond_with_custom
    locations = CustomLocation.find_beyond(3.95, :origin => @loc_a)
    assert_equal 1, locations.size
    locations = CustomLocation.count_beyond(3.95, :origin => @loc_a)
    assert_equal 1, locations
  end

  def test_find_beyond_with_coordinates_with_custom
    locations = CustomLocation.find_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng])
    assert_equal 1, locations.size
    locations = CustomLocation.count_beyond(3.95, :origin =>[@loc_a.lat, @loc_a.lng])
    assert_equal 1, locations
  end

  def test_find_nearest_with_custom
    assert_equal @custom_loc_a, CustomLocation.find_nearest(:origin => @loc_a)
  end

  def test_find_nearest_with_coordinates_with_custom
    assert_equal @custom_loc_a, CustomLocation.find_nearest(:origin =>[@loc_a.lat, @loc_a.lng])
  end

  def test_find_farthest_with_custom
    assert_equal @custom_loc_e, CustomLocation.find_farthest(:origin => @loc_a)
  end

  def test_find_farthest_with_coordinates_with_custom
    assert_equal @custom_loc_e, CustomLocation.find_farthest(:origin =>[@loc_a.lat, @loc_a.lng])
  end

  def test_find_with_array_origin
    locations = Location.find(:all, :origin =>[@loc_a.lat,@loc_a.lng], :conditions => "distance < 3.97")
    assert_equal 5, locations.size
    locations = Location.count(:origin =>[@loc_a.lat,@loc_a.lng], :conditions => "distance < 3.97")
    assert_equal 5, locations
  end

  # Bounding box tests

  def test_find_within_bounds
    locations = Location.find_within_bounds([@sw,@ne])
    assert_equal 2, locations.size
    locations = Location.count_within_bounds([@sw,@ne])
    assert_equal 2, locations
  end

  def test_find_within_bounds_ordered_by_distance
    locations = Location.find_within_bounds([@sw,@ne], :origin=>@bounds_center, :order=>'distance asc')
    assert_equal locations[0], locations(:d)
    assert_equal locations[1], locations(:a)
  end

  def test_find_within_bounds_with_token
    locations = Location.find(:all, :bounds=>[@sw,@ne])
    assert_equal 2, locations.size
    locations = Location.count(:bounds=>[@sw,@ne])
    assert_equal 2, locations
  end

  def test_find_within_bounds_with_string_conditions
    locations = Location.find(:all, :bounds=>[@sw,@ne], :conditions=>"id !=#{locations(:a).id}")
    assert_equal 1, locations.size
  end

  def test_find_within_bounds_with_array_conditions
    locations = Location.find(:all, :bounds=>[@sw,@ne], :conditions=>["id != ?", locations(:a).id])
    assert_equal 1, locations.size
  end

  def test_find_within_bounds_with_hash_conditions
    locations = Location.find(:all, :bounds=>[@sw,@ne], :conditions=>{:id => locations(:a).id})
    assert_equal 1, locations.size
  end

  def test_auto_geocode
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("Irving, TX").returns(@location_a)
    store=Store.new(:address=>'Irving, TX')
    store.save
    assert_equal store.lat,@location_a.lat
    assert_equal store.lng,@location_a.lng
    assert_equal 0, store.errors.size
  end

  def test_auto_geocode_failure
    GeoKit::Geocoders::MultiGeocoder.expects(:geocode).with("BOGUS").returns(GeoKit::GeoLoc.new)
    store=Store.new(:address=>'BOGUS')
    store.save
    assert store.new_record?
    assert_equal 1, store.errors.size
  end

  # Test :through

  def test_find_with_through
    organizations = MockOrganization.find(:all, :origin => @location_a, :order => 'distance ASC')
    assert_equal 2, organizations.size
    organizations = MockOrganization.count(:origin => @location_a, :conditions => "distance < 3.97")
    assert_equal 1, organizations
  end

  def test_find_with_through_with_hash
    people = MockPerson.find(:all, :origin => @location_a, :order => 'distance ASC')
    assert_equal 2, people.size
    people = MockPerson.count(:origin => @location_a, :conditions => "distance < 3.97")
    assert_equal 2, people
  end
end


text:
import { merge } from 'lodash'
import path from 'path'

// Default configuations applied to all environments
const defaultConfig = {
  env: process.env.NODE_ENV,
  get envs() {
    return {
      test: process.env.NODE_ENV === 'test',
      development: process.env.NODE_ENV === 'development',
      production: process.env.NODE_ENV === 'production'
    }
  },
  apiVersion: require('../../package.json').apiVersion,
  root: path.normalize(__dirname + '/../../..'),
  port: process.env.PORT || 4567,
  ip: process.env.IP || '0.0.0.0',
  auth0: {
    secret: 'secret',
    client: 'client',
    domain: 'https://likelyloans.eu.auth0.com/'
  },
  /**
   * Security configuation options regarding sessions, authentication and hashing
   */
  security: {
    sessionSecret: process.env.SESSION_SECRET || 'i-am-the-secret-key',
    sessionExpiration: process.env.SESSION_EXPIRATION || 60 * 60 * 24 * 7, // 1 week
    saltRounds: process.env.SALT_ROUNDS || 12
  }
}

// Environment specific overrides
const environmentConfigs = {
  development: {
    security: {
      saltRounds: 4
    }
  },
  test: {
    port: 5678,
    security: {
      saltRounds: 4
    }
  },
  production: {
  }
}

// Recursively merge configurations
export default merge(defaultConfig, environmentConfigs[process.env.NODE_ENV] || {})


text:
module BannersHelper
end


text:
{% extends "projects/base_project_editing.html" %}

{% load pagination_tags %}

{% block title %}Builds{% endblock %}

{% block content %}

          {% autopaginate build_list 15 %}

Recent Builds

                    {% include "core/build_list_detailed.html" %}

          {% paginate %}

{% endblock %}

{% block extra_scripts %}
{{ block.super }}

{% endblock %}


text:
FactoryGirl.define do
  factory :mongoid_dialectic_post, class: 'Dialectic::Post' do
    subject "MyString"
    posted_by 1
    body "MyString"
  end
end


text:
using System;
using System.Collections.Generic;
using System.Web;

namespace FilmWebAPI
{
    internal static class Url
    {
        internal static string Create(string baseUrl, ICollection<KeyValuePair<string, string>> arguments)
        {
            var builder = new UriBuilder(baseUrl);
            var query = HttpUtility.ParseQueryString(string.Empty);

            foreach (var argument in arguments)
            {
                query.Add(argument.Key, argument.Value);
            }

            builder.Query = query.ToString();
            return builder.ToString();
        }
    }
}


text:
#include "precomp.h"

BOOLEAN
p2pDevStateInit_IDLE(IN P_ADAPTER_T prAdapter,
		     IN P_P2P_CHNL_REQ_INFO_T prChnlReqInfo, OUT P_ENUM_P2P_DEV_STATE_T peNextState)
{
	BOOLEAN fgIsTransition = FALSE;

	do {
		ASSERT_BREAK((prAdapter != NULL) && (prChnlReqInfo) && (peNextState != NULL));

		if (!LINK_IS_EMPTY(&(prChnlReqInfo->rP2pChnlReqLink))) {
			fgIsTransition = TRUE;
			*peNextState = P2P_DEV_STATE_REQING_CHANNEL;
			break;
		}

		/* Stay in IDLE state. */
		UNSET_NET_ACTIVE(prAdapter, P2P_DEV_BSS_INDEX);
		nicDeactivateNetwork(prAdapter, P2P_DEV_BSS_INDEX);
	} while (FALSE);

	return fgIsTransition;
}				/* p2pDevStateInit_IDLE */

VOID p2pDevStateAbort_IDLE(IN P_ADAPTER_T prAdapter)
{
	/* Currently Aobrt IDLE do nothing. */
	return;
}				/* p2pDevStateAbort_IDLE */

BOOLEAN
p2pDevStateInit_REQING_CHANNEL(IN P_ADAPTER_T			prAdapter,
			       IN UINT_8			ucBssIdx,
			       IN P_P2P_CHNL_REQ_INFO_T		prChnlReqInfo,
			       OUT P_ENUM_P2P_DEV_STATE_T	peNextState)
{
	BOOLEAN fgIsTransition = FALSE;
	P_MSG_P2P_CHNL_REQUEST_T prP2pMsgChnlReq = (P_MSG_P2P_CHNL_REQUEST_T)NULL;
    P_BSS_INFO_T prBssInfo = (P_BSS_INFO_T)NULL;

	do {
		ASSERT_BREAK((prAdapter != NULL) &&
			     (prChnlReqInfo != NULL) && (peNextState != NULL));

        prBssInfo = GET_BSS_INFO_BY_INDEX(prAdapter, ucBssIdx);

		if (LINK_IS_EMPTY(&(prChnlReqInfo->rP2pChnlReqLink))) {
			/* NO Channel Request Pending. */
			DBGLOG(P2P, ERROR,
			       ("NO Pending Channel Request, but enter Req Channel State\n"));
			fgIsTransition = TRUE;
			*peNextState = P2P_DEV_STATE_IDLE;
			break;
		}

		LINK_REMOVE_HEAD(&(prChnlReqInfo->rP2pChnlReqLink),
				 prP2pMsgChnlReq, P_MSG_P2P_CHNL_REQUEST_T);

		ASSERT(prP2pMsgChnlReq);

		prChnlReqInfo->u4MaxInterval = prP2pMsgChnlReq->u4Duration;
		prChnlReqInfo->ucReqChnlNum = prP2pMsgChnlReq->rChannelInfo.ucChannelNum;
		prChnlReqInfo->eChnlSco = prP2pMsgChnlReq->eChnlSco;
		prChnlReqInfo->eBand = prP2pMsgChnlReq->rChannelInfo.eBand;
		prChnlReqInfo->u8Cookie = prP2pMsgChnlReq->u8Cookie;
		prChnlReqInfo->eChnlReqType = prP2pMsgChnlReq->eChnlReqType;
		prChnlReqInfo->eChannelWidth = prBssInfo->ucVhtChannelWidth;
        prChnlReqInfo->ucCenterFreqS1 = prBssInfo->ucVhtChannelFrequencyS1;
        prChnlReqInfo->ucCenterFreqS2 = prBssInfo->ucVhtChannelFrequencyS2;

		p2pFuncAcquireCh(prAdapter, ucBssIdx, prChnlReqInfo);
	} while (FALSE);

	if (prP2pMsgChnlReq) {
		cnmMemFree(prAdapter, prP2pMsgChnlReq);
	}

	return fgIsTransition;
}				/* p2pDevStateInit_REQING_CHANNEL */

VOID
p2pDevStateAbort_REQING_CHANNEL(IN P_ADAPTER_T			prAdapter,
				IN P_P2P_CHNL_REQ_INFO_T	prChnlReqInfo,
				IN ENUM_P2P_DEV_STATE_T		eNextState)
{
	do {
		ASSERT_BREAK((prAdapter != NULL) &&
			     (prChnlReqInfo != NULL) && (eNextState < P2P_DEV_STATE_NUM));

		switch (eNextState) {
		case P2P_DEV_STATE_IDLE:
			/* Channel abort case. */
			p2pFuncReleaseCh(prAdapter, P2P_DEV_BSS_INDEX, prChnlReqInfo);
			break;
		case P2P_DEV_STATE_CHNL_ON_HAND:
			/* Channel on hand case. */
			break;
		default:
			/* Un-expected state transition. */
			DBGLOG(P2P, ERROR, ("Unexpected State Transition(eNextState=%d)\n", eNextState));
			ASSERT(FALSE);
			break;
		}
	} while (FALSE);

	return;
}				/* p2pDevStateAbort_REQING_CHANNEL */

VOID
p2pDevStateInit_CHNL_ON_HAND(IN P_ADAPTER_T		prAdapter,
			     IN P_BSS_INFO_T		prP2pBssInfo,
			     IN P_P2P_DEV_FSM_INFO_T	prP2pDevFsmInfo,
			     IN P_P2P_CHNL_REQ_INFO_T	prChnlReqInfo)
{
	do {
		ASSERT_BREAK((prAdapter != NULL) &&
			     (prP2pDevFsmInfo != NULL) && (prChnlReqInfo != NULL));

		ASSERT(prChnlReqInfo->eChnlReqType == CH_REQ_TYPE_P2P_LISTEN);

		prChnlReqInfo->ucOriChnlNum = prP2pBssInfo->ucPrimaryChannel;
		prChnlReqInfo->eOriBand = prP2pBssInfo->eBand;
		prChnlReqInfo->eOriChnlSco = prP2pBssInfo->eBssSCO;

		prP2pBssInfo->ucPrimaryChannel = prChnlReqInfo->ucReqChnlNum;
		prP2pBssInfo->eBand = prChnlReqInfo->eBand;
		prP2pBssInfo->eBssSCO = prChnlReqInfo->eChnlSco;

		cnmTimerStartTimer(prAdapter, &(prP2pDevFsmInfo->rP2pFsmTimeoutTimer),
				   prChnlReqInfo->u4MaxInterval);

		kalP2PIndicateChannelReady(prAdapter->prGlueInfo,
					   prChnlReqInfo->u8Cookie,
					   prChnlReqInfo->ucReqChnlNum,
					   prChnlReqInfo->eBand,
					   prChnlReqInfo->eChnlSco, prChnlReqInfo->u4MaxInterval);
	} while (FALSE);

	return;
}				/* p2pDevStateInit_CHNL_ON_HAND */

VOID
p2pDevStateAbort_CHNL_ON_HAND(IN P_ADAPTER_T		prAdapter,
			      IN P_BSS_INFO_T		prP2pBssInfo,
			      IN P_P2P_DEV_FSM_INFO_T	prP2pDevFsmInfo,
			      IN P_P2P_CHNL_REQ_INFO_T	prChnlReqInfo)
{
	do {
		ASSERT_BREAK((prAdapter != NULL) || (prChnlReqInfo != NULL));

		cnmTimerStopTimer(prAdapter, &(prP2pDevFsmInfo->rP2pFsmTimeoutTimer));

		prP2pBssInfo->ucPrimaryChannel = prChnlReqInfo->ucOriChnlNum;
		prP2pBssInfo->eBand = prChnlReqInfo->eOriBand;
		prP2pBssInfo->eBssSCO = prChnlReqInfo->eOriChnlSco;

		kalP2PIndicateChannelExpired(prAdapter->prGlueInfo,
					     prChnlReqInfo->u8Cookie,
					     prChnlReqInfo->ucReqChnlNum,
					     prChnlReqInfo->eBand, prChnlReqInfo->eChnlSco);

		p2pFuncReleaseCh(prAdapter, prP2pDevFsmInfo->ucBssIndex, prChnlReqInfo);
	} while (FALSE);

	return;
}				/* p2pDevStateAbort_CHNL_ON_HAND */

VOID
p2pDevStateInit_SCAN(IN P_ADAPTER_T prAdapter,
		     IN UINT_8 ucBssIndex, IN P_P2P_SCAN_REQ_INFO_T prScanReqInfo)
{
	do {
		ASSERT_BREAK((prAdapter != NULL) && (prScanReqInfo != NULL));

		prScanReqInfo->fgIsScanRequest = TRUE;

		p2pFuncRequestScan(prAdapter, ucBssIndex, prScanReqInfo);
	} while (FALSE);

	return;
}				/* p2pDevStateInit_CHNL_ON_HAND */

VOID p2pDevStateAbort_SCAN(IN P_ADAPTER_T prAdapter, IN P_P2P_DEV_FSM_INFO_T prP2pDevFsmInfo)
{
	P_P2P_SCAN_REQ_INFO_T prScanInfo = (P_P2P_SCAN_REQ_INFO_T)NULL;

	do {
		ASSERT_BREAK((prAdapter != NULL) && (prP2pDevFsmInfo != NULL));

		prScanInfo = &(prP2pDevFsmInfo->rScanReqInfo);

		p2pFuncCancelScan(prAdapter, prP2pDevFsmInfo->ucBssIndex, prScanInfo);

		kalP2PIndicateScanDone(prAdapter->prGlueInfo, 0xFF, prScanInfo->fgIsAbort);
	} while (FALSE);

	return;
}				/* p2pDevStateAbort_CHNL_ON_HAND */

BOOLEAN
p2pDevStateInit_OFF_CHNL_TX(IN P_ADAPTER_T		prAdapter,
			    IN P_P2P_DEV_FSM_INFO_T	prP2pDevFsmInfo,
			    IN P_P2P_CHNL_REQ_INFO_T	prChnlReqInfo,
			    IN P_P2P_MGMT_TX_REQ_INFO_T prP2pMgmtTxInfo,
			    OUT P_ENUM_P2P_DEV_STATE_T	peNextState)
{
	P_P2P_OFF_CHNL_TX_REQ_INFO_T prP2pOffChnlTxPkt = (P_P2P_OFF_CHNL_TX_REQ_INFO_T)NULL;
	BOOLEAN fgIsTransition = FALSE;

	do {
		ASSERT_BREAK((prAdapter != NULL) && (prP2pMgmtTxInfo != NULL)
			     && (peNextState != NULL));

		if (!LINK_IS_EMPTY(&(prP2pMgmtTxInfo->rP2pTxReqLink))) {
			prP2pOffChnlTxPkt =
				LINK_PEEK_HEAD(&(prP2pMgmtTxInfo->rP2pTxReqLink),
					       P2P_OFF_CHNL_TX_REQ_INFO_T, rLinkEntry);

			if (prP2pOffChnlTxPkt == NULL) {
				DBGLOG(P2P, ERROR,
				       ("Fetal Error, Link not empty but get NULL pointer.\n"));
				ASSERT(FALSE);
				break;
			}

			if (prChnlReqInfo->ucReqChnlNum !=
			    prP2pOffChnlTxPkt->rChannelInfo.ucChannelNum) {
				prChnlReqInfo->ucReqChnlNum =
					prP2pOffChnlTxPkt->rChannelInfo.ucChannelNum;
				prChnlReqInfo->eChnlSco = prP2pOffChnlTxPkt->eChnlExt;
				prChnlReqInfo->eBand = prP2pOffChnlTxPkt->rChannelInfo.eBand;
				prChnlReqInfo->u8Cookie = 0;
				prChnlReqInfo->eChannelWidth = CW_20_40MHZ;
				prChnlReqInfo->ucCenterFreqS1 = 0;
				prChnlReqInfo->ucCenterFreqS2 = 0;
				ASSERT(prChnlReqInfo->eChnlReqType == CH_REQ_TYPE_OFFCHNL_TX);

				p2pFuncAcquireCh(prAdapter,
						 prP2pDevFsmInfo->ucBssIndex, prChnlReqInfo);
			} else {
				LINK_REMOVE_HEAD(&(prP2pMgmtTxInfo->rP2pTxReqLink),
						 prP2pOffChnlTxPkt, P_P2P_OFF_CHNL_TX_REQ_INFO_T);

				p2pFuncTxMgmtFrame(prAdapter,
						   prP2pDevFsmInfo->ucBssIndex,
						   prP2pOffChnlTxPkt->prMgmtTxMsdu,
						   prP2pOffChnlTxPkt->fgNoneCckRate);

				prP2pMgmtTxInfo->prMgmtTxMsdu = prP2pOffChnlTxPkt->prMgmtTxMsdu;
				prP2pMgmtTxInfo->fgIsWaitRsp = prP2pOffChnlTxPkt->fgIsWaitRsp;
			}
		} else {
			/* Link is empty, return back to IDLE. */
			*peNextState = P2P_DEV_STATE_IDLE;
			fgIsTransition = TRUE;
		}
	} while (FALSE);

	return fgIsTransition;
}				/* p2pDevSateInit_OFF_CHNL_TX */

VOID
p2pDevStateAbort_OFF_CHNL_TX(IN P_ADAPTER_T			prAdapter,
			     IN P_P2P_MGMT_TX_REQ_INFO_T	prP2pMgmtTxInfo,
			     IN P_P2P_CHNL_REQ_INFO_T		prChnlReqInfo,
			     IN ENUM_P2P_DEV_STATE_T		eNextState)
{
	P_P2P_OFF_CHNL_TX_REQ_INFO_T prP2pOffChnlTxPkt = (P_P2P_OFF_CHNL_TX_REQ_INFO_T)NULL;

	do {
		ASSERT_BREAK((prAdapter != NULL) &&
			     (prP2pMgmtTxInfo != NULL) && (prChnlReqInfo != NULL));

		if (eNextState != P2P_DEV_STATE_OFF_CHNL_TX) {
			while (!LINK_IS_EMPTY(&(prP2pMgmtTxInfo->rP2pTxReqLink))) {
				LINK_REMOVE_HEAD(&(prP2pMgmtTxInfo->rP2pTxReqLink),
						 prP2pOffChnlTxPkt, P_P2P_OFF_CHNL_TX_REQ_INFO_T);

				kalP2PIndicateMgmtTxStatus(prAdapter->prGlueInfo,
							   prP2pOffChnlTxPkt->prMgmtTxMsdu, FALSE);
			}

			p2pFuncReleaseCh(prAdapter, P2P_DEV_BSS_INDEX, prChnlReqInfo);
		}
	} while (FALSE);

	return;
}				/* p2pDevSateAbort_OFF_CHNL_TX */


text:
<?xml version="1.0" encoding="UTF-8"?>
<InterchangeStaffAssociation xmlns:sli="http://slc-sli/ed-org/0.1" xmlns="http://ed-fi.org/0100"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <TeacherSectionAssociation>
    <TeacherReference>
      <StaffIdentity>
        <StaffUniqueStateId>pXas4CbbfwQQi</StaffUniqueStateId>
      </StaffIdentity>
    </TeacherReference>
    <SectionReference>
      <SectionIdentity>
        <EducationalOrgReference>
          <EducationalOrgIdentity>
            <StateOrganizationId>A2GmaqA5BhrhWmBw6J_5ow</StateOrganizationId>
          </EducationalOrgIdentity>
        </EducationalOrgReference>
        <UniqueSectionCode>bjoYzn6NwaVpdHYLbRpGkaxkkIYDHMfC6XAfLTAZZr-Q</UniqueSectionCode>
      </SectionIdentity>
    </SectionReference>
    <ClassroomPosition>Substitute Teacher</ClassroomPosition>
    <BeginDate>2014-03-29</BeginDate>
    <EndDate>2013-11-14</EndDate>
    <HighlyQualifiedTeacher>true</HighlyQualifiedTeacher>
  </TeacherSectionAssociation>
</InterchangeStaffAssociation>


text:
import {Component} from '@angular/core';

const USD_TO_JPY = 110.29;

@Component({
  moduleId: module.id,
  selector: 'input-a11y',
  templateUrl: 'input-a11y.html',
})
export class InputAccessibilityDemo {
  firstName: string;
  lastName: string;
  password: string;
  showPassword = false;
  email: string;
  usd: number;
  comment: string;
  commentMax = 200;

  get passwordType() { return this.showPassword ? 'text' : 'password'; }

  get passwordToggleLabel() { return this.showPassword ? 'Hide password' : 'Reveal password'; }

  get passwordToggleIcon() { return this.showPassword ? 'visibility_off' : 'visibility'; }

  get jpy() { return this.usd ? this.usd * USD_TO_JPY : this.usd; }
  set jpy(value) { this.usd = value ? value / USD_TO_JPY : value; }

  get commentCount() { return this.comment ? this.comment.length : 0; }
}


text:
import numpy as np

import pandas as pd

ops = ["mean", "sum", "median", "std", "skew", "kurt", "mad", "prod", "sem", "var"]

class FrameOps:

    params = [ops, ["float", "int", "Int64"], [0, 1]]
    param_names = ["op", "dtype", "axis"]

    def setup(self, op, dtype, axis):
        if op == "mad" and dtype == "Int64":
            # GH-33036, GH#33600
            raise NotImplementedError
        values = np.random.randn(100000, 4)
        if dtype == "Int64":
            values = values.astype(int)
        df = pd.DataFrame(values).astype(dtype)
        self.df_func = getattr(df, op)

    def time_op(self, op, dtype, axis):
        self.df_func(axis=axis)

class FrameMultiIndexOps:

    params = ([0, 1, [0, 1]], ops)
    param_names = ["level", "op"]

    def setup(self, level, op):
        levels = [np.arange(10), np.arange(100), np.arange(100)]
        codes = [
            np.arange(10).repeat(10000),
            np.tile(np.arange(100).repeat(100), 10),
            np.tile(np.tile(np.arange(100), 100), 10),
        ]
        index = pd.MultiIndex(levels=levels, codes=codes)
        df = pd.DataFrame(np.random.randn(len(index), 4), index=index)
        self.df_func = getattr(df, op)

    def time_op(self, level, op):
        self.df_func(level=level)

class SeriesOps:

    params = [ops, ["float", "int"]]
    param_names = ["op", "dtype"]

    def setup(self, op, dtype):
        s = pd.Series(np.random.randn(100000)).astype(dtype)
        self.s_func = getattr(s, op)

    def time_op(self, op, dtype):
        self.s_func()

class SeriesMultiIndexOps:

    params = ([0, 1, [0, 1]], ops)
    param_names = ["level", "op"]

    def setup(self, level, op):
        levels = [np.arange(10), np.arange(100), np.arange(100)]
        codes = [
            np.arange(10).repeat(10000),
            np.tile(np.arange(100).repeat(100), 10),
            np.tile(np.tile(np.arange(100), 100), 10),
        ]
        index = pd.MultiIndex(levels=levels, codes=codes)
        s = pd.Series(np.random.randn(len(index)), index=index)
        self.s_func = getattr(s, op)

    def time_op(self, level, op):
        self.s_func(level=level)

class Rank:

    params = [["DataFrame", "Series"], [True, False]]
    param_names = ["constructor", "pct"]

    def setup(self, constructor, pct):
        values = np.random.randn(10**5)
        self.data = getattr(pd, constructor)(values)

    def time_rank(self, constructor, pct):
        self.data.rank(pct=pct)

    def time_average_old(self, constructor, pct):
        self.data.rank(pct=pct) / len(self.data)

class Correlation:

    params = [["spearman", "kendall", "pearson"]]
    param_names = ["method"]

    def setup(self, method):
        self.df = pd.DataFrame(np.random.randn(500, 15))
        self.df2 = pd.DataFrame(np.random.randn(500, 15))
        self.df_wide = pd.DataFrame(np.random.randn(500, 100))
        self.df_wide_nans = self.df_wide.where(np.random.random((500, 100)) < 0.9)
        self.s = pd.Series(np.random.randn(500))
        self.s2 = pd.Series(np.random.randn(500))

    def time_corr(self, method):
        self.df.corr(method=method)

    def time_corr_wide(self, method):
        self.df_wide.corr(method=method)

    def time_corr_wide_nans(self, method):
        self.df_wide_nans.corr(method=method)

    def peakmem_corr_wide(self, method):
        self.df_wide.corr(method=method)

    def time_corr_series(self, method):
        self.s.corr(self.s2, method=method)

    def time_corrwith_cols(self, method):
        self.df.corrwith(self.df2, method=method)

    def time_corrwith_rows(self, method):
        self.df.corrwith(self.df2, axis=1, method=method)

class Covariance:

    params = []
    param_names = []

    def setup(self):
        self.s = pd.Series(np.random.randn(100000))
        self.s2 = pd.Series(np.random.randn(100000))

    def time_cov_series(self):
        self.s.cov(self.s2)

from .pandas_vb_common import setup  # noqa: F401 isort:skip


text:
(function()
{
    var CACHE = {
        VERSION : 1.0,
        DATE : '2019-02-12',
        NAME : 'mochi-sw-cache-master',
        LIST : [
            './',
            'bootstrap/css/bootstrap.css',
            'bootstrap/css/bootstrap.min.css',
            'bootstrap/css/bootstrap-grid.css',
            'bootstrap/css/bootstrap-grid.min.css',
            'bootstrap/css/bootstrap-reboot.css',
            'bootstrap/css/bootstrap-reboot.min.css',
            'bootstrap/js/bootstrap.bundle.js',
            'bootstrap/js/bootstrap.bundle.min.js',
            'bootstrap/js/bootstrap.js',
            'bootstrap/js/bootstrap.min.js',
            'frontend/css/print.css',
            'frontend/css/style.css',
            'frontend/img/brand/launcher-icon-1x.png',
            'frontend/img/brand/launcher-icon-4x.png',
            'frontend/js/onload.js',
            'index.html',
            'mochi/css/helpers/animate.less/dist/css/animate.css',
            'mochi/js/helpers/basil.min.js',
            'mochi/js/helpers/Chart.bundle.min.js',
            'mochi/js/helpers/clipboard.min.js',
            'mochi/js/helpers/font-awesome-free/js/all.min.js',
            'mochi/js/helpers/holder.min.js',
            'mochi/js/helpers/iScroll/build/iscroll.js',
            'mochi/js/helpers/iScroll/build/iscroll.min.js',
            'mochi/js/helpers/iScroll/build/iscroll-infinite.js',
            'mochi/js/helpers/iScroll/build/iscroll-infinite.min.js',
            'mochi/js/helpers/iScroll/build/iscroll-lite.js',
            'mochi/js/helpers/iScroll/build/iscroll-lite.min.js',
            'mochi/js/helpers/iScroll/build/iscroll-probe.js',
            'mochi/js/helpers/iScroll/build/iscroll-probe.min.js',
            'mochi/js/helpers/iScroll/build/iscroll-zoom.js',
            'mochi/js/helpers/iScroll/build/iscroll-zoom.min.js',
            'mochi/js/helpers/jquery.canvasjs.min.js',
            'mochi/js/helpers/modernizr-custom.js',
            'mochi/js/helpers/popper.min.js',
            'mochi/js/helpers/sprintf.min.js',
            'mochi/js/helpers/underscore.string.min.js',
            'mochi/js/helpers/underscore-min.js',
            'mochi/js/helpers/ViewerJS/example.local.css',
            'mochi/js/helpers/ViewerJS/HeaderCompiled.html',
            'mochi/js/helpers/ViewerJS/HeaderCompiled.js',
            'mochi/js/helpers/ViewerJS/images/kogmbh.png',
            'mochi/js/helpers/ViewerJS/images/nlnet.png',
            'mochi/js/helpers/ViewerJS/images/texture.png',
            'mochi/js/helpers/ViewerJS/images/toolbarButton-download.png',
            'mochi/js/helpers/ViewerJS/images/toolbarButton-fullscreen.png',
            'mochi/js/helpers/ViewerJS/images/toolbarButton-menuArrows.png',
            'mochi/js/helpers/ViewerJS/images/toolbarButton-pageDown.png',
            'mochi/js/helpers/ViewerJS/images/toolbarButton-pageUp.png',
            'mochi/js/helpers/ViewerJS/images/toolbarButton-presentation.png',
            'mochi/js/helpers/ViewerJS/images/toolbarButton-zoomIn.png',
            'mochi/js/helpers/ViewerJS/images/toolbarButton-zoomOut.png',
            'mochi/js/helpers/ViewerJS/index.html',
            'mochi/js/helpers/ViewerJS/index-template.html',
            'mochi/js/helpers/ViewerJS/ODFViewerPlugin.css',
            'mochi/js/helpers/ViewerJS/ODFViewerPlugin.js',
            'mochi/js/helpers/ViewerJS/PDFViewerPlugin.css',
            'mochi/js/helpers/ViewerJS/PDFViewerPlugin.js',
            'mochi/js/helpers/ViewerJS/PluginLoader.js',
            'mochi/js/helpers/ViewerJS/tools/replaceByFileContents.js',
            'mochi/js/helpers/ViewerJS/viewer.css',
            'mochi/js/helpers/ViewerJS/viewer.js',
            'mochi/js/helpers/ViewerJS/viewerTouch.css',
            'mochi/js/jquery/jquery.min.js',
            'mochi/js/jquery/ui/images/ui-icons_444444_256x240.png',
            'mochi/js/jquery/ui/images/ui-icons_555555_256x240.png',
            'mochi/js/jquery/ui/images/ui-icons_777620_256x240.png',
            'mochi/js/jquery/ui/images/ui-icons_777777_256x240.png',
            'mochi/js/jquery/ui/images/ui-icons_cc0000_256x240.png',
            'mochi/js/jquery/ui/images/ui-icons_ffffff_256x240.png',
            'mochi/js/jquery/ui/jquery-ui.css',
            'mochi/js/jquery/ui/jquery-ui.js',
            'mochi/js/jquery/ui/jquery-ui.min.css',
            'mochi/js/jquery/ui/jquery-ui.min.js',
            'mochi/js/jquery/ui/jquery-ui.structure.css',
            'mochi/js/jquery/ui/jquery-ui.structure.min.css',
            'mochi/js/jquery/ui/jquery-ui.theme.css',
            'mochi/js/jquery/ui/jquery-ui.theme.min.css',
            'mochi/js/libraries.js',
            'mochi/js/mochi.js',
            'mochi/js/mochi.min.js',
            'mochi/js/plugins/dialog/dist/dialog.js',
            'mochi/js/plugins/dialog/dist/dialog.min.js',
            'mochi/js/plugins/veeva/dist/veeva.js',
            'mochi/js/plugins/veeva/dist/veeva.min.js',
            'mochi/js/plugins/veeva/dist/veeva-library.js',
            'mochi/js/plugins/veeva/dist/veeva-library.min.js',
            'offline.html',
            ],
        };

    self.addEventListener(
        'install',
        function(event)
        {
            self.skipWaiting();

            event.waitUntil(
                caches
                  .open(CACHE.NAME)
                  .then(
                    function(cache)
                    {
                        console.log('Opened cache: '+CACHE.NAME+' (v'+CACHE.VERSION.toString()+' - '+CACHE.DATE+')');
                        return cache.addAll(CACHE.LIST);
                    }
                    )
                );
        }
        );

    self.addEventListener(
        'fetch',
        function(event)
        {
            event.respondWith(
                caches.match(event.request)
                  .then(
                    function(response)
                    {
                        if (response) return response;
                        else var fetchRequest = event.request.clone();

                        return fetch(fetchRequest).then(
                            function(response)
                            {
                                if (
                                  !response
                                  || response.status !== 200
                                  || response.type !== 'basic')
                                {
                                    return response
                                }

                                var responseToCache = response.clone();

                                caches
                                  .open(CACHE.NAME)
                                  .then(
                                    function(cache)
                                    {
                                        cache.put(
                                            event.request,
                                            responseToCache
                                            );
                                    }
                                    );

                                return response
                            }
                            );
                    }
                    )
                );
        }
        );

    self.addEventListener(
        'activate',
        function(event)
        {
            event.waitUntil(
                caches
                  .keys()
                  .then(
                    function(cacheNames)
                    {
                        return Promise.all(
                            cacheNames.map(
                                function(cacheName)
                                {
                                    if (cacheName != CACHE.NAME)
                                    {
                                        return caches.delete(cacheName)
                                    }
                                }
                                )
                            );
                    }
                    )
                );
        }
        );
}
)();


text:
<?php
// Check for empty fields
if(empty($_POST['name'])  		||
   empty($_POST['email']) 		||
   empty($_POST['phone']) 		||
   empty($_POST['message'])	||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
	echo "No arguments Provided!";
	return false;
   }

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message

$from = "contact.bordeaux@grand-gala.org";
$to = 'gg.bo@gadz.fr';
$subject = "Website Contact Form:  $name";
$email_body = "Vous avez reçu un nouveau message venant du formulaire du site.\n\n"."Les détails sont:\n\nNom: $name\n\nEmail: $email_address\n\nTelephone: $phone\n\nMessage:\n$message";
$headers = "From:" . $from;
mail($to,$subject,$email_body,$headers);
return true;
?>


text:
This guide explains how to migrate from Lagom 1.3 to Lagom 1.4. If you are upgrading from an earlier version, be sure to review previous migration guides.

## Build changes

### Maven

If you're using a `lagom.version` property in the `properties` section of your root `pom.xml`, then simply update that to `1.4.0`. Otherwise, you'll need to go through every place that a Lagom dependency, including plugins, is used, and set the version there.

### sbt

The version of Lagom can be updated by editing the `project/plugins.sbt` file, and updating the version of the Lagom sbt plugin. For example:

```scala
addSbtPlugin("com.lightbend.lagom" % "lagom-sbt-plugin" % "1.4.0-M1")
```

## Binding services

Binding multiple Lagom service descriptors in one Lagom service has been deprecated. If you are currently binding multiple Lagom service descriptors in one Lagom service, you should combine these into one. The reason for this change is that we found most microservice deployment platforms simply don't support having multiple names for the one service, hence a service that serves multiple service descriptors, each with their own name, would not be compatible with those environments.

Consequently, we have deprecated the methods for binding multiple service descriptors. To migrate, in your Guice module that binds your services, change the following code:

```java
bindServices(serviceBinding(MyService.class, MyServiceImpl.class));
```

to:

```java
bindService(MyService.class, MyServiceImpl.class);
```

## Configuring Cassandra keyspaces

Lagom 1.4 requires each service that uses Cassandra persistence to define three keyspace configuration settings in `application.conf`:

```conf
cassandra-journal.keyspace = my_service_journal
cassandra-snapshot-store.keyspace = my_service_snapshot
lagom.persistence.read-side.cassandra.keyspace = my_service_read_side
```

While different services should be isolated by using different keyspaces, it is perfectly fine to use the same keyspace for all of these components within one service. In that case, it can be convenient to define a custom keyspace configuration property and use [property substitution](https://github.com/typesafehub/config#factor-out-common-values) to avoid repeating it.

```conf
my-service.cassandra.keyspace = my_service

cassandra-journal.keyspace = ${my-service.cassandra.keyspace}
cassandra-snapshot-store.keyspace = ${my-service.cassandra.keyspace}
lagom.persistence.read-side.cassandra.keyspace = ${my-service.cassandra.keyspace}
```

If you are using macOS or Linux, or have other access to a bash scripting environment, running this shell script in your base project directory can help add this configuration to existing services:

```bash
#!/bin/bash

set -eu

for svc_dir in *-impl; do
    svc=${svc_dir%-impl}

    # change $svc_dir to $svc on the next line to leave out the _impl suffix
    keyspace=$(tr - _ <<<$svc_dir)
    cat >> $svc_dir/src/main/resources/application.conf <<END
$svc.cassandra.keyspace = $keyspace

cassandra-journal.keyspace = \${$svc.cassandra.keyspace}
cassandra-snapshot-store.keyspace = \${$svc.cassandra.keyspace}
lagom.persistence.read-side.cassandra.keyspace = \${$svc.cassandra.keyspace}
END
done
```

Previous versions of Lagom automatically calculated a default Cassandra keyspace for each service, based on the name of the service project, and injected this keyspace configuration in development mode. When running in production, these calculated keyspaces were not used, resulting in multiple services sharing the same keyspaces by default.

In Lagom 1.4, services that use Cassandra persistence will fail on startup when these properties are not defined.

See [[Storing Persistent Entities in Cassandra|PersistentEntityCassandra#Configuration]] for more details.

## Upgrading to Play 2.6 and Akka 2.5

The internal upgrade to latest major versions of Play and Akka may need some changes in your code if you are using either of them directly. Please refer to the [Play 2.6 migration guide](https://www.playframework.com/documentation/2.6.x/Migration26) and the [Akka 2.5 migration guide](http://doc.akka.io/docs/akka/current/scala/project/migration-guide-2.4.x-2.5.x.html) for more details.

### Deprecations

Lagom uses Play and Akka under the covers and in occasions Lagom exposes the API provided by Play or Akka. In general this is a good enough solution to avoid adding extra layers of abstraction and wrapping. Sometimes, changes in Play or Akka can leak into our users. One such change is the [deprecation of `play.Configuration`](https://www.playframework.com/documentation/2.6.x/JavaConfigMigration26) in favour of Typesafe-Config. You may need to review your code to fix these deprecation warnings.

### Rolling upgrade

When running a rolling upgrade the nodes composing your Akka cluster must keep the ability to connect to each other and must use the same serialization formats.

If you are running Lagom 1.2.x and must do a rolling upgrade, you must first migrate to Lagom  1.3.5. Lagom 1.2.x nodes can't forma cluster with Lagom 1.4.x nodes.

One relevant change Akka 2.5 introduced involves a new method (DData) [internally handle the sharding](http://doc.akka.io/docs/akka/current/java/project/migration-guide-2.4.x-2.5.x.html#cluster-sharding-state-store-mode) of your Persistent Entities in Lagom. We have decided to not enable that new method so your migration from Lagom 1.3.x to 1.4.x should be fine. You may opt in and use DData instead of the default persistence-based one but keep in mind that switching from persistence-based to DData requires a complete-cluster shutdown.

The Java serialization was already discouraged and since Lagom 1.4.0 it is not the default anymore. This is a setting we inherit from Akka and which we are propagating transparently. If your code was dependant on the Java serialization you will need to review your serializers. This change in the defaults will also affect your ability to do a rolling upgrade. If you must support rolling upgrades and you depended on the default serializations you may override the new defaults using the [additional-serialization-bindings](http://doc.akka.io/docs/akka/current/scala/project/migration-guide-2.4.x-2.5.x.html#additional-serialization-bindings) settings.


text:
namespace syncer {
namespace {

void ReportErrorOnModelThread(
    scoped_refptr<base::SequencedTaskRunner> ui_thread,
    const ModelErrorHandler& error_handler,
    const ModelError& error) {
  ui_thread->PostTask(error.location(), base::BindOnce(error_handler, error));
}

// Takes the strictest policy for clearing sync metadata.
SyncStopMetadataFate TakeStrictestMetadataFate(SyncStopMetadataFate fate1,
                                               SyncStopMetadataFate fate2) {
  switch (fate1) {
    case CLEAR_METADATA:
      return CLEAR_METADATA;
    case KEEP_METADATA:
      return fate2;
  }
  NOTREACHED();
  return KEEP_METADATA;
}

}  // namespace

ModelTypeController::ModelTypeController(ModelType type)
    : DataTypeController(type) {}

ModelTypeController::ModelTypeController(
    ModelType type,
    std::unique_ptr<ModelTypeControllerDelegate> delegate_for_full_sync_mode)
    : ModelTypeController(type) {
  InitModelTypeController(std::move(delegate_for_full_sync_mode), nullptr);
}

ModelTypeController::ModelTypeController(
    ModelType type,
    std::unique_ptr<ModelTypeControllerDelegate> delegate_for_full_sync_mode,
    std::unique_ptr<ModelTypeControllerDelegate> delegate_for_transport_mode)
    : ModelTypeController(type) {
  InitModelTypeController(std::move(delegate_for_full_sync_mode),
                          std::move(delegate_for_transport_mode));
}

ModelTypeController::~ModelTypeController() = default;

void ModelTypeController::InitModelTypeController(
    std::unique_ptr<ModelTypeControllerDelegate> delegate_for_full_sync_mode,
    std::unique_ptr<ModelTypeControllerDelegate> delegate_for_transport_mode) {
  DCHECK(delegate_map_.empty());
  delegate_map_.emplace(SyncMode::kFull,
                        std::move(delegate_for_full_sync_mode));
  if (delegate_for_transport_mode) {
    delegate_map_.emplace(SyncMode::kTransportOnly,
                          std::move(delegate_for_transport_mode));
  }
}

void ModelTypeController::LoadModels(
    const ConfigureContext& configure_context,
    const ModelLoadCallback& model_load_callback) {
  DCHECK(CalledOnValidThread());
  DCHECK(model_load_callback);
  DCHECK_EQ(NOT_RUNNING, state_);

  auto it = delegate_map_.find(configure_context.sync_mode);
  DCHECK(it != delegate_map_.end()) << ModelTypeToDebugString(type());
  delegate_ = it->second.get();
  DCHECK(delegate_);

  DVLOG(1) << "Sync starting for " << ModelTypeToDebugString(type());
  state_ = MODEL_STARTING;
  model_load_callback_ = model_load_callback;

  DataTypeActivationRequest request;
  request.error_handler = base::BindRepeating(
      &ReportErrorOnModelThread, base::SequencedTaskRunnerHandle::Get(),
      base::BindRepeating(&ModelTypeController::ReportModelError,
                          base::AsWeakPtr(this), SyncError::DATATYPE_ERROR));
  request.authenticated_account_id = configure_context.authenticated_account_id;
  request.cache_guid = configure_context.cache_guid;
  request.sync_mode = configure_context.sync_mode;
  request.configuration_start_time = configure_context.configuration_start_time;

  // Note that |request.authenticated_account_id| may be empty for local sync.
  DCHECK(!request.cache_guid.empty());

  // Ask the delegate to actually start the datatype.
  delegate_->OnSyncStarting(
      request, base::BindOnce(&ModelTypeController::OnDelegateStarted,
                              base::AsWeakPtr(this)));
}

std::unique_ptr<DataTypeActivationResponse> ModelTypeController::Connect() {
  DCHECK(CalledOnValidThread());
  DCHECK(activation_response_);
  DCHECK_EQ(MODEL_LOADED, state_);

  state_ = RUNNING;
  DVLOG(1) << "Sync running for " << ModelTypeToDebugString(type());

  return std::move(activation_response_);
}

void ModelTypeController::Stop(ShutdownReason reason, StopCallback callback) {
  DCHECK(CalledOnValidThread());

  // Leave metadata if we do not disable sync completely.
  SyncStopMetadataFate metadata_fate = KEEP_METADATA;
  switch (reason) {
    case ShutdownReason::STOP_SYNC_AND_KEEP_DATA:
      break;
    case ShutdownReason::DISABLE_SYNC_AND_CLEAR_DATA:
      metadata_fate = CLEAR_METADATA;
      break;
    case ShutdownReason::BROWSER_SHUTDOWN_AND_KEEP_DATA:
      break;
  }

  switch (state()) {
    case NOT_RUNNING:
    case FAILED:
      // Nothing to stop. |metadata_fate| might require CLEAR_METADATA,
      // which could lead to leaking sync metadata, but it doesn't seem a
      // realistic scenario (disable sync during shutdown?).
      std::move(callback).Run();
      return;

    case STOPPING:
      DCHECK(!model_stop_callbacks_.empty());
      model_stop_metadata_fate_ =
          TakeStrictestMetadataFate(model_stop_metadata_fate_, metadata_fate);
      model_stop_callbacks_.push_back(std::move(callback));
      break;

    case MODEL_STARTING:
      DCHECK(model_load_callback_);
      DCHECK(model_stop_callbacks_.empty());
      DLOG(WARNING) << "Deferring stop for " << ModelTypeToDebugString(type())
                    << " because it's still starting";
      model_load_callback_.Reset();
      model_stop_metadata_fate_ = metadata_fate;
      model_stop_callbacks_.push_back(std::move(callback));
      // The actual stop will be executed when the starting process is finished.
      state_ = STOPPING;
      break;

    case MODEL_LOADED:
    case RUNNING:
      DVLOG(1) << "Stopping sync for " << ModelTypeToDebugString(type());
      model_load_callback_.Reset();
      state_ = NOT_RUNNING;
      delegate_->OnSyncStopping(metadata_fate);
      delegate_ = nullptr;
      std::move(callback).Run();
      break;
  }
}

DataTypeController::State ModelTypeController::state() const {
  return state_;
}

bool ModelTypeController::ShouldRunInTransportOnlyMode() const {
  // By default, running in transport-only mode is enabled if the corresponding
  // delegate exists, i.e. the controller is aware of transport-only mode and
  // supports it in principle. Subclass can still override this with more
  // specific logic.
  return delegate_map_.count(SyncMode::kTransportOnly) != 0;
}

void ModelTypeController::GetAllNodes(AllNodesCallback callback) {
  DCHECK(delegate_);
  delegate_->GetAllNodesForDebugging(std::move(callback));
}

void ModelTypeController::GetTypeEntitiesCount(
    base::OnceCallback<void(const TypeEntitiesCount&)> callback) const {
  if (delegate_) {
    delegate_->GetTypeEntitiesCountForDebugging(std::move(callback));
  } else {
    std::move(callback).Run(TypeEntitiesCount(type()));
  }
}

void ModelTypeController::RecordMemoryUsageAndCountsHistograms() {
  DCHECK(delegate_);
  delegate_->RecordMemoryUsageAndCountsHistograms();
}

ModelTypeControllerDelegate* ModelTypeController::GetDelegateForTesting(
    SyncMode sync_mode) {
  auto it = delegate_map_.find(sync_mode);
  return it != delegate_map_.end() ? it->second.get() : nullptr;
}

void ModelTypeController::ReportModelError(SyncError::ErrorType error_type,
                                           const ModelError& error) {
  DCHECK(CalledOnValidThread());

  switch (state_) {
    case MODEL_LOADED:
    // Fall through. Before state_ is flipped to RUNNING, we treat it as a
    // start failure. This is somewhat arbitrary choice.
    case STOPPING:
    // Fall through. We treat it the same as starting as this means stopping was
    // requested while starting the data type.
    case MODEL_STARTING:
      RecordStartFailure();
      break;
    case RUNNING:
      RecordRunFailure();
      break;
    case NOT_RUNNING:
      // Error could arrive too late, e.g. after the datatype has been stopped.
      // This is allowed for the delegate's convenience, so there's no
      // constraints around when exactly
      // DataTypeActivationRequest::error_handler is supposed to be used (it can
      // be used at any time). This also simplifies the implementation of
      // task-posting delegates.
      state_ = FAILED;
      return;
    case FAILED:
      // Do not record for the second time and exit early.
      return;
  }

  state_ = FAILED;

  TriggerCompletionCallbacks(
      SyncError(error.location(), error_type, error.message(), type()));
}

void ModelTypeController::RecordStartFailure() const {
  DCHECK(CalledOnValidThread());
  UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeStartFailures2",
                            ModelTypeHistogramValue(type()));
}

void ModelTypeController::RecordRunFailure() const {
  DCHECK(CalledOnValidThread());
  UMA_HISTOGRAM_ENUMERATION("Sync.DataTypeRunFailures2",
                            ModelTypeHistogramValue(type()));
}

void ModelTypeController::OnDelegateStarted(
    std::unique_ptr<DataTypeActivationResponse> activation_response) {
  DCHECK(CalledOnValidThread());

  switch (state_) {
    case STOPPING:
      DCHECK(!model_stop_callbacks_.empty());
      DCHECK(!model_load_callback_);
      state_ = NOT_RUNNING;
      [[fallthrough]];
    case FAILED:
      DVLOG(1) << "Successful sync start completion received late for "
               << ModelTypeToDebugString(type())
               << ", it has been stopped meanwhile";
      delegate_->OnSyncStopping(model_stop_metadata_fate_);
      delegate_ = nullptr;
      break;
    case MODEL_STARTING:
      DCHECK(model_stop_callbacks_.empty());
      // Hold on to the activation context until Connect is called.
      activation_response_ = std::move(activation_response);
      state_ = MODEL_LOADED;
      DVLOG(1) << "Sync start completed for " << ModelTypeToDebugString(type());
      break;
    case MODEL_LOADED:
    case RUNNING:
    case NOT_RUNNING:
      NOTREACHED() << " type " << ModelTypeToDebugString(type()) << " state "
                   << StateToString(state_);
  }

  TriggerCompletionCallbacks(SyncError());
}

void ModelTypeController::TriggerCompletionCallbacks(const SyncError& error) {
  DCHECK(CalledOnValidThread());

  if (model_load_callback_) {
    DCHECK(model_stop_callbacks_.empty());
    DCHECK(state_ == MODEL_LOADED || state_ == FAILED);

    model_load_callback_.Run(type(), error);
  } else if (!model_stop_callbacks_.empty()) {
    // State FAILED is possible if an error occurred during STOPPING, either
    // because the load failed or because ReportModelError() was called
    // directly by a subclass.
    DCHECK(state_ == NOT_RUNNING || state_ == FAILED);

    // We make a copy in case running the callbacks has side effects and
    // modifies the vector, although we don't expect that in practice.
    std::vector<StopCallback> model_stop_callbacks =
        std::move(model_stop_callbacks_);
    DCHECK(model_stop_callbacks_.empty());
    for (StopCallback& stop_callback : model_stop_callbacks) {
      std::move(stop_callback).Run();
    }
  }
}

}  // namespace syncer


text:
package com.yahoo.athenz.common.server.store.impl;

import com.yahoo.athenz.common.server.store.ChangeLogStore;

import java.security.PrivateKey;

public class MockS3ChangeLogStoreFactory extends S3ChangeLogStoreFactory {

    @Override
    public ChangeLogStore create(String ztsHomeDir, PrivateKey privateKey,
                                 String privateKeyId) {
        return new MockS3ChangeLogStore();
    }
}


text:
using OrigoDB.Core.Utilities;
using NUnit.Framework;
using System;

namespace OrigoDB.Core.Test
{
    [TestFixture]
    public class HashUtilityTest
    {
        [Test,ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void RejectsZeroSaltLength()
        {
            HashUtility.CreateHashWithRandomSalt("abc", 0);
        }

        [Test, ExpectedException(typeof(ArgumentOutOfRangeException))]
        public void RejectsNegativeSaltLength()
        {
            HashUtility.CreateHashWithRandomSalt("abc", -7);
        }

        [Test, ExpectedException(typeof(ArgumentNullException))]
        public void RejectsNullPlainText()
        {
            HashUtility.CreateHashWithRandomSalt(null);
        }

        [Test, ExpectedException(typeof(ArgumentException))]
        public void RejectsZeroLengthPlainText()
        {
            HashUtility.CreateHashWithRandomSalt(String.Empty);
        }

        [Test]
        public void HashWithDefaultSaltLengthIsVerified()
        {
            string plainText = "abc";
            string hash = HashUtility.CreateHashWithRandomSalt(plainText);
            Assert.IsTrue(HashUtility.Verify(plainText, hash));
        }

        [Test]
        [TestCase(4)]
        [TestCase(6)]
        [TestCase(10)]
        [TestCase(43)]
        [TestCase(100)]
        public void HashWithSpecificSaltLengthIsVerified(int saltLength)
        {
            string plainText = "abc" + saltLength;
            string hash = HashUtility.CreateHashWithRandomSalt(plainText);
            Assert.IsTrue(HashUtility.Verify(plainText, hash));
        }

    }
}


text:
using namespace std;

// This is for printing a particular node

void print_node(int node_number, vector<vector<int> > graph){
    vector<int>::iterator vector_iterator;

    cout << "This is node number " << node_number << endl;

    for(vector_iterator=graph[node_number - 1].begin(); vector_iterator!=graph[node_number - 1].end(); ++vector_iterator){
    cout << (*vector_iterator) << " ";
  }
    cout << endl;

}

void select_edge(int *node_u, int *node_v, vector<vector<int> > &graph){

    // First select a node
    cout << "Select edge graph size" << graph.size() << endl;

    (*node_u) = rand() % graph.size()  + 1;
    vector<int> aux_vector = graph[(*node_u) - 1];

    // Then select and edge
    print_node((*node_u), graph);

    int index_v = rand() % aux_vector.size();

    cout << "Index " << index_v << endl;
    cout << "node v size" << aux_vector.size() << endl;

    (*node_v) = aux_vector[index_v];

    cout << "node v" << (*node_v) << endl;

}

// Now we have a function to merge

void merge(int node_u, int node_v, vector<vector<int> > &graph){
    vector<int>::iterator vector_iterator;
    vector<int>::iterator vector_iterator2;
    int x;

    for(vector_iterator=graph[node_v - 1].begin(); vector_iterator!=graph[node_v - 1].end(); ++vector_iterator){
	x = (*vector_iterator);  // This is the node that node_v points to
	// Now we need to change the contents of the vector x
	for(vector_iterator2=graph[x - 1].begin(); vector_iterator2!=graph[x - 1].end(); ++vector_iterator2){
	    if ((*vector_iterator2)== node_v){
		(*vector_iterator2) = node_u;
	    }
	}
    }

}

void erase_node_v(int node_v, vector<vector<int> > &graph){

    for(int i=0; i<graph.size(); ++i){
	if(i == (node_v - 1)){
	    graph.erase(graph.begin() + i);
	}
    }
}

// Now we need to erase the self loops
void erase_self_loop(int node_u, vector<vector<int> > &graph){
    for(int i=0; i<graph[node_u - 1].size(); ++i){
	if(graph[node_u - 1][i]  == node_u){
	    graph[node_u - 1].erase(graph[node_u - 1].begin() + i);
	}
    }

}

int main()
{
  string line;
  vector<string> data;
  // Set the seed
  srand(time(NULL));

  // First we load the file

  ifstream infile("kargerMinCut.txt");

  if(!infile){
    cout << "no file " << endl;
  }

  while(infile){
    getline(infile, line);
    data.push_back(line); // Put data in the vector
  }

  // Now we define the graph as a vector of vector.
  // Every entry in the vector is a node, and each node is
  // a vector with the adjancent nodes.

  vector<vector<int> > graph (data.size());

  int n = data.size();

  cout << "Number of nodes = " <<  n << endl;

  for(int i=0; i < data.size(); ++i){
    // Make the i row a string-stream
    stringstream iss(data[i]);
    int number;
    vector<int> aux_vector;
    // As long as there is something on the buffer
    while(iss >> number){
	if(number != i + 1){
	    aux_vector.push_back(number);
	}
    }
    graph[i] = aux_vector;

  }

  int node_u, node_v;

  while(graph.size() > 2){
      cout << "graph size " << graph.size() << endl;

      // First we select a node
      select_edge(&node_u, &node_v, graph);

      cout << "outside u is " << node_u << endl;
      cout << "outside v is " << node_v << endl;

      // Then we merge the nodes u and v
      merge(node_u, node_v, graph);
      cout << "merged" << endl;

      // No we erase the self loops
      erase_self_loop(node_u, graph);
      cout << "self loop erased" << endl;

      // No we need to erase the node_v
      erase_node_v(node_v, graph);
      cout << "node erased" << endl;

      cout << "print node u for errors" << endl;
      print_node(node_u, graph);
      // Jump the line to visualize
      cout << endl;
  }
  return 0;

}


text:
That's some text with a footnote [^b] and another [^c] and another [^a].

[^a]: And that's the footnote.

    That's the second paragraph of the footnote.

[^b]: And that's the footnote.
This is second sentence (same paragraph).

[^c]:
    This is the very long one.

    That's the second paragraph.

This is not a footnote.


text:
package me.puras.mooro.controller;

import me.puras.common.holder.ObjectMapperHolder;
import me.puras.common.json.Converter;
import me.puras.common.json.JacksonConverter;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author puras <he@puras.me>
 * @since 16/3/3  下午3:38
 */
@RestController
public class EmulatorController {
    @RequestMapping(value ="/**/*", method = RequestMethod.GET)
    public Object get(HttpServletRequest req) {
        return doRest(req);
    }

    @RequestMapping(value ="/**/*", method = RequestMethod.POST)
    public Object post(HttpServletRequest req) {
        return doRest(req);
    }

    @RequestMapping(value ="/**/*", method = RequestMethod.PUT)
    public Object put(HttpServletRequest req) {
        return doRest(req);
    }

    @RequestMapping(value ="/**/*", method = RequestMethod.DELETE)
    public Object del(HttpServletRequest req) {
        return doRest(req);
    }

    private Object doRest(HttpServletRequest req) {
        displayRequestInfo(req);
        String fileName = (getFileName(req));
        System.out.println("File Name is: " + fileName);
        InputStream is = this.getClass().getResourceAsStream("/data/" + fileName);

        if (null == is) {
            return "File is not found.";
        }

        String json = "Parse Error.";
        try {
            StringWriter writer = new StringWriter();
            IOUtils.copy(is, writer, "UTF-8");
            json = writer.toString();
            System.out.println("******************************");
            System.out.println("Response Body: ");
            System.out.println(json);
            System.out.println("******************************");
            Converter converter = new JacksonConverter(ObjectMapperHolder.getInstance().getMapper());
            Object obj = converter.convertToObject(json, Object.class);
            return obj;
        } catch (IOException ex) {
            ex.printStackTrace();
            return json;
        }
//        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
//            json = reader.lines().collect(Collectors.joining());
//            System.out.println(json);
//            Converter converter = new JacksonConverter(ObjectMapperHolder.getInstance().getMapper());
//            Object obj = converter.convertToObject(json, Object.class);
//            return obj;
//        } catch (IOException ex) {
//            ex.printStackTrace();
//            return json;
//        }
    }

    private String getFileName(HttpServletRequest req) {
        String url = req.getRequestURI();
        String method = req.getMethod();
        url = url.replaceAll("/", "_");
        if (url.startsWith("_")) {
            url = url.substring(1);
        }

        Map<String, String[]> params = req.getParameterMap();
        String queryString = "";
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = "";
            String[] values = entry.getValue();
            if (null != values && values.length > 0) {
                for (String val : values) {
                    value += val;
                }
            }
            queryString += key + "=" + value + "+";
        }

        if (queryString.endsWith("+")) {
            queryString = queryString.substring(0, queryString.length() - 1);
        }

        if (null != queryString && queryString.length() > 0) {
            url += "#" + queryString;
        }

        return url.toLowerCase() + "-" + method.toLowerCase() + ".json";
    }

    private void displayRequestInfo(HttpServletRequest req) {
        System.out.println("==============================");
        System.out.println("Request URL:" + req.getRequestURI());
        System.out.println("Request Method: " + req.getMethod());
        System.out.println("------------------------------");
        System.out.println("Request Header");
        System.out.println("------------------------------");
        Enumeration<String> enumeration = req.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            System.out.println("Header[" + key + "]=" + req.getHeader(key));
        }
        System.out.println("------------------------------");
        System.out.println("Request Query String");
        System.out.println("------------------------------");
        Map<String, String[]> params = req.getParameterMap();
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            String key = entry.getKey();
            String value = "";
            String[] values = entry.getValue();
            if (null != values && values.length > 0) {
                for (String val : values) {
                    value += val;
                }
            }
            System.out.println("QueryString[" + key + "]=" + value);
        }
        if (req.getMethod().toLowerCase().equals("post")) {
            System.out.println("------------------------------");
            System.out.println("Request Body");
            System.out.println("------------------------------");
            try {
                BufferedReader reader = req.getReader();
                String buffer = null;
                while ((buffer = reader.readLine()) != null) {
                    System.out.println(buffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("==============================");
    }
}