text:
import threading
from OSC import *
from pymt import *

def binary(n, digits=8):
    '''
    Based on: http://www.daniweb.com/code/snippet216539.html
    '''
    data = '{0:0>{1}}'.format(bin(n)[2:], digits)
    return [int(x) for x in data]

class MTMonome(MTButtonMatrix):
    '''
    An pymt implementation of monome, based on MTButtonMatrix and SerialOSC.
    http://github.com/tehn/serialoscp
    http://monome.org/data/app/monomeserial/osc
    '''

    def __init__(self, **kwargs):
        kwargs.setdefault('matrix_size', (8,8))
        kwargs.setdefault('size', (400, 400))

        super(MTMonome, self).__init__(**kwargs)

        self.prefix = '/box'
        self.address = 'localhost'
        self.output_port = 8000
        self.input_port = 8080

        try:
            self.osc_client = OSCClient()
            self.osc_client.connect((self.address, self.output_port))
        except OSCClientError as e:
            print '[ERROR] OSCClient', e

        try:
            self.osc_server = OSCServer((self.address, self.input_port))
            self.osc_server.addDefaultHandlers()
            self.osc_server.addMsgHandler('default', self.osc_handler)
            self.server_thread = threading.Thread(target=self.osc_server.serve_forever)
            self.server_thread.start()
        except IOError as e:
            print '[ERROR] OSCServer', e

    def on_press(self, state):
        '''
        Send an osc message when a button is touched down an up
        state = (row, column, state)
        /prefix/press [x] [y] [state]
        state: 1 (down) or 0 (up)
        '''
        y = state[0]
        x = state[1]
        state = state[2]

        m = OSCMessage(self.prefix + '/press')
        m.append([y, (self.matrix_size[1]-1)-x, state])

        try:
            self.osc_client.send(m)
        except OSCClientError as e:
            print '[ERROR] OSCClient.send', e

    def on_touch_down(self, touch):
        if self.collide_point(touch.x, touch.y):
            i,j = self.collide_point(touch.x, touch.y)
            self.dispatch_event('on_value_change', self.matrix)
            self.dispatch_event('on_press', (i,j, 1))
            self.last_tile = (i,j)

    def on_touch_up(self, touch):
        if self.collide_point(touch.x, touch.y):
            i,j = self.collide_point(touch.x, touch.y)
            self.dispatch_event('on_value_change', self.matrix)
            self.dispatch_event('on_press', (i,j, 0))
            self.last_tile = (i,j)

    def osc_handler(self, addr, tags, data, client_address):
        '''
        Handle incoming messages
        '''

        print '[OSC]', addr, tags, data, client_address

        if addr == self.prefix + '/led':
            '''
            /prefix/led [x] [y] [state]
            state: 1 (on) or 0 (off)
            '''

            x = data[0]
            y = (self.matrix_size[1]-1)-data[1]
            state = data[2]

            self.matrix[x][y] = state

        elif addr == self.prefix + '/led_row':
            '''
            /prefix/led_row [row] [data]
            row: which row to update
            data: one byte of data (8 led positions)
            '''

            row = (self.matrix_size[1]-1)-data[0]
            data = binary(data[1]) #ex. [1,0,1,0,1,0,0,1]

            for i in range(self.matrix_size[1]):
                self.matrix[i][row] = data[i]

        elif addr == self.prefix + '/led_col':
            '''
            /prefix/led_col [col] [data]
            col: which column to update
            data: one byte of data (8 led positions)
            '''

            column = data[0]
            data = binary(data[1])

            self.matrix[column] = data

        elif addr == self.prefix + '/frame':
            '''
            /prefix/frame [A B C D E F G H]
            update a display, offset by x and y.
            '''

            self.matrix = [binary(y) for y in data]

        elif addr == self.prefix + '/clear':
            '''
            /prefix/clear [state]
            state: 0 (off, default if unspecified) or 1 (on)
            '''

            if len(data):
                self.clear(data[0])
            else:
                self.clear(0)

        #Sys Msgs
        elif addr == '/sys/prefix':
            '''
            /sys/prefix [string]
            change prefix to [string]

            Return:
            /sys/prefix [newprefix]
            '''

            prefix = data[0]
            self.prefix = prefix

            m = OSCMessage('/sys/press')
            m.append(self.prefix)

            try:
                self.osc_client.send(m)
            except OSCClientError as e:
                print '[ERROR] OSCClient.send', e

        elif addr == '/sys/cable':
            '''
            /sys/cable [left|up|right|down]
            changes cable setting for the unit
            '''

            pass

        elif addr == '/sys/offset':
            '''
            /sys/offset x y
            changes offset value for the unit
            '''

            pass

        elif addr == '/sys/intensity':
            '''
            /sys/intensity 0.
            changes unit intensity
            '''

            self.intensity(data[0])

        elif addr == '/sys/test':
            '''
            /sys/test [0|1]
            toggles test mode for the unit (turn on/off all leds)
            '''

            if data[0]:
                import time

                for i in range(9):
                    self.clear(i%2)
                    time.sleep(0.5)

        elif addr == '/sys/report':
            '''
            /sys/report
            Return:
            /sys/prefix
            /sys/cable
            /sys/offset
            '''

            pass

        return

    def clear(self, state):
        if state:
            self.matrix = [[1 for i in range(self.matrix_size[1])] for j in range(self.matrix_size[0])]
        else:
            self.reset()

    def intensity(self, intensity):
        r, g, b, i = self.downcolor
        self.downcolor = (r,g,b,intensity)

    def close(self):
        self.osc_client.close()
        self.osc_server.close()
        self.server_thread.join()

class MTScatterMonome(MTScatterWidget):

    def __init__(self, **kwargs):
        self.monome = MTMonome()
        kwargs.setdefault('size', (self.monome.width + 30, self.monome.height + 30))
        super(MTScatterMonome, self).__init__(**kwargs)
        self.monome.pos = (15 + self.monome.x, 15 + self.monome.y)
        self.add_widget(self.monome)

if __name__ == '__main__':

    additional_css = '''
    .simple {
            border-width: 3;
            draw-border: 1;
            bg-color:  rgb(100, 100, 200, 255);
            touch-color: rgba(100, 100, 250, 255);
    }

    .dois {
            border-width: 3;
            draw-border: 1;
            bg-color:  rgb(200, 100, 100, 255);
            touch-color: rgba(100, 100, 250, 255);
    }
    '''

    css_add_sheet(additional_css)

    window = MTWindow()

    #monome = MTMonome()
    #window.add_widget(monome)

    smonome = MTScatterMonome(cls=('simple'))
    window.add_widget(smonome)

    try:
        runTouchApp()
    except KeyboardInterrupt:
        #monome.close()
        smonome.monome.close()


text:
"""Module for ProcessIO event."""

from .running_process_event import RunningProcessEvent

class ProcessIO(RunningProcessEvent):
    """Event emitted when a process generates output on stdout or stderr, or if stdin is used."""

    name = 'launch.events.process.ProcessIO'

    def __init__(self, *, text: bytes, fd: int, **kwargs) -> None:
        """
        Create a ProcessIO event.

        Unmatched keyword arguments are passed to RunningProcessEvent, see it
        for details on those arguments.

        :param: text is the unicode data associated with the event
        :param: fd is an integer that indicates which file descriptor the text is from
        """
        super().__init__(**kwargs)
        self.__text = text
        self.__from_stdin = fd == 0
        self.__from_stdout = fd == 1
        self.__from_stderr = fd == 2

    @property
    def text(self) -> bytes:
        """Getter for text."""
        return self.__text

    @property
    def from_stdin(self) -> bool:
        """Getter for from_stdin."""
        return self.__from_stdin

    @property
    def from_stdout(self) -> bool:
        """Getter for from_stdout."""
        return self.__from_stdout

    @property
    def from_stderr(self) -> bool:
        """Getter for from_stderr."""
        return self.__from_stderr

redpajama_set_name: RedPajamaGithub


text:
<html>
<head>
<script src="base64.js" type="text/javascript"></script>
</head>
<body>
<pre>
<script>
var orig = "\u0000\u0000\u0000\u0001abcedeffsdfsdfs";
var b64 = window.btoa(orig);
var d = window.atob(b64);
document.writeln(orig);
document.writeln(b64);
document.writeln(base64.encode(orig));
document.writeln(base64.decode(b64));
</script>
</pre>
</body>
</html>


text:
<!DOCTYPE html>

    <meta charset="UTF-8"/>
    <title>User Edit</title>
    <link href="../static/tether/css/tether.min.css" th:href="@{/tether/css/tether.min.css}" rel="stylesheet"/>
    <link href="../static/bootstrap4a2/css/bootstrap.min.css" th:href="@{/bootstrap4a2/css/bootstrap.min.css}" rel="stylesheet"/>
    <link href="../static/font-awesome/css/font-awesome.min.css" th:href="@{/font-awesome/css/font-awesome.min.css}" rel="stylesheet"/>
    <link href="../static/app/css/style.css" th:href="@{/app/css/style.css}" rel="stylesheet"/>

        INSECURE USER ADMIN

                ユーザーリスト

                プロファイル変更

    <form action="user-edit" method="post">

            ユーザー名

                user name

            フルネーム

                <input type="text" class="form-control" name="fullname" th:value="${user.fullname}"/>

                <input type="submit" class="btn btn-primary" value="更新"/>

    </form>


text:
var Offshore = require('../../../lib/offshore'),
    assert = require('assert');

describe('Model', function() {
  describe('.toJSON()', function() {

    /////////////////////////////////////////////////////
    // TEST SETUP
    ////////////////////////////////////////////////////

    var collection, collection2;

    before(function(done) {
      var offshore = new Offshore();
      var Collection = Offshore.Collection.extend({
        connection: 'my_foo',
        tableName: 'person',
        attributes: {
          first_name: 'string',
          last_name: 'string',
          full_name: function() {
            return this.first_name + ' ' + this.last_name;
          },
          toJSON: function() {
            var obj = this.toObject();
            delete obj.last_name;
            return obj;
          }
        }
      });
      var Collection2 = Offshore.Collection.extend({
        connection: 'my_foo',
        tableName: 'person2',
        attributes: {
          first_name: {type: 'string', protected: true},
          last_name: 'string',
          full_name: function() {
            return this.first_name + ' ' + this.last_name;
          }
        }
      });

      offshore.loadCollection(Collection);
      offshore.loadCollection(Collection2);

      var connections = {
        'my_foo': {
          adapter: 'foobar'
        }
      };

      offshore.initialize({ adapters: { foobar: {} }, connections: connections }, function(err, colls) {
        if(err) done(err);
        collection = colls.collections.person;
        collection2 = colls.collections.person2;
        done();
      });
    });

    /////////////////////////////////////////////////////
    // TEST METHODS
    ////////////////////////////////////////////////////

    it('should be overridable', function() {
      var person = new collection._model({ first_name: 'foo', last_name: 'bar' });
      var obj = person.toJSON();

      assert(obj === Object(obj));
      assert(obj.first_name === 'foo');
      assert(!obj.last_name);
    });

    it('should remove any attributes marked as "protected"', function() {
      var person = new collection2._model({ first_name: 'foo', last_name: 'bar' });
      var obj = person.toJSON();

      assert(obj === Object(obj));
      assert(!obj.first_name);
      assert(obj.last_name == 'bar');
    });

  });
});


