text:
{% extends "base.html" %}

{% block content %}

Deprecated column definition guide

        Before version 0.9 and the Datatable configuration class it introduced, all
        options had to be specified in one big dictionary and assigned as an attribute on the view.
        For simple tables, view attributes weren't that so bad, but it didn't take much to get
        out of control.  You should avoid using it when building new tables.

        Using this configuration style, you name a model field and the table would find the model
        field's verbose name for display purposes.  To use a custom verbose name, or if the column
        needed to show more than one model field worth of data (a method, property, two concatenated
        field values, etc) then the column had to become a 2- or 3-tuple of settings.

        The following formats are all valid (but deprecated) ways to write a column definition on
        a ``LegacyConfigurationDatatableView`` or ``LegacyDatatableView``, via the
        datatable_options class attribute dict:

datatable_options = {
    'columns': [
        # "concrete" field backed by the database
        'name',  # field's verbose_name will be used
        ("Name", 'name'),  # custom verbose name provided
        ("Name", 'name', 'callback_attr_name'),  # callback looked up on view
        ("Name", 'name', callback_handle),  # calback used directly

        # non-field, but backed by methods, properties, etc
        "Virtual Field",

        # "fake" virtual field whose data is generated by the view
        ("Virtual Field", None, 'callback_attr_name'),
        ("Virtual Field", None, callback_handle),
    ],
}

        For concrete fields that also provide callbacks, the actual database value will be consulted
        during searches and sorts, but the table will use the return value of the callback as the
        display data.

        Virtual fields are useful ways to mount methods onto a table.  Consider a read-only property
        that generates its return value based on some underlying database field:

datatable_options = {
    'columns': [
        ("Average profit", 'get_average_profit'),
    ],
}

        Be careful with virtual columns that might cause database queries per-row.  That doesn't
        scale very well!

{% endblock content %}


text:
package com.paritytrading.philadelphia;

/**
 * Indicates a heartbeat timeout.
 */
public class FIXHeartbeatTimeoutException extends FIXException {

    /**
     * Construct an instance with the specified detail message.
     *
     * @param message the detail message
     */
    public FIXHeartbeatTimeoutException(String message) {
        super(message);
    }

}

redpajama_set_name: RedPajamaGithub


text:
package es.gob.afirma.core.misc.http;

/** Factoría para la obtención de un manejador para la lectura y envío de datos a URL remotas.
 * @author Carlos Gamuci */
public abstract class UrlHttpManagerFactory {

	private static UrlHttpManager staticUrlManager = null;

	/**
	 * Instala el manejador que se encargará de realizar las conexiones con las URL indicadas.
	 * @param urlManager Manejador de conexicion para la lectura y envío de datos. */
	public static void install(final UrlHttpManager urlManager) {
		staticUrlManager = urlManager;
	}

	/**
	 * Recupera el manejador instalado o, en su defecto, el manejador por defecto.
	 * @return Manejador de conexiónes.
	 */
	public static UrlHttpManager getInstalledManager() {
		if (staticUrlManager == null) {
			staticUrlManager = new UrlHttpManagerImpl();
		}
		return staticUrlManager;
	}
}


text:
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///puppyshelter.db')
from test.tutorial_shelter import Base, Puppy
from datetime import datetime, timedelta

Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)

session = DBSession()

puppies = session.query(Puppy).order_by(Puppy.name.asc())
for pup in puppies:
    print(pup.name)
print()
young_puppies = session.query(Puppy).filter(datetime.now() - timedelta(weeks=6*4) <= Puppy.dateOfBirth).order_by(Puppy.dateOfBirth.asc())
for pup in young_puppies:
    print(pup.name, pup.dateOfBirth)
print()
weight_puppies = session.query(Puppy).order_by(Puppy.weight.asc())
for pup in weight_puppies:
    print(pup.name, pup.weight)
print()
shelters = session.query(func.count(Puppy.shelter_id), Puppy.shelter_id).group_by(Puppy.shelter_id).all()
print(shelters)
for shelter in shelters:
    print(shelter.shelter_id, shelter[0])


text:
using System;
using UnityEngine;
using System.Collections;
using Devdog.General;
using Devdog.SciFiDesign.UI;
using UnityEngine.Events;
using UnityEngine.UI;

namespace Devdog.SciFiDesign
{
    public class ShipVisuals : MonoBehaviour
    {
        [System.Serializable]
        public class Element
        {
            public float displayValueMultiplier = 1f;

            [Required]
            public ImageFillInterpolator fill;
            public float increaseFactor = 1f;
            public float decreaseFactor = 1f;
            public float startValue = 0f;

            [Header("UI")]
            public Text text;
            public string textFormat = "{0} AU/S";
            public Color fromColor = Color.green;
            public Color toColor = Color.green;
            public AnimationCurve blendCurve = AnimationCurve.EaseInOut(0f, 0f, 1f, 1f);

            public float value { get; protected set; }
            public float maxValue { get; set; }

            public Element()
            {
                this.value = startValue;
            }

            public void Increase()
            {
                value += Time.deltaTime * increaseFactor;
                value = Mathf.Clamp(value, startValue, fill.minFrom + ((fill.maxTo - fill.minFrom) * maxValue) + startValue);

                Repaint();
            }

            public void Decrease()
            {
                value -= Time.deltaTime * decreaseFactor;
                value = Mathf.Max(value, startValue);

                Repaint();
            }

            public void Repaint()
            {
                var c = fill.minFrom + ((fill.maxTo - fill.minFrom) * (value / (fill.minFrom + ((fill.maxTo - fill.minFrom) * maxValue))));
                fill.image.fillAmount = Mathf.Clamp(c, fill.minFrom, fill.maxTo);

                var p = blendCurve.Evaluate(value / (fill.minFrom + ((fill.maxTo - fill.minFrom) * maxValue)));
                fill.image.color = Color.Lerp(fromColor, toColor, p);

                text.text = string.Format(textFormat, System.Math.Round(value * displayValueMultiplier, 2));
            }
        }

        [Header("Particle systems")]
        [Required]
        public ParticleSystem small;

        [Required]
        public ParticleSystem medium;

        [Header("Speed")]
        public Element speed = new Element();

        [Header("G-Force")]
        public Element gForce = new Element();
        public UnityEvent onGForceWarningAboveEvent = new UnityEvent();
        public UnityEvent onGForceWarningBelowEvent = new UnityEvent();

        private float _warningGForceSpeed = 10f;
        private bool _boost = false;
        private bool _aboveGForceLimit = false;

        protected virtual void Start()
        {
            speed.maxValue = 5;
            gForce.maxValue = 32;

            small.Play();
        }

        protected void Update()
        {
            if (Input.GetKeyDown(KeyCode.LeftShift))
            {
                StartBoost();
            }
            else if (Input.GetKeyUp(KeyCode.LeftShift))
            {
                StopBoost();
            }

            if (_boost)
            {
                DoBoost();
            }
            else
            {
                RestoreBoost();
            }
        }

        protected virtual void RestoreBoost()
        {
            if (speed.value > 0f)
            {
                speed.Decrease();
            }

            if (gForce.value > 0f)
            {
                gForce.Decrease();

                if (_aboveGForceLimit)
                {
                    _aboveGForceLimit = false;
                    onGForceWarningBelowEvent.Invoke();
                }
            }
        }

        protected virtual void DoBoost()
        {
            speed.Increase();
            gForce.Increase();

            if (gForce.value > _warningGForceSpeed && _aboveGForceLimit == false)
            {
                _aboveGForceLimit = true;
                onGForceWarningAboveEvent.Invoke();
            }
        }

        protected virtual void StartBoost()
        {
            medium.Play();
            _boost = true;
        }

        protected virtual void StopBoost()
        {
            medium.Stop();
            _boost = false;
        }
    }
}


text:
package ve.web.chebetos.xsd_analizer.lib;

import java.io.File;

import org.apache.ws.commons.schema.XmlSchema;
import org.apache.ws.commons.schema.XmlSchemaCollection;
import org.junit.Assert;
import org.junit.Test;

public class ApacheSchemaLoaderTest {

    @Test
    public void canParseAFile() {
    	final String schemaTestFile = "./src";
    	XmlSchemaCollection schemaCollection = ApacheSchemaLoader.getInstance().parse(new File(schemaTestFile));
    	Assert.assertNotNull(schemaCollection);

    	XmlSchema[] schemas =  schemaCollection.getXmlSchemas();
    	Assert.assertTrue(schemas.length > 0);
    }

    //leer un esquema (comprobar que trae un esquema y probar que pasa si tiene import)
    //leer un directorio (comprobar que carga varios esquemas)

    //listar elementos en un esquema
    //listar tipos
    //OBJETIVO: poner por cada tipo (global) el elemento (global) del esquema donde se usa.
}


text:
layout: guida
title: Guida
permalink: /guida/
---


text:
require File.expand_path('../../../lib/admit_one',  __FILE__)
require 'test/unit'

class LockFileTest < Test::Unit::TestCase

  def setup
    File.delete(lock_file_path) if File.exist?(lock_file_path)
  end

  def test_should_create_and_remove_lockfile
    block_executed = false
    AdmitOne::LockFile.new(:admit_one_lock_file_unit_test) do
      block_executed = true
      assert(File.exist?(lock_file_path))
    end
    assert(block_executed)
    assert(!File.exist?(lock_file_path))
  end

  def test_should_not_clobber_another_lock_file
    File.open(lock_file_path, "a") { |file| file.write("1\n") }
    assert_raise(AdmitOne::LockFailure) do
      AdmitOne::LockFile.new(:admit_one_lock_file_unit_test) do
        assert false #should never run
      end
    end
    assert(File.exist?(lock_file_path))
    File.delete(lock_file_path)
  end

  #######
  private
  #######

  def lock_file_path
    "#{Dir.tmpdir}/admit_one_lock_file_unit_test.lock"
  end
end


text:
#import <Foundation/Foundation.h>
#import <Metal/Metal.h>

