text:
class logstream : public std::ofstream {

  public:
    static bool log_initialized;
    unsigned int priority;
    unsigned int threshold;

    logstream(const char *fname, unsigned int p = 0, unsigned int tp = 0);
    ~logstream();

    // Output operators

    _DECLARE_LOGSTREAM_OUTPUT_OPERATOR(const char *);
    _DECLARE_LOGSTREAM_OUTPUT_OPERATOR(const char);
    _DECLARE_LOGSTREAM_OUTPUT_OPERATOR(const int);
    _DECLARE_LOGSTREAM_OUTPUT_OPERATOR(const unsigned int);
    _DECLARE_LOGSTREAM_OUTPUT_OPERATOR(const long int);
    _DECLARE_LOGSTREAM_OUTPUT_OPERATOR(const long unsigned int);
    _DECLARE_LOGSTREAM_OUTPUT_OPERATOR(const float);
    _DECLARE_LOGSTREAM_OUTPUT_OPERATOR(const double);

    //  WIN32 does not support data type "long long".
    TPIE_OS_UNIX_ONLY_DATA_TYPE_LONG_LONG
};

// The logmanip template is based on the omanip template from iomanip.h
// in the libg++ sources.

template <class TP> class logmanip {
    logstream& (*_f)(logstream&, TP);
    TP _a;
public:
    logmanip(logstream& (*f)(logstream&, TP), TP a) : _f(f), _a(a) {}

#if (__GNUC__ > 2) || (__GNUC__ == 2 &&  __GNUC_MINOR__ >= 8)
    friend logstream& operator<< <> (logstream& o, const logmanip<TP>& m);
#else
    friend logstream& operator<< (logstream& o, const logmanip<TP>& m);
#endif
};

template <class TP>
logstream& operator<< (logstream& o, const logmanip<TP>& m)
{
  (*m._f)(o, m._a); return o;
}

logmanip<unsigned int> setpriority(unsigned int p);
logmanip<unsigned int> setthreshold(unsigned int p);

#endif // _LOGSTREAM_H


text:
package com.maddyhome.idea.copyright.psi;

import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiManager;
import com.maddyhome.idea.copyright.CopyrightManager;
import com.maddyhome.idea.copyright.CopyrightProfile;
import com.maddyhome.idea.copyright.options.LanguageOptions;
import com.maddyhome.idea.copyright.pattern.EntityUtil;
import com.maddyhome.idea.copyright.pattern.VelocityHelper;
import com.maddyhome.idea.copyright.util.FileTypeUtil;

public abstract class AbstractUpdateCopyright implements UpdateCopyright {
  private String commentText = null;
  private final Project project;
  private final Module module;
  private final VirtualFile root;
  private final CopyrightProfile myCopyrightProfile;
  private final PsiManager manager;

  protected AbstractUpdateCopyright(Project project, Module module, VirtualFile root, CopyrightProfile copyrightProfile) {
    this.project = project;
    this.module = module;
    this.root = root;
    myCopyrightProfile = copyrightProfile;
    manager = PsiManager.getInstance(project);
  }

  protected String getCommentText(String prefix, String suffix) {
    if (commentText == null) {
      FileType ftype = FileTypeUtil.getInstance().getFileTypeByFile(root);
      LanguageOptions opts = CopyrightManager.getInstance(project).getOptions().getMergedOptions(ftype.getName());
      String base = EntityUtil.decode(myCopyrightProfile.getNotice());
      if (base.isEmpty()) {
        commentText = "";
      }
      else {
        String expanded = VelocityHelper.evaluate(manager.findFile(root), project, module, base);
        String cmt = FileTypeUtil.buildComment(root.getFileType(), expanded, opts);
        commentText = StringUtil.convertLineSeparators(prefix + cmt + suffix);
      }
    }

    return commentText;
  }

  @Override
  public VirtualFile getRoot() {
    return root;
  }

  public PsiManager getManager() {
    return manager;
  }

  protected void resetCommentText() {
    commentText = null;
  }

  protected static int countNewline(String text) {
    int cnt = 0;
    for (int i = 0; i < text.length(); i++) {
      if (text.charAt(i) == '\n') {
        cnt++;
      }
    }

    return cnt;
  }
}

redpajama_set_name: RedPajamaGithub


text:
First line

Second line

      ID
      Item Name
      Item Price


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
  ~ Licensed to the Apache Software Foundation (ASF) under one
  ~ or more contributor license agreements. See the NOTICE file
  ~ distributed with this work for additional information
  ~ regarding copyright ownership. The ASF licenses this file
  ~ to you under the Apache License, Version 2.0 (the
  ~ "License"); you may not use this file except in compliance
  ~ with the License. You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied. See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.apache.axis2</groupId>
        <artifactId>axis2-parent</artifactId>
        <version>1.6.1-wso2v16-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>
    <artifactId>axis2-fastinfoset</artifactId>
    <name>Apache Axis2 - Fast Infoset</name>
    <description>Axis2 Fast Infoset module</description>
    <dependencies>
        <dependency>
            <groupId>com.sun.xml.fastinfoset</groupId>
            <artifactId>FastInfoset</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-kernel</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-adb</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>wsdl4j</groupId>
            <artifactId>wsdl4j</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.ws.commons.schema.wso2</groupId>
            <artifactId>XmlSchema</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-java2wsdl</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-adb-codegen</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>axis2-codegen</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.neethi</groupId>
            <artifactId>neethi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2</groupId>
            <artifactId>addressing</artifactId>
            <version>${project.version}</version>
            <type>mar</type>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>xmlunit</groupId>
            <artifactId>xmlunit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <!--scm>
        <connection>scm:svn:http://svn.apache.org/repos/asf/axis/axis2/java/core/branches/1_6/modules/fastinfoset</connection>
        <developerConnection>scm:svn:https://svn.apache.org/repos/asf/axis/axis2/java/core/branches/1_6/modules/fastinfoset</developerConnection>
        <url>http://svn.apache.org/viewvc/axis/axis2/java/core/branches/1_6/modules/fastinfoset</url>
    </scm-->
    <build>
        <sourceDirectory>src</sourceDirectory>
        <testSourceDirectory>test</testSourceDirectory>
        <resources>
            <resource>
                <directory>conf</directory>
                <includes>
                    <include>**/*.properties</include>
                </includes>
            </resource>
            <resource>
                <directory>src</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>resources</directory>
                <includes>
                    <include>**/*</include>
                </includes>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>test</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.wsdl</include>
                    <include>**/*.properties</include>
                </includes>
            </testResource>
            <testResource>
                <directory>${project.build.directory}/repo</directory>
            </testResource>
        </testResources>
        <plugins>
            <plugin>
                <artifactId>maven-remote-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <resourceBundles>
                                <resourceBundle>org.apache.axis2:axis2-resource-bundle:${project.version}</resourceBundle>
                            </resourceBundles>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <inherited>true</inherited>
            </plugin>
            <plugin>
                <groupId>org.apache.axis2</groupId>
                <artifactId>axis2-repo-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>create-test-repository</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/repo</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-antrun-plugin</artifactId>
                <executions>
                    <execution>
                        <id>gen-ts</id>
                        <phase>generate-test-sources</phase>
                        <configuration>
                            <tasks unless="maven.test.skip">
                                <!-- Set a property that can be picked up from the ant build.xml's -->
                                <property name="maven.class.path" refid="maven.runtime.classpath" />
                                <property name="maven.test.path" refid="maven.compile.classpath" />
                                <mkdir dir="target/test-classes" />

                                <property name="axis2.home" value="${basedir}/target" />
                                <path id="maven.dependency.classpath">
                                    <path refid="maven.compile.classpath" />
                                </path>
                                <!-- compiling some custom wsdl files -->
                                <property name="wsdl.source.dir" value="test-resources/wsdl" />
                                <property name="wsdl.output.base.dir" value="target/wsdl" />
                                <!-- make the dirs -->
                                <mkdir dir="${wsdl.output.base.dir}" />
                                <echo>Compiling Service class</echo>
                                <javac fork="true" destdir="target/test-classes" debug="on">
                                    <classpath refid="maven.dependency.classpath" />
                                    <classpath location="${compiled.classes.dir}" />
                                    <include name="**/*SimpleAddService.java" />
                                    <src path="test/" />
                                </javac>
                                <echo>Generating the WSDL</echo>
                                <java classname="org.apache.ws.java2wsdl.Java2WSDL" fork="true">
                                    <classpath>
                                        <path refid="maven.dependency.classpath" />
                                        <pathelement location="target/test-classes" />
                                    </classpath>
                                    <arg line="-o target/test-classes -of SimpleAddService.wsdl -efd unqualified -cn org.apache.axis2.fastinfoset.SimpleAddService" />
                                </java>

                                <echo>Compiling SimpleAddService.wsdl</echo>
                                <mkdir dir="${wsdl.output.base.dir}/simpleAddService" />

                                <java classname="org.apache.axis2.wsdl.WSDL2Java" fork="true">
                                    <classpath refid="maven.runtime.classpath" />
                                    <classpath location="${compiled.classes.dir}" />
                                    <arg line="-uri target/test-classes/SimpleAddService.wsdl -o target/wsdl/simpleAddService -S . -or" />
                                </java>
                            </tasks>
                        </configuration>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>add-test-source</id>
                        <phase>generate-test-sources</phase>
                        <goals>
                            <goal>add-test-source</goal>
                        </goals>
                        <configuration>
                            <sources>
                                <source>${project.build.directory}/wsdl/simpleAddService</source>
                            </sources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <inherited>true</inherited>
                <configuration>
                    <!-- The pertest forkMode is not ideal but seems to be necessary
                         because the test server doesn't shut down properly :-(
                         Should be removed if possible -->
                    <forkMode>pertest</forkMode>
                    <argLine>-Xms256m -Xmx512m</argLine>
                    <!-- Enable the next 2 lines if you want to attach a debugger
                   <argLine>-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5006</argLine>-->
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                    <systemProperties>
                        <property>
                            <name>build.repository</name>
                            <value>./target/test-classes</value>
                        </property>
                    </systemProperties>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
