text:
import argparse
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import patches
import re
import matplotlib.animation as animation
from algebra import get_ellipse_from_covariance

def parse_args(*argument_list):
  parser = argparse.ArgumentParser()
  parser.add_argument('log_file')
  parser.add_argument('--save')
  parser.add_argument('--update-interval', type=int, default=500,
                      help='interval between frames in milliseconds')
  args = parser.parse_args(*argument_list)
  return args

def update_atoms(lines, i):
  clusters = {}
  for i in range(i, len(lines)):
    if not re.search('macrobase.analysis.stats.mixture.NormalWishartClusters: \d+', lines[i]):
      return clusters
    print lines[i]
    ci = int(re.search('macrobase.analysis.stats.mixture.NormalWishartClusters: (\d)', lines[i]).group(1))
    weight = re.search('weight: (\d+.\d+)', lines[i]).group(1)
    mean = re.search('mean: {([-]?\d+.\d+; [-]?\d+.\d+)}', lines[i]).group(1)
    mean = [float(x) for x in mean.split(';')]
    covObj = re.search('cov: Array2DRowRealMatrix{{([-]?\d+.\d+,[-]?\d+.\d+)},{([-]?\d+.\d+,[-]?\d+.\d+)}}', lines[i])
    beta = float(re.search('beta: ([-]?\d+.\d+)', lines[i]).group(1))
    dof = float(re.search('dof: (\d+.\d+)', lines[i]).group(1))
    scale = (dof + 1 - 2) * beta / (1 + beta)
    print 'beta, dof, scale', beta, dof, scale
    cov = [[scale * float(x) for x in covObj.group(1).split(',')],
           [scale * float(x) for x in covObj.group(2).split(',')]]
    clusters[ci] = (mean, cov)
  return clusters

def update_atoms_easy(lines, i):
  center_regex = re.compile('macrobase.analysis.stats.mixture.VariationalInference: centers = (.*)')
  cov_regex = re.compile('macrobase.analysis.stats.mixture.VariationalInference: covariances = (.*)')
  matrix_regex = re.compile('Array2DRowRealMatrix{{([-]?\d+.\d+,[-]?\d+.\d+)},{([-]?\d+.\d+,[-]?\d+.\d+)}}')
  vector_regex = re.compile('{([-]?\d+(.\d+)?; [-]?\d+(.\d+)?)}')

  def to_matrix(string_tuple):
    return [[float(x) for x in string.split(',')] for string in string_tuple]

  def to_vector(vector_string):
    return [float(x) for x in vector_string.split(';')]

  for i in range(i, len(lines)):
    if center_regex.search(lines[i]):
      centers = [to_vector(x[0]) for x in vector_regex.findall(lines[i])]
      print 'centers:', centers
    elif cov_regex.search(lines[i]):
      covs = [to_matrix(x) for x in matrix_regex.findall(lines[i])]
    else:
      return zip(*(centers, covs))

def update_weights(lines, i):
  coeffs_text = lines[i].split('weights = ')[-1].strip()
  coeffs_text = coeffs_text.strip('[]')
  return [float(x) for x in coeffs_text.split(',')]

def convert_into_ellipses(data):
  list_of_lists = []
  for weights, atoms in data:
    _list = []
    for i, (center, sigma) in enumerate(atoms):
      w, h, angle = get_ellipse_from_covariance(sigma)
      e = patches.Ellipse(center, w, h, angle=angle, label='%d' % i)
      e.set_alpha(weights[i])
      _list.append(e)
    list_of_lists.append(_list)
  return list_of_lists

def extract_data(lines, atom_regex, atom_updater, mixing_regex, mixing_updater):
  updated_weights, updated_atoms = False, False
  data = []
  for i in range(len(lines)):
    if atom_regex.search(lines[i]):
      atoms = atom_updater(lines, i)
      updated_atoms = True
    elif mixing_regex.search(lines[i]):
      weights = mixing_updater(lines, i)
      updated_weights = True
    if updated_weights and updated_atoms:
      data.append((weights, atoms))
      print 'weights: ', weights
      for a in atoms[:3]:
        print a
      updated_weights, updated_atoms = False, False
  return data

def original_clusters():
  clusters = [[(1.5,2),((0.5,0.4),(0.4,0.5)),50000],
              [(2,0),((0.3,0),(0,0.6)),30000],
              [(4.5,1),((0.9,0.2),(0.2,0.3)),20000]]
  artists = []
  for center, cov, weight in clusters:
    w, h, angle = get_ellipse_from_covariance(cov)
    e = patches.Ellipse(center, w, h, angle=angle, color='r')
    e.set_alpha(1. * weight / 60000)
    artists.append(e)
  return artists

def plot_per_iteration(args):
  atoms_regex = re.compile('centers = ')
  mixing_regex = re.compile('weights = ')
  list_of_lists = []
  fig = plt.figure()
  plt.xlabel('power_usage')
  plt.ylabel('time of day')
  ax = fig.add_subplot(111)

  with open(args.log_file) as infile:
    lines = list(infile)
  data = extract_data(lines, atoms_regex, update_atoms_easy, mixing_regex, update_weights)
  list_of_lists = convert_into_ellipses(data)

  def init():
    ax.set_xlim([0, 70])
    ax.set_ylim([0, 24])

  def animate(i):
    print 'animate', i
    ax.cla()
    ax.set_xlabel('power_usage')
    ax.set_ylabel('time of day')
    ax.set_title('%d' % i)
    # arts = original_clusters()
    # for a in arts:
    #   ax.add_artist(a)
    for art in list_of_lists[i]:
      ax.add_artist(art)
    return list_of_lists[i]

  print 'len', len(list_of_lists)
  ani = animation.FuncAnimation(fig, animate, np.arange(0, len(list_of_lists)),
                                interval=args.update_interval, blit=False,
                                init_func=init)
  if args.save:
    ani.save(args.save)
  else:
    plt.show()

if __name__ == '__main__':
  args = parse_args()
  plot_per_iteration(args)


text:
//This code was generated from ClipbordWatcherTypes file data

namespace ClipbordWatcherTypes{

	enum class MsgType{
		WindowHandle = 0,
		CopyData = 1,
		ClipboardUpdate = 2,
		DestroyClipboard = 3,
		RenderFormat = 4,
	};
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Seahinet\Promotion\Model\Condition;

class ProductId implements ConditionInterface
{