#import "BrouMacro.h"
#import "BrouStruct.h"
#import "BrouUtils.h"
#import "BrouConvertType.h"
#import "BrouShareBuffer.h"
#import "BrouTensor.h"
#import "BrouLayer.h"

#define type uint16_t
#define real half
#define real_is_half

#include "Basic/BrouUniqueTensor.h"
#include "Basic/BrouTemporaryTensor.h"

#include "Layer/Generate/BrouConvolutionLayer.h"
#include "Layer/Generate/BrouConvolutionMMLayer.h"
#include "Layer/Generate/BrouTransposedConvolutionLayer.h"
#include "Layer/Generate/BrouTransposedConvolutionMMLayer.h"
#include "Layer/Generate/BrouDilatedConvolutionLayer.h"
#include "Layer/Generate/BrouDilatedConvolutionMMLayer.h"
#include "Layer/Generate/BrouMaxPoolingLayer.h"
#include "Layer/Generate/BrouAveragePoolingLayer.h"
#include "Layer/Generate/BrouTanHLayer.h"
#include "Layer/Generate/BrouReLuLayer.h"
#include "Layer/Generate/BrouPReLuLayer.h"
#include "Layer/Generate/BrouLinearLayer.h"
#include "Layer/Generate/BrouFullConnectLayer.h"
#include "Layer/Generate/BrouAddLayer.h"
#include "Layer/Generate/BrouAddBiasLayer.h"
#include "Layer/Generate/BrouBatchNormalizationLayer.h"
#undef real
#undef real_is_half
#undef type

#define type float
#define real float
#define real_is_float

#include "Basic/BrouUniqueTensor.h"
#include "Basic/BrouTemporaryTensor.h"

#include "Layer/Generate/BrouConvolutionLayer.h"
#include "Layer/Generate/BrouConvolutionMMLayer.h"
#include "Layer/Generate/BrouTransposedConvolutionLayer.h"
#include "Layer/Generate/BrouTransposedConvolutionMMLayer.h"
#include "Layer/Generate/BrouDilatedConvolutionLayer.h"
#include "Layer/Generate/BrouDilatedConvolutionMMLayer.h"
#include "Layer/Generate/BrouMaxPoolingLayer.h"
#include "Layer/Generate/BrouAveragePoolingLayer.h"
#include "Layer/Generate/BrouTanHLayer.h"
#include "Layer/Generate/BrouReLuLayer.h"
#include "Layer/Generate/BrouPReLuLayer.h"
#include "Layer/Generate/BrouLinearLayer.h"
#include "Layer/Generate/BrouFullConnectLayer.h"
#include "Layer/Generate/BrouAddLayer.h"
#include "Layer/Generate/BrouAddBiasLayer.h"
#include "Layer/Generate/BrouBatchNormalizationLayer.h"
#undef real
#undef real_is_float
#undef type

/**
 * a convert layer used to convert number type
 */
#define from uchar
#define to half
#include "Layer/Generate/BrouConvertLayer.h"
#undef to
#undef from

#define from half
#define to uchar
#include "Layer/Generate/BrouConvertLayer.h"
#undef to
#undef from

#define from half
#define to float
#include "Layer/Generate/BrouConvertLayer.h"
#undef to
#undef from

#define from float
#define to half
#include "Layer/Generate/BrouConvertLayer.h"
#undef to
#undef from

#define from uchar
#define to float
#include "Layer/Generate/BrouConvertLayer.h"
#undef to
#undef from

#define from float
#define to uchar
#include "Layer/Generate/BrouConvertLayer.h"
#undef to
#undef from


text:
<?php

namespace Clc\ExpensemanagerBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * expense
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Clc\ExpensemanagerBundle\Entity\expenseRepository")
 */
class expense
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    protected $name;

    /**
     * @var float
     *
     * @ORM\Column(name="amount", type="decimal")
     */
    protected $amount;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="addedDate", type="datetime")
     */
    protected $addedDate;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="date")
     */
    protected $date;

    /**
     * @var boolean
     *
     * @ORM\Column(name="active", type="boolean")
     */
    protected $active = true;

    /**
     * @ORM\ManyToOne(targetEntity="Clc\UserBundle\Entity\User", cascade={"persist"})
     */
    protected $author;

    /**
     * @ORM\ManyToOne(targetEntity="Clc\UserBundle\Entity\User", inversedBy="myExpenses", cascade={"persist"})
     */
    protected $owner;

    /**
     * @ORM\ManyToOne(targetEntity="Clc\ColocBundle\Entity\coloc", inversedBy="expenses", cascade={"persist"})
     */
    protected $coloc;

    /**
     * @ORM\ManyToMany(targetEntity="Clc\UserBundle\Entity\User", inversedBy="ForMeExpenses", cascade={"persist"})
     * @ORM\JoinColumn(nullable=false)
     */
    protected $users;

    /**
     * @ORM\OneToOne(targetEntity="Clc\InboxBundle\Entity\notification", mappedBy="expense", cascade={"persist", "remove"})
     */
    protected $notification;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set name
     *
     * @param string $name
     * @return expense
     */
    public function setName($name)
    {
        $this->name = $name;

        return $this;
    }

    /**
     * Get name
     *
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Set amount
     *
     * @param float $amount
     * @return expense
     */
    public function setAmount($amount)
    {
        $this->amount = $amount;

        return $this;
    }

    /**
     * Get amount
     *
     * @return float
     */
    public function getAmount()
    {
        return $this->amount;
    }

    /**
     * Set addedDate
     *
     * @param \DateTime $addedDate
     * @return expense
     */
    public function setAddedDate($addedDate)
    {
        $this->addedDate = $addedDate;

        return $this;
    }

    /**
     * Get addedDate
     *
     * @return \DateTime
     */
    public function getAddedDate()
    {
        return $this->addedDate;
    }

    /**
     * Set date
     *
     * @param \DateTime $date
     * @return expense
     */
    public function setDate($date)
    {
        $this->date = $date;

        return $this;
    }

    /**
     * Get date
     *
     * @return \DateTime
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * Set active
     *
     * @param integer $active
     * @return expense
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return integer
     */
    public function getActive()
    {
        return $this->active;
    }

    /**
     * Set owner
     *
     * @param \Clc\UserBundle\Entity\User $owner
     * @return expense
     */
    public function setOwner(\Clc\UserBundle\Entity\User $owner = null)
    {
        $this->owner = $owner;

        return $this;
    }

    /**
     * Get owner
     *
     * @return \Clc\UserBundle\Entity\User
     */
    public function getOwner()
    {
        return $this->owner;
    }

    /**
     * Set coloc
     *
     * @param \Clc\ColocBundle\Entity\coloc $coloc
     * @return expense
     */
    public function setColoc(\Clc\ColocBundle\Entity\coloc $coloc = null)
    {
        $this->coloc = $coloc;

        return $this;
    }

    /**
     * Get coloc
     *
     * @return \Clc\ColocBundle\Entity\coloc
     */
    public function getColoc()
    {
        return $this->coloc;
    }

    /**
     * Set author
     *
     * @param \Clc\UserBundle\Entity\User $author
     * @return expense
     */
    public function setAuthor(\Clc\UserBundle\Entity\User $author = null)
    {
        $this->author = $author;

        return $this;
    }

    /**
     * Get author
     *
     * @return \Clc\UserBundle\Entity\User
     */
    public function getAuthor()
    {
        return $this->author;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->users = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add users
     *
     * @param \Clc\UserBundle\Entity\User $users
     * @return expense
     */
    public function addUser(\Clc\UserBundle\Entity\User $users)
    {
        $this->users[] = $users;

        return $this;
    }

    /**
     * Remove users
     *
     * @param \Clc\UserBundle\Entity\User $users
     */
    public function removeUser(\Clc\UserBundle\Entity\User $users)
    {
        $this->users->removeElement($users);
    }

    /**
     * Get users
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getUsers()
    {
        return $this->users;
    }

    public function getNumber()
    {
        $users = $this->getUsers();
        return $n = count($users);
    }

    /**
     * Set notification
     *
     * @param \Clc\InboxBundle\Entity\notification $notification
     * @return expense
     */
    public function setNotification(\Clc\InboxBundle\Entity\notification $notification = null)
    {
        $this->notification = $notification;

        return $this;
    }

    /**
     * Get notification
     *
     * @return \Clc\InboxBundle\Entity\notification
     */
    public function getNotification()
    {
        return $this->notification;
    }
}


text:
package org.apache.commons.dbcp.datasources;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.PooledConnection;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;

import org.apache.commons.pool.impl.GenericKeyedObjectPool;

/**
 * @version $Revision$ $Date$
 */
public class TestKeyedCPDSConnectionFactory extends TestCase {

    protected ConnectionPoolDataSourceProxy cpds = null;

    public TestKeyedCPDSConnectionFactory(String testName) {
        super(testName);
    }

    public static Test suite() {
        return new TestSuite(TestKeyedCPDSConnectionFactory.class);
    }

    public void setUp() throws Exception {
        cpds = new ConnectionPoolDataSourceProxy(new DriverAdapterCPDS());
        DriverAdapterCPDS delegate = (DriverAdapterCPDS) cpds.getDelegate();
        delegate.setDriver("org.apache.commons.dbcp.TesterDriver");
        delegate.setUrl("jdbc:apache:commons:testdriver");
        delegate.setUser("username");
        delegate.setPassword("password");
    }

    /**
     * JIRA DBCP-216
     *
     * Check PoolableConnection close triggered by destroy is handled
     * properly. PooledConnectionProxy (dubiously) fires connectionClosed
     * when PooledConnection itself is closed.
     */
    public void testSharedPoolDSDestroyOnReturn() throws Exception {
       SharedPoolDataSource ds = new SharedPoolDataSource();
       ds.setConnectionPoolDataSource(cpds);
       ds.setMaxActive(10);
       ds.setMaxWait(50);
       ds.setMaxIdle(2);
       Connection conn1 = ds.getConnection("username", "password");
       Connection conn2 = ds.getConnection("username", "password");
       Connection conn3 = ds.getConnection("username", "password");
       assertEquals(3, ds.getNumActive());
       conn1.close();
       assertEquals(1, ds.getNumIdle());
       conn2.close();
       assertEquals(2, ds.getNumIdle());
       conn3.close(); // Return to pool will trigger destroy -> close sequence
       assertEquals(2, ds.getNumIdle());
    }