text:
UIKIT_EXTERN  NSString *const kBaseURL;
UIKIT_EXTERN NSInteger const kCommonMargin;
UIKIT_EXTERN CGFloat const kMenueBarHeight;
UIKIT_EXTERN CGFloat const kNavigationBarMaxY;
UIKIT_EXTERN CGFloat const kTabbarHeight;


text:
package ro.ubb.samples.structural.adapter;

class Adaptee {
    public void methodB() {
        System.out.println("methodB called");
    }
}


text:
import {onDomReady} from 'lin3s-event-bus';

class Panel {
  constructor(rootNode) {
    this.panel = rootNode;
    this.panelHeaders = this.panel.querySelectorAll('.panel__header');

    this.onClick = this.onClick.bind(this);

    Array.from(this.panelHeaders).forEach(panelHeader => panelHeader.addEventListener('click', this.onClick));
  }

  onClick(event) {
    event.preventDefault();

    this.panel.classList.toggle('panel--closed');
  }
}

const onReady = () => {
  const panels = document.querySelectorAll('.panel');

  if (panels.length === 0) {
    return;
  }

  Array.from(panels).forEach(panel => new Panel(panel));
};

onDomReady(onReady);


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cross-preferences</artifactId>
        <groupId>com.adobe.prefs</groupId>
        <version>0.2.3-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.adobe.prefs</groupId>
    <artifactId>prefs-testing</artifactId>

    <name>Preferences testing</name>

</project>


text:
<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::THEME,
    'frontend/Vendor_FrameworkThemeTest/custom_theme',
    __DIR__
);


text:
class GLTextureWork:public RefCount
{
    public:
        GLTextureWork();
        GLTextureWork(const char* vertex, const char* frag);
        virtual ~GLTextureWork();
        //Must in GL Thread
        virtual bool onPrepare();
        virtual void onDestroy();
        virtual void run(GLTexture* dst, std::vector<GLTexture*> sources);
        virtual bool onGenerateShader(std::ostream& vertex, std::ostream& frag) const {return false;}

        void setProgram(GPPtr<GLProgram> pro) {mShader = pro;}
        static void DefaultVertex(std::ostream& vertex);
        virtual void onUse(GLTexture* dst, std::vector<GLTexture*> sources, GLProgram* shader);
    private:
        GPPtr<GLProgram> mShader;
};
#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
 | Version 10.2
 | Copyright 2012 Esri
 |
 | Licensed under the Apache License, Version 2.0 (the "License");
 | you may not use this file except in compliance with the License.
 | You may obtain a copy of the License at
 |
 |    http://www.apache.org/licenses/LICENSE-2.0
 |
 | Unless required by applicable law or agreed to in writing, software
 | distributed under the License is distributed on an "AS IS" BASIS,
 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 | See the License for the specific language governing permissions and
 | limitations under the License.
-->
<!--
////////////////////////////////////////////////////////////////////////////////
//
// Read more about ArcGIS Viewer for Flex - http://links.esri.com/flexviewer
//
////////////////////////////////////////////////////////////////////////////////
-->
<configuration>
    <title>Community Planning</title>
    <subtitle>Your plan for a sustainable community</subtitle>
    <logo>assets/images/PL_logo.png</logo>
    <style>
        <colors>0xFFFFFF,0x333333,0x101010,0x000000,0xFFD700</colors>
        <alpha>0.8</alpha>
    </style>
    <!-- replace the following url with your own geometryservice -->
    <geometryservice url="http://tasks.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer" />

    <!-- UI elements -->
    <splashpage label="ArcGIS Viewer for Flex" config="widgets/Splash/CP_SplashWidget.xml" url="widgets/Splash/SplashWidget.swf"/>
    <widget left="10"  top="50"    config="widgets/Navigation/PL_NavigationWidget.xml" url="widgets/Navigation/NavigationWidget.swf"/>
    <widget right="20" top="55"    config="widgets/MapSwitcher/PL_MapSwitcherWidget.xml" url="widgets/MapSwitcher/MapSwitcherWidget.swf"/>
    <widget left="0"   top="0"     config="widgets/HeaderController/PL_HeaderControllerWidget.xml" url="widgets/HeaderController/HeaderControllerWidget.swf"/>

    <map wraparound180="true" initialextent="-9816892 5124514 -9812592 5127381" fullextent="-9816892 5124514 -9812592 5127381" top="40" addarcgisbasemaps="false">

      <basemaps>
        <layer label="Parcel" type="tiled" visible="true" alpha="1"
               url="http://yourserver/arcgis/rest/services/GeneralPurpose/MapServer"/>
        <layer label="Imagery" type="tiled" visible="false" alpha="1"
               url="http://yourserver/arcgis/rest/services/ImageryHybrid/MapServer"/>
      </basemaps>
    </map>

    <!-- widgets organized into widget containers that manage close/open etc -->
    <!-- supported layout property options: horizontal(default)|float|vertical|fix-->

      <widgetcontainer layout="float">

        <widget label="Create My Plan"
                left="100" top="50" preload="open"
                icon="widgets/CommunityPlanning/assets/images/MyPlan.png"
                config="widgets/CommunityPlanning/CommunityPlanningWidget.xml"
                url="widgets/CommunityPlanning/CommunityPlanningWidget.swf"/>

        <widget label="Community Impact" right="20" top="85"
                icon="widgets/CommunityImpact/assets/images/Pie.png"
                config="widgets/CommunityImpact/CommunityImpactWidget.xml"
                url="widgets/CommunityImpact/CommunityImpactWidget.swf"/>

        <widget label="Review My Plan"
                left="100" top="405"
                icon="widgets/ReviewPlan/assets/images/Review.png"
                config="widgets/ReviewPlan/ReviewPlanWidget.xml"
                url="widgets/ReviewPlan/ReviewPlanWidget.swf"/>

        <widget label="Share My Plan"
                right="20" top="80"
                config="widgets/SharePlan/SharePlanWidget.xml"
                icon="widgets/SharePlan/assets/images/Share.png"
                url="widgets/SharePlan/SharePlanWidget.swf"/>
      </widgetcontainer>

</configuration>


text:
package com.planet_ink.coffee_mud.Abilities.Skills;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("rawtypes")
public class Skill_Write extends StdSkill
{
	@Override public String ID() { return "Skill_Write"; }
	private final static String localizedName = CMLib.lang()._("Write");
	@Override public String name() { return localizedName; }
	@Override protected int canAffectCode(){return 0;}
	@Override protected int canTargetCode(){return Ability.CAN_ITEMS;}
	@Override public int abstractQuality(){return Ability.QUALITY_INDIFFERENT;}
	private static final String[] triggerStrings =_i(new String[] {"WRITE","WR"});
	@Override public String[] triggerStrings(){return triggerStrings;}
	@Override public int classificationCode(){return Ability.ACODE_SKILL|Ability.DOMAIN_CALLIGRAPHY;}
	@Override public int overrideMana(){return 0;}

	@Override
	public boolean invoke(MOB mob, Vector commands, Physical givenTarget, boolean auto, int asLevel)
	{
		if(mob.charStats().getStat(CharStats.STAT_INTELLIGENCE)<5)
		{
			mob.tell(_("You are too stupid to actually write anything."));
			return false;
		}
		if(commands.size()<1)
		{
			mob.tell(_("What would you like to write on?"));
			return false;
		}
		Item target=mob.fetchItem(null,Wearable.FILTER_UNWORNONLY,(String)commands.elementAt(0));
		if(target==null)
		{
			target=mob.location().findItem(null,(String)commands.elementAt(0));
			if((target!=null)&&(CMLib.flags().isGettable(target)))
			{
				mob.tell(_("You don't have that."));
				return false;
			}
		}
		if((target==null)||(!CMLib.flags().canBeSeenBy(target,mob)))
		{
			mob.tell(_("You don't see '@x1' here.",((String)commands.elementAt(0))));
			return false;
		}

		final Item item=target;
		if(((item.material()!=RawMaterial.RESOURCE_PAPER)
		   &&(item.material()!=RawMaterial.RESOURCE_SILK)
		   &&(item.material()!=RawMaterial.RESOURCE_HIDE)
		   &&(item.material()!=RawMaterial.RESOURCE_HEMP))
		||(!item.isReadable()))
		{
			mob.tell(_("You can't write on that."));
			return false;
		}

		if(item instanceof Scroll)
		{
			mob.tell(_("You can't write on a scroll."));
			return false;
		}

		if(CMParms.combine(commands,1).toUpperCase().startsWith("FILE="))
		{
			mob.tell(_("You can't write that."));
			return false;
		}

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);

		if(success)
		{
			final CMMsg msg=CMClass.getMsg(mob,target,this,CMMsg.MSG_WRITE,_("<S-NAME> write(s) on <T-NAMESELF>."),CMMsg.MSG_WRITE,CMParms.combine(commands,1),CMMsg.MSG_WRITE,_("<S-NAME> write(s) on <T-NAMESELF>."));
			if(mob.location().okMessage(mob,msg))
				mob.location().send(mob,msg);
		}
		else
			mob.location().show(mob,target,CMMsg.MSG_OK_VISUAL,_("<S-NAME> attempt(s) to write on <T-NAMESELF>, but mess(es) up."));
		return success;
	}

}


text:
@interface MBProgressHUD (TVAssistant)

-(void)showToastWithText:(NSString *)text;
-(void)showToastWithText:(NSString *)text whileExecutingBlock:(dispatch_block_t)block;
+(MBProgressHUD *)showToastToView:(UIView *)view withText:(NSString *)text;
+(MBProgressHUD *)showToastNoHideClearColorToView:(UIView *)view withText:(NSString *)text textColor:(UIColor *)textColor;

