text:
package fi.nls.oskari.domain.map.userlayer;

import fi.nls.oskari.util.ConversionHelper;
import org.json.JSONException;
import org.json.JSONObject;

public class UserLayerStyle {

    private long id;
    private long stroke_width;
    private String stroke_color;
    private String fill_color;
    private String dot_color;
    private long dot_size;
    private long border_width;
    private String border_color;
    private String dot_shape;
    private String stroke_linejoin;
    private int fill_pattern;
    private String stroke_linecap;
    private String stroke_dasharray;
    private String border_linejoin;
    private String border_dasharray;

    public void populateFromJSON(final JSONObject stylejs) throws JSONException {
        try {
            // {"area":{"fillColor":"FFDC00","lineColor":"CC9900","size":"2"},"line":{"color":"CC9900","size":"2"},"dot":{"color":"CC9900","size":"4"}}
            setBorder_color(stylejs.getJSONObject("area").optString("lineColor"));
            setBorder_width(stylejs.getJSONObject("area").optInt("size"));
            setDot_color(stylejs.getJSONObject("dot").optString("color"));
            setDot_size(stylejs.getJSONObject("dot").optInt("size"));
            setFill_color(stylejs.getJSONObject("area").optString("fillColor"));
            setStroke_color(stylejs.getJSONObject("line").optString("color"));
            setStroke_width(stylejs.getJSONObject("line").optInt("size"));
            setDot_shape(stylejs.getJSONObject("dot").optString("shape"));
            setStroke_linejoin(stylejs.getJSONObject("line").optString("corner"));
            setFill_pattern(ConversionHelper.getInt(stylejs.getJSONObject("area").optString("fillStyle"), -1));
            setStroke_linecap(stylejs.getJSONObject("line").optString("cap"));
            setStroke_dasharray(stylejs.getJSONObject("line").optString("style"));
            setBorder_linejoin(stylejs.getJSONObject("area").optString("lineCorner"));
            setBorder_dasharray(stylejs.getJSONObject("area").optString("lineStyle"));
        } catch (Exception ex) {
            throw new JSONException(ex);
        }

    }

    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public long getStroke_width() {
        return stroke_width;
    }
    public void setStroke_width(long strokeWidth) {
        stroke_width = strokeWidth;
    }
    public String getStroke_color() {
        return stroke_color;
    }
    public void setStroke_color(String strokeColor) {
        stroke_color = strokeColor;
    }
    public String getFill_color() {
        return fill_color;
    }
    public void setFill_color(String fillColor) {
        fill_color = fillColor;
    }
    public String getDot_color() {
        return dot_color;
    }
    public void setDot_color(String dotColor) {
        dot_color = dotColor;
    }
    public long getDot_size() {
        return dot_size;
    }
    public void setDot_size(long dotSize) {
        dot_size = dotSize;
    }
    public long getBorder_width() {
        return border_width;
    }
    public void setBorder_width(long borderWidth) {
        border_width = borderWidth;
    }
    public String getBorder_color() {
        return border_color;
    }
    public void setBorder_color(String borderColor) {
        border_color = borderColor;
    }

    public String getDot_shape() {
        return dot_shape;
    }

    public void setDot_shape(String dot_shape) {
        this.dot_shape = dot_shape;
    }

    public String getStroke_linejoin() {
        return stroke_linejoin;
    }

    public void setStroke_linejoin(String stroke_linejoin) {
        this.stroke_linejoin = stroke_linejoin;
    }

    public int getFill_pattern() {
        return fill_pattern;
    }

    public void setFill_pattern(int fill_pattern) {
        this.fill_pattern = fill_pattern;
    }

    public String getStroke_linecap() {
        return stroke_linecap;
    }

    public void setStroke_linecap(String stroke_linecap) {
        this.stroke_linecap = stroke_linecap;
    }

    public String getStroke_dasharray() {
        return stroke_dasharray;
    }

    public void setStroke_dasharray(String stroke_dasharray) {
        this.stroke_dasharray = stroke_dasharray;
    }

    public String getBorder_linejoin() {
        return border_linejoin;
    }

    public void setBorder_linejoin(String border_linejoin) {
        this.border_linejoin = border_linejoin;
    }

    public String getBorder_dasharray() {
        return border_dasharray;
    }

    public void setBorder_dasharray(String border_dasharray) {
        this.border_dasharray = border_dasharray;
    }
}

redpajama_set_name: RedPajamaGithub


text:
v2.2

Increased difficulty on Big Boo and Lemmy

Randomize some layer3 effects

Randomize sprites

Re-add water Bowser (included in pogyo mode)

v2.1

Fix hammer velocity to incorporate Mario's running speed

Randomize screen exits

Add new Yoshi color abilities: increased speed, increased jump height, coin factory

Added randomizer changelog :^)

Fix some graphical issues with switch palaces and Mario/Luigi swapping

v2.0

Swap sublevels

Randomize Lemmy fight layout

Add background scrolling

Keys can be added to bubbles and exploding blocks

Prevent keys from despawning due to sprite limits

Fix buoyancy in CI2 sublevels

Make more sprites killable by hammer powerup

Rebalanced randomizer presets


text:
<?php
class BlogModule extends YWebModule
{
    public function getDependencies()
    {
        return array(
            'user',
        );
    }

    public function getCategory()
    {
        return Yii::t('blog', 'Контент');
    }

    public function getParamsLabels()
    {
        return array(
            'adminMenuOrder' => Yii::t('blog', 'Порядок следования в меню'),
            'editor'         => Yii::t('blog', 'Визуальный редактор'),
        );
    }

    public function getEditableParams()
    {
        return array(
            'adminMenuOrder',
            'editor' => Yii::app()->getModule('yupe')->getEditors(),
        );
    }

    public function getNavigation()
    {
        return array(
            array('label' => Yii::t('blog', 'Блоги')),
            array('icon' => 'list-alt', 'label' => Yii::t('blog', 'Список блогов'), 'url' => array('/blog/BlogAdmin/index')),
            array('icon' => 'plus-sign', 'label' => Yii::t('blog', 'Добавить блог'), 'url' => array('/blog/BlogAdmin/create')),
            array('label' => Yii::t('blog', 'Записи')),
            array('icon' => 'list-alt', 'label' => Yii::t('blog', 'Список записей'), 'url' => array('/blog/PostAdmin/index')),
            array('icon' => 'plus-sign', 'label' => Yii::t('blog', 'Добавить запись'), 'url' => array('/blog/PostAdmin/create')),
            array('label' => Yii::t('blog', 'Участники')),
            array('icon' => 'list-alt', 'label' => Yii::t('blog', 'Список участников'), 'url' => array('/blog/UserToBlogAdmin/index')),
            array('icon' => 'plus-sign', 'label' => Yii::t('blog', 'Добавить участника'), 'url' => array('/blog/UserToBlogAdmin/create')),
        );
    }

    public  function getVersion()
    {
        return Yii::t('blog', '0.3');
    }

    public function getName()
    {
        return Yii::t('blog', 'Блоги');
    }

    public function getDescription()
    {
        return Yii::t('blog', 'Модуль для построения личного блога или блогового сообщества');
    }

    public function getAuthor()
    {
        return Yii::t('blog', 'yupe team');
    }

    public function getAuthorEmail()
    {
        return Yii::t('blog', 'team@yupe.ru');
    }

    public function getUrl()
    {
        return Yii::t('blog', 'http://yupe.ru');
    }

    public function getAdminPageLink()
    {
        return '/blog/blogAdmin/index';
    }

    public function getIcon()
    {
        return "pencil";
    }

    public function init()
    {
        parent::init();

        $this->setImport(array(
            'blog.models.*',
            'blog.components.*',
        ));
    }
}


text:
package org.testng;

import org.testng.collections.Lists;
import org.testng.collections.Objects;
import org.testng.internal.IResultListener2;

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

/**
 * A simple ITestListener adapter that stores all the tests
 * that were run.  You can retrieve these results with the
 * following methods:
 * getPassedTests()
 * getFailedTests()
 * getSkippedTests()
 *
 * If you extend this class in order to override any of these
 * methods, remember to call their super equivalent if you want
 * this list of tests to be maintained.
 *
 * @author Cedric Beust, Aug 6, 2004
 * @author Alexandru Popescu
 */
public class TestListenerAdapter implements IResultListener2 {
  private List<ITestNGMethod> m_allTestMethods =
      Collections.synchronizedList(Lists.<ITestNGMethod>newArrayList());
  private List<ITestResult> m_passedTests = Collections.synchronizedList(Lists.<ITestResult>newArrayList());
  private List<ITestResult> m_failedTests = Collections.synchronizedList(Lists.<ITestResult>newArrayList());
  private List<ITestResult> m_skippedTests = Collections.synchronizedList(Lists.<ITestResult>newArrayList());
  private List<ITestResult> m_failedButWSPerTests = Collections.synchronizedList(Lists.<ITestResult>newArrayList());
  private List<ITestContext> m_testContexts= Collections.synchronizedList(new ArrayList<ITestContext>());
  private List<ITestResult> m_failedConfs= Collections.synchronizedList(Lists.<ITestResult>newArrayList());
  private List<ITestResult> m_skippedConfs= Collections.synchronizedList(Lists.<ITestResult>newArrayList());
  private List<ITestResult> m_passedConfs= Collections.synchronizedList(Lists.<ITestResult>newArrayList());

  @Override
  public void onTestSuccess(ITestResult tr) {
    m_allTestMethods.add(tr.getMethod());
    m_passedTests.add(tr);
  }

  @Override
  public void onTestFailure(ITestResult tr) {
    m_allTestMethods.add(tr.getMethod());
    m_failedTests.add(tr);
  }

  @Override
  public void onTestSkipped(ITestResult tr) {
    m_allTestMethods.add(tr.getMethod());
    m_skippedTests.add(tr);
  }

  @Override
  public void onTestFailedButWithinSuccessPercentage(ITestResult tr) {
    m_allTestMethods.add(tr.getMethod());
    m_failedButWSPerTests.add(tr);
  }

  protected ITestNGMethod[] getAllTestMethods() {
    return m_allTestMethods.toArray(new ITestNGMethod[m_allTestMethods.size()]);
  }

  @Override
  public void onStart(ITestContext testContext) {
	  m_testContexts.add(testContext);
  }

  @Override
  public void onFinish(ITestContext testContext) {
  }

  /**
   * @return Returns the failedButWithinSuccessPercentageTests.
   */
  public List<ITestResult> getFailedButWithinSuccessPercentageTests() {
    return new ArrayList<>(m_failedButWSPerTests);
  }
  /**
   * @return Returns the failedTests.
   */
  public List<ITestResult> getFailedTests() {
    return new ArrayList<>(m_failedTests);
  }
  /**
   * @return Returns the passedTests.
   */
  public List<ITestResult> getPassedTests() {
    return new ArrayList<>(m_passedTests);
  }
  /**
   * @return Returns the skippedTests.
   */
  public List<ITestResult> getSkippedTests() {
    return new ArrayList<>(m_skippedTests);
  }