    public function match($model, $condition, $storeId)
    {
        if ($condition['identifier'] === 'product_id') {
            switch ($condition['operator']) {
                case '=':
                    foreach ($model->getItems(true) as $item) {
                        if ((!isset($item['store_id']) || $item['store_id'] == $storeId) && $item['product_id'] == $condition['value']) {
                            return true;
                        }
                    }
                    break;
                case '<>':
                case '!=':
                    foreach ($model->getItems(true) as $item) {
                        if ((!isset($item['store_id']) || $item['store_id'] == $storeId) && $item['product_id'] != $condition['value']) {
                            return true;
                        }
                    }
                    break;
            }
        }
        return false;
    }

}


text:
//*****************************************************************************
/*!
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *****************************************************************************
 *
 *  \file   request.cpp
 *
 *  \brief
 *  A request object.
 *
 *  \version
 *      - Sri Panyam      10/02/2009
 *        Created
 *
 *****************************************************************************/

#include "request.h"
#include "response.h"

#include <sstream>
#include <string.h>

// Creates a new http request object
SHttpRequest::SHttpRequest(SConnection *pConn) :
    scheme("http"),
    host(""),
    port(80),
    method("GET"),
    resource("/"),
    pContentBody(NULL),
    pConnection(pConn),
    pResponse(new SHttpResponse())
{
}

//! Resets to start all over again
void SHttpRequest::Reset(SConnection *pConn)
{
    SHttpMessage::Reset();
    if (pContentBody)
        pContentBody->Reset();

    if (pResponse)
        pResponse->Reset();

    pConnection = pConn;
}

// Clears a http req object
SHttpRequest::~SHttpRequest()
{
    if (pContentBody)
    {
        delete pContentBody;
        pContentBody = NULL;
    }

    if (pResponse)
    {
        delete pResponse;
        pResponse = NULL;
    }
}

// Gets the host
const SString &SHttpRequest::Host() const
{
    return host;
}

// Gets the port
int SHttpRequest::Port() const
{
    return port;
}

// Gets the method
const SString &SHttpRequest::Method() const
{
    return method;
}

// Sets the method
void SHttpRequest::SetMethod(const SString &m)
{
    method = m;
}

// Gets the method Resource
const SString &SHttpRequest::Resource() const
{
    return resource;
}

// Sets the request Resource
void SHttpRequest::SetResource(const SString &r)
{
    realResource                = r;
    const char *pStart          = r.c_str();
    const char *pEnd            = pStart + r.size();

    // set defaults
    port        = 80;
    queryValues.clear();

    // remove the scheme out - eg http:// or https://
    const char *pColSlashSlash  = strstr(pStart, "://");
    if (pColSlashSlash != NULL)
    {
        scheme = SString(pStart, pColSlashSlash - pStart);
        pStart = pColSlashSlash + 3;
    }
    else
    {
        scheme = "http";
    }

    const char *pHostEnd = pStart;
    // find the end of the host
    while (*pHostEnd != 0 && *pHostEnd != ':' && *pHostEnd != '/' && *pHostEnd != '?') pHostEnd++;

    if (*pHostEnd == 0)
    {
        host        = pStart;
        resource    = "";
        return ;
    }
    else if (*pHostEnd == ':')
    {
        host = SString(pStart, pHostEnd - pStart);

        // find port and resource
        pStart = ++pHostEnd;
        int newport = 0;
        while (*pHostEnd != 0 && isdigit(*pHostEnd))
        {
            newport = (newport * 10) + (*pHostEnd - '0');
            pHostEnd++;
        }
        if (newport != 0)
            port = newport;
    }

    pStart = pHostEnd;
    while (*pHostEnd != 0 && *pHostEnd != '?') pHostEnd++;
    resource = URLUtils::Unescape(SString(pStart, pHostEnd - pStart));

    if (*pHostEnd == '?')
    {
        // we have a query
        const char *pNextParam = pHostEnd;
        pStart = pNextParam + 1;

        do
        {
            pNextParam = strchr(pStart, '&');
            if (pNextParam == NULL) pNextParam = pEnd;
            const char *pEqPos = strchr(pStart, '=');
            if (pEqPos != NULL)
            {
                SString qName(pEqPos > pStart ? URLUtils::Unescape(SString(pStart, pEqPos - pStart)) : "");
                SString qValue(pEqPos + 1 < pNextParam ? URLUtils::Unescape(SString(pEqPos + 1, pNextParam - (pEqPos + 1))) : "");
                if (qName != "")
                {
                    queryValues.push_back(qName);
                    queryValues.push_back(qValue);
                }
            }
            else
            {
                break ;
            }
            pStart = pNextParam + 1;
        } while (pStart < pEnd);
    }
}

//! Get the value of a query param
SString SHttpRequest::GetQueryValue(const SString &param) const
{
    for (SStringList::const_iterator iter = queryValues.begin(); iter != queryValues.end();++iter)
    {
        if (*iter == param)
        {
            ++iter;
            return *iter;
        }
        else
        {
            ++iter;
        }
    }
    return "";
}

//! Parses the first line
bool SHttpRequest::ParseFirstLine(const SString &line)
{
    const char *pStart  = line.c_str();

    while (*pStart && isspace(*pStart)) pStart++;
    const char *pCurr = pStart;
    while (*pCurr && !isspace(*pCurr)) pCurr++;

    method = SString(pStart, pCurr - pStart);

    pStart = pCurr;
    while (*pStart && isspace(*pStart)) pStart++;

    if (!pStart) return false;
    pCurr = pStart;
    while (*pCurr && !isspace(*pCurr)) pCurr++;

    SetResource(SString(pStart, pCurr - pStart));

    pStart = pCurr;
    while (*pStart && isspace(*pStart)) pStart++;
    if (!pStart) return false;
    version = SString(pStart);

    SLogger::Get()->Log("\nDEBUG: ===============================\n");
    SLogger::Get()->Log("DEBUG: Request: %s %s %s\n",
                         method.c_str(), resource.c_str(), version.c_str());

    return true;
}

// Reads the request line
bool SHttpRequest::ReadFirstLine(std::istream &input)
{
    SString line = URLUtils::ReadTillCrLf(input);

    return ParseFirstLine(line);

    return true;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Ninject;

#if !SELFRUNNER
using NUnit.Framework;
#endif

using ImpromptuInterface.MVVM;
using ImpromptuInterface.MVVM.Ninject;

#if SILVERLIGHT
namespace UnitTestImpromptuInterface.Silverlight
#else
namespace UnitTestImpromptuInterface
#endif
{
    [TestFixture]
    public class NinjectTest
    {
        private readonly Assembly _assembly = Assembly.GetExecutingAssembly();

        [Test]
        public void Get_View()
        {
            var kernel = new StandardKernel();
            var container = new Container(kernel, typeof(IKernel), _assembly);
            var view = container.View.Test();

            Assert.IsInstanceOf<TestView>(view);
        }

        [Test]
        public void Get_ViewModel()
        {
            var kernel = new StandardKernel();
            var container = new Container(kernel, typeof(IKernel), _assembly);
            var viewModel = container.ViewModel.Test();

            Assert.IsInstanceOf<TestViewModel>(viewModel);
        }

        [Test]
        public void Get_ViewFor()
        {
            var kernel = new StandardKernel();
            var container = new Container(kernel, typeof(IKernel), _assembly);

            var viewModel = container.GetViewModel("Test");
            var view = container.GetViewFor(viewModel);

            Assert.IsInstanceOf<TestView>(view);
        }

        [Test]
        public void Get_Many()
        {
            var kernel = new StandardKernel();
            var container = new Container(kernel, typeof(IKernel), _assembly);

            foreach (var item in container.GetMany<ITestInterface>())
            {
                Assert.IsNotNull(item);
            }
        }

        [Test]
        public void Get_Many_Dynamic()
        {
            var kernel = new StandardKernel();
            var container = new Container(kernel, typeof(IKernel), _assembly);

            foreach (var item in container.GetMany("Testing123"))
            {
                Assert.IsInstanceOf<ITestInterface>(item);
            }
        }

        [Test]
        public void Get()
        {
            var kernel = new StandardKernel();
            var container = new Container(kernel, typeof(IKernel), _assembly);
            kernel.Bind<ITestInterface>().To<TestClassA>();
            var item = container.Get<ITestInterface>();

            Assert.IsInstanceOf<TestClassA>(item);
        }

        [Test]
        public void Get_Dynamic()
        {
            var kernel = new StandardKernel();
            var container = new Container(kernel, typeof(IKernel), _assembly);
            kernel.Bind<object>().To<TestClassC>().Named("Testing123");
            var item = container.Get("Testing123");

            Assert.IsInstanceOf<TestClassC>(item);
        }
    }
}


text:
import urllib2
import re
import os
import HTMLParser
import BeautifulSoup
import scholar as gs

GOOGLE_SCHOLAR_ID = "DDLTYpAAAAAJ"
class metadataExtraction:
    # get source
    def getSource(self,urlList):
        """ grap the web page source """
        content=""
        for url in urlList:
            req=urllib2.urlopen(url)
            newcontent=req.read()
            content+=newcontent
        return content

    def mainProcess(self,url):
        raw_data = self.getSource(url)
        soup = BeautifulSoup.BeautifulSoup(''.join(raw_data))
        papers_title = soup.findAll("a", { "class" : "gsc_a_at" })
        with open('publication.json', 'w') as f:
            for title in papers_title:
                articles = gs.query(search=title.string,
                        author='Si Chen',
                        max_results=1)
                f.write(articles[0].dumps('json').encode('utf8'))
                print(articles[0].dumps('json'))

if __name__ == "__main__":
    #test url list
    url_vetle=["https://scholar.google.com/citations?user="+GOOGLE_SCHOLAR_ID+"&hl=en"]

    me=metadataExtraction()
    me.mainProcess(url_vetle)


text:
package com.sinotrans.transport.gbs.model;

import com.sinotrans.framework.orm.model.BaseModel;

import javax.persistence.*;
import java.util.Date;

/**
 * Created by jason on 2016/6/2.
 */
@Entity
@Table(name = "TF_TRUCKING_ACT")
public class TruckingAct extends BaseModel {

    private String truckingActId;

    private String statusCode;

    private Date endTime;

    private String remarks;

    private String omsRemarks;

    public void setTruckingActId(String truckingActId) {
        this.truckingActId = truckingActId;
        addValidField("truckingActId");
    }

    public void setStatusCode(String statusCode) {
        this.statusCode = statusCode;
        addValidField("statusCode");
    }

    public void setEndTime(Date endTime) {
        this.endTime = endTime;
        addValidField("endTime");
    }

    public void setRemarks(String remarks) {
        this.remarks = remarks;
        addValidField("remarks");
    }

    public void setOmsRemarks(String omsRemarks) {
        this.omsRemarks = omsRemarks;
        addValidField("omsRemarks");
    }

    @Column(name = "TRUCKING_ACT_ID", length = 18)
    @SequenceGenerator(name="TRUCKING_ACT_ID", sequenceName="TRUCKING_ACT_ID",allocationSize = 1)
    @Id @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="TRUCKING_ACT_ID")
    public String getTruckingActId() {
        return truckingActId;
    }
    @Column(name = "STATUS_CODE", length = 12)
    public String getStatusCode() {
        return statusCode;
    }
    @Column(name = "END_TIME")
    public Date getEndTime() {
        return endTime;
    }
    @Column(name = "REMARKS")
    public String getRemarks() {
        return remarks;
    }
    @Column(name = "OMS_REMARKS")
    public String getOmsRemarks() {
        return omsRemarks;
    }
}


text:
#pragma once
#include <aws/swf/SWF_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace SWF
{
namespace Model
{
  enum class ChildPolicy
  {
    NOT_SET,
    TERMINATE,
    REQUEST_CANCEL,
    ABANDON
  };

namespace ChildPolicyMapper
{
AWS_SWF_API ChildPolicy GetChildPolicyForName(const Aws::String& name);

AWS_SWF_API Aws::String GetNameForChildPolicy(ChildPolicy value);
} // namespace ChildPolicyMapper
} // namespace Model
} // namespace SWF
} // namespace Aws


text:
#ifndef _BLUEDBM_THREAD_H
#define _BLUEDBM_THREAD_H

/*
 * Thread Implementation for Kernel Mode
 */
#if defined(KERNEL_MODE)

#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/sched.h>

#if LINUX_VERSION_CODE <= KERNEL_VERSION(3,5,0)
#define bdbm_daemonize(a) daemonize(a)
#else
#define bdbm_daemonize(a)
#endif

typedef struct {
	/* thread management */
	bdbm_mutex_t thread_done;
	wait_queue_head_t wq;
	wait_queue_t* wait;
	struct task_struct* thread;

	/* user management */
	void* user_data;
	int (*user_threadfn)(void *data);
} bdbm_thread_t;

#elif defined(USER_MODE)

#include <stdint.h>
#include <pthread.h>
#include "uatomic64.h"

#define SIGKILL	0xCCCC

typedef struct {
	/* thread management */
	bdbm_mutex_t thread_done;
	bdbm_mutex_t thread_sleep;
	pthread_cond_t thread_con;
	pthread_t thread;

	/* user management */
	void* user_data;
	int (*user_threadfn)(void *data);
} bdbm_thread_t;

#endif /* USER_MODE */

bdbm_thread_t* bdbm_thread_create (int (*threadfn)(void *data), void* data, char* name);
int bdbm_thread_run (bdbm_thread_t* k);
int bdbm_thread_schedule (bdbm_thread_t* k);
void bdbm_thread_wakeup (bdbm_thread_t* k);
void bdbm_thread_stop (bdbm_thread_t* k);
void bdbm_thread_msleep (uint32_t ms);
void bdbm_thread_yield (void);
void bdbm_thread_schedule_setup (bdbm_thread_t* k);
void bdbm_thread_schedule_cancel (bdbm_thread_t* k);
int bdbm_thread_schedule_sleep (bdbm_thread_t* k);

#endif /* _BLUEDBM_THREAD_H */


text:
package com.webcohesion.enunciate.modules.jaxb.api.impl;

import com.webcohesion.enunciate.api.InterfaceDescriptionFile;
import com.webcohesion.enunciate.api.datatype.DataType;
import com.webcohesion.enunciate.api.datatype.Namespace;
import com.webcohesion.enunciate.facets.FacetFilter;
import com.webcohesion.enunciate.modules.jaxb.model.ComplexTypeDefinition;
import com.webcohesion.enunciate.modules.jaxb.model.EnumTypeDefinition;
import com.webcohesion.enunciate.modules.jaxb.model.SchemaInfo;
import com.webcohesion.enunciate.modules.jaxb.model.TypeDefinition;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Ryan Heaton
 */
public class NamespaceImpl implements Namespace {

  private final SchemaInfo schema;

  public NamespaceImpl(SchemaInfo schema) {
    this.schema = schema;
  }

  @Override
  public String getUri() {
    String ns = this.schema.getNamespace();
    return ns == null ? "" : ns;
  }

  @Override
  public InterfaceDescriptionFile getSchemaFile() {
    return this.schema.getSchemaFile();
  }