@end


text:
<?php

namespace Owl\Log;

abstract class AbstractWriter implements \Owl\Log\WriterInterface
{
    /**
     * Writer log levels
     */
    protected $levels = array();

    /**
     * Writer records
     */
    protected $records = array();

    /**
     * Writer options
     */
    protected $options = array();

    /**
     * Writer formatter
     */
    protected $formatter;

    /**
     * Records limit to commit them to writers
     */
    protected $recordsInterval = 1000;

    /**
     * Writer log levels
     */
    public function getLevels() {}

    /**
     * Writer log levels
     *
     * @param mixed $levels
     */
    public function setLevels($levels) {}

    /**
     * Writer records
     */
    public function getRecords() {}

    /**
     * Writer options
     */
    public function getOptions() {}

    /**
     * Writer options
     *
     * @param mixed $options
     */
    public function setOptions($options) {}

    /**
     * Records limit to commit them to writers
     */
    public function getRecordsInterval() {}

    /**
     * Records limit to commit them to writers
     *
     * @param mixed $recordsInterval
     */
    public function setRecordsInterval($recordsInterval) {}

    public function __destruct() {}

    /**
     * @inheritdoc
     * @param string $option
     * @param mixed $value
     */
    public function setOption($option, $value) {}

    /**
     * @inheritdoc
     * @param string $option
     */
    public function getOption($option) {}

    /**
     * @return \Owl\Log\FormatterInterface
     */
    protected function defaultFormatter() {}

    /**
     * @inheritdoc
     * @return \Owl\Log\FormatterInterface
     */
    public function getFormatter() {}

    /**
     * @param mixed $formatter
     */
    public function setFormatter($formatter) {}

    /**
     * @param mixed $record
     * @return string
     */
    protected function format(Record $record) {}

    /**
     * Filter records by levels
     *
     * @param array $records
     * @return array
     */
    protected function filterRecords($records) {}

    /**
     * @inheritdoc
     * @param array $records
     */
    public function commit($records) {}

    /**
     * @inheritdoc
     */
    public function push() {}

    /**
     * Write record
     *
     * @param string $record
     */
    abstract protected function write($record);

}


text:
std::map< std::string, std::pair< std::string, std::unique_ptr< sf::SoundBuffer > > >
    SoundManager::soundsMap;

sf::SoundBuffer& SoundManager::add( const std::string& alias, const std::string& filePath ) {
    auto it = soundsMap.find( alias );

    if( it != soundsMap.end() ) {
        return *it->second.second;
    }

    std::unique_ptr< sf::SoundBuffer > sound = std::make_unique< sf::SoundBuffer >();
    if( !sound->loadFromFile( DEFAULT_SOUND_PATH + filePath ) ) {
        std::string exception = "File " + ( DEFAULT_SOUND_PATH + filePath ) + " not found!";
        throw std::runtime_error( exception );
    }

    soundsMap.insert( std::make_pair( alias, std::make_pair( filePath, std::move( sound ) ) ) );

    return get( alias );
}

void SoundManager::remove( const std::string& alias ) {
    soundsMap.erase( alias );
}

sf::SoundBuffer& SoundManager::get( const std::string& alias ) {
    return *soundsMap[ alias ].second;
}


text:
echo "Launching 256!"
open index.html


text:
#ifndef QAUTHENTICATOR_H
#define QAUTHENTICATOR_H

#include <QtNetwork/qtnetworkglobal.h>
#include <QtCore/qstring.h>
#include <QtCore/qvariant.h>

QT_BEGIN_NAMESPACE

class QAuthenticatorPrivate;
class QUrl;

class Q_NETWORK_EXPORT QAuthenticator
{
public:
    QAuthenticator();
    ~QAuthenticator();

    QAuthenticator(const QAuthenticator &other);
    QAuthenticator &operator=(const QAuthenticator &other);

    bool operator==(const QAuthenticator &other) const;
    inline bool operator!=(const QAuthenticator &other) const { return !operator==(other); }

    QString user() const;
    void setUser(const QString &user);

    QString password() const;
    void setPassword(const QString &password);

    QString realm() const;
    void setRealm(const QString &realm);

    QVariant option(const QString &opt) const;
    QVariantHash options() const;
    void setOption(const QString &opt, const QVariant &value);

    bool isNull() const;
    void detach();
private:
    friend class QAuthenticatorPrivate;
    QAuthenticatorPrivate *d;
};

QT_END_NAMESPACE

#endif


text:
package com.interest.common.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName:SerializeUtils
 * @Date:2016-06-12 16:32:59
 * @Description:(序列化,反序列化对象)
 *
 */
public class SerializeUtils {
	private static final Logger logger = LoggerFactory.getLogger(SerializeUtils.class);

	/**
	 *
	 * @Title: serialize
	 * @Description: (获取对象序列化byte数组)
	 * @param object
	 * @return
	 */
	public static byte[] serialize(Object object) {
		byte[] bytes = null;

		if (null == object) {
			bytes = new byte[0];
		}

		if (!(object instanceof Serializable)) {
			throw new IllegalArgumentException(
					SerializeUtils.class.getSimpleName()
							+ " requires a Serializable object, but "
							+ object.getClass().getName()
							+ " not a Serializable object");
		}

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ObjectOutputStream oos;
		try {
			oos = new ObjectOutputStream(os);
			oos.writeObject(object);
			oos.flush();
			bytes = os.toByteArray();
		} catch (IOException e) {
			logger.error("Failed to serialize", e);
		}

		return bytes;
	}

	/**
	 *
	 * @Title: deserialize
	 * @Description: (将byte[]反序列化为对象)
	 * @param bytes
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static <T>T deserialize(byte[] bytes) {
		T object = null;

		if(!isEmpty(bytes)) {
			ByteArrayInputStream is = new ByteArrayInputStream(bytes);
			try {
				ObjectInputStream ois = new ObjectInputStream(is);
				object = (T) ois.readObject();
			} catch (IOException e) {
				logger.error("Failed to deserialize", e);
			} catch (ClassNotFoundException ex) {
				logger.error("Failed to deserialize object", ex);
			}
		}

		return object;
	}

	private static boolean isEmpty(byte[] bytes) {
			return (null == bytes || bytes.length == 0);
	}

}


text:
require "spec_helper"

RSpec.describe ElasticHelper::Aggregation::Aggs do
  describe '#build' do
    let(:agg1) { double(:agg1, block: Proc.new { |query| query.magg1 'myagg1' }) }
    let(:agg2) { double(:agg2, block: Proc.new { |query| query.magg2 'myagg2' }) }

    subject { ElasticHelper::Aggregation::Aggs.new }
    before do
      subject.add(agg1)
      subject.add(agg2)
    end

    it "builds the query" do
      query = JSON.parse(subject.build.target!)
      expect(query).to eq({"aggs"=>{"magg1"=>"myagg1", "magg2"=>"myagg2"}})
    end
  end
end


text:
namespace hashtable_test {

void using_empty_table()
{
    Value val, val2;
    set_hashtable(&val);

    copy(&val, &val2);
    touch(&val);
    hashtable_get(&val, &val2);
    set_null(&val);
}

void test_safe_copy()
{
    Value val1, val2;

    set_hashtable(&val1);
    set_int(hashtable_insert(&val1, temp_string("a")), 5);
    test_equals(&val1, "{'a' => 5}");

    copy(&val1, &val2);
    test_equals(&val2, "{'a' => 5}");
    test_assert(val1.value_data.ptr == val2.value_data.ptr);

    touch(&val1);
    set_int(hashtable_insert(&val1, temp_string("a")), 10);
    test_equals(&val1, "{'a' => 10}");
    test_equals(&val2, "{'a' => 5}");
    test_assert(val1.value_data.ptr != val2.value_data.ptr);
}

void test_mutable_hashtable_simple()
{
    Value val;
    set_mutable_hashtable(&val);
    set_int(hashtable_insert(&val, temp_string("a")), 5);
}

void test_mutable_hashtable()
{
    Value val1, val2;

    set_mutable_hashtable(&val1);
    set_int(hashtable_insert(&val1, temp_string("a")), 5);
    test_equals(&val1, "{'a' => 5}");

    copy(&val1, &val2);
    touch(&val1);
    set_int(hashtable_insert(&val1, temp_string("a")), 10);
    test_equals(&val1, "{'a' => 10}");
    test_equals(&val2, "{'a' => 10}");
}

void test_get_keys()
{
    Value table;
    set_hashtable(&table);
    set_int(hashtable_insert(&table, temp_string("a")), 1);
    set_int(hashtable_insert(&table, temp_string("b")), 2);
    set_int(hashtable_insert(&table, temp_string("c")), 3);

    Value keys;
    hashtable_get_keys(&table, &keys);
    test_equals(&keys, "['a', 'b', 'c']");
}

void test_hashtable_iterator()
{
    Value table;
    set_hashtable(&table);
    set_int(hashtable_insert(&table, temp_string("a")), 1);
    set_int(hashtable_insert(&table, temp_string("b")), 2);
    set_int(hashtable_insert(&table, temp_string("c")), 3);

    Value table2;
    set_hashtable(&table2);

    for (HashtableIterator it(&table); it; ++it) {
        set_value(hashtable_insert(&table2, it.currentKey()), it.current());
    }

    test_assert(equals(&table, &table2));
}

void register_tests()
{
    REGISTER_TEST_CASE(hashtable_test::using_empty_table);
    REGISTER_TEST_CASE(hashtable_test::test_safe_copy);
    REGISTER_TEST_CASE(hashtable_test::test_mutable_hashtable_simple);
    REGISTER_TEST_CASE(hashtable_test::test_mutable_hashtable);
    REGISTER_TEST_CASE(hashtable_test::test_get_keys);
    REGISTER_TEST_CASE(hashtable_test::test_hashtable_iterator);
}

} // namespace hashtable_test


text:
package Servlet;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Integracion.BaseDeDatos;
import logicaDeNegocios.Curso;
import logicaDeNegocios.Subtema;
import logicaDeNegocios.Tema;

/**
 * Servlet implementation class ServletCargarDatsTema
 */
@WebServlet("/ServletCargarDatsTema")
public class ServletCargarDatsTema extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletCargarDatsTema() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String codigoTema = request.getParameter("selCodigo");
		BaseDeDatos bd = new BaseDeDatos();
		String nombreTema = bd.SelectPorCodigoTema(codigoTema);
		request.setAttribute("texto", nombreTema);
		ArrayList<Tema> temas = bd.selectTema();
		request.setAttribute("ListTemas", temas);
		request.setAttribute("Tema", codigoTema);
		ArrayList<Curso> cursos = bd.selectCurso();
		request.setAttribute("ListCursos", cursos);
		request.getRequestDispatcher("ActualizarTema.jsp").forward(request, response);
	}

}