  private static void ppp(String s) {
    System.out.println("[TestListenerAdapter] " + s);
  }
  /**
   * @param allTestMethods The allTestMethods to set.
   */
  public void setAllTestMethods(List<ITestNGMethod> allTestMethods) {
    m_allTestMethods = allTestMethods;
  }
  /**
   * @param failedButWithinSuccessPercentageTests The failedButWithinSuccessPercentageTests to set.
   */
  public void setFailedButWithinSuccessPercentageTests(
      List<ITestResult> failedButWithinSuccessPercentageTests) {
    m_failedButWSPerTests = failedButWithinSuccessPercentageTests;
  }
  /**
   * @param failedTests The failedTests to set.
   */
  public void setFailedTests(List<ITestResult> failedTests) {
    m_failedTests = failedTests;
  }
  /**
   * @param passedTests The passedTests to set.
   */
  public void setPassedTests(List<ITestResult> passedTests) {
    m_passedTests = passedTests;
  }
  /**
   * @param skippedTests The skippedTests to set.
   */
  public void setSkippedTests(List<ITestResult> skippedTests) {
    m_skippedTests = skippedTests;
  }

  @Override
  public void onTestStart(ITestResult result) {
  }

  public List<ITestContext> getTestContexts() {
    return m_testContexts;
  }

  public List<ITestResult> getConfigurationFailures() {
    return m_failedConfs;
  }

  /**
   * @see org.testng.IConfigurationListener#onConfigurationFailure(org.testng.ITestResult)
   */
  @Override
  public void onConfigurationFailure(ITestResult itr) {
    m_failedConfs.add(itr);
  }

  public List<ITestResult> getConfigurationSkips() {
    return m_skippedConfs;
  }

  @Override
  public void beforeConfiguration(ITestResult tr) {
  }

  /**
   * @see org.testng.IConfigurationListener#onConfigurationSkip(org.testng.ITestResult)
   */
  @Override
  public void onConfigurationSkip(ITestResult itr) {
    m_skippedConfs.add(itr);
  }

  /**
   * @see org.testng.IConfigurationListener#onConfigurationSuccess(org.testng.ITestResult)
   */
  @Override
  public void onConfigurationSuccess(ITestResult itr) {
    m_passedConfs.add(itr);
  }

  @Override
  public String toString() {
    return Objects.toStringHelper(getClass())
        .add("passed", getPassedTests().size())
        .add("failed", getFailedTests().size())
        .add("skipped", getSkippedTests().size())
        .toString();
  }
}


text:
<cybox:Observables xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:cybox="http://cybox.mitre.org/cybox-2"
    xmlns:cyboxCommon="http://cybox.mitre.org/common-2"
    xmlns:FileObj="http://cybox.mitre.org/objects#FileObject-2"
    xmlns:URIObj="http://cybox.mitre.org/objects#URIObject-2"
    xmlns:AddressObj="http://cybox.mitre.org/objects#AddressObject-2"
    xmlns:PortObj="http://cybox.mitre.org/objects#PortObject-2"
    xmlns:SocketAddressObj="http://cybox.mitre.org/objects#SocketAddressObject-1"
    xmlns:NetworkConnectionObj="http://cybox.mitre.org/objects#NetworkConnectionObject-2"
    xmlns:HTTPSessionObj="http://cybox.mitre.org/objects#HTTPSessionObject-2"
    xmlns:WinMailslotObj="http://cybox.mitre.org/objects#WinMailslotObject-2"
    xmlns:WinHandleObj="http://cybox.mitre.org/objects#WinHandleObject-2"
    xmlns:WinExecutableFileObj="http://cybox.mitre.org/objects#WinExecutableFileObject-2"
    xmlns:WinTaskObj="http://cybox.mitre.org/objects#WinTaskObject-2"
    xmlns:example="http://example.com/"
    xsi:schemaLocation="http://cybox.mitre.org/cybox-2 http://cybox.mitre.org/XMLSchema/core/2.0.1/cybox_core.xsd http://cybox.mitre.org/objects#WinTaskObject-2 http://cybox.mitre.org/XMLSchema/objects/Win_Task/2.0.1/Win_Task_Object.xsd http://cybox.mitre.org/objects#WinExecutableFileObject-2 http://cybox.mitre.org/XMLSchema/objects/Win_Executable_File/2.0.1/Win_Executable_File_Object.xsd  http://cybox.mitre.org/objects#WinHandleObject-2  http://cybox.mitre.org/XMLSchema/objects/Win_Handle/2.1/Win_Handle_Object.xsd  http://cybox.mitre.org/objects#WinMailslotObject-2 http://cybox.mitre.org/XMLSchema/objects/Win_Mailslot/2.0.1/Win_Mailslot_Object.xsd    http://cybox.mitre.org/objects#URIObject-2 http://cybox.mitre.org/XMLSchema/objects/URI/2.0.1/URI_Object.xsd http://cybox.mitre.org/objects#NetworkConnectionObject-2 http://cybox.mitre.org/XMLSchema/objects/Network_Connection/2.0.1/Network_Connection_Object.xsd     "
    cybox_major_version="2" cybox_minor_version="0" cybox_update_version="1">
    <cybox:Observable id="example:Observable-1b427720-98d7-4735-b125-754c7e08f285">
        <cybox:Description>
            This Observable specifies an example pattern written against a Network Connection Object
            with an HTTP Session, specifically the Network Protocols, Destination Socket IP Address and Port,
            and HTTP Request Method and Value.
        </cybox:Description>
        <cybox:Object id="example:Object-d1fdd983-530b-489f-9ab8-ed3cb5212c35">
            <cybox:Properties xsi:type="NetworkConnectionObj:NetworkConnectionObjectType">
                <NetworkConnectionObj:Layer3_Protocol datatype="string" condition="Equals">IPv4</NetworkConnectionObj:Layer3_Protocol>
                <NetworkConnectionObj:Layer4_Protocol datatype="string" condition="Equals">TCP</NetworkConnectionObj:Layer4_Protocol>
                <NetworkConnectionObj:Layer7_Protocol datatype="string" condition="Equals">HTTP</NetworkConnectionObj:Layer7_Protocol>
                <NetworkConnectionObj:Destination_Socket_Address>
                    <SocketAddressObj:IP_Address>
                        <AddressObj:Address_Value datatype="string" condition="StartsWith">198.49</AddressObj:Address_Value>
                    </SocketAddressObj:IP_Address>
                    <SocketAddressObj:Port>
                        <PortObj:Port_Value condition="Equals">80</PortObj:Port_Value>
                    </SocketAddressObj:Port>
                </NetworkConnectionObj:Destination_Socket_Address>
                <NetworkConnectionObj:Layer7_Connections>
                    <NetworkConnectionObj:HTTP_Session>
                        <HTTPSessionObj:HTTP_Request_Response>
                            <HTTPSessionObj:HTTP_Client_Request>
                                <HTTPSessionObj:HTTP_Request_Line>
                                    <HTTPSessionObj:HTTP_Method datatype="string" condition="Equals">GET</HTTPSessionObj:HTTP_Method>
                                    <HTTPSessionObj:Value condition="Contains">.asp</HTTPSessionObj:Value>
                                </HTTPSessionObj:HTTP_Request_Line>
                            </HTTPSessionObj:HTTP_Client_Request>
                        </HTTPSessionObj:HTTP_Request_Response>
                    </NetworkConnectionObj:HTTP_Session>
                </NetworkConnectionObj:Layer7_Connections>
            </cybox:Properties>
        </cybox:Object>
    </cybox:Observable>
    <cybox:Observable id="example:Observable-1c9af310-0d5a-4c44-bdd7-aea3d99f13b9">
        <cybox:Description>Test HTTP Session Object translations</cybox:Description>
        <cybox:Object id="example:Object-26be6630-b2df-4bf9-8750-3f45ca9e19d3">
            <cybox:Properties xsi:type="HTTPSessionObj:HTTPSessionObjectType">
                <HTTPSessionObj:HTTP_Request_Response>
                    <HTTPSessionObj:HTTP_Server_Response>
                        <HTTPSessionObj:HTTP_Response_Header>
                            <HTTPSessionObj:Parsed_Header>
                                <HTTPSessionObj:X_Forwarded_Proto/>
                            </HTTPSessionObj:Parsed_Header>
                        </HTTPSessionObj:HTTP_Response_Header>
                    </HTTPSessionObj:HTTP_Server_Response>
                </HTTPSessionObj:HTTP_Request_Response>
            </cybox:Properties>
        </cybox:Object>
    </cybox:Observable>
    <cybox:Observable>
        <cybox:Object>
            <cybox:Properties xsi:type="WinTaskObj:WindowsTaskObjectType">
                <WinTaskObj:Trigger_List>
                    <WinTaskObj:Trigger>
                        <WinTaskObj:Trigger_Type/>
                    </WinTaskObj:Trigger>
                </WinTaskObj:Trigger_List>
            </cybox:Properties>
        </cybox:Object>
    </cybox:Observable>
    <cybox:Observable id="example:Observable-1c9af310-0d5a-4c44-bdd7-aea3d99f13b6">
        <cybox:Object id="example:Object-26be6630-b2df-4bf9-8750-3f45ca9e19cf">
            <cybox:Properties xsi:type="URIObj:URIObjectType" type="URL">
                <URIObj:Value condition="Equals">http://example.com/index1.html</URIObj:Value>
            </cybox:Properties>
        </cybox:Object>
    </cybox:Observable>
    <cybox:Observable id="example:Observable-1c9af310-0d5a-4c44-bdd7-aea3d99f13b7">
        <cybox:Object id="example:Object-26be6630-b2df-4bf9-8750-3f45ca9e19cg">
            <cybox:Properties xsi:type="URIObj:URIObjectType" type="URL">
                <cyboxCommon:Custom_Properties>
                    <cyboxCommon:Property name="Test" condition="Equals">TEST</cyboxCommon:Property>
                </cyboxCommon:Custom_Properties>
                <URIObj:Value></URIObj:Value>
            </cybox:Properties>
        </cybox:Object>
    </cybox:Observable>
    <!--The following Observable contains the same IDs as the OBservable/Object above it.
        This is schema-valid (though violates suggested practices) in CybOX 2.0.1 but not
        CybOX 2.1-->
    <cybox:Observable id="example:Observable-1c9af310-0d5a-4c44-bdd7-aea3d99f13b7">
        <cybox:Object id="example:Object-26be6630-b2df-4bf9-8750-3f45ca9e19cg">
            <cybox:Properties xsi:type="URIObj:URIObjectType" type="URL">
                <cyboxCommon:Custom_Properties>
                    <cyboxCommon:Property name="Test" condition="Equals">TEST</cyboxCommon:Property>
                </cyboxCommon:Custom_Properties>
                <URIObj:Value></URIObj:Value>
            </cybox:Properties>
        </cybox:Object>
    </cybox:Observable>
    <cybox:Observable id="example:Observable-1c9af310-0d5a-4c44-bdd7-aea3d99f13b8">
        <cybox:Object id="example:Object-26be6630-b2df-4bf9-8750-3f45ca9e19ch">
            <cybox:Properties xsi:type="WinMailslotObj:WindowsMailslotObjectType">
                <WinMailslotObj:Handle>
                    <WinHandleObj:Handle>
                        <WinHandleObj:Name>Test</WinHandleObj:Name>
                    </WinHandleObj:Handle>
                    <WinHandleObj:Handle>
                        <WinHandleObj:Name>THIS REQUIRES FORCED UPDATES WHICH WILL REMOVE THE PARENT `HANDLE` OBJECT</WinHandleObj:Name>
                    </WinHandleObj:Handle>
                </WinMailslotObj:Handle>
                <WinMailslotObj:Name>TEST NAME</WinMailslotObj:Name>
            </cybox:Properties>
        </cybox:Object>
    </cybox:Observable>
    <cybox:Observable>
        <cybox:Object>
            <cybox:Properties xsi:type="WinExecutableFileObj:WindowsExecutableFileObjectType">
                <FileObj:File_Name>Hax.exe</FileObj:File_Name>
                <WinExecutableFileObj:Sections>
                    <WinExecutableFileObj:Section>
                        <WinExecutableFileObj:Entropy>
                            <WinExecutableFileObj:Value>1.0</WinExecutableFileObj:Value>
                        </WinExecutableFileObj:Entropy>
                        <WinExecutableFileObj:Type>THIS REQUIRES FORCED UPDATES</WinExecutableFileObj:Type>
                    </WinExecutableFileObj:Section>
                </WinExecutableFileObj:Sections>
                <WinExecutableFileObj:Type>Invalid</WinExecutableFileObj:Type>
            </cybox:Properties>
        </cybox:Object>
    </cybox:Observable>