  @Override
  public List<? extends DataType> getTypes() {
    FacetFilter facetFilter = this.schema.getContext().getContext().getConfiguration().getFacetFilter();

    ArrayList<DataType> dataTypes = new ArrayList<DataType>();
    for (TypeDefinition typeDefinition : this.schema.getTypeDefinitions()) {
      if (!facetFilter.accept(typeDefinition)) {
        continue;
      }

      if (typeDefinition instanceof ComplexTypeDefinition) {
        dataTypes.add(new ComplexDataTypeImpl((ComplexTypeDefinition) typeDefinition));
      }
      else if (typeDefinition instanceof EnumTypeDefinition) {
        dataTypes.add(new EnumDataTypeImpl((EnumTypeDefinition) typeDefinition));
      }
    }
    return dataTypes;
  }
}


text:
using System.Collections.Generic;

namespace TwitterOAuth.RestAPI.Models.Twitter
{
    public class Url
    {
        public List<UrlData> urls { get; set; }
    }
}


text:
<?php
namespace SimpleMvC\system;

/**
 * -----------------------------THE EXCEPTIONS CLASS---------------------------
 *
 * Extending classic php exceptions simply by adding a return url property
 *
 * ----------------------------------------------------------------------------
 */

class Controller_Exception extends \Exception
{
	/**
	 * The url to return to in case of an error or exception
	 *
	 * -------------------------CUSTOM VAR-------------------------------------
	 *
	 * the url to redirect to in the case of a error where error is anything
	 * that disables a controller from executing its action
	 *
	 * ------------------------------------------------------------------------
	 *
	 * @var string the url to return to in case of an exception
	 * @access private
	 *
	 */
	private $return_url;

	public function __construct($message, $return_url = '', $code = 0, Exception $previous = null)
	{
		$this->return_url=$return_url;

		parent::__construct($message, $code, $previous);
	}

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

?>


text:
$(function() {
    // anchor with a fixed menu
    if (location.hash) {
        var offset = $(location.hash).offset();
        if (offset) {
          setTimeout(function() {
              window.scrollTo(offset.left, offset.top - ACE_EDITOR_SCROLL_TOP_MARGIN);
          }, 1);
        }
    }

    // usage of http://dimsemenov.com/plugins/magnific-popup/
    $('.image-popup-vertical-fit').magnificPopup({
        type: 'image',
        closeOnContentClick: true,
        mainClass: 'mfp-img-mobile',
        image: {
            verticalFit: true
        }
    });
});


text:
require 'yaml'
require 'mongo'

class Car
  attr_reader :specs
  def initialize(specs={})
    @specs = specs
<<<<<<< HEAD
    @gas_prices = YAML.load_file( File.join(__dir__, '..', 'config', 'gas_prices.yaml'))
=======
    @gas_prices = YAML.load_file( File.join(__dir__, '..', 'config', 'gas_prices.yaml') )
    puts @gas_prices if $DEBUG
>>>>>>> d4e37d6582c2ca5b369042822ca7b5229a3049e5
  end

  def gallons_burned(miles = 100000, driving_type='city')
    return nil unless @specs.has_key?("mpg_#{driving_type}")
    mpg = @specs["mpg_#{driving_type}"].to_i

    miles / mpg
  end

  def total_gas_cost(gas_type = 'regular', miles=100000, driving_type='city')
    return nil unless @gas_prices.has_key?(gas_type.downcase.to_sym)

    @gas_prices[gas_type.downcase.to_sym].to_f * gallons_burned(miles, driving_type)
  end

  # Compute "fun" in terms of peak engine power per unit mass.
  # Computed here in horsepower peak per pound curb weight.
  def unit_horsepower
    hp = @specs['peak_power']
    weight = @specs['empty_weight']

    return nil if hp.nil? || weight.nil?

    hp.to_f / weight.to_i
  end

  # Compute how cost-effective the fun rating is for this car.
  # This is computed in terms of unit horsepower per TCO dollar * 1000000.
  # @param features [String] Either 'min' or 'loaded'.
  def giga_funs(features='min', gas_type='regular', miles = 100000)
    fun = unit_horsepower
    base_cost = @specs["msrp_#{features}"]
    gas_cost = total_gas_cost(gas_type, miles, 'city')
    return 0 if fun.nil? || base_cost.nil? || base_cost.to_i == 0 || base_cost == 'NULL'

    (fun.to_f * 1000000000 / (base_cost.to_f + gas_cost)).round(1)
  end

  def min_cost(driving_type = 'city', features = 'min')
    gas_cost = total_gas_cost(@specs['gas_type'].downcase, 100000, driving_type)
    gas_cost + @specs['msrp_min'].to_i
  end
  def max_cost(driving_type = 'city', features = 'min')
    gas_cost = total_gas_cost(@specs['gas_type'].downcase, 100000, driving_type)
    gas_cost + @specs['msrp_loaded'].to_i
  end

  def fun_descr(driving_type = 'city', features = 'min')
    gas_type = @specs['gas_type'].downcase
    puts "GasType=#{gas_type}" if $DEBUG
    gas_cost = total_gas_cost(gas_type, 100000, driving_type)
    puts "TotalGasCost=#{gas_cost}" if $DEBUG
    min_cost = gas_cost + @specs['msrp_min'].to_i
    max_cost = gas_cost + @specs['msrp_loaded'].to_i
    "#{@specs['year']}\t#{@specs['make']}\t#{@specs['model'].ljust(10,' ')}\t#{@specs['variant'].ljust(10,' ')}\t$#{min_cost} - $#{max_cost}\t#{giga_funs('min', gas_type)} - #{giga_funs('loaded', gas_type)}"
  end
end

if __FILE__ == $0
  cars = {} # Sort by price
  db = Mongo::MongoClient.new.db('shopping')
  coll = db['cars']
  cursor = coll.find({})
  cursor.each do |doc|
    data = doc.to_h
    puts data if $DEBUG
    car = Car.new(data)
    puts car.specs.nil? if $DEBUG
    cars[car.max_cost] = car
  end

  cars.keys.sort.each do |price|
    puts cars[price].fun_descr
  end
end


text:
require 'formula'

# NOTE: GCC 4.6.0 adds the gccgo compiler for the Go language. However,
# gccgo "is currently known to work on GNU/Linux and RTEMS. Solaris support
# is in progress. It may or may not work on other platforms."

def cxx?
  ARGV.include? '--enable-cxx'
end

def fortran?
  ARGV.include? '--enable-fortran'
end

def java?
  ARGV.include? '--enable-java'
end

def objc?
  ARGV.include? '--enable-objc'
end

def objcxx?
  ARGV.include? '--enable-objcxx'
end

def build_everything?
  ARGV.include? '--enable-all-languages'
end

def nls?
  ARGV.include? '--enable-nls'
end

def profiledbuild?
  ARGV.include? '--enable-profiled-build'
end

class Ecj < Formula
  # Little Known Fact: ecj, Eclipse Java Complier, is required in order to
  # produce a gcj compiler that can actually parse Java source code.
  url 'ftp://sourceware.org/pub/java/ecj-4.5.jar'
  md5 'd7cd6a27c8801e66cbaa964a039ecfdb'
end

class Gcc46 < Formula
  homepage 'http://gcc.gnu.org'
  url 'http://ftpmirror.gnu.org/gcc/gcc-4.6.3/gcc-4.6.3.tar.bz2'
  mirror 'http://ftp.gnu.org/gnu/gcc/gcc-4.6.3/gcc-4.6.3.tar.bz2'
  md5 '773092fe5194353b02bb0110052a972e'

  depends_on 'gmp'
  depends_on 'libmpc'
  depends_on 'mpfr'

  def patches
    { :p0 => ["http://gcc.gnu.org/bugzilla/attachment.cgi?id=25656"] }
  end

  def options
    [
      ['--enable-cxx', 'Build the g++ compiler'],
      ['--enable-fortran', 'Build the gfortran compiler'],
      ['--enable-java', 'Buld the gcj compiler'],
      ['--enable-objc', 'Enable Objective-C language support'],
      ['--enable-objcxx', 'Enable Objective-C++ language support'],
      ['--enable-all-languages', 'Enable all compilers and languages, except Ada'],
      ['--enable-nls', 'Build with natural language support'],
      ['--enable-profiled-build', 'Make use of profile guided optimization when bootstrapping GCC']
    ]
  end

  def install
    # Force 64-bit on systems that use it. Build failures reported for some
    # systems when this is not done.
    ENV.m64 if MacOS.prefer_64_bit?

    # GCC will suffer build errors if forced to use a particular linker.
    ENV.delete 'LD'

    ENV.remove_from_cflags '-Qunused-arguments'
    ENV.set_cpu_flags 'core2'

    # This is required on systems running a version newer than 10.6, and
    # it's probably a good idea regardless.
    #
    # https://trac.macports.org/ticket/27237
    ENV.append 'CXXFLAGS', '-U_GLIBCXX_DEBUG -U_GLIBCXX_DEBUG_PEDANTIC'

    gmp = Formula.factory 'gmp'
    mpfr = Formula.factory 'mpfr'
    libmpc = Formula.factory 'libmpc'

    # Sandbox the GCC lib, libexec and include directories so they don't wander
    # around telling small children there is no Santa Claus. This results in a
    # partially keg-only brew following suggestions outlined in the "How to
    # install multiple versions of GCC" section of the GCC FAQ:
    #     http://gcc.gnu.org/faq.html#multiple
    gcc_prefix = prefix + 'gcc'

    args = [
      # Sandbox everything...
      "--prefix=#{gcc_prefix}",
      # ...except the stuff in share...
      "--datarootdir=#{share}",
      # ...and the binaries...
      "--bindir=#{bin}",
      # ...which are tagged with a suffix to distinguish them.
      "--program-suffix=-#{version.to_s.slice(/\d\.\d/)}",
      "--with-gmp=#{gmp.prefix}",
      "--with-mpfr=#{mpfr.prefix}",
      "--with-mpc=#{libmpc.prefix}",
      "--with-system-zlib",
      "--enable-stage1-checking",
      "--enable-plugin",
      "--enable-lto",
      "--disable-multilib"
    ]

    args << '--disable-nls' unless nls?

    if build_everything?
      # Everything but Ada, which requires a pre-existing GCC Ada compiler
      # (gnat) to bootstrap. GCC 4.6.0 add go as a language option, but it is
      # currently only compilable on Linux.
      languages = %w[c c++ fortran java objc obj-c++]
    else
      # The C compiler is always built, but additional defaults can be added
      # here.
      languages = %w[c]

      languages << 'c++' if cxx?
      languages << 'fortran' if fortran?
      languages << 'java' if java?
      languages << 'objc' if objc?
      languages << 'obj-c++' if objcxx?
    end

    if java? or build_everything?
      source_dir = Pathname.new Dir.pwd

      Ecj.new.brew do |ecj|
        # Copying ecj.jar into the toplevel of the GCC source tree will cause
        # gcc to automagically package it into the installation. It *must* be
        # named ecj.jar and not ecj-version.jar in order for this to happen.
        mv "ecj-#{ecj.version}.jar", (source_dir + 'ecj.jar')
      end
    end

    Dir.mkdir 'build'
    Dir.chdir 'build' do
      system '../configure', "--enable-languages=#{languages.join(',')}", *args