text:
using namespace blackhole;

/// As always specify severity enumeration.
enum severity {
    debug   = 0,
    info    = 1,
    warning = 2,
    error   = 3
};

auto main(int argc, char** argv) -> int {
    if (argc != 2) {
        std::cerr << "Usage: 3.config PATH" << std::endl;
        return 1;
    }

    /// Here we are going to build the logger using registry. The registry's responsibility is to
    /// track registered handlers, formatter and sinks, but for now we're not going to register
    /// anything else, since there are predefined types.
    auto log = blackhole::registry::configured()
        /// Specify the concrete builder type we want to use. It may be JSON, XML, YAML or whatever
        /// else.
        ->builder<blackhole::config::json_t>(std::ifstream(argv[1]))
            /// Build the logger named "root".
            .build("root");

    log.log(severity::debug, "GET /static/image.png HTTP/1.1 404 347");
    log.log(severity::info, "nginx/1.6 configured");
    log.log(severity::warning, "client stopped connection before send body completed");
    log.log(severity::error, "file does not exist: /var/www/favicon.ico");

    return 0;
}


text:
package org.jnode.xmpp.commands;

/**
 * Пустой "процессор" для еще несделанных фич
 *
 * @author kreon
 *
 */
public class DummyCommandProcessor implements CommandProcessor {

	@Override
	public String process(String command) {
		return "Not realized yet";
	}

}


text:
<?php

namespace BCRM\BackendBundle\Entity\Event;

use Doctrine\ORM\EntityRepository;
use PhpOption\None;
use PhpOption\Option;
use PhpOption\Some;
use Symfony\Component\Config\Definition\Exception\Exception;

class DoctrineTicketRepository extends EntityRepository implements TicketRepository
{
    /**
     * @param Event $event
     *
     * @return Ticket[]
     */
    public function getToNotify(Event $event)
    {
        return $this->createQueryBuilder('t')
            ->andWhere('t.event = :event')->setParameter('event', $event)
            ->andWhere('t.notified = 0')
            ->andWhere('t.payment IS NOT NULL')
            ->getQuery()
            ->getResult();
    }

    /**
     * @param Event  $event
     * @param string $email
     *
     * @return Ticket[]
     */
    public function getTicketsForEmail(Event $event, $email)
    {
        return $this->createQueryBuilder('t')
            ->andWhere('t.event = :event')->setParameter('event', $event)
            ->andWhere('t.email = :email')->setParameter('email', $email)
            ->getQuery()
            ->getResult();
    }

    /**
     * @param integer $id
     * @param string  $code
     *
     * @return Option
     */
    public function getTicketByIdAndCode($id, $code)
    {
        return Option::fromValue($this->createQueryBuilder('t')
            ->andWhere('t.id = :id')->setParameter('id', $id)
            ->andWhere('t.code = :code')->setParameter('code', $code)
            ->getQuery()
            ->getOneOrNullResult());
    }

    /**
     * @param Event $event
     *
     * @return Ticket[]
     */
    public function getTicketsForEvent(Event $event)
    {
        return $this->createQueryBuilder('t')
            ->andWhere('t.event = :event')->setParameter('event', $event)
            ->getQuery()
            ->getResult();
    }

    /**
     * Returns the number of tickets for the given day.
     *
     * @param Event $event
     * @param       $day
     *
     * @return mixed
     */
    public function getTicketCountForEvent(Event $event, $day)
    {
        return $this->createQueryBuilder('t')
            ->select('COUNT(t.id)')
            ->andWhere('t.event = :event')->setParameter('event', $event)
            ->andWhere('t.day = :day')->setParameter('day', $day)
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * Returns the number of checkins for the given day.
     *
     * @param Event $event
     * @param       $day
     *
     * @return mixed
     */
    public function getCheckinCountForEvent(Event $event, $day)
    {
        return $this->createQueryBuilder('t')
            ->select('COUNT(t.id)')
            ->andWhere('t.event = :event')->setParameter('event', $event)
            ->andWhere('t.day = :day')->setParameter('day', $day)
            ->andWhere('t.checkedIn IS NOT NULL')
            ->getQuery()
            ->getSingleScalarResult();
    }

    /**
     * Returns the list of unprinted tickets for the given day.
     *
     * @param Event $event
     * @param       $day
     *
     * @return Ticket[]
     */
    public function getUnprintedTickets(Event $event, $day)
    {
        return $this->createQueryBuilder('t')
            ->andWhere('t.event = :event')->setParameter('event', $event)
            ->andWhere('t.day = :day')->setParameter('day', $day)
            ->andWhere('t.checkedIn IS NOT NULL')
            ->andWhere('t.printed = 0')
            ->getQuery()
            ->getResult();
    }

    /**
     * Search tickets matching the given term
     *
     * @param Event $event
     * @param       $day
     * @param       $term
     *
     * @return mixed
     */
    public function searchTickets(Event $event, $day, $term)
    {
        $qb = $this->createQueryBuilder('t');
        return $qb
            ->andWhere('t.event = :event')->setParameter('event', $event)
            ->andWhere('t.day = :day')->setParameter('day', $day)
            ->andWhere($qb->expr()->orX(
                $qb->expr()->like('t.name', ':term'),
                $qb->expr()->like('t.code', ':term'),
                $qb->expr()->like('t.email', ':term')
            ))->setParameter('term', '%' . $term . '%')
            ->getQuery()
            ->getResult();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using SAHB.GraphQLClient.FieldBuilder;

namespace SAHB.GraphQLClient.Internal
{
    internal class Helper
    {
        internal static IEnumerable<GraphQLField> GetFilteredSelectionSet(IEnumerable<GraphQLField> selectionSet, Func<GraphQLField, bool> filter)
        {
            if (filter == null)
                return selectionSet;

            var filteredSelectionSet = selectionSet.Where(filter);
            return filteredSelectionSet;
        }

        internal static IDictionary<string, IEnumerable<GraphQLFieldArguments>> GetAllArgumentsFromFields(IEnumerable<GraphQLField> selectionSet, Func<GraphQLField, bool> filter)
        {
            var dictionary = new Dictionary<string, IEnumerable<GraphQLFieldArguments>>();
            GetAllArgumentsFromFields(selectionSet, filter, dictionary, null);
            return dictionary;
        }

        private static void GetAllArgumentsFromFields(IEnumerable<GraphQLField> selectionSet, Func<GraphQLField, bool> filter, Dictionary<string, IEnumerable<GraphQLFieldArguments>> dictionary, string path)
        {
            foreach (var field in GetFilteredSelectionSet(selectionSet, filter))
            {
                var currentPathPart = field.Alias ?? field.Field;
                var fieldPath = path == null ?
                    currentPathPart :
                    string.Join(".", path, currentPathPart);

                // Get arguments
                List<GraphQLFieldArguments> arguments = new List<GraphQLFieldArguments>();

                // Add all arguments
                if (field?.Arguments.Any() ?? false)
                {
                    arguments.AddRange(field.Arguments);
                }

                // Add all directive arguments
                if (field?.Directives.Any() ?? false)
                {
                    foreach (var directive in field.Directives)
                    {
                        if (directive.Arguments?.Any() ?? false)
                        {
                            arguments.AddRange(directive.Arguments);
                        }
                    }
                }

                if (arguments.Any())
                {
                    dictionary.Add(fieldPath, arguments);
                }

                // Add all arguments from selectionSet (added by providing same dictionary)
                GetAllArgumentsFromFields(field.SelectionSet, null, dictionary, fieldPath);
            }
        }
    }
}


text:
package at.arz.latte.rodeo.scm;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 * Session Bean implementation class ScmAdmin
 */
@Stateless
@LocalBean
public class ScmRepository {

	@PersistenceContext(unitName = "latte-rodeo")
	private EntityManager entityManager;

	public void create(Scm scm) {
		entityManager.persist(scm);
	}

	public List<Scm> findByLocation(ScmLocation location) {
		TypedQuery<Scm> query = entityManager.createNamedQuery(Scm.FIND_BY_LOCATION, Scm.class);
		query.setParameter("location", location);
		List<Scm> list = query.getResultList();
		return list;
	}

	public List<Scm> findByLocationOrName(ScmLocation location, ScmName name) {
		TypedQuery<Scm> query = entityManager.createNamedQuery(Scm.FIND_BY_LOCATION_OR_NAME, Scm.class);
		query.setParameter("location", location);
		query.setParameter("name", name);
		List<Scm> list = query.getResultList();
		return list;
	}

}


text:
define(["dojo/_base/declare","dojox/data/CssRuleStore"],
  function(declare, CssRuleStore) {

return declare("dojox.data.CssClassStore", CssRuleStore, {
	// summary:
	//		Basic store to display CSS information.
	// description:
	//		The CssClassStore allows users to get information about active Css classes in the page running the CssClassStore.
	//		It can also filter out classes from specific stylesheets.  The attributes it exposes on classes are as follows:
	//
	//		- class:		The classname, including the '.'.
	//		- classSans:	The classname without the '.'.

	// _labelAttribute:
	//		text representation of the Item [label and identifier may need to stay due to method names]
	_labelAttribute: 'class',

	_idAttribute: 'class',
	_cName: "dojox.data.CssClassStore",

	getFeatures: function(){
		// summary:
		//		See dojo/data/api/Read.getFeatures()
		return {
			"dojo.data.api.Read" : true,
			"dojo.data.api.Identity" : true
		};
	},

	getAttributes: function(item){
		// summary:
		//		See dojo/data/api/Read.getAttributes()
		this._assertIsItem(item);
		return ['class', 'classSans'];
	},

	getValue: function(item, attribute, defaultValue){
		// summary:
		//		See dojo/data/api/Read.getValue()
		var values = this.getValues(item, attribute);
		if(values && values.length > 0){
			return values[0];
		}
		return defaultValue;
	},

	getValues: function(item, attribute){
		// summary:
		//		See dojo/data/api/Read.getValues()
		this._assertIsItem(item);
		this._assertIsAttribute(attribute);
		var value = [];
		if(attribute === "class"){
			value = [item.className];
		}else if(attribute === "classSans"){
			value = [item.className.replace(/\./g,'')];
		}
		return value;
	},

	_handleRule: function(rule, styleSheet, href){
		// summary:
		//		Handles the creation of an item based on the passed rule.  In this store, this implies
		//		parsing out all available class names.
		var obj = {};
		var s = rule['selectorText'].split(" ");
		for(var j=0; j<s.length; j++){
			var tmp = s[j];
			var first = tmp.indexOf('.');
			if(tmp && tmp.length > 0 && first !== -1){
				var last = tmp.indexOf(',') || tmp.indexOf('[');
				tmp = tmp.substring(first, ((last !== -1 && last > first)?last:tmp.length));
				obj[tmp] = true;
			}
		}
		for(var key in obj){
			if(!this._allItems[key]){
				var item = {};
				item.className = key;
				item[this._storeRef] = this;
				this._allItems[key] = item;
			}
		}
	},

	_handleReturn: function(){
		// summary:
		//		Handles the return from a fetching action.  Delegates requests to act on the resulting
		//		item set to eitehr the _handleFetchReturn or _handleFetchByIdentityReturn depending on
		//		where the request originated.
		var _inProgress = [];

		var items = {};
		for(var i in this._allItems){
			items[i] = this._allItems[i];
		}
		var requestInfo;
		// One-level deep clone (can't use dojo.clone, since we don't want to clone all those store refs!)
		while(this._pending.length){
			requestInfo = this._pending.pop();
			requestInfo.request._items = items;
			_inProgress.push(requestInfo);
		}

		while(_inProgress.length){
			requestInfo = _inProgress.pop();
			if(requestInfo.fetch){
				this._handleFetchReturn(requestInfo.request);
			}else{
				this._handleFetchByIdentityReturn(requestInfo.request);
			}
		}
	},

	_handleFetchByIdentityReturn: function(request){
		// summary:
		//		Handles a fetchByIdentity request by finding the correct item.
		var items = request._items;
		// Per https://bugs.webkit.org/show_bug.cgi?id=17935 , Safari 3.x always returns the selectorText
		// of a rule in full lowercase.
		var item = items[request.identity];
		if(!this.isItem(item)){
			item = null;
		}
		if(request.onItem){
			var scope = request.scope || dojo.global;
			request.onItem.call(scope, item);
		}
	},

	/* Identity API */
	getIdentity: function(/* item */ item){
		// summary:
		//		See dojo/data/api/Identity.getIdentity()
		this._assertIsItem(item);
		return this.getValue(item, this._idAttribute);
	},

	getIdentityAttributes: function(/* item */ item){
		// summary:
		//		See dojo/data/api/Identity.getIdentityAttributes()
		this._assertIsItem(item);
		return [this._idAttribute];
	},

	fetchItemByIdentity: function(/* request */ request){
		// summary:
		//		See dojo/data/api/Identity.fetchItemByIdentity()
		request = request || {};
		if(!request.store){
			request.store = this;
		}
		if(this._pending && this._pending.length > 0){
			this._pending.push({request: request});
		}else{
			this._pending = [{request: request}];
			this._fetch(request);
		}
		return request;
	}
});

});


text:
droid_bites
===========

My Little Android Exercises


text:
/* eslint-disable no-constant-condition */
import { take } from 'redux-saga/effects';
import { history } from '../../services';
import * as actions from './actions';

/**
 ****************************** WATCHERS ***********************************
 *
 **/

// trigger router navigation via history
export function* watchNavigate() {
  while (true) {
    const { pathname } = yield take(actions.NAVIGATE);
    yield history.push(pathname);
  }
}

export default {
  watchNavigate
};


text:
<?php namespace Powerplanetonline\LogViewer\Contracts;

/**
 * Interface  Patternable
 *
 * @package   Powerplanetonline\LogViewer\Contracts
 * @author    ARCANEDEV <arcanedev.maroc@gmail.com>
 */
interface Patternable
{
    /* ------------------------------------------------------------------------------------------------
     |  Getters & Setters
     | ------------------------------------------------------------------------------------------------
     */
    /**
     * Get the log pattern.
     *
     * @return string
     */
    public function getPattern();

    /**
     * Set the log pattern.
     *
     * @param  string  $date
     * @param  string  $prefix
     * @param  string  $extension
     *
     * @return self
     */
    public function setPattern(
        $prefix    = FilesystemInterface::PATTERN_PREFIX,
        $date      = FilesystemInterface::PATTERN_DATE,
        $extension = FilesystemInterface::PATTERN_EXTENSION
    );
}


text:
package com.levien.synthesizer.android.widgets.waveform;

import com.levien.synthesizer.core.model.WaveformInput;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * WaveformRowView is like a WaveformView, but it arranges its buttons in a row.
 */
public class WaveformRowView extends WaveformView {
  /** Basic constructor for an Android widget. */
  public WaveformRowView(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  /**
   * Touch event handler.
   */
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    int action = event.getAction();
    switch (action) {
      case MotionEvent.ACTION_DOWN: {
        getDrawingRect(rect_);
        double x = (event.getX() - rect_.left) / rect_.width();
        if (x < 1.0/6.0f) {
          setWaveform(WaveformInput.SINE);
        } else if (x < 2.0/6.0f) {
          setWaveform(WaveformInput.TRIANGLE);
        } else if (x < 3.0/6.0f) {
          setWaveform(WaveformInput.SQUARE);
        } else if (x < 4.0/6.0f) {
          setWaveform(WaveformInput.SAWTOOTH);
        } else if (x < 5.0/6.0f) {
          setWaveform(WaveformInput.NOISE);
        } else {
          CharSequence[] items = new CharSequence[input_.getWaveformCount()];
          for (int i = 0; i < items.length; ++i) {
            items[i] = input_.getWaveform(i);
          }
          AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
          builder.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
              setWaveform(input_.getWaveform(which));
            }
          });
          builder.create().show();
        }
        invalidate();
        break;
      }

      case MotionEvent.ACTION_MOVE: {
        break;
      }

      case MotionEvent.ACTION_UP: {
        break;
      }
    }
    return true;
  }

