text:
package e2e_node

import (
	"path"

	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/util/uuid"
	"k8s.io/kubernetes/pkg/kubelet/cm"
	"k8s.io/kubernetes/test/e2e/framework"
	imageutils "k8s.io/kubernetes/test/utils/image"

	"github.com/golang/glog"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

// getResourceList returns a ResourceList with the
// specified cpu and memory resource values
func getResourceList(cpu, memory string) v1.ResourceList {
	res := v1.ResourceList{}
	if cpu != "" {
		res[v1.ResourceCPU] = resource.MustParse(cpu)
	}
	if memory != "" {
		res[v1.ResourceMemory] = resource.MustParse(memory)
	}
	return res
}

// getResourceRequirements returns a ResourceRequirements object
func getResourceRequirements(requests, limits v1.ResourceList) v1.ResourceRequirements {
	res := v1.ResourceRequirements{}
	res.Requests = requests
	res.Limits = limits
	return res
}

const (
	// Kubelet internal cgroup name for burstable tier
	burstableCgroup = "burstable"
	// Kubelet internal cgroup name for besteffort tier
	bestEffortCgroup = "besteffort"
)

// makePodToVerifyCgroups returns a pod that verifies the existence of the specified cgroups.
func makePodToVerifyCgroups(cgroupNames []cm.CgroupName) *v1.Pod {
	// convert the names to their literal cgroupfs forms...
	cgroupFsNames := []string{}
	for _, cgroupName := range cgroupNames {
		// Add top level cgroup used to enforce node allocatable.
		cgroupFsNames = append(cgroupFsNames, toCgroupFsName(path.Join(defaultNodeAllocatableCgroup, string(cgroupName))))
	}
	glog.Infof("expecting %v cgroups to be found", cgroupFsNames)
	// build the pod command to either verify cgroups exist
	command := ""
	for _, cgroupFsName := range cgroupFsNames {
		localCommand := "if [ ! -d /tmp/memory/" + cgroupFsName + " ] || [ ! -d /tmp/cpu/" + cgroupFsName + " ]; then exit 1; fi; "
		command += localCommand
	}

	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name: "pod" + string(uuid.NewUUID()),
		},
		Spec: v1.PodSpec{
			RestartPolicy: v1.RestartPolicyNever,
			Containers: []v1.Container{
				{
					Image:   busyboxImage,
					Name:    "container" + string(uuid.NewUUID()),
					Command: []string{"sh", "-c", command},
					VolumeMounts: []v1.VolumeMount{
						{
							Name:      "sysfscgroup",
							MountPath: "/tmp",
						},
					},
				},
			},
			Volumes: []v1.Volume{
				{
					Name: "sysfscgroup",
					VolumeSource: v1.VolumeSource{
						HostPath: &v1.HostPathVolumeSource{Path: "/sys/fs/cgroup"},
					},
				},
			},
		},
	}
	return pod
}

// makePodToVerifyCgroupRemoved verfies the specified cgroup does not exist.
func makePodToVerifyCgroupRemoved(cgroupName cm.CgroupName) *v1.Pod {
	cgroupFsName := toCgroupFsName(string(cgroupName))
	pod := &v1.Pod{
		ObjectMeta: metav1.ObjectMeta{
			Name: "pod" + string(uuid.NewUUID()),
		},
		Spec: v1.PodSpec{
			RestartPolicy: v1.RestartPolicyOnFailure,
			Containers: []v1.Container{
				{
					Image:   busyboxImage,
					Name:    "container" + string(uuid.NewUUID()),
					Command: []string{"sh", "-c", "for i in `seq 1 10`; do if [ ! -d /tmp/memory/" + cgroupFsName + " ] && [ ! -d /tmp/cpu/" + cgroupFsName + " ]; then exit 0; else sleep 10; fi; done; exit 1"},
					VolumeMounts: []v1.VolumeMount{
						{
							Name:      "sysfscgroup",
							MountPath: "/tmp",
						},
					},
				},
			},
			Volumes: []v1.Volume{
				{
					Name: "sysfscgroup",
					VolumeSource: v1.VolumeSource{
						HostPath: &v1.HostPathVolumeSource{Path: "/sys/fs/cgroup"},
					},
				},
			},
		},
	}
	return pod
}

var _ = framework.KubeDescribe("Kubelet Cgroup Manager", func() {
	f := framework.NewDefaultFramework("kubelet-cgroup-manager")
	Describe("QOS containers", func() {
		Context("On enabling QOS cgroup hierarchy", func() {
			It("Top level QoS containers should have been created", func() {
				if !framework.TestContext.KubeletConfig.CgroupsPerQOS {
					return
				}
				cgroupsToVerify := []cm.CgroupName{cm.CgroupName(burstableCgroup), cm.CgroupName(bestEffortCgroup)}
				pod := makePodToVerifyCgroups(cgroupsToVerify)
				f.PodClient().Create(pod)
				err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name)
				Expect(err).NotTo(HaveOccurred())
			})
		})
	})

	Describe("Pod containers", func() {
		Context("On scheduling a Guaranteed Pod", func() {
			It("Pod containers should have been created under the cgroup-root", func() {
				if !framework.TestContext.KubeletConfig.CgroupsPerQOS {
					return
				}
				var (
					guaranteedPod *v1.Pod
					podUID        string
				)
				By("Creating a Guaranteed pod in Namespace", func() {
					guaranteedPod = f.PodClient().Create(&v1.Pod{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "pod" + string(uuid.NewUUID()),
							Namespace: f.Namespace.Name,
						},
						Spec: v1.PodSpec{
							Containers: []v1.Container{
								{
									Image:     imageutils.GetPauseImageName(),
									Name:      "container" + string(uuid.NewUUID()),
									Resources: getResourceRequirements(getResourceList("100m", "100Mi"), getResourceList("100m", "100Mi")),
								},
							},
						},
					})
					podUID = string(guaranteedPod.UID)
				})
				By("Checking if the pod cgroup was created", func() {
					cgroupsToVerify := []cm.CgroupName{cm.CgroupName("pod" + podUID)}
					pod := makePodToVerifyCgroups(cgroupsToVerify)
					f.PodClient().Create(pod)
					err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name)
					Expect(err).NotTo(HaveOccurred())
				})
				By("Checking if the pod cgroup was deleted", func() {
					gp := int64(1)
					Expect(f.PodClient().Delete(guaranteedPod.Name, &metav1.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred())
					pod := makePodToVerifyCgroupRemoved(cm.CgroupName("pod" + podUID))
					f.PodClient().Create(pod)
					err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name)
					Expect(err).NotTo(HaveOccurred())
				})
			})
		})
		Context("On scheduling a BestEffort Pod", func() {
			It("Pod containers should have been created under the BestEffort cgroup", func() {
				if !framework.TestContext.KubeletConfig.CgroupsPerQOS {
					return
				}
				var (
					podUID        string
					bestEffortPod *v1.Pod
				)
				By("Creating a BestEffort pod in Namespace", func() {
					bestEffortPod = f.PodClient().Create(&v1.Pod{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "pod" + string(uuid.NewUUID()),
							Namespace: f.Namespace.Name,
						},
						Spec: v1.PodSpec{
							Containers: []v1.Container{
								{
									Image:     imageutils.GetPauseImageName(),
									Name:      "container" + string(uuid.NewUUID()),
									Resources: getResourceRequirements(getResourceList("", ""), getResourceList("", "")),
								},
							},
						},
					})
					podUID = string(bestEffortPod.UID)
				})
				By("Checking if the pod cgroup was created", func() {
					cgroupsToVerify := []cm.CgroupName{cm.CgroupName("besteffort/pod" + podUID)}
					pod := makePodToVerifyCgroups(cgroupsToVerify)
					f.PodClient().Create(pod)
					err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name)
					Expect(err).NotTo(HaveOccurred())
				})
				By("Checking if the pod cgroup was deleted", func() {
					gp := int64(1)
					Expect(f.PodClient().Delete(bestEffortPod.Name, &metav1.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred())
					pod := makePodToVerifyCgroupRemoved(cm.CgroupName("besteffort/pod" + podUID))
					f.PodClient().Create(pod)
					err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name)
					Expect(err).NotTo(HaveOccurred())
				})
			})
		})
		Context("On scheduling a Burstable Pod", func() {
			It("Pod containers should have been created under the Burstable cgroup", func() {
				if !framework.TestContext.KubeletConfig.CgroupsPerQOS {
					return
				}
				var (
					podUID       string
					burstablePod *v1.Pod
				)
				By("Creating a Burstable pod in Namespace", func() {
					burstablePod = f.PodClient().Create(&v1.Pod{
						ObjectMeta: metav1.ObjectMeta{
							Name:      "pod" + string(uuid.NewUUID()),
							Namespace: f.Namespace.Name,
						},
						Spec: v1.PodSpec{
							Containers: []v1.Container{
								{
									Image:     imageutils.GetPauseImageName(),
									Name:      "container" + string(uuid.NewUUID()),
									Resources: getResourceRequirements(getResourceList("100m", "100Mi"), getResourceList("200m", "200Mi")),
								},
							},
						},
					})
					podUID = string(burstablePod.UID)
				})
				By("Checking if the pod cgroup was created", func() {
					cgroupsToVerify := []cm.CgroupName{cm.CgroupName("burstable/pod" + podUID)}
					pod := makePodToVerifyCgroups(cgroupsToVerify)
					f.PodClient().Create(pod)
					err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name)
					Expect(err).NotTo(HaveOccurred())
				})
				By("Checking if the pod cgroup was deleted", func() {
					gp := int64(1)
					Expect(f.PodClient().Delete(burstablePod.Name, &metav1.DeleteOptions{GracePeriodSeconds: &gp})).NotTo(HaveOccurred())
					pod := makePodToVerifyCgroupRemoved(cm.CgroupName("burstable/pod" + podUID))
					f.PodClient().Create(pod)
					err := framework.WaitForPodSuccessInNamespace(f.ClientSet, pod.Name, f.Namespace.Name)
					Expect(err).NotTo(HaveOccurred())
				})
			})
		})
	})
})

redpajama_set_name: RedPajamaGithub


text:
package json.bind.hearthstone;

import org.apache.commons.math3.stat.regression.OLSMultipleLinearRegression;
import org.junit.Test;

/**
 * Created by jimb on 4/28/2015.
 */
public class OLSTest {

    @Test
    public void testSimpleOLS(){
        OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression();
        //double [] manaCost = {4,6,6,3,1,0,4,1};
        //double [] [] x = new double[8][];

        double [] manaCost = {4,6,6,3,1}; // mana cost is y intercept
        double [] [] x = new double[5][];

        //atk,health,charge,divine
        double [] korkon = new double []{4,3,1,0};
        x[0] = korkon;
        double [] reckless = new double []{5,2,1,0};
        x[1] = reckless;
        double [] commander = new double []{4,2,1,1};
        x[2] = commander;
        double [] scarlet = new double []{3,1,0,1};
        x[3] = scarlet;
        double [] squire = new double []{1,1,0,1};
        x[4] = squire;

        /*double [] wisp = new double []{1,1,0,0};
        x[5] = wisp;
        double [] silvermoon = new double []{3,3,0,1};
        x[6] = silvermoon;
        double [] divine = new double []{0,0,0,1};
        x[7] = divine;*/

        ols.newSampleData(manaCost, x);

        double[] regressionParameters = ols.estimateRegressionParameters();

        for (int i = 0; i < regressionParameters.length; i++) {
            double regressionParameter = regressionParameters[i];
            System.out.println(i + " " + regressionParameter);
        }

        System.out.println("Korkon: " + calculateValue(korkon, regressionParameters));
        System.out.println("Reckless: " + calculateValue(reckless, regressionParameters));
        System.out.println("Commander: " + calculateValue(commander, regressionParameters));
        System.out.println("Scarlet: " + calculateValue(scarlet, regressionParameters));
        System.out.println("Squire: " + calculateValue(squire, regressionParameters));
        /*System.out.println("Wisp: " + calculateValue(wisp, regressionParameters));
        System.out.println("Silvermoon: " + calculateValue(silvermoon, regressionParameters));
        System.out.println("Divine: " + calculateValue(divine, regressionParameters));*/
    }