      if profiledbuild?
        # Takes longer to build, may bug out. Provided for those who want to
        # optimise all the way to 11.
        system 'make profiledbootstrap'
      else
        system 'make bootstrap'
      end

      # At this point `make check` could be invoked to run the testsuite. The
      # deja-gnu and autogen formulae must be installed in order to do this.

      system 'make install'
    end
  end
end


text:
set -ev
# psql -c 'SELECT version();' -U postgres
psql -c 'create database filesender;'        -U postgres
psql -U postgres -c "alter user postgres with password 'password';"
php ./scripts/upgrade/database.php;

psql -c 'create database filesenderdataset;' -U postgres
bzcat ./scripts/dataset/dumps/filesender-2.0beta1.pg.bz2 | psql -d filesenderdataset


text:
#ifndef CTDAIO_H
#define CTDAIO_H

#include "ctresource.h"
#include "ctimap.h"
#include <linux/spinlock.h>
#include <linux/list.h>

/* Define the descriptor of a daio resource */
enum DAIOTYP {
	LINEO1,
	LINEO2,
	LINEO3,
	LINEO4,
	SPDIFOO,	/* S/PDIF Out (Flexijack/Optical) */
	LINEIM,
	SPDIFIO,	/* S/PDIF In (Flexijack/Optical) on the card */
	MIC,		/* Dedicated mic on Titanium HD */
	SPDIFI1,	/* S/PDIF In on internal Drive Bay */
	NUM_DAIOTYP
};

struct dao_rsc_ops;
struct dai_rsc_ops;
struct daio_mgr;

struct daio {
	struct rsc rscl;	/* Basic resource info for left TX/RX */
	struct rsc rscr;	/* Basic resource info for right TX/RX */
	enum DAIOTYP type;
};

struct dao {
	struct daio daio;
	struct dao_rsc_ops *ops;	/* DAO specific operations */
	struct imapper **imappers;
	struct daio_mgr *mgr;
	void *hw;
	void *ctrl_blk;
};

struct dai {
	struct daio daio;
	struct dai_rsc_ops *ops;	/* DAI specific operations */
	void *hw;
	void *ctrl_blk;
};

struct dao_desc {
	unsigned int msr:4;
	unsigned int passthru:1;
};

struct dao_rsc_ops {
	int (*set_spos)(struct dao *dao, unsigned int spos);
	int (*commit_write)(struct dao *dao);
	int (*get_spos)(struct dao *dao, unsigned int *spos);
	int (*reinit)(struct dao *dao, const struct dao_desc *desc);
	int (*set_left_input)(struct dao *dao, struct rsc *input);
	int (*set_right_input)(struct dao *dao, struct rsc *input);
	int (*clear_left_input)(struct dao *dao);
	int (*clear_right_input)(struct dao *dao);
};

struct dai_rsc_ops {
	int (*set_srt_srcl)(struct dai *dai, struct rsc *src);
	int (*set_srt_srcr)(struct dai *dai, struct rsc *src);
	int (*set_srt_msr)(struct dai *dai, unsigned int msr);
	int (*set_enb_src)(struct dai *dai, unsigned int enb);
	int (*set_enb_srt)(struct dai *dai, unsigned int enb);
	int (*commit_write)(struct dai *dai);
};

/* Define daio resource request description info */
struct daio_desc {
	unsigned int type:4;
	unsigned int msr:4;
	unsigned int passthru:1;
};

struct daio_mgr {
	struct rsc_mgr mgr;	/* Basic resource manager info */
	spinlock_t mgr_lock;
	spinlock_t imap_lock;
	struct list_head imappers;
	struct imapper *init_imap;
	unsigned int init_imap_added;

	 /* request one daio resource */
	int (*get_daio)(struct daio_mgr *mgr,
			const struct daio_desc *desc, struct daio **rdaio);
	/* return one daio resource */
	int (*put_daio)(struct daio_mgr *mgr, struct daio *daio);
	int (*daio_enable)(struct daio_mgr *mgr, struct daio *daio);
	int (*daio_disable)(struct daio_mgr *mgr, struct daio *daio);
	int (*imap_add)(struct daio_mgr *mgr, struct imapper *entry);
	int (*imap_delete)(struct daio_mgr *mgr, struct imapper *entry);
	int (*commit_write)(struct daio_mgr *mgr);
};

/* Constructor and destructor of daio resource manager */
int daio_mgr_create(void *hw, struct daio_mgr **rdaio_mgr);
int daio_mgr_destroy(struct daio_mgr *daio_mgr);

#endif /* CTDAIO_H */


text:
from django.db import models
from django.conf import settings
#from django.forms import ModelForm
#from schedules.models import Schedule
#from weddings.models import Wedding
#from places.models import Bakery, Venue

# ============= Blog ==============
'''
class Comment(models.Model):
	title = models.CharField(max_length=64)
	user = models.ForeignKey(settings.AUTH_USER_MODEL)
	datetime = models.DateTimeField()
	message = models.CharField(max_length=256)

class Blog(models.Model):
	title = models.CharField(max_length=64)
	user = models.ForeignKey(settings.AUTH_USER_MODEL)
	datetime = models.DateTimeField()
	abstract = models.CharField(max_length=256)
	content = models.CharField(max_length=10240)
	comments = models.ManyToManyField(Comment)

class Alarm(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    schedule = models.ForeignKey(Schedule)
    title = models.CharField(max_length=64)

    def __unicode__(self):
        return self.title
'''

class Notebook(models.Model):
    title = models.CharField(max_length=63)
    subscription = models.CharField(max_length=255, blank=True)
    owner = models.ForeignKey(settings.AUTH_USER_MODEL)
    partners = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='notebooks')
    #watching_venues = models.ManyToManyField(Venue, blank=True)
    #watching_bakeries = models.ManyToManyField(Bakery, blank=True)

    def __unicode__(self):
        return self.title

class Memo(models.Model):
    author = models.ForeignKey(settings.AUTH_USER_MODEL)
    recipients = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='memos')
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=63, blank=True)
    message = models.CharField(max_length=255)
    alarm = models.BooleanField(blank=True)
    #blogs = models.ManyToManyField(Blog)
    datetime = models.DateTimeField(blank=True, null=True)
    notebook = models.ForeignKey(Notebook, blank=True, null=True, related_name='memos')

    def __unicode__(self):
        return self.message

'''
# ===========  Form ==========

class MemoForm(ModelForm):
    class Meta:
        model = Memo
#fields = ['name', 'title', 'birth_date']
'''


text:
<?php

use Moa\API\Provider\ProviderInterface;

class BaseAPIController extends BaseController {

    protected $api;

    /**
     * @constructor
     */
    public function __construct(ProviderInterface $api) {
        $this->api = $api;
        $this->api->startSession();
    }

}


text:
@font-face {
	font-family: 'icomoon';
	src:url('fonts/icomoon.eot');
	src:url('fonts/icomoon.eot?#iefix') format('embedded-opentype'),
		url('fonts/icomoon.svg#icomoon?v=.2') format('svg'),
		url('fonts/icomoon.woff') format('woff'),
		url('fonts/icomoon.ttf') format('truetype');
	font-weight: normal;
	font-style: normal;
}

/* Use the following CSS code if you want to use data attributes for inserting your icons */
[data-icon]:before {
	font-family: 'icomoon';
	content: attr(data-icon);
	speak: none;
	font-weight: normal;
	line-height: 1;
	-webkit-font-smoothing: antialiased;
}

/* Use the following CSS code if you want to have a class per icon */
/*
Instead of a list of all class selectors,
you can use the generic selector below, but it's slower:
[class*="icon-"]:before {
*/
.icon-google-plus:before, .icon-facebook:before, .icon-twitter:before,.icon-pinterest:before, .icon-dribbble:before, .icon-github:before {
	font-family: 'icomoon';
	speak: none;
	font-style: normal;
	font-weight: normal;
	line-height: 1;
	-webkit-font-smoothing: antialiased;
}
.icon-facebook:before {
	content: "\66";
}
.icon-twitter:before {
	content: "\74";
}
.icon-github:before {
	content: "\69";
}
.icon-pinterest:before {
	content: "\70";
}
.icon-google-plus:before {
	content: "\67";
}
.icon-dribbble:before {
	content: "\64";
}

.icon-google-plus,.icon-facebook,.icon-twitter,.icon-pinterest,.icon-dribbble,.icon-github {
	display:inline-block;
}


text:
import json

from blog.models import BlogIndexPage as _BlogIndexPage
from blog.models import BlogPage as _BlogPage
from django.contrib import messages
from django.contrib.auth.views import login, logout, password_change
from django.db import models
from django.http.response import HttpResponseRedirect
from django.template.response import TemplateResponse
from django.utils.text import slugify
from django.shortcuts import render
from django.core.serializers.json import DjangoJSONEncoder
from django.forms.widgets import EmailInput
from django.db.models import F
from modelcluster.fields import ParentalKey, ParentalManyToManyField
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase

from wagtail.search.backends import get_search_backend
from wagtail.search.models import Query
from wagtail.search import index
from wagtail.contrib.routable_page.models import route, RoutablePageMixin
from wagtail.admin.edit_handlers import *
from wagtail.images.edit_handlers import ImageChooserPanel
from wagtail.core.fields import RichTextField, StreamField
from wagtail.core.models import Page
from wagtail.contrib.forms.models import AbstractFormField, AbstractEmailForm
from wagtail.admin.utils import send_mail
from wagtail.snippets.models import register_snippet

from isi_mip.climatemodels.blocks import InputDataBlock, OutputDataBlock, ImpactModelsBlock
from isi_mip.climatemodels.models import BaseImpactModel, SimulationRound, Sector
from isi_mip.climatemodels.views import (
    impact_model_details, impact_model_edit, input_data_details,
    impact_model_download, participant_download, show_participants, STEP_BASE, STEP_DETAIL, STEP_TECHNICAL_INFORMATION,
    STEP_INPUT_DATA, STEP_OTHER, STEP_SECTOR, STEP_ATTACHMENT,
    duplicate_impact_model, create_new_impact_model, update_contact_information_view, confirm_data, impact_model_pdf)
from isi_mip.contrib.blocks import BlogBlock, smart_truncate
from isi_mip.pages.blocks import *
from isi_mip.contrib.forms import AuthenticationForm

class BlogPage(_BlogPage):
    parent_page_types = ['pages.BlogIndexPage']

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context['blog'] = self
        try:
            rendition = self.header_image.get_rendition('max-800x800')
            context['image'] = {'url': rendition.url, 'name': self.header_image.title}
        except:
            pass
        return context

class BlogIndexPage(_BlogIndexPage):
    subpage_types = ['pages.BlogPage']
    description = RichTextField(null=True, blank=True)
    flat = models.BooleanField(default=False, help_text='Whether or not the index page should display items as a flat list or as blocks.')

    content_panels = _BlogIndexPage.content_panels + [
        RichTextFieldPanel('description'),
    ]
    settings_panels = Page.settings_panels + [
        FieldPanel('flat'),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)

        entries = self.blogs
        context['title'] = self.title

        context['entries'] = []
        for entry in entries:
            body = '' if entry.body.strip() == '