  /**
   * Drawing handler.
   */
  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    getDrawingRect(rect_);
    rect_.set(rect_);

    paint_.setColor(Color.BLACK);
    paint_.setStyle(Paint.Style.FILL);
    canvas.drawRect(rect_, paint_);

    // Draw waveforms.
    float lineWidth = 5.0f;
    float margin = 15.0f;
    float waveWidth = (rect_.width() - 7.0f * margin) / 6.0f;
    float waveHeight = (rect_.height() - 2.0f * margin);

    float xOffset = margin;
    float yOffset = margin;
    drawSine(canvas, xOffset, yOffset, waveWidth, waveHeight, margin, lineWidth);
    xOffset += waveWidth;
    xOffset += margin;
    drawTriangle(canvas, xOffset, yOffset, waveWidth, waveHeight, margin, lineWidth);
    xOffset += waveWidth;
    xOffset += margin;
    drawSquare(canvas, xOffset, yOffset, waveWidth, waveHeight, margin, lineWidth);
    xOffset += waveWidth;
    xOffset += margin;
    drawSawtooth(canvas, xOffset, yOffset, waveWidth, waveHeight, margin, lineWidth);
    xOffset += waveWidth;
    xOffset += margin;
    drawNoise(canvas, xOffset, yOffset, waveWidth, waveHeight, margin, lineWidth);
    xOffset += waveWidth;
    xOffset += margin;
    drawOther(canvas, xOffset, yOffset, waveWidth, waveHeight, margin, lineWidth);
  }

  /**
   * Layout measurement for this widget.
   * This method just sets a basic minimum size and makes the width maximized otherwise.
   */
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width = 0;
    int height = 0;

    switch (widthMode) {
      case MeasureSpec.EXACTLY:
        width = widthSize;
        break;
      case MeasureSpec.AT_MOST:
        width = widthSize;
        break;
      case MeasureSpec.UNSPECIFIED:
        width = 10;
        break;
    }

    switch (heightMode) {
      case MeasureSpec.EXACTLY:
        height = heightSize;
        break;
      case MeasureSpec.AT_MOST:
        height = 150;
        break;
      case MeasureSpec.UNSPECIFIED:
        height = 10;
        break;
    }

    setMeasuredDimension(width, height);
  }
}


text:
package analytics

import "testing"

func TestGroupMissingGroupId(t *testing.T) {
	group := Group{
		UserId: "1",
	}

	if err := group.Validate(); err == nil {
		t.Error("validating an invalid group object succeeded:", group)

	} else if e, ok := err.(FieldError); !ok {
		t.Error("invalid error type returned when validating group:", err)

	} else if e != (FieldError{
		Type:  "analytics.Group",
		Name:  "GroupId",
		Value: "",
	}) {
		t.Error("invalid error value returned when validating group:", err)
	}
}

func TestGroupMissingUserId(t *testing.T) {
	group := Group{
		GroupId: "1",
	}

	if err := group.Validate(); err == nil {
		t.Error("validating an invalid group object succeeded:", group)

	} else if e, ok := err.(FieldError); !ok {
		t.Error("invalid error type returned when validating group:", err)

	} else if e != (FieldError{
		Type:  "analytics.Group",
		Name:  "UserId",
		Value: "",
	}) {
		t.Error("invalid error value returned when validating group:", err)
	}
}

func TestGroupValidWithUserId(t *testing.T) {
	group := Group{
		GroupId: "1",
		UserId:  "2",
	}

	if err := group.Validate(); err != nil {
		t.Error("validating a valid group object failed:", group, err)
	}
}

func TestGroupValidWithAnonymousId(t *testing.T) {
	group := Group{
		GroupId:     "1",
		AnonymousId: "2",
	}

	if err := group.Validate(); err != nil {
		t.Error("validating a valid group object failed:", group, err)
	}
}


text:
<!DOCTYPE html>