    /**
     * JIRA DBCP-216
     *
     * Verify that pool counters are maintained properly and listeners are
     * cleaned up when a PooledConnection throws a connectionError event.
     */
    public void testConnectionErrorCleanup() throws Exception {
        // Setup factory
        UserPassKey key = new UserPassKey("username", "password");
        GenericKeyedObjectPool pool = new GenericKeyedObjectPool(null);
        KeyedCPDSConnectionFactory factory =
            new KeyedCPDSConnectionFactory(cpds, pool, null, false);

        // Checkout a pair of connections
        PooledConnection pcon1 =
            ((PooledConnectionAndInfo) pool.borrowObject(key))
                .getPooledConnection();
        Connection con1 = pcon1.getConnection();
        PooledConnection pcon2 =
            ((PooledConnectionAndInfo) pool.borrowObject(key))
                .getPooledConnection();
        assertEquals(2, pool.getNumActive(key));
        assertEquals(0, pool.getNumIdle(key));

        // Verify listening
        PooledConnectionProxy pc = (PooledConnectionProxy) pcon1;
        assertTrue(pc.getListeners().contains(factory));

        // Throw connectionError event
        pc.throwConnectionError();

        // Active count should be reduced by 1 and no idle increase
        assertEquals(1, pool.getNumActive(key));
        assertEquals(0, pool.getNumIdle(key));

        // Throw another one - we should be on cleanup list, so ignored
        pc.throwConnectionError();
        assertEquals(1, pool.getNumActive(key));
        assertEquals(0, pool.getNumIdle(key));

        // Ask for another connection - should trigger makeObject, which causes
        // cleanup, removing listeners.
        PooledConnection pcon3 =
            ((PooledConnectionAndInfo) pool.borrowObject(key))
                .getPooledConnection();
        assertTrue(!pcon3.equals(pcon1)); // better not get baddie back
        assertTrue(!pc.getListeners().contains(factory)); // verify cleanup
        assertEquals(2, pool.getNumActive(key));
        assertEquals(0, pool.getNumIdle(key));

        // Return good connections back to pool
        pcon2.getConnection().close();
        pcon3.getConnection().close();
        assertEquals(2, pool.getNumIdle(key));
        assertEquals(0, pool.getNumActive(key));

        // Verify pc is closed
        try {
           pc.getConnection();
           fail("Expecting SQLException using closed PooledConnection");
        } catch (SQLException ex) {
            // expected
        }

        // Back from the dead - ignore the ghost!
        con1.close();
        assertEquals(2, pool.getNumIdle(key));
        assertEquals(0, pool.getNumActive(key));

        // Clear pool
        factory.getPool().clear();
        assertEquals(0, pool.getNumIdle(key));
    }

}


text:
function title {
  emulate -L zsh
  setopt prompt_subst

  [[ "$EMACS" == *term* ]] && return

  # if $2 is unset use $1 as default
  # if it is set and empty, leave it as is
  : ${2=$1}

  if [[ "$TERM" == screen* ]]; then
    print -Pn "\ek$1:q\e\\" #set screen hardstatus, usually truncated at 20 chars
  elif [[ "$TERM" == xterm* ]] || [[ "$TERM" == rxvt* ]] || [[ "$TERM" == ansi ]] || [[ "$TERM_PROGRAM" == "iTerm.app" ]]; then
    print -Pn "\e]2;$2:q\a" #set window name
    print -Pn "\e]1;$1:q\a" #set icon (=tab) name
  fi
}

ZSH_THEME_TERM_TAB_TITLE_IDLE="%15<..<%~%<<" #15 char left truncated PWD
ZSH_THEME_TERM_TITLE_IDLE="%n@%m: %~"
# Avoid duplication of directory in terminals with independent dir display
if [[ $TERM_PROGRAM == Apple_Terminal ]]; then
  ZSH_THEME_TERM_TITLE_IDLE="%n@%m"
fi

# Runs before showing the prompt
function omz_termsupport_precmd {
  if [[ $DISABLE_AUTO_TITLE == true ]]; then
    return
  fi

  title $ZSH_THEME_TERM_TAB_TITLE_IDLE $ZSH_THEME_TERM_TITLE_IDLE
}

# Runs before executing the command
function omz_termsupport_preexec {
  if [[ $DISABLE_AUTO_TITLE == true ]]; then
    return
  fi

  emulate -L zsh
  setopt extended_glob

  # cmd name only, or if this is sudo or ssh, the next cmd
  local CMD=${1[(wr)^(*=*|sudo|ssh|mosh|rake|-*)]:gs/%/%%}
  local LINE="${2:gs/%/%%}"

  title '$CMD' '%100>...>$LINE%<<'
}

precmd_functions+=(omz_termsupport_precmd)
preexec_functions+=(omz_termsupport_preexec)

# Runs before showing the prompt, to update the current directory in Terminal.app
function omz_termsupport_cwd {
  # Notify Terminal.app of current directory using undocumented OSC sequence
  # found in OS X 10.9 and 10.10's /etc/bashrc
  if [[ $TERM_PROGRAM == Apple_Terminal ]] && [[ -z $INSIDE_EMACS ]]; then
    local PWD_URL="file://$HOSTNAME${PWD// /%20}"
    printf '\e]7;%s\a' "$PWD_URL"
  fi
}

precmd_functions+=(omz_termsupport_cwd)


text:
namespace Microsoft.Azure.Batch.Protocol.Models
{

    /// <summary>
    /// Defines values for JobAction.
    /// </summary>
    [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]
    public enum JobAction
    {
        [System.Runtime.Serialization.EnumMember(Value = "none")]
        None,
        [System.Runtime.Serialization.EnumMember(Value = "disable")]
        Disable,
        [System.Runtime.Serialization.EnumMember(Value = "terminate")]
        Terminate
    }
}


text:
using Library.Events.v1;
using Library.Frontend.Host.Hubs;
using Microsoft.AspNet.SignalR;
using NServiceBus;

namespace Library.Frontend.Host.EventHandlers
{
    public class BookRegisteredEventHandler : IHandleMessages<BookRegisteredEvent>
    {
        public void Handle(BookRegisteredEvent bookRegisteredEvent)
        {
            var context = GlobalHost.ConnectionManager.GetHubContext<BookHub, IBookHub>();
            context.Clients.All.BookRegistered(bookRegisteredEvent.AggregateId, bookRegisteredEvent.Title);
        }
    }
}


text:
<?php
namespace common\modules\api\controllers;

use yii\rest\ActiveController;

class CountryController extends ActiveController
{
	public $modelClass ='common\models\Country';
}
?>


text:
package org.jetbrains.idea.svn;

import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
import com.intellij.openapi.options.ConfigurableUi;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.changes.VcsDirtyScopeManager;
import com.intellij.ui.components.JBCheckBox;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.idea.svn.auth.SvnAuthenticationNotifier;

import javax.swing.*;

import static org.jetbrains.idea.svn.SvnUtil.USER_CONFIGURATION_PATH;

public class GeneralSettingsPanel implements ConfigurableUi<SvnConfiguration> {

  @NotNull private final Project myProject;

  private JPanel myMainPanel;

  private JCheckBox myUseCustomConfigurationDirectory;
  private TextFieldWithBrowseButton myConfigurationDirectoryText;
  private JButton myClearAuthButton;
  private JBCheckBox myRunUnderTerminal;
  private TextFieldWithBrowseButton myCommandLineClient;

  public GeneralSettingsPanel(@NotNull Project project) {
    myProject = project;

    myUseCustomConfigurationDirectory.addActionListener(e -> {
      boolean enabled = myUseCustomConfigurationDirectory.isSelected();
      myConfigurationDirectoryText.setEnabled(enabled);
      myConfigurationDirectoryText.setEditable(enabled);
      SvnConfiguration configuration = SvnConfiguration.getInstance(myProject);
      String path = configuration.getConfigurationDirectory();
      if (!enabled || path == null) {
        myConfigurationDirectoryText.setText(USER_CONFIGURATION_PATH.getValue().toString());
      }
      else {
        myConfigurationDirectoryText.setText(path);
      }
    });
    myCommandLineClient.addBrowseFolderListener("Subversion", "Select path to Subversion executable (1.7+)", project,
                                                FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor());
    myClearAuthButton.addActionListener(
      e -> SvnAuthenticationNotifier.clearAuthenticationCache(myProject, myMainPanel, myConfigurationDirectoryText.getText()));
    myConfigurationDirectoryText.addActionListener(e -> {
      @NonNls String path = myConfigurationDirectoryText.getText().trim();
      SvnConfigurable.selectConfigurationDirectory(path, s -> myConfigurationDirectoryText.setText(s), myProject, myMainPanel);
    });
  }

  @NotNull
  @Override
  public JComponent getComponent() {
    return myMainPanel;
  }

  @Override
  public void reset(@NotNull SvnConfiguration configuration) {
    String path = configuration.getConfigurationDirectory();
    if (configuration.isUseDefaultConfiguration() || path == null) {
      path = USER_CONFIGURATION_PATH.getValue().toString();
    }
    myConfigurationDirectoryText.setText(path);
    myUseCustomConfigurationDirectory.setSelected(!configuration.isUseDefaultConfiguration());

    boolean enabled = myUseCustomConfigurationDirectory.isSelected();
    myConfigurationDirectoryText.setEnabled(enabled);
    myConfigurationDirectoryText.setEditable(enabled);

    myRunUnderTerminal.setSelected(configuration.isRunUnderTerminal());
    final SvnApplicationSettings applicationSettings17 = SvnApplicationSettings.getInstance();
    myCommandLineClient.setText(applicationSettings17.getCommandLinePath());
  }