</cybox:Observables>


text:
/***********************************************************************//**
* @file			EngineFactory.java
* @author		Kurt E. Clothier
* @date			December 7, 2015
*
* @breif		Factory for creating game engine components
*
* @pre			Compiler: Eclipse - Mars Release (4.5.0)
* @pre			Java: JRE 7 or greater
*
* @see			http://www.projectsbykec.com/
*
* @copyright	The MIT License (MIT) - see LICENSE.txt
****************************************************************************/
package games.engine;

import games.engine.plugin.Plugin;
import games.engine.plugin.PluginException;
import games.engine.plugin.PluginKeyword;
import games.engine.util.CardDealer;
import games.engine.util.CardDealerFactory;
import games.engine.util.CardGameBoard;
import games.engine.util.CardGameBoardFactory;
import games.engine.util.CardPileCollection;
import games.engine.util.CardPileFactory;
import games.engine.util.CardPileParameter;
import games.engine.util.CardPlayer;
import games.engine.util.Deck;
import games.engine.util.DeckFactory;
import games.engine.util.GamePlayer;
import games.engine.util.PlayingCardAlias;
import games.engine.util.PlayingCardFactory;
import games.engine.util.PlayingCardRanking;

/******************************************************************//**
 * The EngineFactory Enum
 * - Access statically as EngineFactory.INSTANCE.method()
 *	 or EngineFactory factory = EngineFactory.getInstance()
 *
 * These methods are extremely UGLY, and will be cleaned up if time allows...
 *********************************************************************/
public enum EngineFactory {

	/** An instance of this component factory */
	INSTANCE;

	/* Constructs this <tt>EngineFactory</tt> when first used. */
	private EngineFactory() {}

	/** Return an instance of this <tt>EngineFactory</tt>. */
	public static EngineFactory getInstance()
	{
		return INSTANCE;
	}

	public CardGameEngine createCardGameEngine(final Plugin plugin, final GamePlayer...gamePlayers) throws PluginException {
		plugin.checkType(Plugin.Type.RULES);

		// Create Engine Components
		EngineComponentFactory comFactory = EngineComponentFactory.getInstance();
		EngineComponentSet<Action> actions = comFactory.createActions(plugin);
		EngineComponentSet<Condition> conditions = comFactory.createConditions(plugin);
		EngineComponentSet<ControlledAction> cActions = comFactory.createControlledActions(plugin, conditions, actions);
		EngineComponentSet<Phase> phases = comFactory.createPhases(plugin, actions, conditions, cActions);
		EngineComponentSet<PlayingCardAlias> aliases = comFactory.createAliases(plugin);
		EngineComponentCollecion components = new EngineComponentCollecion(conditions, actions, cActions, phases, aliases);

		// Create CardPile collections
		final Plugin boardPlugin = new Plugin(Plugin.Type.BOARD, plugin.checkParamsFor(PluginKeyword.BOARD));
		final CardPileFactory pileFactory = CardPileFactory.getInstance();
		final Plugin[] pilePlugins = pileFactory.createPlugins(boardPlugin);

		// Create Card Players using the passed game players...
		final CardPlayer[] players = new CardPlayer[gamePlayers.length];
		final String startPhase = plugin.checkParamsFor(PluginKeyword.START_PHASE);
		if (!phases.contains(startPhase)) {
			throw PluginException.create(PluginException.Type.INVALID_PARAMETER, plugin, PluginKeyword.START_PHASE.toString(), startPhase);
		}
		for (int i = 0; i < players.length; i++) {
			// Read rules to get direction of play, order players in array accordingly
			switch (PluginKeyword.DIRECTION_OF_PLAY.checkBoundedParams(plugin, Engine.DirectionOfPlay.class)) {
			case CCW:
				// Put players in reverse order
				players[i] = new CardPlayer(gamePlayers[players.length - 1 - i], pileFactory.createCardPileCollection(CardPileParameter.Owner.PLAYER, pilePlugins));
				break;
			case CW:
			default:
				// Put players in forward order
				players[i] = new CardPlayer(gamePlayers[i], pileFactory.createCardPileCollection(CardPileParameter.Owner.PLAYER, pilePlugins));

				break;
			}
			players[i].setStartingPhase(phases.get(startPhase));
		}

		// Create Deck, Board, and Dealer
		final Deck deck = DeckFactory.INSTANCE.createDeck(plugin);
		final CardGameBoard board = CardGameBoardFactory.INSTANCE.createCardGameBoard(boardPlugin, deck);
		final CardPileCollection commonPiles = board.getCommonPiles();
		final CardDealer dealer = CardDealerFactory.INSTANCE.createCardDealer(plugin, commonPiles, deck, players);
		final PlayingCardRanking ranking = PlayingCardFactory.INSTANCE.createCardRanking(plugin);

		return new CardGameEngine(plugin.getFilename().getConvertedName(), components, ranking, board, dealer, players);
	}

}


text:
package com.ugg.gdxjam.model.configs;

import com.badlogic.gdx.ai.steer.Steerable;
import com.badlogic.gdx.ai.steer.behaviors.Arrive;
import com.badlogic.gdx.ai.steer.behaviors.Seek;
import com.ugg.gdxjam.model.components.SteeringBehaviorComponent;

/**
 * Created by Jose Cuellar on 14/01/2016.
 */
public class EnemySeekConfig implements BaseConfig<SteeringBehaviorComponent> {

    static final float MAX_LINEAR_SPEED = 2.5f;
    static final float MAX_LINEAR_ACCELERATION = 11000;
    static final float MAX_ANGULAR_SPEED = 1000;
    static final float MAX_ANGULAR_ACCELERATION =  1500;

    @Override
    public void applyConfigs(SteeringBehaviorComponent steeringBC) {
        Seek seek = (Seek)steeringBC.behavior;
        Steerable steerable = seek.getOwner();
        steerable.setMaxLinearSpeed(MAX_LINEAR_SPEED);
        steerable.setMaxLinearAcceleration(MAX_LINEAR_ACCELERATION);
        steerable.setMaxAngularSpeed(MAX_ANGULAR_SPEED);
        steerable.setMaxAngularAcceleration(MAX_ANGULAR_ACCELERATION);

    }
}


text:
The `@testing-library` family of packages helps you test UI components in a user-centric way.

> The more your tests resemble the way your software is used, the more confidence they can give you.

## Packages

`@testing-library` is a family of packages. The core library, DOM Testing Library, is a light-weight solution for testing web pages by querying and interacting with DOM nodes. The core library has been wrapped to provide ergonomic APIs for several frameworks, including React, Angular, and Vue.