<?php
function getFullDay($day) {
    if ($day == "Mon") {
        return "Monday";
    } else if ($day == "Tue") {
        return "Tuesday";
    } else if ($day == "Wed") {
        return "Wednesday";
    } else if ($day == "Thur") {
        return "Thursday";
    } else if ($day == "Fri") {
        return "Friday";
    }
}
?>

        <meta charset="UTF-8">
        <title>TiTaMa</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
        <meta name="description" content="A web time table manager">

        <meta name="theme-color" content="#3f51b5">

        <link rel="manifest" href="manifest.json">

        <meta name="msapplication-TileColor" content="#3f51b5">

        <meta name="mobile-web-app-capable" content="yes">
        <meta name="application-name" content="TiTaMa">
        <meta rel="icon" sizes="192x192" href="images/touch/chrome-touch-icon-192x192.png">

        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">
        <meta name="apple-mobile-web-app-title" content="TiTaMa">
        <link rel="apple-touch-icon" href="images/touch/apple-touch-icon.png">

        <meta name="msapplication-TileImage" content="images/touch/ms-touch-icon-144x144.png">

        <link href='//fonts.googleapis.com/css?family=Roboto:400,600,300,700' rel='stylesheet' type='text/css'>
        <link rel="stylesheet" type="text/css" href="./res/titama.css" />

            TiTaMa

<?php
include './res/php/config.php';
if (isset($_GET['add'])) {
    $conn = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
    $name = $_POST['name'];
    $kind = $_POST['kind'];
    $room = $_POST['room'];
    $day = $_POST['day'];
    $time = $_POST['time'];
    $prof = $_POST['prof'];
    if ($conn->error) {
?>

Error

<?php
        die("Failed to connect to the database: " . $conn->error);
?>

<?php
    }
    $sql = "INSERT INTO Titama (name, kind, room, day, time, prof)
        VALUES('$name', '$kind', '$room', '$day', '$time', '$prof')";
    if ($conn->query($sql) === TRUE) {
?>

Success

<?php
        echo "The new course was created successfully.";
?>

                    OK

<?php
    } else {
?>

Error

<?php
        echo "Error:" . $sql . "
" . $conn->error;
?>

                    OK

<?php
    }
}

if (isset($_GET['change'])) {
    $conn = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
    $userid = $_POST['userid'];
    $name = $_POST['name'];
    $kind = $_POST['kind'];
    $room = $_POST['room'];
    $day = $_POST['day'];
    $time = $_POST['time'];
    $prof = $_POST['prof'];
    if ($conn->error) {
?>

Error

<?php
        die("Failed to connect to the database: " . $conn->error);
?>

                    OK

<?php
    }
    $sql = "UPDATE Titama SET name='$name',kind='$kind',room='$room',day='$day',time='$time',prof='$prof' WHERE id=$userid";
    if ($conn->query($sql)) {
?>

Success

<?php
        echo "Course successfully updated";
?>

                    OK

<?php
    } else {
?>

Error

<?php
        echo "Some error occured. SQL: " . $sql . "
 ERROR: " . $conn->error;
?>

                    OK

<?php
    }
}

if (isset($_GET['del'])) {
    $userid = $_POST['userid'];
    $conn = new mysqli($conn, $dbuser, $dbpassword, $dbname);
    if ($conn->error) {
?>

Error

<?php
        die("Failed to connect to the database: " . $conn->error);
?>

                    OK

<?php
    }
    $sql = "DELETE FROM Titama WHERE id=$userid";
    $results = $conn->query($sql);
    if ($conn->query($sql)) {
?>

Success

<?php
        echo "Course successfully deleted";
?>

                    OK

<?php
    } else {
?>

Error

<?php
        echo "Some error occured. SQL: " . $sql . "
 ERROR: " . $conn->error;
?>

                    OK

<?php
    }
}

$conn = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
if ($conn->error) {
?>

Error

<?php
    die("Failed to connect to the database: " . $conn->error);
?>

                    OK

<?php
}
$days = array("Mon", "Tue", "Wed", "Thur", "Fri");
foreach ($days as $day) {
    $sql = "SELECT * FROM Titama WHERE day='$day'";
    $res = $conn->query($sql);
    if ($res->num_rows > 0) {
?>

<?php echo getFullDay($day) ?>

<?php
        $courses = array();
        $result = $conn->query($sql);
        while ($row = $result->fetch_assoc()) {
            $courses[] = $row;
        }
        usort($courses, function($a, $b) {
            return $a["time"] - $b["time"];
        });
        foreach ($courses as $course) {
?>

    <div class="c_name" id="c_name_<?php echo $course["id"] ?>"><?php echo $course["name"]; ?>

<?php echo $course["time"]; ?>:00

Id: <?php echo $course["id"]; ?>

Kind: <?php echo $course["kind"]; ?>

Place: <?php echo $course["room"]; ?>

Prof: <?php echo $course["prof"]; ?>

<?php
        }
    }
?>

<?php
}
include './res/php/closedb.php';
?>

Add new course

                <form action="?add=1" method="post">

Name:
<input name="name" class="itextfield"/>

Kind:
<input name="kind" class="itextfield"/>

Room:
<input name="room" class="itextfield"/>

Day:
<input name="day" class="itextfield"/>

Starts at:
<input name="time" class="itextfield"/>

Prof:
<input name="prof" class="itextfield"/>

                    <input type="submit" class="button" value="ADD"/>
                </form>

Change course

                <form action="?change=1" method="post">

Course ID:
<input name="userid" id="change_id" class="itextfield"/>

Name:
<input name="name" id="change_name" class="itextfield"/>

Kind:
<input name="kind" id="change_kind" class="itextfield"/>

Room:
<input name="room" id="change_room" class="itextfield"/>

Day:
<input name="day" id="change_day" class="itextfield"/>

Starts at:
<input name="time" id="change_time" class="itextfield"/>

Prof:
<input name="prof" id="change_prof" class="itextfield"/>

                    <input type="submit" class="button" value="CHANGE" />
                </form>

Delete course

                <form action="?del=1" method="post">

Course ID:
<input name="userid" class="itextfield"/>

                    <input type="submit" class="button" value="DELETE" />
                </form>

Marcel Kapfer (mmk2410) - 2015-2016


text:
int ANTLR3_CDECL
main	(int argc, char *argv[])
{
    // Now we declare the ANTLR related local variables we need.
    // Note that unless you are convinced you will never need thread safe
    // versions for your project, then you should always create such things
    // as instance variables for each invocation.
    // -------------------

    // Name of the input file. Note that we always use the abstract type pANTLR3_UINT8
    // for ASCII/8 bit strings - the runtime library garauntees that this will be
    // good on all platforms. This is a general rule - always use the ANTLR3 supplied
    // typedefs for pointers/types/etc.
    //
    pANTLR3_UINT8	    fName;

    // The ANTLR3 character input stream, which abstracts the input source such that
    // it is easy to privide inpput from different sources such as files, or
    // memory strings.
    //
    // For an ASCII/latin-1 memory string use:
    //	    input = antlr3NewAsciiStringInPlaceStream (stringtouse, (ANTLR3_UINT64) length, NULL);
    //
    // For a UCS2 (16 bit) memory string use:
    //	    input = antlr3NewUCS2StringInPlaceStream (stringtouse, (ANTLR3_UINT64) length, NULL);
    //
    // For input from a file, see code below
    //
    // Note that this is essentially a pointer to a structure containing pointers to functions.
    // You can create your own input stream type (copy one of the existing ones) and override any
    // individual function by installing your own pointer after you have created the standard
    // version.
    //
    pANTLR3_INPUT_STREAM    input;

    // The lexer is of course generated by ANTLR, and so the lexer type is not upper case.
    // The lexer is supplied with a pANTLR3_INPUT_STREAM from whence it consumes its
    // input and generates a token stream as output.
    //
    pTLexer		    lxr;

    // The token stream is produced by the ANTLR3 generated lexer. Again it is a structure based
    // API/Object, which you can customise and override methods of as you wish. a Token stream is
    // supplied to the generated parser, and you can write your own token stream and pass this in
    // if you wish.
    //
    pANTLR3_COMMON_TOKEN_STREAM	    tstream;

    // The C parser is also generated by ANTLR and accepts a token stream as explained
    // above. The token stream can be any source in fact, so long as it implements the
    // ANTLR3_TOKEN_SOURCE interface. In this case the parser does not return anything
    // but it can of cousre speficy any kind of return type from the rule you invoke
    // when calling it.
    //
    pTParser				psr;

    // Create the input stream based upon the argument supplied to us on the command line
    // for this example, the input will always default to ./input if there is no explicit
    // argument.
    //
    if (argc < 2 || argv[1] == NULL)
    {
	fName	=(pANTLR3_UINT8)"./input"; // Note in VS2005 debug, working directory must be configured
    }
    else
    {
	fName	= (pANTLR3_UINT8)argv[1];
    }

    // Create the input stream using the supplied file name
    // (Use antlr3AsciiFileStreamNew for UCS2/16bit input).
    //
    input	= antlr3AsciiFileStreamNew(fName);

    // The input will be created successfully, providing that there is enough
    // memory and the file exists etc
    //
    if ( input == NULL )
    {
	    fprintf(stderr, "Unable to open file %s\n", (char *)fName);
	    exit(ANTLR3_ERR_NOMEM);
    }

    // Our input stream is now open and all set to go, so we can create a new instance of our
    // lexer and set the lexer input to our input stream:
    //  (file | memory | ?) --> inputstream -> lexer --> tokenstream --> parser ( --> treeparser )?
    //
    lxr	    = TLexerNew(input);	    // CLexerNew is generated by ANTLR

    // Need to check for errors
    //
    if (lxr == NULL )
    {
	    fprintf(stderr, "Unable to create the lexer due to malloc() failure1\n");
	    exit(ANTLR3_ERR_NOMEM);
    }

    // Our lexer is in place, so we can create the token stream from it
    // NB: Nothing happens yet other than the file has been read. We are just
    // connecting all these things together and they will be invoked when we
    // call the parser rule. ANTLR3_SIZE_HINT can be left at the default usually
    // unless you have a very large token stream/input. Each generated lexer
    // provides a token source interface, which is the second argument to the
    // token stream creator.
    // Note tha even if you implement your own token structure, it will always
    // contain a standard common token within it and this is the pointer that
    // you pass around to everything else. A common token as a pointer within
    // it that should point to your own outer token structure.
    //
    tstream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lxr));

    if (tstream == NULL)
    {
		fprintf(stderr, "Out of memory trying to allocate token stream\n");
		exit(ANTLR3_ERR_NOMEM);
    }

    // Finally, now that we have our lexer constructed, we can create the parser
    //
    psr	    = TParserNew(tstream);  // CParserNew is generated by ANTLR3

	if (tstream == NULL)
	{
		fprintf(stderr, "Out of memory trying to allocate parser\n");
		exit(ANTLR3_ERR_NOMEM);
	}

    // We are all ready to go. Though that looked complicated at first glance,
    // I am sure, you will see that in fact most of the code above is dealing
    // with errors and there isn't really that much to do (isn't this always the
    // case in C? ;-).
    //
    // So, we now invoke the parser. All elements of ANTLR3 generated C components
    // as well as the ANTLR C runtime library itself are pseudo objects. This means
    // that they are represented as pointers to structures, which contain any
    // instance data they need, and a set of pointers to other interfaces or
    // 'methods'. Note that in general, these few pointers we have created here are
    // the only things you will ever explicitly free() as everything else is created
    // via factories, that allocate memory efficiently and free() everything they use
    // automatically when you close the parser/lexer/etc.
    //
    // Note that this means only that the methods are always called via the object
    // pointer and the first argument to any method, is a pointer to the structure itself.
    // It also has the side advantage, if you are using an IDE such as VS2005 that can do it
    // that when you type ->, you will see a list of tall the methods the object supports.
    //
    psr->program(psr);

    // We did not return anything from this parser rule, so we can finish. It only remains
    // to close down our open objects, in the reverse order we created them
    //
    psr	    ->free  (psr);	    psr = NULL;
    tstream ->free  (tstream);	    tstream = NULL;
    lxr	    ->free  (lxr);	    lxr = NULL;
    input   ->close (input);	    input = NULL;

    return 0;
}


