text:
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.statements import *
from indra.tools.incremental_model import IncrementalModel

stmts = [Complex([Agent('MAPK1'), Agent('MAPK3')]),
         Complex([Agent('MAPK3'), Agent('MAP2K1')])]
stmts2 = [Phosphorylation(None, Agent('MAPK3', db_refs={'UP': '123'}))]
stmt3 = Phosphorylation(None, Agent('BRAF', db_refs={'HGNC': '1097',
                                                     'UP': 'P15056'}))
stmt4 = Phosphorylation(None, Agent('RAF', db_refs={'FPLX': 'RAF'}))
stmt5 = Phosphorylation(Agent('X'), Agent('RAF', db_refs={'FPLX': 'RAF'}))

def test_add_stmts_blank():
    im = IncrementalModel()
    im.add_statements('12345', stmts)
    assert len(im.get_statements()) == 2
    im.preassemble()
    assert len(im.assembled_stmts) == 2

def test_add_stmts_blank_nofilter():
    im = IncrementalModel()
    im.add_statements('12345', stmts)
    im.preassemble(filters=None)
    assert len(im.assembled_stmts) == 2

def test_add_stmts_blank_emptyfilter():
    im = IncrementalModel()
    im.add_statements('12345', stmts)
    im.preassemble(filters=[])
    assert len(im.assembled_stmts) == 2

def test_add_stmts_blank_noprior():
    im = IncrementalModel()
    im.add_statements('12345', stmts)
    im.preassemble(filters=['prior_one'])
    assert len(im.assembled_stmts) == 2

def test_add_stmts_blank_noprior2():
    im = IncrementalModel()
    im.add_statements('12345', stmts)
    im.preassemble(filters=['prior_all'])
    assert len(im.assembled_stmts) == 2

def test_add_stmts_prior_one():
    im = IncrementalModel()
    im.stmts['prior'] = [stmts[0]]
    im.prior_genes = ['MAPK1', 'MAPK3']
    im.add_statements('12345', [stmts[1]])
    im.preassemble(filters=['prior_one'])
    assert len(im.assembled_stmts) == 2

def test_add_stmts_prior_all():
    im = IncrementalModel()
    im.stmts['prior'] = [stmts[0]]
    im.prior_genes = ['MAPK1', 'MAPK3']
    im.add_statements('12345', [stmts[1]])
    im.preassemble(filters=['prior_all'])
    assert len(im.assembled_stmts) == 1

def test_grounding_not_all():
    im = IncrementalModel()
    stmt = Complex([Agent('A', db_refs={'UP': 'ABCD'}),
                   Agent('B')])
    im.add_statements('12345', [stmt])
    im.preassemble(filters=['grounding'])
    assert len(im.assembled_stmts) == 0

def test_grounding_all():
    im = IncrementalModel()
    stmt = Complex([Agent('A', db_refs={'UP': 'ABCD'}),
                   Agent('B', db_refs={'HGNC': '1234'})])
    im.add_statements('12345', [stmt])
    im.preassemble(filters=['grounding'])
    assert len(im.assembled_stmts) == 1

def test_grounding_none():
    im = IncrementalModel()
    im.add_statements('12345', stmts)
    im.preassemble(filters=['grounding'])
    assert len(im.assembled_stmts) == 0

def test_grounding_none_agent():
    im = IncrementalModel()
    im.add_statements('12345', stmts2)
    im.preassemble(filters=['grounding'])
    assert len(im.assembled_stmts) == 1

def test_human_only():
    im = IncrementalModel()
    stmt1 = Phosphorylation(None, Agent('BRAF', db_refs={'UP': 'P15056'}))
    stmt2 = Phosphorylation(None, Agent('BRAF', db_refs={'UP': 'P28028'}))
    stmt3 = Phosphorylation(None, Agent('BRAF', db_refs={'HGNC': 'BRAF'}))
    stmt4 = Phosphorylation(None, Agent('BRAF', db_refs={}))
    im.add_statements('12345', [stmt1])
    im.preassemble(filters=['human_only'])
    assert len(im.assembled_stmts) == 1
    im.add_statements('12346', [stmt2])
    im.preassemble(filters=['human_only'])
    assert len(im.assembled_stmts) == 1
    im.add_statements('12346', [stmt3])
    im.preassemble(filters=['human_only'])
    assert (len(im.assembled_stmts) == 2)
    im.add_statements('12346', [stmt4])
    im.preassemble(filters=['human_only'])
    assert (len(im.assembled_stmts) == 3)


text: A simple Genetic Algorithm framework useful to solve optimization problems.

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Neptune\Service;

use Neptune\Service\ServiceInterface;
use Neptune\Routing\Router;
use Neptune\Core\Neptune;
use Neptune\Config\ConfigManager;

/**
 * AbstractModule
 *
 * @author Glynn Forrest <me@glynnforrest.com>
 **/
abstract class AbstractModule implements ServiceInterface
{

    protected $route_prefix;

    public function __construct($route_prefix = '')
    {
        $this->route_prefix = $route_prefix;
    }

    /**
     * Set the route prefix for the module. Pass false to disable routing.
     *
     * @param string|bool $route_prefix The prefix
     */
    public function routePrefix($route_prefix)
    {
        $this->route_prefix = $route_prefix;
    }

    /**
     * Load routes for this module.
     *
     * @param Route $router
     * @param Neptune $neptune
     */
    public function loadRoutes(Router $router, Neptune $neptune)
    {
        if ($this->route_prefix !== false) {
            $this->routes($router, $this->route_prefix, $neptune);
        }
    }

    protected function routes(Router $router, $prefix, Neptune $neptune) {
        //add routes in child classes
    }

    /**
     * Load configuration for this module.
     *
     * @param ConfigManager $config
     */
    public function loadConfig(ConfigManager $config)
    {
        $file = $this->getDirectory() . 'config.yml';
        if (file_exists($file)) {
            $config->load($file);
        }
    }

    abstract public function getName();

    public function getNamespace()
    {
        $class = get_class($this);

        return substr($class, 0, strrpos($class, '\\'));
    }

    public function getDirectory()
    {
        $self = new \ReflectionObject($this);

        return dirname($self->getFileName()) . '/';
    }

}


text:
package com.thoughtworks.go.agent;

import com.thoughtworks.go.config.*;
import com.thoughtworks.go.config.materials.MaterialConfigs;
import com.thoughtworks.go.domain.*;
import com.thoughtworks.go.domain.buildcause.BuildCause;
import com.thoughtworks.go.domain.builder.Builder;
import com.thoughtworks.go.helper.BuilderMother;
import com.thoughtworks.go.helper.JobInstanceMother;
import com.thoughtworks.go.remote.AgentIdentifier;
import com.thoughtworks.go.remote.AgentInstruction;
import com.thoughtworks.go.remote.work.BuildAssignment;
import com.thoughtworks.go.remote.work.BuildWork;
import com.thoughtworks.go.remote.work.GoArtifactsManipulatorStub;
import com.thoughtworks.go.server.service.AgentRuntimeInfo;
import com.thoughtworks.go.server.service.UpstreamPipelineResolver;
import com.thoughtworks.go.util.GoConstants;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.work.FakeWork;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

import static com.thoughtworks.go.util.SystemUtil.currentWorkingDirectory;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoMoreInteractions;

public class JobRunnerTest {
    private static final String SERVER_URL = "somewhere-does-not-matter";
    private static final String JOB_PLAN_NAME = "run-ant";
    private JobRunner runner;
    private FakeWork work;
    private List<String> consoleOut;
    private List<Enum> statesAndResult;
    private List<Property> properties;
    private BuildWork buildWork;
    private AgentIdentifier agentIdentifier;
    private UpstreamPipelineResolver resolver;

    public static String withJob(String jobXml) {
        return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                + "<cruise xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
                + " xsi:noNamespaceSchemaLocation=\"cruise-config.xsd\" schemaVersion=\""
                + GoConstants.CONFIG_SCHEMA_VERSION + "\">\n"
                + " <server artifactsdir=\"logs\"></server>"
                + "  <pipelines>\n"
                + "    <pipeline name=\"pipeline1\">\n"
                + "      <materials>\n"
                + "        <svn url=\"foobar\" checkexternals=\"true\" />\n"
                + "      </materials>\n"
                + "      <stage name=\"mingle\">\n"
                + "       <jobs>\n"
                + jobXml
                + "        </jobs>\n"
                + "      </stage>\n"
                + "    </pipeline>\n"
                + "  </pipelines>\n"
                + "  <agents>\n"
                + "    <agent hostname=\"agent1\" ipaddress=\"1.2.3.4\" uuid=\"ywZRuHFIKvw93TssFeWl8g==\" />\n"
                + "  </agents>"
                + "</cruise>";
    }

    @Before
    public void setUp() throws Exception {
        runner = new JobRunner();
        work = new FakeWork();
        consoleOut = new ArrayList<>();
        statesAndResult = new ArrayList<>();
        properties = new ArrayList<>();
        agentIdentifier = new AgentIdentifier("localhost", "127.0.0.1", "uuid");

        new SystemEnvironment().setProperty("serviceUrl", SERVER_URL);
        resolver = mock(UpstreamPipelineResolver.class);
    }

    @After
    public void tearDown() {
        verifyNoMoreInteractions(resolver);
    }