angular.module('orderCloud')
	.config(checkoutShippingConfig)
	.controller('CheckoutShippingCtrl', CheckoutShippingController)
    .factory('OrderShippingAddress', OrderShippingAddressFactory)
;

function checkoutShippingConfig($stateProvider) {
	$stateProvider
		.state('checkout.shipping', {
			url: '/shipping',
			templateUrl: 'checkout/shipping/templates/checkout.shipping.tpl.html',
			controller: 'CheckoutShippingCtrl',
			controllerAs: 'checkoutShipping'
		})
}

function CheckoutShippingController($state, $rootScope, Addresses, Orders, Me, ImpersonationService, OrderShippingAddress) {
	var vm = this;
    vm.saveAddress = null;
    vm.isAlsoBilling = null;
    vm.address = {};
    vm.SaveShippingAddress = saveShipAddress;
    vm.SaveCustomAddress = saveCustomAddress;
    vm.customShipping = false;
    vm.shippingAddress = null;

    function saveShipAddress(order) {
        if (order && order.ShippingAddressID) {
            OrderShippingAddress.Set(order.ShippingAddressID);
            Addresses.Get(order.ShippingAddressID)
                .then(function(address){
                    Orders.SetShippingAddress(order.ID, address)
                        .then(function() {
                            $rootScope.$broadcast('OrderShippingAddressChanged', order, address);
                        });
                })

        }
    }

    function saveCustomAddress(order) {
        if (vm.saveAddress) {
            Addresses.Create(vm.address)
                .then(function(address) {
                    ImpersonationService.Impersonation(function() {
                        Me.Get()
                            .then(function(me) {
                                Addresses.SaveAssignment({
                                    AddressID: address.ID,
                                    UserID: me.ID,
                                    IsBilling: vm.isAlsoBilling,
                                    IsShipping: true
                                })
                                    .then(function() {
                                        Addresses.Get(address.ID)
                                            .then(function(address) {
                                                Orders.SetShippingAddress(order.ID, address)
                                                    .then(function() {
                                                        $state.reload();
                                                    });
                                    })
                                });
                            });
                    });
                });
        }
        else {
            Orders.SetShippingAddress(order.ID, vm.address)
                .then(function() {
                    $state.reload();
                });
        }
    }
}

function OrderShippingAddressFactory($q, $localForage, appname, Addresses) {
    var StorageName = appname + '.ShippingAddressID';
    return {
        Get: Get,
        Set: Set,
        Clear: Clear
    };

    function Get() {
        var dfd = $q.defer();
        $localForage.getItem(StorageName)
            .then(function(shipID) {
                if (shipID) {
                    Addresses.Get(shipID)
                        .then(function(address) {
                            if (!address.Items) {
                                dfd.resolve(address);
                            }
                            else dfd.reject();
                        })
                        .catch(function() {
                            Clear();
                            dfd.reject();
                        });
                }
                else dfd.reject();
            })
            .catch(function() {
                dfd.reject();
            });
        return dfd.promise;
    }

    function Set(ShipAddressID) {
        $localForage.setItem(StorageName, ShipAddressID);
    }

    function Clear() {
        $localForage.removeItem(StorageName);
    }
}


text:
import hbs                          from 'htmlbars-inline-precompile';
import Ember                        from 'ember';
import { moduleForComponent, test } from 'ember-qunit';
// import waitForPromise               from '../../helpers/wait-for-promise';

moduleForComponent('g-maps', 'Integration | Component | g maps', {
  integration: true,
  beforeEach() {
    this.inject.service('g-map', { as: 'gMapService' });
  }
});

test('it renders', function(assert) {
  this.setProperties({
    name: 'name',
    lat: 0,
    lng: 0,
    zoom: 10,
    gMap: Ember.inject.service()
  });

  this.render(hbs`{{g-maps name=name lat=lat lng=lng zoom=zoom}}`);

  /* Need map to render
  Ember.run(() => {
    this.get('gMap').maps.select('name').onLoad.then(() => {
      console.log('excelzior!');
    });
  });
  */

  const $gmap = this.$('.ember-cli-g-map');
  assert.equal($gmap.length, 1);
});

test('it should add a map instance to the g-map service', function(assert) {
  assert.expect(1);

  this.setProperties({
    name: 'name',
    lat: 0,
    lng: 0,
    zoom: 10,
    gMap: Ember.inject.service()
  });

  this.render(hbs`{{g-maps name=name lat=lat lng=lng zoom=zoom}}`);

  assert.equal(
    this.get('gMapService').maps.select('name').name,
    'name',
    'should have added a map instance to map service'
  );
});