  @Override
  public boolean isModified(@NotNull SvnConfiguration configuration) {
    if (configuration.isUseDefaultConfiguration() == myUseCustomConfigurationDirectory.isSelected()) {
      return true;
    }
    if (configuration.isRunUnderTerminal() != myRunUnderTerminal.isSelected()) return true;
    final SvnApplicationSettings applicationSettings17 = SvnApplicationSettings.getInstance();
    if (!Comparing.equal(applicationSettings17.getCommandLinePath(), myCommandLineClient.getText().trim())) return true;
    if (!configuration.getConfigurationDirectory().equals(myConfigurationDirectoryText.getText().trim())) return true;

    return false;
  }

  @Override
  public void apply(@NotNull SvnConfiguration configuration) {
    configuration.setConfigurationDirParameters(!myUseCustomConfigurationDirectory.isSelected(), myConfigurationDirectoryText.getText());

    final SvnVcs vcs17 = SvnVcs.getInstance(myProject);

    final SvnApplicationSettings applicationSettings17 = SvnApplicationSettings.getInstance();
    boolean reloadWorkingCopies = !StringUtil.equals(applicationSettings17.getCommandLinePath(), myCommandLineClient.getText().trim());
    configuration.setRunUnderTerminal(myRunUnderTerminal.isSelected());

    applicationSettings17.setCommandLinePath(myCommandLineClient.getText().trim());
    boolean isClientValid = vcs17.checkCommandLineVersion();
    if (!myProject.isDefault() && isClientValid && reloadWorkingCopies) {
      vcs17.invokeRefreshSvnRoots();
      VcsDirtyScopeManager.getInstance(myProject).markEverythingDirty();
    }
  }
}


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

namespace VMF.UI.Messages
{
    public class FilterViewMessage
    {
        public FilterType Type { get; set; }
    }
}


text:
<resources>
    <string name="app_name">TVWatchList</string>

    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>

    <string name="action_settings">Settings</string>

    <string name="following">Following</string>
    <string name="finished">Finished</string>
    <string name="is_followed">Follow ?</string>
    <string name="retry">Retry</string>
    <string name="oops">Oops something went wrong</string>
    <string name="no_results_found">No results found...</string>
    <string name="search_tv_shows">Search TV Shows</string>
    <string name="overview">Overview</string>
    <string name="genres">Genres:</string>
    <string name="first_air_date">First air date:</string>
    <string name="status">Status:</string>
    <string name="number_of_episodes">Number of Episodes:</string>
    <string name="average_score">Average score:</string>
    <string name="no_follow">You do not follow any tv shows</string>
    <string name="no_ended">You do not have any ended tv shows</string>
    <string name="title_find_shows">Find Shows</string>
    <string name="title_my_shows">My Shows</string>
</resources>


text:
'use strict';
module.exports = function(sequelize, DataTypes) {
  var Candle = sequelize.define('Candle', {
    code: DataTypes.STRING,
    name: DataTypes.STRING,
    price: DataTypes.DOUBLE,
    description: DataTypes.TEXT,
    discontinued: DataTypes.BOOLEAN
  }, {
    classMethods: {
      associate: function(models) {
        // associations can be defined here
        Candle.hasMany(models.CandleDetails)
        Candle.hasMany(models.Stock)
      }
    }
  });
  return Candle;
};


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
ImageIO (Axis API)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.axis.components.image.ImageIO interface">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.axis.components.image

Interface ImageIO

All Known Implementing Classes:
JDK13IO, JimiIO, MerlinIO

public interface ImageIO

This interface defines a ImageIO modules functionality

Since:

2.0

Author:

Davanum Srinivas

Method Summary

 java.awt.Image
loadImage(java.io.InputStream in)

          Load an Image.

 void
saveImage(java.lang.String id,
          java.awt.Image image,
          java.io.OutputStream os)

          Save an image.

Method Detail

saveImage

public void saveImage(java.lang.String id,
                      java.awt.Image image,
                      java.io.OutputStream os)
               throws java.lang.Exception

Save an image.

Parameters:
id - the mime-type of the format to save the image
image - the image to save
os - the output stream to write to

Throws:

java.lang.Exception - if an error prevents image encoding

loadImage

public java.awt.Image loadImage(java.io.InputStream in)
                         throws java.lang.Exception

Load an Image.

Parameters:
in - the stream to load the image

Returns:
the Image

Throws:

java.lang.Exception

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2005 Apache Web Services Project. All Rights Reserved.


text:
require 'rails_helper'

RSpec.describe BalancesController, type: :routing do
  describe "simple routing" do
    it "routes to #index" do
      expect(get: "/balances").to route_to("balances#index")
    end

    it "does not route to #new" do
      expect(get: "/balances/new").not_to be_routable
    end

    it "routes to #show" do
      expect(get: "/balances/1").not_to be_routable
      expect(get: "/balances/1.pdf").to route_to("balances#show", id: "1", format: "pdf")
    end

    it "does not route to #edit" do
      expect(get: "/balances/1/edit").not_to be_routable
    end

    it "does not route to #create" do
      expect(post: "/balances").not_to be_routable
    end

    it "does not route to #update via PUT" do
      expect(put: "/balances/1").not_to be_routable
    end

    it "does not route to #update via PATCH" do
      expect(patch: "/balances/1").not_to be_routable
    end

    it "does not route to #destroy" do
      expect(delete: "/balances/1").not_to be_routable
    end
  end

  describe "STI-routes" do
    [:auto_balances, :manual_balances].each do |balance_type|
      context "#{balance_type}" do
        let(:type){ balance_type.to_s.singularize.camelcase }

        it "does not route to #index" do
          expect(get: nested("/#{balance_type}")).not_to be_routable
        end

        it "does not route to #show" do
          expect(get: nested("/#{balance_type}/1")).not_to be_routable
          expect(get: nested("/#{balance_type}/1.pdf")).not_to be_routable
        end

        it "routes to edit" do
          expect(get: nested("/#{balance_type}/1/edit")).to route_to("balances#edit", id: "1", credit_agreement_id: "1", type: type)
        end

        it "does not route to create" do
          expect(post: nested("/#{balance_type}")).not_to be_routable
        end

        it "routes to update" do
          expect(patch: nested("/#{balance_type}/1")).to route_to("balances#update", id: "1", credit_agreement_id: "1", type: type)
        end

      end
    end

    context "auto_balances" do
      it "routes to destroy" do
        expect(delete: nested("/auto_balances/1")).not_to be_routable
      end
    end

    context "manual_balances" do
      it "routes to destroy" do
        expect(delete: nested("/manual_balances/1")).to route_to("balances#destroy", id: "1", credit_agreement_id: "1", type: 'ManualBalance')
      end
    end

    context "termination_balance" do
      it "does not route to #index" do
        expect(get: nested("/termination_balances")).not_to be_routable
      end

      it "does not route to #show" do
        expect(get: nested("/termination_balances/1")).not_to be_routable
        expect(get: nested("/termination_balances/1.pdf")).not_to be_routable
      end

      it "does not route to new" do
        expect(get: nested("/termination_balances/new")).not_to be_routable
      end

      it "does not route to edit" do
        expect(get: nested("/termination_balances/1/edit")).not_to be_routable
      end

      it "does not route to create" do
        expect(post: nested("/termination_balances")).not_to be_routable
      end

      it "does not route to update" do
        expect(patch: nested("/termination_balances/1")).not_to be_routable
      end

      it "routes to destroy" do
        expect(delete: nested("/termination_balances/1")).to route_to("balances#destroy", id: "1", credit_agreement_id: "1", type: 'TerminationBalance')
      end
    end
  end

  def nested(string)
    "/credit_agreements/1#{string}"
  end
end


text:
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import App from './containers/App';
import todoApp from './reducers';

const store = createStore(todoApp);

const rootElement = document.getElementById('root');
React.render(
  // The child must be wrapped in a function
  // to work around an issue in React 0.13.
  <Provider store={store}>
    {() => <App />}
  </Provider>,
  rootElement
);


text:
<?php

namespace LiveTest\Event;

use phmLabs\Components\Annovent\Event\Event;
use phmLabs\Components\Annovent\Dispatcher as AnnoventDispatcher;

use LiveTest\Config\ConfigConfig;

/**
 * This dispatcher is a standard Annovent dispatcher with the possibility to register
 * listeners using a ConfigConfig object.
 *
 * @author Nils Langner
 */
class Dispatcher extends AnnoventDispatcher
{
  /**
   * This function is used to register listeners using a global configuration file
   *
   * @param ConfigConfig $config
   * @param string $runId
   */
  public function registerByConfig(ConfigConfig $config, $runId)
  {
    foreach ( $config->getListeners() as $listener )
    {
      $className = $listener['className'];
      if (!class_exists($className))
      {
        throw new \LiveTest\ConfigurationException('Listener not found (' . $className . ').');
      }
      $listenerObject = new $className($runId, $this);
      \LiveTest\Functions::initializeObject($listenerObject, $listener['parameters']);
      $this->connectListener($listenerObject, $listener['priority']);
    }
  }

  public function simpleNotify($name, array $namedParameters = array())
  {
    $event = new Event($name, $namedParameters);
    return $this->notify($event, $namedParameters);
  }
}


text:
package com.siyeh.ig.performance;

import com.intellij.psi.PsiClassType;
import com.intellij.psi.PsiType;
import com.intellij.psi.PsiTypeElement;
import com.intellij.psi.PsiVariable;
import com.siyeh.InspectionGadgetsBundle;
import com.siyeh.ig.BaseInspection;
import com.siyeh.ig.BaseInspectionVisitor;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

public class JavaLangReflectInspection extends BaseInspection {

  @Override
  @NotNull
  public String getDisplayName() {
    return InspectionGadgetsBundle.message(
      "java.lang.reflect.display.name");
  }

  @Override
  @NotNull
  protected String buildErrorString(Object... infos) {
    return InspectionGadgetsBundle.message(
      "java.lang.reflect.problem.descriptor");
  }

  @Override
  public BaseInspectionVisitor buildVisitor() {
    return new JavaLangReflectVisitor();
  }

  private static class JavaLangReflectVisitor extends BaseInspectionVisitor {