text:
@implementation SecondPageView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

@end


text:
#ifndef PTM_STRUCTURE_MATCHER_H
#define PTM_STRUCTURE_MATCHER_H

#include "ptm_initialize_data.h"
#include "ptm_constants.h"

namespace ptm {

typedef struct
{
        double rmsd;
        double scale;
        double q[4];                //rotation in quaternion form (rigid body transformation)
        int8_t mapping[PTM_MAX_POINTS];
        const refdata_t* ref_struct;
} result_t;

int match_general(const refdata_t* s, double (*ch_points)[3], double (*points)[3], convexhull_t* ch, result_t* res);
int match_fcc_hcp_ico(double (*ch_points)[3], double (*points)[3], int32_t flags, convexhull_t* ch, result_t* res);
int match_dcub_dhex(double (*ch_points)[3], double (*points)[3], int32_t flags, convexhull_t* ch, result_t* res);
int match_graphene(double (*points)[3], result_t* res);

}

#endif


text:
extern QColor bluefill;  // 99ccff
extern QColor bluestroke;  // 0066cc
extern QColor bluishstroke;  //
extern QColor orangefill;  // ffcc99
extern QColor orangestroke;  // cc6633
extern QColor lightorangefill;
extern QColor lightorangestroke;
extern QColor grayfill;  // eeeeee (was a1a1a1)
extern QColor graystroke;  // 666666 (was 424242)

// Path Sizing
#define VIRTUALHELIXHANDLEITEM_RADIUS        30
#define VIRTUALHELIXHANDLEITEM_STROKE_WIDTH  2
#define PATH_BASE_WIDTH                      20  // used to size bases (grid squares, handles, etc)
#define PATH_HELIX_HEIGHT                    (2 * PATH_BASE_WIDTH)  // staple + scaffold
#define PATH_HELIX_PADDING                   50 // gap between PathHelix objects in path view
#define PATH_GRID_STROKE_WIDTH               0.5
#define SLICE_HANDLE_STROKE_WIDTH            1
#define PATH_STRAND_STROKE_WIDTH             3
#define PATH_STRAND_HIGHLIGHT_STROKE_WIDTH   8
#define PATH_SELECTBOX_STROKE_WIDTH          1.5
#define PCH_BORDER_PADDING                   1
#define PATH_BASE_HL_STROKE_WIDTH            2  // PathTool highlight box
#define MINOR_GRID_STROKE_WIDTH              0.5
#define MAJOR_GRID_STROKE_WIDTH              0.5
#define OLIGOLENBELOWWHICHHIGHLIGHT          20
#define OLIGOLENABOVEWHICHHIGHLIGHT          49

// Path Drawing
#define PATH_XOVER_LINE_SCALE_X  0.035
#define PATH_XOVER_LINE_SCALE_Y  0.035

// Path Colors
extern QColor scaffold_bkg_fill;
extern QColor activeslicehandlefill;  // ffcc99
extern QColor activeslicehandlestroke;  // cc6633
extern QColor minorgridstroke;  // 999999
extern QColor majorgridstroke;  // 333333
extern QColor scafstroke;  // 0066cc
extern QColor handlefill;  // 0066cc
extern QColor pxi_scaf_stroke;
extern QColor pxi_stap_stroke;
extern QColor pxi_disab_stroke;
extern QColor redstroke;
extern QColor erasefill;
extern QColor forcefill;
extern QColor breakfill;
extern QColor colorbox_fill;
extern QColor colorbox_stroke;
extern QColor *stapcolors;
extern QColor *scafcolors;

//#define DEFAULT_STAP_COLOR  "#888888"
//#define DEFAULT_SCAF_COLOR  "#0066cc"
extern QColor selected_color;

// Loop/Insertion path details
#define INSERTWIDTH   2
#define SKIPWIDTH     2

// Add Sequence Tool
extern QColor invalid_dna_color;
#define UNDERLINE_INVALID_DNA   true

// Additional Prefs
#define PREF_AUTOSCAF_INDEX        0
#define PREF_STARTUP_TOOL_INDEX    0
#define PREF_ZOOM_SPEED            20 //50
#define PREF_ZOOM_AFTER_HELIX_ADD  true

//Z values
//bottom
#define ZACTIVESLICEHANDLE  10
#define ZPATHHELIXGROUP     20
#define ZPATHHELIX          30
#define ZPATHSELECTION      40
#define ZSLICEHELIX         50
#define ZDESELECTOR         60
#define ZFOCUSRING          70
#define ZPREXOVERHANDLE     80
#define ZXOVERITEM          90
#define ZBREAKPOINTHANDLE   100
#define ZSKIPHANDLE         110
#define ZBREAKITEM          120
#define ZPATHTOOL           130
#define ZSTRANDITEM         140
#define ZENDPOINTITEM       150
#define ZINSERTHANDLE       160
#define ZPARTITEM           200
//top

// sequence stuff
extern QFont SEQUENCEFONT;
#define SEQUENCEFONTH                          (PATH_BASE_WIDTH / 3.0)

extern QFontMetricsF SEQUENCEFONTMETRICS;
extern int SEQUENCEFONTCHARWIDTH;
#define SEQUENCEFONTCHARHEIGHT                 SEQUENCEFONTMETRICS.height()
#define SEQUENCEFONTEXTRAWIDTH                 (PATH_BASE_WIDTH - SEQUENCEFONTCHARWIDTH)
#define SEQUENCETEXTXCENTERINGOFFSET           (SEQUENCEFONTEXTRAWIDTH / 4.0)
#define SEQUENCETEXTYCENTERINGOFFSET           (PATH_BASE_WIDTH * 0.6)

extern QFont XOVER_LABEL_FONT;
#ifdef Q_WS_WIN
//    #define THEFONT           "Times"
    #define THEFONT           "Arial"
    #define THEFONTSIZE       10

#elif Q_WS_MAC
//    #define THEFONT           "Segoe UI"
//    #define THEFONT           "Calibri"
    #define THEFONT           "Arial"
    #define THEFONTSIZE       9
#else // linux
    #define THEFONT  "DejaVu Sans"
    #define THEFONTSIZE       9
#endif

extern QFont SLICE_NUM_FONT;
extern QFont VIRTUALHELIXHANDLEITEM_FONT;
extern QColor XOVER_LABEL_COLOR;

// Overwrite for Maya
// majorgridstroke                    QColor(255, 255, 255)  // ffffff for maya

void setupStyle(void);

#endif // STYLES_H


text:
<!DOCTYPE html>

		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.legacy.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.grids.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.frames.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.forms.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.tables.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.drawers.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.tabs.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/symphony.notices.css">
		<link rel="stylesheet" type="text/css" media="screen" href="../../../assets/css/admin.css">

		<title>Pages – Symphony</title>

Your Symphony installation is up to date, but the installer was still detected. For security reasons, it should be removed. Remove installer?

					Symphony CMS

						John Smith

						Log out

Content

									Articles

									Categories

									Notes

									Comments

									Messages

Blueprints

									Pages

									Sections

									Data Sources

									Events

									Utilities

System

									Authors

									Preferences

									Extensions

							Pages
							›

Untitled

				<form action="../../../blueprints/pages/new/" method="post">
					<fieldset class="settings">
						<legend>Page Settings</legend>
						Title
							<input name="fields[title]" type="text">

								URL Handle
									<input name="fields[handle]" type="text">

								Parent Page
									<select name="fields[parent]">
										<option value="">/</option>
										<option value="66">/about</option>
										<option value="68">/archive</option>
										<option value="69">/articles</option>
										<option value="70">/drafts</option>
										<option value="64">/home</option>
										<option value="75">/maintenance</option>
										<option value="76">/page-not-found</option>
										<option value="67">/rss</option>
									</select>

								URL Parameters
									<input name="fields[params]" type="text" placeholder="param1/param2">

								Page Type
									<input name="fields[type]" type="text">

index

XML

JSON

admin

404

403

hidden

maintenance

					</fieldset>
					<fieldset class="settings">
						<legend>Page Resources</legend>

							Events
								<select name="fields[events][]" multiple="multiple">
									<option value="login">Login Info</option>
									<option value="publish_article">Publish Article</option>
									<option value="save_comment">Save Comment</option>
									<option value="save_message">Save Message</option>
								</select>

							Data Sources
								<select name="fields[data_sources][]" multiple="multiple">
									<option value="archive">Archive</option>
									<option value="article">Article</option>
									<option value="article_images">Article Images</option>
									<option value="comments">Comments</option>
									<option value="drafts">Drafts</option>
									<option value="homepage_articles">Homepage Articles</option>
									<option value="jit_image_manipulation_recipes">JIT Image Manipulation Recipes</option>
									<option value="navigation">Navigation</option>
									<option value="notes">Notes</option>
									<option value="rss_articles">RSS Articles</option>
									<option value="website_owner">Website Owner</option>
								</select>

					</fieldset>

						<input name="action[save]" type="submit" value="Create Page" accesskey="s">

				</form>