    double calculateValue(double[] card, double[] regressionParameters){
        //regression param 0 is y intercept
        //1 = atk
        //2 = health
        //3 = charge
        //4 = shield

        return card[0] * regressionParameters[1] //attack
                    + card[1] * regressionParameters[2] //health
                + card[2] * regressionParameters[3] * regressionParameters[1] //charge
                + card[3] * regressionParameters[4];// * regressionParameters[1] * 1.1; //divine shield // * attack * extra health
    }

    //from http://bitingcode.blogspot.com/2012/01/simplest-olsmultiplelinearregression.html
    @Test
    public void anotherSimpleOLS(){
        OLSMultipleLinearRegression ols = new OLSMultipleLinearRegression();

        double[] data = { 2, 1, 4, 2 }; // 1
        double[] y = {4,6}  ;
        double [] [] x = new double[2][];
        x[0] = new double []{1};
        x[1] = new double []{2};

        int obs = 2;
        int vars = 1; // 2
        try {
            //ols.newSampleData(data, obs, vars); // 3
            ols.newSampleData(y, x);
        }
        catch(IllegalArgumentException e) {
            System.out.print("Can't sample data: ");
            e.printStackTrace();
            return;
        }

        double[] coe = null;
        try {
            //0=0
            //1=2
            coe = ols.estimateRegressionParameters(); // 4
        }
        catch(IllegalArgumentException e) { // 5
            System.out.print("Can't estimate parameters: ");
            e.printStackTrace();
            return;
        }

        dumpEstimation(coe);
    }

    private void dumpEstimation(double[] coe) {
        if(coe == null)
            return;

        for(double d : coe)
            System.out.print(d + " ");
        System.out.println();

        System.out.println("Estimations:");
        System.out.println("x = 0, y = " + calculateEstimation(0, coe));
        System.out.println("x = 1, y = " + calculateEstimation(1, coe));
        System.out.println("x = 2, y = " + calculateEstimation(2, coe));
        System.out.println("x = 3, y = " + calculateEstimation(3, coe));
        System.out.println("x = 4, y = " + calculateEstimation(4, coe));
    }

    private double calculateEstimation(double x, double[] coe) {
        double result = 0;
        for(int i = 0; i < coe.length; ++i)
            result += coe[i] * Math.pow(x, i); // 1
        return result;
    }

    //http://stackoverflow.com/questions/14533475/using-least-square-method-with-commons-math-and-fitting
    @Test
    public void helpMeUnderstandEstimateRegressionParamters(){
        OLSMultipleLinearRegression regression2 = new OLSMultipleLinearRegression();
        double[] y = {
                4,
                8,
                13,
                18
        };
        double[][] x2 =
                {
                        { 1, 1, 1  },
                        { 1, 2, 4  },
                        { 1, 3, 9  },
                        { 1, 4, 16  },
                };

        regression2.newSampleData(y, x2);
        regression2.setNoIntercept(true);
        regression2.newSampleData(y, x2);
        double[] beta = regression2.estimateRegressionParameters();
        for (double d : beta) {
            System.out.println("D: " + d);
        }
    }

}


text:
<?php
namespace Intuit\V1\Rpc\MFARequestForRefresh;

class MFARequestForRefreshControllerFactory
{
    public function __invoke($controllers)
    {
        return new MFARequestForRefreshController();
    }
}


text:
class Event < ApplicationRecord
  belongs_to :community
  belongs_to :location
  has_many :friend_event_attendances, dependent: :destroy
  has_many :user_event_attendances, dependent: :destroy
  has_many :users, through: :user_event_attendances
  has_many :friends, through: :friend_event_attendances
  validates :date, :location_id, :title, :category, :community_id, presence: true

  CATEGORIES = %w[pro_se_clinic sijs_clinic asylum_workshop asylum_training accompaniment_training social].map { |category| [category.titlecase, category] }

  def user_attendances
    user_event_attendances.includes(:user).order('created_at asc')
  end

  def friend_attendances
    friend_event_attendances.includes(:friend).order('created_at asc')
  end

  def self.between_dates(start_date, end_date)
    where('date > ? AND date < ?', start_date, end_date)
  end

  def friend_attending?(friend)
    FriendEventAttendance.where(event_id: id, friend_id: friend.id).present?
  end

  def self.pro_se_clinics_at_dates(start_dates)
    events = []
    start_dates.each do |start_date|
      event = Event.where(category: 'pro_se_clinic')
                        .between_dates(start_date, start_date.end_of_day)
                        .first
      events << event if event
    end
    events
  end
end


text:
module Haystack
  class Aggregator
    class PostProcessor
      attr_reader :transactions

      def initialize(transactions)
        @transactions = transactions
      end

      def post_processed_queue!
        transactions.map do |transaction|
          transaction.events.each do |event|
            Haystack.post_processing_middleware.invoke(event)
          end
          transaction.to_hash
        end
      end

      def self.default_middleware
        Middleware::Chain.new do |chain|
          chain.add Haystack::Aggregator::Middleware::DeleteBlanks
          if defined?(::ActionView)
            chain.add Haystack::Aggregator::Middleware::ActionViewSanitizer
          end
          if defined?(::ActiveRecord)
            chain.add Haystack::Aggregator::Middleware::ActiveRecordSanitizer
          end
        end
      end
    end
  end
end


text:
namespace nwc_toolkit {

class TokenMap {
 public:
  TokenMap() : pool_(), map_(), tokens_() {}
  ~TokenMap() {
    Clear();
  }

  int operator[](const String &token) const {
    return map_.find(token)->second;
  }
  const String &operator[](int token_id) const {
    return tokens_[token_id];
  }

  std::size_t num_tokens() const {
    return tokens_.size();
  }

  void Clear() {
    pool_.Clear();
    map_.clear();
    tokens_.clear();
  }

  int Insert(const String &token) {
    MapType::iterator it = map_.find(token);
    if (it != map_.end()) {
      return it->second;
    }
    int token_id = static_cast<int>(num_tokens());
    String token_clone = pool_.Append(token);
    map_[token_clone] = token_id;
    tokens_.push_back(token_clone);
    return token_id;
  }

 private:
  typedef std::tr1::unordered_map<String, int, StringHash> MapType;

  StringPool pool_;
  MapType map_;
  std::vector<String> tokens_;

  // Disallows copy and assignment.
  TokenMap(const TokenMap &);
  TokenMap &operator=(const TokenMap &);
};

}  // namespace nwc_toolkit

#endif  // NWC_TOOLKIT_TOKEN_MAP_H_


text:
These demos are a proof of concept to demonstrate that SVG filter effects can serve as some form of "CSS for type", making it possible to create sophisticated display typography with pure web technologies.

## Basic Effects:

The directory "basic-effects" contains the building blocks that can be used to onstruct a sophisticated SVG filter.

## Sophisticated Effects:

Examples of sophisticated filter effects constructed by combining multiple modules.

The directory "SVG" contains filters applied to SVG text.

The directory "HTML" contains the same filters, this time  applied to HTML Text


text:
/*
 * 2520 is the smallest number that can be divided by each of the numbers from 1 to 10
 * without any remainder.
 *
 * What is the smallest positive number that is evenly divisible by all of the numbers
 * from 1 to 20?
 */
#ifndef PROBLEM0005_HPP__
#define PROBLEM0005_HPP__

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <numeric>
#include <map>
#include <cmath>
#include "trial_division.hpp"

long problem5()
{
  vector<long> factors(19);
  iota(factors.begin(), factors.end(), 2);
  vector<vector<long>> prime_factors;

  for (auto x : factors)
  {
    prime_factors.push_back(vector<long>());
    trial_division(x, back_inserter(prime_factors.back()));
  }

  vector<long> unique_factors;

  for (auto element_prime_factors : prime_factors)
  {
    for (auto element_factor : element_prime_factors)
    {
      if (count(unique_factors.begin(), unique_factors.end(), element_factor) == 0)
      {
        unique_factors.push_back(element_factor);
      }
    }

    sort(unique_factors.begin(), unique_factors.end());
  }

  map<long, long> factor_powers_map;

  for_each(unique_factors.begin(), unique_factors.end(), [&](long x) { factor_powers_map.insert(make_pair(x, 0UL)); });

  for_each(unique_factors.begin(), unique_factors.end(),
    [&](long x)
    {
      for (auto element_prime_factors : prime_factors)
      {
        auto factor_exponent = count(element_prime_factors.begin(), element_prime_factors.end(), x);

        if (factor_exponent > factor_powers_map[x])
        {
          factor_powers_map[x] = factor_exponent;
        }
      };
    });

  return accumulate(factor_powers_map.begin(), factor_powers_map.end(), 1L,
    [](long previous, const pair<long, long>& factor_with_power)
    {
      return previous *= pow(factor_with_power.first, factor_with_power.second);
    });
}

#endif


text:
ActiveRecord::Schema.define(:version => 1) do

  create_table "authors", :force => true do |t|
    t.column "first_name", :string
    t.column "last_name", :string
    t.column "birth_date", :date
    t.column "created_at", :datetime
    t.column "updated_at", :datetime
  end

  create_table "authors_books", :force => true do |t|
    t.column "author_id", :integer
    t.column "book_id", :integer
  end

  create_table "books", :force => true do |t|
    t.column "title", :string
    t.column "isbn", :string
    t.column "publication_date", :date
    t.column "publisher_id", :integer, :default => 1
    t.column "created_at", :datetime
    t.column "updated_at", :datetime
  end

  create_table "categories", :force => true do |t|
    t.column "name", :string, :limit => 64
    t.column "description", :string
  end

  create_table "categorizations", :force => true do |t|
    t.column "category_id", :integer
    t.column "book_id", :integer
    t.column "created_at", :datetime
    t.column "updated_at", :datetime
  end

  create_table "publishers", :force => true do |t|
    t.column "name", :string
    t.column "created_at", :datetime
    t.column "updated_at", :datetime
  end

end


text:
# Custom Page Templates

There are a few ways to manage custom pages in WordPress and Timber, in order from simple-to-complex:

