text:
Commandline
===========
Usage
-----
.. code-block:: bash

    tree-cli [OPTIONS]

**Options:**

-l, --length     The start length of tree.
-b, --branches   Add a branch with a scale and a angle.
-s, --sigma      Add randomness to scale and angle.
-a, --age        Indicates how many time the tree should be iterated.
-p, --path       The path for saving the tree.
-c1, --color1    The starting color given as r g b.
-c2, --color2    The end color given as r g b.
-t, --thickness  The start width of the first branch.
--help           Show this message and exit.
--show           Shows a image of the tree.

Examples
--------


text:
<?php

/*
 * For instructions on how to run the full sample:
 *
 * @see https://github.com/GoogleCloudPlatform/php-docs-samples/tree/master/secretmanager/README.md
 */

declare(strict_types=1);

namespace Google\Cloud\Samples\SecretManager;

// [START secretmanager_iam_grant_access]
// Import the Secret Manager client library.
use Google\Cloud\SecretManager\V1\SecretManagerServiceClient;

// Import the Secret Manager IAM library.
use Google\Cloud\Iam\V1\Binding;

/**
 * @param string $projectId Your Google Cloud Project ID (e.g. 'my-project')
 * @param string $secretId  Your secret ID (e.g. 'my-secret')
 * @param string $member Your member (e.g. 'user:foo@example.com')
 */
function iam_grant_access(string $projectId, string $secretId, string $member): void
{
    // Create the Secret Manager client.
    $client = new SecretManagerServiceClient();

    // Build the resource name of the secret.
    $name = $client->secretName($projectId, $secretId);

    // Get the current IAM policy.
    $policy = $client->getIamPolicy($name);

    // Update the bindings to include the new member.
    $bindings = $policy->getBindings();
    $bindings[] = new Binding([
        'members' => [$member],
        'role' => 'roles/secretmanager.secretAccessor',
    ]);
    $policy->setBindings($bindings);

    // Save the updated policy to the server.
    $client->setIamPolicy($name, $policy);

    // Print out a success message.
    printf('Updated IAM policy for %s', $secretId);
}
// [END secretmanager_iam_grant_access]

// The following 2 lines are only needed to execute the samples on the CLI
require_once __DIR__ . '/../../testing/sample_helpers.php';
\Google\Cloud\Samples\execute_sample(__FILE__, __NAMESPACE__, $argv);

redpajama_set_name: RedPajamaGithub


text:
#ifndef __CONFIG_H
#define __CONFIG_H

/* number of getties/logins */
#define NGETTY 101 /* should be less or equal to ten */
#define DEBUG /* comment out for non debug builds */
/* constants you might want to change, like the shell and/or getty */
const char shell[]	= "/bin/sh";
const char rc[]		= "/etc/rc";
const char getty[]	= "/sbin/agetty";

#endif /* #ifndef __CONFIG_H */


text:
/// <reference path="models.js" />

var AppViewModel = function () {
	var self = this;

	self.developers = ko.observableArray([]);
	self.bugs = ko.observableArray([]);

	self.isModifyDeveloper = false;
	self.currentDeveloper = ko.observable(new Developer());

	self.saveDeveloper = function () {
		// add developer
		if(!self.isModifyDeveloper) self.developers.unshift(self.currentDeveloper());
		// reset developer
		self.currentDeveloper(new Developer());
		self.isModifyDeveloper = false;
	}

	self.modifyDeveloper = function(developer) {
		// developer will automatically be the one the user clicked on
		self.currentDeveloper(developer);
		self.isModifyDeveloper = true;
	}

	self.currentBug = ko.observable(new Bug());
	self.saveBug = function () {
		self.bugs.unshift(self.currentBug());
		self.currentBug(new Bug());
	}

	ko.components.register('developers-display', {
		template: '
 \

 \

',
		viewModel: function (params) {
			this.developers = params.developers;
		}
	});
}

// Bind up the view model
ko.applyBindings(new AppViewModel());


text:
<?php

namespace Sonata\MediaBundle\Tests\DependencyInjection;

use Sonata\MediaBundle\DependencyInjection\Configuration;
use Symfony\Component\Config\Definition\Processor;

class ConfigurationTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var array
     */
    protected $config;

    protected function setUp()
    {
        $configs = array(
            'sonata_media' => array(
                'db_driver' => 'doctrine_orm',
                'default_context' => 'default',
            ),
        );
        $processor = new Processor();
        $configuration = new Configuration();
        $this->config = $processor->processConfiguration($configuration, $configs);
    }

    public function testProcess()
    {
        $this->assertArrayHasKey('resizers', $this->config);
        $this->assertArrayHasKey('default', $this->config['resizers']);
        $this->assertEquals('sonata.media.resizer.simple', $this->config['resizers']['default']);

        $this->assertArrayHasKey('adapters', $this->config);
        $this->assertArrayHasKey('default', $this->config['adapters']);
        $this->assertEquals('sonata.media.adapter.image.gd', $this->config['adapters']['default']);
    }
}


text:
Template['components_campaignLookup'].rendered = function() {
  var template = this;
};

Template['components_campaignLookup'].helpers({});

Template['components_campaignLookup'].events({
  /**
  Deploy the price feed, used for setup of contract.

  @event (click #weifundDeploy)
  **/

  'click #campaignLookup': function(event, template) {
    var campaignID = Helpers.cleanAscii($("#campaignID").val());

    // Import relevant campaign
    objects.helpers.importCampaign(campaignID, function(err, campaign) {
      if (err)
        return TemplateVar.set(template, 'state', {
          isError: true,
          error: err
        });

      if (campaign.isValid)
        Campaigns.upsert({
          id: campaign.id
        }, campaign);

      TemplateVar.set(template, 'state', {
        isCampaign: true,
        campaign: campaign
      });
    });
  }
});


text:
//---------------------------------------------------------------------
// <copyright file="ForceRawMessageFormatBinding.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

namespace Microsoft.Test.Taupo.OData.WCFService
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.ServiceModel.Configuration;

    /// <summary>
    /// Custom WCF binding classes used to force raw content format. This allows us to use the same endpoint for both
    /// XML & JSON since we have our own deserializers.
    /// </summary>
    /// <remarks>See http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-receiving-arbitrary-data.aspx for more information.</remarks>
    public class ForceRawMessageFormatBinding : CustomBinding
    {
        public ForceRawMessageFormatBinding() : base(new WebHttpBinding())
        {
            var encodingBindingElement = this.Elements.Find<WebMessageEncodingBindingElement>();
            encodingBindingElement.ContentTypeMapper = new ForceRawMessageFormatMapper();
        }
    }

    public class ForceRawMessageFormatBindingElement : StandardBindingElement
    {
        protected override Type BindingElementType
        {
            get { return typeof(ForceRawMessageFormatBinding); }
        }

        protected override void OnApplyConfiguration(Binding binding)
        {
        }
    }

    public class ForceRawMessageFormatBindingCollectionElement : StandardBindingCollectionElement<ForceRawMessageFormatBinding, ForceRawMessageFormatBindingElement>
    {
    }

    public class ForceRawMessageFormatMapper : WebContentTypeMapper
    {
        public override WebContentFormat GetMessageFormatForContentType(string contentType)
        {
            return WebContentFormat.Raw;
        }
    }
}


text:
package com.backend.controllers.yearly;

import java.util.ArrayList;

import com.backend.models.IPlayoff;
import com.backend.models.PlayoffGroup;
import com.backend.models.PlayoffRound;
import com.backend.models.School;
import com.backend.models.SchoolInteger;
import com.backend.models.Tournament;
import com.backend.models.enums.GameTypeEnum;

public class Playoff27Teams implements IPlayoff
{
	private void RemoveOtherThan3rd(ArrayList<SchoolInteger> bestThird, ArrayList<School> group)
	{
		for(int i = 0; i < group.size(); i++)
		{
			if( i != (3-1) )
			{
				bestThird.remove(group.get(i));
			}
		}
	}