text:
package lecho.lib.hellocharts.samples;

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

import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.util.XYDataset;
import lecho.lib.hellocharts.view.LineChartView;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class GoodBadChartActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_good_bad);
		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction().add(R.id.container, new PlaceholderFragment()).commit();
		}
	}

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		private LineChartView chart;
		private LineChartData data;

		public PlaceholderFragment() {
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_good_bad, container, false);

			chart = (LineChartView) rootView.findViewById(R.id.chart);

			generateDefaultData();
			chart.setLineChartData(data);

			// Increase viewport height for better look
			Viewport v = chart.getMaximumViewport();
			float dy = v.height() * 0.2f;
			v.inset(0, -dy);
			chart.setMaximumViewport(v);
			chart.setCurrentViewport(v);

			return rootView;
		}

		private void generateDefaultData() {

			// Generate data, every line has 3 points to form filled triangle. Point radius is set to 1 to be almost
			// invisible but it has to be there because without points there is not labels. Area transparency is set to
			// 255(full opacity).

			// Important note. This example uses negative values, to properly fill area below 0 chart base value have to
			// be set to 0. That is default base value but if you want to be sure you can call data.setBaseValue(0)
			// method.

			Line line;
			XYDataset values;
			List<Line> lines = new ArrayList<Line>();

			// First good triangle
			values = new XYDataset();
			values.add(new PointValue(0, 0).setLabel("".toCharArray()));
			values.add(new PointValue(1, 1).setLabel("Very Good:)".toCharArray()));
			values.add(new PointValue(2, 0).setLabel("".toCharArray()));

			line = new Line(values);
			line.setColor(ChartUtils.COLOR_GREEN);
			line.setAreaTransparency(255);
			line.setFilled(true);
			line.setPointRadius(1);
			line.setHasLabels(true);
			lines.add(line);

			// Second good triangle
			values = new XYDataset();
			values.add(new PointValue(3, 0).setLabel("".toCharArray()));
			values.add(new PointValue(4, 0.5f).setLabel("Good Enough".toCharArray()));
			values.add(new PointValue(5, 0).setLabel("".toCharArray()));

			line = new Line(values);
			line.setColor(ChartUtils.COLOR_GREEN);
			line.setAreaTransparency(255);
			line.setFilled(true);
			line.setPointRadius(1);
			line.setHasLabels(true);
			lines.add(line);

			// Bad triangle
			values = new XYDataset();
			values.add(new PointValue(1, 0).setLabel("".toCharArray()));
			values.add(new PointValue(2, -1).setLabel("Very Bad".toCharArray()));
			values.add(new PointValue(3, 0).setLabel("".toCharArray()));

			line = new Line(values);
			line.setColor(ChartUtils.COLOR_RED);
			line.setAreaTransparency(255);
			line.setFilled(true);
			line.setPointRadius(1);
			line.setHasLabels(true);
			lines.add(line);

			data = new LineChartData(lines);

			// *** Important, set base value to 0 to fill negative part of chart.
			// data.setBaseValue(0);

		}
	}
}


text:
from disco.test import TestCase, TestJob
from disco.worker.classic.modutil import find_modules, ModUtilImportError

import sys, os

support = os.path.join(os.path.dirname(__file__), 'support')
mod1req = ('mod1', os.path.normpath(os.path.join(support, 'mod1.py')))
mod2req = ('mod2', os.path.normpath(os.path.join(support, 'mod2.py')))

def system_modules():
    os.path.abspath('')
    random.random()
    time.time()

def local_module():
    extramodule1.magic(5)

def missing_module():
    missing_module_ifitexiststhistestwillfail.magic()

def recursive_module():
    mod1.plusceil(1, 2)

class ModUtilJob(TestJob):
    @staticmethod
    def map(e, params):
        x, y = [float(x) for x in e.split('|')]
        yield mod1.plusceil(x, y) + math.ceil(1.5), ''

class RequiredFilesJob(TestJob):
    @staticmethod
    def map(e, params):
        x = extramodule1.magic(int(e))
        y = extramodule2.kungfu(x)
        open('lib/mod1.py')
        import mod1
        yield '', y

class ModUtilTestCase(TestCase):
    def serve(self, path):
        return '%s\n' % path

    def setUp(self):
        super(ModUtilTestCase, self).setUp()
        self.sys_path = sys.path
        sys.path.append(support)
        python_path = os.getenv('PYTHONPATH', '').split(':')
        os.environ['PYTHONPATH'] = ':'.join(python_path + [support])

    def tearDown(self):
        super(ModUtilTestCase, self).tearDown()
        sys.path = self.sys_path

    def assertFindsModules(self, functions, modules, send_modules=False, recurse=True):
        self.assertEquals(sorted(find_modules(functions,
                                              send_modules=send_modules,
                                              recurse=recurse)),
                          sorted(modules))

    def test_system(self):
        self.assertFindsModules([system_modules], ['os', 'random', 'time'])

    def test_local(self):
        self.assertFindsModules([local_module], ['extramodule1'])

    def test_missing(self):
        self.assertRaises(ModUtilImportError, lambda: find_modules([missing_module]))

    def test_recursive(self):
        self.assertFindsModules([recursive_module], [mod1req, mod2req], send_modules=True)

    def test_norecursive(self):
        self.assertFindsModules([recursive_module], ['mod1'], recurse=False)

    def test_auto_modules(self):
        self.job = ModUtilJob().run(input=self.test_server.urls(['0.5|1.2']))
        self.assertResults(self.job, [(4.0, '')])

    def test_find_modules(self):
        self.job = ModUtilJob()
        self.job.run(input=self.test_server.urls(['0.5|1.2']),
                     required_modules=find_modules([self.job.map]))
        self.assertResults(self.job, [(4.0, '')])

    def test_list_modules(self):
        self.job = ModUtilJob().run(input=self.test_server.urls(['0.5|1.2']),
                                    required_modules=['math', mod1req, mod2req])
        self.assertResults(self.job, [(4.0, '')])

    def test_required_files(self):
        self.job = RequiredFilesJob().run(input=self.test_server.urls([123]),
                                          required_files=[mod1req[1], mod2req[1]])
        self.assertResults(self.job, [('', 123 ** 2 + 2)])


text:
package com.gary.garytool;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.gary.garytool.business.baseframe.BaseFrameMainActivity;
import com.gary.garytool.business.guessmusic.GuessMusicMainActivity;
import com.gary.garytool.business.insane.MainInsaneActivity;
import com.gary.garytool.business.map.MapMainActivity;
import com.gary.garytool.business.puzzle.PuzzleMainActivity;
import com.gary.garytool.business.stock.StockMainActivity;
import com.gary.garytool.business.tourist.TouristMainActivity;
import com.gary.garytool.util.Util;
import com.gary.garytool.view.pulltorefreshused.PullToRefreshListViewActivity;

public class MainActivity extends Activity {

    public static void  main(String[] args)
    {
        System.out.print("hello garyts");
        System.out.print(2<<3);
    }

    Button mFunctions;
    TextView mTextView;
    Button mPullToRefresh;
    Button bt_insane;
    Button btControls;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mFunctions = (Button) findViewById(R.id.bt_functions);
        mFunctions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MainFunctionActivity.class);
                startActivity(intent);
            }
        });

        btControls = (Button) findViewById(R.id.bt_controls);
        btControls.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MainControlActivity.class);
                startActivity(intent);
            }
        });

        mTextView= (TextView) findViewById(R.id.tv);
        mTextView.setText("个人框架 \n Volley \n XUtils \n" +
                " PullToRefresh ");
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, BaseFrameworkActivity.class);
                startActivity(intent);
            }
        });
        //PullToRefresh 控件专题
        //https://github.com/chrisbanes/Android-PullToRefresh
        //http://blog.csdn.net/lmj623565791/article/details/38238749
        mPullToRefresh= (Button) findViewById(R.id.bt_pull_to_refresh);
        mPullToRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,PullToRefreshListViewActivity.class);
                startActivity(intent);
            }
        });

        bt_insane= (Button) findViewById(R.id.bt_insane);
        bt_insane.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,MainInsaneActivity.class);
                startActivity(intent);
            }
        });
    }

    //景区主页进入事件
    public void onTourist(View view)
    {
        Util.startActivity(MainActivity.this, TouristMainActivity.class);
    }

    /**
     * 进入股票分析功能
     * @param view
     */
    public void stockMain(View view)
    {
        Intent intent=new Intent(MainActivity.this, StockMainActivity.class);
        startActivity(intent);
    }

    public void onGuessMusic(View view)
    {
        Intent intent=new Intent(MainActivity.this, GuessMusicMainActivity.class);
        startActivity(intent);
    }

    public void onPuzzle(View view)
    {
        //洪洋的美女拼图小游戏 http://www.imooc.com/learn/224
        Intent intent=new Intent(MainActivity.this, PuzzleMainActivity.class);
        startActivity(intent);
    }

    //知识点  fragment的replace和add hide的使用 http://blog.csdn.net/shimiso/article/details/44677007
    //知识点 android:descendantFocusability 的使用  http://www.cnblogs.com/eyu8874521/archive/2012/10/17/2727882.html
    public void onBaseFrame(View view)
    {
        Intent intent=new Intent(MainActivity.this, BaseFrameMainActivity.class);
        startActivity(intent);
    }

    public void onMap(View view)
    {
        Util.startActivity(MainActivity.this, MapMainActivity.class);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        //采用FLAG_ACTIVITY_CLEAR_TOP退出整个程序
        if ((Intent.FLAG_ACTIVITY_CLEAR_TOP & intent.getFlags()) != 0) {
            finish();
        }
        /* 个人补充
        1.可以把A设置成不可见的Acitivity(方法见下面),然后在它的onCreate方法里跳转到"真正"的载入界面就可以实现在D中点退出程序按钮时看上去立即退出程序的效果
        2.A必须是程序启动的第一个Activity才能起到这种立即退出的效果,因为Intent.FLAG_ACTIVITY_CLEAR_TOP只会把目标Activity的"上面"的Activity清理掉,
        而如果目标Activity的"下面"还有Activity(换句话说,目标Activity不在栈底),则finish后只会到他下面的那个Activity,而不是立即退出的效果了
        3.不可见Activity在项目的AndroidManifest.xml文件中相应的Activity标签中添加这样一行:android:theme="@android:style/Theme.NoDisplay"这样一来,
        当这个Activity启动的时候,就不会显示出界面了。
        */
    }
}