test('it should sync on `isMapLoaded` and updates to bound `markers.[]`', function(assert) {
  this.setProperties({
    markers: Ember.A(),
    map: null
  });

  // *Warning* causes console warning: "was modified inside the didInsertElement hook"
  this.render(hbs`{{g-maps markers=markers isMapLoaded=true map=(mut map)}}`);

  assert.equal(this.get('map.markers.length'), '0', 'should have `0` markers length');

  this.get('markers').pushObject({ id: 123, lat: 1, lng: 1});

  assert.equal(this.get('map.markers.length'), '1', 'should have `1` markers length');
});

test('it should sync on `isMapLoaded` and updates to bound `circles.[]`', function(assert) {
  this.setProperties({
    circles: Ember.A(),
    map: null
  });

  // *Warning* causes console warning: "was modified inside the didInsertElement hook"
  this.render(hbs`{{g-maps circles=circles isMapLoaded=true map=(mut map)}}`);

  assert.equal(this.get('map.circles.length'), '0', 'should have `0` circles length');

  this.get('circles').pushObject({ id: 123, lat: 1, lng: 1, radius: 2 });

  assert.equal(this.get('map.circles.length'), '1', 'should have `1` circles length');
});

test('it should sync on `isMapLoaded` and updates to bound `polygons.[]`', function(assert) {
  this.setProperties({
    polygons: Ember.A(),
    map: null
  });

  // *Warning* causes console warning: "was modified inside the didInsertElement hook"
  this.render(hbs`{{g-maps polygons=polygons isMapLoaded=true map=(mut map)}}`);

  assert.equal(this.get('map.polygons.length'), '0', 'should have `0` polygons length');

  this.get('polygons').pushObject({ id: 123, paths: [ [1, 2], [2, 1] ]});

  assert.equal(this.get('map.polygons.length'), '1', 'should have `1` polygons length');
});

test('it should sync on `isMapLoaded` and updates to bound `polylines.[]`', function(assert) {
  this.setProperties({
    polylines: Ember.A(),
    map: null
  });

  // *Warning* causes console warning: "was modified inside the didInsertElement hook"
  this.render(hbs`{{g-maps polylines=polylines isMapLoaded=true map=(mut map)}}`);

  assert.equal(this.get('map.polylines.length'), '0', 'should have `0` polylines length');

  this.get('polylines').pushObject({ id: 123, path: [ [1, 2], [2, 1] ]});

  assert.equal(this.get('map.polylines.length'), '1', 'should have `1` polylines length');
});

test('it should sync on `isMapLoaded` and updates to bound `rectangles.[]`', function(assert) {
  this.setProperties({
    rectangles: Ember.A(),
    map: null
  });

  // *Warning* causes console warning: "was modified inside the didInsertElement hook"
  this.render(hbs`{{g-maps rectangles=rectangles isMapLoaded=true map=(mut map)}}`);

  assert.equal(this.get('map.rectangles.length'), '0', 'should have `0` rectangles length');

  this.get('rectangles').pushObject({ id: 123, bounds: [ [1, 2], [2, 1] ]});

  assert.equal(this.get('map.rectangles.length'), '1', 'should have `1` rectangles length');
});

// test('it should sync on `isMapLoaded` and updates to bound `overlays.[]`', function(assert) {
//   this.setProperties({
//     overlays: Ember.A(),
//     map: null
//   });
//
//   // *Warning* causes console warning: "was modified inside the didInsertElement hook"
//   this.render(hbs`{{g-maps overlays=overlays isMapLoaded=true map=(mut map)}}`);
//
//   assert.equal(this.get('map.overlays.length'), '0', 'should have `0` overlays length');
//
//   this.get('overlays').pushObject({ id: 123, lat: 1, lng: 1});
//
//   assert.equal(this.get('map.overlays.length'), '1', 'should have `1` overlays length');
// });


text:
package com.dms.core.req.model;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.axonframework.commandhandling.annotation.CommandHandler;
import org.axonframework.eventsourcing.annotation.EventSourcingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dms.core.base.common.ddd.aggregate.BaseAnnotatedAggregateRoot;
import com.dms.core.inf.req.MReqApplication;
import com.dms.core.inf.req.cmd.CReqApplicationCmd;
import com.dms.core.inf.req.cmd.SubmitReqApplicationCmd;
import com.dms.core.inf.req.cmd.UReqApplicationCmd;
import com.dms.core.req.evt.CReqApplicationEvt;
import com.dms.core.req.evt.SubmitReqApplicationEvt;
import com.dms.core.req.evt.UReqApplicationEvt;

/**
 * 需求申请
 *
 * @author xhtian
 *
 */
public class ReqApplication extends BaseAnnotatedAggregateRoot<String>{

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

	private MReqApplication mReqApplication;

	public ReqApplication() {
		super();
	}

	@CommandHandler
	public ReqApplication(CReqApplicationCmd cmd) {
		apply(new CReqApplicationEvt(cmd.getModel()));
	}

	@CommandHandler
	public void updateDesc(UReqApplicationCmd cmd){
		apply(new UReqApplicationEvt(cmd.getModel()));
	}

	@CommandHandler
	public void submit(SubmitReqApplicationCmd cmd){
		apply(new SubmitReqApplicationEvt(cmd.getModel()));
	}

	/**
	 *
	 * @param evt
	 * @see com.dms.core.req.evd.ReqApplicationDtoEvd#cReqApplicationDto(CReqApplicationEvt)
	 */
	@EventSourcingHandler
	private void onCReqApplicationEvt(CReqApplicationEvt evt){
		setIdentifier(evt.getModel().identifier());
		this.mReqApplication = evt.getModel();
		logger.debug("created:[{}]" ,ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE));
	}

	/**
	 *
	 * @param evt
	 * @see com.dms.core.req.evd.ReqApplicationDtoEvd#uReqApplicationDto(UReqApplicationEvt)
	 */
	@EventSourcingHandler
	private void onUReqApplicationEvt(UReqApplicationEvt evt){
		if (mReqApplication.isState()) {
			throw new UnsupportedOperationException("u had submited.");
		}
		mReqApplication.setAppDescription(evt.getModel().getAppDescription());
		logger.debug("update:[{}]" , ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE));
	}

	/**
	 *
	 * @param evt
	 * @see com.dms.core.req.evd.ReqApplicationDtoEvd#submit(SubmitReqApplicationEvt)
	 * @see com.dms.core.req.evd.SubmitReqApplicationEvdCreatChangeLog#createChangeLog(SubmitReqApplicationEvt)
	 */
	@EventSourcingHandler
	private void onSubmitReqApplicationEvt(SubmitReqApplicationEvt evt){
		if (mReqApplication.isState()) {
			throw new UnsupportedOperationException("u had submited.");
		}
		mReqApplication.setState(evt.getModel().isState());
		logger.debug("submit:[{}]" , ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE));
	}

}


text:
package org.apache.james.mailbox.inmemory.mail;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.james.mailbox.MailboxSession;
import org.apache.james.mailbox.exception.MailboxException;
import org.apache.james.mailbox.inmemory.InMemoryId;
import org.apache.james.mailbox.store.mail.ModSeqProvider;
import org.apache.james.mailbox.store.mail.model.Mailbox;

public class InMemoryModSeqProvider implements ModSeqProvider<InMemoryId>{
    private final ConcurrentMap<InMemoryId, AtomicLong> map = new ConcurrentHashMap<InMemoryId, AtomicLong>();

    @Override
    public long nextModSeq(MailboxSession session, Mailbox<InMemoryId> mailbox) throws MailboxException {
        return getHighest(mailbox.getMailboxId()).incrementAndGet();

    }