	public ArrayList<PlayoffGroup> GenerateNextRound(Tournament tournament, PlayoffRound previousRound, int groupNo, GameTypeEnum gameType, ArrayList<School> preliminaryRanking, ArrayList<School> excludedSchools)
	{
		ArrayList<PlayoffGroup> playoffGroups = new ArrayList<PlayoffGroup>();

		switch (gameType)
		{
		// REPECHAGE
		// A 11 12 19 20 27
		// B 10 13 18 21 26
		// C 9  14 17 22 25
		// D 8  15 16 23 24
		case PLAYOFF_REPECHAGE:
		{
			ArrayList<School> schoolsPoolA = new ArrayList<School>();
			schoolsPoolA.add(preliminaryRanking.get(11 - 1));
			schoolsPoolA.add(preliminaryRanking.get(12 - 1));
			schoolsPoolA.add(preliminaryRanking.get(19 - 1));
			schoolsPoolA.add(preliminaryRanking.get(20 - 1));
			schoolsPoolA.add(preliminaryRanking.get(27 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolA, groupNo++));

			ArrayList<School> schoolsPoolB = new ArrayList<School>();
			schoolsPoolB.add(preliminaryRanking.get(10 - 1));
			schoolsPoolB.add(preliminaryRanking.get(13 - 1));
			schoolsPoolB.add(preliminaryRanking.get(18 - 1));
			schoolsPoolB.add(preliminaryRanking.get(21 - 1));
			schoolsPoolB.add(preliminaryRanking.get(26 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolB, groupNo++));

			ArrayList<School> schoolsPoolC = new ArrayList<School>();
			schoolsPoolC.add(preliminaryRanking.get(9 - 1));
			schoolsPoolC.add(preliminaryRanking.get(14 - 1));
			schoolsPoolC.add(preliminaryRanking.get(17 - 1));
			schoolsPoolC.add(preliminaryRanking.get(22 - 1));
			schoolsPoolC.add(preliminaryRanking.get(25 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolC, groupNo++));

			ArrayList<School> schoolsPoolD = new ArrayList<School>();
			schoolsPoolD.add(preliminaryRanking.get(8 - 1));
			schoolsPoolD.add(preliminaryRanking.get(15 - 1));
			schoolsPoolD.add(preliminaryRanking.get(16 - 1));
			schoolsPoolD.add(preliminaryRanking.get(23 - 1));
			schoolsPoolD.add(preliminaryRanking.get(24 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolD, groupNo++));
			break;
		}

		// QUART
		// E 4 A1 B2 C1 D2
		// F 5 6  B1 C2 MT1
		// G 3 7  A2 D1 MT2
		case PLAYOFF_QUARTER:
		{
			ArrayList<SchoolInteger> repechageResults = tournament.getRoundRanking(GameTypeEnum.PLAYOFF_REPECHAGE);
			ArrayList<School> schoolsPoolA = previousRound.playoffGroups.get(0).getSchoolsRanked(repechageResults, excludedSchools);
			ArrayList<School> schoolsPoolB = previousRound.playoffGroups.get(1).getSchoolsRanked(repechageResults, excludedSchools);
			ArrayList<School> schoolsPoolC = previousRound.playoffGroups.get(2).getSchoolsRanked(repechageResults, excludedSchools);
			ArrayList<School> schoolsPoolD = previousRound.playoffGroups.get(3).getSchoolsRanked(repechageResults, excludedSchools);

			// Remove best 2 of each pool. The next schools are the best third.
			ArrayList<SchoolInteger> bestThird = new ArrayList<SchoolInteger>(repechageResults);
			RemoveOtherThan3rd(bestThird, schoolsPoolA);
			RemoveOtherThan3rd(bestThird, schoolsPoolB);
			RemoveOtherThan3rd(bestThird, schoolsPoolC);
			RemoveOtherThan3rd(bestThird, schoolsPoolD);

			ArrayList<School> schoolsPoolE = new ArrayList<School>();
			schoolsPoolE.add(preliminaryRanking.get(4 - 1));
			schoolsPoolE.add(schoolsPoolA.get(1 - 1));
			schoolsPoolE.add(schoolsPoolB.get(2 - 1));
			schoolsPoolE.add(schoolsPoolC.get(1 - 1));
			schoolsPoolE.add(schoolsPoolD.get(2 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolE, groupNo++));

			ArrayList<School> schoolsPoolF = new ArrayList<School>();
			schoolsPoolF.add(preliminaryRanking.get(5 - 1));
			schoolsPoolF.add(preliminaryRanking.get(6 - 1));
			schoolsPoolF.add(schoolsPoolB.get(1 - 1));
			schoolsPoolF.add(schoolsPoolC.get(2 - 1));
			schoolsPoolF.add(bestThird.get(1 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolF, groupNo++));

			// G 3 7  A2 D1 MT2
			ArrayList<School> schoolsPoolG = new ArrayList<School>();
			schoolsPoolG.add(preliminaryRanking.get(3 - 1));
			schoolsPoolG.add(preliminaryRanking.get(7 - 1));
			schoolsPoolG.add(schoolsPoolA.get(2 - 1));
			schoolsPoolG.add(schoolsPoolD.get(1 - 1));
			schoolsPoolG.add(bestThird.get(2 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolG, groupNo++));
			}
			break;

		// SEMI
		// H 2 E1 F2 G1
		// I 1 E2 F1 G2
		case PLAYOFF_DEMI:
		{
			ArrayList<SchoolInteger> quarterResults = tournament.getRoundRanking(GameTypeEnum.PLAYOFF_QUARTER);
			ArrayList<School> schoolsPoolE = previousRound.playoffGroups.get(0).getSchoolsRanked(quarterResults, excludedSchools);
			ArrayList<School> schoolsPoolF = previousRound.playoffGroups.get(1).getSchoolsRanked(quarterResults, excludedSchools);
			ArrayList<School> schoolsPoolG = previousRound.playoffGroups.get(2).getSchoolsRanked(quarterResults, excludedSchools);

			ArrayList<School> schoolsPoolH = new ArrayList<School>();
			schoolsPoolH.add(preliminaryRanking.get(2 - 1));
			schoolsPoolH.add(schoolsPoolE.get(1 - 1));
			schoolsPoolH.add(schoolsPoolF.get(2 - 1));
			schoolsPoolH.add(schoolsPoolG.get(1 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolH, groupNo++));

			ArrayList<School> schoolsPoolI = new ArrayList<School>();
			schoolsPoolI.add(preliminaryRanking.get(1 - 1));
			schoolsPoolI.add(schoolsPoolE.get(2 - 1));
			schoolsPoolI.add(schoolsPoolF.get(1 - 1));
			schoolsPoolI.add(schoolsPoolG.get(2 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolI, groupNo++));

			break;
		}

		// FINAL
		// J H1 H2 I1 I2
		case PLAYOFF_FINAL:
		{
			ArrayList<SchoolInteger> demiResults = tournament.getRoundRanking(GameTypeEnum.PLAYOFF_DEMI);
			ArrayList<School> schoolsPoolH = previousRound.playoffGroups.get(0).getSchoolsRanked(demiResults, excludedSchools);
			ArrayList<School> schoolsPoolI = previousRound.playoffGroups.get(1).getSchoolsRanked(demiResults, excludedSchools);

			ArrayList<School> schoolsPoolJ = new ArrayList<School>();
			schoolsPoolJ.add(schoolsPoolH.get(1 - 1));
			schoolsPoolJ.add(schoolsPoolH.get(2 - 1));
			schoolsPoolJ.add(schoolsPoolI.get(1 - 1));
			schoolsPoolJ.add(schoolsPoolI.get(2 - 1));
			playoffGroups.add(new PlayoffGroup(schoolsPoolJ, groupNo++));
		}
		break;

		default:
			break;
		}

		return playoffGroups;
	}
}


text:
from __future__ import print_function
import time
import threading
import jenkinsapi
import config as cfg
import signal
import automationhat
import copy
from jenkinsapi.jenkins import Jenkins
from requests.exceptions import ConnectionError

# ---------------------------------------------------- #
# --         General output information             -- #
# ---------------------------------------------------- #
# -- RED = output.one                               -- #
# -- YELLOW = output.two                            -- #
# -- GREEN = output.three                           -- #
# -- BUZZER = relay.one = unused at this moment     -- #
# ---------------------------------------------------- #

# Global variables
building = False
error = False
keepAlive = True

# ---------------------------------------------------- #
# --         All globally used functions            -- #
# ---------------------------------------------------- #

# Function to toggle everything off
def all_tower_off():
    automationhat.output.one.off()
    automationhat.output.two.off()
    automationhat.output.three.off()
    automationhat.relay.one.off()
    return

# For the automation HAT, turn of the LED's.
def all_hat_off():
    if automationhat.is_automation_hat():
        automationhat.light.power.off()
        automationhat.light.comms.off()
        automationhat.light.warn.off()
    return

# Toggle function with parameter output and duration
def toggle(output_type, index, duration):
    # Create the function based on the parameters
    result = getattr(automationhat, output_type)
    full_function = getattr(result, index)

    full_function.on()
    time.sleep(duration)
    full_function.off()
    return

# Set according to status
def set_status(status):
    if status != "":
        all_tower_off()
        if status == "SUCCESS":
            automationhat.output.three.on()

        if status == "UNSTABLE":
            automationhat.output.two.on()

        if status == "FAILURE":
            automationhat.output.one.on()
    return

def set_error(value):
    global error
    if value is True or value is False:
        error = value
        if value is True:
            if automationhat.is_automation_hat():
                automationhat.light.warn.on()
        else:
            if automationhat.is_automation_hat():
                automationhat.light.warn.off()
    else:
        error = True
        if automationhat.is_automation_hat():
            automationhat.light.warn.on()
        print("[ERROR] Only supply True or False to the setError function")

# Get all the jobs by a given name.
def get_jenkins_job_by_name(name):
    # Support sub-folders.
    if '/' in name:
        folder, name = name.rsplit('/', 1)
        server = copy.deepcopy(J)
        folder_path = '/'.join([f'job/{x}' for x in folder.split('/')])
        server.baseurl = server.baseurl + '/' + folder_path
        return server.get_job(name)
    else:
        return J.get_job(name)

def check_jobs_build_status():
    if automationhat.is_automation_hat():
        automationhat.light.comms.on()
    jobs = cfg.jobs
    success = 0
    unstable = 0
    failed = 0

    for item in jobs:
        try:
            job = get_jenkins_job_by_name(item)
        except jenkinsapi.custom_exceptions.UnknownJob:
            set_error(True)
        else:
            getstatus = job.get_last_build().get_status()
            if getstatus == "SUCCESS":
                success += 1
                continue
            if getstatus == "UNSTABLE":
                unstable += 1
                continue
            if getstatus == "FAILURE":
                failed += 1
                continue

    if success > 0 and unstable == 0 and failed == 0:
        set_status('SUCCESS')
    if unstable > 0 and failed == 0:
        set_status('UNSTABLE')
    if failed > 0:
        set_status('FAILURE')
    if automationhat.is_automation_hat():
        automationhat.light.comms.off()

def check_jobs_building():
    if automationhat.is_automation_hat():
        automationhat.light.comms.on()
    global building
    jobs = cfg.jobs
    building = 0

    for item in jobs:
        try:
            job = get_jenkins_job_by_name(item)
        except jenkinsapi.custom_exceptions.UnknownJob:
            set_error(True)
        else:
            if job.is_running():
                building += 1

    if building > 0:
        building = True
    else:
        building = False
        check_jobs_build_status()
    if automationhat.is_automation_hat():
        automationhat.light.comms.off()

# ---------------------------------------------------- #
# --            Startup of the script               -- #
# ---------------------------------------------------- #
# Turn all off if any inputs are still high
all_hat_off()
all_tower_off()
if automationhat.is_automation_hat():
    automationhat.light.power.on()

# Toggle everything once
toggle("output", "one", .4)
toggle("output", "two", .4)
toggle("output", "three", .4)

# Configure the Jenkins parameter and get the job
try:
    J = Jenkins(cfg.jenkinsurl, username=cfg.username, password=cfg.password)
except jenkinsapi.custom_exceptions.JenkinsAPIException:
    set_error(True)
    print("[ERROR] Jenkins authentication error!")
except ConnectionError:
    set_error(True)
    print("[ERROR] Jenkins connection error!")
else:
    set_error(False)
    print("[INFO] No Jenkins error!")
    # Get the status of the latest build before starting the threads
    check_jobs_build_status()

# Thread for the blinking function
# Every 10s blink for 3s when we are building
def blinking():
    if keepAlive:
        threading.Timer(10.0, blinking).start()

        # Only blink when we are actually building
        if building or error:
            # If error, blink red.
            if error:
                all_tower_off()
                toggle("output", "one", 3)
            else:
                all_tower_off()
                toggle("output", "two", 3)

# Check every 10s if we are building, if not or done get latest status
def build_running():
    if keepAlive:
        threading.Timer(10.0, build_running).start()
        if not error:
            check_jobs_building()

# Initiate the threads
blinking()
if not error:
    build_running()

# Catch the keyboard interrupt and stop the threads from executing
def main():
    global keepAlive
    while keepAlive:
        try:
            time.sleep(1)
        except KeyboardInterrupt:
            print("[NOTICE] Jenkins Light terminated!")
            all_tower_off()
            all_hat_off()
            keepAlive = False

main()


text:
<?php

class Output
{
    public static function init()
    {
        ob_start();
    }

    public static function render()
    {
        $contents = ob_get_contents();
        ob_end_clean();
        $template = new View('template', ['content' => $contents]);
        echo $template->render();
    }
}

class View
{
    protected $path;
    public $data;

    public function __construct($fileName, $data = [])
    {
        $this->path = dirname(dirname(__FILE__)).'/views/'.$fileName.'.php';
        $this->data = $data;
    }

    public function render()
    {
        ob_start();
        extract($this->data);
        include($this->path);
        $contents = ob_get_contents();
        ob_end_clean();
        return $contents;
    }

    public function __toString()
    {
        return $this->render();
    }
}


text:
import SemVer = require('../classes/semver');
import semver = require('../index');

/**
 * Return the minor version number.
 */
declare function minor(version: string | SemVer, optionsOrLoose?: boolean | semver.Options): number;

export = minor;


text:
package com.datawizards.sparklocal.dataset.grouped

import com.datawizards.sparklocal.SparkLocalBaseTest
import com.datawizards.sparklocal.dataset.DataSetAPI
import com.datawizards.sparklocal.implicits._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class KeysTest extends SparkLocalBaseTest {

  test("Keys result") {
    assertDatasetOperationResultWithSorted(
      DataSetAPI(Seq(("a",1),("b",2))).groupByKey(_._1).keys
    ) {
      Array("a","b")
    }
  }

  test("Keys equal") {
    assertDatasetOperationReturnsSameResult(Seq(("a",1),("b",2))){
      ds => ds.groupByKey(_._1).keys
    }
  }

}