' else entry.body
            entry_context = {
                'date': entry.date,
                'href': entry.slug,
                'description': smart_truncate(body, 300, 350),
                'title': entry.title,
                'arrow_right_link': True
            }
            try:
                rendition = entry.header_image.get_rendition('fill-640x360-c100')
                entry_context['image'] = {'url': rendition.url, 'name': entry.header_image.title}
                entry_context['description'] = smart_truncate(body, 0, 100)
            except:
                pass
            context['entries'] += [entry_context]
        return context

    def serve(self, request, *args, **kwargs):
        if self.flat:
        # if 'flat' in request.GET and request.GET['flat'] == 'True':
            self.template = 'pages/blog_index_flat_page.html'
        return super(BlogIndexPage, self).serve(request, *args, **kwargs)

class TOCPage(Page):
    show_toc = models.BooleanField(default=False, help_text='Show Table of Contents')

    settings_panels = Page.settings_panels + [
        FieldPanel('show_toc'),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        if self.show_toc:
            context['toc'] = []
            for block in self.content:
                if block.block_type == 'heading':
                    link = "#"+slugify(block.value, allow_unicode=True)
                    context['toc'] += [{'href': link, 'text': block.value}]
        return context

    class Meta:
        abstract = True

class RoutablePageWithDefault(RoutablePageMixin, TOCPage):
    @route(r'^$')
    def base(self, request):
        return TemplateResponse(
            request,
            self.get_template(request),
            self.get_context(request)
        )

    class Meta:
        abstract = True

class GenericPage(TOCPage):
    template = 'pages/default_page.html'
    content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS)
    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]

    search_fields = Page.search_fields + [
        index.SearchField('content'),
    ]

class PaperOverviewPage(Page):
    content = StreamField(BASE_BLOCKS, blank=True)
    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        context['papers'] = PaperPage.objects.child_of(self).live().order_by('-year', '-first_published_at')
        context['tags'] = PaperPageTag.objects.filter(paper_page__in=context['papers']).distinct().order_by('order')
        context['simulation_rounds'] = SimulationRound.objects.all()
        context['sectors'] = Sector.objects.all()
        return context

@register_snippet
class PaperPageTag(models.Model):
    name = models.CharField(max_length=255)
    order = models.PositiveIntegerField(default=0)

    def __str__(self):
        return self.name

class PaperPage(Page):
    author = models.CharField(max_length=1000)
    journal = models.CharField(max_length=1000)
    year = models.CharField(max_length=1000)
    link = models.URLField()
    tags = ParentalManyToManyField('PaperPageTag', blank=True, related_name='paper_page')
    simulation_rounds = ParentalManyToManyField(SimulationRound, blank=True)
    sectors = ParentalManyToManyField(Sector, blank=True)

    parent_page_types = ['pages.PaperOverviewPage']

    content_panels = Page.content_panels + [
        FieldPanel('author'),
        FieldPanel('journal'),
        FieldPanel('year'),
        FieldPanel('link'),
        MultiFieldPanel([
            FieldPanel('simulation_rounds', widget=forms.CheckboxSelectMultiple),
            FieldPanel('sectors', widget=forms.CheckboxSelectMultiple),
            FieldPanel('tags', widget=forms.CheckboxSelectMultiple),
        ], heading="Tags")
    ]

    def get_journal_with_year(self):
        if self.year and not self.year == '-':
            return "%s (%s)" % (self.journal, self.year)
        else:
            return self.journal

class HomePage(RoutablePageWithDefault):
    parent_page_types = ['wagtailcore.Page']

    teaser_title = models.CharField(max_length=500)
    teaser_text = RichTextField()
    teaser_link_external = models.URLField("External link", blank=True,
                                           help_text="Will be ignored if an internal link is provided")
    teaser_link_internal = models.ForeignKey(
        'wagtailcore.Page',
        verbose_name="Or internal link",
        help_text='If set, this has precedence over the external link.',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        related_name='+',
    )

    number1_link = models.URLField(null=True, blank=True)
    number1_imported_number = models.CharField(max_length=255, null=True, blank=True)
    number2_link = models.URLField(null=True, blank=True)
    number2_imported_number = models.CharField(max_length=255, null=True, blank=True)

    content = StreamField([
        ('row', RowBlock([
            ('teaser', SmallTeaserBlock()),
            ('bigteaser', BigTeaserBlock(wideimage=True)),
            ('blog', BlogBlock()),
            ('numbers', IsiNumbersBlock()),
            ('twitter', TwitterBlock()),
        ])
         )
    ])

    content_panels = Page.content_panels + [
        MultiFieldPanel([
            FieldPanel('teaser_title'),
            RichTextFieldPanel('teaser_text'),
            MultiFieldPanel([
                FieldPanel('teaser_link_external'),
                PageChooserPanel('teaser_link_internal'),

            ]),
        ], heading='Teaser'),
        MultiFieldPanel([
            FieldPanel('number1_link'),
            FieldPanel('number1_imported_number'),
        ], heading='First import number', help_text='The manual number will be displayed in favor of the imported number.', classname="collapsible collapsed"),
        MultiFieldPanel([
            FieldPanel('number2_link'),
            FieldPanel('number2_imported_number'),
        ], heading='Second import number', help_text='The manual number will be displayed in favor of the imported number.', classname="collapsible collapsed"),
        StreamFieldPanel('content'),
    ]

    search_fields = Page.search_fields + [
        index.SearchField('teaser_text'),
        index.SearchField('teaser_title', partial_match=True),
        index.SearchField('content'),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        if self.teaser_link_internal:
            link = self.teaser_link_internal.url
        else:
            link = self.teaser_link_external
        context['teaser'] = {
            'title': self.teaser_title,
            'text': self.teaser_text,
            'button': {
                'href': link,
                'text': 'Read more',
                'fontawesome': 'facebook',
            }
        }
        context['noborder'] = True
        return context

    @route(r'search/$')
    def search(self, request):
        subpage = {'title': 'Search', 'url': ''}
        context = {'page': self, 'subpage': subpage, 'headline': ''}
        # Search
        search_query = request.GET.get('query', None)
        if search_query:
            page_results = Page.objects.live().not_type((BlogPage, BlogIndexPage)).search(search_query).annotate_score("score")

            # Log the query so Wagtail can suggest promoted results
            Query.get(search_query).add_hit()

            # Also query non-wagtail models
            s = get_search_backend()
            model_results = s.search(search_query, BaseImpactModel.objects.filter(impact_model__public=True))

        else:
            page_results = []
            model_results = []

        context.update({
            'search_query': search_query,
            'page_results': page_results,
            'model_results': model_results,
        })
        # raise Exception(dir(model_results[0]))
        # raise Exception(search_results)

        # Render template
        return render(request, 'pages/search_page.html', context)

class AboutPage(TOCPage):
    template = 'pages/default_page.html'

    content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS + [
        ('pdf', PDFBlock()),
        ('paper', PaperBlock(template='widgets/page-teaser-wide.html')),
        ('bigteaser', BigTeaserBlock()),
        ('contact', ContactsBlock()),
    ])
    content_panels = Page.content_panels + [
        StreamFieldPanel('content')
    ]

    search_fields = Page.search_fields + [
        index.SearchField('content'),
    ]

class GettingStartedPage(RoutablePageWithDefault):
    template = 'pages/default_page.html'
    parent_page_types = [HomePage, 'GettingStartedPage']

    content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS + [
        ('protocol', ProtocolBlock()),
        ('input_data', InputDataBlock()),
        ('contact', ContactsBlock()),
        ('blog', BlogBlock(template='blocks/flat_blog_block.html')),

    ])
    input_data_description = RichTextField(null=True, blank=True, verbose_name='Input Data Details Description')

    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]
    details_content_panels = [
        RichTextFieldPanel('input_data_description'),
    ]
    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(details_content_panels, heading='Input Data Details'),
        ObjectList(RoutablePageWithDefault.promote_panels, heading='Promote'),
        ObjectList(RoutablePageWithDefault.settings_panels, heading='Settings', classname="settings"),
    ])
    search_fields = Page.search_fields + [
        index.SearchField('content'),
    ]

    @route(r'^details/(?P<id>\d+)/$')
    def details(self, request, id):
        return input_data_details(self, request, id)

class ImpactModelsPage(RoutablePageWithDefault):
    template = 'pages/default_page.html'
    parent_page_types = [HomePage]

    content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS + [
        ('impact_models', ImpactModelsBlock()),
        ('blog', BlogBlock(template='blocks/flat_blog_block.html')),
    ])
    private_model_message = models.TextField()
    common_attributes_text = models.TextField()

    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]
    settings_panels = RoutablePageWithDefault.settings_panels + [
        FieldPanel('private_model_message'),
        FieldPanel('common_attributes_text'),
    ]
    search_fields = Page.search_fields + [
        index.SearchField('content'),
    ]

    @route(r'^details/(?P<id>\d+)/$')
    def details(self, request, id):
        return impact_model_details(self, request, id)

    @route(r'^confirm-data/(?P<id>\d+)/$')
    def confirm_data(self, request, id):
        return confirm_data(self, request, id)

    @route(r'^pdf/(?P<id>\d+)/$')
    def pdf(self, request, id):
        return impact_model_pdf(self, request, id)

    @route(r'edit/(?P<id>[0-9]*)/$')
    def edit_base(self, request, id=None):
        return impact_model_edit(self, request, id, STEP_BASE)

    @route(r'edit/model-reference/(?P<id>[0-9]*)/$')
    def edit_detail(self, request, id=None):
        return impact_model_edit(self, request, id, STEP_DETAIL)

    @route(r'edit/resolution/(?P<id>[0-9]*)/$')
    def edit_technical_information(self, request, id=None):
        return impact_model_edit(self, request, id, STEP_TECHNICAL_INFORMATION)

    @route(r'edit/input-data/(?P<id>[0-9]*)/$')
    def edit_input_data(self, request, id=None):
        return impact_model_edit(self, request, id, STEP_INPUT_DATA)

    @route(r'edit/model-setup/(?P<id>[0-9]*)/$')
    def edit_other(self, request, id=None):
        return impact_model_edit(self, request, id, STEP_OTHER)

    @route(r'edit/sector/(?P<id>[0-9]*)/$')
    def edit_sector(self, request, id=None):
        return impact_model_edit(self, request, id, STEP_SECTOR)

    @route(r'edit/attachment/(?P<id>[0-9]*)/$')
    def edit_attachment(self, request, id=None):
        return impact_model_edit(self, request, id, STEP_ATTACHMENT)

    @route(r'duplicate/(?P<impact_model_id>[0-9]*)/(?P<simulation_round_id>[0-9]*)/$')
    def duplicate(self, request, impact_model_id=None, simulation_round_id=None):
        return duplicate_impact_model(self, request, impact_model_id, simulation_round_id)

    @route(r'create/(?P<base_model_id>[0-9]*)/(?P<simulation_round_id>[0-9]*)/$')
    def create(self, request, base_model_id=None, simulation_round_id=None):
        return create_new_impact_model(self, request, base_model_id, simulation_round_id)

    @route(r'download/$')
    def download(self, request):
        return impact_model_download(self, request)