    @Override
    public long highestModSeq(MailboxSession session, Mailbox<InMemoryId> mailbox) throws MailboxException {
        return getHighest(mailbox.getMailboxId()).get();
    }
    private AtomicLong getHighest(InMemoryId id) {
        AtomicLong uid = map.get(id);
        if (uid == null) {
            uid = new AtomicLong(0);
            AtomicLong u = map.putIfAbsent(id, uid);
            if (u != null) {
                uid = u;
            }
        }
        return uid;
    }
}


text:
canvas-gantt
============

gantt chart


text:
/*********************                                                        */
/*! \file cvc4parser_public.h
 ** \verbatim
 ** Original author: Morgan Deters
 ** Major contributors: none
 ** Minor contributors (to current version): none
 ** This file is part of the CVC4 project.
 ** Copyright (c) 2009-2014  New York University and The University of Iowa
 ** See the file COPYING in the top-level source directory for licensing
 ** information.\endverbatim
 **
 ** \brief Macros that should be defined everywhere during the building of
 ** the libraries and driver binary, and also exported to the user.
 **
 ** Macros that should be defined everywhere during the building of
 ** the libraries and driver binary, and also exported to the user.
 **/

#ifndef __CVC4PARSER_PUBLIC_H
#define __CVC4PARSER_PUBLIC_H

#include <cvc4/cvc4_public.h>

#endif /* __CVC4PARSER_PUBLIC_H */


text:
'use strict';

var fs = require('fs');
var tools = require('./tools.js');

var defaultConfiguration = {
	/* name of configuration */
	name: 'default',
	/* path of root directories to parse */
	rootFolders: [],
	/* Parse only files which match these rules */
	fileFilter: {
		whitelist: [],
		blacklist: []
	},
	/* Format files name to be unique. The result will be used as an id for this file */
	fileNameAdapter: [],
	/* Format files name to be more understandable. The result will be displayed in boxes */
	fileLabelAdapter: [],
	/* Configure type groups */
	types: [],
	/* Describe what should be analysed to be considered as a dependency. */
	requireMatcher: ['ES Module'],
	/* Format require name to match file "id" */
	requireNameAdapter: []
};

var configuration = {
	configuration: [tools.extend({}, defaultConfiguration)],
	/* The id of the configuration to be displayed */
	currentConf: 0,
	/* level of Logs*/
	logLevel: 3,
	/* Settings about security */
	security: {
		passwordFile: false, // to add one it expects a string (the path of the file)
		maxStoreSalt: 10,
		key: '',
		cert: '',
	},

	/* these attributes will be replaced by methods */
	getType: null,
	getFile: null,

	/*private attributes should not be changed */
	_logLevel: -1,
	_parsed: [],
	_password: null
};

/* Assert that configuration is valid */
configuration.checkConfig = function() {
	function isInt(value) {
		return typeof value === 'number' && value >= 0 && value%1 === 0;
	}
	function isArray(value) {
		return value instanceof Array;
	}

	var msg, data;
	var errors = [];

	if (!isInt(configuration.logLevel)) {
		errors.push('logLevel');
	}
	if (!isInt(configuration.currentConf)) {
		errors.push('currentConf');
	}

	if (!isArray(configuration.configuration) || configuration.configuration.length === 0) {
		errors.push('configuration');
	} else {
		configuration.configuration.forEach(function(conf, idx) {
			if (!isArray(conf.rootFolders)) {
				errors.push('configuration['+idx+'].rootFolders');
			}
			if (!isArray(conf.fileFilter.whitelist)) {
				errors.push('configuration['+idx+'].fileFilter.whitelist');
			}
			if (!isArray(conf.fileFilter.blacklist)) {
				errors.push('configuration['+idx+'].fileFilter.blacklist');
			}
			if (!isArray(conf.fileNameAdapter)) {
				errors.push('configuration['+idx+'].fileNameAdapter');
			}
			if (!isArray(conf.fileLabelAdapter)) {
				errors.push('configuration['+idx+'].fileLabelAdapter');
			}
			if (!isArray(conf.types)) {
				errors.push('configuration['+idx+'].types');
			}
			if (!isArray(conf.requireMatcher)) {
				errors.push('configuration['+idx+'].requireMatcher');
			}
			if (!isArray(conf.requireNameAdapter)) {
				errors.push('configuration['+idx+'].requireNameAdapter');
			}
		});
	}

	if (typeof configuration.security !== 'object') {
		errors.push('security');
	} else {

		if (!isInt(configuration.security.maxStoreSalt) || configuration.security.maxStoreSalt === 0) {
			errors.push('security.maxStoreSalt');
		}

		if (typeof configuration.security.passwordFile !== 'string' && configuration.security.passwordFile !== false) {
			errors.push('security.passwordFile');
		} else if (typeof configuration.security.passwordFile === 'string') {
			var data;
			try {
				data = fs.readFileSync(configuration.security.passwordFile, {
					encoding: 'utf8'
				});
			} catch (e) {
				errors.push('security.passwordFile (file cannot be read)');
			}

			if (data) {
				configuration._password = tools.sha256(data);
			} else {
				errors.push('security.passwordFile (password not found)');
			}
		}

		if (typeof configuration.security.key !== 'string') {
			errors.push('security.key');
		} else if (typeof configuration.security.key === 'string' && configuration.security.key) {
			var data;
			try {
				data = fs.readFileSync(configuration.security.key);
			} catch (e) {
				errors.push('security.key (file cannot be read)');
			}

			if (!data) {
				errors.push('security.key (key not found)');
			}
			if (!configuration.security.cert) {
				errors.push('security.cert should be also defined to set HTTPS connection');
			}
		}

		if (typeof configuration.security.cert !== 'string') {
			errors.push('security.cert');
		} else if (typeof configuration.security.cert === 'string' && configuration.security.cert) {
			var data;
			try {
				data = fs.readFileSync(configuration.security.cert);
			} catch (e) {
				errors.push('security.cert (file cannot be read)');
			}

			if (!data) {
				errors.push('security.cert (certificate not found)');
			}
			if (!configuration.security.key) {
				errors.push('security.key should be also defined to set HTTPS connection');
			}
		}
	}

	if (errors.length) {
		msg = 'Configuration file is not valid.\nThese attributes are not correctly configured:\n' + errors.join('\n');

		logger.error(msg);
		logger.debug(JSON.stringify(configuration));
		process.exit(1);
	}

	return errors.length === 0;
};

configuration.readConfig = function(configPath) {
	var fileConfiguration, fileObj, refPath;

	configPath = configPath || './configuration.json';
	if (/\/$/.test(configPath)) {
		configPath += 'configuration.json';
	} else if (configPath.indexOf('/') === -1) {
		configPath = './' + configPath;
	}
	refPath = configPath.replace(/\/[^\/]+$/, '/');
	configuration.refPath = refPath;

	try {
		fileConfiguration = fs.readFileSync(configPath, {
			encoding: 'utf8'
		});
		logger.info('Configuration file "' + configPath + '" loaded');
	} catch(e) {
		logger.log('Cannot load file "' + configPath + '"');
	}

	if (fileConfiguration) {
		try{
			fileObj = JSON.parse(fileConfiguration, function(key, value) {
				if (key === 'rules') {
					var k, v, r;
					for(k in value) {
						v = value[k];
						if (typeof v === 'object' && v.source) {
							r = new RegExp(v.source, v.flags);
							value[k] = r;
						}
					}
				}

				return value;
			});
		} catch(err) {
			console.error('configuration.json is not a valid JSON file');
			console.error('reason:', err.message);
			process.exit(1);
		}

		fileObj.configuration = fileObj.configuration.map(function(conf) {
			var defaultConf = tools.clone(defaultConfiguration);
			return tools.extend(defaultConf, conf);
		});
		logger.debug('configuration:\n' + JSON.stringify(fileObj.configuration[0], '', '  '));

		tools.extend(configuration, fileObj);
		updatePaths();
		this.checkConfig();
		convertObjects();
		applyMethods();
	}
};