text:
/*
 * FileName: DefaultBeanPropertyRowMapper.java
 * Author:   v_qinyuchen
 * Date:     2016年4月6日 下午3:51:37
 * Description: //模块目的、功能描述
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package org.alljet.dal.client.support.rowmapper;

import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.persistence.Column;

import org.alljet.dal.client.support.PaginationDalClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.NotWritablePropertyException;
import org.springframework.beans.PropertyAccessorFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.dao.DataRetrievalFailureException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

/**
 * 翻页处理规则 原来的find方法ORMapping没有依赖Column注解里的配置,是采用Spring JDBC Template默认的Mapping机制,导致java属性与数据表字段不匹配的情况发生
 * 现通过自定义的rowmapper来实现
 *
 * @author zhaopin
 * @param <T> 泛型T
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class DefaultBeanPropertyRowMapper<T> implements RowMapper<T> {
    /** Logger available to subclasses */
    private final Logger logger = LoggerFactory.getLogger(PaginationDalClient.class);
    /** The class we are mapping to */
    private Class<T> mappedClass;

    /** Whether we're strictly validating */
    private boolean checkFullyPopulated;

    /** Whether we're defaulting primitives when mapping a null value */
    private boolean primitivesDefaultedForNullValue;

    /** Map of the fields we provide mapping for */
    private Map<String, PropertyDescriptor> mappedFields;

    /** Set of bean properties we provide mapping for */
    private Set<String> mappedProperties;

    /**
     * Create a new BeanPropertyRowMapper for bean-style configuration.
     *
     * @see #setMappedClass
     * @see #setCheckFullyPopulated
     */
    public DefaultBeanPropertyRowMapper() {
    }

    /**
     * Create a new BeanPropertyRowMapper, accepting unpopulated properties in the target bean.
     *

     * Consider using the {@link #newInstance} factory method instead, which allows for specifying the mapped type once
     * only.
     *
     * @param mappedClass the class that each row should be mapped to
     */
    public DefaultBeanPropertyRowMapper(Class<T> mappedClass) {
        initialize(mappedClass);
    }

    /**
     * Create a new BeanPropertyRowMapper.
     *
     * @param mappedClass the class that each row should be mapped to
     * @param checkFullyPopulated whether we're strictly validating that all bean properties have been mapped from
     *            corresponding database fields
     */
    public DefaultBeanPropertyRowMapper(Class<T> mappedClass, boolean checkFullyPopulated) {
        initialize(mappedClass);
        this.checkFullyPopulated = checkFullyPopulated;
    }

    /**
     * Set the class that each row should be mapped to.
     *
     * @param mappedClass the mapped class.
     */
    public void setMappedClass(Class<T> mappedClass) {
        if (this.mappedClass == null) {
            initialize(mappedClass);
        } else {
            if (!this.mappedClass.equals(mappedClass)) {
                throw new InvalidDataAccessApiUsageException("The mapped class can not be reassigned to map to "
                        + mappedClass + " since it is already providing mapping for " + this.mappedClass);
            }
        }
    }

    /**
     * Initialize the mapping metadata for the given class.
     *
     * @param mappedClass the mapped class.
     */
    protected void initialize(Class<T> mappedClass) {
        this.mappedClass = mappedClass;
        this.mappedFields = new HashMap<String, PropertyDescriptor>();
        this.mappedProperties = new HashSet<String>();
        PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
        for (PropertyDescriptor pd : pds) {
            if (pd.getReadMethod() != null) {
                Column column = pd.getReadMethod().getAnnotation(Column.class);
                if (column != null) {
                    this.mappedFields.put(column.name().toLowerCase(), pd);
                    this.mappedProperties.add(pd.getName());
                } else {
                    this.mappedFields.put(pd.getName().toLowerCase(), pd);
                    String underscoredName = underscoreName(pd.getName());
                    if (!pd.getName().toLowerCase().equals(underscoredName)) {
                        this.mappedFields.put(underscoredName, pd);
                    }
                    this.mappedProperties.add(pd.getName());
                }
            }
        }
    }

    /**
     * Convert a name in camelCase to an underscored name in lower case. Any upper case letters are converted to lower
     * case with a preceding underscore.
     *
     * @param name the string containing original name
     * @return the converted name
     */
    private String underscoreName(String name) {
        if (!StringUtils.hasLength(name)) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        result.append(name.substring(0, 1).toLowerCase());
        for (int i = 1; i < name.length(); i++) {
            String s = name.substring(i, i + 1);
            String slc = s.toLowerCase();
            if (!s.equals(slc)) {
                result.append("_").append(slc);
            } else {
                result.append(s);
            }
        }
        return result.toString();
    }

    /**
     * Get the class that we are mapping to.
     *
     * @return class 映射类
     */
    public final Class<T> getMappedClass() {
        return this.mappedClass;
    }

    /**
     * Set whether we're strictly validating that all bean properties have been mapped from corresponding database
     * fields.
     *

     * Default is {@code false}, accepting unpopulated properties in the target bean.
     *
     * @param checkFullyPopulated Return whether we're strictly validating that all bean properties have been mapped
     *            from corresponding database fields.
     */
    public void setCheckFullyPopulated(boolean checkFullyPopulated) {
        this.checkFullyPopulated = checkFullyPopulated;
    }

    /**
     * Return whether we're strictly validating that all bean properties have been mapped from corresponding database
     * fields.
     *
     * @return 判断结果
     */
    public boolean isCheckFullyPopulated() {
        return this.checkFullyPopulated;
    }

    /**
     * Set whether we're defaulting Java primitives in the case of mapping a null value from corresponding database
     * fields.
     *

     * Default is {@code false}, throwing an exception when nulls are mapped to Java primitives.
     *
     * @param primitivesDefaultedForNullValue Return whether we're defaulting Java primitives in the case of mapping a
     *            null value from corresponding database fields.
     */
    public void setPrimitivesDefaultedForNullValue(boolean primitivesDefaultedForNullValue) {
        this.primitivesDefaultedForNullValue = primitivesDefaultedForNullValue;
    }

    /**
     * Return whether we're defaulting Java primitives in the case of mapping a null value from corresponding database
     * fields.
     *
     * @return 判断结果
     */
    public boolean isPrimitivesDefaultedForNullValue() {
        return primitivesDefaultedForNullValue;
    }

    /**
     * Extract the values for all columns in the current row.
     *

     * Utilizes public setters and result set metadata.
     *
     * @param rs 结果集
     * @param rowNumber 行数
     * @return 结果值
     * @exception SQLException SQL异常
     * @see java.sql.ResultSetMetaData
     */
    @Override
    public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
        Assert.state(this.mappedClass != null, "Mapped class was not specified");
        T mappedObject = BeanUtils.instantiate(this.mappedClass);
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
        initBeanWrapper(bw);

        ResultSetMetaData rsmd = rs.getMetaData();
        int columnCount = rsmd.getColumnCount();
        Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

        for (int index = 1; index <= columnCount; index++) {
            String column = JdbcUtils.lookupColumnName(rsmd, index);
            PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
            if (pd != null) {
                try {
                    Object value = getColumnValue(rs, index, pd);
                    if (logger.isDebugEnabled() && rowNumber == 0) {
                        logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                                + pd.getPropertyType());
                    }
                    try {
                        bw.setPropertyValue(pd.getName(), value);
                    } catch (TypeMismatchException e) {
                        if (value == null && primitivesDefaultedForNullValue) {
                            logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                    + column + "' with value null" + " when setting property '" + pd.getName()
                                    + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                        } else {
                            throw e;
                        }
                    }
                    if (populatedProperties != null) {
                        populatedProperties.add(pd.getName());
                    }
                } catch (NotWritablePropertyException ex) {
                    throw new DataRetrievalFailureException("Unable to map column " + column + " to property "
                            + pd.getName(), ex);
                }
            }
        }

        if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
            throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                    + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
        }

        return mappedObject;
    }

    /**
     * Initialize the given BeanWrapper to be used for row mapping. To be called for each row.
     *

     * The default implementation is empty. Can be overridden in subclasses.
     *
     * @param bw the BeanWrapper to initialize
     */
    protected void initBeanWrapper(BeanWrapper bw) {
    }

    /**
     * Retrieve a JDBC object value for the specified column.
     *

     * The default implementation calls {@link JdbcUtils#getResultSetValue(java.sql.ResultSet, int, Class)}. Subclasses
     * may override this to check specific value types upfront, or to post-process values return from
     * {@code getResultSetValue}.
     *
     * @param rs is the ResultSet holding the data
     * @param index is the column index
     * @param pd the bean property that each result object is expected to match (or {@code null} if none specified)
     * @return the Object value
     * @throws SQLException in case of extraction failure
     */
    protected Object getColumnValue(ResultSet rs, int index, PropertyDescriptor pd) throws SQLException {
        return JdbcUtils.getResultSetValue(rs, index, pd.getPropertyType());
    }

    /**
     * Static factory method to create a new BeanPropertyRowMapper (with the mapped class specified only once).
     *
     * @param mappedClass the class that each row should be mapped to
     * @param <T> 泛型对象
     * @return newInstances
     */
    public static <T> BeanPropertyRowMapper<T> newInstance(Class<T> mappedClass) {
        BeanPropertyRowMapper<T> newInstance = new BeanPropertyRowMapper<T>();
        newInstance.setMappedClass(mappedClass);
        return newInstance;
    }

}


text:
<!DOCTYPE html>
<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no"/>
  <link rel="shortcut icon" href="favicon.png">
  <link rel="apple-touch-icon" href="/apple-touch-icon.png">
  <link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114-precomposed.png" />
  <link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72-precomposed.png" />
  <link rel="apple-touch-icon-precomposed" href="touch-icon-iphone-precomposed.png" />
  <title>Social Follow</title>

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <link rel="stylesheet" type="text/css" href="css/fa-snapchat.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

  <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>
  <link href='https://fonts.googleapis.com/css?family=Raleway:900,300' rel='stylesheet' type='text/css'>
  <link href='https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.4.0/animate.min.css' rel='stylesheet' type='text/css'>

Instagram 1

Twitter 2

Facebook 4

Instagram

Twitter

Facebook

      menu

Follow The Force

             John Boyega

             Daisey Ridley

             Billie Lourd

             Oscar Isaac

             Domhnall Gleeson

             Gwendoline Christie

Follow The Force
            Who's the more foolish, the fool or the fool who follows him?

           Obi-Wan Kenobi

Contact Us

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam scelerisque id nunc nec volutpat. Etiam pellentesque tristique arcu, non consequat magna fermentum ac. Cras ut ultricies eros. Maecenas eros justo, ullamcorper a sapien id, viverra ultrices eros. Morbi sem neque, posuere et pretium eget, bibendum sollicitudin lacus. Aliquam eleifend sollicitudin diam, eu mattis nisl maximus sed. Nulla imperdiet semper molestie. Morbi massa odio, condimentum sed ipsum ac, gravida ultrices erat. Nullam eget dignissim mauris, non tristique erat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;

 Instagram

 Twitter

Company Bio

We are a team of college students working on this project like it's our full time job. Any amount would help support and continue development on this project and is greatly appreciated.

Settings

Link 1

Link 2

Link 3

Link 4

Connect

Link 1

Link 2

Link 3

Link 4

      Made by 20 Year Media

        <input id="share-text" type="text" length="150">
        Add a Message

        Share to your Wall

          Shared on Facebook

      cancel


text:
// Boost.Bimap
//
// Copyright (c) 2006-2007 Matias Capeletto
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

/// \file detail/manage_bimap_key.hpp
/// \brief Utility class to manage the set types of a bimap.

#ifndef BOOST_BIMAP_DETAIL_MANAGE_BIMAP_KEY_HPP
#define BOOST_BIMAP_DETAIL_MANAGE_BIMAP_KEY_HPP

#if defined(_MSC_VER) && (_MSC_VER>=1200)
#pragma once
#endif

#include <boost/config.hpp>

#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>

#include <boost/bimap/detail/is_set_type_of.hpp>

#include <boost/bimap/set_of.hpp>