class OutputDataPage(TOCPage):
    template = 'pages/default_page.html'
    parent_page_types = [HomePage]

    content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS + [
        ('output_data', OutputDataBlock()),
        ('blog', BlogBlock(template='blocks/flat_blog_block.html')),
    ])
    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]
    search_fields = Page.search_fields + [
        index.SearchField('content'),
    ]

class OutcomesPage(TOCPage):
    template = 'pages/default_page.html'

    content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS + [
        ('papers', PapersBlock()),
    ])
    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]
    search_fields = Page.search_fields + [
        index.SearchField('content'),
    ]

class FAQPage(TOCPage):
    template = 'pages/default_page.html'
    parent_page_types = [HomePage]

    content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS + [
        ('faqs', FAQsBlock()),
    ])
    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]
    search_fields = Page.search_fields + [
        index.SearchField('content'),
    ]

class LinkListPage(TOCPage):
    template = 'pages/default_page.html'

    content = StreamField(BASE_BLOCKS + [
        ('links', ListBlock(LinkBlock(), template='blocks/link_list_block.html', icon='fa fa-list-ul')),
        ('supporters', SupportersBlock())
    ])

    content_panels = Page.content_panels + [
        StreamFieldPanel('content'),
    ]
    search_fields = Page.search_fields + [
        index.SearchField('content'),
    ]

class DashboardPage(RoutablePageWithDefault):
    impact_models_description = RichTextField(null=True, blank=True)
    content_panels = Page.content_panels + [
        RichTextFieldPanel('impact_models_description'),
    ]

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        base_impact_models = request.user.userprofile.owner.all().order_by('name')
        if request.user.is_authenticated() and request.user.is_superuser:
            base_impact_models = BaseImpactModel.objects.all()
        impage = ImpactModelsPage.objects.get()
        impage_details = lambda imid: "{{0}}".format(
            impage.url + impage.reverse_subpage('details', args=(imid, )))
        impage_edit = lambda imid: " Edit model information for {{0}}".format(
            impage.url + impage.reverse_subpage('edit_base', args=(imid,)))
        impage_create = lambda bmid, srid: " Enter ALL new model information for {{0}}".format(
            impage.url + impage.reverse_subpage('create', args=(bmid, srid)))
        impage_duplicate = lambda imid, srid: " Use model information for {{0}} as starting point for {{1}}".format(
            impage.url + impage.reverse_subpage('duplicate', args=(imid, srid)))
        context['head'] = {
            'cols': [{'text': 'Model'}, {'text': 'Sector'}, {'text': 'Simulation round'}, {'text': 'Public'}, {'text': 'Action'}]
        }

        bodyrows = []
        for bims in base_impact_models:
            for imodel in bims.impact_model.all():
                values = [
                    [impage_details(bims.id).format(bims.name)],
                    [bims.sector.name],
                    [imodel.simulation_round.name],
                    [''.format('check' if imodel.public else 'times')],
                    [impage_edit(imodel.id).format(imodel.simulation_round.name)],
                ]
                row = {
                    'cols': [{'texts': x} for x in values],
                }
                bodyrows.append(row)
            duplicate_impact_model = bims.can_duplicate_from()
            for sr in bims.get_missing_simulation_rounds():
                duplicate_model_text = ''
                if duplicate_impact_model:
                    duplicate_model_text = impage_duplicate(duplicate_impact_model.id, sr.id).format(duplicate_impact_model.simulation_round, sr.name)
                values = [
                    [bims.name],
                    [bims.sector.name],
                    [sr.name],
                    [],
                    [
                        impage_create(bims.id, sr.id).format(sr.name),
                        duplicate_model_text
                    ],
                ]
                row = {
                    'cols': [{'texts': x} for x in values],
                }
                bodyrows.append(row)
        context['body'] = {'rows': bodyrows}
        if request.user.groups.filter(name='ISIMIP-Team').exists():
            context['show_participants_link'] = True
        return context

    @route(r'^$')
    def base(self, request):
        if not request.user.is_authenticated():
            messages.info(request, 'This is a restricted area. To proceed you need to log in.')
            return HttpResponseRedirect(self.reverse_subpage('login'))

        return TemplateResponse(
            request,
            self.get_template(request),
            self.get_context(request)
        )

    @route(r'participants/$')
    def participants(self, request):
        if not request.user.is_authenticated():
            messages.info(request, 'This is a restricted area. To proceed you need to log in.')
            return HttpResponseRedirect(self.reverse_subpage('login'))
        subpage = {'title': 'ISIMIP participants', 'url': ''}
        context = {'page': self, 'subpage': subpage, 'headline': ''}
        return show_participants(request, extra_context=context)

    @route(r'download/$')
    def download(self, request):
        if not request.user.is_authenticated():
            messages.info(request, 'This is a restricted area. To proceed you need to log in.')
            return HttpResponseRedirect(self.reverse_subpage('login'))
        return participant_download(self, request)

    @route(r'logout/$')
    def logout(self, request):
        subpage = {'title': 'Logout', 'url': ''}
        context = {'page': self, 'subpage': subpage, 'headline': ''}
        return logout(request, extra_context=context)

    @route(r'login/$')
    def login(self, request):
        subpage = {'title': 'Login', 'url': ''}
        context = {'page': self, 'subpage': subpage, 'headline': ''}
        return login(request, extra_context=context, authentication_form=AuthenticationForm)

    @route(r'change-password/$')
    def change_password(self, request):
        if not request.user.is_authenticated():
            messages.info(request, 'This is a restricted area. To proceed you need to log in.')
            return HttpResponseRedirect(self.reverse_subpage('login'))
        subpage = {'title': 'Change password', 'url': ''}
        context = {'page': self, 'subpage': subpage, 'headline': ''}
        return password_change(request, extra_context=context)

    @route(r'update-contact-information/$')
    def update_contact_information(self, request):
        if not request.user.is_authenticated():
            messages.info(request, 'This is a restricted area. To proceed you need to log in.')
            return HttpResponseRedirect(self.reverse_subpage('login'))
        subpage = {'title': 'Update contact information', 'url': ''}
        context = {'page': self, 'subpage': subpage, 'headline': ''}
        return update_contact_information_view(request, self, extra_context=context)

class FormField(AbstractFormField):
    page = ParentalKey('FormPage', related_name='form_fields')

class FormPage(AbstractEmailForm):
    landing_page_template = 'pages/form_page_confirmation.html'
    subpage_types = []

    top_content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS, blank=True)
    confirmation_text = models.TextField(default='Your registration was submitted')
    send_confirmation_email = models.BooleanField(default=False, verbose_name='Send confirmation email?')
    confirmation_email_subject = models.CharField(default='ISIMIP Form submission confirmation.', max_length=500, verbose_name='Email subject', null=True, blank=True)
    confirmation_email_text = models.TextField(default='The form was submitted successfully. We will get back to you soon.', verbose_name='Email text', null=True, blank=True)
    bottom_content = StreamField(BASE_BLOCKS + COLUMNS_BLOCKS, blank=True)

    button_name = models.CharField(max_length=500, verbose_name='Button name', default='Submit')

    content_panels = AbstractEmailForm.content_panels + [
        StreamFieldPanel('top_content'),
        StreamFieldPanel('bottom_content')
    ]
    form_content_panels = [
        InlinePanel('form_fields', label="Form fields"),
        FieldPanel('button_name'),
        FieldPanel('confirmation_text', classname="full"),
        MultiFieldPanel([
            FieldPanel('send_confirmation_email'),
            FieldPanel('confirmation_email_subject'),
            FieldPanel('confirmation_email_text', classname="full"),
        ], "Confirmation email"),
        MultiFieldPanel([
            FieldPanel('to_address', classname="full"),
            FieldPanel('from_address', classname="full"),
            FieldPanel('subject', classname="full"),
        ], "Email"),
    ]
    search_fields = Page.search_fields + [
        index.SearchField('top_content'),
        index.SearchField('bottom_content'),
    ]

    edit_handler = TabbedInterface([
        ObjectList(content_panels, heading='Content'),
        ObjectList(form_content_panels, heading='Form Builder'),
        ObjectList(AbstractEmailForm.promote_panels, heading='Promote'),
        ObjectList(AbstractEmailForm.settings_panels, heading='Settings', classname="settings"),
    ])

    def get_context(self, request, *args, **kwargs):
        context = super().get_context(request, *args, **kwargs)
        message = {'tags': 'success', 'text': self.confirmation_text}
        context['confirmation_messages'] = [message]
        return context

    def serve(self, request, *args, **kwargs):
        context = self.get_context(request)
        if request.method == 'POST':
            form = self.get_form(request.POST, page=self, user=request.user)

            if form.is_valid():
                self.process_form_submission(form)

                # render the landing_page
                # TODO: It is much better to redirect to it
                return render(
                    request,
                    self.get_landing_page_template(request),
                    self.get_context(request)
                )
            else:
                context['form_error'] = 'One of the fields below has not been filled out correctly. Please correct and resubmit.'
        else:
            form = self.get_form(page=self, user=request.user)

        context['form'] = form
        return render(
            request,
            self.get_template(request),
            context
        )

    def process_form_submission(self, form):
        self.get_submission_class().objects.create(
            form_data=json.dumps(form.cleaned_data, cls=DjangoJSONEncoder), page=self
        )
        if self.to_address:
            self.send_mail(form)
        if self.send_confirmation_email:
            # quick hack sending a confirmation email to the user
            confirmation_email_address = None
            # check for confirmation email address and filter headings
            for field in form:
                if isinstance(field.field.widget, EmailInput):
                    confirmation_email_address = field.value()
                    break
            if confirmation_email_address:
                extra_content = ['', ]
                for field in form:
                    value = field.value()
                    if isinstance(value, list):
                        value = ', '.join(value)
                    extra_content.append('{}: {}'.format(field.label, value))
                extra_content = '\n'.join(extra_content)
                send_mail(self.confirmation_email_subject, self.confirmation_email_text + extra_content, [confirmation_email_address, ], self.from_address,)