    @Test
    public void shouldDoNothingWhenJobIsNotCancelled() {
        runner.setWork(work);
        runner.handleInstruction(new AgentInstruction(false), new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie", false));
        assertThat(work.getCallCount(), is(0));
    }

    @Test
    public void shouldCancelOncePerJob() {
        runner.setWork(work);
        runner.handleInstruction(new AgentInstruction(true), new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie", false));
        assertThat(work.getCallCount(), is(1));

        runner.handleInstruction(new AgentInstruction(true), new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie", false));
        assertThat(work.getCallCount(), is(1));
    }

    @Test
    public void shouldReturnTrueOnGetJobIsCancelledWhenJobIsCancelled() {
        assertThat(runner.isJobCancelled(), is(false));
        runner.handleInstruction(new AgentInstruction(true), new AgentRuntimeInfo(agentIdentifier, AgentRuntimeStatus.Idle, currentWorkingDirectory(), "cookie", false));
        assertThat(runner.isJobCancelled(), is(true));
    }

    private GoArtifactsManipulatorStub stubPublisher(final List<Property> properties,
                                                     final List<String> consoleOuts) {
        return new GoArtifactsManipulatorStub(properties, consoleOuts);
    }

}


text:
Vagrant is slow, so this gets a cow to read fortune cookies for you
while you wait.

```
$ vagrant up
 _______________________________________
/ Don't you wish you had more energy... \
\ or less ambition?                     /
 ---------------------------------------
        \   ^__^
         \  (oo)\_______
            (__)\       )\/\
                ||----w |
                ||     ||
Bringing machine 'web' up with 'virtualbox' provider...
==> web: Clearing any previously set forwarded ports...
==> web: Clearing any previously set network interfaces...
==> web: Preparing network interfaces based on configuration...
    web: Adapter 1: nat
    web: Adapter 2: hostonly
```

## Installation

You'll need `fortune` and `cowsay`. Then, do:

    $ vagrant plugin install vagrant-cowsay-fortune

## License

MIT, see LICENSE.txt


text:
<!DOCTYPE html>
<html>
    <head>
        <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet' type='text/css'>
    </head>
    <body>
        <script src="https://code.jquery.com/jquery-2.2.3.min.js" crossorigin="anonymous"></script>
    </body>
</html>


text:
//
//  fd.m
//  yiliaotoutiao
//
//  Created by Jason T on 16/9/27.
//  Copyright © 2016年 YLTT. All rights reserved.
//

#import "UIImage+cutCircleImage.h"

@implementation UIImage(cutCircleImage)

//在此之后建议大家尽量不要这么设置, 因为使用图层过量会有卡顿现象, 特别是弄圆角或者阴影会很卡, 如果设置图片圆角我们一般用绘图来做:
/** 设置圆形图片(放到分类中使用) */
- (UIImage *)cutCircleImage {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 获取上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    // 设置圆形
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctr, rect);
    // 裁剪
    CGContextClip(ctr);
    // 将图片画上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

- (UIImage *)setImageSize:(CGSize)size {
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    // 获取上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    // 设置圆形
    CGRect rect = CGRectMake(0, 0, size.width,  size.height);
    CGContextAddEllipseInRect(ctr, rect);
    // 裁剪
//    CGContextClip(ctr);
    // 将图片画上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

@end


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

<TITLE>
DisplayOrderable
</TITLE>

<META NAME="keywords" CONTENT="org.cidrz.webapp.dynasite.valueobject.DisplayOrderable interface">

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

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.zeprs.data

Interface DisplayOrderable

All Known Implementing Classes:
EncounterValue, EncounterValueArchive, FieldEnumeration, FormField, PageItem

public interface DisplayOrderable

Interfaced used for display order sorting. See also
 DisplayOrderComparator

Method Summary

 java.lang.Integer
getDisplayOrder()

 void
setDisplayOrder(java.lang.Integer displayOrder)

Method Detail

getDisplayOrder

java.lang.Integer getDisplayOrder()

setDisplayOrder

void setDisplayOrder(java.lang.Integer displayOrder)

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
layout: post
title: "Personal Config 4 Youtube"
tags: javascript modification youtube en-us
---

## current features
* open your videos always in theater mode;
* disable video annotations automatically

*compatible with new appearance

## changelog
> 2017-08-23 version 0.1
2017-09-01 version 0.2 bug fix
2017-09-08 version 0.3 bug fix

[source code](https://github.com/h01000110/js-scripts/blob/master/personal-config-youtube.user.js)
[install script](https://github.com/h01000110/js-scripts/raw/master/personal-config-youtube.user.js)


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using uhttpsharp.Headers;

namespace uhttpsharp
{
    [DebuggerDisplay("{Method} {OriginalUri,nq}")]
    internal class HttpRequest : IHttpRequest
    {
        private readonly IHttpHeaders _headers;
        private readonly HttpMethods _method;
        private readonly string _protocol;
        private readonly Uri _uri;
        private readonly string[] _requestParameters;
        private readonly IHttpHeaders _queryString;
        private readonly IHttpPost _post;

        public HttpRequest(IHttpHeaders headers, HttpMethods method, string protocol, Uri uri, string[] requestParameters, IHttpHeaders queryString, IHttpPost post)
        {
            _headers = headers;
            _method = method;
            _protocol = protocol;
            _uri = uri;
            _requestParameters = requestParameters;
            _queryString = queryString;
            _post = post;
        }

        public IHttpHeaders Headers
        {
            get { return _headers; }
        }

        public HttpMethods Method
        {
            get { return _method; }
        }

        public string Protocol
        {
            get { return _protocol; }
        }

        public Uri Uri
        {
            get { return _uri; }
        }

        public string[] RequestParameters
        {
            get { return _requestParameters; }
        }

        public IHttpPost Post
        {
            get { return _post; }
        }

        public IHttpHeaders QueryString
        {
            get { return _queryString; }
        }

        internal string OriginalUri
        {
            get
            {
                if (QueryString == null)
                {
                    return Uri.OriginalString;
                }

                return Uri.OriginalString + "?" + QueryString.ToUriData();

            }
        }
    }

    public interface IHttpRequest
    {
        IHttpHeaders Headers { get; }

        HttpMethods Method { get; }

        string Protocol { get; }

        Uri Uri { get; }

        string[] RequestParameters { get; }

        IHttpPost Post {get;}

        IHttpHeaders QueryString { get; }

    }

    public interface IHttpPost
    {

        byte[] Raw {get;}

        IHttpHeaders Parsed {get;}

    }

    public sealed class HttpRequestParameters
    {
        private readonly string[] _params;

        private static readonly char[] Separators = { '/' };

        public HttpRequestParameters(Uri uri)
        {
            var url = uri.OriginalString;
            _params = url.Split(Separators, StringSplitOptions.RemoveEmptyEntries);
        }

        public IList<string> Params
        {
            get { return _params; }
        }
    }
}


text:
package org.cloumon.gruter.oozie.service.external;

public class HadoopCluster {
	String clusterName;

	public HadoopCluster() {
	}

	public String getClusterName() {
		return clusterName;
	}

	public void setClusterName(String clusterName) {
		this.clusterName = clusterName;
	}
}


text:
enum
{
    // show Sunday as the first day of the week (default)
    wxCAL_SUNDAY_FIRST               = 0x0000,

    // show Monday as the first day of the week
    wxCAL_MONDAY_FIRST               = 0x0001,

    // highlight holidays
    wxCAL_SHOW_HOLIDAYS              = 0x0002,

    // disable the year change control, show only the month change one
    // deprecated
    wxCAL_NO_YEAR_CHANGE             = 0x0004,

    // don't allow changing neither month nor year (implies
    // wxCAL_NO_YEAR_CHANGE)
    wxCAL_NO_MONTH_CHANGE            = 0x000c,

    // use MS-style month-selection instead of combo-spin combination
    wxCAL_SEQUENTIAL_MONTH_SELECTION = 0x0010,

    // show the neighbouring weeks in the previous and next month
    wxCAL_SHOW_SURROUNDING_WEEKS     = 0x0020,

    // show week numbers on the left side of the calendar.
    wxCAL_SHOW_WEEK_NUMBERS          = 0x0040
};

// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------

// return values for the HitTest() method
enum wxCalendarHitTestResult
{
    wxCAL_HITTEST_NOWHERE,      // outside of anything
    wxCAL_HITTEST_HEADER,       // on the header (weekdays)
    wxCAL_HITTEST_DAY,          // on a day in the calendar
    wxCAL_HITTEST_INCMONTH,
    wxCAL_HITTEST_DECMONTH,
    wxCAL_HITTEST_SURROUNDING_WEEK,
    wxCAL_HITTEST_WEEK
};

// border types for a date
enum wxCalendarDateBorder
{
    wxCAL_BORDER_NONE,          // no border (default)
    wxCAL_BORDER_SQUARE,        // a rectangular border
    wxCAL_BORDER_ROUND          // a round border
};

// ----------------------------------------------------------------------------
// wxCalendarDateAttr: custom attributes for a calendar date
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_ADV wxCalendarDateAttr
{
public:
    // ctors
    wxCalendarDateAttr(const wxColour& colText = wxNullColour,
                       const wxColour& colBack = wxNullColour,
                       const wxColour& colBorder = wxNullColour,
                       const wxFont& font = wxNullFont,
                       wxCalendarDateBorder border = wxCAL_BORDER_NONE)
        : m_colText(colText), m_colBack(colBack),
          m_colBorder(colBorder), m_font(font)
    {
        Init(border);
    }
    wxCalendarDateAttr(wxCalendarDateBorder border,
                       const wxColour& colBorder = wxNullColour)
        : m_colBorder(colBorder)
    {
        Init(border);
    }

    // setters
    void SetTextColour(const wxColour& colText) { m_colText = colText; }
    void SetBackgroundColour(const wxColour& colBack) { m_colBack = colBack; }
    void SetBorderColour(const wxColour& col) { m_colBorder = col; }
    void SetFont(const wxFont& font) { m_font = font; }
    void SetBorder(wxCalendarDateBorder border) { m_border = border; }
    void SetHoliday(bool holiday) { m_holiday = holiday; }

    // accessors
    bool HasTextColour() const { return m_colText.IsOk(); }
    bool HasBackgroundColour() const { return m_colBack.IsOk(); }
    bool HasBorderColour() const { return m_colBorder.IsOk(); }
    bool HasFont() const { return m_font.IsOk(); }
    bool HasBorder() const { return m_border != wxCAL_BORDER_NONE; }

    bool IsHoliday() const { return m_holiday; }

    const wxColour& GetTextColour() const { return m_colText; }
    const wxColour& GetBackgroundColour() const { return m_colBack; }
    const wxColour& GetBorderColour() const { return m_colBorder; }
    const wxFont& GetFont() const { return m_font; }
    wxCalendarDateBorder GetBorder() const { return m_border; }

    // get or change the "mark" attribute, i.e. the one used for the items
    // marked with wxCalendarCtrl::Mark()
    static const wxCalendarDateAttr& GetMark() { return m_mark; }
    static void SetMark(wxCalendarDateAttr const& m) { m_mark = m; }

protected:
    void Init(wxCalendarDateBorder border = wxCAL_BORDER_NONE)
    {
        m_border = border;
        m_holiday = false;
    }

private:
    static wxCalendarDateAttr m_mark;

    wxColour m_colText,
             m_colBack,
             m_colBorder;
    wxFont   m_font;
    wxCalendarDateBorder m_border;
    bool m_holiday;
};

// ----------------------------------------------------------------------------
// wxCalendarCtrl events
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_FWD_ADV wxCalendarCtrl;

class WXDLLIMPEXP_ADV wxCalendarEvent : public wxDateEvent
{
public:
    wxCalendarEvent() : m_wday(wxDateTime::Inv_WeekDay)  { }
    wxCalendarEvent(wxWindow *win, const wxDateTime& dt, wxEventType type)
        : wxDateEvent(win, dt, type),
          m_wday(wxDateTime::Inv_WeekDay) { }
    wxCalendarEvent(const wxCalendarEvent& event)
        : wxDateEvent(event), m_wday(event.m_wday) { }

    void SetWeekDay(wxDateTime::WeekDay wd) { m_wday = wd; }
    wxDateTime::WeekDay GetWeekDay() const { return m_wday; }

    virtual wxEvent *Clone() const wxOVERRIDE { return new wxCalendarEvent(*this); }

private:
    wxDateTime::WeekDay m_wday;

    wxDECLARE_DYNAMIC_CLASS_NO_ASSIGN(wxCalendarEvent);
};

// ----------------------------------------------------------------------------
// wxCalendarCtrlBase
// ----------------------------------------------------------------------------

class WXDLLIMPEXP_ADV wxCalendarCtrlBase : public wxControl
{
public:
    // do we allow changing the month/year?
    bool AllowMonthChange() const { return !HasFlag(wxCAL_NO_MONTH_CHANGE); }

    // get/set the current date
    virtual wxDateTime GetDate() const = 0;
    virtual bool SetDate(const wxDateTime& date) = 0;

    // restricting the dates shown by the control to the specified range: only
    // implemented in the generic and MSW versions for now

    // if either date is set, the corresponding limit will be enforced and true
    // returned; if none are set, the existing restrictions are removed and
    // false is returned
    virtual bool
    SetDateRange(const wxDateTime& WXUNUSED(lowerdate) = wxDefaultDateTime,
                 const wxDateTime& WXUNUSED(upperdate) = wxDefaultDateTime)
    {
        return false;
    }

    // retrieves the limits currently in use (wxDefaultDateTime if none) in the
    // provided pointers (which may be NULL) and returns true if there are any
    // limits or false if none
    virtual bool
    GetDateRange(wxDateTime *lowerdate, wxDateTime *upperdate) const
    {
        if ( lowerdate )
            *lowerdate = wxDefaultDateTime;
        if ( upperdate )
            *upperdate = wxDefaultDateTime;
        return false;
    }

    // returns one of wxCAL_HITTEST_XXX constants and fills either date or wd
    // with the corresponding value (none for NOWHERE, the date for DAY and wd
    // for HEADER)
    //
    // notice that this is not implemented in all versions
    virtual wxCalendarHitTestResult
    HitTest(const wxPoint& WXUNUSED(pos),
            wxDateTime* WXUNUSED(date) = NULL,
            wxDateTime::WeekDay* WXUNUSED(wd) = NULL)
    {
        return wxCAL_HITTEST_NOWHERE;
    }

    // allow or disable changing the current month (and year), return true if
    // the value of this option really changed or false if it was already set
    // to the required value
    //
    // NB: we provide implementation for this pure virtual function, derived
    //     classes should call it
    virtual bool EnableMonthChange(bool enable = true) = 0;

    // an item without custom attributes is drawn with the default colours and
    // font and without border, setting custom attributes allows to modify this
    //
    // the day parameter should be in 1..31 range, for days 29, 30, 31 the
    // corresponding attribute is just unused if there is no such day in the
    // current month
    //
    // notice that currently arbitrary attributes are supported only in the
    // generic version, the native controls only support Mark() which assigns
    // some special appearance (which can be customized using SetMark() for the
    // generic version) to the given day

    virtual void Mark(size_t day, bool mark) = 0;

    virtual wxCalendarDateAttr *GetAttr(size_t WXUNUSED(day)) const
        { return NULL; }
    virtual void SetAttr(size_t WXUNUSED(day), wxCalendarDateAttr *attr)
        { delete attr; }
    virtual void ResetAttr(size_t WXUNUSED(day)) { }

    // holidays support
    //
    // currently only the generic version implements all functions in this
    // section; wxMSW implements simple support for holidays (they can be
    // just enabled or disabled) and wxGTK doesn't support them at all

    // equivalent to changing wxCAL_SHOW_HOLIDAYS flag but should be called
    // instead of just changing it
    virtual void EnableHolidayDisplay(bool display = true);

    // set/get the colours to use for holidays (if they're enabled)
    virtual void SetHolidayColours(const wxColour& WXUNUSED(colFg),
                                   const wxColour& WXUNUSED(colBg)) { }

    virtual const wxColour& GetHolidayColourFg() const { return wxNullColour; }
    virtual const wxColour& GetHolidayColourBg() const { return wxNullColour; }

    // mark the given day of the current month as being a holiday
    virtual void SetHoliday(size_t WXUNUSED(day)) { }

    // customizing the colours of the controls
    //
    // most of the methods in this section are only implemented by the native
    // version of the control and do nothing in the native ones

    // set/get the colours to use for the display of the week day names at the
    // top of the controls
    virtual void SetHeaderColours(const wxColour& WXUNUSED(colFg),
                                  const wxColour& WXUNUSED(colBg)) { }

    virtual const wxColour& GetHeaderColourFg() const { return wxNullColour; }
    virtual const wxColour& GetHeaderColourBg() const { return wxNullColour; }

    // set/get the colours used for the currently selected date
    virtual void SetHighlightColours(const wxColour& WXUNUSED(colFg),
                                     const wxColour& WXUNUSED(colBg)) { }

    virtual const wxColour& GetHighlightColourFg() const { return wxNullColour; }
    virtual const wxColour& GetHighlightColourBg() const { return wxNullColour; }

    // implementation only from now on

    // generate the given calendar event, return true if it was processed
    //
    // NB: this is public because it's used from GTK+ callbacks
    bool GenerateEvent(wxEventType type)
    {
        wxCalendarEvent event(this, GetDate(), type);
        return HandleWindowEvent(event);
    }

protected:
    // generate all the events for the selection change from dateOld to current
    // date: SEL_CHANGED, PAGE_CHANGED if necessary and also one of (deprecated)
    // YEAR/MONTH/DAY_CHANGED ones
    //
    // returns true if page changed event was generated, false if the new date
    // is still in the same month as before
    bool GenerateAllChangeEvents(const wxDateTime& dateOld);

    // call SetHoliday() for all holidays in the current month
    //
    // should be called on month change, does nothing if wxCAL_SHOW_HOLIDAYS is
    // not set and returns false in this case, true if we do show them
    bool SetHolidayAttrs();

    // called by SetHolidayAttrs() to forget the previously set holidays
    virtual void ResetHolidayAttrs() { }

    // called by EnableHolidayDisplay()
    virtual void RefreshHolidays() { }
};

// ----------------------------------------------------------------------------
// wxCalendarCtrl
// ----------------------------------------------------------------------------

#define wxCalendarNameStr "CalendarCtrl"

#ifndef __WXUNIVERSAL__
    #if defined(__WXGTK20__)
        #define wxHAS_NATIVE_CALENDARCTRL
        #include "wx/gtk/calctrl.h"
        #define wxCalendarCtrl wxGtkCalendarCtrl
    #elif defined(__WXMSW__)
        #define wxHAS_NATIVE_CALENDARCTRL
        #include "wx/msw/calctrl.h"
    #elif defined(__WXQT__)
        #define wxHAS_NATIVE_CALENDARCTRL
        #include "wx/qt/calctrl.h"
    #endif
#endif // !__WXUNIVERSAL__

#ifndef wxHAS_NATIVE_CALENDARCTRL
    #include "wx/generic/calctrlg.h"
    #define wxCalendarCtrl wxGenericCalendarCtrl
#endif

// ----------------------------------------------------------------------------
// calendar event types and macros for handling them
// ----------------------------------------------------------------------------

wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_ADV, wxEVT_CALENDAR_SEL_CHANGED, wxCalendarEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_ADV, wxEVT_CALENDAR_PAGE_CHANGED, wxCalendarEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_ADV, wxEVT_CALENDAR_DOUBLECLICKED, wxCalendarEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_ADV, wxEVT_CALENDAR_WEEKDAY_CLICKED, wxCalendarEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_ADV, wxEVT_CALENDAR_WEEK_CLICKED, wxCalendarEvent );

// deprecated events
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_ADV, wxEVT_CALENDAR_DAY_CHANGED, wxCalendarEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_ADV, wxEVT_CALENDAR_MONTH_CHANGED, wxCalendarEvent );
wxDECLARE_EXPORTED_EVENT( WXDLLIMPEXP_ADV, wxEVT_CALENDAR_YEAR_CHANGED, wxCalendarEvent );

typedef void (wxEvtHandler::*wxCalendarEventFunction)(wxCalendarEvent&);

#define wxCalendarEventHandler(func) \
    wxEVENT_HANDLER_CAST(wxCalendarEventFunction, func)

#define wx__DECLARE_CALEVT(evt, id, fn) \
    wx__DECLARE_EVT1(wxEVT_CALENDAR_ ## evt, id, wxCalendarEventHandler(fn))

#define EVT_CALENDAR(id, fn) wx__DECLARE_CALEVT(DOUBLECLICKED, id, fn)
#define EVT_CALENDAR_SEL_CHANGED(id, fn) wx__DECLARE_CALEVT(SEL_CHANGED, id, fn)
#define EVT_CALENDAR_PAGE_CHANGED(id, fn) wx__DECLARE_CALEVT(PAGE_CHANGED, id, fn)
#define EVT_CALENDAR_WEEKDAY_CLICKED(id, fn) wx__DECLARE_CALEVT(WEEKDAY_CLICKED, id, fn)
#define EVT_CALENDAR_WEEK_CLICKED(id, fn) wx__DECLARE_CALEVT(WEEK_CLICKED, id, fn)

// deprecated events
#define EVT_CALENDAR_DAY(id, fn) wx__DECLARE_CALEVT(DAY_CHANGED, id, fn)
#define EVT_CALENDAR_MONTH(id, fn) wx__DECLARE_CALEVT(MONTH_CHANGED, id, fn)
#define EVT_CALENDAR_YEAR(id, fn) wx__DECLARE_CALEVT(YEAR_CHANGED, id, fn)

#endif // wxUSE_CALENDARCTRL

#endif // _WX_CALCTRL_H_


text:
from abc import ABCMeta, abstractmethod
from collections import namedtuple

DeliveryItem = namedtuple('DeliveryItem', ['sku', 'price', 'qty'])
SupplierProduct = namedtuple('SupplierProduct', ['name', 'price', 'units'])

class SupplierAPIException(Exception):
    pass

class SupplierBase(metaclass=ABCMeta):
    """Defines the interface of a supplier module.

    The mysterious SKU all over this class is abbreviation for Stock Keeping
    Unit and in this context it is basically an unique identifier for every
    product at supplier.
    """

    @abstractmethod
    def parse_delivery_report(self, report_path):
        """Parses a delivery report file and returns the delivered items.

        :param report_path: Path to the report file.
        :type report_path: str
        :rtype: List[DeliveryItem] -- The list of products imported from the
                                      file.
        :raises: SupplierAPIException
        """

    @abstractmethod
    def retrieve_product(self, sku):
        """Retrieve product data for given SKU.

        :param sku: SKU of the product to be retrieved.
        :type sku: str
        :rtype: Union[SupplierProduct, None]
        """

    @abstractmethod
    def order_product(self, sku, qty):
        """Places an order on product with given SKU.

        :param sku: SKU of the product to be ordered.
        :type sku: str
        :param qty: Quantity.
        :type qty: int
        """


text:
require 'rest_client'
require "stringio"

#
# Handle arguments
#

$options = {
  :make_class   => ARGV.delete("class")     != nil,
  :make_mobile  => ARGV.delete("mobile")    != nil,
  :fresh        => ARGV.delete("--fresh")   != nil,
  :verbose      => ARGV.delete("--verbose") != nil,
  :help         => ARGV.delete("--help")    != nil
}

if ARGV.length > 0 or $options[:help] or (!$options[:make_class] and !$options[:make_mobile])

  commands = {
    "class"     => "Makes a Tangerine Class APK",
    "mobile"    => "Makes a regular Tangerine APK",
    "--fresh"   => "Starts with a new database",
    "--verbose" => "Outputs additional information",
    "--help"    => "..."
  }
  plural = if ARGV.length > 1 then "s" else "" end
  puts "\nTangerine make script\n\nUsage: make [class|mobile] --fresh --verbose --help\n"
  if $options[:help] then
    puts "\n"
    commands.each_pair do |opt, desc| printf "    %-20s %s\n", opt, desc end
  end
  puts "Unrecognized argument#{plural}: #{ARGV.join(',')}" if ARGV.length > 0
  puts "\n"
  exit(2)
end

#
# Helper functions
#

# handles verbosity
def check_step(response="", intent="")

  if response.downcase.include? "error"
    puts "Aborting. Error while attempting to #{intent}."
    puts split("\n").select { |line| line if line.downcase.include? "error" }
    exit(2)
  end

  if response.downcase.include? "warning"
    puts response.split("\n").select { |line| line if line.downcase.include? "warning" }
  elsif $options[:verbose]
    puts response
  end

end

# Shows user nice updates
def section(title="")
  puts "\n\n*** #{title}\n"
  yield
  puts "Done."
end

# capture standard error
def bite_tongue
  previous_stderr, $stderr = $stderr, StringIO.new
  yield
  $stderr.string
ensure
  $stderr = previous_stderr
end

#
# Config
#

time = Time.new

home_dir        = ENV['HOME']
backup_dir      = "#{home_dir}/tangerine-apks/"
relative_to_app = "../app/"

version    = `git log --pretty=format:'%h' -n 1`
date_hour  = "#{time.year}-#{time.month}-#{time.day}-#{time.day}"

if $options[:make_class]
  package_name = "org.rti.tangerineclass"
  app_name     = "Tangerine Class"
  context      = "class"
elsif $options[:make_mobile]
  package_name = "org.rti.tangy"
  app_name     = "Tangerine"
  context      = "mobile"
end

#
# Prepare CouchDB
#
section "Preparing couch" do

  # reverted to "server" after push
  File.open("#{relative_to_app}_docs/configuration.json", "r+") { |file|
    newText = file.read.sub(/\"context(.*)\"/, "\"context\" : \"#{context}\"")
    file.seek(0)
    file.truncate(0)
    file.write newText
  }

  if $options[:fresh]

    begin
      check_step RestClient.delete("http://admin:password@localhost:5984/tangerine"), "delete database"
    rescue
      nil
    end
    check_step RestClient.put("http://admin:password@localhost:5984/tangerine", "", :content_type => 'application/json'), "create new database"

  end

  bite_tongue do
    check_step `cd #{relative_to_app}; couchapp push; cd -`, "push with Couchapp"
  end

  #File.open("#{relative_to_app}_docs/configuration.json", "r+") { |file|
  #  newText = file.read.sub(/\"context(.*)\"/, "\"context\" : \"server\"")
  #  file.seek(0)
  #  file.truncate(0)
  #  file.write newText
  #}

  check_step RestClient.post("http://admin:password@localhost:5984/tangerine/_compact", "", :content_type => 'application/json'), "compact database"
  check_step RestClient.post("http://admin:password@localhost:5984/tangerine/_ensure_full_commit", "", :content_type => 'application/json'), "ensure full commit of database"
end

#
# Prepare the source
#

section "Preparing source" do

  File.open("AndroidManifest.xml", "r+") { |file|
    newText = file.read.sub(/package=\"(.*?)\"/, "package=\"#{package_name}\"")
    file.seek(0)
    file.truncate(0)
    file.write newText
  }

  File.open("res/values/strings.xml", "r+") { |file|
    newText = file.read.sub(/\<string name=\"app_name\"\>(.*?)\<\/string\>/, "<string name=\"app_name\">#{app_name}</string>")
    file.seek(0)
    file.truncate(0)
    file.write newText
  }

  File.open("src/Tangerine.java", "r+") { |file|
    newText = file.read.sub(/package(.*?);/, "package #{package_name};")
    file.seek(0)
    file.truncate(0)
    file.write newText
  }

end

#
# Get on with the building
#

bite_tongue do

  section "Building" do
    check_step `ant clean`, "clean with ant"
    check_step `ant debug`, "build APK"
  end

  section "Installing" do
    if $options[:make_class]
      check_step `adb uninstall org.rti.tangerineclass`, "uninstall old APK"
    elsif $options[:make_mobile]
      check_step `adb uninstall org.rti.tangy`,      "uninstall old APK"
    end
    check_step `adb install bin/Tangerine-debug.apk`,  "install new APK"
  end

  # Save backup
  check_step `cp bin/Tangerine-debug.apk #{backup_dir}Tangerine-#{date_hour}-#{version}.apk`, "make backup"

end

puts "\nAll done. Enjoy your #{if $options[:fresh] then "fresh " else "" end}Tangerine.\n\n"
if $options[:make_mobile]
  `adb shell am start -n org.rti.tangy/org.rti.tangy.Tangy`
elsif $options[:make_class]
  `adb shell am start -n org.rti.tangerineclass/org.rti.tangerineclass.Tangerine`
end


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================

#ifndef SEQAN_HEADER_STREAM_ALGORITHMS_H
#define SEQAN_HEADER_STREAM_ALGORITHMS_H

/* IOREV
 * _tested_
 * _doc_
 *
 *
 * mostly documented (doc for some functions missing)
 * used ubiquitously, but possibly not all specializations
 *
 * functions seem to be agnostic of FileType (stream.h or cstream.)
 * it is not clear if both are actually tested (but shouldn't matter
 * if underlying routines work correctly)
 */

namespace SEQAN_NAMESPACE_MAIN
{
//////////////////////////////////////////////////////////////////////////////

/**
.Internal._streamPutInt:
..summary:Converts an integer to a character and writes it to stream.
..cat:Streams
..signature:_streamPutInt(stream, number [, format_string])
..param.target:An output stream.
...type:Adaption."std::iostream"
..param.number:A number that is written to $stream$.
*/
template <typename TStream>
inline void
_streamPutInt(TStream & target,
			  int number,
			  char const * format_string)
{
//IOREV _doc_
SEQAN_CHECKPOINT
	char str[BitsPerValue<int>::VALUE];
	sprintf(str, format_string, number);
	_streamWrite(target, str);
}
template <typename TStream>
inline void
_streamPutInt(TStream & target,
			  int number)
{
//IOREV _doc_
SEQAN_CHECKPOINT
	_streamPutInt(target, number, "%d");
}

/**
.Internal._streamPutFloat:
..summary:Converts a float to a character and writes it to stream.
..cat:Streams
..signature:_streamPutFloat(stream, number [, format_string])
..param.target:An output stream.
...type:Adaption."std::iostream"
..param.number:A number that is written to $stream$.
*/
template <typename TStream>
inline void
_streamPutFloat(TStream & target,
			  double number,
			  char const * format_string)
{
//IOREV _doc_
    SEQAN_CHECKPOINT;
	char str[BitsPerValue<float>::VALUE];
	sprintf(str, format_string, number);
	_streamWrite(target, str);
}
template <typename TStream>
inline void
_streamPutFloat(TStream & target,
				double number)
{
//IOREV _doc_
    SEQAN_CHECKPOINT;
	_streamPutFloat(target, number, "%f");
}

//////////////////////////////////////////////////////////////////////////////

template <typename TTarget, typename T1, typename T2, typename TCompression>
inline void
_streamWrite(TTarget & target,
			 Pair<T1, T2, TCompression> const & source)
{
//IOREV _nodoc_
SEQAN_CHECKPOINT
	_streamWrite(target, getValueI1(source));
	_streamWrite(target, getValueI2(source));
}

template <typename TTarget, typename T1, typename T2, typename T3, typename TCompression>
inline void
_streamWrite(TTarget & target,
			 Triple<T1, T2, T3, TCompression> const & source)
{
//IOREV _nodoc_
SEQAN_CHECKPOINT
	_streamWrite(target, getValueI1(source));
	_streamWrite(target, getValueI2(source));
	_streamWrite(target, getValueI3(source));
}

//////////////////////////////////////////////////////////////////////////////

/**
.Internal._streamWrite:
..summary:Writes a sequence to stream.
..cat:Streams
..signature:_streamWrite(stream, sequence)
..param.stream:An input stream.
..param.sequence:A sequence that is written to $stream$.
*/

template <typename TTarget, typename TSource>
inline void
_streamWrite(TTarget & target,
			 TSource const & source)
{
//IOREV _doc_
SEQAN_CHECKPOINT
	_streamWriteSeq(target, source, typename IsSequence<TSource const>::Type());
}

//____________________________________________________________________________

template <typename TTarget, typename TSource>
inline void
_streamWriteSeq(TTarget & target,
				TSource const & source,
				False const)
{
//IOREV  _nodoc_
	_streamPut(target, source);
}

//____________________________________________________________________________

template <typename TTarget, typename TSource>
inline void
_streamWriteSeq(TTarget & target,
				TSource const & source,
				True const)
{
//IOREV _nodoc_
SEQAN_CHECKPOINT
	typename Iterator<TSource const, Standard>::Type it = begin(source, Standard());
	typename Iterator<TSource const, Standard>::Type it_end = end(source, Standard());

	for (; it != it_end; ++it)
	{
		typename GetValue<TSource const>::Type val_ = getValue(it);
		_streamWrite(target, val_);
	}
}

template <typename TTarget, typename TSourceValue>
inline void
_streamWriteSeq(TTarget & target,
			    TSourceValue const * source,
				True const)
{
//IOREV _nodoc_
SEQAN_CHECKPOINT

	for (; !atEnd(source); ++source)
	{
		_streamWrite(target, *source);
	}
}

//////////////////////////////////////////////////////////////////////////////

/**
.Internal._streamWriteRange:
..summary:Writes a range to stream.
..cat:Streams
..signature:_streamWriteRange(stream, begin_iterator, end_iterator)
..param.stream:An input stream.
..param.sequence:A sequence that is written to $stream$.
*/

template <typename TTarget, typename TIterator>
inline void
_streamWriteRange(TTarget & target,
				  TIterator begin_,
				  TIterator end_)
{
//IOREV _doc_
SEQAN_CHECKPOINT
	for (; begin_ != end_; ++begin_)
	{
		_streamPut(target, *begin_);
	}
}

//////////////////////////////////////////////////////////////////////////////

} //namespace SEQAN_NAMESPACE_MAIN

#endif //#ifndef SEQAN_HEADER_...


text:
module Database.Neo4j.Internal.Util.Table(
  Table,
  mkCase,
  compile,
  compileWithDefault,
  compileM,
  compileWithDefaultM
) where

import qualified Data.Map   as M
import           Data.Maybe (fromMaybe)

-- TODO: Actually try it out
-- TODO: Switch to using an array based lookup table

newtype Table m a b = MkTable { unTable :: M.Map a (m b) } deriving (Show, Eq, Ord)

instance (Ord a) => Monoid (Table m a b) where
  mempty = MkTable M.empty
  (MkTable leftMap) `mappend` (MkTable rightMap) = MkTable $ leftMap `mappend` rightMap

instance (Ord a, Functor m) => Functor (Table m a) where
  fmap f (MkTable m) = MkTable $ M.map (fmap f) m

instance (Ord a, Applicative m) => Applicative (Table m a) where
  pure _ = MkTable M.empty
  (MkTable fMap) <*> (MkTable vMap) = MkTable $ M.intersectionWith (<*>) fMap vMap

mkCase :: a -> m b -> Table m a b
mkCase k v = MkTable $ M.singleton k v

compile :: (Ord a, Monad m, Monoid (m b)) => Table m a b -> a -> m b
compile t = compileWithDefault t mempty

compileWithDefault :: (Ord a, Monad m) => Table m a b -> m b -> a -> m b
compileWithDefault t els k = fromMaybe els $ M.lookup k $ unTable t

compileM :: (Ord a, Monad m, Monoid (m b)) => Table m a b -> m a -> m b
compileM t = compileWithDefaultM t mempty

compileWithDefaultM :: (Ord a, Monad m) => Table m a b -> m b -> m a -> m b
compileWithDefaultM t els keyM = keyM >>= \k -> fromMaybe els $ M.lookup k $ unTable t


text:
#include "arch/locked_mem.hh"
#include "arch/mmapped_ipr.hh"
#include "arch/utility.hh"
#include "base/bigint.hh"
#include "base/output.hh"
#include "config/the_isa.hh"
#include "cpu/simple/atomic.hh"
#include "cpu/exetrace.hh"
#include "debug/Drain.hh"
#include "debug/ExecFaulting.hh"
#include "debug/SimpleCPU.hh"
#include "mem/packet.hh"
#include "mem/packet_access.hh"
#include "mem/physical.hh"
#include "params/AtomicSimpleCPU.hh"
#include "sim/faults.hh"
#include "sim/system.hh"
#include "sim/full_system.hh"

using namespace std;
using namespace TheISA;

AtomicSimpleCPU::TickEvent::TickEvent(AtomicSimpleCPU *c)
    : Event(CPU_Tick_Pri), cpu(c)
{
}

void
AtomicSimpleCPU::TickEvent::process()
{
    cpu->tick();
}

const char *
AtomicSimpleCPU::TickEvent::description() const
{
    return "AtomicSimpleCPU tick";
}

void
AtomicSimpleCPU::init()
{
    BaseCPU::init();

    // Initialise the ThreadContext's memory proxies
    tcBase()->initMemProxies(tcBase());

    if (FullSystem && !params()->switched_out) {
        ThreadID size = threadContexts.size();
        for (ThreadID i = 0; i < size; ++i) {
            ThreadContext *tc = threadContexts[i];
            // initialize CPU, including PC
            TheISA::initCPU(tc, tc->contextId());
        }
    }

    // Atomic doesn't do MT right now, so contextId == threadId
    ifetch_req.setThreadContext(_cpuId, 0); // Add thread ID if we add MT
    data_read_req.setThreadContext(_cpuId, 0); // Add thread ID here too
    data_write_req.setThreadContext(_cpuId, 0); // Add thread ID here too
}

AtomicSimpleCPU::AtomicSimpleCPU(AtomicSimpleCPUParams *p)
    : BaseSimpleCPU(p), tickEvent(this), width(p->width), locked(false),
      simulate_data_stalls(p->simulate_data_stalls),
      simulate_inst_stalls(p->simulate_inst_stalls),
      drain_manager(NULL),
      icachePort(name() + ".icache_port", this),
      dcachePort(name() + ".dcache_port", this),
      fastmem(p->fastmem), dcache_access(false), dcache_latency(0),
      ppCommit(nullptr)
{
    _status = Idle;
}

AtomicSimpleCPU::~AtomicSimpleCPU()
{
    if (tickEvent.scheduled()) {
        deschedule(tickEvent);
    }
}

unsigned int
AtomicSimpleCPU::drain(DrainManager *dm)
{
    assert(!drain_manager);
    if (switchedOut())
        return 0;

    if (!isDrained()) {
        DPRINTF(Drain, "Requesting drain: %s\n", pcState());
        drain_manager = dm;
        return 1;
    } else {
        if (tickEvent.scheduled())
            deschedule(tickEvent);

        DPRINTF(Drain, "Not executing microcode, no need to drain.\n");
        return 0;
    }
}

void
AtomicSimpleCPU::drainResume()
{
    assert(!tickEvent.scheduled());
    assert(!drain_manager);
    if (switchedOut())
        return;

    DPRINTF(SimpleCPU, "Resume\n");
    verifyMemoryMode();

    assert(!threadContexts.empty());
    if (threadContexts.size() > 1)
        fatal("The atomic CPU only supports one thread.\n");

    if (thread->status() == ThreadContext::Active) {
        schedule(tickEvent, nextCycle());
        _status = BaseSimpleCPU::Running;
        notIdleFraction = 1;
    } else {
        _status = BaseSimpleCPU::Idle;
        notIdleFraction = 0;
    }

    system->totalNumInsts = 0;
}

bool
AtomicSimpleCPU::tryCompleteDrain()
{
    if (!drain_manager)
        return false;

    DPRINTF(Drain, "tryCompleteDrain: %s\n", pcState());
    if (!isDrained())
        return false;

    DPRINTF(Drain, "CPU done draining, processing drain event\n");
    drain_manager->signalDrainDone();
    drain_manager = NULL;

    return true;
}

void
AtomicSimpleCPU::switchOut()
{
    BaseSimpleCPU::switchOut();

    assert(!tickEvent.scheduled());
    assert(_status == BaseSimpleCPU::Running || _status == Idle);
    assert(isDrained());
}

void
AtomicSimpleCPU::takeOverFrom(BaseCPU *oldCPU)
{
    BaseSimpleCPU::takeOverFrom(oldCPU);

    // The tick event should have been descheduled by drain()
    assert(!tickEvent.scheduled());

    ifetch_req.setThreadContext(_cpuId, 0); // Add thread ID if we add MT
    data_read_req.setThreadContext(_cpuId, 0); // Add thread ID here too
    data_write_req.setThreadContext(_cpuId, 0); // Add thread ID here too
}

void
AtomicSimpleCPU::verifyMemoryMode() const
{
    if (!system->isAtomicMode()) {
        fatal("The atomic CPU requires the memory system to be in "
              "'atomic' mode.\n");
    }
}

void
AtomicSimpleCPU::activateContext(ThreadID thread_num)
{
    DPRINTF(SimpleCPU, "ActivateContext %d\n", thread_num);

    assert(thread_num == 0);
    assert(thread);

    assert(_status == Idle);
    assert(!tickEvent.scheduled());

    notIdleFraction = 1;
    Cycles delta = ticksToCycles(thread->lastActivate - thread->lastSuspend);
    numCycles += delta;
    ppCycles->notify(delta);

    //Make sure ticks are still on multiples of cycles
    schedule(tickEvent, clockEdge(Cycles(0)));
    _status = BaseSimpleCPU::Running;
}

void
AtomicSimpleCPU::suspendContext(ThreadID thread_num)
{
    DPRINTF(SimpleCPU, "SuspendContext %d\n", thread_num);

    assert(thread_num == 0);
    assert(thread);

    if (_status == Idle)
        return;

    assert(_status == BaseSimpleCPU::Running);

    // tick event may not be scheduled if this gets called from inside
    // an instruction's execution, e.g. "quiesce"
    if (tickEvent.scheduled())
        deschedule(tickEvent);

    notIdleFraction = 0;
    _status = Idle;
}

Tick
AtomicSimpleCPU::AtomicCPUDPort::recvAtomicSnoop(PacketPtr pkt)
{
    DPRINTF(SimpleCPU, "Atomic: received snoop pkt for addr:%#x %s\n", pkt->getAddr(),
            pkt->cmdString());

    // X86 ISA: Snooping an invalidation for monitor/mwait
    AtomicSimpleCPU *cpu = (AtomicSimpleCPU *)(&owner);
    if(cpu->getAddrMonitor()->doMonitor(pkt)) {
        cpu->wakeup();
    }

    // if snoop invalidates, release any associated locks
    if (pkt->isInvalidate()) {
        DPRINTF(SimpleCPU, "Atomic: received invalidation for addr:%#x\n",
                pkt->getAddr());
        TheISA::handleLockedSnoop(cpu->thread, pkt, cacheBlockMask);
    }

    return 0;
}

void
AtomicSimpleCPU::AtomicCPUDPort::recvFunctionalSnoop(PacketPtr pkt)
{
    DPRINTF(SimpleCPU, "Functional: received snoop pkt for addr:%#x %s\n", pkt->getAddr(),
            pkt->cmdString());

    // X86 ISA: Snooping an invalidation for monitor/mwait
    AtomicSimpleCPU *cpu = (AtomicSimpleCPU *)(&owner);
    if(cpu->getAddrMonitor()->doMonitor(pkt)) {
        cpu->wakeup();
    }

    // if snoop invalidates, release any associated locks
    if (pkt->isInvalidate()) {
        DPRINTF(SimpleCPU, "Functional: received invalidation for addr:%#x\n",
                pkt->getAddr());
        TheISA::handleLockedSnoop(cpu->thread, pkt, cacheBlockMask);
    }
}

int normal = 1;

Fault
AtomicSimpleCPU::readMem(Addr addr, uint8_t * data,
                         unsigned size, unsigned flags)
{
    DPRINTF(SimpleCPU, "Read Memory %#x\n", addr);
    // use the CPU's statically allocated read request and packet objects
    Request *req = &data_read_req;

    if (traceData)
        traceData->setMem(addr, size, flags);

    //The size of the data we're trying to read.
    int fullSize = size;

    //The address of the second part of this access if it needs to be split
    //across a cache line boundary.
    Addr secondAddr = roundDown(addr + size - 1, cacheLineSize());

    if (secondAddr > addr)
        size = secondAddr - addr;

    dcache_latency = 0;

    req->taskId(taskId());
    while (1) {
        req->setVirt(0, addr, size, flags, dataMasterId(), thread->pcState().instAddr());

        // translate to physical address
        Fault fault = thread->dtb->translateAtomic(req, tc, BaseTLB::Read);

        // Now do the access.
        if (fault == NoFault && !req->getFlags().isSet(Request::NO_ACCESS)) {
            Packet pkt(req, MemCmd::ReadReq);
            pkt.refineCommand();
            pkt.dataStatic(data);

            if (req->isMmappedIpr())
                dcache_latency += TheISA::handleIprRead(thread->getTC(), &pkt);
            else {
                if (fastmem && system->isMemAddr(pkt.getAddr()))
                    system->getPhysMem().access(&pkt);
                else
                    dcache_latency += dcachePort.sendAtomic(&pkt);
            }
            dcache_access = true;

            assert(!pkt.isError());

            if (req->isLLSC()) {
                TheISA::handleLockedRead(thread, req);
            }
        }

        //If there's a fault, return it
        if (fault != NoFault) {
            if (req->isPrefetch()) {
                return NoFault;
            } else {
                /* Modified */
                    return fault;
                /* End Modified */
            }
        }

        //If we don't need to access a second cache line, stop now.
        if (secondAddr <= addr)
        {
            if (req->isLocked() && fault == NoFault) {
                assert(!locked);
                locked = true;
            }
            return fault;
        }

        /*
         * Set up for accessing the second cache line.
         */

        //Move the pointer we're reading into to the correct location.
        data += size;
        //Adjust the size to get the remaining bytes.
        size = addr + fullSize - secondAddr;
        //And access the right address.
        addr = secondAddr;
    }
}

Fault
AtomicSimpleCPU::writeMem(uint8_t *data, unsigned size,
                          Addr addr, unsigned flags, uint64_t *res)
{

    static uint8_t zero_array[64] = {};
    DPRINTF(SimpleCPU, "Write Memory %#x\n", addr);

    if (data == NULL) {
        assert(size <= 64);
        assert(flags & Request::CACHE_BLOCK_ZERO);
        // This must be a cache block cleaning request
        data = zero_array;
    }

    // use the CPU's statically allocated write request and packet objects
    Request *req = &data_write_req;

    if (traceData)
        traceData->setMem(addr, size, flags);

    //The size of the data we're trying to read.
    int fullSize = size;

    //The address of the second part of this access if it needs to be split
    //across a cache line boundary.
    Addr secondAddr = roundDown(addr + size - 1, cacheLineSize());

    if(secondAddr > addr)
        size = secondAddr - addr;

    dcache_latency = 0;

    req->taskId(taskId());
    while(1) {
        req->setVirt(0, addr, size, flags, dataMasterId(), thread->pcState().instAddr());

        // translate to physical address
        Fault fault = thread->dtb->translateAtomic(req, tc, BaseTLB::Write);

        // Now do the access.
        if (fault == NoFault) {
            MemCmd cmd = MemCmd::WriteReq; // default
            bool do_access = true;  // flag to suppress cache access

            if (req->isLLSC()) {
                cmd = MemCmd::StoreCondReq;
                do_access = TheISA::handleLockedWrite(thread, req, dcachePort.cacheBlockMask);
            } else if (req->isSwap()) {
                cmd = MemCmd::SwapReq;
                if (req->isCondSwap()) {
                    assert(res);
                    req->setExtraData(*res);
                }
            }

            if (do_access && !req->getFlags().isSet(Request::NO_ACCESS)) {
                Packet pkt = Packet(req, cmd);
                pkt.dataStatic(data);

                if (req->isMmappedIpr()) {
                    dcache_latency +=
                        TheISA::handleIprWrite(thread->getTC(), &pkt);
                } else {
                    if (fastmem && system->isMemAddr(pkt.getAddr()))
                        system->getPhysMem().access(&pkt);
                    else
                        dcache_latency += dcachePort.sendAtomic(&pkt);
                }
                dcache_access = true;
                assert(!pkt.isError());

                if (req->isSwap()) {
                    assert(res);
                    memcpy(res, pkt.getConstPtr<uint8_t>(), fullSize);
                }
            }

            if (res && !req->isSwap()) {
                *res = req->getExtraData();
            }
        }

        //If there's a fault or we don't need to access a second cache line,
        //stop now.
        if (fault != NoFault || secondAddr <= addr)
        {
            if (req->isLocked() && fault == NoFault) {
                assert(locked);
                locked = false;
            }
            if (fault != NoFault && req->isPrefetch()) {
                return NoFault;
            } else {
                /* Modified */
                    return fault;
                /* End Modified */
            }
        }

        /*
         * Set up for accessing the second cache line.
         */

        //Move the pointer we're reading into to the correct location.
        data += size;
        //Adjust the size to get the remaining bytes.
        size = addr + fullSize - secondAddr;
        //And access the right address.
        addr = secondAddr;
    }
}

TheISA::PCState *thePCState = nullptr;
Tick startTick = 0;
Tick currTick = 0;

void dumpTiming(const char* filename);

void
dumpTiming(const char* filename)
{
    FILE *fp;
    fp = fopen(filename, "w");
    if (fp != NULL) {
        fprintf(fp, "%ld", currTick - startTick);
        fclose(fp);
    }
}

void
AtomicSimpleCPU::tick()
{
    DPRINTF(SimpleCPU, "Tick\n");

    Tick latency = 0;
    currTick = curTick();

    for (int i = 0; i < width || locked; ++i) {
        numCycles++;
        ppCycles->notify(1);

        if (!curStaticInst || !curStaticInst->isDelayedCommit()) {
            checkForInterrupts();
            checkPcEventQueue();
        }

        // We must have just got suspended by a PC event
        if (_status == Idle) {
            tryCompleteDrain();
            return;
        }

        Fault fault = NoFault;

        TheISA::PCState pcState = thread->pcState();

        bool needToFetch = !isRomMicroPC(pcState.microPC()) &&
                           !curMacroStaticInst;
        if (needToFetch) {
            ifetch_req.taskId(taskId());
            setupFetchRequest(&ifetch_req);
            fault = thread->itb->translateAtomic(&ifetch_req, tc,
                                                 BaseTLB::Execute);
        }

        if (fault == NoFault) {
            Tick icache_latency = 0;
            bool icache_access = false;
            dcache_access = false; // assume no dcache access

            if (needToFetch) {
                // This is commented out because the decoder would act like
                // a tiny cache otherwise. It wouldn't be flushed when needed
                // like the I cache. It should be flushed, and when that works
                // this code should be uncommented.
                //Fetch more instruction memory if necessary
                //if(decoder.needMoreBytes())
                //{
                    icache_access = true;
                    Packet ifetch_pkt = Packet(&ifetch_req, MemCmd::ReadReq);
                    ifetch_pkt.dataStatic(&inst);

                    if (fastmem && system->isMemAddr(ifetch_pkt.getAddr()))
                        system->getPhysMem().access(&ifetch_pkt);
                    else
                        icache_latency = icachePort.sendAtomic(&ifetch_pkt);

                    assert(!ifetch_pkt.isError());

                    // ifetch_req is initialized to read the instruction directly
                    // into the CPU object's inst field.
                //}
            }

            preExecute();

            if (curStaticInst) {
                fault = curStaticInst->execute(this, traceData);

                // keep an instruction count
                if (fault == NoFault) {
                    countInst();
                    ppCommit->notify(std::make_pair(thread, curStaticInst));
                }
                else if (traceData && !DTRACE(ExecFaulting)) {
                    delete traceData;
                    traceData = NULL;
                }

                postExecute();
            }

            // @todo remove me after debugging with legion done
            if (curStaticInst && (!curStaticInst->isMicroop() ||
                        curStaticInst->isFirstMicroop()))
                instCnt++;

            Tick stall_ticks = 0;
            if (simulate_inst_stalls && icache_access)
                stall_ticks += icache_latency;

            if (simulate_data_stalls && dcache_access)
                stall_ticks += dcache_latency;

            if (stall_ticks) {
                // the atomic cpu does its accounting in ticks, so
                // keep counting in ticks but round to the clock
                // period
                latency += divCeil(stall_ticks, clockPeriod()) *
                    clockPeriod();
            }

        }
        if(fault != NoFault || !stayAtPC) {
            // instruction takes at least one cycle
            /* Modified */
            if (latency < clockPeriod())
                latency = clockPeriod();
            currTick = currTick+latency; // NOTICE:
            /* End Modified */
            advancePC(fault);
        }
    }

    if (tryCompleteDrain())
        return;

    /* Modified */
    // printf("curTick = %lu, nextTick = %lu\n", curTick(), currTick);
    if (_status != Idle)
        schedule(tickEvent, currTick);
    /* End Modified */
}

void
AtomicSimpleCPU::regProbePoints()
{
    BaseCPU::regProbePoints();

    ppCommit = new ProbePointArg<pair<SimpleThread*, const StaticInstPtr>>
                                (getProbeManager(), "Commit");
}

void
AtomicSimpleCPU::printAddr(Addr a)
{
    dcachePort.printAddr(a);
}

////////////////////////////////////////////////////////////////////////
//
//  AtomicSimpleCPU Simulation Object
//
AtomicSimpleCPU *
AtomicSimpleCPUParams::create()
{
    numThreads = 1;
    if (!FullSystem && workload.size() != 1)
        panic("only one workload allowed");
    return new AtomicSimpleCPU(this);
}


text:
require 'spec_helper'
require 'capybara/rspec'

Capybara.app = Application

feature 'User registration' do
  scenario 'User can register, log out and log back in again' do
    visit '/'

    expect(page).to have_content 'You are not logged in'

    # Register
    click_link 'Register'

    fill_in 'email', :with => 'user@example.com'
    fill_in 'password', :with => 'my_password'
    fill_in 'password_confirmation', :with => 'my_password'
    click_button 'Register'

    expect(page).to have_content 'Welcome, user@example.com'

    # Log out
    click_link 'Log out'

    expect(page).to_not have_content 'Welcome, user@example.com'
    expect(page).to have_content 'You are not logged in'

    # Log in with invalid password
    click_link 'Log in'

    fill_in 'email', :with => 'user@example.com'
    fill_in 'password', :with => 'not_my_password'
    click_button 'Log in'

    expect(page).to_not have_content 'Welcome, user@example.com'
    expect(page).to have_content 'Email / password is invalid'

    # Log back in again
    visit '/'
    click_link 'Log in'

    fill_in 'email', :with => 'user@example.com'
    fill_in 'password', :with => 'my_password'
    click_button 'Log in'

    expect(page).to have_content 'Welcome, user@example.com'
  end

  scenario 'User can not log in if they have not registered' do
    visit '/'

    click_link 'Log in'

    fill_in 'email', :with => 'user_does_not_exist@example.com'
    fill_in 'password', :with => 'password'
    click_button 'Log in'

    expect(page).to have_content 'Email / password is invalid'
  end

  scenario 'User can not register if they password confirmation does not match' do
    visit '/'
    click_link 'Register'

    fill_in 'email', :with => 'user@example.com'
    fill_in 'password', :with => 'my_password'
    fill_in 'password_confirmation', :with => 'not_my_password'
    click_button 'Register'

    expect(page).to have_content 'Password and confirmation do not match'
  end

  scenario 'User can not register if password is less than three characters' do
    visit '/'
    click_link 'Register'

    fill_in 'email', :with => 'user@example.com'
    fill_in 'password', :with => '12'
    fill_in 'password_confirmation', :with => '12'
    click_button 'Register'

    expect(page).to have_content 'Password must be at least three characters'
  end

  scenario 'User can not register if password is blank' do
    visit '/'
    click_link 'Register'

    fill_in 'email', :with => 'user@example.com'
    fill_in 'password', :with => ''
    fill_in 'password_confirmation', :with => ''
    click_button 'Register'

    expect(page).to have_content 'Password must not be blank'
  end

  scenario 'User an not register if password is 3 or more whitespaces' do
    visit '/'
    click_link 'Register'

    fill_in 'email', :with => 'user@example.com'
    fill_in 'password', :with => '   '
    fill_in 'password_confirmation', :with => '   '
    click_button 'Register'

    expect(page).to have_content 'Password must not be blank'
  end

  scenario 'User can not register if email is already taken' do
    password = BCrypt::Password.create('password')
    DB[:users].insert(email: 'user@example.com', password: password)

    visit '/'
    click_link 'Register'

    fill_in 'email', :with => 'user@example.com'
    fill_in 'password', :with => 'another_password'
    fill_in 'password_confirmation', :with => 'another_password'
    click_button 'Register'

    expect(page).to have_content 'Email is already taken'
  end
end


text:
package edu.utah.sci.cyclist.core.event.notification;

public class CyclistNotification {

	private String _type;
	private Object _src = null;
	private String _destId;

	public CyclistNotification(String type) {
		this(type, null);
	}
	public CyclistNotification(String type, String dest) {
		_type = type;
		_destId = dest;
	}

	public void setSource(Object src) {
		if (_src != null) {
			// throw an illegal action
		}
		_src = src;
	}

	public String getType() {
		return _type;
	}

	public Object getSource() {
		return _src;
	}

	public String getDestID() {
		return _destId;
	}

}


text:
export interface Product {
  _id: number;
  tags: Array<Object>;
  title: string;
  amount: string;

  description: string;
  rating: number;
  creator: string;
  ingredients: Array<Object>;
  directions: Array<Object>;
};


text:
package org.spongepowered.common.data.builder.block.tileentity;

import net.minecraft.tileentity.TileEntityDispenser;
import org.spongepowered.api.block.tileentity.carrier.Dispenser;
import org.spongepowered.api.data.DataView;
import org.spongepowered.api.data.persistence.InvalidDataException;
import org.spongepowered.common.util.Constants;

import java.util.Optional;

public class SpongeDispenserBuilder extends SpongeLockableBuilder<Dispenser> {

    public SpongeDispenserBuilder() {
        super(Dispenser.class, 1);
    }

    @Override
    protected Optional<Dispenser> buildContent(DataView container) throws InvalidDataException {
        return super.buildContent(container).map(dispenser -> {
            if (container.contains(Constants.TileEntity.CUSTOM_NAME)) {
                ((TileEntityDispenser) dispenser).setCustomName(container.getString(Constants.TileEntity.CUSTOM_NAME).get());
            }
            ((TileEntityDispenser) dispenser).validate();
            return dispenser;
        });
    }
}


text:
require 'methadone'
require 'open3'
require 'json'
require_relative 'runner'
require_relative 'safe_runner'

class Kb8Run

  include Methadone::Main
  include Methadone::CLILogging

  API_VERSION = 'v1'
  MISSING_DATA_RETRIES = 3
  LEGACY_CONTEXT_NAME = 'kb8or-context'
  NAMESPACE_FLAG='--namespace=%s'
  CMD_KUBECTL = 'kubectl'
  CMD_ROLLING_UPDATE = "#{CMD_KUBECTL} rolling-update %s -f -"
  CMD_CREATE = "#{CMD_KUBECTL} create -f -"
  CMD_REPLACE = "#{CMD_KUBECTL} replace -f -"
  CMD_DELETE = "#{CMD_KUBECTL} delete %s/%s %s"
  CMD_GET_POD_LOGS = "#{CMD_KUBECTL} logs %s %s"
  CMD_GET_POD = "#{CMD_KUBECTL} get pods -l %s -o yaml"
  CMD_GET_EVENTS = "#{CMD_KUBECTL} get events -o yaml"
  CMD_GET_RESOURCE = "#{CMD_KUBECTL} get %s -o yaml %s"
  CMD_DELETE_PODS = "#{CMD_KUBECTL} delete pods -l %s"
  CMD_PATCH_RESOURCE = "#{CMD_KUBECTL} patch %s %s -p '%s'"
  CMD_LABEL_RESOURCE = "#{CMD_KUBECTL} label %ss %s %s"
  CMD_CONFIG_CLUSTER = "#{CMD_KUBECTL} config set-cluster %s --server=%s"
  CMD_CONFIG_CONTEXT_SERVER = "#{CMD_KUBECTL} config set-context #{LEGACY_CONTEXT_NAME} --cluster=%s --namespace=%s"
  CMD_CONFIG_CONTEXT = "#{CMD_KUBECTL} config set-context %s --cluster=%s --namespace=%s %s"
  CMD_CONFIG_DEFAULT = "#{CMD_KUBECTL} config use-context %s"

  class KubeCtlError < StandardError

    attr_accessor :output,
                  :message,
                  :retryable

    RETRY_COUNT = 3
    RETRY_BACK_OFF = 3
    ERROR_IO_TIMEOUT = /error: couldn't read version from server.*i\/o timeout/
    ERROR_IO_REFUSED = /error: couldn't read version from server.*: connection refused/
    ERROR_IO_TLS_TIMEOUT = /error: couldn't read version from server.*: TLS handshake timeout/
    RETRY_ERRS = [ERROR_IO_REFUSED, ERROR_IO_TIMEOUT, ERROR_IO_TLS_TIMEOUT]

    def initialize(status, cmd, output, input)
      @output = output
      @message = ''

      # Work out if the error is retryable...
      @retryable = false
      RETRY_ERRS.each do | err_regexp |
        if err_regexp =~ @output
          @retryable = true
          break
        end
      end
      if input
        @message = "Error when using stdin:\n#{input}\n"
      end
      @message = "#{@message}Error (exit code:'#{status.exitstatus.to_i}') running '#{cmd}':\n#{output}\n"
      @message = "#{@message}Error (Tried #{RETRY_COUNT} times) #{@message}" if @retryable
    end

    def enough_already?(errors)
      # For non-retryable errors - we've always had enough!
      return true unless retryable
      error_count = 0
      errors.each do |error|
        if error == self
          error_count = error_count + 1
          sleep RETRY_BACK_OFF
        end
      end
      (error_count >= RETRY_COUNT)
    end

    def == (other_object)
      (self.output == other_object.output)
    end
  end

  def self.run(cmd, capture=false, term_output=true, input=nil, safe=true)

    errors = []
    ok = false
    until ok
      # Run process and capture output if required...
      debug "Running:'#{cmd}'"
      pid = nil
      if safe
        runner = SafeRunner.new(cmd, term_output, input)
      else
        # Something wrong with thread handling - no problem when not parsing returned text
        runner = Runner.new(cmd, term_output, input)
      end

      pid = runner.status
      if runner.status.success?
        if capture
          return runner.stdout
        end
        ok = true
      else
        if cmd.start_with?(CMD_KUBECTL)
          error = KubeCtlError.new(runner.status, cmd, runner.stderr, input)
          raise error if error.enough_already?(errors)
          errors << error
        else
          raise "Error running #{cmd}, exit code '#{runner.status.exitstatus}':\n#{runner.stderr}"
        end
      end
    end
    pid
  end

  def self.get_yaml_data(cmd)
    retries = 0
    yaml = nil
    until yaml || retries >= MISSING_DATA_RETRIES
      retries = retries + 1
      kb8_out = Kb8Run.run(cmd, true, false)
      debug "Loading YAML data from kubectl:\n#{kb8_out}"
      if kb8_out
        yaml = YAML.load(kb8_out)
        debug 'YAML loaded...'
      end
    end
    unless yaml
      raise "Cmd:#{cmd} failed to return any data for loading into YAML after #{MISSING_DATA_RETRIES} tries!"
    end
    yaml
  end

  def self.update_environment(env_name, server)
    # Add the config commands (read from the environments)
    cmd = CMD_CONFIG_CLUSTER % [env_name, server]
    Kb8Run.run(cmd, false, true)
    # Ensure a namespace compatible name...
    cmd = CMD_CONFIG_CONTEXT_SERVER % [env_name, env_name]
    Kb8Run.run(cmd, false, true)
    cmd = CMD_CONFIG_DEFAULT % LEGACY_CONTEXT_NAME
    Kb8Run.run(cmd, false, true)
  end

  def self.update_context(kb8_context)
    # Add the config commands (read from the environments)
    if kb8_context.user
      user_flag = " --user=#{kb8_context.user}"
    else
      user_flag = ''
    end
    # Create / update context entry
    cmd = CMD_CONFIG_CONTEXT % [kb8_context.name, kb8_context.cluster, kb8_context.namespace, user_flag]
    Kb8Run.run(cmd, false, true)
    # Set default context...
    cmd = CMD_CONFIG_DEFAULT % kb8_context.name
    Kb8Run.run(cmd, false, true)
  end

  def self.create(yaml_data)
    debug "Creating with:'#{yaml_data.to_s}'"
    Kb8Run.run(CMD_CREATE, true, true, yaml_data.to_s)
  end

  def self.replace(yaml_data)
    debug "Replacing with:'#{yaml_data.to_s}'"
    Kb8Run.run(CMD_REPLACE, true, true, yaml_data.to_s)
  end

  def self.rolling_update(yaml_data, old_controller)
    debug "Rolling update with:'#{yaml_data.to_s}'"
    cmd = CMD_ROLLING_UPDATE % old_controller
    Kb8Run.run(cmd, true, true, yaml_data.to_s, false)
  end

  def self.patch(patch_data, type, resource)
    patch_string = patch_data.to_json()
    debug "Patching #{patch_string}"
    cmd = CMD_PATCH_RESOURCE % [type, resource, patch_string]
    Kb8Run.run(cmd, false, false)
  end

  def self.delete_label(label, type, resource)
    debug "Deleting label #{label} from #{type}/#{resource}"
    cmd = CMD_LABEL_RESOURCE % [type, resource, "#{label}-"]
    Kb8Run.run(cmd, false, false)
  end

  def self.delete_pods(selector_string)
    debug "Deleting pods matching selectors:#{selector_string}"
    cmd = CMD_DELETE_PODS % [selector_string]
    Kb8Run.run(cmd, false, true)
  end

  def self.delete_resource(type, name, namespace=nil)
    debug "Deleting resource:#{type}/#{name}"
    namespace_flag = ''
    if namespace
      namespace_flag = NAMESPACE_FLAG % [namespace]
    end
    cmd = CMD_DELETE % [type, name, namespace_flag]
    Kb8Run.run(cmd, false, true)
  end

  def self.get_resource_data(type, all_namespaces=false, namespace=nil)
    debug "Getting resource data:#{type}"
    if all_namespaces
      cmd = CMD_GET_RESOURCE % [type, ' --all-namespaces=true ']
    else
      if namespace
        cmd = CMD_GET_RESOURCE % [type, " --namespace=#{namespace}"]
      else
        cmd = CMD_GET_RESOURCE % [type, '']
      end
    end
    yaml_data = Kb8Run.get_yaml_data(cmd)
    yaml_data
  end

  def self.get_pod_status(selector_string)
    # Allow a few retires here, to cope with no data:
    debug "Get pods with selectors: '#{selector_string}'"
    cmd = CMD_GET_POD % [selector_string]
    yaml_data = Kb8Run.get_yaml_data(cmd)
    yaml_data
  end

  def self.get_pod_logs(pod_name, container_name=nil)
    unless pod_name
      raise "Error - expecting a valid string for pod_name"
    end
    debug "Getting logs from kubectl:\n#{pod_name}"
    options = [pod_name]
    if container_name
      options << " -c #{container_name}"
    end
    cmd = CMD_GET_POD_LOGS % options
    kb8_out = Kb8Run.run(cmd, true, false)
    kb8_out
  end

  # Will get all events for a pod
  def self.get_pod_events(pod_name)
    unless pod_name
      raise 'Error - expecting a valid string for pod_name'
    end
    yaml = Kb8Run.get_yaml_data(CMD_GET_EVENTS)
    relevant_events = []
    # TODO: work out filters (selectors set by rc's don't work here!!!)
    yaml['items'].each do |event|
      if event['involvedObject'].nil?
        # Can't deal with this event...
        next
      else
        event_name = event['involvedObject']['name'].to_s
        if event_name == pod_name.to_s
          relevant_events << event unless event['lastTimestamp'].nil?
        end
      end
    end
    events_by_time = relevant_events.sort { |a, b| a['lastTimestamp'] <=> b['lastTimestamp'] }
    events_by_time
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@drawable/live_icon_live_room_closed_pressed" />
    <item android:state_enabled="false" android:drawable="@drawable/live_icon_live_room_closed_normal" />
    <item android:drawable="@drawable/live_icon_live_room_closed_normal" />
</selector>


text:
from datetime import datetime
import re

from sqlalchemy import (Column, Integer, String, Numeric, ForeignKey, Text,
                        Date, DateTime, Boolean)
from sqlalchemy.orm import relationship
from flask_login import UserMixin

from newbeercellar import db

RATEBEER_BASE_URL = "http://www.ratebeer.com/beer"

class User(db.Model, UserMixin):
    __tablename__ = "users"
    id = Column('user_id', Integer, primary_key=True)
    name = Column('name', String(50), unique=False)
    username = Column('username', String(50), unique=True)
    email = Column('email', String(50), unique=True)
    google_id = Column('google_id', String(50), unique=True, index=True)
    registered_on = Column('registered_on', DateTime)

    def __init__(self, name=None, google_id=None, email=None, username=None):
        self.name = name
        self.username = username
        self.email = email
        self.google_id = google_id
        self.registered_on = datetime.utcnow()

class Cellar(db.Model):
    __tablename__ = 'cellars'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False)
    user = relationship('User', lazy=False)
    bottles = relationship("Bottle")
    is_default = Column(Boolean, default=False)
    is_public = Column(Boolean, default=True)

    def __init__(self, name, user, is_default=False):
        self.name = name
        self.user = user
        self.is_default = is_default

def iso_or_none(date):
    if date is not None:
        return date.isoformat()
    return None

def parse_date(date):
    return date

class Bottle(db.Model):
    __tablename__ = 'bottles'

    id = Column(Integer, primary_key=True)
    amount = Column(Integer, nullable=False, default=1)
    size = Column(Numeric, nullable=True)
    comment = Column(Text, nullable=True)
    batch_no = Column(String, nullable=True)
    brew_date = Column(Date, nullable=True)
    best_before_date = Column(Date, nullable=True)
    date_added = Column(Date, nullable=False, default=datetime.now)
    date_removed = Column(Date, nullable=True)

    beer_id = Column(Integer, ForeignKey('rb_beers.id'), nullable=False)
    beer = relationship('RbBeer', lazy=False)

    cellar_id = Column(Integer, ForeignKey('cellars.id'), nullable=False)
    cellar = relationship('Cellar', lazy=False)

    def __init__(self, beer, cellar, data):
        self.beer = beer
        self.cellar = cellar
        self.update(data)

    def update(self, data):
        self.amount = data.get('amount', None)
        self.size = data.get('size', None)
        self.comment = data.get('comment', None)
        self.batch_no = data.get('batchNo', None)
        self.brew_date = parse_date(data.get('brewDate', None))
        self.best_before_date = parse_date(data.get('bbfDate', None))

    @property
    def serialize(self):
        return {
            "id": self.id,
            "breweryId": self.beer.brewery.id,
            "breweryName": self.beer.brewery.name,
            "beerId": self.beer.id,
            "beerName": self.beer.name,
            "batchNo": self.batch_no,
            "brewDate": iso_or_none(self.brew_date),
            "bbfDate": iso_or_none(self.best_before_date),
            "size": self.size,
            "amount": self.amount,
            "comment": self.comment,
            "added": iso_or_none(self.date_added),
            "removed": iso_or_none(self.date_removed),
            'ratebeerUrl': self.beer.ratebeer_url,
        }

class RbBrewery(db.Model):
    __tablename__ = 'rb_breweries'

    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)

    def __init__(self, name):
        assert(name is not None)
        assert(name != "")
        self.name = name

    @property
    def serialize(self):
        return {
            'id': self.id,
            'name': self.name,
        }

class RbBeer(db.Model):
    __tablename__ = 'rb_beers'

    id = Column(Integer, primary_key=True)
    name = Column(String(255), nullable=False)
    ratebeer_id = Column(Integer)
    short_name = Column(String(255), nullable=False)
    brewery_id = Column(Integer, ForeignKey("rb_breweries.id"), nullable=False)
    brewery = relationship("RbBrewery", lazy=False)
    rating = Column(Numeric, nullable=False)
    num = Column(Numeric, nullable=True)

    def __init__(self, ratebeer_id, name, short_name, brewery, rating, num):
        assert(brewery is not None)
        self.ratebeer_id = ratebeer_id
        self.name = name
        self.short_name = short_name
        self.brewery = brewery
        self.rating = rating
        self.num = num

    @property
    def serialize(self):
        return {
            'id': self.id,
            'name': self.name,
            'brewery': self.brewery.name,
            "breweryId": self.brewery.id,
        }

    @property
    def ratebeer_url(self):
        fixed_name = re.sub(
            '[^A-Za-z0-9\-]+',
            '',
            self.short_name.replace(' ', '-')
        )
        return "%s/%s/%s/" % (RATEBEER_BASE_URL, fixed_name, self.ratebeer_id)


text:
package com.app.dextrous.barbara.adapter;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.app.dextrous.barbara.R;
import com.app.dextrous.barbara.model.User;

import java.util.List;

import static com.app.dextrous.barbara.constant.BarbaraConstants.TAG;

public class UserArrayAdapter extends ArrayAdapter<User> {

    private final Context context;
    private final List<User> values;

    public UserArrayAdapter(Context context, List<User> values) {
        super(context, -1, values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.user_list_item_view, parent, false);
        TextView textView = (TextView) rowView.findViewById(R.id.firstLine);
        TextView textView2 = (TextView) rowView.findViewById(R.id.secondLine);
        User item = values.get(position);
        textView.setText(item.getFullName());
        // change the icon for Windows and iPhone
        textView2.setText(item.getSpeakerProfileId());
        Log.d(TAG, item.toString());
        return rowView;
    }

    @Override
    public long getItemId(int position) {
        return values.get(position).getId();
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

}


text:
using Newtonsoft.Json;

namespace Services.DTO.WeatherInCity
{
    public class Sys
    {
        [JsonProperty("type")]
        public int Type { get; set; }

        [JsonProperty("id")]
        public int Id { get; set; }

        [JsonProperty("message")]
        public double Message { get; set; }

        [JsonProperty("country")]
        public string Country { get; set; }

        [JsonProperty("sunrise")]
        public int Sunrise { get; set; }

        [JsonProperty("sunset")]
        public int Sunset { get; set; }
    }
}


text:
package co.cask.cdap.gateway.router;

import org.jboss.netty.handler.codec.http.HttpRequest;

/**
 * Applies rule that may change {@link HttpRequest} being forwarded
 */
public interface ProxyRule {
  HttpRequest apply(HttpRequest request);
}


text:
package org.jboss.netty.channel.socket.nio;

import static org.jboss.netty.channel.Channels.*;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.jboss.netty.channel.AbstractServerChannel;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.channel.ChannelFactory;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelSink;
import org.jboss.netty.channel.socket.DefaultServerSocketChannelConfig;
import org.jboss.netty.channel.socket.ServerSocketChannelConfig;
import org.jboss.netty.logging.InternalLogger;
import org.jboss.netty.logging.InternalLoggerFactory;

class NioServerSocketChannel extends AbstractServerChannel
                             implements org.jboss.netty.channel.socket.ServerSocketChannel {

    private static final InternalLogger logger =
        InternalLoggerFactory.getInstance(NioServerSocketChannel.class);

    final ServerSocketChannel socket;
    final Lock shutdownLock = new ReentrantLock();
    volatile Selector selector;
    private final ServerSocketChannelConfig config;

    NioServerSocketChannel(
            ChannelFactory factory,
            ChannelPipeline pipeline,
            ChannelSink sink) {

        super(factory, pipeline, sink);

        try {
            socket = ServerSocketChannel.open();
        } catch (IOException e) {
            throw new ChannelException(
                    "Failed to open a server socket.", e);
        }

        try {
            socket.configureBlocking(false);
        } catch (IOException e) {
            try {
                socket.close();
            } catch (IOException e2) {
                logger.warn(
                        "Failed to close a partially initialized socket.", e2);
            }

            throw new ChannelException("Failed to enter non-blocking mode.", e);
        }

        config = new DefaultServerSocketChannelConfig(socket.socket());

        fireChannelOpen(this);
    }

    public ServerSocketChannelConfig getConfig() {
        return config;
    }

    public InetSocketAddress getLocalAddress() {
        return (InetSocketAddress) socket.socket().getLocalSocketAddress();
    }

    public InetSocketAddress getRemoteAddress() {
        return null;
    }

    public boolean isBound() {
        return isOpen() && socket.socket().isBound();
    }

    @Override
    protected boolean setClosed() {
        return super.setClosed();
    }
}