namespace boost {
namespace bimaps {
namespace detail {

/** \struct boost::bimaps::detail::manage_bimap_key
\brief Metafunction to manage the set types of a bimap.

\code
template< class Type >
struct manage_bimap_key
{
    typedef -SetType- type;
}
\endcode

See also bimap, bimap_core.
                                                                                **/

#ifndef BOOST_BIMAP_DOXYGEN_WILL_NOT_PROCESS_THE_FOLLOWING_LINES

template< class Type >
struct manage_bimap_key
{

typedef BOOST_DEDUCED_TYPENAME

    mpl::eval_if< BOOST_DEDUCED_TYPENAME is_set_type_of< Type >::type,
    // {
            mpl::identity< Type >,
    // }
    // else
    // {
            // Default it to a set
            mpl::identity< set_of< Type > >
    // }

    >::type set_type;

    // Returns set_type and evaluate the concept_checked_type

    typedef BOOST_DEDUCED_TYPENAME mpl::if_c< true, set_type,
        BOOST_DEDUCED_TYPENAME set_type::lazy_concept_checked::type
    >::type type;
};

#endif // BOOST_BIMAP_DOXYGEN_WILL_NOT_PROCESS_THE_FOLLOWING_LINES

} // namespace detail
} // namespace bimaps
} // namespace boost

#endif // BOOST_BIMAP_DETAIL_MANAGE_BIMAP_KEY_HPP


text:
import __init__
import io
from urllib2 import urlopen
from PIL import Image
import json
import filelib as fl
import image_pylib as imglib

if __name__ == '__main__':
    OriginImagePath = 'images'
    ResizedImagePath = 'resizedImg'
    fl.checkDir(ResizedImagePath,True)
    imageW = 400
    imageH = 400
    il = imglib.IMGLIB()
    files = fl.getAllFiles(OriginImagePath,'.jpg')
    allNum = len(files)
    nowNum = 0
    for file in files:
        il.read_img(file[0])
        il.resize(imageW,imageH)
        saveImgPath = ResizedImagePath+'/'+file[1]+'.jpg'
        nowNum += 1
        print str(allNum) + ' '+str(nowNum)+' '+saveImgPath
        il.save_img(saveImgPath)


text:
__author__ = 'romilly'

import fcntl

IOCTL_I2C_SLAVE = 0x0703

class I2C_device:

    def __init__(self, address):
        self.address = address
        self.fh = None

    def begin_transmission(self):
        if self.fh:
            self.end_transmission()
            raise Exception('already open. (Now closed')
        self.fh = open('/dev/i2c-2', 'r+', 1)
        fcntl.ioctl(self.fh, IOCTL_I2C_SLAVE, self.address)

    def send(self, byte):
        if not self.fh:
            raise Exception('must open before write')
        self.fh.write(chr(byte))
       # self.fh.flush()

    def end_transmission(self):
        self.fh.close()
        self.fh = None


text:
module Dropout

# package code goes here

end # module


text:
module Linearize (linearize) where

import Control.Monad.Reader
import Data.Foldable (toList)
import Data.Functor
import Data.List (elemIndex)
import qualified Data.Set as S
import GHC.Stack

import Name
import Builder
import Syntax
import MTL1
import QueryType
import Util (bindM2)
import PPrint
import Types.Core
import Core

-- === linearization monad ===

data ActivePrimals (n::S) = ActivePrimals
  { activeVars    :: [SAtomName n]  -- includes refs and regions
  , activeEffs    :: EffectRow n }

emptyActivePrimals :: ActivePrimals n
emptyActivePrimals = ActivePrimals [] Pure

data TangentArgs (n::S) = TangentArgs [SAtomName n]

type PrimalM  = SubstReaderT Name (ReaderT1 ActivePrimals (BuilderM SimpIR)) :: MonadKind2
type TangentM = ReaderT1 TangentArgs (BuilderM SimpIR) :: MonadKind1

data WithTangent (n::S) (e1::E) (e2::E) =
  WithTangent (e1 n) (forall l. (Emits l, DExt n l) => TangentM l (e2 l))

type LinM i o e1 e2 = PrimalM i o (WithTangent o e1 e2)

-- TODO: maybe we shouldn't roll subst into this
pureLin :: (SubstE Name e, SinkableE e) => e i -> LinM i o e e
pureLin x = do
  x' <- substM x
  return $ WithTangent x' (sinkM x')

runPrimalM :: Subst Name i o -> ActivePrimals o -> PrimalM i o a -> BuilderM SimpIR o a
runPrimalM subst args cont = runReaderT1 args $ runSubstReaderT subst cont

activePrimalIdx :: SAtomName o -> PrimalM i o (Maybe Int)
activePrimalIdx v = asks \primals -> elemIndex v (activeVars primals)

getActivePrimals :: PrimalM i o (ActivePrimals o)
getActivePrimals = ask

extendActiveSubst
  :: BindsAtMostOneName b AtomNameC
  => b i i' -> SAtomName o -> PrimalM i' o a -> PrimalM i o a
extendActiveSubst b v cont = do
  extendSubst (b@>v) $ extendActivePrimals v cont

extendActiveEffs :: Effect o -> PrimalM i o a -> PrimalM i o a
extendActiveEffs eff = local \primals ->
  primals { activeEffs = extendEffRow (S.singleton eff) (activeEffs primals)}

extendActivePrimals :: SAtomName o -> PrimalM i o a -> PrimalM i o a
extendActivePrimals v =
  local \primals -> primals { activeVars = activeVars primals ++ [v] }

getTangentArg :: Int -> TangentM o (SAtom o)
getTangentArg idx = asks \(TangentArgs vs) -> Var $ vs !! idx

extendTangentArgs :: SAtomName n -> TangentM n a -> TangentM n a
extendTangentArgs v m = local (\(TangentArgs vs) -> TangentArgs $ vs ++ [v]) m

getTangentArgs :: TangentM o (TangentArgs o)
getTangentArgs = ask