### Custom Twig File
Say you've created a page called "About Us" and WordPress has given it the slug `about-us`. If you're using the [Timber Starter Theme](https://github.com/Upstatement/timber-starter-theme) you can simply...
- Create a file called `page-about-us.twig` inside your `views` and go crazy.
- I recommend copying-and-pasting the contents of [`page.twig`](https://github.com/Upstatement/timber-starter-theme/blob/master/views/page.twig) into here so you have something to work from.

##### How does this work?
In the `page.php` file you'll see this code...
```php
Timber::render(array('page-' . $post->post_name . '.twig', 'page.twig'), $context);
```
Which is telling PHP to first look for a twig file named `page-{{slug}}.twig` and falling back to [`page.twig`](https://github.com/Upstatement/timber-starter-theme/blob/master/views/page.twig) if that doesn't exist.

* * *

### Custom PHP File
If you need to do something special for this page in PHP, you can use standard WordPress [template hierarchy](http://codex.wordpress.org/Template_Hierarchy) to gather and manipulate data for this page. In the above example, you would create a file called `/wp-content/themes/my-theme/page-about-us.php` and populate it with the necessary PHP. Again, you can use the contents of the starter theme's [`page.php`](https://github.com/Upstatement/timber-starter-theme/blob/master/page.php) file as a guide.

* * *

### Custom Page Template
```php
<?php
/*
 * Template Name: My Custom Page
 * Description: A Page Template with a darker design.
 */

// Code to display Page goes here...
```

In the WordPress admin, this will now display in your page's list of available templates like so:

![wordpress custom page template chooser](http://codex.wordpress.org/images/thumb/a/a3/page-templates-pulldown-screenshot.png/180px-page-templates-pulldown-screenshot.png)

I recommend naming it something like `/wp-content/themes/my-theme/template-my-custom-page.php`. Do NOT name it something beginning with `page-` or WP will get very confused. Here's [an example of what the PHP in this file](https://github.com/Upstatement/blades/blob/master/template-person.php) looks like.


text:
import bookmarks, phases, obsolete

def _nslist(repo):
    n = {}
    for k in _namespaces:
        n[k] = ""
    if not obsolete._enabled:
        n.pop('obsolete')
    return n

_namespaces = {"namespaces": (lambda *x: False, _nslist),
               "bookmarks": (bookmarks.pushbookmark, bookmarks.listbookmarks),
               "phases": (phases.pushphase, phases.listphases),
               "obsolete": (obsolete.pushmarker, obsolete.listmarkers),
              }

def register(namespace, pushkey, listkeys):
    _namespaces[namespace] = (pushkey, listkeys)

def _get(namespace):
    return _namespaces.get(namespace, (lambda *x: False, lambda *x: {}))

def push(repo, namespace, key, old, new):
    '''should succeed iff value was old'''
    pk = _get(namespace)[0]
    return pk(repo, key, old, new)

def list(repo, namespace):
    '''return a dict'''
    lk = _get(namespace)[1]
    return lk(repo)


text:
define('ace/snippets/golang', ['require', 'exports', 'module' ], function(require, exports, module) {

exports.snippetText = "";
exports.scope = "golang";

});


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>logo generator</title>
<meta name="Keywords" content="">
<meta name="Description" content="">

    <canvas id="canvas" width="180" height="180" style="border:1px solid blue;"></canvas>

    <input type="button"  value="ToPNG" onClick="addToGallery()">

    Download


text:
namespace base {

namespace {

void wakeup_callback(uv_async_t* handle, int status) {
  // do nothing, just make libuv exit loop.
}

void idle_callback(uv_idle_t* handle, int status) {
  // do nothing, just make libuv exit loop.
}

void timer_callback(uv_timer_t* timer, int status) {
  // libuv would block unexpectedly with zero-timeout timer
  // this is a workaround of libuv bug #574:
  // https://github.com/joyent/libuv/issues/574
  uv_idle_start(static_cast<uv_idle_t*>(timer->data), idle_callback);
}

}  // namespace

MessagePumpUV::MessagePumpUV()
    : keep_running_(true),
      nesting_level_(0) {
  wakeup_events_.push(uv_async_t());
  uv_async_init(uv_default_loop(), &wakeup_events_.top(), wakeup_callback);
}

MessagePumpUV::~MessagePumpUV() {
}

void MessagePumpUV::Run(Delegate* delegate) {
  v8::HandleScope scope;

  ++nesting_level_;
  DCHECK(keep_running_) << "Quit must have been called outside of Run!";

  // Poll external loop in nested message loop, so node.js's events will be
  // paused in nested loop.
  uv_loop_t* loop = uv_default_loop();
  if (nesting_level_ > 1) {
    loop = uv_loop_new();

    wakeup_events_.push(uv_async_t());
    uv_async_init(loop, &wakeup_events_.top(), wakeup_callback);
  }

  // Create handles for the loop.
  uv_idle_t idle_handle;
  uv_idle_init(loop, &idle_handle);

  uv_timer_t delay_timer;
  delay_timer.data = &idle_handle;
  uv_timer_init(loop, &delay_timer);

  // Enter Loop
  for (;;) {
    bool did_work = delegate->DoWork();
    if (!keep_running_)
      break;

    did_work |= delegate->DoDelayedWork(&delayed_work_time_);
    if (!keep_running_)
      break;

    if (did_work)
      continue;

    did_work = delegate->DoIdleWork();
    if (!keep_running_)
      break;

    if (did_work)
      continue;

    // Enter node context while dealing with uv events.
    v8::Context::Scope context_scope(node::g_context);

    if (delayed_work_time_.is_null()) {
      uv_run_once(loop);
    } else {
      TimeDelta delay = delayed_work_time_ - TimeTicks::Now();
      if (delay > TimeDelta()) {
        uv_timer_start(&delay_timer, timer_callback,
                       delay.InMilliseconds(), 0);
        uv_run_once(loop);
        uv_idle_stop(&idle_handle);
        uv_timer_stop(&delay_timer);
      } else {
        // It looks like delayed_work_time_ indicates a time in the past, so we
        // need to call DoDelayedWork now.
        delayed_work_time_ = TimeTicks();
      }
    }
    // Since event_ is auto-reset, we don't need to do anything special here
    // other than service each delegate method.
  }

  if (nesting_level_ > 1) {
    // Delete external loop.
    uv_loop_delete(loop);

    // Restore previous async handle.
    wakeup_events_.pop();
  }

  keep_running_ = true;
  --nesting_level_;
}

void MessagePumpUV::Quit() {
  keep_running_ = false;
}

void MessagePumpUV::ScheduleWork() {
  // Since this can be called on any thread, we need to ensure that our Run
  // loop wakes up.
  uv_async_send(&wakeup_events_.top());
}

void MessagePumpUV::ScheduleDelayedWork(
    const TimeTicks& delayed_work_time) {
  // We know that we can't be blocked on Wait right now since this method can
  // only be called on the same thread as Run, so we only need to update our
  // record of how long to sleep when we do sleep.
  delayed_work_time_ = delayed_work_time;
}

}  // namespace base


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2010-2019 Evolveum and contributors
  ~
  ~ This work is dual-licensed under the Apache License 2.0
  ~ and European Union Public License. See LICENSE file for details.
  -->

<shadow oid="c0c010c0-d34d-b44f-f11d-3332eeff0001"
    xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:icfs="http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/resource-schema-3"
    xmlns:ri="http://midpoint.evolveum.com/xml/ns/public/resource/instance/ef2bc95b-76e0-59e2-86d6-9999dddddddd">
    <name>bargain</name>
    <resourceRef oid="ef2bc95b-76e0-59e2-86d6-9999dddddddd" />
    <objectClass>ri:CustomprivilegeObjectClass</objectClass>
    <kind>entitlement</kind>
    <intent>privilege</intent>
    <attributes>
        <icfs:name>bargain</icfs:name>
    </attributes>
</shadow>


text:
.class Lcom/android/server/connectivity/Tethering$TetherMasterSM$ErrorState;
.super Lcom/android/internal/util/State;
.source "Tethering.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/connectivity/Tethering$TetherMasterSM;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "ErrorState"
.end annotation

# instance fields
.field mErrorNotification:I

.field final synthetic this$1:Lcom/android/server/connectivity/Tethering$TetherMasterSM;

# direct methods
.method constructor <init>(Lcom/android/server/connectivity/Tethering$TetherMasterSM;)V
    .locals 0

    .prologue
    .line 3003
    iput-object p1, p0, Lcom/android/server/connectivity/Tethering$TetherMasterSM$ErrorState;->this$1:Lcom/android/server/connectivity/Tethering$TetherMasterSM;

    invoke-direct {p0}, Lcom/android/internal/util/State;-><init>()V

    return-void
.end method

# virtual methods
.method notify(I)V
    .locals 4
    .param p1, "msgType"    # I

    .prologue
    .line 3020
    iput p1, p0, Lcom/android/server/connectivity/Tethering$TetherMasterSM$ErrorState;->mErrorNotification:I

    .line 3021
    iget-object v3, p0, Lcom/android/server/connectivity/Tethering$TetherMasterSM$ErrorState;->this$1:Lcom/android/server/connectivity/Tethering$TetherMasterSM;

    # getter for: Lcom/android/server/connectivity/Tethering$TetherMasterSM;->mNotifyList:Ljava/util/ArrayList;
    invoke-static {v3}, Lcom/android/server/connectivity/Tethering$TetherMasterSM;->access$7400(Lcom/android/server/connectivity/Tethering$TetherMasterSM;)Ljava/util/ArrayList;

    move-result-object v3

    invoke-virtual {v3}, Ljava/util/ArrayList;->iterator()Ljava/util/Iterator;

    move-result-object v0

    .local v0, "i$":Ljava/util/Iterator;
    :goto_0
    invoke-interface {v0}, Ljava/util/Iterator;->hasNext()Z

    move-result v3

    if-eqz v3, :cond_0

    invoke-interface {v0}, Ljava/util/Iterator;->next()Ljava/lang/Object;

    move-result-object v1

    check-cast v1, Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;

    .local v1, "o":Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;
    move-object v2, v1

    .line 3022
    check-cast v2, Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;

    .line 3023
    .local v2, "sm":Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;
    invoke-virtual {v2, p1}, Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;->sendMessage(I)V

    goto :goto_0

    .line 3025
    .end local v1    # "o":Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;
    .end local v2    # "sm":Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;
    :cond_0
    return-void
.end method

.method public processMessage(Landroid/os/Message;)Z
    .locals 5
    .param p1, "message"    # Landroid/os/Message;

    .prologue
    .line 3007
    const-string v2, "Tethering"

    new-instance v3, Ljava/lang/StringBuilder;

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

    const-string v4, "[MSM_Error]["

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget-object v4, p0, Lcom/android/server/connectivity/Tethering$TetherMasterSM$ErrorState;->this$1:Lcom/android/server/connectivity/Tethering$TetherMasterSM;

    # getter for: Lcom/android/server/connectivity/Tethering$TetherMasterSM;->mName:Ljava/lang/String;
    invoke-static {v4}, Lcom/android/server/connectivity/Tethering$TetherMasterSM;->access$4900(Lcom/android/server/connectivity/Tethering$TetherMasterSM;)Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    const-string v4, "] processMessage what="

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    iget v4, p1, Landroid/os/Message;->what:I

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Lcom/mediatek/xlog/Xlog;->i(Ljava/lang/String;Ljava/lang/String;)I

    .line 3008
    const/4 v0, 0x1

    .line 3009
    .local v0, "retValue":Z
    iget v2, p1, Landroid/os/Message;->what:I

    packed-switch v2, :pswitch_data_0

    .line 3015
    const/4 v0, 0x0

    .line 3017
    :goto_0
    return v0

    .line 3011
    :pswitch_0
    iget-object v1, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v1, Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;

    .line 3012
    .local v1, "who":Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;
    iget v2, p0, Lcom/android/server/connectivity/Tethering$TetherMasterSM$ErrorState;->mErrorNotification:I

    invoke-virtual {v1, v2}, Lcom/android/server/connectivity/Tethering$TetherInterfaceSM;->sendMessage(I)V

    goto :goto_0

    .line 3009
    :pswitch_data_0
    .packed-switch 0x1
        :pswitch_0
    .end packed-switch
.end method


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Helmisporium teretiusculum Sacc. & Berl.

### Remarks
null


text:
<?php

use PHPieces\Framework\Util\File;

class FileTest extends \PHPUnit_Framework_TestCase
{
    private $temp_dir;

    public function setUp()
    {
        parent::setUp(); // TODO: Change the autogenerated stub

        $this->temp_dir = __DIR__.'/../data/temp';

        mkdir($this->temp_dir);
    }

    public function tearDown()
    {
         $files = glob($this->temp_dir.'/*'); // get all file names
        foreach($files as $file){ // iterate files
            if(is_file($file))
                unlink($file); // delete file
        }

        rmdir($this->temp_dir);

        parent::tearDown(); // TODO: Change the autogenerated stub
    }

    /**
     * @test
     */
    public function it_gets_the_contents_of_a_file()
    {
        $file = new File();

        $path = $this->temp_dir .'/temp.txt';

        $content = 'foo bar';

        file_put_contents($path, $content);

        $this->assertEquals($content, $file->get($path));
    }

    /**
     * @test
     */
    public function it_writes_content_to_file()
    {
        $file = new File();

        $path = $this->temp_dir .'/temp.txt';

        $content = 'foo bar';

        $file->put($path, $content);

        $this->assertEquals($content, file_get_contents($path));
    }

    /**
     * @test
     */
    public function it_checks_if_file_exists()
    {
        $file = new File();

        $path = $this->temp_dir .'/temp.txt';

        $content = 'foo bar';

        file_put_contents($path, $content);

        $this->assertTrue($file->exists($path));
    }
}


text:
Macro {
  description="PgDn: never scroll beyond EOF (like in FAR 1.70 beta 4 and earlier)";
  area="Viewer";
  key="PgDn Num3";
  action=function()
    Keys("AKey")
    if Object.Eof then
      Keys("End")
    end
  end;
}


text:
wedge
=====
A drop-dead simple lightbox.

[Demo](http://matthewsot.github.com/wedge)

How to use
==========
To use wedge, just use wedge.show:

```
wedge.show(link, options);
```

``link`` is a string, containing an element selector (like ``#id``), youtube link, or image link.

```options``` is an object with any number of properties, all of which are optional:

```
wedge.options = {
    animator: fadeAnimation, //The animation to use
    allowExit: true, //Whether to allow exiting the wedge
    exitOnEscape: true, //Whether pressing "Escape" should exit the wedge
    exitOnClick: true, //Whether clicking the overlay should exit the wedge
    title: "", //The title to be displayed below the wedge
    type: "element", //The type of the wedge, either "element", "image", or "youtube"
    opacity: 0.9, //The opacity of the overlay
    autoPositionType: 1, //The auto positioner to use. 0 is none/custom, 1 is auto, and 2 is experimental
    positioner: function() { }, //The positioner to use
    overlayId: "wedge-overlay", //The ID to use for the overlay
    contentId: "wedge-content" //The ID to use for the content container
};
```

### Custom Animators
Wedge supports custom animators. All you need to do is create an object with two function properties:
```
var yourAnimation = {};
yourAnimation.animateIn = function (overlay, content, completed) {
    //Complete the animation on $(overlay) and $(content), then call completed
};

yourAnimation.animateOut = function (overlay, content, completed) {
    //Complete the animation on $(overlay) and $(content), then call completed
};
```

### Types
Wedge will attempt to auto-determine the type of link, but if you'd like to override that you can pass the ```type``` option.

### Positioners
I'd recommend leaving ``options.autoPositionType: 1`` unless you have major problems with the positioner.

If you do have problems, try ``options.autoPositionType: 2``. To use a custom positioner, set ``options.autoPositionType: 0`` and provide an ``options.positioner``:

```
var options = {
    autoPositionType: 0,
    positioner: function (content) {
        //position $(content) however you'd like
    }
}
```

## Dependencies
jQuery is the only requirement to use wedge, which contains the basic lightbox and two animations (fadeAnimation and slideAnimation).

If you'd like to use the animations in animations.js (such as scaleAnimation and rotateAnimation), you'll need to add the jquery.gsap plugin to your site. Instructions for that can be found [here](http://www.greensock.com/jquery-gsap-plugin/).


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using FluentAssertions;
using NUnit.Framework;
using Toscana.Common;

namespace Toscana.Tests
{
    public class GithubRepositoryTests
    {
        public const string GithubRepositoryZip = "https://github.com/qualisystems/tosca/archive/master.zip";

        private class GithubRepositoryTestCasesFactory
        {
            public static IEnumerable TestCases
            {
                get
                {
                    return GetYamlFilesFromZippedUrl(GithubRepositoryZip);
                }
            }

            private static IEnumerable GetYamlFilesFromZippedUrl(string repositoryUrl)
            {
                return GetYamlFilesContentFromUrl(repositoryUrl, IsYaml);
            }

            public static List<FileContent> GetYamlFilesContentFromUrl(string repositoryUrl, Func<ZipArchiveEntry, bool> filesFilter)
            {
                using (var tempFile = new TempFile(Path.GetTempPath()))
                using (var client = new WebClient())
                {
                    client.DownloadFile(repositoryUrl, tempFile.FilePath);

                    using (var zipToOpen = new FileStream(tempFile.FilePath, FileMode.Open))
                    using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
                    {
                        return archive.Entries
                            .Where(filesFilter)
                            .Select(ReadFileContent)
                            .ToList();
                    }
                }
            }

            public static bool IsYaml(ZipArchiveEntry a)
            {
                return Path.GetExtension(a.Name).EqualsAny(".yaml", ".yml");
            }

            private static FileContent ReadFileContent(ZipArchiveEntry archiveEntry)
            {
                using (var streamReader = new StreamReader(archiveEntry.Open()))
                {
                    return new FileContent(archiveEntry.Name, streamReader.ReadToEnd());
                }
            }
        }

        private class LocalDirectoryTestCasesFactory
        {
            public static IEnumerable TestCases
            {
                get
                {
                    return GetYamlFilesFromLocalDirectory(@"C:\work\github\tosca");
                }
            }

            private static IEnumerable GetYamlFilesFromLocalDirectory(string directoryPath)
            {
                return GetYamlFilesContentFromDirectory(directoryPath);
            }

            public static List<TestCaseData> GetYamlFilesContentFromDirectory(string directoryPath)
            {
                return Directory.EnumerateFiles(directoryPath).Where(a =>
                    Path.GetExtension(a).EqualsAny(".yaml", ".yml"))
                    .Select(ReadFileContent)
                    .Select(_=>new TestCaseData(_))
                    .ToList();
            }

            private static FileContent ReadFileContent(string filePath)
            {
                using (var streamReader = File.OpenText(filePath))
                {
                    return new FileContent(filePath, streamReader.ReadToEnd());
                }
            }
        }

        [Test, TestCaseSource(typeof (GithubRepositoryTestCasesFactory), "TestCases")]
        public void Validate_Tosca_Files_In_Github_Repository_Of_Quali(FileContent fileContent)
        {
            string toscaAsString = fileContent.Content;
            using (var memoryStream = toscaAsString.ToMemoryStream())
            {
                ToscaServiceTemplate.Load(memoryStream);
            }
        }

        [Test, TestCaseSource(typeof(LocalDirectoryTestCasesFactory), "TestCases")]
        public void Validate_Tosca_Files_In_Local_Directory(FileContent fileContent)
        {
            using (var memoryStream = fileContent.Content.ToMemoryStream())
            {
                ToscaServiceTemplate.Load(memoryStream);
            }
        }

        [Test]
        public void Build_Combined_Tosca_Service_Template_From_Github_Repo()
        {
            var filesContent = GithubRepositoryTestCasesFactory.GetYamlFilesContentFromUrl(GithubRepositoryZip, GithubRepositoryTestCasesFactory.IsYaml);
            var toscaSimpleProfileBuilder = new ToscaServiceTemplateBuilder();
            foreach (var fileContent in filesContent)
            {
                using (var memoryStream = fileContent.Content.ToMemoryStream())
                {
                    toscaSimpleProfileBuilder.Append(memoryStream);
                }
            }
            toscaSimpleProfileBuilder.Build();
        }

        [Test]
        [Ignore]
        public void Load_Tosca_Cloud_Service_Archive_From_Github()
        {
            using (var tempFile = new TempFile(Path.GetTempPath()))
            using (var client = new WebClient())
            {
                client.DownloadFile(GithubRepositoryZip, tempFile.FilePath);

                var toscaCloudServiceArchive = ToscaCloudServiceArchive.Load(tempFile.FilePath);

                var entryLeafNodeTypes = toscaCloudServiceArchive.GetEntryLeafNodeTypes();
                entryLeafNodeTypes.Should().HaveCount(1);
                var nxosNodeType = entryLeafNodeTypes.Single().Value;
                nxosNodeType.Properties.Should().ContainKey("device_owner");
            }
        }
    }
}


text:
/* eslint-env node */
'use strict';

module.exports = {
  name: 'ember-cli-hoverintent',

  included: function (app) {
    this._super.included.apply(this, arguments);

    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }

    app.import(app.bowerDirectory + '/hoverintentjs/dist/hoverintent.min.js');
    app.import('vendor/shims/hoverintent.js');
  }
};


text:
#include "NeonDepthwiseConv.h"
#include "paddle/legacy/function/ConvOp.h"

namespace paddle {

#if defined(__ARM_NEON__) || defined(__ARM_NEON)

template <DeviceType Device>
class NeonDepthwiseConvFunction : public ConvFunctionBase {
 public:
  void init(const FuncConfig& config) override {
    ConvFunctionBase::init(config);
  }

  void check(const BufferArgs& inputs, const BufferArgs& outputs) override {
    const TensorShape& input = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& output = outputs[0].shape();
    checkShape(input, filter, output);
  }

  void calc(const BufferArgs& inputs, const BufferArgs& outputs) override {
    CHECK_EQ(numInputs_, inputs.size());
    CHECK_EQ(numOutputs_, outputs.size());
    check(inputs, outputs);

    const TensorShape& input = inputs[0].shape();
    const TensorShape& filter = inputs[1].shape();
    const TensorShape& output = outputs[0].shape();

    int batchSize = input[0];
    int inputChannels = input[1];
    int inputHeight = input[2];
    int inputWidth = input[3];
    int filterHeight = getFilterHeight(filter);
    int filterWidth = getFilterWidth(filter);
    int outputChannels = output[1];
    int outputHeight = output[2];
    int outputWidth = output[3];
    int filterMultiplier = outputChannels / groups_;
    CHECK_EQ(static_cast<size_t>(inputChannels), groups_);

    // only support strideH() == strideW() and filterHeight == filterWidth.
    CHECK_EQ(strideH(), strideW());
    CHECK_EQ(filterHeight, filterWidth);

    float* inputData = inputs[0].data<float>();
    float* filterData = inputs[1].data<float>();
    float* outputData = outputs[0].data<float>();

    // padding the input
    float* inputPadding = inputData;
    int padInputHeight = inputHeight + 2 * paddingH();
    int padInputWidth = inputWidth + 2 * paddingW();
    int newSize =
        batchSize * (inputChannels + 1) * padInputHeight * padInputWidth;

    resizeBuffer<Device>(newSize);
    inputPadding = reinterpret_cast<float*>(memory_->getBuf());
    neon::Padding<float>::run(inputData,
                              inputPadding,
                              batchSize * inputChannels,
                              inputHeight,
                              inputWidth,
                              padInputHeight,
                              padInputWidth);

    std::function<void(
        const float*, const float*, int, int, int, int, int, int, float*)>
        DepthWiseConv;

    if (filterWidth == 3 && strideW() == 1) {
      DepthWiseConv = neon::DepthwiseConvKernel<3, 1>::run;
    } else if (filterWidth == 3 && strideW() == 2) {
      DepthWiseConv = neon::DepthwiseConvKernel<3, 2>::run;
    } else if (filterWidth == 4 && strideW() == 1) {
      DepthWiseConv = neon::DepthwiseConvKernel<4, 1>::run;
    } else if (filterWidth == 4 && strideW() == 2) {
      DepthWiseConv = neon::DepthwiseConvKernel<4, 2>::run;
    } else {
      LOG(FATAL) << "Not supported";
    }

    for (int i = 0; i < batchSize; i++) {
      DepthWiseConv(inputPadding,
                    filterData,
                    padInputHeight,
                    padInputWidth,
                    outputChannels,
                    outputHeight,
                    outputWidth,
                    filterMultiplier,
                    outputData);
      inputPadding += inputChannels * padInputHeight * padInputWidth;
      outputData += outputChannels * outputHeight * outputWidth;
    }
  }
};

#ifndef PADDLE_TYPE_DOUBLE
REGISTER_TYPED_FUNC(NeonDepthwiseConv, CPU, NeonDepthwiseConvFunction);
#endif

#endif

}  // namespace paddle


text:
class ResponseMate::Connection
  delegate :params, to: :client
  delegate(*(ResponseMate::HTTP_METHODS), to: :client)

  attr_accessor :client

  def initialize
    @client = Faraday.new do |c|
      c.use FaradayMiddleware::FollowRedirects, limit: 5
      c.adapter Faraday.default_adapter
    end
  end

  # Performs the supplied request
  # @param {ResponseMate::Request} The request to be performed
  def fetch(request) # rubocop:disable Metrics/AbcSize
    uri = URI.parse(request[:url])

    if request[:params]
      query = request[:params].to_query
      query = uri.query ? uri.query << '&' << query : query
      uri.query = query
    end

    client.headers = request[:headers] if request[:headers]
    client.send request[:verb].downcase.to_sym, uri.to_s
  rescue Faraday::Error::ConnectionFailed
    puts "Is a server up and running at #{request[:path]}?".red
    exit 1
  end
end


text:
JavaScript concatenation to 1 file, with JavaScript validation.

# Usage
Install with `npm install`.
Run with `grunt watch`.


text:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;

namespace FunctionalQuery.Helpers {
	internal class ConnectionDictionary {
		private readonly string _defaultConnectionString;

		private readonly Dictionary<string, string> _connectionStrings;

		public ConnectionDictionary() : this(null, null) { }

		public ConnectionDictionary(string defaultConnectionString) : this(null, defaultConnectionString) { }

		public ConnectionDictionary(IEnumerable<KeyValuePair<string, string>> connectionStrings) : this(connectionStrings, null) { }

		public ConnectionDictionary(IEnumerable<KeyValuePair<string, string>> connectionStrings, string defaultConnectionString) {
			_defaultConnectionString = string.IsNullOrWhiteSpace(defaultConnectionString) ? null : defaultConnectionString.Trim();
			if (connectionStrings == null) {
				connectionStrings = ReadFromConfig();
			}
			_connectionStrings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			foreach (var connString in connectionStrings) {
				_connectionStrings.Add(connString.Key.Trim(), connString.Value.Trim());
			}
			if (_defaultConnectionString == null && _connectionStrings.Keys.Count == 1) {
				_defaultConnectionString = _connectionStrings.Values.First();
			}
		}

		public string this[string connectionKey] {
			get {
				var key = GetConnectionKeyOrDefault(connectionKey);
				if (_connectionStrings != null && _connectionStrings.ContainsKey(key)) {
					return _connectionStrings[key].Trim();
				}
				return key;
			}
		}

		private string GetConnectionKeyOrDefault(string connectionKey) {
			if (string.IsNullOrWhiteSpace(connectionKey)) {
				if (_defaultConnectionString == null) {
					throw new DatabaseException("No connection provided.  Add connection string(s) to constructor or pass it into the function");
				}
				return _defaultConnectionString;
			}
			return connectionKey.Trim();
		}

		public static IEnumerable<KeyValuePair<string, string>> ReadFromConfig() {
			var connectionStrings = ConfigurationManager.ConnectionStrings;
			var conns = new Dictionary<string, string>();
			foreach (ConnectionStringSettings connectionString in connectionStrings) {
				conns[connectionString.Name] = connectionString.ConnectionString;
			}
			return conns;
		}
	}
}


text:
"""
Represents a Virtual Private Cloud.
"""

from boto.ec2.ec2object import TaggedEC2Object

class VPC(TaggedEC2Object):

    def __init__(self, connection=None):
        """
        Represents a VPC.

        :ivar id: The unique ID of the VPC.
        :ivar dhcp_options_id: The ID of the set of DHCP options you've associated with the VPC
                                (or default if the default options are associated with the VPC).
        :ivar state: The current state of the VPC.
        :ivar cidr_block: The CIDR block for the VPC.
        :ivar is_default: Indicates whether the VPC is the default VPC.
        :ivar instance_tenancy: The allowed tenancy of instances launched into the VPC.
        """
        TaggedEC2Object.__init__(self, connection)
        self.id = None
        self.dhcp_options_id = None
        self.state = None
        self.cidr_block = None
        self.is_default = None
        self.instance_tenancy = None

    def __repr__(self):
        return 'VPC:%s' % self.id

    def endElement(self, name, value, connection):
        if name == 'vpcId':
            self.id = value
        elif name == 'dhcpOptionsId':
            self.dhcp_options_id = value
        elif name == 'state':
            self.state = value
        elif name == 'cidrBlock':
            self.cidr_block = value
        elif name == 'isDefault':
            self.is_default = True if value == 'true' else False
        elif name == 'instanceTenancy':
            self.instance_tenancy = value
        else:
            setattr(self, name, value)

    def delete(self):
        return self.connection.delete_vpc(self.id)

    def _update(self, updated):
        self.__dict__.update(updated.__dict__)

    def update(self, validate=False, dry_run=False):
        vpc_list = self.connection.get_all_vpcs(
            [self.id],
            dry_run=dry_run
        )
        if len(vpc_list):
            updated_vpc = vpc_list[0]
            self._update(updated_vpc)
        elif validate:
            raise ValueError('%s is not a valid VPC ID' % (self.id,))
        return self.state


text:
package de.ieg.infra.domain;

import java.util.Date;
import java.util.List;

import de.ieg.infra.utils.Utils;

public class InfImpcIkmcRome1Booking extends Booking{
	private String sex;
	private String needHotel;
	private String hotelYesNo;
	private String hotelRemarks;
	private List<String> numberOfNights;
	private String flightNeeded;
	private String outboundFlightFrom;
	private String outboundFlightTo;
	private Date outboundFlightDate;
	private String outboundFlightTime;
	private String outboundFlightHour;
	private String outboundFlightMinute;
	private String returnFlightFrom;
	private String returnFlightTo;
	private Date returnFlightDate;
	private String returnFlightTime;
	private String returnFlightHour;
	private String returnFlightMinute;

	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getNeedHotel() {
		return needHotel;
	}
	public void setNeedHotel(String needHotel) {
		this.needHotel = needHotel;
	}
	public String getHotelYesNo() {
		return hotelYesNo;
	}
	public void setHotelYesNo(String hotelYesNo) {
		this.hotelYesNo = hotelYesNo;
	}
	public List<String> getNumberOfNights() {
		return numberOfNights;
	}
	public void setNumberOfNights(List<String> numberOfNights) {
		this.numberOfNights = numberOfNights;
	}
	public String getFlightNeeded() {
		return flightNeeded;
	}
	public void setFlightNeeded(String flightNeeded) {
		this.flightNeeded = flightNeeded;
	}
	public String getOutboundFlightFrom() {
		return outboundFlightFrom;
	}
	public void setOutboundFlightFrom(String outboundFlightFrom) {
		this.outboundFlightFrom = outboundFlightFrom;
	}
	public String getOutboundFlightTo() {
		return outboundFlightTo;
	}
	public void setOutboundFlightTo(String outboundFlightTo) {
		this.outboundFlightTo = outboundFlightTo;
	}
	public Date getOutboundFlightDate() {
		return outboundFlightDate;
	}
	public void setOutboundFlightDate(Date outboundFlightDate) {
		this.outboundFlightDate = outboundFlightDate;
	}

	public String getOutboundFlightHour() {
		return outboundFlightHour;
	}
	public void setOutboundFlightHour(String outboundFlightHour) {
		this.outboundFlightHour = outboundFlightHour;
	}
	public String getOutboundFlightMinute() {
		return outboundFlightMinute;
	}
	public void setOutboundFlightMinute(String outboundFlightMinute) {
		this.outboundFlightMinute = outboundFlightMinute;
	}
	public String getReturnFlightFrom() {
		return returnFlightFrom;
	}
	public void setReturnFlightFrom(String returnFlightFrom) {
		this.returnFlightFrom = returnFlightFrom;
	}
	public String getReturnFlightTo() {
		return returnFlightTo;
	}
	public void setReturnFlightTo(String returnFlightTo) {
		this.returnFlightTo = returnFlightTo;
	}
	public Date getReturnFlightDate() {
		return returnFlightDate;
	}
	public void setReturnFlightDate(Date returnFlightDate) {
		this.returnFlightDate = returnFlightDate;
	}

	public String getReturnFlightHour() {
		return returnFlightHour;
	}
	public void setReturnFlightHour(String returnFlightHour) {
		this.returnFlightHour = returnFlightHour;
	}
	public String getReturnFlightMinute() {
		return returnFlightMinute;
	}
	public void setReturnFlightMinute(String returnFlightMinute) {
		this.returnFlightMinute = returnFlightMinute;
	}

	public String getOutboundFlightTime() {
		this.outboundFlightHour=this.outboundFlightHour==null || this.outboundFlightHour.equals("-please_select-")? "":this.outboundFlightHour;
		this.outboundFlightMinute=this.outboundFlightMinute==null || this.outboundFlightMinute.equals("-please_select-")? "":this.outboundFlightMinute;
		outboundFlightTime=this.outboundFlightHour + ":" + this.outboundFlightMinute;

		return outboundFlightTime;
	}

	public String getReturnFlightTime() {
		this.returnFlightHour=this.returnFlightHour==null || this.returnFlightHour.equals("-please_select-")? "":this.returnFlightHour;
		this.returnFlightMinute=this.returnFlightMinute==null || this.returnFlightMinute.equals("-please_select-")? "":this.returnFlightMinute;
		returnFlightTime=this.returnFlightHour +":" +this.returnFlightMinute;
		return returnFlightTime;
	}

	public String getHotelRemarks() {
		return hotelRemarks;
	}
	public void setHotelRemarks(String hotelRemarks) {
		this.hotelRemarks = hotelRemarks;
	}

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Barsik.Client.Exceptions
{
    public class ResponseTypeNotFoundException : Exception
    {
    }
}


text:
//-----------------------------------------------------------------------------
// Headers
//-----------------------------------------------------------------------------
// General headers
#include <stdio.h>
// OpenNI headers
#include <XnOpenNI.h>
// NITE headers
#include <XnVSessionManager.h>
#include "XnVMultiProcessFlowClient.h"
#include <XnVWaveDetector.h>

#include "kbhit.h"
#include "signal_catch.h"

// xml to initialize OpenNI
#define SAMPLE_XML_FILE "../../Data/Sample-Tracking.xml"

XnBool g_bQuit = false;

//-----------------------------------------------------------------------------
// Callbacks
//-----------------------------------------------------------------------------

// Callback for when the focus is in progress
void XN_CALLBACK_TYPE SessionProgress(const XnChar* strFocus, const XnPoint3D& ptFocusPoint, XnFloat fProgress, void* UserCxt)
{
	printf("Session progress (%6.2f,%6.2f,%6.2f) - %6.2f [%s]\n", ptFocusPoint.X, ptFocusPoint.Y, ptFocusPoint.Z, fProgress,  strFocus);
}
// callback for session start
void XN_CALLBACK_TYPE SessionStart(const XnPoint3D& ptFocusPoint, void* UserCxt)
{
	printf("Session started. Please wave (%6.2f,%6.2f,%6.2f)...\n", ptFocusPoint.X, ptFocusPoint.Y, ptFocusPoint.Z);
}
// Callback for session end
void XN_CALLBACK_TYPE SessionEnd(void* UserCxt)
{
	printf("Session ended. Please perform focus gesture to start session\n");
}
// Callback for wave detection
void XN_CALLBACK_TYPE OnWaveCB(void* cxt)
{
	printf("Wave!\n");
}
// callback for a new position of any hand
void XN_CALLBACK_TYPE OnPointUpdate(const XnVHandPointContext* pContext, void* cxt)
{
	printf("%d: (%f,%f,%f) [%f]\n", pContext->nID, pContext->ptPosition.X, pContext->ptPosition.Y, pContext->ptPosition.Z, pContext->fTime);
}

//-----------------------------------------------------------------------------
// Main
//-----------------------------------------------------------------------------

// this sample can run either as a regular sample, or as a client for multi-process (remote mode)
int main(int argc, char** argv)
{
	xn::Context context;
	XnVSessionGenerator* pSessionGenerator;
	XnBool bRemoting = FALSE;

	if (argc > 1)
	{
		// remote mode
		context.Init();
		printf("Running in 'Remoting' mode (Section name: %s)\n", argv[1]);
		bRemoting = TRUE;

		// Create multi-process client
		pSessionGenerator = new XnVMultiProcessFlowClient(argv[1]);

		XnStatus rc = ((XnVMultiProcessFlowClient*)pSessionGenerator)->Initialize();
		if (rc != XN_STATUS_OK)
		{
			printf("Initialize failed: %s\n", xnGetStatusString(rc));
			delete pSessionGenerator;
			return 1;
		}
	}
	else
	{
		// Local mode
		// Create context
		XnStatus rc = context.InitFromXmlFile(SAMPLE_XML_FILE);
		if (rc != XN_STATUS_OK)
		{
			printf("Couldn't initialize: %s\n", xnGetStatusString(rc));
			return 1;
		}

		// Create the Session Manager
		pSessionGenerator = new XnVSessionManager();
		rc = ((XnVSessionManager*)pSessionGenerator)->Initialize(&context, "Click", "RaiseHand");
		if (rc != XN_STATUS_OK)
		{
			printf("Session Manager couldn't initialize: %s\n", xnGetStatusString(rc));
			delete pSessionGenerator;
			return 1;
		}

		// Initialization done. Start generating
		context.StartGeneratingAll();
	}

	// Register session callbacks
	pSessionGenerator->RegisterSession(NULL, &SessionStart, &SessionEnd, &SessionProgress);

	// Start catching signals for quit indications
	CatchSignals(&g_bQuit);

	// init & register wave control
	XnVWaveDetector wc;
	wc.RegisterWave(NULL, OnWaveCB);
	wc.RegisterPointUpdate(NULL, OnPointUpdate);
	pSessionGenerator->AddListener(&wc);

	printf("Please perform focus gesture to start session\n");
	printf("Hit any key to exit\n");

	// Main loop
	while ((!_kbhit()) && (!g_bQuit))
	{
		if (bRemoting)
		{
			((XnVMultiProcessFlowClient*)pSessionGenerator)->ReadState();
		}
		else
		{
			context.WaitAnyUpdateAll();
			((XnVSessionManager*)pSessionGenerator)->Update(&context);
		}
	}

	delete pSessionGenerator;

	context.Shutdown();

	return 0;
}


text:
require "spec_helper"
require "svg_rails"

class FakeView < ActionView::Base
  include SvgRails::Helper
end

describe SvgRails::Helper do
  it "ouputs correct HTML for images without fallback" do
    FakeView.new.svg_image_tag("icon.svg", "/images/icon.png").should == ''
    FakeView.new.svg_image_tag("icon.svg", "icon.png").should == ''
  end
end


text:
package us.kbase.fbatools;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

/**
 *
Original spec-file type: CheckModelMassBalanceResults

 *
 *
 */
@JsonInclude(JsonInclude.Include.NON_NULL)
@Generated("com.googlecode.jsonschema2pojo")
@JsonPropertyOrder({
    "new_report_ref"
})
public class CheckModelMassBalanceResults {

    @JsonProperty("new_report_ref")
    private String newReportRef;
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();

    @JsonProperty("new_report_ref")
    public String getNewReportRef() {
        return newReportRef;
    }

    @JsonProperty("new_report_ref")
    public void setNewReportRef(String newReportRef) {
        this.newReportRef = newReportRef;
    }

    public CheckModelMassBalanceResults withNewReportRef(String newReportRef) {
        this.newReportRef = newReportRef;
        return this;
    }

    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
        return this.additionalProperties;
    }

    @JsonAnySetter
    public void setAdditionalProperties(String name, Object value) {
        this.additionalProperties.put(name, value);
    }

    @Override
    public String toString() {
        return ((((("CheckModelMassBalanceResults"+" [newReportRef=")+ newReportRef)+", additionalProperties=")+ additionalProperties)+"]");
    }

}


text:
from pandac.PandaModules import *
from panda3d.core import loadPrcFileData
from direct.distributed.PyDatagram import PyDatagram
from direct.distributed.PyDatagramIterator import PyDatagramIterator
loadPrcFileData("",
"""
   load-display p3tinydisplay # to force CPU only rendering
   window-type offscreen # Spawn an offscreen buffer
   audio-library-name null # Prevent ALSA errors
   show-frame-rate-meter 0
   sync-video 0
   default-model-extension .bam
   model-path ../../resources
""")
from direct.showbase.ShowBase import ShowBase
base = ShowBase()
from direct.actor.Actor import Actor

from SnapshotRendererConsts import *

def compileGlobalAnimList():
    phaseList = [Phase3AnimList,
     Phase3_5AnimList,
     Phase4AnimList,
     Phase5AnimList,
     Phase5_5AnimList,
     Phase6AnimList,
     Phase9AnimList,
     Phase10AnimList,
     Phase12AnimList]
    phaseStrList = ['phase_3',
     'phase_3.5',
     'phase_4',
     'phase_5',
     'phase_5.5',
     'phase_6',
     'phase_9',
     'phase_10',
     'phase_12']
    for animList in phaseList:
        phaseStr = phaseStrList[phaseList.index(animList)]
        for key in LegDict.keys():
            LegsAnimDict.setdefault(key, {})
            for anim in animList:
                file = phaseStr + LegDict[key] + anim[1]
                LegsAnimDict[key][anim[0]] = file

        for key in TorsoDict.keys():
            TorsoAnimDict.setdefault(key, {})
            for anim in animList:
                file = phaseStr + TorsoDict[key] + anim[1]
                TorsoAnimDict[key][anim[0]] = file

        for key in HeadDict.keys():
            if key.find('d') >= 0:
                HeadAnimDict.setdefault(key, {})
                for anim in animList:
                    file = phaseStr + HeadDict[key] + anim[1]
                    HeadAnimDict[key][anim[0]] = file

def loadModels():
    global Preloaded
    if not Preloaded:
        print 'Preloading avatars...'

        for key in LegDict.keys():
            fileRoot = LegDict[key]

            Preloaded[fileRoot+'-1000'] = loader.loadModel('phase_3' + fileRoot + '1000')
            Preloaded[fileRoot+'-500'] = loader.loadModel('phase_3' + fileRoot + '500')
            Preloaded[fileRoot+'-250'] = loader.loadModel('phase_3' + fileRoot + '250')

        for key in TorsoDict.keys():
            fileRoot = TorsoDict[key]

            Preloaded[fileRoot+'-1000'] = loader.loadModel('phase_3' + fileRoot + '1000')

            if len(key) > 1:
                Preloaded[fileRoot+'-500'] = loader.loadModel('phase_3' + fileRoot + '500')
                Preloaded[fileRoot+'-250'] = loader.loadModel('phase_3' + fileRoot + '250')

class SnapshotRenderer:
    def __init__(self, dnaString):
        self.dnaString = dnaString
        loadModels()
        compileGlobalAnimList()
        self.makeFromNetString(dnaString)
        self.toon = Actor()
        self.generateToon()
        self.renderSnapshot()

    def makeFromNetString(self, string):
        dg = PyDatagram(string)
        dgi = PyDatagramIterator(dg)
        self.type = dgi.getFixedString(1)
        if self.type == 't':
            headIndex = dgi.getUint8()
            torsoIndex = dgi.getUint8()
            legsIndex = dgi.getUint8()
            self.head = toonHeadTypes[headIndex]
            self.torso = toonTorsoTypes[torsoIndex]
            self.legs = toonLegTypes[legsIndex]
            gender = dgi.getUint8()
            if gender == 1:
                self.gender = 'm'
            else:
                self.gender = 'f'
            self.topTex = dgi.getUint8()
            self.topTexColor = dgi.getUint8()
            self.sleeveTex = dgi.getUint8()
            self.sleeveTexColor = dgi.getUint8()
            self.botTex = dgi.getUint8()
            self.botTexColor = dgi.getUint8()
            self.armColor = dgi.getUint8()
            self.gloveColor = dgi.getUint8()
            self.legColor = dgi.getUint8()
            self.headColor = dgi.getUint8()
        else:
            notify.error('unknown avatar type: ', self.type)

    def getAnimal(self):
        if self.head[0] == 'd':
            return 'dog'
        elif self.head[0] == 'c':
            return 'cat'
        elif self.head[0] == 'm':
            return 'mouse'
        elif self.head[0] == 'h':
            return 'horse'
        elif self.head[0] == 'r':
            return 'rabbit'
        elif self.head[0] == 'f':
            return 'duck'
        elif self.head[0] == 'p':
            return 'monkey'
        elif self.head[0] == 'b':
            return 'bear'
        elif self.head[0] == 's':
            return 'pig'
        else:
            notify.error('unknown headStyle: ', self.head[0])

    def getArmColor(self):
        try:
            return allColorsList[self.armColor]
        except:
            return allColorsList[0]

    def getLegColor(self):
        try:
            return allColorsList[self.legColor]
        except:
            return allColorsList[0]

    def getHeadColor(self):
        try:
            return allColorsList[self.headColor]
        except:
            return allColorsList[0]

    def getGloveColor(self):
        try:
            return allColorsList[self.gloveColor]
        except:
            return allColorsList[0]

    def getGender(self):
        return self.gender

    def generateToon(self):
        self.setLODs()
        self.generateToonLegs()
        self.generateToonHead(1, ('1000', '500', '250'))
        self.generateToonTorso()
        self.generateToonColor()
        self.parentToonParts()
        # self.rescaleToon()
        # self.resetHeight()
        # self.setupToonNodes()
        self.toon.reparentTo(render)
        self.toon.setPos(0, 5, -3)
        self.toon.setH(180)
        self.toon.getPart('head', '1000').setR(10)
        self.toon.pose('neutral', 0)

    def generateToonLegs(self, copy = 1):
        global Preloaded
        legStyle = self.legs
        filePrefix = LegDict.get(legStyle)
        if filePrefix is None:
            print('unknown leg style: %s' % legStyle)
        self.toon.loadModel(Preloaded[filePrefix+'-1000'], 'legs', '1000', True)
        self.toon.loadModel(Preloaded[filePrefix+'-500'], 'legs', '500', True)
        self.toon.loadModel(Preloaded[filePrefix+'-250'], 'legs', '250', True)
        if not copy:
            self.toon.showPart('legs', '1000')
            self.toon.showPart('legs', '500')
            self.toon.showPart('legs', '250')
        self.toon.loadAnims(LegsAnimDict[legStyle], 'legs', '1000')
        self.toon.loadAnims(LegsAnimDict[legStyle], 'legs', '500')
        self.toon.loadAnims(LegsAnimDict[legStyle], 'legs', '250')
        self.toon.findAllMatches('**/boots_short').stash()
        self.toon.findAllMatches('**/boots_long').stash()
        self.toon.findAllMatches('**/shoes').stash()
        return

    def generateToonTorso(self, copy = 1, genClothes = 1):
        global Preloaded
        torsoStyle = self.torso
        filePrefix = TorsoDict.get(torsoStyle)
        if filePrefix is None:
            self.notify.error('unknown torso style: %s' % torsoStyle)
        self.toon.loadModel(Preloaded[filePrefix+'-1000'], 'torso', '1000', True)
        if len(torsoStyle) == 1:
            self.toon.loadModel(Preloaded[filePrefix+'-1000'], 'torso', '500', True)
            self.toon.loadModel(Preloaded[filePrefix+'-1000'], 'torso', '250', True)
        else:
            self.toon.loadModel(Preloaded[filePrefix+'-500'], 'torso', '500', True)
            self.toon.loadModel(Preloaded[filePrefix+'-250'], 'torso', '250', True)
        if not copy:
            self.toon.showPart('torso', '1000')
            self.toon.showPart('torso', '500')
            self.toon.showPart('torso', '250')
        self.toon.loadAnims(TorsoAnimDict[torsoStyle], 'torso', '1000')
        self.toon.loadAnims(TorsoAnimDict[torsoStyle], 'torso', '500')
        self.toon.loadAnims(TorsoAnimDict[torsoStyle], 'torso', '250')
        if genClothes == 1 and not len(torsoStyle) == 1:
            self.generateToonClothes()
        return

    def generateToonClothes(self, fromNet = 0):
        swappedTorso = 0
        if self.toon.hasLOD():
            if self.getGender() == 'f' and fromNet == 0:
                try:
                    bottomPair = GirlBottoms[self.botTex]
                except:
                    bottomPair = GirlBottoms[0]
            try:
                texName = Shirts[self.topTex]
            except:
                texName = Shirts[0]

            shirtTex = loader.loadTexture(texName, okMissing=True)
            if shirtTex is None:
                shirtTex = loader.loadTexture(Shirts[0])
            shirtTex.setMinfilter(Texture.FTLinearMipmapLinear)
            shirtTex.setMagfilter(Texture.FTLinear)
            try:
                shirtColor = ClothesColors[self.topTexColor]
            except:
                shirtColor = ClothesColors[0]

            try:
                texName = Sleeves[self.sleeveTex]
            except:
                texName = Sleeves[0]

            sleeveTex = loader.loadTexture(texName, okMissing=True)
            if sleeveTex is None:
                self.sendLogSuspiciousEvent('failed to load texture %s' % texName)
                sleeveTex = loader.loadTexture(Sleeves[0])
            sleeveTex.setMinfilter(Texture.FTLinearMipmapLinear)
            sleeveTex.setMagfilter(Texture.FTLinear)
            try:
                sleeveColor = ClothesColors[self.sleeveTexColor]
            except:
                sleeveColor = ClothesColors[0]

            if self.getGender() == 'm':
                try:
                    texName = BoyShorts[self.botTex]
                except:
                    texName = BoyShorts[0]

            else:
                try:
                    texName = GirlBottoms[self.botTex][0]
                except:
                    texName = GirlBottoms[0][0]

            bottomTex = loader.loadTexture(texName, okMissing=True)
            if bottomTex is None:
                self.sendLogSuspiciousEvent('failed to load texture %s' % texName)
                if self.getGender() == 'm':
                    bottomTex = loader.loadTexture(BoyShorts[0])
                else:
                    bottomTex = loader.loadTexture(GirlBottoms[0][0])
            bottomTex.setMinfilter(Texture.FTLinearMipmapLinear)
            bottomTex.setMagfilter(Texture.FTLinear)
            try:
                bottomColor = ClothesColors[self.botTexColor]
            except:
                bottomColor = ClothesColors[0]

            darkBottomColor = bottomColor * 0.5
            darkBottomColor.setW(1.0)
            for lodName in self.toon.getLODNames():
                thisPart = self.toon.getPart('torso', lodName)
                top = thisPart.find('**/torso-top')
                top.setTexture(shirtTex, 1)
                top.setColor(shirtColor)
                sleeves = thisPart.find('**/sleeves')
                sleeves.setTexture(sleeveTex, 1)
                sleeves.setColor(sleeveColor)
                bottoms = thisPart.findAllMatches('**/torso-bot')
                for bottomNum in xrange(0, bottoms.getNumPaths()):
                    bottom = bottoms.getPath(bottomNum)
                    bottom.setTexture(bottomTex, 1)
                    bottom.setColor(bottomColor)

                caps = thisPart.findAllMatches('**/torso-bot-cap')
                caps.setColor(darkBottomColor)

        return swappedTorso

    def generateToonColor(self):
        parts = self.toon.findAllMatches('**/head*')
        parts.setColor(self.getHeadColor())
        animalType = self.getAnimal()
        if animalType == 'cat' or animalType == 'rabbit' or animalType == 'bear' or animalType == 'mouse' or animalType == 'pig':
            parts = self.toon.findAllMatches('**/ear?-*')
            parts.setColor(self.getHeadColor())

        armColor = self.getArmColor()
        gloveColor = self.getGloveColor()
        legColor = self.getLegColor()
        for lodName in self.toon.getLODNames():
            torso = self.toon.getPart('torso', lodName)
            if len(self.torso) == 1:
                parts = torso.findAllMatches('**/torso*')
                parts.setColor(armColor)
            for pieceName in ('arms', 'neck'):
                piece = torso.find('**/' + pieceName)
                piece.setColor(armColor)

            hands = torso.find('**/hands')
            hands.setColor(gloveColor)
            legs = self.toon.getPart('legs', lodName)
            for pieceName in ('legs', 'feet'):
                piece = legs.find('**/%s;+s' % pieceName)
                piece.setColor(legColor)

    def generateToonHead(self, copy, lods):
        headStyle = self.head
        fix = None
        if headStyle == 'dls':
            filePrefix = HeadDict['dls']
            headHeight = 0.75
        elif headStyle == 'dss':
            filePrefix = HeadDict['dss']
            headHeight = 0.5
        elif headStyle == 'dsl':
            filePrefix = HeadDict['dsl']
            headHeight = 0.5
        elif headStyle == 'dll':
            filePrefix = HeadDict['dll']
            headHeight = 0.75
        elif headStyle == 'cls':
            filePrefix = HeadDict['c']
            fix = self.__fixHeadLongShort
            headHeight = 0.75
        elif headStyle == 'css':
            filePrefix = HeadDict['c']
            fix = self.__fixHeadShortShort
            headHeight = 0.5
        elif headStyle == 'csl':
            filePrefix = HeadDict['c']
            fix = self.__fixHeadShortLong
            headHeight = 0.5
        elif headStyle == 'cll':
            filePrefix = HeadDict['c']
            fix = self.__fixHeadLongLong
            headHeight = 0.75
        elif headStyle == 'hls':
            filePrefix = HeadDict['h']
            fix = self.__fixHeadLongShort
            headHeight = 0.75
        elif headStyle == 'hss':
            filePrefix = HeadDict['h']
            fix = self.__fixHeadShortShort
            headHeight = 0.5
        elif headStyle == 'hsl':
            filePrefix = HeadDict['h']
            fix = self.__fixHeadShortLong
            headHeight = 0.5
        elif headStyle == 'hll':
            filePrefix = HeadDict['h']
            fix = self.__fixHeadLongLong
            headHeight = 0.75
        elif headStyle == 'mls':
            filePrefix = HeadDict['m']
            fix = self.__fixHeadLongShort
            headHeight = 0.75
        elif headStyle == 'mss':
            filePrefix = HeadDict['m']
            fix = self.__fixHeadShortShort
            headHeight = 0.5
        elif headStyle == 'rls':
            filePrefix = HeadDict['r']
            fix = self.__fixHeadLongShort
            headHeight = 0.75
        elif headStyle == 'rss':
            filePrefix = HeadDict['r']
            fix = self.__fixHeadShortShort
            headHeight = 0.5
        elif headStyle == 'rsl':
            filePrefix = HeadDict['r']
            fix = self.__fixHeadShortLong
            headHeight = 0.5
        elif headStyle == 'rll':
            filePrefix = HeadDict['r']
            fix = self.__fixHeadLongLong
            headHeight = 0.75
        elif headStyle == 'fls':
            filePrefix = HeadDict['f']
            fix = self.__fixHeadLongShort
            headHeight = 0.75
        elif headStyle == 'fss':
            filePrefix = HeadDict['f']
            fix = self.__fixHeadShortShort
            headHeight = 0.5
        elif headStyle == 'fsl':
            filePrefix = HeadDict['f']
            fix = self.__fixHeadShortLong
            headHeight = 0.5
        elif headStyle == 'fll':
            filePrefix = HeadDict['f']
            fix = self.__fixHeadLongLong
            headHeight = 0.75
        elif headStyle == 'pls':
            filePrefix = HeadDict['p']
            fix = self.__fixHeadLongShort
            headHeight = 0.75
        elif headStyle == 'pss':
            filePrefix = HeadDict['p']
            fix = self.__fixHeadShortShort
            headHeight = 0.5
        elif headStyle == 'psl':
            filePrefix = HeadDict['p']
            fix = self.__fixHeadShortLong
            headHeight = 0.5
        elif headStyle == 'pll':
            filePrefix = HeadDict['p']
            fix = self.__fixHeadLongLong
            headHeight = 0.75
        elif headStyle == 'bls':
            filePrefix = HeadDict['b']
            fix = self.__fixHeadLongShort
            headHeight = 0.75
        elif headStyle == 'bss':
            filePrefix = HeadDict['b']
            fix = self.__fixHeadShortShort
            headHeight = 0.5
        elif headStyle == 'bsl':
            filePrefix = HeadDict['b']
            fix = self.__fixHeadShortLong
            headHeight = 0.5
        elif headStyle == 'bll':
            filePrefix = HeadDict['b']
            fix = self.__fixHeadLongLong
            headHeight = 0.75
        elif headStyle == 'sls':
            filePrefix = HeadDict['s']
            fix = self.__fixHeadLongShort
            headHeight = 0.75
        elif headStyle == 'sss':
            filePrefix = HeadDict['s']
            fix = self.__fixHeadShortShort
            headHeight = 0.5
        elif headStyle == 'ssl':
            filePrefix = HeadDict['s']
            fix = self.__fixHeadShortLong
            headHeight = 0.5
        elif headStyle == 'sll':
            filePrefix = HeadDict['s']
            fix = self.__fixHeadLongLong
            headHeight = 0.75
        else:
            ToonHead.notify.error('unknown head style: %s' % headStyle)
        if len(lods) == 1:
            self.toon.loadModel(filePrefix + lods[0], 'head', 'lodRoot', copy)
            if not copy:
                self.toon.showAllParts('head')
            if fix != None:
                fix(None, copy)
            self.__lods = lods
            self.__headStyle = headStyle
            self.__copy = copy
        else:
            for lod in lods:
                self.toon.loadModel(filePrefix + lod, 'head', lod, copy)
                if not copy:
                    self.toon.showAllParts('head', lod)
                if fix != None:
                    fix(lod, copy)
                self.__lods = lods
                self.__headStyle = headStyle
                self.__copy = copy

        # self.setupEyelashes()
        self.setupMuzzles()
        return headHeight

    def setupMuzzles(self):
        self.__muzzles = []
        self.__surpriseMuzzles = []
        self.__angryMuzzles = []
        self.__sadMuzzles = []
        self.__smileMuzzles = []
        self.__laughMuzzles = []

        def hideAddNonEmptyItemToList(item, list):
            if not item.isEmpty():
                item.hide()
                list.append(item)

        def hideNonEmptyItem(item):
            if not item.isEmpty():
                item.hide()

        if self.toon.hasLOD():
            for lodName in self.toon.getLODNames():
                animal = self.getAnimal()
                if animal != 'dog':
                    muzzle = self.toon.find('**/' + lodName + '/**/muzzle*neutral')
                else:
                    muzzle = self.toon.find('**/' + lodName + '/**/muzzle*')
                    if lodName == '1000' or lodName == '500':
                        filePrefix = DogMuzzleDict[self.head]
                        muzzles = self.toon.loadModel(filePrefix + lodName)
                        if base.config.GetBool('want-new-anims', 1):
                            if not self.toon.find('**/' + lodName + '/**/__Actor_head/def_head').isEmpty():
                                muzzles.reparentTo(self.toon.find('**/' + lodName + '/**/__Actor_head/def_head'))
                            else:
                                muzzles.reparentTo(self.toon.find('**/' + lodName + '/**/joint_toHead'))
                        elif self.toon.find('**/' + lodName + '/**/joint_toHead'):
                            muzzles.reparentTo(self.toon.find('**/' + lodName + '/**/joint_toHead'))
                surpriseMuzzle = self.toon.find('**/' + lodName + '/**/muzzle*surprise')
                angryMuzzle = self.toon.find('**/' + lodName + '/**/muzzle*angry')
                sadMuzzle = self.toon.find('**/' + lodName + '/**/muzzle*sad')
                smileMuzzle = self.toon.find('**/' + lodName + '/**/muzzle*smile')
                laughMuzzle = self.toon.find('**/' + lodName + '/**/muzzle*laugh')
                self.__muzzles.append(muzzle)
                hideAddNonEmptyItemToList(surpriseMuzzle, self.__surpriseMuzzles)
                hideAddNonEmptyItemToList(angryMuzzle, self.__angryMuzzles)
                hideAddNonEmptyItemToList(sadMuzzle, self.__sadMuzzles)
                hideAddNonEmptyItemToList(smileMuzzle, self.__smileMuzzles)
                hideAddNonEmptyItemToList(laughMuzzle, self.__laughMuzzles)

    def setupEyelashes(self):
        animal = self.head[0]
        model = self.toon.loadModel(EyelashDict[animal])
        if self.toon.hasLOD():
            head = self.toon.getPart('head', '1000')
        else:
            head = self.toon.getPart('head', 'lodRoot')
        length = self.head[1]
        if length == 'l':
            openString = 'open-long'
            closedString = 'closed-long'
        else:
            openString = 'open-short'
            closedString = 'closed-short'
        self.__eyelashOpen = model.find('**/' + openString).copyTo(head)
        self.__eyelashClosed = model.find('**/' + closedString).copyTo(head)
        model.removeNode()
        return

    def parentToonParts(self):
        if self.toon.hasLOD():
            for lodName in self.toon.getLODNames():
                if base.config.GetBool('want-new-anims', 1):
                    if not self.toon.getPart('torso', lodName).find('**/def_head').isEmpty():
                        self.toon.attach('head', 'torso', 'def_head', lodName)
                    else:
                        self.toon.attach('head', 'torso', 'joint_head', lodName)
                else:
                    self.toon.attach('head', 'torso', 'joint_head', lodName)
                self.toon.attach('torso', 'legs', 'joint_hips', lodName)
        else:
            self.toon.attach('head', 'torso', 'joint_head')
            self.toon.attach('torso', 'legs', 'joint_hips')

    def __fixHeadLongLong(self, lodName=None, copy=1):
        if lodName == None:
            searchRoot = self.toon
        else:
            searchRoot = self.toon.find('**/' + str(lodName))
        otherParts = searchRoot.findAllMatches('**/*short*')
        for partNum in xrange(0, otherParts.getNumPaths()):
            if copy:
                otherParts.getPath(partNum).removeNode()
            else:
                otherParts.getPath(partNum).stash()

        return

    def __fixHeadLongShort(self, lodName=None, copy=1):
        animalType = self.getAnimal()
        headStyle = self.head
        if lodName == None:
            searchRoot = self.toon
        else:
            searchRoot = self.toon.find('**/' + str(lodName))
        if animalType != 'duck' and animalType != 'horse':
            if animalType == 'rabbit':
                if copy:
                    searchRoot.find('**/ears-long').removeNode()
                else:
                    searchRoot.find('**/ears-long').hide()
            elif copy:
                searchRoot.find('**/ears-short').removeNode()
            else:
                searchRoot.find('**/ears-short').hide()
        if animalType != 'rabbit':
            if copy:
                searchRoot.find('**/eyes-short').removeNode()
            else:
                searchRoot.find('**/eyes-short').hide()
        if animalType != 'dog':
            if copy:
                searchRoot.find('**/joint_pupilL_short').removeNode()
                searchRoot.find('**/joint_pupilR_short').removeNode()
            else:
                searchRoot.find('**/joint_pupilL_short').stash()
                searchRoot.find('**/joint_pupilR_short').stash()
        if animalType != 'rabbit':
            muzzleParts = searchRoot.findAllMatches('**/muzzle-long*')
            for partNum in xrange(0, muzzleParts.getNumPaths()):
                if copy:
                    muzzleParts.getPath(partNum).removeNode()
                else:
                    muzzleParts.getPath(partNum).hide()

        else:
            muzzleParts = searchRoot.findAllMatches('**/muzzle-short*')
            for partNum in xrange(0, muzzleParts.getNumPaths()):
                if copy:
                    muzzleParts.getPath(partNum).removeNode()
                else:
                    muzzleParts.getPath(partNum).hide()

        return

    def __fixHeadShortLong(self, lodName=None, copy=1):
        animalType = self.getAnimal()
        headStyle = self.head
        if lodName == None:
            searchRoot = self.toon
        else:
            searchRoot = self.toon.find('**/' + str(lodName))
        if animalType != 'duck' and animalType != 'horse':
            if animalType == 'rabbit':
                if copy:
                    searchRoot.find('**/ears-short').removeNode()
                else:
                    searchRoot.find('**/ears-short').hide()
            elif copy:
                searchRoot.find('**/ears-long').removeNode()
            else:
                searchRoot.find('**/ears-long').hide()
        if animalType != 'rabbit':
            if copy:
                searchRoot.find('**/eyes-long').removeNode()
            else:
                searchRoot.find('**/eyes-long').hide()
        if animalType != 'dog':
            if copy:
                searchRoot.find('**/joint_pupilL_long').removeNode()
                searchRoot.find('**/joint_pupilR_long').removeNode()
            else:
                searchRoot.find('**/joint_pupilL_long').stash()
                searchRoot.find('**/joint_pupilR_long').stash()
        if copy:
            searchRoot.find('**/head-long').removeNode()
            searchRoot.find('**/head-front-long').removeNode()
        else:
            searchRoot.find('**/head-long').hide()
            searchRoot.find('**/head-front-long').hide()
        if animalType != 'rabbit':
            muzzleParts = searchRoot.findAllMatches('**/muzzle-short*')
            for partNum in xrange(0, muzzleParts.getNumPaths()):
                if copy:
                    muzzleParts.getPath(partNum).removeNode()
                else:
                    muzzleParts.getPath(partNum).hide()

        else:
            muzzleParts = searchRoot.findAllMatches('**/muzzle-long*')
            for partNum in xrange(0, muzzleParts.getNumPaths()):
                if copy:
                    muzzleParts.getPath(partNum).removeNode()
                else:
                    muzzleParts.getPath(partNum).hide()

        return

    def __fixHeadShortShort(self, lodName=None, copy=1):
        if lodName == None:
            searchRoot = self
        else:
            searchRoot = self.toon.find('**/' + str(lodName))
        otherParts = searchRoot.findAllMatches('**/*long*')
        for partNum in xrange(0, otherParts.getNumPaths()):
            if copy:
                otherParts.getPath(partNum).removeNode()
            else:
                otherParts.getPath(partNum).stash()

        return

    def setLODs(self):
        self.toon.setLODNode()
        levelOneIn = base.config.GetInt('lod1-in', 20)
        levelOneOut = base.config.GetInt('lod1-out', 0)
        levelTwoIn = base.config.GetInt('lod2-in', 80)
        levelTwoOut = base.config.GetInt('lod2-out', 20)
        levelThreeIn = base.config.GetInt('lod3-in', 280)
        levelThreeOut = base.config.GetInt('lod3-out', 80)
        self.toon.addLOD(1000, levelOneIn, levelOneOut)
        self.toon.addLOD(500, levelTwoIn, levelTwoOut)
        self.toon.addLOD(250, levelThreeIn, levelThreeOut)

    def loadPhaseAnims(self, phaseStr = 'phase_3', loadFlag = 1):
        if phaseStr == 'phase_3':
            animList = Phase3AnimList
        elif phaseStr == 'phase_3.5':
            animList = Phase3_5AnimList
        elif phaseStr == 'phase_4':
            animList = Phase4AnimList
        elif phaseStr == 'phase_5':
            animList = Phase5AnimList
        elif phaseStr == 'phase_5.5':
            animList = Phase5_5AnimList
        elif phaseStr == 'phase_6':
            animList = Phase6AnimList
        elif phaseStr == 'phase_9':
            animList = Phase9AnimList
        elif phaseStr == 'phase_10':
            animList = Phase10AnimList
        elif phaseStr == 'phase_12':
            animList = Phase12AnimList
        else:
            self.notify.error('Unknown phase string %s' % phaseStr)
        for key in LegDict.keys():
            for anim in animList:
                if loadFlag:
                    pass
                elif anim[0] in LegsAnimDict[key]:
                    if self.legs == key:
                        self.toon.unloadAnims([anim[0]], 'legs', None)

        for key in TorsoDict.keys():
            for anim in animList:
                if loadFlag:
                    pass
                elif anim[0] in TorsoAnimDict[key]:
                    if self.torso == key:
                        self.toon.unloadAnims([anim[0]], 'torso', None)

        for key in HeadDict.keys():
            if key.find('d') >= 0:
                for anim in animList:
                    if loadFlag:
                        pass
                    elif anim[0] in HeadAnimDict[key]:
                        if self.head == key:
                            self.toon.unloadAnims([anim[0]], 'head', None)
    def renderSnapshot(self):
        print 'Rendering Snapshot...'
        base.graphicsEngine.renderFrame()
        base.screenshot(namePrefix='snapshot-render', defaultFilename=1, source=None, imageComment="")


text:
{% load utils %}
{% load staticfiles %}
{% static 'herders/images/' as img_url_prefix %}

            {% if is_owner %}

                <button class="btn btn-default btn-xs rune-craft-edit" data-craft-id="{{ craft.pk.hex }}">

            </button>
            <button class="btn btn-default btn-xs rune-craft-delete" data-craft-id="{{ craft.pk.hex }}">

            </button>

            {% endif %}

{{ craft }}

            {% include 'herders/profile/runes/craft_image_fragment.html' with craft=craft only %}

                        {% if 'Ancient' in craft.get_type_display %}

                        {% endif %}
                        {{ craft.get_quality_display }}

                    Qty. {{ craft.quantity }}

                {% if craft.value %}

                        {{ craft.value }}

                {% endif %}