text:
using System.Buffers;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace System.IO.Pipelines.Tests
{
    public class SchedulerFacts
    {
        private class ThreadScheduler : PipeScheduler, IDisposable
        {
            private readonly BlockingCollection<Action> _work = new BlockingCollection<Action>();

            public ThreadScheduler()
            {
                Thread = new Thread(Work) { IsBackground = true };
                Thread.Start();
            }

            public Thread Thread { get; }

            public void Dispose()
            {
                _work.CompleteAdding();
            }

            public override void Schedule(Action action)
            {
                Schedule(o => ((Action)o)(), action);
            }

            public override void Schedule(Action<object> action, object state)
            {
                _work.Add(() => action(state));
            }

            private void Work(object state)
            {
                foreach (Action callback in _work.GetConsumingEnumerable())
                {
                    callback();
                }
            }
        }

        [Fact]
        public async Task DefaultReaderSchedulerRunsOnThreadPool()
        {
            var pipe = new Pipe();

            var id = 0;

            Func<Task> doRead = async () =>
            {
                ReadResult result = await pipe.Reader.ReadAsync();

                Assert.True(Thread.CurrentThread.IsThreadPoolThread);

                pipe.Reader.AdvanceTo(result.Buffer.End, result.Buffer.End);

                pipe.Reader.Complete();
            };

            Task reading = doRead();

            id = Thread.CurrentThread.ManagedThreadId;

            PipeWriter buffer = pipe.Writer;
            buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
            await buffer.FlushAsync();

            pipe.Writer.Complete();

            await reading;
        }

        [Fact]
        public async Task DefaultWriterSchedulerRunsOnThreadPool()
        {
            using (var pool = new TestMemoryPool())
            {
                var pipe = new Pipe(
                    new PipeOptions(
                        pool,
                        resumeWriterThreshold: 32,
                        pauseWriterThreshold: 64
                    ));

                PipeWriter writableBuffer = pipe.Writer.WriteEmpty(64);
                PipeAwaiter<FlushResult> flushAsync = writableBuffer.FlushAsync();

                Assert.False(flushAsync.IsCompleted);

                var id = 0;

                Func<Task> doWrite = async () =>
                {
                    await flushAsync;

                    pipe.Writer.Complete();

                    Assert.True(Thread.CurrentThread.IsThreadPoolThread);
                };

                Task writing = doWrite();

                ReadResult result = await pipe.Reader.ReadAsync();

                id = Thread.CurrentThread.ManagedThreadId;

                pipe.Reader.AdvanceTo(result.Buffer.End, result.Buffer.End);

                pipe.Reader.Complete();

                await writing;
            }
        }

        [Fact]
        public async Task FlushCallbackRunsOnWriterScheduler()
        {
            using (var pool = new TestMemoryPool())
            {
                using (var scheduler = new ThreadScheduler())
                {
                    var pipe = new Pipe(
                        new PipeOptions(
                            pool,
                            resumeWriterThreshold: 32,
                            pauseWriterThreshold: 64,
                            readerScheduler: PipeScheduler.Inline,
                            writerScheduler: scheduler));

                    PipeWriter writableBuffer = pipe.Writer.WriteEmpty(64);
                    PipeAwaiter<FlushResult> flushAsync = writableBuffer.FlushAsync();

                    Assert.False(flushAsync.IsCompleted);

                    Func<Task> doWrite = async () =>
                    {
                        int oid = Thread.CurrentThread.ManagedThreadId;

                        await flushAsync;

                        Assert.NotEqual(oid, Thread.CurrentThread.ManagedThreadId);

                        pipe.Writer.Complete();

                        Assert.Equal(Thread.CurrentThread.ManagedThreadId, scheduler.Thread.ManagedThreadId);
                    };

                    Task writing = doWrite();

                    ReadResult result = await pipe.Reader.ReadAsync();

                    pipe.Reader.AdvanceTo(result.Buffer.End, result.Buffer.End);

                    pipe.Reader.Complete();

                    await writing;
                }
            }
        }

        [Fact]
        public async Task ReadAsyncCallbackRunsOnReaderScheduler()
        {
            using (var pool = new TestMemoryPool())
            {
                using (var scheduler = new ThreadScheduler())
                {
                    var pipe = new Pipe(new PipeOptions(pool, scheduler, writerScheduler: PipeScheduler.Inline));

                    Func<Task> doRead = async () =>
                    {
                        int oid = Thread.CurrentThread.ManagedThreadId;

                        ReadResult result = await pipe.Reader.ReadAsync();

                        Assert.NotEqual(oid, Thread.CurrentThread.ManagedThreadId);

                        Assert.Equal(Thread.CurrentThread.ManagedThreadId, scheduler.Thread.ManagedThreadId);

                        pipe.Reader.AdvanceTo(result.Buffer.End, result.Buffer.End);

                        pipe.Reader.Complete();
                    };

                    Task reading = doRead();

                    PipeWriter buffer = pipe.Writer;
                    buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
                    await buffer.FlushAsync();

                    await reading;
                }
            }
        }

        [Fact]
        public async Task ThreadPoolScheduler_SchedulesOnThreadPool()
        {
            var pipe = new Pipe(new PipeOptions(readerScheduler: PipeScheduler.ThreadPool, writerScheduler: PipeScheduler.Inline));

            async Task DoRead()
            {
                int oid = Thread.CurrentThread.ManagedThreadId;

                ReadResult result = await pipe.Reader.ReadAsync();

                Assert.NotEqual(oid, Thread.CurrentThread.ManagedThreadId);
                Assert.True(Thread.CurrentThread.IsThreadPoolThread);
                pipe.Reader.AdvanceTo(result.Buffer.End, result.Buffer.End);
                pipe.Reader.Complete();
            }

            bool callbackRan = false;
            Task reading = DoRead();

            PipeWriter buffer = pipe.Writer;
            pipe.Writer.OnReaderCompleted((state, exception) =>
                {
                    callbackRan = true;
                    Assert.True(Thread.CurrentThread.IsThreadPoolThread);
                }, null);
            buffer.Write(Encoding.UTF8.GetBytes("Hello World"));
            await buffer.FlushAsync();

            await reading;

            Assert.True(callbackRan);
        }
    }
}


text:
using System.Data.Entity;

namespace FinancesSharp.Models
{
    public class EmptyInitializer : IDatabaseInitializer<FinanceDb>
    {
        public void InitializeDatabase(FinanceDb context)
        {
            //do nothing
        }
    }
}


text:
'use strict'

const joi = require('joi')

const envVarsSchema = joi.object({
  NODE_ENV: joi.string()
    .allow(['production', 'development'])
    .required(),
  NODE_LEVEL: joi.string()
    .allow(['error', 'warn', 'info', 'verbose', 'debug', 'silly'])
    .required()
}).unknown()
  .required()

const { error, value: envVars } = joi.validate(process.env, envVarsSchema)
if (error) {
  throw new Error(`Config validation error: ${error.message}`)
}

const config = {
  env: envVars.NODE_ENV,
  level: envVars.NODE_LEVEL
}

module.exports = config


text:
require("awful")
require("awful.autofocus")
require("awful.rules")
-- Theme handling library
require("beautiful")
-- Notification library
require("naughty")

-- {{{ Variable definitions
-- Themes define colours, icons, and wallpapers
	beautiful.init("/usr/share/awesome/themes/sky/theme.lua")

-- This is used later as the default terminal and editor to run.
terminal = "xterm"
editor = os.getenv("EDITOR") or "nano"
editor_cmd = terminal .. " -e " .. editor

-- Default modkey.
-- Usually, Mod4 is the key with a logo between Control and Alt.
-- If you do not like this or do not have such a key,
-- I suggest you to remap Mod4 to another key using xmodmap or other tools.
-- However, you can use another modifier like Mod1, but it may interact with others.
modkey = "Mod4"

-- Table of layouts to cover with awful.layout.inc, order matters.
layouts =
{
    awful.layout.suit.floating,
    awful.layout.suit.tile,
    awful.layout.suit.tile.left,
    awful.layout.suit.tile.bottom,
    awful.layout.suit.tile.top,
    awful.layout.suit.fair,
    awful.layout.suit.fair.horizontal,
    awful.layout.suit.spiral,
    awful.layout.suit.spiral.dwindle,
    awful.layout.suit.max,
    awful.layout.suit.max.fullscreen,
    awful.layout.suit.magnifier
}
-- }}}

-- {{{ Tags
-- Define a tag table which hold all screen tags.
tags = {}
for s = 1, screen.count() do
    -- Each screen has its own tag table.
    tags[s] = awful.tag({ 1, 2, 3, 4, 5, 6, 7, 8, 9 }, s, layouts[1])
end
-- }}}

-- {{{ Menu
-- Create a laucher widget and a main menu
mylaunchmenu = {
   { "firefox" 		, "firefox" },
   { "thunderbird" 	, "thunderbird" },
   { "pidgin"		, "pidgin" },
   { "sonata"		, "sonata" }
}

myawesomemenu = {
   { "manual", terminal .. " -e man awesome" },
   { "edit config", editor_cmd .. " " .. awful.util.getdir("config") .. "/rc.lua" },
   { "restart", awesome.restart },
   { "quit", awesome.quit }
}

mymainmenu = awful.menu({ items = { { "launch",mylaunchmenu },
				    { "awesome", myawesomemenu, beautiful.awesome_icon },
                                    { "open terminal", terminal }
                                  }
                        })

mylauncher = awful.widget.launcher({ image = image(beautiful.awesome_icon),
                                     menu = mymainmenu })
-- }}}

-- {{{ Wibox
-- Create a textclock widget
mytextclock = awful.widget.textclock({ align = "right" })

-- Create a systray
mysystray = widget({ type = "systray" })

-- Create a wibox for each screen and add it
mywibox = {}
mypromptbox = {}
mylayoutbox = {}
mytaglist = {}
mytaglist.buttons = awful.util.table.join(
                    awful.button({ }, 1, awful.tag.viewonly),
                    awful.button({ modkey }, 1, awful.client.movetotag),
                    awful.button({ }, 3, awful.tag.viewtoggle),
                    awful.button({ modkey }, 3, awful.client.toggletag),
                    awful.button({ }, 4, awful.tag.viewnext),
                    awful.button({ }, 5, awful.tag.viewprev)
                    )
mytasklist = {}
mytasklist.buttons = awful.util.table.join(
                     awful.button({ }, 1, function (c)
                                              if not c:isvisible() then
                                                  awful.tag.viewonly(c:tags()[1])
                                              end
                                              client.focus = c
                                              c:raise()
                                          end),
                     awful.button({ }, 3, function ()
                                              if instance then
                                                  instance:hide()
                                                  instance = nil
                                              else
                                                  instance = awful.menu.clients({ width=250 })
                                              end
                                          end),
                     awful.button({ }, 4, function ()
                                              awful.client.focus.byidx(1)
                                              if client.focus then client.focus:raise() end
                                          end),
                     awful.button({ }, 5, function ()
                                              awful.client.focus.byidx(-1)
                                              if client.focus then client.focus:raise() end
                                          end))
require("lib/volcontrol")
for s = 1, screen.count() do
    -- Create a promptbox for each screen
    mypromptbox[s] = awful.widget.prompt({ layout = awful.widget.layout.horizontal.leftright })
    -- Create an imagebox widget which will contains an icon indicating which layout we're using.
    -- We need one layoutbox per screen.
    mylayoutbox[s] = awful.widget.layoutbox(s)
    mylayoutbox[s]:buttons(awful.util.table.join(
                           awful.button({ }, 1, function () awful.layout.inc(layouts, 1) end),
                           awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end),
                           awful.button({ }, 4, function () awful.layout.inc(layouts, 1) end),
                           awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end)))
    -- Create a taglist widget
    mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.label.all, mytaglist.buttons)

    -- Create a tasklist widget
    mytasklist[s] = awful.widget.tasklist(function(c)
                                              return awful.widget.tasklist.label.currenttags(c, s)
                                          end, mytasklist.buttons)
    myvolbox = volcontrol.new({ mixer="Master",channel="Mono"})
    myvolbox:run()

    -- Create the wibox
    mywibox[s] = awful.wibox({ position = "top", screen = s })
    -- Add widgets to the wibox - order matters
    mywibox[s].widgets = {
        {
            mylauncher,
            mytaglist[s],
            mypromptbox[s],
            layout = awful.widget.layout.horizontal.leftright
        },
        mylayoutbox[s],
        mytextclock,
	myvolbox.widget,
        s == 1 and mysystray or nil,
        mytasklist[s],
        layout = awful.widget.layout.horizontal.rightleft
    }