- [DOM Testing Library](https://testing-library.com/docs/dom-testing-library/intro)
- [React Testing Library](https://testing-library.com/docs/react-testing-library/intro)
- [Native Testing Library](https://testing-library.com/docs/native-testing-library/intro)
- [Cypress Testing Library](https://testing-library.com/docs/cypress-testing-library/intro)
- [Puppeteer Testing Library](https://testing-library.com/docs/pptr-testing-library/intro)
- [Testcafe Testing Library](https://testing-library.com/docs/testcafe-testing-library/intro)

## What This Library is Not

1. A test runner or framework.
1. Specific to a testing framework.

`DOM Testing Library` works with any environment that provides DOM APIs, such as Jest, Mocha + JSDOM, or a real browser.

## DOM Testing Library

The `DOM Testing Library` is a very light-weight solution for testing DOM nodes (whether simulated with JSDOM as provided by default with Jest or in the browser). The main utilities it provides involve querying the DOM for nodes in a way that's similar to how the user finds elements on the page.


text:
//   ConfigNodeWrapper.cs
//
//  Author:
//       Allis Tauri <allista@gmail.com>
//
//  Copyright (c) 2016 Allis Tauri

using System;
using System.Collections.Generic;
using KSP.IO;

namespace AT_Utils
{
    //fuck you Squad! How come the ConfigNode is not serializable anymore? O_o
    [Obsolete("SerializableFiledsPartModule now handles ConfigNodes and IConfigNodes seamlessly.")]
    [Serializable]
    public class ConfigNodeWrapper
    {
        public string name;
        public ConfigNode.ValueList values;
        public List<ConfigNodeWrapper> nodes = new List<ConfigNodeWrapper>();

        public ConfigNodeWrapper(ConfigNode node)
        {
            name = node.name;
            values = node.values;
            foreach(ConfigNode n in node.nodes)
                nodes.Add(new ConfigNodeWrapper(n));
        }

        public ConfigNode ToConfigNode()
        {
            var node = new ConfigNode(name);
            foreach(ConfigNode.Value v in values)
                node.AddValue(v.name, v.value);
            foreach(var n in nodes)
                node.AddNode(n.ToConfigNode());
            return node;
        }

        public static byte[] SaveConfigNode(ConfigNode node)
        {
            byte[] data = null;
            try { data = IOUtils.SerializeToBinary(new ConfigNodeWrapper(node)); }
            catch(Exception ex) { Utils.Log("{}", ex); }
            return data;
        }

        public static ConfigNode RestoreConfigNode(byte[] data)
        {
            ConfigNodeWrapper node = null;
            try { node = IOUtils.DeserializeFromBinary(data) as ConfigNodeWrapper; }
            catch(System.Exception ex) { Utils.Log("{}", ex); }
            return node != null? node.ToConfigNode() : null;
        }

        public static implicit operator ConfigNode(ConfigNodeWrapper wrp)
        { return wrp.ToConfigNode(); }

        public override string ToString() { return ToConfigNode().ToString(); }
    }
}


text:
package org.senkbeil.debugger.akka.messages.structures

case class JDIThreadGroup(
  entryCount:     Option[Int]                 = None,
  isCollected:    Option[Boolean]             = None,
  owningThread:   Option[JDIThread]           = None,
  referenceType:  Option[JDIReferenceType]    = None,
  uniqueId:       Option[Long]                = None,
  waitingThreads: Option[Seq[JDIThread]]      = None,
  name:           Option[String]              = None,
  parent:         Option[JDIThreadGroup]      = None,
  threadGroups:   Option[Seq[JDIThreadGroup]] = None,
  threads:        Option[Seq[JDIThread]]      = None
) extends JDIObjectLike


text:
package com.wx.qi.service;

import java.util.List;
import java.util.Set;

import com.wx.qi.beans.MenuInfo;

public interface IAdminManageService {
	public List<MenuInfo> getAdminMenuOfDesktop(int adminId);

	public List<MenuInfo> getAdminMenuOfMenuItem(int adminId);

	public Set<String> getAdminPowerInfo(int adminId);
}


text:
/*=================================*/
/* Reset & Clearfix Styles
/*=================================*/

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } :focus { outline: 0; } ins { text-decoration: none; } del { text-decoration: line-through; } table { border-collapse: collapse; border-spacing: 0; }

.clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .clearfix { display: inline-block; } /* Hide from IE Mac \*/ .clearfix { display: block; } /* End hide from IE Mac */ .none { display: none; } /* End Clearfix */

/*=================================*/
/* Main Styles
/*=================================*/

body {
	font: 14px/1.6 "HelveticaNeue", "Helvetica Neue", Helvetica, Tahoma, Geneva, Arial, sans-serif;
	background: #fff;
	color: #333;
}

a, a:visited {
	color: #2ecc71;
	text-decoration: none;
}
a:hover, a:active {
	color: #333;
	text-decoration: none;
}

h1,h2,h3,h4,h5,h6 {
	font-weight: normal;
	line-height: 1.2em;
	margin-bottom: 20px;
}

h1 { font-size: 24px; }

h2 { font-size: 20px; }

h3 { font-size: 16px; }

h4 { font-size: 14px; }

h5 { font-size: 12px; }

h6 { font-size: 10px; }

p { margin-bottom: 20px; }

img {
	height: auto;
	max-width: 100%;
	vertical-align: bottom;
}

.content,
.loading {
	width: 500px;
	margin: 0 auto;
}
.content { margin-top: 100px; }
.pagination {
	margin-top: 50px;
	margin-bottom: 100px;
}
.loading {
	text-align: center;
	font-style: italic;
	margin-top: 50px;
	margin-bottom: 100px;
	display: none;
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SitemapsAndNavigationDemo.UK
{
    public partial class Bristol : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
	<gradient android:angle="0" android:startColor="#066dc9"
		android:centerColor="#1e7acd" android:endColor="#84ddff"/>
</shape>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="widget_label_1x1">Konumum 1 x 1</string>
  <string name="widget_label_2x1">Konumum 2 x 1</string>
  <string name="widget_label_4x1">Konumum 4 x 1</string>
  <string name="my_location">Konumum</string>
  <string name="app_name">Benim konum widget</string>
  <string name="location_not_found">Konumu bulunamıyor</string>
  <string name="tap_here_to_fix_that">Konum ayarlarını düzeltmek için buraya dokunun.</string>
  <string name="share_location">Paylaşım yeri</string>
  <string name="view_location">Konum görüntüleme</string>
  <string name="unknown_location">Bilinmeyen konum</string>
  <string name="determining_address">Adres çözme...</string>
  <string name="finding_location">Konum bulma</string>
  <string name="tap_to_get_location">< konum almak için dokunun simgesi.</string>
  <string name="tap_to_cancel">İptal etmek için dokunun.</string>
  <string name="cannot_share_location">Konum paylaşamazsınız.</string>
  <!-- Share Types -->
  <string name="address">Adres</string>
  <string name="coordinates">İletişim bilgileri</string>
  <string name="maps_link">Haritalar bağlantı</string>
  <string name="address_with_link">Adres eşleme bağlantısı ile</string>
  <!-- View Types -->
  <string name="you_are_here">You are here</string>
  <string name="your_friend_is_here">Arkadaşınız İşte.</string>
</resources>


text:
export function warnOnce(zone) {
  var didWarn = {};
  return function (message) {
    var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "warn";

    if (!didWarn[message]) {
      console[type]("[VKUI/".concat(zone, "] ").concat(message));
      didWarn[message] = true;
    }
  };
}
//# sourceMappingURL=warnOnce.js.map


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/background_color"
    android:orientation="vertical"
    >
    <include layout="@layout/include_toolbar"/>
    <include layout="@layout/include_recyclerview"/>
</LinearLayout>


text:
module Kana::PublicFilter
  extend ActiveSupport::Concern

  included do
    after_action :render_kana, if: ->{ filters.include?(:kana) }
  end

  private

  def set_request_path_with_kana
    return if @cur_main_path !~ /^#{SS.config.kana.location}\//
    @cur_main_path.sub!(/^#{SS.config.kana.location}\//, "/")
    filters << :kana
  end

  def render_kana
    body = response.body

    body = Kana::Convertor.kana_html(@cur_site, body)
    body.sub!(/<body( |>)/m, '<body data-kana="true"\\1')

    response.body = body
  end
end


text:
using System.Collections.Specialized;
using Common.Logging.Log4Net;

namespace Rhino.Etl.Cmd
{
    using System;
    using System.IO;
    using Core;
    using log4net;
    using log4net.Config;

    public class RhinoEtlRunner : MarshalByRefObject
    {
        private readonly ILog log = LogManager.GetLogger(typeof (RhinoEtlRunner));

        public static void SetupLogging(bool verbose)
        {
            Common.Logging.LogManager.Adapter = new Log4NetLoggerFactoryAdapter(new NameValueCollection());

            string configurationName = "Rhino.Etl.Cmd.standard.log4net.config";
            if (verbose)
                configurationName = "Rhino.Etl.Cmd.verbose.log4net.config";
            using (Stream stream = typeof(RhinoEtlSetup).Assembly.GetManifestResourceStream(configurationName))
                XmlConfigurator.Configure(stream);
        }

        public void Start(Type type, bool verboseLogging)
        {
            try
            {
                SetupLogging(verboseLogging);
                EtlProcess process = (EtlProcess)Activator.CreateInstance(type);
                process.Execute();
                foreach (Exception error in process.GetAllErrors())
                {
                    log.Debug(error);
                    log.Error(error.Message);
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }
    }
}


text:
<?php

namespace ERede\Acquiring\Integration;

class AvsQueryClass {

    public $CEP = null;
    public $COMPLEMENTO = null;
    public $CPF = null;
    public $ENDERECO = null;
    public $MSG_AVS = null;
    public $NU_ENDERECO = null;
    public $RESP_AVS = null;

}


text:
layout: post
title: "Thinkpad X220 Review"
---

After returning my previous company's Macbook Air, I was in the market for a
laptop for doing personal stuff and software dev. The MBA is almost the perfect
hardware in my mind - it's extremely light, has a quality build, 8 hours of
battery life, a really amazing TN screen, and i7 processor.  With linux loaded
on it, it _flies_. But, unfortunately, there are a couple drawbacks that led me
to look elsewhere. The horrible chiclet keyboard and - the ultimate dealbreaker
- the price. A fully loaded 12" MBA costs around $1800, and they don't resell
  for much less.

So, I turned to my old stalwart, the venerable Thinkpad. I've owned Thinkpads for
a while, from an x24 I used at UCLA to a few x40/x41s. My latest x41 recently
died, so I wanted to find a nice upgrade with a bit more processing power and
increased screen size.

## Thinkpad x200s

So, the x200s seemed like the best option to me, with a WXGA+ 1440x900 screen.
I got a used one off of Ebay for about $200. Being my first Lenovo, I was quite
impressed out of the box - very solid build quality and great keyboard. But
after turning it on, the screen quality just destroyed my impressions of the
machine. After spending years with IPS and good quality TN screens, this was
appalling.

IBM was infamous for using poor quality panels on its laptops. Even still, my
X41 was pretty usable. But not the x200s screen. I tried using it for a few
days but couldn't use it for more than few hours before getting eye fatigue. A
real shame, because it's such a great machine otherwise.

![My X220](/images/james-x220.png)
{: .image-pull-right}

## Thinkpad x220

So after a disappointing experience with the x200s, I started looking at the
later model Thinkpads - particularly the X220 with it's IPS screen option. I
sold the x200s and bought an x220 with warranty off of ebay for just under $500.

Turning on the x220 blew me away. The screen is amazing. Finally a Thinkpad
with a decent screen. With the tried and true scissor switch keyboard I had the
best of both worlds now. And ivy bridge is the icing on the cake.

## Build quality and tech support

I've been using the x220 for about a month now, and there are, unfortunately, a
few build quality issues with the x220 that I've been experiencing.

The bottom and top chassis tend to warp themselves over time This can be fixed
by gently twisting the chassis to realign it, I kid you not.

The IPS screen, while much better than any other Thinkpad screen I've used,
suffers from backlight bleeding along the bottom. This is exacerbated by the
top chassis warping and applying pressure to the panel. It's not too
noticeable, but more than any Macbook I've used.

I also haven't had a great experience with tech support so far.

## Final impressions

Still, I'm pretty happy with my x220, and the price is hard to beat. The
screen, battery life, trackpoint, and keyboard are all great. While not the
perfect laptop (which I don't think exists), it's pretty darned close.

If I had the money, I might spring for an MBA again, but I'd have a hard time
giving up the Thinkpad's keyboard. It's hard to overstate how nice it is
compared to the chiclet keyboards on the Macbooks.

See my [next post]({% post_url 2013-06-26-thinkpad-x220-arch %}) for a guide to
setting up Arch Linux on the x220.


text:
package net.robotmedia.widget;

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.ViewGroup;

public class ImageView extends android.widget.ImageView {

	public ImageView(Context context) {
		super(context);
	}

    public ImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public ImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void fitYUniformly() {
    	final Drawable drawable = getDrawable();
    	if (drawable == null) return;

		final int dwidth = drawable.getIntrinsicWidth();
		final int dheight = drawable.getIntrinsicHeight();
		if (dwidth == -1 || dheight == -1) return;

		int vheight = this.getHeight();
		float scale = (float) vheight / (float) dheight;

		final int vwidth = (int) (dwidth * scale);
		scale(scale, vwidth, vheight);
    }

    public void fitXUniformly() {
    	final Drawable drawable = getDrawable();
    	if (drawable == null) return;

		final int dwidth = drawable.getIntrinsicWidth();
		final int dheight = drawable.getIntrinsicHeight();
		if (dwidth == -1 || dheight == -1) return;

		int vwidth = this.getWidth();
		float scale = (float) vwidth / (float) dwidth;

		final int vheight = (int) (dheight * scale);
		scale(scale, vwidth, vheight);
    }

    private void scale(float scale, int newWidth, int newHeight) {
		final ViewGroup.LayoutParams params = this.getLayoutParams();
		params.width = newWidth;
		params.height = newHeight;
		this.setLayoutParams(params);
		this.setScaleType(ScaleType.MATRIX);
		final Matrix matrix = new Matrix();
		matrix.setScale(scale, scale);
		this.setImageMatrix(matrix);
    }

}


text:
"""
Class that holds a genetic algorithm for evolving a network.

Credit:
    A lot of those code was originally inspired by:
    http://lethain.com/genetic-algorithms-cool-name-damn-simple/
"""
from functools import reduce
from operator import add
import random
from network import Network

class Optimizer():
    """Class that implements genetic algorithm for MLP optimization."""

    def __init__(self, nn_param_choices, retain=0.4,
                 random_select=0.1, mutate_chance=0.2):
        """Create an optimizer.

        Args:
            nn_param_choices (dict): Possible network paremters
            retain (float): Percentage of population to retain after
                each generation
            random_select (float): Probability of a rejected network
                remaining in the population
            mutate_chance (float): Probability a network will be
                randomly mutated

        """
        self.mutate_chance = mutate_chance
        self.random_select = random_select
        self.retain = retain
        self.nn_param_choices = nn_param_choices

    def create_population(self, count):
        """Create a population of random networks.

        Args:
            count (int): Number of networks to generate, aka the
                size of the population

        Returns:
            (list): Population of network objects

        """
        pop = []
        for _ in range(0, count):
            # Create a random network.
            network = Network(self.nn_param_choices)
            network.create_random()

            # Add the network to our population.
            pop.append(network)

        return pop

    @staticmethod
    def fitness(network):
        """Return the accuracy, which is our fitness function."""
        return network.accuracy

    def grade(self, pop):
        """Find average fitness for a population.

        Args:
            pop (list): The population of networks

        Returns:
            (float): The average accuracy of the population

        """
        summed = reduce(add, (self.fitness(network) for network in pop))
        return summed / float((len(pop)))

    def breed(self, mother, father):
        """Make two children as parts of their parents.

        Args:
            mother (dict): Network parameters
            father (dict): Network parameters

        Returns:
            (list): Two network objects

        """
        children = []
        for _ in range(2):

            child = {}

            # Loop through the parameters and pick params for the kid.
            for param in self.nn_param_choices:
                child[param] = random.choice(
                    [mother.network[param], father.network[param]]
                )

            # Now create a network object.
            network = Network(self.nn_param_choices)
            network.create_set(child)

            children.append(network)

        return children

    def mutate(self, network):
        """Randomly mutate one part of the network.

        Args:
            network (dict): The network parameters to mutate

        Returns:
            (Network): A randomly mutated network object

        """
        # Choose a random key.
        mutation = random.choice(list(self.nn_param_choices.keys()))

        # Mutate one of the params.
        network.network[mutation] = random.choice(self.nn_param_choices[mutation])

        return network

    def evolve(self, pop):
        """Evolve a population of networks.

        Args:
            pop (list): A list of network parameters

        Returns:
            (list): The evolved population of networks

        """
        # Get scores for each network.
        graded = [(self.fitness(network), network) for network in pop]

        # Sort on the scores.
        graded = [x[1] for x in sorted(graded, key=lambda x: x[0], reverse=True)]

        # Get the number we want to keep for the next gen.
        retain_length = int(len(graded)*self.retain)

        # The parents are every network we want to keep.
        parents = graded[:retain_length]

        # For those we aren't keeping, randomly keep some anyway.
        for individual in graded[retain_length:]:
            if self.random_select > random.random():
                parents.append(individual)

        # Randomly mutate some of the networks we're keeping.
        for individual in parents:
            if self.mutate_chance > random.random():
                individual = self.mutate(individual)

        # Now find out how many spots we have left to fill.
        parents_length = len(parents)
        desired_length = len(pop) - parents_length
        children = []

        # Add children, which are bred from two remaining networks.
        while len(children) < desired_length:

            # Get a random mom and dad.
            male = random.randint(0, parents_length-1)
            female = random.randint(0, parents_length-1)

            # Assuming they aren't the same network...
            if male != female:
                male = parents[male]
                female = parents[female]

                # Breed them.
                babies = self.breed(male, female)

                # Add the children one at a time.
                for baby in babies:
                    # Don't grow larger than desired length.
                    if len(children) < desired_length:
                        children.append(baby)

        parents.extend(children)

        return parents


text:
namespace psy {

template <class T>
Substitution<T> Substitution<T>::Trivial;

template <>
std::string applyAll(const Substitution<std::string>& sub, const std::string& input)
{
    if (sub == Substitution<std::string>::Trivial)
        return input;

    std::string substituted = input;
    std::string::size_type pos = 0;
    while ((pos = substituted.find(sub.from(), pos)) != std::string::npos) {
        substituted.replace(pos, sub.from().size(), sub.to());
        pos += sub.to().size();
    }
    return substituted;
}

template <>
std::string applyOnce(const std::vector<Substitution<std::string>>& seq, const std::string& input)
{
    std::string substituted = input;
    std::string::size_type pos = 0;
    for (const auto& sub : seq) {
        if (sub == Substitution<std::string>::Trivial)
            continue;

        if ((pos = substituted.find(sub.from(), pos)) != std::string::npos) {
            substituted.replace(pos, sub.from().size(), sub.to());
            pos += sub.to().size();
        }
    }
    return substituted;
}

} // psy


text:
Framework 4.5.1

properties {
	$base_directory = Resolve-Path .
	$src_directory = "$base_directory\source"
	$output_directory = "$base_directory\build"
	$dist_directory = "$base_directory\distribution"
	$sln_file = "$src_directory\IdentityServer3.WsFederation.EntityFramework.sln"
	$target_config = "Release"
	$framework_version = "v4.5"
	$xunit_path = "$src_directory\packages\xunit.runners.2.0.0\tools\xunit.console.exe"
	$nuget_path = "$src_directory\.nuget\nuget.exe"

	$buildNumber = 0;
	$version = "2.2.0.0"
	$preRelease = $null
}

task default -depends Clean, CreateNuGetPackage
task appVeyor -depends Clean, CreateNuGetPackage

task Clean {
	rmdir $output_directory -ea SilentlyContinue -recurse
	rmdir $dist_directory -ea SilentlyContinue -recurse
	exec { msbuild /nologo /verbosity:quiet $sln_file /p:Configuration=$target_config /t:Clean }
}

task Compile -depends UpdateVersion {
	exec { msbuild /nologo /verbosity:q $sln_file /p:Configuration=$target_config /p:TargetFrameworkVersion=v4.5 }
	if ($LastExitCode -ne 0) {
        exit $LastExitCode
    }
}

task UpdateVersion {
	$vSplit = $version.Split('.')
	if($vSplit.Length -ne 4)
	{
		throw "Version number is invalid. Must be in the form of 0.0.0.0"
	}
	$major = $vSplit[0]
	$minor = $vSplit[1]
	$patch = $vSplit[2]
	$assemblyFileVersion =  "$major.$minor.$patch.$buildNumber"
	$assemblyVersion = "$major.$minor.0.0"
	$versionAssemblyInfoFile = "$src_directory/VersionAssemblyInfo.cs"
	"using System.Reflection;" > $versionAssemblyInfoFile
	"" >> $versionAssemblyInfoFile
	"[assembly: AssemblyVersion(""$assemblyVersion"")]" >> $versionAssemblyInfoFile
	"[assembly: AssemblyFileVersion(""$assemblyFileVersion"")]" >> $versionAssemblyInfoFile
}

task RunTests -depends Compile {
	$project = "IdentityServer3.WsFederation.EntityFramework.Tests"
	mkdir $output_directory\xunit\$project -ea SilentlyContinue
	.$xunit_path "$src_directory\Tests\UnitTests\bin\Release\$project.dll"
}

task CreateNuGetPackage -depends Compile {
	$vSplit = $version.Split('.')
	if($vSplit.Length -ne 4)
	{
		throw "Version number is invalid. Must be in the form of 0.0.0.0"
	}
	$major = $vSplit[0]
	$minor = $vSplit[1]
	$patch = $vSplit[2]
	$packageVersion =  "$major.$minor.$patch"
	if($preRelease){
		$packageVersion = "$packageVersion-$preRelease"
	}

	if ($buildNumber -ne 0){
		$packageVersion = $packageVersion + "-build" + $buildNumber.ToString().PadLeft(5,'0')
	}

  md $dist_directory
  md $dist_directory\lib
  md $dist_directory\lib\net45

  copy-item $src_directory\IdentityServer3.WsFederation.EntityFramework.nuspec $dist_directory
  copy-item $output_directory\IdentityServer3.WsFederation.EntityFramework.dll $dist_directory\lib\net45
  copy-item $output_directory\IdentityServer3.WsFederation.EntityFramework.pdb $dist_directory\lib\net45

	exec { . $nuget_path pack $dist_directory\IdentityServer3.WsFederation.EntityFramework.nuspec -BasePath $dist_directory -o $dist_directory -version $packageVersion }
}


text:
export class AddressModel {
    name : string = 'John Doe';
    company : string = 'Johnathan Doe Inc.';
    line1 : string = '1 Infinite Loop';
    line2 : string = 'Cupertino, California, US';
    zip : string = '90210';
}


text:
package com.tectonica.jonix.onix3;

import com.tectonica.jonix.common.JPU;
import com.tectonica.jonix.common.OnixElement;
import com.tectonica.jonix.common.codelist.PrintedOnProducts;
import com.tectonica.jonix.common.codelist.RecordSourceTypes;

import java.io.Serializable;

/*
 * NOTE: THIS IS AN AUTO-GENERATED FILE, DO NOT EDIT MANUALLY
 */

/**
 *
Price printed on product

 *

 * An ONIX code indicating whether the price in a <Price> composite is printed on the product. Optional and
 * non-repeating. Omission of this element must not be interpreted as indicating that the price is not printed
 * on the product.
 *

 *

 *

 * Format
 * Fixed length, two digits
 *

 *

 * Codelist
 * List 174
 *

 *

 * Reference name
 * <tt><PrintedOnProduct></tt>
 *

 *

 * Short tag
 * <tt><x301></tt>
 *

 *

 * Cardinality
 * 0…1
 *

 *

 * Example
 * <tt><x301>02</x301></tt> (Price is printed on product)
 *

 *

 *

 * This tag may be included in the following composites:
 *

 *
<{@link Price}>

 *

 *

 * Possible placements within ONIX message:
 *

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ProductSupply} ⯈ {@link SupplyDetail} ⯈ {@link Reissue} ⯈
 * {@link Price} ⯈ {@link PrintedOnProduct}

 *
{@link ONIXMessage} ⯈ {@link Product} ⯈ {@link ProductSupply} ⯈ {@link SupplyDetail} ⯈ {@link Price} ⯈
 * {@link PrintedOnProduct}

 *

 */
public class PrintedOnProduct implements OnixElement<PrintedOnProducts>, Serializable {
    private static final long serialVersionUID = 1L;

    public static final String refname = "PrintedOnProduct";
    public static final String shortname = "x301";

    /////////////////////////////////////////////////////////////////////////////////
    // ATTRIBUTES
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * (type: dt.DateOrDateTime)
     */
    public String datestamp;

    /**
     * (type: dt.NonEmptyString)
     */
    public String sourcename;

    public RecordSourceTypes sourcetype;

    /////////////////////////////////////////////////////////////////////////////////
    // VALUE MEMBER
    /////////////////////////////////////////////////////////////////////////////////

    public PrintedOnProducts value;

    /**
     * Internal API, use the {@link #value()} method or the {@link #value} field instead
     */
    @Override
    public PrintedOnProducts _value() {
        return value;
    }

    /////////////////////////////////////////////////////////////////////////////////
    // SERVICES
    /////////////////////////////////////////////////////////////////////////////////

    private final boolean exists;
    public static final PrintedOnProduct EMPTY = new PrintedOnProduct();

    public PrintedOnProduct() {
        exists = false;
    }

    public PrintedOnProduct(org.w3c.dom.Element element) {
        exists = true;
        datestamp = JPU.getAttribute(element, "datestamp");
        sourcename = JPU.getAttribute(element, "sourcename");
        sourcetype = RecordSourceTypes.byCode(JPU.getAttribute(element, "sourcetype"));

        value = PrintedOnProducts.byCode(JPU.getContentAsString(element));
    }

    /**
     * @return whether this tag (<PrintedOnProduct> or <x301>) is explicitly provided in the ONIX XML
     */
    @Override
    public boolean exists() {
        return exists;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
	"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

	<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

	<title>ActsAsPrice</title>

	<link type="text/css" media="screen" href="rdoc.css" rel="stylesheet" />

ActsAsPrice

This is the API documentation for 'ActsAsPrice'.

Files

README.rdoc

Classes/Modules

ActiveRecord

ActiveRecord::Acts

ActiveRecord::Acts::Price

ActiveRecord::Acts::Price::ClassMethods

ActsAsPriceHelper

Methods

::included — ActiveRecord::Acts::Price

#acts_as_price — ActiveRecord::Acts::Price::ClassMethods

#columns_in_cents — ActsAsPriceHelper

#columns_in_doubles — ActsAsPriceHelper

#test_acts_as_price_methods — ActsAsPriceHelper

#test_setter_in_cents — ActsAsPriceHelper

#test_setter_in_doubles — ActsAsPriceHelper

[Validate]

Generated with the Darkfish
			Rdoc Generator 1.1.6.


text:
package translator

import (
	"fmt"
	"go/token"
	"strings"

	"modernc.org/cc"
	"modernc.org/xc"
)

func (t *Translator) walkTranslationUnit(unit *cc.TranslationUnit) {
	t.fileScope = unit.Declarations
	for unit != nil {
		t.walkExternalDeclaration(unit.ExternalDeclaration)
		unit = unit.TranslationUnit
	}
}

func (t *Translator) walkExternalDeclaration(d *cc.ExternalDeclaration) {
	if t.IsTokenIgnored(d.Pos()) {
		return
	}
	switch d.Case {
	case 0: // FunctionDefinition
		var decl *CDecl
		if declr := d.FunctionDefinition.Declarator; declr != nil {
			decl = t.declarator(declr)
			t.registerTagsOf(decl)
		} else {
			return
		}
		if decl.IsTypedef {
			t.typedefs = append(t.typedefs, decl)
			t.typedefsSet[decl.Name] = struct{}{}
			return
		}
		t.declares = append(t.declares, decl)
	case 1: // Declaration
		declares := t.walkDeclaration(d.Declaration)
		for _, decl := range declares {
			if decl.IsTypedef {
				t.typedefs = append(t.typedefs, decl)
				t.typedefsSet[decl.Name] = struct{}{}
				continue
			}
			t.declares = append(t.declares, decl)
		}
	}
}

func (t *Translator) walkDeclaration(d *cc.Declaration) (declared []*CDecl) {
	if t.IsTokenIgnored(d.Pos()) {
		return
	}
	if d.InitDeclaratorListOpt != nil {
		list := d.InitDeclaratorListOpt.InitDeclaratorList
		for list != nil {
			decl := t.declarator(list.InitDeclarator.Declarator)
			init := list.InitDeclarator.Initializer
			if init != nil && init.Expression != nil {
				decl.Value = init.Expression.Value
				decl.Expression = blessName(init.Expression.Token.S())
			}
			t.registerTagsOf(decl)
			declared = append(declared, decl)
			if init != nil {
				t.valueMap[decl.Name] = decl.Value
				t.exprMap[decl.Name] = decl.Expression
			}
			list = list.InitDeclaratorList
		}
	} else if declr := d.Declarator(); declr != nil {
		decl := t.declarator(declr)
		t.registerTagsOf(decl)
		declared = append(declared, decl)
	}
	return
}

func (t *Translator) declarator(d *cc.Declarator) *CDecl {
	specifier := d.RawSpecifier()
	decl := &CDecl{
		Spec:      t.typeSpec(d.Type, 0, false),
		Name:      identifierOf(d.DirectDeclarator),
		IsTypedef: specifier.IsTypedef(),
		IsStatic:  specifier.IsStatic(),
		Pos:       d.Pos(),
	}
	return decl
}

func (t *Translator) getStructTag(typ cc.Type) (tag string) {
	b := t.fileScope.Lookup(cc.NSTags, typ.Tag())
	switch v := b.Node.(type) {
	case *cc.StructOrUnionSpecifier:
		if v.IdentifierOpt != nil {
			return blessName(v.IdentifierOpt.Token.S())
		}
	case xc.Token:
		return blessName(v.S())
	}
	return
}

func (t *Translator) enumSpec(base *CTypeSpec, typ cc.Type) *CEnumSpec {
	tag := blessName(xc.Dict.S(typ.Tag()))
	spec := &CEnumSpec{
		Tag:      tag,
		Pointers: base.Pointers,
		OuterArr: base.OuterArr,
		InnerArr: base.InnerArr,
	}
	list := typ.EnumeratorList()
	for _, en := range list {
		name := blessName(en.DefTok.S())
		m := &CDecl{
			Name: name,
			Pos:  en.DefTok.Pos(),
		}
		switch {
		case en.Value == nil:
			panic("value cannot be nil in enum")
		case t.constRules[ConstEnum] == ConstCGOAlias:
			m.Expression = fmt.Sprintf("C.%s", name)
		case t.constRules[ConstEnum] == ConstExpand:
			srcParts := make([]string, 0, len(en.Tokens))
			exprParts := make([]string, 0, len(en.Tokens))
			valid := true

			// TODO: some state machine
			needsTypecast := false
			typecastValue := false
			typecastValueParens := 0

			for _, token := range en.Tokens {
				src := cc.TokSrc(token)
				srcParts = append(srcParts, src)
				switch token.Rune {
				case cc.IDENTIFIER:
					exprParts = append(exprParts, string(t.TransformName(TargetConst, src, true)))
				default:
					// TODO: state machine
					const (
						lparen = rune(40)
						rparen = rune(41)
					)
					switch {
					case needsTypecast && token.Rune == rparen:
						typecastValue = true
						needsTypecast = false
						exprParts = append(exprParts, src+"(")
					case typecastValue && token.Rune == lparen:
						typecastValueParens++
					case typecastValue && token.Rune == rparen:
						if typecastValueParens == 0 {
							typecastValue = false
							exprParts = append(exprParts, ")"+src)
						} else {
							typecastValueParens--
						}
					default:
						// somewhere in the world a helpless kitten died because of this
						if token.Rune == '~' {
							src = "^"
						}
						if runes := []rune(src); len(runes) > 0 && isNumeric(runes) {
							// TODO(xlab): better const handling
							src = readNumeric(runes)
						}
						exprParts = append(exprParts, src)
					}
				}
				if !valid {
					break
				}
			}
			if typecastValue {
				// still in typecast value, need to close paren
				exprParts = append(exprParts, ")")
				typecastValue = false
			}

			if len(exprParts) > 0 {
				m.Expression = strings.Join(exprParts, " ")
			} else {
				m.Value = en.Value
			}
			m.Src = strings.Join(srcParts, " ")
		default:
			m.Value = en.Value
		}
		m.Spec = spec.PromoteType(en.Value)
		spec.Members = append(spec.Members, m)
		t.valueMap[m.Name] = en.Value
		t.exprMap[m.Name] = m.Expression
	}

	return spec
}

func (t *Translator) walkEnumerator(e *cc.Enumerator) *CDecl {
	decl := &CDecl{
		Name: blessName(e.EnumerationConstant.Token.S()),
	}
	switch e.Case {
	case 0: // EnumerationConstant
	case 1: // EnumerationConstant '=' ConstantExpression
		decl.Value = e.ConstantExpression.Value
		decl.Expression = string(e.ConstantExpression.Expression.Token.S())
	}
	return decl
}

const maxDeepLevel = 3

func (t *Translator) structSpec(base *CTypeSpec, typ cc.Type, deep int) *CStructSpec {
	tag := t.getStructTag(typ)
	spec := &CStructSpec{
		Tag:      tag,
		IsUnion:  typ.Kind() == cc.Union,
		Pointers: base.Pointers,
		OuterArr: base.OuterArr,
		InnerArr: base.InnerArr,
	}
	if deep > maxDeepLevel {
		return spec
	}
	members, _ := typ.Members()
	for i, m := range members {
		var pos token.Pos
		if m.Declarator != nil {
			pos = m.Declarator.Pos()
		}
		spec.Members = append(spec.Members, &CDecl{
			Name: memberName(i, m),
			Spec: t.typeSpec(m.Type, deep+1, false),
			Pos:  pos,
		})
	}
	return spec
}

func (t *Translator) functionSpec(base *CTypeSpec, typ cc.Type, deep int) *CFunctionSpec {
	spec := &CFunctionSpec{
		Pointers: base.Pointers,
	}
	if deep > 2 { // a function inside params of another function
		spec.Raw = typedefNameOf(typ)
	} else {
		spec.Raw = identifierOf(typ.Declarator().DirectDeclarator)
	}
	if deep > maxDeepLevel {
		return spec
	}
	if ret := typ.Result(); ret != nil && ret.Kind() != cc.Void {
		spec.Return = t.typeSpec(ret, deep+1, true)
	}
	params, _ := typ.Parameters()
	for i, p := range params {
		spec.Params = append(spec.Params, &CDecl{
			Name: paramName(i, p),
			Spec: t.typeSpec(p.Type, deep+1, false),
			Pos:  p.Declarator.Pos(),
		})
	}
	return spec
}

func (t *Translator) typeSpec(typ cc.Type, deep int, isRet bool) CType {
	spec := &CTypeSpec{
		Const: typ.Specifier().IsConst(),
	}
	if !isRet {
		spec.Raw = typedefNameOf(typ)
	}

	for typ.Kind() == cc.Array {
		size := typ.Elements()
		typ = typ.Element()
		if size >= 0 {
			spec.AddOuterArr(uint64(size))
		}
	}
	var isVoidPtr bool
	for typ.Kind() == cc.Ptr {
		if next := typ.Element(); next.Kind() == cc.Void {
			isVoidPtr = true
			spec.Base = "void*"
			break
		}
		typ = typ.Element()
		spec.Pointers++
	}
	for typ.Kind() == cc.Array {
		size := typ.Elements()
		typ = typ.Element()
		if size >= 0 {
			spec.AddInnerArr(uint64(size))
		}
	}
	if isVoidPtr {
		return spec
	}

	switch typ.Kind() {
	case cc.Void:
		spec.Base = "void"
	case cc.Char:
		spec.Base = "char"
	case cc.SChar:
		spec.Base = "char"
		spec.Signed = true
	case cc.UChar:
		spec.Base = "char"
		spec.Unsigned = true
	case cc.Short:
		spec.Base = "int"
		spec.Short = true
	case cc.UShort:
		spec.Base = "int"
		spec.Short = true
		spec.Unsigned = true
	case cc.Int:
		spec.Base = "int"
	case cc.UInt:
		spec.Base = "int"
		spec.Unsigned = true
	case cc.Long:
		spec.Base = "int"
		spec.Long = true
	case cc.ULong:
		spec.Base = "int"
		spec.Long = true
		spec.Unsigned = true
	case cc.LongLong:
		spec.Base = "long"
		spec.Long = true
	case cc.ULongLong:
		spec.Base = "long"
		spec.Long = true
		spec.Unsigned = true
	case cc.Float:
		spec.Base = "float"
	case cc.Double:
		spec.Base = "double"
	case cc.LongDouble:
		spec.Base = "double"
		spec.Long = true
	case cc.Bool:
		spec.Base = "_Bool"
	case cc.FloatComplex:
		spec.Base = "complexfloat"
		spec.Complex = true
	case cc.DoubleComplex:
		spec.Base = "complexdouble"
		spec.Complex = true
	case cc.LongDoubleComplex:
		spec.Base = "complexdouble"
		spec.Long = true
		spec.Complex = true
	case cc.Enum:
		s := t.enumSpec(spec, typ)
		if !isRet {
			s.Typedef = typedefNameOf(typ)
		}
		return s
	case cc.Union:
		return &CStructSpec{
			Tag:      t.getStructTag(typ),
			IsUnion:  true,
			Pointers: spec.Pointers,
			OuterArr: spec.OuterArr,
			InnerArr: spec.InnerArr,
			Typedef:  typedefNameOf(typ),
		}
	case cc.Struct:
		s := t.structSpec(spec, typ, deep+1)
		if !isRet {
			s.Typedef = typedefNameOf(typ)
		}
		return s
	case cc.Function:
		s := t.functionSpec(spec, typ, deep+1)
		if !isRet && !typ.Specifier().IsTypedef() {
			s.Typedef = typedefNameOf(typ)
			retTyp := typ.Result().RawDeclarator().Type
			retTypedef := typedefNameOf(retTyp)
			if s.Return != nil {
				s.Return.SetRaw(retTypedef)
			}
		}
		return s
	default:
		panic("unknown type " + typ.String())
	}

	return spec
}

func paramName(n int, p cc.Parameter) string {
	if p.Name == 0 {
		return fmt.Sprintf("arg%d", n)
	}
	return blessName(xc.Dict.S(p.Name))
}

func memberName(n int, m cc.Member) string {
	if m.Name == 0 {
		return fmt.Sprintf("field%d", n)
	}
	return blessName(xc.Dict.S(m.Name))
}

func typedefNameOf(typ cc.Type) string {
	rawSpec := typ.Declarator().RawSpecifier()
	if name := rawSpec.TypedefName(); name > 0 {
		return blessName(xc.Dict.S(name))
	} else if rawSpec.IsTypedef() {
		return identifierOf(typ.Declarator().DirectDeclarator)
	}
	return ""
}

func identifierOf(dd *cc.DirectDeclarator) string {
	switch dd.Case {
	case 0: // IDENTIFIER
		if dd.Token.Val == 0 {
			return ""
		}
		return blessName(dd.Token.S())
	case 1: // '(' Declarator ')'
		return identifierOf(dd.Declarator.DirectDeclarator)
	default:
		//	DirectDeclarator '[' TypeQualifierListOpt ExpressionOpt ']'
		//	DirectDeclarator '[' "static" TypeQualifierListOpt Expression ']'
		//	DirectDeclarator '[' TypeQualifierList "static" Expression ']'
		//	DirectDeclarator '[' TypeQualifierListOpt '*' ']'
		//	DirectDeclarator '(' ParameterTypeList ')'
		//	DirectDeclarator '(' IdentifierListOpt ')'
		return identifierOf(dd.DirectDeclarator)
	}
}


text:
## TinyCore.js / Extensions

### AMD

#### Features

- Wrapper over [require.js](http://requirejs.org).
- Provides async modules loading using the [Asynchronous Module Definition](https://github.com/amdjs/amdjs-api/wiki/AMD) format.
- Less than 1Kb minified + 15Kb for require.js.

#### TinyCore.AMD API

```js
TinyCore.AMD.config( settings )
TinyCore.AMD.define( moduleName, dependencies, creatorFunction )
TinyCore.AMD.require( resourcesNames, callback )
TinyCore.AMD.requireAndStart( modulesData, callback )
TinyCore.AMD.setErrorHandler( errorHandler )
```

#### Examples

An example from "demos/todolist/amd/index.html" :

**app.js :**
```js
TinyCore.AMD.config( {
	require : {
		// see http://requirejs.org/docs/api.html#config
		baseUrl : 'modules',
		paths : {
			'tools' : '../tools'
		}
	}
} );

TinyCore.AMD.requireAndStart( [ 'todo_form_add', 'todo_list' ], function ( aModulesData )
{
	console.info( aModulesData.length+' module(s) loaded:', aModulesData );
} );
```

**todo_form_add.js :**
```js
TinyCore.AMD.define( 'todo_form_add', ['tools/mediator', 'tools/events'], function ( mediator, events )
{
	return { /* ... */ };
} );
```

**todo_list.js :**
```js
TinyCore.AMD.define( 'todo_list', ['tools/mediator', 'tools/dom', 'tools/events'], function ( mediator, dom, events )
{
	return { /* ... */ };
} );
```

### AMD with DOM boot

#### Features

- Supports a declarative approach : simply by adding the proper "data-" attribute in the markup, modules can be attached to any DOM element. Modules can then be loaded and started from the declarations found in the DOM, on demand.
- Lazy loading based on strategies : by adding the proper "data-" attribute, strategies can be declared for deferring the loading of modules.
- 3 types of strategies are supported : event-based (when a given event occurs on the element where the module is attached), time-based (after xxx milliseconds), distance-based (when the distance between the mouse pointer and the DOM element is less than yyy pixels).
- Loading strategies can be combined (e.g.: event+timer).
- Around 3Kb minified + 15Kb for require.js.

#### Extended TinyCore.AMD API

```js
// existing
TinyCore.AMD.config( settings )
TinyCore.AMD.define( moduleName, dependencies, creatorFunction )
TinyCore.AMD.require( resourcesNames, callback )
TinyCore.AMD.requireAndStart( modulesData, callback )
TinyCore.AMD.setErrorHandler( errorHandler )

// extended
TinyCore.AMD.domBoot( rootNode, callback )
```

#### Examples

See the demos in the "demos/todolist/amd" folder :

- "demos/todolist/amd/index-domboot.html" : declarative approach using "data-" attributes in the markup, without deferred loading strategies.
- "demos/todolist/amd/index-deferred" : same as before, but with several deferred loading strategies.

An example from "demos/todolist/amd/index-deferred.html" :

**app.js :**
```js
TinyCore.AMD.config( {
	require : {
		// see http://requirejs.org/docs/api.html#config
		baseUrl : 'modules',
		paths : {
			'tools' : '../tools'
		}
	}
	domBoot : {
		// node names to ignore when scanning the DOM (must be in capital letters)
		nodesIgnored : { H1 : true, LI : true, A : true }
	}
} );

TinyCore.AMD.domBoot( function ( aModulesData )
{
	console.info( 'DOM boot ok. '+aModulesData.length+' module(s) loaded:', aModulesData );
} );
```

**app.html :**
```html
(...)
<body>
	<div id="container" data-tc-modules="todo_storage" data-tc-defer="time:5000">
		<h1>A todo list (AMD deferred load)</h1>
		<form id="todo-form-add" class="todo-form">
			<input id="add-input" class="todo-input" placeholder="Enter your comma-separated todos..." data-tc-modules='todo_form_add' data-tc-defer="event:click" />
		</form>
		<form id="search-form" class="todo-form">
			<input id="search-input" class="todo-input" placeholder="Quick search..." data-tc-modules="todo_form_search" data-tc-defer="distance:50;time:10000" />
			<a title="reset" href="#" id="search-reset"></a>
		</form>
		<span id="summary" data-tc-modules="todo_summary" data-tc-defer="time:1000">
			<span id="count-done"></span>/<span id="count-total"></span> completed - <a href="#" id="clear-completed" class="clear">clear completed</a> - <a href="#" id="clear-list" class="clear">clear all</a>
		</span>
		<ul id="todo-list" data-tc-modules="todo_list" data-tc-defer="time:1000">
			<li id="list-header">
				<input type="checkbox" class="todo-check-all" id="todo-check-all" />
				<span class="label">Name</span>
			</li>
		</ul>
	</div>
</body>
(...)
```

When calling `TinyCore.AMD.domBoot`, the DOM is scanned for finding modules declarations. The following modules are found and are started as follows :

- "todo_storage", loaded after 5s
- "todo_form_add", loaded when the user will click on the "#add-input" element
- "todo_form_search", loaded when the mouse pointer is closer than 50px or after 10s
- "todo_summary" and "todo_list", loaded after 1s

Without any deferred strategies declared, modules are loaded directly.


text:
angular.module("congo")
.constant("sprUrl", "http://ec2-34-193-194-23.compute-1.amazonaws.com/Congo-Logic-Api/Api/SingleProduct/")
.constant("carUrl", "http://ec2-34-193-194-23.compute-1.amazonaws.com/Congo-Logic-Api/Api/Cart/")
.controller("productCtrl", function ($scope, $http, $stateParams, $state, sprUrl, carUrl)
{
    $scope.data.CurrentProduct = "";

    var newUrl = sprUrl+$stateParams.ProductID;

    $http.get(newUrl, {responseType:"json"})
        .success(function (data) {
            $scope.data.CurrentProduct = data;
        })
        .error(function (error) {
            $scope.data.CurrentProduct = error;
        });

    $scope.addToCart = function () {
        if(getCookie("AccountID") != "" && $stateParams.ProductID != null)
        {
            var cart = {
                CustomerID: getCookie("AccountID"),
                ProductID: $stateParams.ProductID,
                CartID: getCookie("AccountID")
            };

            console.log(cart);

            $http.post(carUrl, JSON.stringify(cart)).then(function (res) {
                    if(res.data.success)
                    {
                        $state.go("cart");
                    }
                }, function (err) {

                });
        }
    }
});


text:
namespace Fade { namespace Resources {

class CResourceImporterHub : public IResourceImporterHub
{
public:
	virtual ~CResourceImporterHub() override;

	virtual bool ImportResource(std::string a_FilePath);

	virtual void RegisterImporter(IResourceImporter* a_Importer);

private:

};

} }


text:
/** @author Jia Pan */

#ifndef FCL_COLLISIONRESULT_H
#define FCL_COLLISIONRESULT_H

#include <set>
#include <vector>
#include "fcl/common/types.h"
#include "fcl/narrowphase/contact.h"
#include "fcl/narrowphase/cost_source.h"

namespace fcl
{

/// @brief collision result
template <typename S>
struct CollisionResult
{
private:
  /// @brief contact information
  std::vector<Contact<S>> contacts;

  /// @brief cost sources
  std::set<CostSource<S>> cost_sources;

public:
  Vector3<S> cached_gjk_guess;

public:
  CollisionResult();

  /// @brief add one contact into result structure
  void addContact(const Contact<S>& c);

  /// @brief add one cost source into result structure
  void addCostSource(const CostSource<S>& c, std::size_t num_max_cost_sources);

  /// @brief return binary collision result
  bool isCollision() const;

  /// @brief number of contacts found
  size_t numContacts() const;

  /// @brief number of cost sources found
  size_t numCostSources() const;

  /// @brief get the i-th contact calculated
  const Contact<S>& getContact(size_t i) const;

  /// @brief get all the contacts
  void getContacts(std::vector<Contact<S>>& contacts_);

  /// @brief get all the cost sources
  void getCostSources(std::vector<CostSource<S>>& cost_sources_);

  /// @brief clear the results obtained
  void clear();
};

using CollisionResultf = CollisionResult<float>;
using CollisionResultd = CollisionResult<double>;

} // namespace fcl

#include "fcl/narrowphase/collision_result-inl.h"

#endif


text:
module ScoreboardService
  class << self
    def update(with:, type: :update)
      case with
      when CircleCheckScore, ManeuverParticipant, OnboardJudging, QuizScore
        update_object with
      when Participant
        update_participant with, type
      end
    end

    private

    def update_object(object)
      channels[object.class].broadcast_to 'update', object
    end

    def update_participant(participant, type)
      ParticipantsChannel.broadcast_to type,
                                       event: type, participant: participant
    end

    def channels
      {
        CircleCheckScore => CircleCheckScoresChannel,
        ManeuverParticipant => ManeuverParticipantsChannel,
        OnboardJudging => OnboardJudgingsChannel,
        Participant => ParticipantsChannel,
        QuizScore => QuizScoresChannel
      }
    end
  end
end


text:
package org.ovirt.engine.core.common.queries;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

import org.ovirt.engine.core.compat.Guid;

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "GetAllVmSnapshotsByDriveParameters")
@Deprecated
public class GetAllVmSnapshotsByDriveParameters extends VdcQueryParametersBase {
    private static final long serialVersionUID = -3768508134295864787L;

    public GetAllVmSnapshotsByDriveParameters(Guid id, String drive) {
        _id = id;
        _drive = drive;
    }

    @XmlElement(name = "Id")
    private Guid _id = new Guid();
    @XmlElement(name = "Drive")
    private String _drive;

    public Guid getId() {
        return _id;
    }

    public String getDrive() {
        return _drive;
    }

    @Override
    public RegisterableQueryReturnDataType GetReturnedDataTypeByVdcQueryType(VdcQueryType queryType) {
        return RegisterableQueryReturnDataType.UNDEFINED;
    }

    public GetAllVmSnapshotsByDriveParameters() {
    }
}


text:
app.shell = (function () {
    var
      configMap = {
        anchor_schema_map : {
            chat : { opened : true, closed : true }
        },
        resize_interval : 200,
        main_html : String() +
          '
' +
            '

' +
            '

' +
            '

' +
          '
' +
          '
' +
            '

' +
            '

' +
          '
' +
          '

' +
          '

',
      },
      stateMap = {
          $container : undefined,
          anchor_map : {},
          resize_idto : undefined
      },
      jqueryMap = {},
      setJqueryMap, initModule, copyAnchorMap, changeAnchorPart, onHasChange, onResize, setChatAnchor;

      copyAnchorMap = function () {
          return $.extend( true, {}, stateMap.anchor_map );
      };

      setJqueryMap = function () {
          var $container = stateMap.$container;
          jqueryMap = {
              $container : $container
          };
      };

      changeAnchorPart = function ( arg_map ) {
          var
            anchor_map_revise = copyAnchorMap(),
            bool_return = true,
            key_name, key_name_dep;
          KEYVAL:
          for ( key_name in arg_map ) {
              if (arg_map.hasOwnProperty( key_name ) ) {
                  if ( key_name.indexOf( '_' ) === 0 ) {
                      continue KEYVAL;
                  }

                  anchor_map_revise[key_name] = arg_map[key_name];
                  key_name_dep = '_' + key_name;

                  if ( arg_map[key_name_dep] ) {
                      anchor_map_revise[key_name_dep] = arg_map[key_name_dep];
                  }
                  else {
                      delete anchor_map_revise[key_name_dep];
                      delete anchor_map_revise['_s' + key_name_dep];
                  }
              }
          }

          try {
              $.uriAnchor.setAnchor( anchor_map_revise );
          }
          catch ( error ) {
              $.uriAnchor.setAnchor( stateMap.anchor_map, null, true );
              bool_return = false;
          }

          return bool_return;
      };

      onHasChange = function ( event ) {
          var
            anchor_map_previous = copyAnchorMap(),
            is_ok = true,
            anchor_map_proposed, _s_chat_previous, _s_chat_proposed, s_chat_proposed;

          try {
              anchor_map_proposed = $.uriAnchor.makeAnchorMap();
          }
          catch ( error ) {
              $.uriAnchor.setAnchor( anchor_map_proposed, null, true );
              return false;
          }
          stateMap.anchor_map = anchor_map_proposed;

          _s_chat_previous = anchor_map_previous._s_chat;
          _s_chat_proposed = anchor_map_proposed._s_chat;

          if ( ! anchor_map_previous || _s_chat_previous !== _s_chat_proposed ) {
              s_chat_proposed = anchor_map_proposed.chat;
              switch ( s_chat_proposed ) {
                  case 'opened' :
                    is_ok = app.chat.setSliderPosition( 'opened' );
                  break;
                  case 'closed' :
                    is_ok = app.chat.setSliderPosition( 'closed' );
                  break;
                  default :
                    app.chat.setSliderPosition( 'closed' );
                    delete anchor_map_proposed.chat;
                    $.uriAnchor.setAnchor( anchor_map_proposed, null, true );
              }
          }

          if ( ! is_ok ) {
            if ( anchor_map_previous ) {
                $.uriAnchor.setAnchor( anchor_map_previous, null, true );
                stateMap.anchor_map = anchor_map_previous;
            }
            else {
                delete anchor_map_proposed.chat;
                $.uriAnchor.setAnchor( anchor_map_proposed, null, true );
            }
          }

          return false;
      };

      onResize = function (){
        if ( stateMap.resize_idto ){ return true; }

        app.chat.handleResize();
        stateMap.resize_idto = setTimeout(
        function (){ stateMap.resize_idto = undefined; },
        configMap.resize_interval
        );

        return true;
    };

      setChatAnchor = function ( position_type ) {
          return changeAnchorPart( { chat : position_type } );
      };

      initModule = function ( $container ) {
          stateMap.$container = $container;
          $container.html( configMap.main_html );
          setJqueryMap();

          $.uriAnchor.configModule({
            schema_map : configMap.anchor_schema_map
          });

          app.chat.configModule({
            set_chat_anchor : setChatAnchor,
            chat_model      : app.model.chat,
            people_model    : app.model.people
          });
          app.chat.initModule( jqueryMap.$container );

          $(window)
            .bind( 'resize', onResize )
              .bind( 'hashchange', onHasChange )
            .trigger( 'hashchange' );
      };

      return { initModule : initModule };
} () );


text:
package momijikawa.p2pscalaproto

import akka.actor._
import akka.event.Logging

/**
 * ノードに定期的に安定化の命令を発します。
 * @param chord 命令を受けるべきノードの[[akka.actor.ActorRef]]
 * @param message 安定化のトリガとなるメッセージ。
 * @param executionContext 文脈
 */
class Stabilizer(chord: ActorRef, message: chordMessage, implicit val executionContext: akka.dispatch.MessageDispatcher) extends Actor {

  import scala.concurrent.duration._
  import akka.agent.Agent

  var scheduler: Cancellable = _
  val log = Logging(context.system, this)
  val isStarted = Agent[Boolean](false)(executionContext)

  /**
   * メッセージを受けると安定化タイマ開始もしくは停止のいずれかの処理を行います。
   */
  def receive = {
    case m: stabilizeMessage =>
      m match {
        case StartStabilize => start()
        case StopStabilize => stop()
        case StabilizeStatus => sender ! isStarted()
      }
    case _ => unhandled("unknown message")
  }

  /**
   * 安定化のスケジューリングを行います。
   * 既にスケジューリングが行なわれているときは何もしません。
   * スケジュール後に開始フラグを立てます。
   */
  def start() = {
    //scheduler.cancel()
    isStarted() match {
      case false =>
        log.debug("stabilizer started")
        scheduler = context.system.scheduler.schedule(3 seconds, 5 seconds, chord, message)
        isStarted send true
      case true => // do nothing
    }
  }

  /**
   * 安定化のスケジューリングを停止します。
   * そもそもスケジューリングがないときは何もしません。
   * スケジューリングを中止した後に停止フラグを立てます。
   */
  def stop() = {
    isStarted() match {
      case true =>
        log.debug("going to stop stabilizer")
        scheduler.cancel()
        isStarted send false
      case false => // do nothing
    }
  }

  override def postStop() = {
    log.debug("stabilizer has been terminated")
  }
}


text:
FROM mdillon/postgis:9.4
ENV IMPORT_DATA_DIR=/data/import \
    NATURAL_EARTH_DB=/data/import/natural_earth_vector.sqlite

RUN apt-get update && apt-get install -y --no-install-recommends \
      wget \
      unzip \
      gdal-bin \
      sqlite3 \
    && rm -rf /var/lib/apt/lists/*

RUN mkdir -p $IMPORT_DATA_DIR \
    && wget --quiet http://data.openstreetmapdata.com/water-polygons-split-3857.zip \
    && unzip -oj water-polygons-split-3857.zip -d $IMPORT_DATA_DIR \
    && rm water-polygons-split-3857.zip

RUN wget --quiet http://data.openstreetmapdata.com/simplified-water-polygons-complete-3857.zip \
    && unzip -oj simplified-water-polygons-complete-3857.zip -d $IMPORT_DATA_DIR \
    && rm simplified-water-polygons-complete-3857.zip

COPY ./clean-natural-earth.sh /usr/src/app/
RUN wget --quiet http://naciscdn.org/naturalearth/packages/natural_earth_vector.sqlite.zip \
    && unzip -oj natural_earth_vector.sqlite.zip -d /data/import \
    && rm natural_earth_vector.sqlite.zip \
    && ./usr/src/app/clean-natural-earth.sh

COPY . /usr/src/app
WORKDIR /usr/src/app

CMD ["./import.sh"]


text:
"""
Calculate the average SNP frequency at all residues in the alignment. Assumes the alignment is in fasta format!
"""

import os
import sys
import argparse

from roblib import sequences

def average_snp_frequency(seqs, min_num_reads=1):
    """
    Calculate the average SNP frequency at sites where there is a SNP across the alignment. At each position
    SNPs must be in >= min_num_reads to be included

    :param sequences: An array of just the sequences. All elements in the array should be the same length (ie.
        sequences should be padded with -)
    :type sequences: list
    :param min_num_reads:minimum number of reads for a SNP to be in to be included
    :type min_num_reads: int
    :return:
    :rtype:
    """

    allsnps = []
    sites = 0

    bases = {'A', 'T', 'G', 'C', 'a', 't', 'g', 'c',}

    for i in range(len(seqs[0])):
        counts = {}
        for s in seqs:
            if s[i] not in bases:
                continue
            counts[s[i]] = counts.get(s[i], 0) + 1
        snps = 0
        for c in counts:
            if counts[c] >= min_num_reads:
                snps += 1
        if snps > 1:
            allsnps.append(snps)
            sites += 1

    sys.stdout.write("Alignment length: {} Informative sites: {} ".format(len(seqs[0]), sites))
    if sites == 0:
        # if there are no informative sites everything has the same sequence so we have one SNP!
        print("Average number of SNPs: 1")
    else:
       print("Average number of SNPs: {}".format(1.0 * sum(allsnps)/len(allsnps)))

def average_genotype_frequency(seqs, kmer=10, min_num_reads=1):
    """
    Calculate the average genotype frequency using k-mer profiles. At each position
    genotypes must be in >= min_num_reads to be included

    :param kmer: The length of the sequence to use to calculate the genotypes
    :type kmer: int
    :param sequences: An array of just the sequences. All elements in the array should be the same length (ie.
        sequences should be padded with -)
    :type sequences: list
    :param min_num_reads:minimum number of reads for a SNP to be in to be included
    :type min_num_reads: int
    :return:
    :rtype:
    """

    all_genotypes = []
    sites = 0

    bases = {'A', 'T', 'G', 'C', 'a', 't', 'g', 'c', }

    for i in range(len(seqs[0])-kmer):
        counts = {}
        for s in seqs:
            kseq = s[i:i+kmer]
            keep_kmer = True
            for k in kseq:
                if k not in bases:
                    keep_kmer = False
            if not keep_kmer:
                continue
            counts[kseq] = counts.get(kseq, 0) + 1
        snps = 0
        for c in counts:
            if counts[c] >= min_num_reads:
                snps += 1
        if snps > 0:
            all_genotypes.append(snps)
            sites += 1

    sys.stdout.write("Alignment length: {} Informative kmers: {} ".format(len(seqs[0]), sites))
    if sites == 0:
        print("Average number of genotypes: 1")
    else:
        print("Average number of genotypes: {}".format(1.0 * sum(all_genotypes) / len(all_genotypes)))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Calculate the average number of SNPs at informative sites")
    parser.add_argument('-a', help='Alignment file in fasta format')
    parser.add_argument('-s', help='Count SNPs', action='store_true')
    parser.add_argument('-g', help='Count genotypes', action='store_true')
    parser.add_argument('-k', help='k-mer size to estimate genotypes. Default=10', default=10, type=int)
    parser.add_argument('-m', help='minimum number of reads for site to be informative', default=2, type=int)
    args = parser.parse_args()

    seqids = []
    seqs = []

    for rid, seq in sequences.stream_fasta(args.a):
        seqids.append(rid)
        seqs.append(seq)

    if args.s:
        average_snp_frequency(seqs, min_num_reads=args.m)
    if args.g:
        average_genotype_frequency(seqs, kmer=args.k, min_num_reads=args.m)