bindLin
  :: Emits o
  => LinM i o e  e
  -> (forall o' m. (Emits o', DExt o o', Builder SimpIR m) => e o' -> m o' (e' o'))
  -> LinM i o e' e'
bindLin m f = do
  result <- m
  withBoth result f

withBoth
  :: Emits o
  => WithTangent o e e
  -> (forall o' m. (Emits o', DExt o o', Builder SimpIR m) => e o' -> m o' (e' o'))
  -> PrimalM i o (WithTangent o e' e')
withBoth (WithTangent x tx) f = do
  Distinct <- getDistinct
  y <- f x
  return $ WithTangent y do
    tx >>= f

_withTangentComputation
  :: Emits o
  => WithTangent o e1 e2
  -> (forall o' m. (Emits o', DExt o o', Builder SimpIR m) => e2 o' -> m o' (e2' o'))
  -> PrimalM i o (WithTangent o e1 e2')
_withTangentComputation (WithTangent x tx) f = do
  Distinct <- getDistinct
  return $ WithTangent x do
    tx >>= f

fmapLin
  :: Emits o
  => (forall o'. e o' -> e' o')
  -> LinM i o e  e
  -> LinM i o e' e'
fmapLin f m = m `bindLin` (pure . f)

zipLin :: LinM i o e1 e1 -> LinM i o e2 e2 -> LinM i o (PairE e1 e2) (PairE e1 e2)
zipLin m1 m2 = do
  WithTangent x1 t1 <- m1
  WithTangent x2 t2 <- m2
  return $ WithTangent (PairE x1 x2) do PairE <$> t1 <*> t2

seqLin
  :: Traversable f
  => f (LinM i o e e)
  -> LinM i o (ComposeE f e) (ComposeE f e)
seqLin ms = do
  ms' <- sequence ms
  let xs = ms' <&> \(WithTangent x _) -> x
  return $ WithTangent (ComposeE xs) do
    ComposeE <$> forM ms' \(WithTangent _ t) -> t

traverseLin
  :: Traversable f
  => (a -> LinM i o e e)
  -> f a
  -> LinM i o (ComposeE f e) (ComposeE f e)
traverseLin f xs = seqLin $ fmap f xs

liftTangentM :: TangentArgs o -> TangentM o a -> PrimalM i o a
liftTangentM args m = liftSubstReaderT $ lift11 $ runReaderT1 args m

isTrivialForAD :: SExpr o -> PrimalM i o Bool
isTrivialForAD expr = do
  trivialTy  <- presentAnd isSingletonType <$> (maybeTangentType =<< getType expr)
  hasActiveEffs <- getEffects expr >>= \case
                     Pure -> return False
                     -- TODO: Be more precise here, such as checking
                     -- whether the effects are themselves active.
                     _ -> return True
  hasActiveVars <- isActive expr
  return $ not hasActiveEffs && (trivialTy || not hasActiveVars)
    where presentAnd :: (a -> Bool) -> Maybe a -> Bool
          presentAnd = any

isActive :: HoistableE e => e o -> PrimalM i o Bool
isActive e = do
  vs <- (S.fromList . activeVars) <$> getActivePrimals
  return $ any (`S.member` vs) (freeAtomVarsList e)

-- === converision between monadic and reified version of functions ===

withTangentFunAsLambda :: Emits o => LinM i o SAtom SAtom -> PrimalM i o (SAtom o)
withTangentFunAsLambda cont = do
  WithTangent primalResult tf <- cont
  lam <- tangentFunAsLambda tf
  return $ PairVal primalResult lam

tangentFunType :: SType o -> PrimalM i o (SType o)
tangentFunType ty = do
  ActivePrimals primalVars effs <- getActivePrimals
  tangentTys <- varsAsBinderNest primalVars
  let effAbs = abstractFreeVarsNoAnn primalVars effs
  buildNaryPi tangentTys \tangentVars -> do
    effs' <- applyNaryAbs (sink effAbs) tangentVars
    buildNullaryPi effs' $
      return $ sink ty

tangentFunAsLambda
  :: Emits o
  => (forall o'. (DExt o o', Emits o') => TangentM o' (SAtom o'))
  -> PrimalM i o (SAtom o)
tangentFunAsLambda cont = do
  ActivePrimals primalVars effs <- getActivePrimals
  tangentTys <- varsAsBinderNest primalVars
  let effAbs = abstractFreeVarsNoAnn primalVars effs
  buildNaryLam tangentTys \tangentVars -> do
    effs' <- applyNaryAbs (sink effAbs) tangentVars
    buildNullaryLam effs' $
      liftTangentM (TangentArgs $ map sink tangentVars) cont

-- Inverse of tangentFunAsLambda. Should be used inside a returned tangent action.
applyLinToTangents :: Emits n => SAtom n -> TangentM n (SAtom n)
applyLinToTangents f = do
  TangentArgs args <- getTangentArgs
  f'  <- naryApp f  $ map Var args
  app f' UnitVal

-- repeat the primal computation in the tangent part (this is ok if the
-- computation is cheap, e.g. the body of a table lambda)
rematPrimal :: Emits o
            => Subst Name i o -> ActivePrimals o
            -> LinM i o e1 e2  -> TangentM o (e2 o)
rematPrimal subst wrt m = do
  WithTangent _ lin <- lift11 $ runPrimalM subst wrt m
  Distinct <- getDistinct
  lin

fromPureUnaryTanFunLam :: EnvReader m => SAtom n -> m n (SAtom n)
fromPureUnaryTanFunLam atom = liftSubstEnvReaderM $ go atom
  where
    go :: SAtom i -> SubstEnvReaderM SAtomSubstVal i o (SAtom o)
    go = \case
      Lam (LamExpr b@(LamBinder _ _ _ Pure) (AtomicBlock nullaryLam)) ->
        substBinders b \(LamBinder b' ty _ _) -> do
          case nullaryLam of
            Lam (LamExpr unitBinder body) -> do
              body' <- extendSubst (unitBinder @> SubstVal UnitVal) $ substM body
              return $ Lam $ LamExpr (LamBinder b' ty LinArrow Pure) body'
            _ -> error notValidStr
      _ -> error notValidStr
      where notValidStr = "not a pure unary tangent function: " ++ pprint atom

-- === actual linearization passs ===

-- main API entrypoint
linearize :: EnvReader m => SAtom n -> m n (SAtom n)
linearize x = liftBuilder $
  runPrimalM idSubst emptyActivePrimals $
    linearizeLambda' x
{-# SCC linearize #-}

-- reify the tangent builder as a lambda
linearizeLambda' :: SAtom i -> PrimalM i o (SAtom o)
linearizeLambda' (Lam (LamExpr (LamBinder b ty PlainArrow Pure) body)) = do
  ty' <- substM ty
  buildLam (getNameHint b) PlainArrow ty' Pure \vp -> do
    extendActiveSubst b vp do
      WithTangent primalResult tangentAction <- linearizeBlock body
      tanFun <- tangentFunAsLambda tangentAction
      lam <- fromPureUnaryTanFunLam tanFun
      return $ PairVal primalResult lam
linearizeLambda' _ = error "not implemented"

linearizeAtom :: Emits o => SAtom i -> LinM i o SAtom SAtom
linearizeAtom atom = case atom of
  Var v -> do
    v' <- substM v
    activePrimalIdx v' >>= \case
      Nothing -> withZeroT $ return (Var v')
      Just idx -> return $ WithTangent (Var v') $ getTangentArg idx
  Con con -> linearizePrimCon con
  TabLam (TabLamExpr b body) -> do
    ty <- substM $ binderAnn b
    wrt <- getActivePrimals
    subst <- getSubst
    atom' <- substM atom
    return $ WithTangent atom' do
      buildTabLam (getNameHint b) (sink ty) \i ->
        rematPrimal (sink subst) (sink wrt) $
          extendSubst (b@>i) $ linearizeBlock body
  DictCon _ -> notImplemented
  DictTy _  -> notImplemented
  DepPair _ _ _     -> notImplemented
  TypeCon _ _ _   -> emitZeroT
  LabeledRow _    -> emitZeroT
  RecordTy _      -> emitZeroT
  VariantTy _     -> emitZeroT
  Pi _            -> emitZeroT
  TabPi _         -> emitZeroT
  DepPairTy _     -> emitZeroT
  TC _            -> emitZeroT
  Eff _           -> emitZeroT
  ProjectElt idxs v ->
    linearizeAtom (Var v) `bindLin` \x ->
      return $ getProjection (toList idxs) x
  -- Those should be gone after simplification
  Lam _            -> error "Unexpected non-table lambda"
  ACase _ _ _      -> error "Unexpected ACase"
  DepPairRef _ _ _ -> error "Unexpected ref"
  where emitZeroT = withZeroT $ substM atom

linearizeBlock :: Emits o => SBlock i -> LinM i o SAtom SAtom
linearizeBlock (Block _ decls result) =
  linearizeDecls decls $ linearizeAtom result

linearizeDecls :: Emits o => Nest SDecl i i' -> LinM i' o e1 e2 -> LinM i  o e1 e2
linearizeDecls Empty cont = cont
-- TODO: as an optimization, don't bother extending the tangent args if the
-- tangent is trivial, either because its type is a singleton or because there
-- are no active vars.
linearizeDecls (Nest (Let b (DeclBinding ann _ expr)) rest) cont = do
  expr' <- substM expr
  isTrivialForAD expr' >>= \case
    True -> do
      v <- emit expr'
      extendSubst (b@>v) $ linearizeDecls rest cont
    False -> do
      WithTangent p tf <- linearizeExpr expr
      v <- emitDecl (getNameHint b) ann (Atom p)
      extendActiveSubst b v do
        WithTangent pRest tfRest <- linearizeDecls rest cont
        return $ WithTangent pRest do
          t <- tf
          vt <- emitDecl (getNameHint b) ann (Atom t)
          extendTangentArgs vt $
            tfRest

linearizeExpr :: Emits o => SExpr i -> LinM i o SAtom SAtom
linearizeExpr expr = case expr of
  Atom x -> linearizeAtom x
  App (Var f) xs -> do
    f' <- substM f
    lookupCustomRules f' >>= \case
      Nothing -> error "not implemented"
      Just (CustomLinearize n zeros cl) -> do
        let (polyXs, argXs) = splitAt n $ toList xs
        polyXs' <- mapM substM polyXs
        (any id <$> mapM isActive polyXs') >>= \case
          True -> error $
            "Polymorphic arguments of custom linearization rules are " ++
            "expected to be inactive (i.e. independent of any differentiated " ++
            "function argument)"
          False -> return ()
        wts <- case zeros of
          InstantiateZeros -> forM (toList argXs) linearizeAtom
          SymbolicZeros -> do
            stDefName <- lookupSourceMap "ZeroTangent" >>= \case
              Just (UDataConVar conName) -> do
                DataConBinding dataDefName zeroConIx _ <- lookupEnv conName
                unless (zeroConIx == 0) $ error "Ill-defined SymbolicTangent?"
                return dataDefName
              _ -> error "Ill-defined SymbolicTangent?"
            forM (toList argXs) \arg -> do
              arg' <- substM arg
              argTy' <- getType arg'
              isActive arg' >>= \case
                False -> -- Pass in ZeroTangent as the tangent
                  return $ WithTangent arg' $
                    return $ sink $ Con $ Newtype
                      (TypeCon "SymbolicTangent" stDefName
                       (DataDefParams [(PlainArrow, argTy')]))
                      (SumVal [UnitTy, argTy'] 0 UnitVal)
                True -> do  -- Wrap tangent in SomeTangent
                  WithTangent arg'' argLin <- dropSubst $ linearizeAtom arg'
                  return $ WithTangent arg'' $ argLin <&> \argTan ->
                    Con $ Newtype
                      (TypeCon "SymbolicTangent" (sink stDefName)
                       (DataDefParams [(PlainArrow, sink argTy')]))
                      (SumVal [UnitTy, sink argTy'] 1 argTan)
        (ans, flin) <- fromPair =<< naryApp cl (polyXs' ++ (wts <&> \(WithTangent p _) -> p))
        return $ WithTangent ans $ naryApp (sink flin) =<< sequence (wts <&> \(WithTangent _ t) -> t)
  App _ _ -> error "not implemented"
  TabApp x idxs -> do
    zipLin (linearizeAtom x) (pureLin $ ListE $ toList idxs) `bindLin`
      \(PairE x' (ListE idxs')) -> naryTabApp x' idxs'
  Op op      -> linearizeOp op
  Hof e      -> linearizeHof e
  Case e alts resultTy _ -> do
    e' <- substM e
    resultTy' <- substM resultTy
    isActive e' >>= \case
      True -> notImplemented
      False -> do
        resultTangentType <- tangentType resultTy'
        resultTyWithTangent <- PairTy <$> substM resultTy
                                      <*> tangentFunType resultTangentType
        (ans, linLam) <- fromPair =<< buildCase e' resultTyWithTangent \i x -> do
          x' <- emitAtomToName noHint x
          Abs b body <- return $ alts !! i
          extendSubst (b @> x') $ withTangentFunAsLambda $ linearizeBlock body
        return $ WithTangent ans do
          applyLinToTangents $ sink linLam
  Handle _ _ _ -> error "handlers should be gone by now"

linearizeOp :: Emits o => Op SimpIR i -> LinM i o SAtom SAtom
linearizeOp op = case op of
  UnOp  uop x       -> linearizeUnOp  uop x
  BinOp bop x y     -> linearizeBinOp bop x y
  PrimEffect ref m -> case m of
    MAsk -> linearizeAtom ref `bindLin` \ref' -> emitOp $ PrimEffect ref' MAsk
    MExtend monoid x -> do
      -- TODO: check that we're dealing with a +/0 monoid
      monoid' <- mapM substM monoid
      zipLin (linearizeAtom ref) (linearizeAtom x) `bindLin` \(PairE ref' x') ->
        emitOp $ PrimEffect ref' $ MExtend (fmap sink monoid') x'
    MGet   -> linearizeAtom ref `bindLin` \ref' -> emitOp $ PrimEffect ref' MGet
    MPut x -> zipLin (linearizeAtom ref) (linearizeAtom x) `bindLin` \(PairE ref' x') ->
                emitOp $ PrimEffect ref' $ MPut x'
  IndexRef ref i -> zipLin (la ref) (pureLin i) `bindLin`
                      \(PairE ref' i') -> emitOp $ IndexRef ref' i'
  ProjRef i ref -> la ref `bindLin` \ref' -> emitOp $ ProjRef i ref'
  Select p t f -> (pureLin p `zipLin` la t `zipLin` la f) `bindLin`
                     \(p' `PairE` t' `PairE` f') -> emitOp $ Select p' t' f'
  -- XXX: This assumes that pointers are always constants
  PtrLoad _              -> emitZeroT
  PtrStore _ _           -> emitZeroT
  PtrOffset _ _          -> emitZeroT
  IOAlloc _ _            -> emitZeroT
  IOFree _               -> emitZeroT
  ThrowError _           -> emitZeroT
  SumTag _               -> emitZeroT
  ToEnum _ _             -> emitZeroT
  TabCon ty xs -> do
    ty' <- substM ty
    seqLin (map linearizeAtom xs) `bindLin` \(ComposeE xs') ->
      emitOp $ TabCon (sink ty') xs'
  CastOp t v             -> do
    vt <- getType =<< substM v
    t' <- substM t
    vtTangentType <- tangentType vt
    tTangentType  <- tangentType t'
    ((&&) <$> (vtTangentType `alphaEq` vt)
          <*> (tTangentType  `alphaEq` t')) >>= \case
      True -> do
        linearizeAtom v `bindLin` \v' -> emitOp $ CastOp (sink t') v'
      False -> do
        WithTangent x xt <- linearizeAtom v
        yt <- case (vtTangentType, tTangentType) of
          (_     , UnitTy) -> return $ UnitVal
          (UnitTy, tt    ) -> zeroAt tt
          _                -> error "Expected at least one side of the CastOp to have a trivial tangent type"
        y <- emitOp $ CastOp t' x
        return $ WithTangent y do xt >> return (sink yt)
  BitcastOp _ _ -> notImplemented
  RecordCons l r ->
    zipLin (la l) (la r) `bindLin` \(PairE l' r') ->
      emitOp $ RecordCons l' r'
  RecordSplit f r ->
    zipLin (la f) (la r) `bindLin` \(PairE f' r') ->
      emitOp $ RecordSplit f' r'
  VariantLift ts v ->
    zipLin (traverseLin pureLin ts) (la v) `bindLin`
      \(PairE (ComposeE ts') v') -> emitOp $ VariantLift ts' v'
  VariantSplit ts v ->
    zipLin (traverseLin pureLin ts) (la v) `bindLin`
      \(PairE (ComposeE ts') v') -> emitOp $ VariantSplit ts' v'
  ThrowException _       -> notImplemented
  SumToVariant _         -> notImplemented
  OutputStream           -> emitZeroT
  _ -> notImplemented
  where
    emitZeroT = withZeroT $ liftM Var $ emit =<< substM (Op op)
    la = linearizeAtom

linearizeUnOp :: Emits o => UnOp -> SAtom i -> LinM i o SAtom SAtom
linearizeUnOp op x' = do
  WithTangent x tx <- linearizeAtom x'
  let emitZeroT = withZeroT $ emitOp $ UnOp op x
  case op of
    Exp    -> do
      y <- emitUnOp Exp x
      return $ WithTangent y (bindM2 mul tx (sinkM y))
    Exp2   -> notImplemented
    Log    -> withT (emitUnOp Log x) $ (tx >>= (`div'` sink x))
    Log2   -> notImplemented
    Log10  -> notImplemented
    Log1p  -> notImplemented
    Sin    -> withT (emitUnOp Sin x) $ bindM2 mul tx (emitUnOp Cos (sink x))
    Cos    -> withT (emitUnOp Cos x) $ bindM2 mul tx (neg =<< emitUnOp Sin (sink x))
    Tan    -> notImplemented
    Sqrt   -> do
      y <- emitUnOp Sqrt x
      return $ WithTangent y do
        denominator <- bindM2 mul (2 `fLitLike` sink y) (sinkM y)
        bindM2 div' tx (pure denominator)
    Floor  -> emitZeroT
    Ceil   -> emitZeroT
    Round  -> emitZeroT
    LGamma -> notImplemented
    Erf    -> notImplemented
    Erfc   -> notImplemented
    FNeg   -> withT (neg x) (neg =<< tx)
    BNot   -> emitZeroT

linearizeBinOp :: Emits o => BinOp -> SAtom i -> SAtom i -> LinM i o SAtom SAtom
linearizeBinOp op x' y' = do
  WithTangent x tx <- linearizeAtom x'
  WithTangent y ty <- linearizeAtom y'
  let emitZeroT = withZeroT $ emitOp $ BinOp op x y
  case op of
    IAdd   -> emitZeroT
    ISub   -> emitZeroT
    IMul   -> emitZeroT
    IDiv   -> emitZeroT
    IRem   -> emitZeroT
    ICmp _ -> emitZeroT
    FAdd -> withT (add x y) (bindM2 add tx ty)
    FSub -> withT (sub x y) (bindM2 sub tx ty)
    FMul -> withT (mul x y)
                  (bindM2 add (bindM2 mul (sinkM x) ty)
                              (bindM2 mul tx (sinkM y)))
    FDiv -> withT (div' x y) do
      tx' <- bindM2 div' tx (sinkM y)
      ty' <- bindM2 div' (bindM2 mul (sinkM x) ty)
                      (bindM2 mul (sinkM y) (sinkM y))
      sub tx' ty'
    FPow -> withT (emitOp $ BinOp FPow x y) do
      c <- fpow (sink x) =<< bindM2 sub (sinkM y) (1.0 `fLitLike` sink y)
      tx' <- bindM2 mul tx (sinkM y)
      ty' <- bindM2 mul (bindM2 mul (sinkM x) ty) (flog $ sink x)
      mul c =<< add tx' ty'
    FCmp _ -> emitZeroT
    BAnd   -> emitZeroT
    BOr    -> emitZeroT
    BXor   -> emitZeroT
    BShL   -> emitZeroT
    BShR   -> emitZeroT

linearizePrimCon :: Emits o => Con SimpIR i -> LinM i o SAtom SAtom
linearizePrimCon con = case con of
  Lit _ -> emitZeroT
  ProdCon xs -> fmapLin (ProdVal . fromComposeE) $ seqLin (fmap linearizeAtom xs)
  SumCon  _ _ _ -> notImplemented
  SumAsProd tys tg elems -> do
    tys' <- traverse substM tys
    tg' <- substM tg
    -- There must be a way to do this with `seqLin` etc but it's too much for me
    elemsWithT <- traverse linearizeAtom elems
    let elemsP = fmap (\(WithTangent x _) -> x) elemsWithT
    return $ WithTangent (Con $ SumAsProd tys' tg' elemsP) do
      elemsT <- forM elemsWithT \(WithTangent _ t) -> t
      return $ Con $ SumAsProd (sinkList tys') (sink tg') elemsT
  Newtype ty x    -> case ty of
    TC (Fin _) -> emitZeroT
    StaticRecordTy _ -> do
      ty' <- substM ty
      tanTy' <- tangentType ty'
      WithTangent prims lins <- linearizeAtom x
      return $ WithTangent (Con $ Newtype ty' prims) (Con . Newtype (sink tanTy') <$> lins)
    _ -> error $ "Unsupported newtype: " ++ pprint ty
  LabelCon _     -> error "Unexpected label"
  BaseTypeRef _  -> error "Unexpected ref"
  TabRef _       -> error "Unexpected ref"
  ConRef _       -> error "Unexpected ref"
  ExplicitDict  _ _ -> error "Unexpected ExplicitDict"
  DictHole _ _ -> error "Unexpected DictHole"
  where emitZeroT = withZeroT $ substM $ Con con

linearizeHof :: Emits o => Hof SimpIR i -> LinM i o SAtom SAtom
linearizeHof hof = case hof of
  For d ixDict (Lam (LamExpr i body)) -> do
    ixTy <- ixTyFromDict =<< substM ixDict
    ansWithLinTab <- buildFor (getNameHint i) d ixTy \i' ->
      extendSubst (i@>i') $ withTangentFunAsLambda $ linearizeBlock body
    (ans, linTab) <- unzipTab ansWithLinTab
    return $ WithTangent ans do
      buildFor (getNameHint i) d (sink ixTy) \i' ->
        tabApp (sink linTab) (Var i') >>= applyLinToTangents
  RunReader r lam -> do
    WithTangent r' rLin <- linearizeAtom r
    lam' <- linearizeEffectFun Reader lam
    result <- liftM Var (emit $ Hof $ RunReader r' lam')
    (primalResult, tangentLam) <- fromPair result
    return $ WithTangent primalResult do
      rLin' <- rLin
      tanEffectLam <- applyLinToTangents $ sink tangentLam
      liftM Var $ emit $ Hof $ RunReader rLin' tanEffectLam
  RunState Nothing sInit lam -> do
    WithTangent sInit' sLin <- linearizeAtom sInit
    lam' <- linearizeEffectFun State lam
    (result, sFinal) <- fromPair =<< liftM Var (emit $ Hof $ RunState Nothing sInit' lam')
    (primalResult, tangentLam) <- fromPair result
    return $ WithTangent (PairVal primalResult sFinal) do
      sLin' <- sLin
      tanEffectLam <- applyLinToTangents $ sink tangentLam
      liftM Var $ emit $ Hof $ RunState Nothing sLin' tanEffectLam
  RunWriter Nothing bm lam -> do
    -- TODO: check it's actually the 0/+ monoid (or should we just build that in?)
    ComposeE bm' <- substM (ComposeE bm)
    lam' <- linearizeEffectFun Writer lam
    (result, wFinal) <- fromPair =<< liftM Var (emit $ Hof $ RunWriter Nothing bm' lam')
    (primalResult, tangentLam) <- fromPair result
    return $ WithTangent (PairVal primalResult wFinal) do
      ComposeE bm'' <- sinkM $ ComposeE bm'
      tanEffectLam <- applyLinToTangents $ sink tangentLam
      liftM Var $ emit $ Hof $ RunWriter Nothing bm'' tanEffectLam
  RunIO (Lam (LamExpr b@(LamBinder _ _ _ effs) body)) -> do
    effs' <- substM $ ignoreHoistFailure $ hoist b effs
    -- TODO: consider the possibility of other effects here besides IO
    ioLam <- buildLam noHint PlainArrow UnitTy effs' \v -> do
      WithTangent primalResult tangentFun <- extendSubst (b@>v) $ linearizeBlock body
      lam <- tangentFunAsLambda tangentFun
      return $ PairVal primalResult lam
    result <- liftM Var $ emit $ Hof $ RunIO ioLam
    (ans, linLam) <- fromPair result
    return $ WithTangent ans $ applyLinToTangents (sink linLam)
  _ -> error $ "not implemented: " ++ pprint hof

-- takes an effect function, of type `(h:Type) -> Ref h s -> a``
-- and augments it with the tangent lambda, so instead of returning `a`, it returns:
-- `[tangent args] -> (a & ((h':Type) -> (ref':Ref h' (T s)) -> T a))`
linearizeEffectFun :: RWS -> SAtom i -> PrimalM i o (SAtom o)
linearizeEffectFun rws ~(Lam lam) = do
  BinaryLamExpr hB refB body <- return lam
  referentTy <- getReferentTy =<< substM (EmptyAbs $ PairB hB refB)
  buildEffLam rws (getNameHint refB) referentTy \h ref -> withTangentFunAsLambda do
    extendActiveSubst hB h $ extendActiveSubst refB ref $
      extendActiveEffs (RWSEffect rws (Just h)) do
        WithTangent p tangentFun <- linearizeBlock body
        return $ WithTangent p do
          tt <- tangentType $ sink referentTy
          buildEffLam rws (getNameHint refB) tt \h' ref' ->
            extendTangentArgs h' $ extendTangentArgs ref' $
              tangentFun

withT :: PrimalM i o (e1 o)
      -> (forall o'. (Emits o', DExt o o') => TangentM o' (e2 o'))
      -> PrimalM i o (WithTangent o e1 e2)
withT p t = do
  p' <- p
  return $ WithTangent p' t

withZeroT :: PrimalM i o (SAtom o)
          -> PrimalM i o (WithTangent o SAtom SAtom)
withZeroT p = do
  p' <- p
  return $ WithTangent p' do
    pTy <- getType $ sink p'
    zeroAt =<< tangentType pTy

notImplemented :: HasCallStack => a
notImplemented = error "Not implemented"

-- === instances ===

instance GenericE ActivePrimals where
  type RepE ActivePrimals = PairE (ListE SAtomName) EffectRow
  fromE (ActivePrimals vs effs) = ListE vs `PairE` effs
  {-# INLINE fromE #-}
  toE   (ListE vs `PairE` effs) = ActivePrimals vs effs
  {-# INLINE toE #-}

instance SinkableE   ActivePrimals
instance HoistableE  ActivePrimals
instance AlphaEqE    ActivePrimals
instance SubstE Name ActivePrimals

instance GenericE TangentArgs where
  type RepE TangentArgs = ListE SAtomName
  fromE (TangentArgs vs) = ListE vs
  {-# INLINE fromE #-}
  toE   (ListE vs) = TangentArgs vs
  {-# INLINE toE #-}

instance SinkableE   TangentArgs
instance HoistableE  TangentArgs
instance AlphaEqE    TangentArgs
instance SubstE Name TangentArgs


text:
from distutils.core import setup

setup(
    name='Django CMS NivoSlider',
    version='0.1.2',
    author='Ryan Bagwell',
    author_email='ryan@ryanbagwell.com',
    packages=['nivoslider',],
    url='https://github.com/ryanbagwell/django-cms-nivo-slider',
    license='LICENSE.txt',
    description='A Django CMS carousel version of Nivo Slider',
    long_description=open('README.txt').read(),
    install_requires=[
        "Django >= 1.4",
        "django-filer >= 0.9.3",
    ],
)


text:
layout: page
title: Carson International Seminar
date: 2016-05-24
author: Gerald Elliott
tags: weekly links, java
status: published
summary: Mauris facilisis est metus, eu ornare est molestie ac. Sed.
banner: images/banner/office-01.jpg
booking:
  startDate: 01/03/2016
  endDate: 01/08/2016
  ctyhocn: MSYLAHX
  groupCode: CIS
published: true
---
Integer sodales leo vel nisi tincidunt molestie. Nullam gravida enim leo, luctus tincidunt ante condimentum vel. Donec pellentesque sed turpis vel lacinia. Suspendisse venenatis est id augue maximus, eu tincidunt odio viverra. Duis congue metus lorem, id auctor sapien feugiat ut. Ut in sagittis felis, id lacinia nunc. Aliquam eget porta massa. Praesent elementum, purus in hendrerit tempor, felis lectus finibus elit, in finibus neque neque nec arcu. Sed diam tellus, viverra ac tempor eget, hendrerit vel lacus. Praesent ligula tellus, accumsan in lacus eu, laoreet posuere elit.

1 Cras sed lorem aliquam, sollicitudin eros id, lobortis libero
1 Fusce at arcu mollis, gravida est vitae, pretium tortor.

Ut dignissim lacus et urna semper suscipit. Donec bibendum consequat diam ac consectetur. Curabitur quis commodo purus, in elementum ex. Phasellus turpis magna, maximus at tristique sit amet, rutrum eget nisi. Cras consectetur hendrerit egestas. Suspendisse sit amet cursus leo, vitae imperdiet massa. Phasellus pulvinar lectus id massa suscipit, vel consequat ante blandit. Etiam a purus scelerisque, eleifend velit vel, blandit lectus. Sed commodo vitae leo nec luctus.


text:
use boxcars::crc::calc_crc;
use boxcars::*;
use criterion::{black_box, criterion_group, criterion_main, Criterion, Throughput};

fn bench_crc(c: &mut Criterion) {
    let data = include_bytes!("../assets/replays/good/rumble.replay");
    let mut group = c.benchmark_group("crc_throughput");
    group.throughput(Throughput::Bytes(data.len() as u64));
    group.bench_function("bench_crc", |b| {
        let data = include_bytes!("../assets/replays/good/rumble.replay");
        b.iter(|| {
            black_box(calc_crc(&data[..]));
        })
    });
    group.finish();
}

fn bench_json_serialization(c: &mut Criterion) {
    let data = include_bytes!("../assets/replays/good/3381.replay");
    let json_data_bytes = 19484480_u64;

    let mut group = c.benchmark_group("json_throughput");
    group.sample_size(10);
    group.throughput(Throughput::Bytes(json_data_bytes));
    group.bench_function("bench_json_serialization", |b| {
        let mut bytes = Vec::new();
        let replay = ParserBuilder::new(data)
            .on_error_check_crc()
            .parse()
            .unwrap();
        serde_json::to_writer(&mut bytes, &replay).unwrap();
        assert!(
            json_data_bytes == bytes.len() as u64,
            "update json benchmark with latest throughput size: {}",
            bytes.len()
        );
        unsafe {
            bytes.set_len(0);
        };

        b.iter(|| {
            black_box(serde_json::to_writer(&mut bytes, &replay).unwrap());
            unsafe {
                bytes.set_len(0);
            };
        })
    });
    group.finish();
}

fn bench_parse_crc_body(c: &mut Criterion) {
    let data = include_bytes!("../assets/replays/good/3381.replay");
    let mut group = c.benchmark_group("parse_crc_body");
    group.throughput(Throughput::Bytes(data.len() as u64));
    group.sample_size(20);
    group.bench_function("bench_parse_crc_body", |b| {
        b.iter(|| {
            black_box(
                ParserBuilder::new(data)
                    .always_check_crc()
                    .must_parse_network_data()
                    .parse()
                    .unwrap(),
            )
        });
    });
    group.finish();
}

fn bench_parse_no_crc_body(c: &mut Criterion) {
    let data = include_bytes!("../assets/replays/good/3381.replay");
    let mut group = c.benchmark_group("parse_no_crc_body");
    group.throughput(Throughput::Bytes(data.len() as u64));
    group.sample_size(20);
    group.bench_function("bench_parse_no_crc_body", |b| {
        b.iter(|| {
            black_box(
                ParserBuilder::new(data)
                    .on_error_check_crc()
                    .must_parse_network_data()
                    .parse()
                    .unwrap(),
            )
        });
    });
    group.finish();
}

fn bench_parse_no_crc_no_body(c: &mut Criterion) {
    // Throughput not included in this benchmark as it is a bit confusing what the number reporting
    // represents. If parsing the header reports based on the entire size of the replay, it will be
    // some very large number (20 GB/s), else it may look deceptively small
    let data = include_bytes!("../assets/replays/good/3381.replay");
    let mut group = c.benchmark_group("parse_no_crc_no_body");
    group.bench_function("bench_parse_no_crc_no_body", |b| {
        b.iter(|| {
            black_box(
                ParserBuilder::new(data)
                    .on_error_check_crc()
                    .never_parse_network_data()
                    .parse()
                    .unwrap(),
            )
        });
    });
    group.finish();
}

fn bench_parse_crc_json(c: &mut Criterion) {
    let data = include_bytes!("../assets/replays/good/3381.replay");
    let mut group = c.benchmark_group("parse_crc_json");
    group.throughput(Throughput::Bytes(data.len() as u64));
    group.sample_size(10);
    group.bench_function("bench_parse_crc_json", |b| {
        // allocate a buffer big enough to hold all of the serialized data
        let mut bytes = Vec::with_capacity(2_usize.pow(25));
        b.iter(|| {
            let data = ParserBuilder::new(data).always_check_crc().parse().unwrap();
            black_box(serde_json::to_writer(&mut bytes, &data).unwrap());
            unsafe {
                bytes.set_len(0);
            }
        });
    });
    group.finish();
}

criterion_group!(
    benches,
    bench_crc,
    bench_json_serialization,
    bench_parse_crc_body,
    bench_parse_no_crc_body,
    bench_parse_no_crc_no_body,
    bench_parse_crc_json,
);

criterion_main!(benches);


text:
<?php
/**
 * Installation model
 * @author Anton Zekeriev Rodin
 */
class Install_model extends CI_Model {

    public function  __construct() {}

    public function set_tables() {

        $query = '
            CREATE TABLE IF NOT EXISTS `users` (
                `id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
                 `username` VARCHAR( 25 ) NOT NULL ,
                 `password` VARCHAR( 32 ) NOT NULL ,
                 `email_address` VARCHAR( 50 ) NOT NULL ,
                PRIMARY KEY (  `id` ) ,
                UNIQUE KEY  `email_address` (  `email_address` ) ,
                UNIQUE KEY  `username` (  `username` )
            ) ENGINE = MYISAM DEFAULT CHARSET = utf8;
            ';
        $this->db->query($query);

    }

    public function set_users() {

        for ($i=1; $i<100; $i++) {
            $insert_data = array(
                'username' => 'root' . $i,
                'password' => md5('1234'),
                'email_address' => 'email' . $i . '@root.com'
            );
            $this->db->insert('users', $insert_data);
        }

    }

}
?>


text:
/*************************************************************************/
/*  audio_driver_pulseaudio.h                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md)    */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#ifdef PULSEAUDIO_ENABLED

#ifndef AUDIO_DRIVER_PULSEAUDIO_H
#define AUDIO_DRIVER_PULSEAUDIO_H

#include "core/os/mutex.h"
#include "core/os/thread.h"
#include "servers/audio_server.h"

#include <pulse/pulseaudio.h>

class AudioDriverPulseAudio : public AudioDriver {

	Thread *thread;
	Mutex *mutex;

	pa_mainloop *pa_ml;
	pa_context *pa_ctx;
	pa_stream *pa_str;
	pa_stream *pa_rec_str;
	pa_channel_map pa_map;
	pa_channel_map pa_rec_map;

	String device_name;
	String new_device;
	String default_device;

	String capture_device_name;
	String capture_new_device;
	String capture_default_device;

	Vector<int32_t> samples_in;
	Vector<int16_t> samples_out;

	unsigned int mix_rate;
	unsigned int buffer_frames;
	unsigned int pa_buffer_size;
	int channels;
	int pa_ready;
	int pa_status;
	Array pa_devices;
	Array pa_rec_devices;

	bool active;
	bool thread_exited;
	mutable bool exit_thread;

	float latency;

	static void pa_state_cb(pa_context *c, void *userdata);
	static void pa_sink_info_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata);
	static void pa_source_info_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata);
	static void pa_server_info_cb(pa_context *c, const pa_server_info *i, void *userdata);
	static void pa_sinklist_cb(pa_context *c, const pa_sink_info *l, int eol, void *userdata);
	static void pa_sourcelist_cb(pa_context *c, const pa_source_info *l, int eol, void *userdata);

	Error init_device();
	void finish_device();

	Error capture_init_device();
	void capture_finish_device();

	void detect_channels(bool capture = false);

	static void thread_func(void *p_udata);

public:
	const char *get_name() const {
		return "PulseAudio";
	};

	virtual Error init();
	virtual void start();
	virtual int get_mix_rate() const;
	virtual SpeakerMode get_speaker_mode() const;

	virtual Array get_device_list();
	virtual String get_device();
	virtual void set_device(String device);

	virtual Array capture_get_device_list();
	virtual void capture_set_device(const String &p_name);
	virtual String capture_get_device();

	virtual void lock();
	virtual void unlock();
	virtual void finish();

	virtual float get_latency();

	virtual Error capture_start();
	virtual Error capture_stop();

	AudioDriverPulseAudio();
	~AudioDriverPulseAudio();
};

#endif // AUDIO_DRIVER_PULSEAUDIO_H

#endif // PULSEAUDIO_ENABLED


text:
define(
	(require, factory) => {
    const { AuthorizedRoute } = require('pages/Route');
		const atlasState = require('atlas-state');
    function routes(router) {
      return {
        '/iranalysis': new AuthorizedRoute(() =>  {
          require(['./ir-browser'], () => {
            router.setCurrentView('ir-browser');
          });
        }),
        '/iranalysis/:analysisId:/version/:version:': new AuthorizedRoute((analysisId, version) =>  {
          require(['./ir-manager'], () => {
            atlasState.IRAnalysis.selectedId(+analysisId);
            router.setCurrentView('ir-manager', { analysisId, activeTab: 'definition', version });
          });
        }),
        '/iranalysis/:analysisId:/?((\w|.)*)': new AuthorizedRoute((analysisId, path) => {
          analysisId = parseInt(analysisId);
          path = path.split("/");
          let activeTab = null;
          if (path.length > 0 && path[0] !== "") {
            activeTab = path[0];
          }
          let selectedSourceId = null;
          // source_id
          if (path.length > 1 && path[1] !== "") {
            selectedSourceId = parseInt(path[1]);
          }
          require(['./ir-manager'], function () {
            atlasState.IRAnalysis.selectedId(+analysisId);
            atlasState.IRAnalysis.selectedSourceId(+selectedSourceId);
            router.setCurrentView('ir-manager', { analysisId, activeTab });
          });
        }),
      };
    }

    return routes;
  }
);


text:
package io.biblia.workflows.definition.parser;

import io.biblia.workflows.definition.Dataset;
import org.bson.Document;

public abstract class DatasetParser {

	public abstract Dataset parseDataset(Document object) throws DatasetParseException;
}


text:
#include <boost/random/uniform_int.hpp>
#include <boost/random/uniform_real.hpp>
#include <boost/random/variate_generator.hpp>
#include <boost/random/normal_distribution.hpp>
#include <boost/math/special_functions/round.hpp>

#include <string>
#include <vector>
#include <algorithm>

#include "../exceptions.h"
#include "../population.h"
#include "../problem/base.h"
#include "../types.h"
#include "base.h"
#include "nsga2.h"

namespace pagmo { namespace algorithm {

/// Constructor
 /**
 * Constructs a NSGA II algorithm
 *
 * @param[in] gen Number of generations to evolve.
 * @param[in] cr Crossover probability
 * @param[in] eta_c Distribution index for crossover
 * @param[in] m Mutation probability
 * @param[in] eta_m Distribution index for mutation
 * @throws value_error if gen is negative, crossover probability is not \f$ \in [0,1[\f$, mutation probability or mutation width is not \f$ \in [0,1]\f$,
 */
nsga2::nsga2(int gen, double cr, double eta_c, double m, double eta_m):base(),m_gen(gen),m_cr(cr),m_eta_c(eta_c),m_m(m),m_eta_m(eta_m)
{
	if (gen < 0) {
		pagmo_throw(value_error,"number of generations must be nonnegative");
	}
	if (cr >= 1 || cr < 0) {
		pagmo_throw(value_error,"crossover probability must be in the [0,1[ range");
	}
	if (m < 0 || m > 1) {
		pagmo_throw(value_error,"mutation probability must be in the [0,1] range");
	}
	if (eta_c <1 || eta_c >= 100) {
		pagmo_throw(value_error,"Distribution index for crossover must be in 1..100");
	}
	if (eta_m <1 || eta_m >= 100) {
		pagmo_throw(value_error,"Distribution index for mutation must be in 1..100");
	}
}

/// Clone method.
base_ptr nsga2::clone() const
{
	return base_ptr(new nsga2(*this));
}

pagmo::population::size_type nsga2::tournament_selection(pagmo::population::size_type idx1, pagmo::population::size_type idx2, const pagmo::population& pop) const
{
	if (pop.get_pareto_rank(idx1) < pop.get_pareto_rank(idx2)) return idx1;
	if (pop.get_pareto_rank(idx1) > pop.get_pareto_rank(idx2)) return idx2;
	if (pop.get_crowding_d(idx1) > pop.get_crowding_d(idx2)) return idx1;
	if (pop.get_crowding_d(idx1) < pop.get_crowding_d(idx2)) return idx2;
	return ((m_drng() > 0.5) ? idx1 : idx2);
}

void nsga2::crossover(decision_vector& child1, decision_vector& child2, pagmo::population::size_type parent1_idx, pagmo::population::size_type parent2_idx,const pagmo::population& pop) const
{

		problem::base::size_type D = pop.problem().get_dimension();
		problem::base::size_type Di = pop.problem().get_i_dimension();
		problem::base::size_type Dc = D - Di;
	const decision_vector &lb = pop.problem().get_lb(), &ub = pop.problem().get_ub();
	const decision_vector& parent1 = pop.get_individual(parent1_idx).cur_x;
	const decision_vector& parent2 = pop.get_individual(parent2_idx).cur_x;
	double y1,y2,yl,yu, rand, beta, alpha, betaq, c1, c2;
	child1 = parent1;
	child2 = parent2;
		int site1, site2;

		//This implements a Simulated Binary Crossover SBX
	if (m_drng() <= m_cr) {
		for (pagmo::problem::base::size_type i = 0; i < Dc; i++) {
			if ( (m_drng() <= 0.5) && (std::fabs(parent1[i]-parent2[i]) ) > 1.0e-14) {
				if (parent1[i] < parent2[i]) {
					y1 = parent1[i];
					y2 = parent2[i];
				} else {
					y1 = parent2[i];
					y2 = parent1[i];
				}
				yl = lb[i];
				yu = ub[i];
				rand = m_drng();

				beta = 1.0 + (2.0*(y1-yl)/(y2-y1));
				alpha = 2.0 - std::pow(beta,-(m_eta_c+1.0));
				if (rand <= (1.0/alpha))
				{
					betaq = std::pow((rand*alpha),(1.0/(m_eta_c+1.0)));
				} else {
					betaq = std::pow((1.0/(2.0 - rand*alpha)),(1.0/(m_eta_c+1.0)));
				}
				c1 = 0.5*((y1+y2)-betaq*(y2-y1));

				beta = 1.0 + (2.0*(yu-y2)/(y2-y1));
				alpha = 2.0 - std::pow(beta,-(m_eta_c+1.0));
				if (rand <= (1.0/alpha))
				{
					betaq = std::pow((rand*alpha),(1.0/(m_eta_c+1.0)));
				} else {
					betaq = std::pow((1.0/(2.0 - rand*alpha)),(1.0/(m_eta_c+1.0)));
				}
				c2 = 0.5*((y1+y2)+betaq*(y2-y1));

				if (c1<lb[i]) c1=lb[i];
				if (c2<lb[i]) c2=lb[i];
				if (c1>ub[i]) c1=ub[i];
				if (c2>ub[i]) c2=ub[i];
				if (m_drng() <= 0.5) {
					child1[i] = c1; child2[i] = c2;
				} else {
					child1[i] = c2; child2[i] = c1;
				}
			}
		}

			}

		//This implements two point binary crossover
		for (pagmo::problem::base::size_type i = Dc; i < D; i++) {
			   if (m_drng() <= m_cr) {
					 boost::uniform_int<int> in_dist(0,Di-1);
					 boost::variate_generator<boost::mt19937 &, boost::uniform_int<int> > ra_num(m_urng,in_dist);
					 site1 = ra_num();
					 site2 = ra_num();
					 if (site1 > site2) std::swap(site1,site2);
					 for(int j=0; j<site1; j++)
					 {
						 child1[j] = parent1[j];
						 child2[j] = parent2[j];
					 }
					 for(int j=site1; j<site2; j++)
					 {
						 child1[j] = parent2[j];
						 child2[j] = parent1[j];
					 }
					 for(pagmo::problem::base::size_type j=site2; j<Di; j++)
					 {
						 child1[j] = parent1[j];
						 child2[j] = parent2[j];
					 }
			  }
			  else {
				   child1[i] = parent1[i];
				   child2[i] = parent2[i];
			  }
	}
}

void nsga2::mutate(decision_vector& child, const pagmo::population& pop) const
{

	problem::base::size_type D = pop.problem().get_dimension();
		problem::base::size_type Di = pop.problem().get_i_dimension();
		problem::base::size_type Dc = D - Di;
	const decision_vector &lb = pop.problem().get_lb(), &ub = pop.problem().get_ub();
	double rnd, delta1, delta2, mut_pow, deltaq;
	double y, yl, yu, val, xy;
		int gen_num;

		//This implements the real polinomial mutation of an individual
	for (pagmo::problem::base::size_type j=0; j < Dc; ++j){
		if (m_drng() <= m_m) {
			y = child[j];
			yl = lb[j];
			yu = ub[j];
			delta1 = (y-yl)/(yu-yl);
			delta2 = (yu-y)/(yu-yl);
			rnd = m_drng();
			mut_pow = 1.0/(m_eta_m+1.0);
			if (rnd <= 0.5)
			{
				xy = 1.0-delta1;
				val = 2.0*rnd+(1.0-2.0*rnd)*(pow(xy,(m_eta_m+1.0)));
				deltaq =  pow(val,mut_pow) - 1.0;
			}
			else
			{
				xy = 1.0-delta2;
				val = 2.0*(1.0-rnd)+2.0*(rnd-0.5)*(pow(xy,(m_eta_m+1.0)));
				deltaq = 1.0 - (pow(val,mut_pow));
			}
			y = y + deltaq*(yu-yl);
			if (y<yl) y = yl;
			if (y>yu) y = yu;
			child[j] = y;
		}
	}

		//This implements the integer mutation for an individual
		 for (pagmo::problem::base::size_type j=Dc; j < D; ++j){
			   if (m_drng() <= m_m) {
						y = child[j];
						yl = lb[j];
						yu = ub[j];
						boost::uniform_int<int> in_dist(yl,yu-1);
						boost::variate_generator<boost::mt19937 &, boost::uniform_int<int> > ra_num(m_urng,in_dist);
						gen_num = ra_num();
						if (gen_num >= y) gen_num = gen_num + 1;
						child[j] = gen_num;
		 }
	  }
}
/// Evolve implementation.
/**
 * Run the NSGA-II algorithm for the number of generations specified in the constructors.
 *
 * @param[in,out] pop input/output pagmo::population to be evolved.
 */

void nsga2::evolve(population &pop) const
{
	// Let's store some useful variables.
	const problem::base &prob = pop.problem();
	const problem::base::size_type D = prob.get_dimension();
	const problem::base::size_type prob_c_dimension = prob.get_c_dimension();
	const population::size_type NP = pop.size();

	//We perform some checks to determine wether the problem/population are suitable for NSGA-II
	if ( prob_c_dimension != 0 ) {
			pagmo_throw(value_error, "The problem is not box constrained and NSGA-II is not suitable to solve it");
	}

	if (NP < 5 || (NP % 4 != 0) ) {
		pagmo_throw(value_error, "for NSGA-II at least 5 individuals in the population are needed and the population size must be a multiple of 4");
	}

	if ( prob.get_f_dimension() < 2 ) {
		pagmo_throw(value_error, "The problem is not multiobjective, try some other algorithm than NSGA-II");
	}

	// Get out if there is nothing to do.
	if (m_gen == 0) {
		return;
	}

	std::vector<population::size_type> best_idx(NP), shuffle1(NP),shuffle2(NP);
	population::size_type parent1_idx, parent2_idx;
	decision_vector child1(D), child2(D);

	for (pagmo::population::size_type i=0; i< NP; i++) shuffle1[i] = i;
	for (pagmo::population::size_type i=0; i< NP; i++) shuffle2[i] = i;

	boost::uniform_int<int> pop_idx(0,NP-1);
	boost::variate_generator<boost::mt19937 &, boost::uniform_int<int> > p_idx(m_urng,pop_idx);

	// Main NSGA-II loop
	for (int g = 0; g<m_gen; g++) {
		//At each generation we make a copy of the population into popnew
		// We compute the crowding distance and the pareto rank of pop
		pop.update_pareto_information();
		population popnew(pop);

		//We create some pseudo-random permutation of the poulation indexes
		std::random_shuffle(shuffle1.begin(),shuffle1.end(),p_idx);
		std::random_shuffle(shuffle2.begin(),shuffle2.end(),p_idx);

		//We then loop thorugh all individuals with increment 4 to select two pairs of parents that will
		//each create 2 new offspring
		for (pagmo::population::size_type i=0; i< NP; i+=4) {
			// We create two offsprings using the shuffled list 1
			parent1_idx = tournament_selection(shuffle1[i], shuffle1[i+1],pop);
			parent2_idx = tournament_selection(shuffle1[i+2], shuffle1[i+3],pop);
			crossover(child1, child2, parent1_idx,parent2_idx,pop);
			mutate(child1,pop);
			mutate(child2,pop);
			popnew.push_back(child1);
			popnew.push_back(child2);

			// We repeat with the shuffled list 2
			parent1_idx = tournament_selection(shuffle2[i], shuffle2[i+1],pop);
			parent2_idx = tournament_selection(shuffle2[i+2], shuffle2[i+3],pop);
			crossover(child1, child2, parent1_idx,parent2_idx,pop);
			mutate(child1,pop);
			mutate(child2,pop);
			popnew.push_back(child1);
			popnew.push_back(child2);
		} // popnew now contains 2NP individuals

		// This method returns the sorted N best individuals in the population according to the crowded comparison operator
		// defined in population.cpp
		best_idx = popnew.get_best_idx(NP);
		// We completely cancel the population (NOTE: memory of all individuals and the notion of
		// champion is thus destroyed)
		pop.clear();
		for (population::size_type i=0; i < NP; ++i) pop.push_back(popnew.get_individual(best_idx[i]).cur_x);
	} // end of main SGA loop
}

/// Algorithm name
std::string nsga2::get_name() const
{
	return "Nondominated Sorting Genetic Algorithm II (NSGA-II)";
}

/// Extra human readable algorithm info.
/**
 * Will return a formatted string displaying the parameters of the algorithm.
 */
std::string nsga2::human_readable_extra() const
{
	std::ostringstream s;
	s << "gen:" << m_gen << ' ';
	s << "cr:" << m_cr << ' ';
	s << "eta_c:" << m_eta_c << ' ';
	s << "m:" << m_m << ' ';
	s << "eta_m:" << m_eta_m << std::endl;

	return s.str();
}

}} //namespaces

BOOST_CLASS_EXPORT_IMPLEMENT(pagmo::algorithm::nsga2)