end
-- }}}

-- {{{ Mouse bindings
root.buttons(awful.util.table.join(
    awful.button({ }, 3, function () mymainmenu:toggle() end),
    awful.button({ }, 4, awful.tag.viewnext),
    awful.button({ }, 5, awful.tag.viewprev)
))
-- }}}

-- {{{ Key bindings
globalkeys = awful.util.table.join(
    awful.key({ modkey,           }, "Left",   awful.tag.viewprev       ),
    awful.key({ modkey,           }, "Right",  awful.tag.viewnext       ),
    awful.key({ modkey,           }, "Escape", awful.tag.history.restore),

    awful.key({ modkey,           }, "j",
        function ()
            awful.client.focus.byidx( 1)
            if client.focus then client.focus:raise() end
        end),
    awful.key({ modkey,           }, "k",
        function ()
            awful.client.focus.byidx(-1)
            if client.focus then client.focus:raise() end
        end),
    awful.key({ modkey,           }, "w", function () mymainmenu:show({keygrabber=true}) end),

    -- Layout manipulation
    awful.key({ modkey, "Shift"   }, "j", function () awful.client.swap.byidx(  1)    end),
    awful.key({ modkey, "Shift"   }, "k", function () awful.client.swap.byidx( -1)    end),
    awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end),
    awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end),
    awful.key({ modkey,           }, "u", awful.client.urgent.jumpto),
    awful.key({ modkey,           }, "Tab",
        function ()
            awful.client.focus.history.previous()
            if client.focus then
                client.focus:raise()
            end
        end),

    -- Standard program
    awful.key({ modkey,           }, "Return", function () awful.util.spawn(terminal) end),
    awful.key({ modkey, "Control" }, "r", awesome.restart),
    awful.key({ modkey, "Shift"   }, "q", awesome.quit),

    awful.key({ modkey,           }, "l",     function () awful.tag.incmwfact( 0.05)    end),
    awful.key({ modkey,           }, "h",     function () awful.tag.incmwfact(-0.05)    end),
    awful.key({ modkey, "Shift"   }, "h",     function () awful.tag.incnmaster( 1)      end),
    awful.key({ modkey, "Shift"   }, "l",     function () awful.tag.incnmaster(-1)      end),
    awful.key({ modkey, "Control" }, "h",     function () awful.tag.incncol( 1)         end),
    awful.key({ modkey, "Control" }, "l",     function () awful.tag.incncol(-1)         end),
    awful.key({ modkey,           }, "space", function () awful.layout.inc(layouts,  1) end),
    awful.key({ modkey, "Shift"   }, "space", function () awful.layout.inc(layouts, -1) end),

    -- Prompt
    awful.key({ modkey },            "r",     function () mypromptbox[mouse.screen]:run() end),

    awful.key({ modkey }, "x",
              function ()
                  awful.prompt.run({ prompt = "Run Lua code: " },
                  mypromptbox[mouse.screen].widget,
                  awful.util.eval, nil,
                  awful.util.getdir("cache") .. "/history_eval")
              end)
)

clientkeys = awful.util.table.join(
    awful.key({ modkey,           }, "f",      function (c) c.fullscreen = not c.fullscreen  end),
    awful.key({ modkey, "Shift"   }, "c",      function (c) c:kill()                         end),
    awful.key({ modkey, "Control" }, "space",  awful.client.floating.toggle                     ),
    awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end),
    awful.key({ modkey,           }, "o",      awful.client.movetoscreen                        ),
    awful.key({ modkey, "Shift"   }, "r",      function (c) c:redraw()                       end),
    awful.key({ modkey,           }, "t",      function (c) c.ontop = not c.ontop            end),
    awful.key({ modkey,           }, "n",      function (c) c.minimized = not c.minimized    end),
    awful.key({ modkey,           }, "m",
        function (c)
            c.maximized_horizontal = not c.maximized_horizontal
            c.maximized_vertical   = not c.maximized_vertical
        end)
)

-- Compute the maximum number of digit we need, limited to 9
keynumber = 0
for s = 1, screen.count() do
   keynumber = math.min(9, math.max(#tags[s], keynumber));
end

-- Bind all key numbers to tags.
-- Be careful: we use keycodes to make it works on any keyboard layout.
-- This should map on the top row of your keyboard, usually 1 to 9.
for i = 1, keynumber do
    globalkeys = awful.util.table.join(globalkeys,
        awful.key({ modkey }, "#" .. i + 9,
                  function ()
                        local screen = mouse.screen
                        if tags[screen][i] then
                            awful.tag.viewonly(tags[screen][i])
                        end
                  end),
        awful.key({ modkey, "Control" }, "#" .. i + 9,
                  function ()
                      local screen = mouse.screen
                      if tags[screen][i] then
                          awful.tag.viewtoggle(tags[screen][i])
                      end
                  end),
        awful.key({ modkey, "Shift" }, "#" .. i + 9,
                  function ()
                      if client.focus and tags[client.focus.screen][i] then
                          awful.client.movetotag(tags[client.focus.screen][i])
                      end
                  end),
        awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9,
                  function ()
                      if client.focus and tags[client.focus.screen][i] then
                          awful.client.toggletag(tags[client.focus.screen][i])
                      end
                  end))
end

clientbuttons = awful.util.table.join(
    awful.button({ }, 1, function (c) client.focus = c; c:raise() end),
    awful.button({ modkey }, 1, awful.mouse.client.move),
    awful.button({ modkey }, 3, awful.mouse.client.resize))

-- Set keys
root.keys(globalkeys)
-- }}}

-- {{{ Rules
awful.rules.rules = {
    -- All clients will match this rule.
    { rule = { },
      properties = { border_width = beautiful.border_width,
                     border_color = beautiful.border_normal,
                     focus = true,
                     keys = clientkeys,
                     buttons = clientbuttons } },
    { rule = { class = "MPlayer" },
      properties = { floating = true } },
    { rule = { class = "pinentry" },
      properties = { floating = true } },
    { rule = { class = "gimp" },
      properties = { floating = true } },
    -- Set Firefox to always map on tags number 2 of screen 1.
    -- { rule = { class = "Firefox" },
    --   properties = { tag = tags[1][2] } },
}
-- }}}

-- {{{ Signals
-- Signal function to execute when a new client appears.
client.add_signal("manage", function (c, startup)
    -- Add a titlebar
    -- awful.titlebar.add(c, { modkey = modkey })

    -- Enable sloppy focus
    c:add_signal("mouse::enter", function(c)
        if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
            and awful.client.focus.filter(c) then
            client.focus = c
        end
    end)

    if not startup then
        -- Set the windows at the slave,
        -- i.e. put it at the end of others instead of setting it master.
        -- awful.client.setslave(c)

        -- Put windows in a smart way, only if they does not set an initial position.
        if not c.size_hints.user_position and not c.size_hints.program_position then
            awful.placement.no_overlap(c)
            awful.placement.no_offscreen(c)
        end
    end
end)

client.add_signal("focus", function(c) c.border_color = beautiful.border_focus end)
client.add_signal("unfocus", function(c) c.border_color = beautiful.border_normal end)
-- }}}


text: package org.zhoubangtao.daemon.service;


text:
package org.sakaiproject.entitybroker.entityprovider.capabilities;

import java.util.Map;

import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.entityprovider.EntityProvider;

/**
 * This entity type can be updated (this is the U in CRUD),
 * the current user id should be used for permissions checking in most cases

 * This is one of the capability extensions for the {@link EntityProvider} interface

 *
 * @author Aaron Zeckoski (aaron@caret.cam.ac.uk)
 */
public interface Updateable extends Resolvable {

   /**
    * Update an existing entity,
    * the object should contain the data needed to update the entity or this will fail

    * Typically the entity will be retrieved first using {@link Resolvable#getEntity(EntityReference)}
    * and the the fields will be updated and it will be passed into this method
    *
    * @param ref the parsed reference object which uniquely represents this entity
    * @param entity an entity object
    * @param params (optional) incoming set of parameters which may be used to send data specific to this request, may be null
    * @throws IllegalArgumentException if the entity could not be updated because of missing or invalid data or could not find entity to update
    * @throws SecurityException if permissions prevented this entity from being updated
    * @throws IllegalStateException for all other failures
    */
   public void updateEntity(EntityReference ref, Object entity, Map<String, Object> params);

}


text:
import Ember from 'ember';
import DS from 'ember-data';

var get = Ember.get;

export default DS.JSONSerializer.extend({
  primaryKey: "_id",
  keyDelimiter: "::",

  collate: function(array) {
    return array.join(get(this, "keyDelimiter"));
  },

  decollate: function(string) {
    return string.split(get(this, "keyDelimiter"));
  },

  normalize: function(type, hash) {
    hash = this._super.apply(this, arguments);

    if (hash.id) {
      hash.id = this.decollate(hash.id)[1];
    }

    this.normalizeRev(hash);

    return hash;
  },

  normalizeRev: function(hash) {
    hash.rev = hash._rev;
    delete hash._rev;
  },

  serialize: function(record, options) {
    var json = this._super.apply(this, arguments),
        type = record.constructor;

    if (options.includeId) {
      json._id = this.collate([ type.typeKey, json._id ]);
    }

    if (options.includeRev) {
      json._rev = get(record, "data.rev");
    }

    return json;
  },

  extractSave: function(store, type, payload) {
    payload.id = this.decollate(payload.id)[1];

    delete payload.ok;

    return payload;
  }
});


text:
/**
 * Package for convert list test classes.
 * Конвертация двумерного массива в ArrayList и наоборот [#10035]
 * Написать программу преобразования List в Map. [#10093]
 *
 * @author Alexey Krasnopolsky (mailto:aak91@mail.ru)
 * @version $Id$
 * @since 0.1
 */

package ru.job4j.convert;