configuration.buildPage = function() {
	var str = 'var __webConfiguration = ';
	var conf = configuration.web;

	str += JSON.stringify(conf);
	str += ';'

	return str;
};

function replacePath(str) {
	if (typeof str !== 'string') {
		if (str instanceof Array) {
			return str.map(replacePath);
		} else
		if (str.path) {
			str.path = replacePath(str.path);
		}
		return str;
	}
	return str.replace(/^(?!\/)(?:\.\/)?/, configuration.refPath);
}

function replaceRegexp(obj) {
	if (obj instanceof Array) {
		return obj.map(replaceRegexp);
	}

	obj.r = new RegExp(obj.pattern, obj.flags);
	if (obj.split) {
		obj.split = replaceRegexp(obj.split);
	}

	if (obj.prettyOutput) {
		obj.prettyOutput.matcher = replaceRegexp(obj.prettyOutput.matcher);
	}

	return obj;
}

function replacePattern(str) {
	switch(str.toLowerCase()) {
		case 'es module':
		case 'esmodule':
		case 'module es':
		case 'modulees':
		case 'js module':
		case 'jsmodule':
		case 'module js':
		case 'modulejs':
			return [{
				patternName: 'simple import',
				flags: 'g',
				r: /\b(?:import|export)\s+(?:[^;]*?)from\s+['"]((?:\\.|[^\\])+?)['"]/g,
			}, {
				patternName: 'import for side effect',
				flags: 'g',
				r: /\b(?:import|export)\s+['"]((?:\\.|[^\\])+?)['"]/g,
			}, {
				patternName: 'dynamic import',
				flags: 'g',
				r: /\b(?:import|export)\s*\(\s*['"]((?:\\.|[^\\])+?)['"]/g,
			}];
		case 'commonjs':
		case 'common js':
			return [{
				patternName: 'simple require',
				flags: 'g',
				r: /\brequire\s*\(\s*['"]((?:\\.|[^\\])+?)['"]\s*\)/g,
				relativePath: true,
			}];
		case 'amd':
			return [{
				patternName: 'simple require',
				flags: 'g',
				r: /\brequire\s*\(\s*['"]((?:\\.|[^\\])+?)['"]\s*\)/g,
			}, {
				patternName: 'complexe require',
				flags: 'g',
				r: /\brequire\s*\(\s*\[[\s\S]*?\]/g,
				split: {
					"pattern": 'parse string',
					flags: 'g',
					r: /['"]((?:\\.|[^\\])+?)['"]/g,
				},
			}, {
				patternName: 'define',
				flags: 'g',
				r: /\bdefine\s*\(\s*\[[\s\S]*?\]/g,
				split: {
					patternName: 'parse string',
					flags: 'g',
					r: /['"]((?:\\.|[^\\])+?)['"]/g,
				},
			}];
		case 'html':
			return [{
				patternName: 'Elements with src',
				flags: 'g',
				r: /<\s*(?:script|iframe|frame|embed)\b[^>]+src\s*=\s*["']([^"']+?)["']/g,
			}, {
				patternName: 'Elements with href',
				flags: 'g',
				r: /<\s*(?:link)\b[^>]+href\s*=\s*["']([^"']+?)["']/g,
			}, {
				patternName: 'Elements with data',
				flags: 'g',
				r: /<\s*(?:object)\b[^>]+data\s*=\s*["']([^"']+?)["']/g,
			}, {
				patternName: 'Elements with code',
				flags: 'g',
				r: /<\s*(?:applet)\b[^>]+code\s*=\s*["']([^"']+?)["']/g,
			}];
		case 'html ressources':
			return [{
				patternName: 'Elements with src',
				flags: 'g',
				r: /<\s*(?:audio|img|source|track|video)\b[^>]+src\s*=\s*["']([^"']+?)["']/g,
			}, {
				patternName: 'Elements with href',
				flags: 'g',
				r: /<\s*(?:a)\b[^>]+href\s*=\s*["']([^"']+?)["']/g,
			}];
		case 'c':
			return [{
				patternName: 'c include package',
				flags: 'g',
				r: /#include\s+<([^>]+)>/g,
			}, {
				patternName: 'c include file',
				flags: 'g',
				r: /#include\s+"([^"]+)"/g,
				relativePath: true,
			}];

		default:
			logger.error('configuration (requireMatcher): pattern "' + str + '" is unknown');
			return {
				patternName: 'default pattern',
				r: /$^/, // should match nothing
			};
	}
}

function replaceRgxPattern(obj) {
	if (obj instanceof Array) {
		return obj.reduce(function(list, pattern) {
			var rslt = replaceRgxPattern(pattern);

			if (!Array.isArray(rslt)) {
				list.push(rslt);
			} else {
				list.push.apply(list, rslt);
			}

			return list;
		}, []);
	}

	if (typeof obj === 'string') {
		return replacePattern(obj);
	}
	return replaceRegexp(obj);
}

function updatePaths() {
	configuration.configuration.forEach(function(conf) {
		conf.rootFolders = replacePath(conf.rootFolders);
	});

	configuration.log = configuration.log && replacePath(configuration.log);
	configuration.security.passwordFile = configuration.security.passwordFile && replacePath(configuration.security.passwordFile);
}

/** Replace object string by their object (like regexp)
 */
function convertObjects() {
	configuration.configuration.forEach(function(conf) {
		conf.fileNameAdapter.forEach(function(rpl) {
			rpl.matcher = replaceRegexp(rpl.matcher);
		});
		conf.fileLabelAdapter.forEach(function(rpl) {
			rpl.matcher = replaceRegexp(rpl.matcher);
		});
		conf.requireNameAdapter.forEach(function(rpl) {
			rpl.matcher = replaceRegexp(rpl.matcher);
		});
		conf.types.forEach(function(type) {
			type.matcher = replaceRegexp(type.matcher);
		});
		conf.requireMatcher = replaceRgxPattern(conf.requireMatcher);
		conf.fileFilter.whitelist = replaceRegexp(conf.fileFilter.whitelist);
		conf.fileFilter.blacklist = replaceRegexp(conf.fileFilter.blacklist);
	});

	if (configuration._logLevel < 0) {
		configuration._logLevel = configuration.logLevel;
	}
}

function applyMethods() {
	configuration.getType = getType;
	configuration.getFile = getFile;
}

/**
 * helps to retrieve type from its Name
 * @param  {string} typeName name of the type
 * @param  {number} index=currentConf index of configuration to look for
 * @return {Type}
 */
function getType(typeName, index) {
	index = index || this.currentConf;

	var getType = function(type) {
		return type.name === typeName;
	};

	var type = this.configuration[index].types.find(getType);

	if (!type && typeName !== 'default') {
		typeName = 'default';
		type = this.configuration[index].types.find(getType);
	}

	if (!type) {

	}

	return type;
}

/**
 * helps to retrieve file from its name
 * @param  {string} fileName name of the file
 * @param  {number} index=currentConf index of configuration to look for
 * @return {FileObject}
 */
function getFile(fileName, index) {
	index = index || this.currentConf;
	if (!this._parsed[index]) {
		logger.error('index ' + index + ' not found in _parsed');
		return;
	}

	return this._parsed[index].files.find(function(item) {
		return item.name === fileName;
	});
}

module.exports = configuration;

/* required after module exports to avoid cycle requirement */
var logger = require('./logger.js');


text:
Beginnings of factoring out an ETL pattern for repeatable data migration and sync in future.

TODO:
=====
Enable threads
Make generic management command
Helpers for extracting from/loading to:
    XML
    JSON
Helpers for deleting destination models that weren't in the source data - set timestamp on a given property
Django-admin-style "fields" to indicate simple transforms from source to destination
Include data-cleansing tools
Logging/debugging/analysis
Cron job/supervisor helpers
Tests!


text:
namespace ceres {
namespace internal {
namespace {
// Small constant for various floating point issues.
const double kEpsilon = 1e-12;
}  // namespace

// Compute a scaling vector that is used to improve the conditioning
// of the Jacobian.
void TrustRegionMinimizer::EstimateScale(const SparseMatrix& jacobian,
                                         double* scale) const {
  jacobian.SquaredColumnNorm(scale);
  for (int i = 0; i < jacobian.num_cols(); ++i) {
    scale[i] = 1.0 / (1.0 + sqrt(scale[i]));
  }
}

void TrustRegionMinimizer::Init(const Minimizer::Options& options) {
  options_ = options;
  sort(options_.trust_region_minimizer_iterations_to_dump.begin(),
       options_.trust_region_minimizer_iterations_to_dump.end());
}

void TrustRegionMinimizer::Minimize(const Minimizer::Options& options,
                                    double* parameters,
                                    Solver::Summary* summary) {
  double start_time = WallTimeInSeconds();
  double iteration_start_time =  start_time;
  Init(options);
  const bool is_not_silent = !options.is_silent;

  summary->termination_type = NO_CONVERGENCE;
  summary->num_successful_steps = 0;
  summary->num_unsuccessful_steps = 0;

  Evaluator* evaluator = CHECK_NOTNULL(options_.evaluator);
  SparseMatrix* jacobian = CHECK_NOTNULL(options_.jacobian);
  TrustRegionStrategy* strategy = CHECK_NOTNULL(options_.trust_region_strategy);

  const int num_parameters = evaluator->NumParameters();
  const int num_effective_parameters = evaluator->NumEffectiveParameters();
  const int num_residuals = evaluator->NumResiduals();

  VectorRef x_min(parameters, num_parameters);
  Vector x = x_min;
  double x_norm = x.norm();

  Vector residuals(num_residuals);
  Vector trust_region_step(num_effective_parameters);
  Vector delta(num_effective_parameters);
  Vector x_plus_delta(num_parameters);
  Vector gradient(num_effective_parameters);
  Vector model_residuals(num_residuals);
  Vector scale(num_effective_parameters);

  IterationSummary iteration_summary;
  iteration_summary.iteration = 0;
  iteration_summary.step_is_valid = false;
  iteration_summary.step_is_successful = false;
  iteration_summary.cost_change = 0.0;
  iteration_summary.gradient_max_norm = 0.0;
  iteration_summary.gradient_norm = 0.0;
  iteration_summary.step_norm = 0.0;
  iteration_summary.relative_decrease = 0.0;
  iteration_summary.trust_region_radius = strategy->Radius();
  // TODO(sameeragarwal): Rename eta to linear_solver_accuracy or
  // something similar across the board.
  iteration_summary.eta = options_.eta;
  iteration_summary.linear_solver_iterations = 0;
  iteration_summary.step_solver_time_in_seconds = 0;

  // Do initial cost and Jacobian evaluation.
  double cost = 0.0;
  if (!evaluator->Evaluate(x.data(),
                           &cost,
                           residuals.data(),
                           gradient.data(),
                           jacobian)) {
    LOG_IF(WARNING, is_not_silent)
        << "Terminating: Residual and Jacobian evaluation failed.";
    summary->termination_type = NUMERICAL_FAILURE;
    return;
  }

  int num_consecutive_nonmonotonic_steps = 0;
  double minimum_cost = cost;
  double reference_cost = cost;
  double accumulated_reference_model_cost_change = 0.0;
  double candidate_cost = cost;
  double accumulated_candidate_model_cost_change = 0.0;

  summary->initial_cost = cost + summary->fixed_cost;
  iteration_summary.cost = cost + summary->fixed_cost;
  iteration_summary.gradient_max_norm = gradient.lpNorm<Eigen::Infinity>();
  iteration_summary.gradient_norm = gradient.norm();

  // The initial gradient max_norm is bounded from below so that we do
  // not divide by zero.
  const double initial_gradient_max_norm =
      max(iteration_summary.gradient_max_norm, kEpsilon);
  const double absolute_gradient_tolerance =
      options_.gradient_tolerance * initial_gradient_max_norm;

  if (iteration_summary.gradient_max_norm <= absolute_gradient_tolerance) {
    VLOG_IF(1, is_not_silent) << "Terminating: Gradient tolerance reached."
                              << "Relative gradient max norm: "
                              << (iteration_summary.gradient_max_norm /
                                  initial_gradient_max_norm)
                              << " <= " << options_.gradient_tolerance;
    summary->termination_type = GRADIENT_TOLERANCE;
    return;
  }

  iteration_summary.iteration_time_in_seconds =
      WallTimeInSeconds() - iteration_start_time;
  iteration_summary.cumulative_time_in_seconds =
      WallTimeInSeconds() - start_time
      + summary->preprocessor_time_in_seconds;
  summary->iterations.push_back(iteration_summary);

  if (options_.jacobi_scaling) {
    EstimateScale(*jacobian, scale.data());
    jacobian->ScaleColumns(scale.data());
  } else {
    scale.setOnes();
  }

  int num_consecutive_invalid_steps = 0;
  bool inner_iterations_are_enabled = options.inner_iteration_minimizer != NULL;
  while (true) {
    bool inner_iterations_were_useful = false;
    if (!RunCallbacks(options.callbacks, iteration_summary, summary)) {
      return;
    }

    iteration_start_time = WallTimeInSeconds();
    if (iteration_summary.iteration >= options_.max_num_iterations) {
      VLOG_IF(1, is_not_silent)
          << "Terminating: Maximum number of iterations reached.";
      summary->termination_type = NO_CONVERGENCE;
      return;
    }

    const double total_solver_time = iteration_start_time - start_time +
        summary->preprocessor_time_in_seconds;
    if (total_solver_time >= options_.max_solver_time_in_seconds) {
      VLOG_IF(1, is_not_silent)
          << "Terminating: Maximum solver time reached.";
      summary->termination_type = NO_CONVERGENCE;
      return;
    }

    const double strategy_start_time = WallTimeInSeconds();
    TrustRegionStrategy::PerSolveOptions per_solve_options;
    per_solve_options.eta = options_.eta;
    if (find(options_.trust_region_minimizer_iterations_to_dump.begin(),
             options_.trust_region_minimizer_iterations_to_dump.end(),
             iteration_summary.iteration) !=
        options_.trust_region_minimizer_iterations_to_dump.end()) {
      per_solve_options.dump_format_type =
          options_.trust_region_problem_dump_format_type;
      per_solve_options.dump_filename_base =
          JoinPath(options_.trust_region_problem_dump_directory,
                   StringPrintf("ceres_solver_iteration_%03d",
                                iteration_summary.iteration));
    } else {
      per_solve_options.dump_format_type = TEXTFILE;
      per_solve_options.dump_filename_base.clear();
    }

    TrustRegionStrategy::Summary strategy_summary =
        strategy->ComputeStep(per_solve_options,
                              jacobian,
                              residuals.data(),
                              trust_region_step.data());

    iteration_summary = IterationSummary();
    iteration_summary.iteration = summary->iterations.back().iteration + 1;
    iteration_summary.step_solver_time_in_seconds =
        WallTimeInSeconds() - strategy_start_time;
    iteration_summary.linear_solver_iterations =
        strategy_summary.num_iterations;
    iteration_summary.step_is_valid = false;
    iteration_summary.step_is_successful = false;

    double model_cost_change = 0.0;
    if (strategy_summary.termination_type != FAILURE) {
      // new_model_cost
      //  = 1/2 [f + J * step]^2
      //  = 1/2 [ f'f + 2f'J * step + step' * J' * J * step ]
      // model_cost_change
      //  = cost - new_model_cost
      //  = f'f/2  - 1/2 [ f'f + 2f'J * step + step' * J' * J * step]
      //  = -f'J * step - step' * J' * J * step / 2
      model_residuals.setZero();
      jacobian->RightMultiply(trust_region_step.data(), model_residuals.data());
      model_cost_change =
          - model_residuals.dot(residuals + model_residuals / 2.0);

      if (model_cost_change < 0.0) {
        VLOG_IF(1, is_not_silent)
            << "Invalid step: current_cost: " << cost
            << " absolute difference " << model_cost_change
            << " relative difference " << (model_cost_change / cost);
      } else {
        iteration_summary.step_is_valid = true;
      }
    }

    if (!iteration_summary.step_is_valid) {
      // Invalid steps can happen due to a number of reasons, and we
      // allow a limited number of successive failures, and return with
      // NUMERICAL_FAILURE if this limit is exceeded.
      if (++num_consecutive_invalid_steps >=
          options_.max_num_consecutive_invalid_steps) {
        summary->error = StringPrintf(
            "Terminating. Number of successive invalid steps more "
            "than Solver::Options::max_num_consecutive_invalid_steps: %d",
            options_.max_num_consecutive_invalid_steps);
        LOG_IF(WARNING, is_not_silent) << summary->error;
        summary->termination_type = NUMERICAL_FAILURE;
        return;
      }

      // We are going to try and reduce the trust region radius and
      // solve again. To do this, we are going to treat this iteration
      // as an unsuccessful iteration. Since the various callbacks are
      // still executed, we are going to fill the iteration summary
      // with data that assumes a step of length zero and no progress.
      iteration_summary.cost = cost + summary->fixed_cost;
      iteration_summary.cost_change = 0.0;
      iteration_summary.gradient_max_norm =
          summary->iterations.back().gradient_max_norm;
      iteration_summary.gradient_norm =
          summary->iterations.back().gradient_norm;
      iteration_summary.step_norm = 0.0;
      iteration_summary.relative_decrease = 0.0;
      iteration_summary.eta = options_.eta;
    } else {
      // The step is numerically valid, so now we can judge its quality.
      num_consecutive_invalid_steps = 0;

      // Undo the Jacobian column scaling.
      delta = (trust_region_step.array() * scale.array()).matrix();

      double new_cost = numeric_limits<double>::max();
      if (!evaluator->Plus(x.data(), delta.data(), x_plus_delta.data())) {
        LOG(WARNING) << "x_plus_delta = Plus(x, delta) failed. "
                     << "Treating it as a step with infinite cost";
      } else if (!evaluator->Evaluate(x_plus_delta.data(),
                                      &new_cost,
                                      NULL,
                                      NULL,
                                      NULL)) {
        LOG(WARNING) << "Step failed to evaluate. "
                     << "Treating it as a step with infinite cost";
        new_cost = numeric_limits<double>::max();
      } else {
        // Check if performing an inner iteration will make it better.
        if (inner_iterations_are_enabled) {
          ++summary->num_inner_iteration_steps;
          double inner_iteration_start_time = WallTimeInSeconds();
          const double x_plus_delta_cost = new_cost;
          Vector inner_iteration_x = x_plus_delta;
          Solver::Summary inner_iteration_summary;
          options.inner_iteration_minimizer->Minimize(options,
                                                      inner_iteration_x.data(),
                                                      &inner_iteration_summary);
          if (!evaluator->Evaluate(inner_iteration_x.data(),
                                   &new_cost,
                                   NULL, NULL, NULL)) {
            VLOG_IF(2, is_not_silent) << "Inner iteration failed.";
            new_cost = x_plus_delta_cost;
          } else {
            x_plus_delta = inner_iteration_x;
            // Boost the model_cost_change, since the inner iteration
            // improvements are not accounted for by the trust region.
            model_cost_change +=  x_plus_delta_cost - new_cost;
            VLOG_IF(2, is_not_silent)
                << "Inner iteration succeeded; Current cost: " << cost
                << " Trust region step cost: " << x_plus_delta_cost
                << " Inner iteration cost: " << new_cost;

            inner_iterations_were_useful = new_cost < cost;

            const double inner_iteration_relative_progress =
                1.0 - new_cost / x_plus_delta_cost;
            // Disable inner iterations once the relative improvement
            // drops below tolerance.
            inner_iterations_are_enabled =
                (inner_iteration_relative_progress >
                 options.inner_iteration_tolerance);
            VLOG_IF(2, is_not_silent && !inner_iterations_are_enabled)
                << "Disabling inner iterations. Progress : "
                << inner_iteration_relative_progress;
          }
          summary->inner_iteration_time_in_seconds +=
              WallTimeInSeconds() - inner_iteration_start_time;
        }
      }

      iteration_summary.step_norm = (x - x_plus_delta).norm();

      // Convergence based on parameter_tolerance.
      const double step_size_tolerance =  options_.parameter_tolerance *
          (x_norm + options_.parameter_tolerance);
      if (iteration_summary.step_norm <= step_size_tolerance) {
        VLOG_IF(1, is_not_silent)
            << "Terminating. Parameter tolerance reached. "
            << "relative step_norm: "
            << (iteration_summary.step_norm /
                (x_norm + options_.parameter_tolerance))
            << " <= " << options_.parameter_tolerance;
        summary->termination_type = PARAMETER_TOLERANCE;
        return;
      }

      iteration_summary.cost_change =  cost - new_cost;
      const double absolute_function_tolerance =
          options_.function_tolerance * cost;
      if (fabs(iteration_summary.cost_change) < absolute_function_tolerance) {
        VLOG_IF(1, is_not_silent) << "Terminating. Function tolerance reached. "
                                  << "|cost_change|/cost: "
                                  << fabs(iteration_summary.cost_change) / cost
                                  << " <= " << options_.function_tolerance;
        summary->termination_type = FUNCTION_TOLERANCE;
        return;
      }

      const double relative_decrease =
          iteration_summary.cost_change / model_cost_change;

      const double historical_relative_decrease =
          (reference_cost - new_cost) /
          (accumulated_reference_model_cost_change + model_cost_change);

      // If monotonic steps are being used, then the relative_decrease
      // is the usual ratio of the change in objective function value
      // divided by the change in model cost.
      //
      // If non-monotonic steps are allowed, then we take the maximum
      // of the relative_decrease and the
      // historical_relative_decrease, which measures the increase
      // from a reference iteration. The model cost change is
      // estimated by accumulating the model cost changes since the
      // reference iteration. The historical relative_decrease offers
      // a boost to a step which is not too bad compared to the
      // reference iteration, allowing for non-monotonic steps.
      iteration_summary.relative_decrease =
          options.use_nonmonotonic_steps
          ? max(relative_decrease, historical_relative_decrease)
          : relative_decrease;

      // Normally, the quality of a trust region step is measured by
      // the ratio
      //
      //              cost_change
      //    r =    -----------------
      //           model_cost_change
      //
      // All the change in the nonlinear objective is due to the trust
      // region step so this ratio is a good measure of the quality of
      // the trust region radius. However, when inner iterations are
      // being used, cost_change includes the contribution of the
      // inner iterations and its not fair to credit it all to the
      // trust region algorithm. So we change the ratio to be
      //
      //                              cost_change
      //    r =    ------------------------------------------------
      //           (model_cost_change + inner_iteration_cost_change)
      //
      // In most cases this is fine, but it can be the case that the
      // change in solution quality due to inner iterations is so large
      // and the trust region step is so bad, that this ratio can become
      // quite small.
      //
      // This can cause the trust region loop to reject this step. To
      // get around this, we expicitly check if the inner iterations
      // led to a net decrease in the objective function value. If
      // they did, we accept the step even if the trust region ratio
      // is small.
      //
      // Notice that we do not just check that cost_change is positive
      // which is a weaker condition and would render the
      // min_relative_decrease threshold useless. Instead, we keep
      // track of inner_iterations_were_useful, which is true only
      // when inner iterations lead to a net decrease in the cost.
      iteration_summary.step_is_successful =
          (inner_iterations_were_useful ||
           iteration_summary.relative_decrease >
           options_.min_relative_decrease);

      if (iteration_summary.step_is_successful) {
        accumulated_candidate_model_cost_change += model_cost_change;
        accumulated_reference_model_cost_change += model_cost_change;

        if (!inner_iterations_were_useful &&
            relative_decrease <= options_.min_relative_decrease) {
          iteration_summary.step_is_nonmonotonic = true;
          VLOG_IF(2, is_not_silent)
              << "Non-monotonic step! "
              << " relative_decrease: "
              << relative_decrease
              << " historical_relative_decrease: "
              << historical_relative_decrease;
        }
      }
    }

    if (iteration_summary.step_is_successful) {
      ++summary->num_successful_steps;
      strategy->StepAccepted(iteration_summary.relative_decrease);
      x = x_plus_delta;
      x_norm = x.norm();

      // Step looks good, evaluate the residuals and Jacobian at this
      // point.
      if (!evaluator->Evaluate(x.data(),
                               &cost,
                               residuals.data(),
                               gradient.data(),
                               jacobian)) {
        summary->error =
            "Terminating: Residual and Jacobian evaluation failed.";
        LOG_IF(WARNING, is_not_silent) << summary->error;
        summary->termination_type = NUMERICAL_FAILURE;
        return;
      }

      iteration_summary.gradient_max_norm = gradient.lpNorm<Eigen::Infinity>();
      iteration_summary.gradient_norm = gradient.norm();

      if (iteration_summary.gradient_max_norm <= absolute_gradient_tolerance) {
        VLOG_IF(1, is_not_silent) << "Terminating: Gradient tolerance reached."
                                  << "Relative gradient max norm: "
                                  << (iteration_summary.gradient_max_norm /
                                      initial_gradient_max_norm)
                                  << " <= " << options_.gradient_tolerance;
        summary->termination_type = GRADIENT_TOLERANCE;
        return;
      }

      if (options_.jacobi_scaling) {
        jacobian->ScaleColumns(scale.data());
      }

      // Update the best, reference and candidate iterates.
      //
      // Based on algorithm 10.1.2 (page 357) of "Trust Region
      // Methods" by Conn Gould & Toint, or equations 33-40 of
      // "Non-monotone trust-region algorithms for nonlinear
      // optimization subject to convex constraints" by Phil Toint,
      // Mathematical Programming, 77, 1997.
      if (cost < minimum_cost) {
        // A step that improves solution quality was found.
        x_min = x;
        minimum_cost = cost;
        // Set the candidate iterate to the current point.
        candidate_cost = cost;
        num_consecutive_nonmonotonic_steps = 0;
        accumulated_candidate_model_cost_change = 0.0;
      } else {
        ++num_consecutive_nonmonotonic_steps;
        if (cost > candidate_cost) {
          // The current iterate is has a higher cost than the
          // candidate iterate. Set the candidate to this point.
          VLOG_IF(2, is_not_silent)
              << "Updating the candidate iterate to the current point.";
          candidate_cost = cost;
          accumulated_candidate_model_cost_change = 0.0;
        }

        // At this point we have made too many non-monotonic steps and
        // we are going to reset the value of the reference iterate so
        // as to force the algorithm to descend.
        //
        // This is the case because the candidate iterate has a value
        // greater than minimum_cost but smaller than the reference
        // iterate.
        if (num_consecutive_nonmonotonic_steps ==
            options.max_consecutive_nonmonotonic_steps) {
          VLOG_IF(2, is_not_silent)
              << "Resetting the reference point to the candidate point";
          reference_cost = candidate_cost;
          accumulated_reference_model_cost_change =
              accumulated_candidate_model_cost_change;
        }
      }
    } else {
      ++summary->num_unsuccessful_steps;
      if (iteration_summary.step_is_valid) {
        strategy->StepRejected(iteration_summary.relative_decrease);
      } else {
        strategy->StepIsInvalid();
      }
    }

    iteration_summary.cost = cost + summary->fixed_cost;
    iteration_summary.trust_region_radius = strategy->Radius();
    if (iteration_summary.trust_region_radius <
        options_.min_trust_region_radius) {
      VLOG_IF(1, is_not_silent)
          << "Termination. Minimum trust region radius reached.";
      summary->termination_type = PARAMETER_TOLERANCE;
      return;
    }

    iteration_summary.iteration_time_in_seconds =
        WallTimeInSeconds() - iteration_start_time;
    iteration_summary.cumulative_time_in_seconds =
        WallTimeInSeconds() - start_time
        + summary->preprocessor_time_in_seconds;
    summary->iterations.push_back(iteration_summary);
  }
}

}  // namespace internal
}  // namespace ceres


text:
FN="genomationData_1.20.0.tar.gz"
URLS=(
  "https://bioconductor.org/packages/3.11/data/experiment/src/contrib/genomationData_1.20.0.tar.gz"
  "https://bioarchive.galaxyproject.org/genomationData_1.20.0.tar.gz"
  "https://depot.galaxyproject.org/software/bioconductor-genomationdata/bioconductor-genomationdata_1.20.0_src_all.tar.gz"
)
MD5="44316dfb314a36a4d062b1e2e944ba94"

# Use a staging area in the conda dir rather than temp dirs, both to avoid
# permission issues as well as to have things downloaded in a predictable
# manner.
STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM
mkdir -p $STAGING
TARBALL=$STAGING/$FN

SUCCESS=0
for URL in ${URLS[@]}; do
  curl $URL > $TARBALL
  [[ $? == 0 ]] || continue

  # Platform-specific md5sum checks.
  if [[ $(uname -s) == "Linux" ]]; then
    if md5sum -c <<<"$MD5  $TARBALL"; then
      SUCCESS=1
      break
    fi
  else if [[ $(uname -s) == "Darwin" ]]; then
    if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then
      SUCCESS=1
      break
    fi
  fi
fi
done

if [[ $SUCCESS != 1 ]]; then
  echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:"
  printf '%s\n' "${URLS[@]}"
  exit 1
fi

# Install and clean up
R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL
rm $TARBALL
rmdir $STAGING