    @Override
    public void visitVariable(@NotNull PsiVariable variable) {
      super.visitVariable(variable);
      final PsiType type = variable.getType();
      final PsiType componentType = type.getDeepComponentType();
      if (!(componentType instanceof PsiClassType)) {
        return;
      }
      final String className = ((PsiClassType)componentType).getClassName();
      @NonNls final String javaLangReflect = "java.lang.reflect.";
      if (!className.startsWith(javaLangReflect)) {
        return;
      }
      final PsiTypeElement typeElement = variable.getTypeElement();
      if (typeElement == null) {
        return;
      }
      registerError(typeElement);
    }
  }
}


text:
# Configure Rails Environment
ENV["RAILS_ENV"] = "test"

require File.expand_path("../../test/dummy/config/environment.rb",  __FILE__)
ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../test/dummy/db/migrate", __FILE__)]
ActiveRecord::Migrator.migrations_paths << File.expand_path('../../db/migrate', __FILE__)
require "rails/test_help"

# Filter out Minitest backtrace while allowing backtrace from other libraries
# to be shown.
Minitest.backtrace_filter = Minitest::BacktraceFilter.new

# Load support files
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

# Load fixtures from the engine
if ActiveSupport::TestCase.respond_to?(:fixture_path=)
  ActiveSupport::TestCase.fixture_path = File.expand_path("../fixtures", __FILE__)
  ActiveSupport::TestCase.fixtures :all
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace KinectoSoar.ScreenManager
{
    /// <summary>
    /// Game component for managing screens. This uses a state-machine
    /// pattern for easy addition and removal of screens. Each class is
    /// responsible for loading its screens based off of user input. This
    /// class mainly just holds the active screen and calls its update
    /// and Draw methods.
    /// </summary>
    public class ScreenManager : Microsoft.Xna.Framework.DrawableGameComponent
    {
        #region Class Member Variables

        private SpriteBatch _spriteBatch;
        private Screen _activeScreen;

        #endregion

        #region Main Game Methods and Constructor

        public ScreenManager(Game game)
            : base(game)
        {
            _spriteBatch = (SpriteBatch)game.Services.GetService(typeof(SpriteBatch));

            // Sets initial screen to start screen since that is
            // the first screen that is present in the game

            // TODO: set first screen
            _activeScreen = new StartScreen(game, _spriteBatch);
        }

        public override void Update(GameTime gameTime)
        {
            // Gives the active screen a reference to the current active
            // screen so it can change it based off of input
            _activeScreen.Update(ref _activeScreen, gameTime);
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            _activeScreen.Draw();
            base.Draw(gameTime);
        }

        #endregion
    }
}


text:
import Component from '@ember/component';

export default Component.extend({
  classNames: ['pusher'],
  tagName: ''
});


text:
using System;

namespace QuantConnect.Brokerages.InteractiveBrokers.Client
{
    /// <summary>
    /// Event arguments class for the <see cref="InteractiveBrokersClient.TickEfp"/> event
    /// </summary>
    public sealed class TickEfpEventArgs : EventArgs
    {
        /// <summary>
        /// The request's unique identifier.
        /// </summary>
        public int TickerId { get; private set; }

        /// <summary>
        /// Specifies the type of tick being received.
        /// </summary>
        public int TickType { get; private set; }

        /// <summary>
        /// Annualized basis points, which is representative of the financing rate that can be directly compared to broker rates.
        /// </summary>
        public double BasisPoints { get; private set; }

        /// <summary>
        /// Annualized basis points as a formatted string that depicts them in percentage form.
        /// </summary>
        public string FormattedBasisPoints { get; private set; }

        /// <summary>
        /// Implied futures price.
        /// </summary>
        public double ImpliedFuture { get; private set; }

        /// <summary>
        /// The number of hold days until the expiry of the EFP.
        /// </summary>
        public int HoldDays { get; private set; }

        /// <summary>
        /// The expiration date of the single stock future.
        /// </summary>
        public string FutureExpiry { get; private set; }

        /// <summary>
        /// The dividend impact upon the annualized basis points interest rate.
        /// </summary>
        public double DividendImpact { get; private set; }

        /// <summary>
        /// The dividends expected until the expiration of the single stock future.
        /// </summary>
        public double DividendsToExpiry { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="TickEfpEventArgs"/> class
        /// </summary>
        public TickEfpEventArgs(int tickerId, int tickType, double basisPoints, string formattedBasisPoints, double impliedFuture, int holdDays, string futureExpiry, double dividendImpact, double dividendsToExpiry)
        {
            TickerId = tickerId;
            TickType = tickType;
            BasisPoints = basisPoints;
            FormattedBasisPoints = formattedBasisPoints;
            ImpliedFuture = impliedFuture;
            HoldDays = holdDays;
            FutureExpiry = futureExpiry;
            DividendImpact = dividendImpact;
            DividendsToExpiry = dividendsToExpiry;
        }
    }
}


text:
author: Anton Stroganov (@aeon)
---

## ruby hangout

monthly ruby meetup over google hangout

## national software school

the only non-profit software academy in the US

## influx db

new time series db, libs for js, ruby, python, etc... in beta now, production target january

## rapgenius - hyperlayers

- caching personalized content is difficult.
- generational caching - standard, uses item id + expiration... but not so good for personalized content
	- naive solution is adding everything that could affect the page content into the cache key
	- but that kinda sucks...
	- dhh's solution - client-side customization,
		- use javascript to manipulate the page to hide the stuff that user is not supposed to see it.
		- kinda sucks security wise.
	- wycat's solution - client-side templating
		- but now the client needs to know all kinds of things about application state
	- our solution - hyperlayers
		- first step, process erb and render everything to HTML _except_ for stuff that's user-specific...
		- cache the resulting erb, and render it on request - it's mostly html now, so processing it for just the user-specific stuff is pretty fast
		- all users use same cache key, so it's cheap

## dependencies testing with appraisal and bundler

[@sikachu](http://twitter.com/aeon)

- you publish a gem, you test it... but do you know if it will work with older versions of your dependencies?
- especially if your gem has been around for a while...
- just because it works with latest version, it doesn't mean it works with older versions :(
- use appraisal to figure it out
- sets up independent environment for each version you want to "appraise", and runs the tests in it.
- run rake appraisal:rails-3-1 test... and it just works.
- you can set it up to run automatically with travis or any other CI probably
- thoughtbot using it to maintain paperclip and other gems

## Programming Programmers

[@schneems](http://twitter.com/schneems)

- how many of us have contributed to open source?
	- hands go up
- how about 2000+ commits?
	- hands go down, 2 hands in the room stay up...
- use CodeTriage - helps you help open source...

## How to make perfume dance

[@nari3](http://twitter.com/nari3), Cruby committer, author

- Perfume is a pop group in Japan
- perfume-dev.github.com - has motion capture of their performance...
- hmmm.... how to make them dance in ruby?
- SDL + bvh gem....
- dancing stick figures as first prototype...
- oh noes... had to disable GC to make it work...
	- motion data is huge, creates tons of read-only objects after parsing...
	- GC was stopping the world and scanning all the objects at each pass...
	- so the dance animation stutters terribly
- ruby 2.1 to the rescue!
	- introduces generational GC... which fixes the problem...
	- the motion objects are not scanned by GC on every pass :)

## mentoring from a newbies perspective

[@allie_p](http://twitter.com/allie_p), Rails girls DC organizer, and a newbie

Tips for being an effective mentor:

- At the beginning, the mentee doesn't even know what questions to ask...
	- Encourage them to ask questions continously
- Don't go down the rabbit hole... it's too confusing too fast...
	- Keep it concise and give them a basic idea first.
- Understand if you're not understood
	- make it ok for the person to say "i don't get it"
- The answer to "what should I read"...
	- don't dump a huge list, just give them one or two titles, and explain what to focus on
- Don't ever steal the keyboard...
	- let the mentee do the work, dictate word by word if needed, but do not type it for them
- Help celebrate the small successes...
	- motivate them to go on to the next thing

## graphs and hamsters

[@moonbeamlabs](http://twitter.com/moonbeamlabs)
- hamsters love food
- cave 1 -> tunnel -> cave 2
- the hamster wants to know how much grain and nuts it has
- but it can't remember the way back past two caves
- the hamster is a visitor... this is usually solved with traversal algorithms
- ArangoDB supports both documents and graphs, very space efficient.
- has REST api
- ruby gems: ashikawa core, guacamole

## minaswan

josh [@crsexton](http://twitter.com/crsexton)

- matz is nice and so we are nice
- keep ruby awesome
- make ruby awesomer
- give back
- use semantic versioning
- good git commit messages
- namespaces
- clean api's...
- ruby is a social movement :)

## maintaining compatibility

[@sferik](http://twitter.com/sferik)

- explaining semantic versioning - see [semver.org](http://semver.org)
- `stability = major version number / (time.now - Time.at(1.0.0.))`
- how often does this package break backwards compatibility?
- Use ~> instead of => in your Gemfile... makes sure you don't upgrade by a major version number by accident.
- ~> 1.2 is same as saying >= 1.2 && < 1.3

## PolyTexNic

Michael Hartl, [@mhartl](http://twitter.com/mhartl), author of Tau Manifesto and Rails Tutorial (awesome!).

- ebook typesetting tool for technical authors
- markdown, ruby, latex, math, figures, cross-references
- generates epub, mobi, pdf with simple build command
- https://www.softcover.io/

## state of ruby-lang.org

Shibata Hiroshi, root of ruby-lang.org

- github.com/ruby/www.ruby-lang.org is now hosted from github
- translations to a bunch of languages in six months, but need more contributors
- use SSL cert from globalsign - they provide free SSL certs for open source projects
- bugs.ruby-lang.org uses redmine
- forked redmine for ruby-lang
- docs.ruby-lang.org

## Rubyist magazine

Satoshi Gunji, [@gunjisatoshi](http://twitter.com/gunjisatoshi)

- magazine.rubyist.net
- 9 years old, but mostly in japanese...
- looking for submissions! Please send your writing!

## reveal-ck
- gem to generate slides in html
- just write haml, uses reveal-js for presentation

## updating library dependencies with Tachikoma

[@sanemat](http://twitter.com/sanemat)

- Tachikoma automates git pull, bundle update, git commit, pull request process to make updating the libraries painless

## unbelievable

[Michael Dvorkin](http://github.com/michaeldv/), author of awesome_print

- inspired by Yusuke Endoh
- demo: ruby program encoded as lorem text, todo list text, ....
- code can generate plaintext that encodes arbitrary ruby code... pretty crazy.

## health tools in ruby
- bit.ly/rubyconf-health
- medical community needs better tools... looking for contributors.

## learn improv for great good

Diego, [@_sc](http://twitter.com/_sc)

improv can teach us useful social and team skills
- to care
- to relinquish control
- to ask for permission
- to accept
- great for practicing empathy


text:
from struct import pack

from electrum_arg.wallet import BIP44_Wallet

class BIP44_HW_Wallet(BIP44_Wallet):
    '''A BIP44 hardware wallet base class.'''
    # Derived classes must set:
    #   - device
    #   - DEVICE_IDS
    #   - wallet_type

    restore_wallet_class = BIP44_Wallet
    max_change_outputs = 1

    def __init__(self, storage):
        BIP44_Wallet.__init__(self, storage)
        # Errors and other user interaction is done through the wallet's
        # handler.  The handler is per-window and preserved across
        # device reconnects
        self.handler = None

    def unpaired(self):
        '''A device paired with the wallet was diconnected.  This can be
        called in any thread context.'''
        self.print_error("unpaired")

    def paired(self):
        '''A device paired with the wallet was (re-)connected.  This can be
        called in any thread context.'''
        self.print_error("paired")

    def get_action(self):
        pass

    def can_create_accounts(self):
        return True

    def can_export(self):
        return False

    def is_watching_only(self):
        '''The wallet is not watching-only; the user will be prompted for
        pin and passphrase as appropriate when needed.'''
        assert not self.has_seed()
        return False

    def can_change_password(self):
        return False

    def get_client(self, force_pair=True):
        return self.plugin.get_client(self, force_pair)

    def first_address(self):
        '''Used to check a hardware wallet matches a software wallet'''
        account = self.accounts.get('0')
        derivation = self.address_derivation('0', 0, 0)
        return (account.first_address()[0] if account else None, derivation)

    def derive_xkeys(self, root, derivation, password):
        if self.master_public_keys.get(self.root_name):
            return BIP44_wallet.derive_xkeys(self, root, derivation, password)

        # When creating a wallet we need to ask the device for the
        # master public key
        xpub = self.get_public_key(derivation)
        return xpub, None

    def i4b(self, x):
        return pack('>I', x)


text:
package org.apache.xmlrpc.serializer;

import org.apache.ws.commons.serialize.DOMSerializer;
import org.w3c.dom.Node;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/** The node serializer is serializing a DOM node.
 */
public class NodeSerializer extends ExtSerializer {
	private static final DOMSerializer ser = new DOMSerializer();
	static {
		ser.setStartingDocument(false);
	}

	/** The local name of a dom tag.
	 */
	public static final String DOM_TAG = "dom";

	protected String getTagName() { return DOM_TAG; }

	protected void serialize(ContentHandler pHandler, Object pObject) throws SAXException {
		ser.serialize((Node) pObject, pHandler);
	}
}


text:
this.Param = (function() {

  /* public constructor */
  function Param(name, value) {

    /* public instance variables */
    this.name = name;
    this.value = value;
  }

  Param.serialize = {
    name: 'string',
    value: 'string'
  };

  return Param;
})();


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright 2014 Daniel Giribet <dani - calidos.cat>

 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.calidos.dani.meteorit</groupId>
	<artifactId>meteorit-backend-storm</artifactId>
	<version>1.1.0-SNAPSHOT</version>
	<packaging>rpm</packaging>

	<name>Meteorit system backend storm component</name>
	<description>Downloads Storm and runs it under 'mon' supervisor
	</description>
    <inceptionYear>2013</inceptionYear>
    <url>http://dani.calidos.com</url>

    <parent>
    	<groupId>com.calidos.dani.meteorit</groupId>
		<artifactId>meteorit-compile-parent</artifactId>
		<version>1.0.0-SNAPSHOT</version>
		<relativePath>../meteorit-compile-parent/pom.xml</relativePath>
    </parent>

    <properties>
		<storm.version_>0.9.1-incubating</storm.version_>
		<!-- please use listing at: http://www.apache.org/dyn/closer.cgi/incubator/storm/apache-storm-0.9.1-incubating/apache-storm-0.9.1-incubating.zip -->
		<storm.mirrorhost_>apache.rediris.es</storm.mirrorhost_>
		<storm.url_>http://${storm.mirrorhost_}/incubator/storm/apache-storm-${storm.version_}/apache-storm-${storm.version_}.zip</storm.url_>
		<storm.sourcefolder_>${project.build.directory}/apache-storm-${storm.version_}</storm.sourcefolder_> <!-- where zip gets expanded -->
		<storm.installfolder_>${install.prefix_}/storm</storm.installfolder_>
		<storm.datafolder_>/var/storm</storm.datafolder_>
		<!--<storm.configfolder_>/etc</storm.configfolder_>-->
		<storm.configfolder_>${storm.installfolder_}/conf</storm.configfolder_>
		<storm.logfolder_>/var/log/storm</storm.logfolder_>
		<storm.username_>storm</storm.username_>
		<storm.groupname_>storm</storm.groupname_>
		<jzmq.version_>master</jzmq.version_>
		<jzmq.url_>https://github.com/nathanmarz/jzmq/archive/${jzmq.version_}.zip</jzmq.url_>
		<jzmq.sourcefolder_>${project.build.directory}/jzmq-${jzmq.version_}</jzmq.sourcefolder_>
		<!--TODO: this can be relocated provided the yaml file config reflects the new path -->
		<jzmq.installfolder_>/usr/local</jzmq.installfolder_>
		<jzmq.tempfolder_>${project.build.directory}/jzmq-install</jzmq.tempfolder_>
		<skipPatch_>false</skipPatch_>	<!-- to skip reapplying logback config patch -->
    </properties>

    <build>
   		<plugins>

            <plugin>	<!-- Download and expand whatever is needed -->
                <artifactId>maven-antrun-plugin</artifactId>
                <version>1.7</version>
                <executions>
                    <execution>
                    	<id>download-storm-and-jzmq</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
                                <get src="${storm.url_}"
                                	 dest="${project.build.directory}/storm-${storm.version_}.zip" skipexisting="true" />
                                <unzip src="${project.build.directory}/storm-${storm.version_}.zip"
                                	   dest="${project.build.directory}" />
                                <get src="${jzmq.url_}"
                                	 dest="${project.build.directory}/jzmq-${jzmq.version_}.zip" skipexisting="true" />
                                <unzip src="${project.build.directory}/jzmq-${jzmq.version_}.zip"
                                	   dest="${project.build.directory}" />
                            </target>
                        </configuration>
                    </execution>
                    <execution>
                    	<id>create-yaml-configuration</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                        <configuration>
                            <target>
	                            <concat
	                            	overwrite="yes"
	                            	encoding="${project.build.sourceEncoding}"
	                            	destfile="${project.build.directory}/storm.yaml">
	                            		<fileset file="${storm.sourcefolder_}/conf/storm.yaml" />
	                            		<fileset dir="${project.build.outputDirectory}/conf" includes="*.yaml" />
	                           	</concat>
                            </target>
                        </configuration>
                    </execution>
                </executions>
		    </plugin>

		    <plugin>	<!-- logback configuration patch (diff -u cluster.xml cluster2.xml) -->
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-patch-plugin</artifactId>
				<version>1.1.1</version>
				<configuration>
					<backups>false</backups>
					<targetDirectory>${storm.sourcefolder_}/logback</targetDirectory>
					<patchFile>${project.build.outputDirectory}/filtered-cluster.xml.patch</patchFile>
					<destFile>${project.build.directory}/cluster.xml</destFile>
					<skipApplication>${skipPatch_}</skipApplication>
				</configuration>
				<executions>
					<execution>
						<id>patch</id>
						<phase>process-classes</phase>
						<goals>
							<goal>apply</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		    <plugin>	<!-- package as rpm, yay -->
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>rpm-maven-plugin</artifactId>
                <version>2.1-alpha-2</version>
                <extensions>true</extensions>

                <configuration>
                    <packager>danigiri</packager>
                    <distribution>Calidos</distribution>
                    <group>Calidos/Meteorit</group>
                    <copyright>See installed LICENSE file</copyright>
                    <summary>${project.name}</summary>
                    <description>${project.description}</description>
                    <url>${project.url}</url>
                    <prefix>${install.prefix_}</prefix>
                    <needarch>${binary.architecture_}</needarch>

	    			<icon />

                    <defineStatements>
                        <defineStatement>_unpackaged_files_terminate_build 0</defineStatement>
                        <defineStatement>_name ${project.artifactId}</defineStatement>
                        <defineStatement>_app ${project.artifactId}</defineStatement>
                    </defineStatements>

                    <defaultDirmode>755</defaultDirmode>
                    <defaultFilemode>644</defaultFilemode>
                    <defaultUsername>${storm.username_}</defaultUsername>
                    <defaultGroupname>${storm.groupname_}</defaultGroupname>

                    <requires>
                    	<require>shunit2 >= 2.1.6</require>
                    	<require>meteorit-env</require>
                    	<require>meteorit-backend-mon</require>
                    	<require>meteorit-backend-zookeeper</require>
                    	<require>zeromq</require>
                    </requires>

                    <mappings>
                    	<!-- storm installation -->
 						<mapping>
							<directory>${storm.installfolder_}</directory>
 						</mapping>
						<!-- storm: script -->
 						<mapping>
							<sources>
								<source>
									<location>${storm.sourcefolder_}/bin/storm</location>
								</source>
								<source>
									<location>${project.build.outputDirectory}/${project.artifactId}-setup.sh</location>
								</source>
							</sources>
							<directory>${storm.installfolder_}/bin</directory>
						    <username>${storm.username_}</username>
                            <groupname>${storm.groupname_}</groupname>
                            <filemode>755</filemode>
							<directoryIncluded>true</directoryIncluded>
						</mapping>
						<!-- storm: dependency jars and storm-core -->
                   		<mapping>
							<sources>
								<source>
									<location>${storm.sourcefolder_}/lib</location>
								</source>
							</sources>
							<directory>${storm.installfolder_}/lib</directory>
							<directoryIncluded>true</directoryIncluded>
						</mapping>
						<!-- storm: ui resources -->
						<mapping>
							<sources>
								<source>
									<location>${storm.sourcefolder_}/public</location>
								</source>
							</sources>
							<directory>${storm.installfolder_}/public</directory>
							<directoryIncluded>true</directoryIncluded>
						</mapping>
						<!-- storm: needed release flag file + the rest of the text stuff -->
						<mapping>
							<sources>
								<source>
									<location>${storm.sourcefolder_}/RELEASE</location>
								</source>
							</sources>
							<directory>${storm.installfolder_}</directory>
						</mapping>
						<!-- storm: final configuration yaml -->
						<mapping>
							<directory>${storm.configfolder_}</directory>
						</mapping>
						<mapping>
							<sources>
								<source>
									<location>${project.build.directory}/storm.yaml</location>
								</source>
							</sources>
							<directory>${storm.configfolder_}</directory>
						    <username>${storm.username_}</username>
                            <groupname>${storm.groupname_}</groupname>
                            <filemode>664</filemode>
							<directoryIncluded>false</directoryIncluded>
							<configuration>noreplace</configuration>
						</mapping>
						<!-- storm: final logback configuration -->
						<mapping>
							<directory>${storm.installfolder_}/logback</directory>
						</mapping>
						<mapping>
							<sources>
								<source>
									<location>${project.build.directory}/cluster.xml</location>
								</source>
							</sources>
						    <username>${storm.username_}</username>
                            <groupname>${storm.groupname_}</groupname>
                            <filemode>664</filemode>
							<directory>${storm.installfolder_}/logback</directory>
							<configuration>noreplace</configuration>
							<directoryIncluded>false</directoryIncluded>
						</mapping>
						<!-- storm: local temporary folder -->
						<mapping>
							<directory>${storm.datafolder_}</directory>
						    <username>root</username>
                            <groupname>${storm.groupname_}</groupname>
                            <filemode>775</filemode>
						</mapping>
						<!-- storm: log folder -->
						<mapping>
							<directory>${storm.logfolder_}</directory>
						    <username>root</username>
                            <groupname>${storm.groupname_}</groupname>
                            <filemode>775</filemode>
						</mapping>
						<!-- init.d scripts, as root -->
						<mapping>
                    		<sources>
                    			<source>
                    				<location>${project.build.outputDirectory}/init.d</location>
                    			</source>
                    		</sources>
 	                        <username>root</username>
                            <groupname>root</groupname>
                            <filemode>755</filemode>
                       		<directory>/etc/init.d</directory>
                       		<directoryIncluded>false</directoryIncluded>
                    	</mapping>
                   		<!-- jzmq binary libs -->
						<mapping>
                    		<sources>
                    			<source>
                    				<location>${jzmq.tempfolder_}/${jzmq.installfolder_}/lib</location>
                    				<includes>
	                    				<include>*.a</include>
    	                				<include>*.la</include>
    	                				<include>*.so.0.0.0</include>
   	                				</includes>
                    			</source>
                    			<softlinkSource>
                    				<destination>libjzmq.so</destination>
                    				<location>libjzmq.so.0.0.0</location>
                    			</softlinkSource>
                    			<softlinkSource>
                    				<destination>libjzmq.so.0</destination>
                    				<location>libjzmq.so.0.0.0</location>
                    			</softlinkSource>
                    		</sources>
 	                        <username>root</username>
                            <groupname>root</groupname>
                            <filemode>755</filemode>
                       		<directory>${jzmq.installfolder_}/lib</directory>
                       		<directoryIncluded>false</directoryIncluded>
                       	</mapping>
                       	<!-- jzmq java libs -->
                       	<mapping>
							<sources>
								<source>
									<location>${jzmq.tempfolder_}/${jzmq.installfolder_}/share/java</location>
								</source>
							</sources>
							<directory>${jzmq.installfolder_}/usr/share/java</directory>
							<directoryIncluded>false</directoryIncluded>
						</mapping>
		    	    </mappings>
		    	    <preinstallScriptlet>
						<scriptFile>${project.build.directory}/preinstall.sh</scriptFile>
						<fileEncoding>utf-8</fileEncoding>
					</preinstallScriptlet>
					<postremoveScriptlet>
						<scriptFile>${project.build.directory}/postremove.sh</scriptFile>
						<fileEncoding>utf-8</fileEncoding>
					</postremoveScriptlet>
		    	    </configuration>
	    	    </plugin>
	    </plugins>

    </build>

    <!--

./usr/local/lib:
total 311
-rw-r__r__. 1 meteorit meteorit 435126 Sep 27 00:19 libjzmq.a
-rwxr-xr-x. 1 meteorit meteorit    937 Sep 27 00:19 libjzmq.la
lrwxr-xr-x. 1 meteorit meteorit     16 Sep 27 00:19 libjzmq.so -> libjzmq.so.0.0.0
lrwxr-xr-x. 1 meteorit meteorit     16 Sep 27 00:19 libjzmq.so.0 -> libjzmq.so.0.0.0
-rwxr-xr-x. 1 meteorit meteorit 197164 Sep 27 00:19 libjzmq.so.0.0.0

./usr/local/share/java:
total 7
-rw-r__r__. 1 meteorit meteorit 13642 Sep 27 00:19 zmq.jar
     -->
</project>


text:
@class DataLoader;

@protocol DataLoaderDelegate <NSObject>
- (void)dataDidChange:(DataLoader *)dataLoader withError:(NSError *)error;
@end

@interface DataLoader : NSObject
@property (nonatomic, weak) id<DataLoaderDelegate> delegate;
@property (nonatomic, strong) NSMutableArray<GaugeData *> *data;
@property (nonatomic, strong) GaugeData *importantData;

- (void)refresh;
@end


text:
var should = require('should');
var assert = require("assert");
var ScheduledMessage = require("../models/scheduledMessage.js");
var mongoose = require('mongoose');
var SenderManager = require('../sendManager');
var	config = require("../../config/config");

var senderManager = new SenderManager(config);

var db;

describe('Send manager:', function(){
	this.timeout(10000);
	before(function () {
		db = mongoose.connect(config.db);
	});
	after(function () {
		db.disconnect();
	});

	var yesterday = (function(d){ d.setDate(d.getDate()-1); return d})(new Date)

	beforeEach(function(done) {
		ScheduledMessage.create(createInvitationScheduledMessage('fundacja1@jow.pl', yesterday.toISOString()),
			createInvitationScheduledMessage('fundacja2@jow.pl', yesterday.toISOString()),
			createInvitationScheduledMessage('fundacja3@jow.pl', new Date(2999,11,17).toISOString()),
			function() {
				done();
			});
	});

	afterEach(function(done) {
		ScheduledMessage.remove({},function(err){
			if (err) {
				console.log("Problem removing ScheduledMessage");
			}
			done();
		});
	});

	it('find all ready to send messages and send out them all', function(done){
		senderManager.sendAllMessages(function(err,response) {
			assert.equal(null,err);
			mailEventLog.sentWith24h(function(err,sent) {
				should.not.exist(err);
				sent.should.equal(2);
				done();
			});
		});
	});

	function createInvitationScheduledMessage(email,date,campaignType,from,subject,text,html) {

		var msg = ScheduledMessage(
		{
			to	: email,
			planedSendDate : date ? date : new Date(2014, 12, 25, 8, 30),
			campaignType : campaignType ? campaignType : 'invitation',
			from : from ? from : 'mateusz.milian@gmail.com',
			subject : subject ? subject : 'This is test message send by script from efektjow.pl',
			text : text ? text : 'Daj znać jak dostaniesz tą wiadomość /Mateusz',
			html : html || '
Daj znać jak dostaniesz tą wiadomość /Mateusz
'
		}
		);
		return msg;
	};
});


text:
package org.apache.commons.math3.ode;

import org.apache.commons.math3.util.FastMath;

/**
 * This class is used in the junit tests for the ODE integrators.

 *
This specific problem is the following differential equation :
 *

 *    y' = t^3 - t y
 *

 * with the initial condition y (0) = 0. The solution of this equation
 * is the following function :
 *

 *   y (t) = t^2 + 2 (exp (- t^2 / 2) - 1)
 *

 *

 */
public class TestProblem2
  extends TestProblemAbstract {

  /** theoretical state */
  private double[] y;

  /**
   * Simple constructor.
   */
  public TestProblem2() {
    super();
    double[] y0 = { 0.0 };
    setInitialConditions(0.0, y0);
    setFinalConditions(1.0);
    double[] errorScale = { 1.0 };
    setErrorScale(errorScale);
    y = new double[y0.length];
  }

  /**
   * Copy constructor.
   * @param problem problem to copy
   */
  public TestProblem2(TestProblem2 problem) {
    super(problem);
    y = problem.y.clone();
  }

  /** {@inheritDoc} */
  @Override
public TestProblem2 copy() {
    return new TestProblem2(this);
  }

  @Override
  public void doComputeDerivatives(double t, double[] y, double[] yDot) {

    // compute the derivatives
    for (int i = 0; i < n; ++i)
      yDot[i] = t * (t * t - y[i]);

  }

  @Override
  public double[] computeTheoreticalState(double t) {
    double t2 = t * t;
    double c = t2 + 2 * (FastMath.exp (-0.5 * t2) - 1);
    for (int i = 0; i < n; ++i) {
      y[i] = c;
    }
    return y;
  }

}


text:
<?php

namespace FTR\WebBundle\Repository;

use Doctrine\ORM\EntityRepository;

/**
 * Facility2siteRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class Facility2siteRepository extends EntityRepository
{
}


text:
// Copyright 2018 Google LLC
//
// 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.

package com.google.firebase.codelab.awesomedrawingquiz.ui.game;

import com.google.firebase.codelab.awesomedrawingquiz.data.Drawing;
import com.google.firebase.codelab.awesomedrawingquiz.data.DrawingDao;
import com.google.firebase.codelab.awesomedrawingquiz.ui.game.event.GameEvent;
import com.google.firebase.codelab.awesomedrawingquiz.ui.game.event.GameLevelClearEvent;
import com.google.firebase.codelab.awesomedrawingquiz.ui.game.event.GameLevelClueUpdateEvent;
import com.google.firebase.codelab.awesomedrawingquiz.ui.game.event.GameLevelEvent;
import com.google.firebase.codelab.awesomedrawingquiz.ui.game.event.GameLevelSkipEvent;
import com.google.firebase.codelab.awesomedrawingquiz.ui.game.event.GameStageClearEvent;
import com.google.firebase.codelab.awesomedrawingquiz.ui.game.event.GameWrongAnswerEvent;

import android.arch.lifecycle.ViewModel;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.PublishSubject;

public final class GameViewModel extends ViewModel {

    private Disposable drawingRequestDisposable;

    private Disposable gameEventDisposable;

    private PublishSubject<GameEvent> gameEvents = PublishSubject.create();

    private final DrawingDao drawingDao;

    // Level-scoped information

    private int currentLevel = 1;

    private int numAttempts = 0;

    private int disclosedLettersByDefault = 1;

    private int disclosedLetters;

    private long levelStartTimeInMillis;

    private String clue;

    private boolean isHintAvailable;

    private boolean isHintUsed;

    private Drawing drawing;

    // Stage-scope information

    private int disclosedLettersOnReward = 1;

    private int gameDifficulty;

    private int numCorrectAnswers = 0;

    private List<String> seenWords = new ArrayList<>();

    public GameViewModel(DrawingDao drawingDao) {
        this.drawingDao = drawingDao;
    }

    void registerGameEventListener(Consumer<GameEvent> listener) {
        disposeIfNeeded(gameEventDisposable);
        gameEventDisposable = gameEvents
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(listener);
    }

    boolean isStarted() {
        return null != drawing;
    }

    void startLevel() {
        numCorrectAnswers = 0;
        gameDifficulty = GameSettings.DIFFICULTY_NORMAL;
        seenWords.clear();

        startLevel(1);
    }

    void checkAnswer(@NonNull String userAnswer) {
        numAttempts++;

        boolean correct = drawing.getWord().equalsIgnoreCase(userAnswer);
        if (correct) {
            numCorrectAnswers++;
            int elapsedTimeInSeconds =
                    (int) (System.currentTimeMillis() - levelStartTimeInMillis) / 1000;
            gameEvents.onNext(GameLevelClearEvent.create(
                    numAttempts, elapsedTimeInSeconds,
                    currentLevel == GameSettings.MAX_LEVEL, isHintUsed, drawing));
        } else {
            gameEvents.onNext(GameWrongAnswerEvent.create(drawing));
        }
    }

    boolean isHintAvailable() {
        return isHintAvailable && !isHintUsed;
    }

    Drawing getCurrentDrawing() {
        if (null == drawing) {
            throw new IllegalStateException("Level is not loaded yet");
        }
        return drawing;
    }

    void skipLevel() {
        int elapsedTimeInSeconds =
                (int) (System.currentTimeMillis() - levelStartTimeInMillis) / 1000;
        gameEvents.onNext(GameLevelSkipEvent.create(
                numAttempts, elapsedTimeInSeconds, isHintUsed, drawing));
        moveToNextLevel();
    }

    void moveToNextLevel() {
        if (currentLevel < GameSettings.MAX_LEVEL) {
            startLevel(currentLevel + 1);
        } else {
            finishStage();
        }
    }

    void useHint() {
        if (isHintUsed) {
            Log.e("GameViewModel", "Hint already used");
            return;
        }

        isHintUsed = true;
        disclosedLetters += disclosedLettersOnReward;

        clue = ClueGenerator.generate(drawing.getWord(), disclosedLetters);
        gameEvents.onNext(GameLevelClueUpdateEvent.create(clue, drawing));
    }

    private void startLevel(int newLevel) {
        numAttempts = 0;
        isHintAvailable = true;
        isHintUsed = false;
        currentLevel = newLevel;
        levelStartTimeInMillis = System.currentTimeMillis();

        applyDifficulty();
        requestNewDrawing();
    }

    private void applyDifficulty() {
        switch (gameDifficulty) {
            case GameSettings.DIFFICULTY_EASY:
                disclosedLettersByDefault = 2;
                break;
            case GameSettings.DIFFICULTY_HARD:
                disclosedLettersByDefault = 0;
                break;
            default:
                disclosedLettersByDefault = 1;
                break;
        }
        disclosedLetters = disclosedLettersByDefault;
    }

    private void requestNewDrawing() {
        disposeIfNeeded(drawingRequestDisposable);

        drawingRequestDisposable = drawingDao.getRandomDrawings(seenWords)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(d -> {
                    clue = ClueGenerator.generate(d.getWord(), disclosedLetters);
                    seenWords.add(d.getWord());
                    drawing = d;

                    // Do not allow using a hint if it reveals all letters of the word
                    // after receiving a reward
                    if (disclosedLettersByDefault + disclosedLettersOnReward
                            >= drawing.getWord().length()) {
                        isHintAvailable = false;
                    }

                    gameEvents.onNext(GameLevelEvent.create(currentLevel, clue, d));
                });
    }

    private void finishStage() {
        gameEvents.onNext(GameStageClearEvent.create(numCorrectAnswers));
    }

    private void disposeIfNeeded(@Nullable Disposable d) {
        if (null != d && !d.isDisposed()) {
            d.dispose();
        }
    }

    @Override
    protected void onCleared() {
        disposeIfNeeded(drawingRequestDisposable);
        disposeIfNeeded(gameEventDisposable);
    }
}


text:
<?php

define('WP_REPAIRING', true);

require_once('../../wp-load.php');

header( 'Content-Type: text/html; charset=utf-8' );
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title><?php _e('WordPress › Database Repair'); ?></title>
	<?php wp_admin_css( 'install', true ); ?>

<?php

if ( !defined('WP_ALLOW_REPAIR') ) {
	echo '
'.__('To allow use of this page to automatically repair database problems, please add the following line to your wp-config.php file.  Once this line is added to your config, reload this page.')."
define('WP_ALLOW_REPAIR', true);";
} elseif ( isset($_GET['repair']) ) {
	$problems = array();
	check_admin_referer('repair_db');

	if ( 2 == $_GET['repair'] )
		$optimize = true;
	else
		$optimize = false;

	$okay = true;

	$tables = $wpdb->tables();
	// Sitecategories may not exist if global terms are disabled.
	if ( is_multisite() && ! $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->sitecategories'" ) )
		unset( $tables['sitecategories'] );
	$tables = array_merge( $tables, (array) apply_filters( 'tables_to_repair', array() ) ); // Return tables with table prefixes.
	// Loop over the tables, checking and repairing as needed.
	foreach ( $tables as $table ) {
		$check = $wpdb->get_row("CHECK TABLE $table");
		if ( 'OK' == $check->Msg_text ) {
			echo "
The $table table is okay.";
		} else {
			echo "
The $table table is not okay. It is reporting the following error: $check->Msg_text.  WordPress will attempt to repair this table…";
			$repair = $wpdb->get_row("REPAIR TABLE $table");
			if ( 'OK' == $check->Msg_text ) {
				echo "
    Successfully repaired the $table table.";
			} else {
				echo "
    Failed to repair the $table table. Error: $check->Msg_text
";
				$problems["$table"] = $check->Msg_text;
				$okay = false;
			}
		}
		if ( $okay && $optimize ) {
			$check = $wpdb->get_row("ANALYZE TABLE $table");
			if ( 'Table is already up to date' == $check->Msg_text )  {
				echo "
    The $table table is already optimized.";
			} else {
				$check = $wpdb->get_row("OPTIMIZE TABLE $table");
				if ( 'OK' == $check->Msg_text || 'Table is already up to date' == $check->Msg_text )
					echo "
    Successfully optimized the $table table.";
				else
					echo "
    Failed to optimize the $table table. Error: $check->Msg_text";
			}
		}
		echo '
';
	}

	if ( !empty($problems) ) {
		printf('
'.__('Some database problems could not be repaired. Please copy-and-paste the following list of errors to the WordPress support forums to get additional assistance.').'
', 'http://wordpress.org/support/forum/3');
		$problem_output = array();
		foreach ( $problems as $table => $problem )
			$problem_output[] = "$table: $problem";
		echo '<textarea name="errors" id="errors" rows="20" cols="60">' . esc_textarea( implode("\n", $problem_output) ) . '</textarea>';
	} else {
		echo '
'.__('Repairs complete.  Please remove the following line from wp-config.php to prevent this page from being used by unauthorized users.')."
define('WP_ALLOW_REPAIR', true);";
	}
} else {
	if ( isset($_GET['referrer']) && 'is_blog_installed' == $_GET['referrer'] )
		_e('One or more database tables are unavailable. To allow WordPress to attempt to repair these tables, press the “Repair Database” button. Repairing can take a while, so please be patient.');
	else
		_e('WordPress can automatically look for some common database problems and repair them.  Repairing can take a while, so please be patient.')
?>

<a class="button" href="<?php echo wp_nonce_url('repair.php?repair=1', 'repair_db') ?>"><?php _e( 'Repair Database' ); ?>

	<?php _e('WordPress can also attempt to optimize the database.  This improves performance in some situations.  Repairing and optimizing the database can take a long time and the database will be locked while optimizing.'); ?>

<a class="button" href="<?php echo wp_nonce_url('repair.php?repair=2', 'repair_db') ?>"><?php _e( 'Repair and Optimize Database' ); ?>

<?php
}
?>