text:
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.core.exceptions import PermissionDenied
from django.http import JsonResponse
from django.urls import reverse, reverse_lazy
from django.utils.decorators import method_decorator
from django.views.generic import (ListView, DetailView, CreateView, DeleteView, UpdateView, View,
                                  TemplateView)

from common.cache import decr_notification
from .decorators import user_is_event_author
from .forms import EventForm
from .models import Event, EventInvite

class EventDetail(DetailView):
    model = Event
    queryset = Event.objects.details()
    invited_by_status = {}
    user_invite_status = None

    def get_object(self, **kwargs):
        event = super().get_object(**kwargs)
        perm, invite = event.get_permission_and_invite(self.request.user)
        if not perm:
            raise PermissionDenied
        event.incr_views()
        setattr(event, 'user_invite', invite)
        return event

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['invite'] = self.object.user_invite
        invited_by_status = self.object.invited_by_status()

        for key, value in invited_by_status.items():
            context['invites_' + key] = value

        return context

class EventActionMixin:
    form_class = EventForm
    template_name = 'events/event_create_update.html'

    @property
    def success_msg(self):
        return NotImplemented

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        messages.success(self.request, self.success_msg, extra_tags='Success')
        return super().form_valid(form)

    def get_success_url(self):
        return reverse('event:detail', args=(self.object.pk, ))

@method_decorator(login_required, name='dispatch')
class EventCreate(EventActionMixin, CreateView):
    model = Event
    success_msg = 'Event created.'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['friends'] = list(self.request.user.profile.get_friends())
        return context

@method_decorator(user_is_event_author, name='dispatch')
class EventUpdate(EventActionMixin, UpdateView):
    model = Event
    success_msg = 'Event updated.'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['attend_init'] = self.object.self_invite_exists(self.request.user.pk)
        kwargs['update'] = True
        return kwargs

@method_decorator(user_is_event_author, name='dispatch')
class EventDelete(DeleteView):
    model = Event
    success_url = reverse_lazy('index')

    def delete(self, request, *args, **kwargs):
        messages.success(request, 'Event deleted.', extra_tags='Success')
        return super().delete(request, *args, **kwargs)

class EventListView(ListView):
    context_object_name = 'events'
    paginate_by = 12
    privacy = Event.PUBLIC

    def get_queryset(self):
        return Event.objects.future_by_privacy(self.privacy, self.request.user)

class IndexView(EventListView):
    template_name = 'events/index.html'

    def get_queryset(self):
        qs = super().get_queryset()
        return qs.order_by('-num_att')

class EventsPaginate(EventListView):
    def get_template_names(self):
        if self.request.is_ajax():
            return 'events/snippets/event_list_pagination.html'
        return 'events/events.html'

@method_decorator(login_required, name='dispatch')
class EventsFriends(EventsPaginate):
    def get_queryset(self):
        return Event.objects.friends_events(self.request.user)

class EventInviteAction(LoginRequiredMixin, View):
    http_method_names = [u'post']
    event_cls = None

    def manager_method(self, *args, **kwargs):
        raise NotImplementedError

    def get_event_object_or_pk(self, pk):
        if self.event_cls:
            try:
                return self.event_cls.objects.get(pk=pk)
            except self.event_cls.DoesNotExist:
                return
        else:
            return pk

    def get_post_value(self):
        return self.request.POST.get('pk')

    def post(self, request, pk):
        result = False
        obj_or_pk = self.get_event_object_or_pk(pk)
        if obj_or_pk:
            result = self.manager_method(obj_or_pk, request.user, self.get_post_value())
        return JsonResponse({'result': result})

class JoinEvent(EventInviteAction):
    event_cls = Event
    manager_method = EventInvite.objects.join

class AcceptEventInvite(EventInviteAction):
    manager_method = EventInvite.objects.accept

class RejectEventInvite(EventInviteAction):
    manager_method = EventInvite.objects.reject

class PendEventInvite(EventInviteAction):
    manager_method = EventInvite.objects.pend

class SelfRemoveEventInvite(EventInviteAction):
    manager_method = EventInvite.objects.self_remove

class RemoveEventInvite(EventInviteAction):
    event_cls = Event
    manager_method = EventInvite.objects.remove

class Invite(EventInviteAction):
    event_cls = Event
    manager_method = EventInvite.objects.invite

    def get_post_value(self):
        return self.request.POST.getlist('pks[]')

class ShowEventInvites(LoginRequiredMixin, TemplateView):
    template_name = 'events/invites.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        invites_grouped = EventInvite.objects.get_all_grouped(self.request.user)

        for key, value in invites_grouped.items():
            context[key] = value

        return context

    def dispatch(self, request, *args, **kwargs):
        response = super().dispatch(request, *args, **kwargs)
        decr_notification('e_invites_count', request.user.pk)
        return response

class ShowEventsInvitedAndAttending(LoginRequiredMixin, ListView):
    context_object_name = 'events'
    template_name = 'events/events.html'

    def get_queryset(self):
        return Event.objects.invited_and_attending(self.request.user)

class Search(TemplateView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        if self.request.method == 'POST':
            search_str = self.request.POST.get('searchInput')
            context['events'] = Event.objects.search(Event.PUBLIC, self.request.user, search_str)
        return context

    def get_template_names(self):
        if self.request.method == 'POST':
            return 'events/snippets/events_4_in_row.html'
        return 'events/search.html'

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)


text:
from registration.forms import RegistrationForm

from CommentRecaptcha.fields import ReCaptchaField

class RegistrationFormRecaptcha(RegistrationForm):
    recaptcha = ReCaptchaField()

redpajama_set_name: RedPajamaGithub


text:
:: After Pulling, Patching, and making sure the version number is changed in src, this bat will compile and create zips for all release.
:: It will also create a zip for ExampleMod

set version=v0.9.1.1
set destinationFolder=.\tModLoader %version% Release

:: Compile/Build exe
call buildRelease.bat
@IF %ERRORLEVEL% NEQ 0 (
	pause
	EXIT /B %ERRORLEVEL%
)

:: Make up-to-date Installers
cd ..\installer2
call createInstallers.bat
cd ..\solutions

:: Folder for release
mkdir "%destinationFolder%"

:: Temp Folders
mkdir "%destinationFolder%\tModLoader Windows %version%"
mkdir "%destinationFolder%\tModLoader Mac %version%"
mkdir "%destinationFolder%\tModLoader Linux %version%"
mkdir "%destinationFolder%\tModLoader Windows %version%\ModCompile"
mkdir "%destinationFolder%\tModLoader Mac %version%\ModCompile"
mkdir "%destinationFolder%\tModLoader Linux %version%\ModCompile"

:: Windows release
copy ..\src\tModLoader\bin\x86\WindowsRelease\Terraria.exe "%destinationFolder%\tModLoader Windows %version%\Terraria.exe" /y
copy ..\src\tModLoader\bin\x86\WindowsServerRelease\Terraria.exe "%destinationFolder%\tModLoader Windows %version%\tModLoaderServer.exe" /y
:: ModCompile
copy ..\src\tModLoader\bin\x86\MacRelease\Terraria.exe "%destinationFolder%\tModLoader Windows %version%\ModCompile\tModLoaderMac.exe" /y
copy ..\references\FNA.dll "%destinationFolder%\tModLoader Windows %version%\ModCompile\FNA.dll" /y
copy ..\references\Microsoft.CodeAnalysis.dll "%destinationFolder%\tModLoader Windows %version%\ModCompile\Microsoft.CodeAnalysis.dll" /y
copy ..\references\Microsoft.CodeAnalysis.CSharp.dll "%destinationFolder%\tModLoader Windows %version%\ModCompile\Microsoft.CodeAnalysis.CSharp.dll" /y
copy ..\references\Mono.Cecil.Pdb.dll "%destinationFolder%\tModLoader Windows %version%\ModCompile\Mono.Cecil.Pdb.dll" /y
copy ..\references\System.Reflection.Metadata.dll "%destinationFolder%\tModLoader Windows %version%\ModCompile\System.Reflection.Metadata.dll" /y
copy ..\RoslynWrapper\bin\Release\RoslynWrapper.dll "%destinationFolder%\tModLoader Windows %version%\ModCompile\RoslynWrapper.dll" /y

copy ..\installer2\WindowsInstaller.jar "%destinationFolder%\tModLoader Windows %version%\tModLoaderInstaller.jar" /y
copy ReleaseExtras\README_Windows.txt "%destinationFolder%\tModLoader Windows %version%\README.txt" /y
copy ReleaseExtras\start-tModLoaderServer.bat "%destinationFolder%\tModLoader Windows %version%\start-tModLoaderServer.bat" /y
copy ReleaseExtras\start-tModLoaderServer-steam-friends.bat "%destinationFolder%\tModLoader Windows %version%\start-tModLoaderServer-steam-friends.bat" /y
copy ReleaseExtras\start-tModLoaderServer-steam-private.bat "%destinationFolder%\tModLoader Windows %version%\start-tModLoaderServer-steam-private.bat" /y

call zipjs.bat zipDirItems -source "%destinationFolder%\tModLoader Windows %version%" -destination "%destinationFolder%\tModLoader Windows %version%.zip" -keep yes -force yes

:: Mac release
copy ..\src\tModLoader\bin\x86\MacRelease\Terraria.exe "%destinationFolder%\tModLoader Mac %version%\Terraria.exe" /y
copy ..\src\tModLoader\bin\x86\MacServerRelease\Terraria.exe "%destinationFolder%\tModLoader Mac %version%\tModLoaderServer.exe" /y
copy ReleaseExtras\tModLoaderServer "%destinationFolder%\tModLoader Mac %version%\tModLoaderServer" /y
copy ReleaseExtras\tModLoaderServer.bin.osx "%destinationFolder%\tModLoader Mac %version%\tModLoaderServer.bin.osx" /y
:: ModCompile
copy ..\src\tModLoader\bin\x86\WindowsRelease\Terraria.exe "%destinationFolder%\tModLoader Mac %version%\ModCompile\tModLoaderWindows.exe" /y
copy ReleaseExtras\Microsoft.Xna.Framework.dll "%destinationFolder%\tModLoader Mac %version%\ModCompile\Microsoft.Xna.Framework.dll" /y
copy ReleaseExtras\Microsoft.Xna.Framework.Game.dll "%destinationFolder%\tModLoader Mac %version%\ModCompile\Microsoft.Xna.Framework.Game.dll" /y
copy ReleaseExtras\Microsoft.Xna.Framework.Graphics.dll "%destinationFolder%\tModLoader Mac %version%\ModCompile\Microsoft.Xna.Framework.Graphics.dll" /y
copy ReleaseExtras\Microsoft.Xna.Framework.Xact.dll "%destinationFolder%\tModLoader Mac %version%\ModCompile\Microsoft.Xna.Framework.Xact.dll" /y
:: References
copy ..\references\MP3Sharp.dll "%destinationFolder%\tModLoader Mac %version%\MP3Sharp.dll" /y
copy ..\references\Ionic.Zip.Reduced.dll "%destinationFolder%\tModLoader Mac %version%\Ionic.Zip.Reduced.dll" /y
copy ..\references\Mono.Cecil.dll "%destinationFolder%\tModLoader Mac %version%\Mono.Cecil.dll" /y

copy ..\installer2\MacInstaller.jar "%destinationFolder%\tModLoader Mac %version%\tModLoaderInstaller.jar" /y
copy ReleaseExtras\README_Mac.txt "%destinationFolder%\tModLoader Mac %version%\README.txt" /y
copy ReleaseExtras\Terraria.exe.config "%destinationFolder%\tModLoader Mac %version%\Terraria.exe.config" /y

call zipjs.bat zipDirItems -source "%destinationFolder%\tModLoader Mac %version%" -destination "%destinationFolder%\tModLoader Mac %version%.zip" -keep yes -force yes

:: Linux release
copy ..\src\tModLoader\bin\x86\LinuxRelease\Terraria.exe "%destinationFolder%\tModLoader Linux %version%\Terraria.exe" /y
copy ..\src\tModLoader\bin\x86\LinuxServerRelease\Terraria.exe "%destinationFolder%\tModLoader Linux %version%\tModLoaderServer.exe" /y
copy ReleaseExtras\tModLoaderServer "%destinationFolder%\tModLoader Linux %version%\tModLoaderServer" /y
copy ReleaseExtras\tModLoaderServer.bin.x86 "%destinationFolder%\tModLoader Linux %version%\tModLoaderServer.bin.x86" /y
copy ReleaseExtras\tModLoaderServer.bin.x86_64 "%destinationFolder%\tModLoader Linux %version%\tModLoaderServer.bin.x86_64" /y
:: ModCompile
copy ..\src\tModLoader\bin\x86\WindowsRelease\Terraria.exe "%destinationFolder%\tModLoader Linux %version%\ModCompile\tModLoaderWindows.exe" /y
copy ReleaseExtras\Microsoft.Xna.Framework.dll "%destinationFolder%\tModLoader Linux %version%\ModCompile\Microsoft.Xna.Framework.dll" /y
copy ReleaseExtras\Microsoft.Xna.Framework.Game.dll "%destinationFolder%\tModLoader Linux %version%\ModCompile\Microsoft.Xna.Framework.Game.dll" /y
copy ReleaseExtras\Microsoft.Xna.Framework.Graphics.dll "%destinationFolder%\tModLoader Linux %version%\ModCompile\Microsoft.Xna.Framework.Graphics.dll" /y
copy ReleaseExtras\Microsoft.Xna.Framework.Xact.dll "%destinationFolder%\tModLoader Linux %version%\ModCompile\Microsoft.Xna.Framework.Xact.dll" /y
:: References
copy ..\references\MP3Sharp.dll "%destinationFolder%\tModLoader Linux %version%\MP3Sharp.dll" /y
copy ..\references\Ionic.Zip.Reduced.dll "%destinationFolder%\tModLoader Linux %version%\Ionic.Zip.Reduced.dll" /y
copy ..\references\Mono.Cecil.dll "%destinationFolder%\tModLoader Linux %version%\Mono.Cecil.dll" /y

copy ..\installer2\LinuxInstaller.jar "%destinationFolder%\tModLoader Linux %version%\tModLoaderInstaller.jar" /y
copy ReleaseExtras\README_Linux.txt "%destinationFolder%\tModLoader Linux %version%\README.txt" /y
copy ReleaseExtras\Terraria.exe.config "%destinationFolder%\tModLoader Linux %version%\Terraria.exe.config" /y

call zipjs.bat zipDirItems -source "%destinationFolder%\tModLoader Linux %version%" -destination "%destinationFolder%\tModLoader Linux %version%.zip" -keep yes -force yes

:: CleanUp, Delete temp Folders
rmdir "%destinationFolder%\tModLoader Windows %version%" /S /Q
rmdir "%destinationFolder%\tModLoader Mac %version%" /S /Q
rmdir "%destinationFolder%\tModLoader Linux %version%" /S /Q

:: Copy to public DropBox Folder
::copy "%destinationFolder%\tModLoader Windows %version%.zip" "C:\Users\Javid\Dropbox\Public\TerrariaModding\tModLoaderReleases\tModLoader Windows %version%.zip"
::copy "%destinationFolder%\tModLoader Mac %version%.zip" "C:\Users\Javid\Dropbox\Public\TerrariaModding\tModLoaderReleases\tModLoader Mac %version%.zip"
::copy "%destinationFolder%\tModLoader Linux %version%.zip" "C:\Users\Javid\Dropbox\Public\TerrariaModding\tModLoaderReleases\tModLoader Linux %version%.zip"

:: ExampleMod.zip (TODO, other parts of ExampleMod release)
rmdir ..\ExampleMod\bin /S /Q
rmdir ..\ExampleMod\obj /S /Q
call zipjs.bat zipItem -source "..\ExampleMod" -destination "%destinationFolder%\ExampleMod %version%.zip" -keep yes -force yes
::copy "%destinationFolder%\ExampleMod %version%.zip" "C:\Users\Javid\Dropbox\Public\TerrariaModding\tModLoaderReleases\"

:: TODO -- tModReader?

echo(
echo(
echo(
echo tModLoader %version% ready to release.
echo(
echo(
pause


text:
import arrow
import requests
from .models import MSLEvent

def get_msl_events_from_api(month_multiplier=1):

    # at the moment, msl only allows 3 month max event range
    from_date = arrow.utcnow()
    if month_multiplier > 1:
        from_date = from_date.shift(months=3 * (month_multiplier - 1))

    req = requests.get('https://www.sussexstudent.com/svc/feeds/events/0?subtree=true&from={from_date}&imagesize=event'.format(
        from_date=from_date.format('YYYY-MM-DD')
    ))

    if req.status_code == 200:
        return req.json()

    return []

def sync_events_from_msl():
    msl_events_requests = [get_msl_events_from_api(m) for m in range(0, 5)]

    msl_events = [y for x in msl_events_requests for y in x]
    msl_events_map = {item['Id']: item for item in msl_events}
    msl_event_ids = set(msl_events_map)
    event_matches = {event.msl_event_id: event for event in MSLEvent.objects.filter(msl_event_id__in=msl_event_ids)}

    report = {}

    for msl_event_id in msl_event_ids:
        if msl_event_id in event_matches:
            event_matches[msl_event_id].update_from_msl(msl_events_map[msl_event_id])
            report[msl_event_id] = 'updated'
        else:
            MSLEvent.create_from_msl(msl_events_map[msl_event_id])
            report[msl_event_id] = 'created new'

    print(report)


text:
package com.github.koraktor.steamcondenser.steam.community.tf2;

import com.github.koraktor.steamcondenser.steam.community.XMLData;

/**
 * Represents the stats for the Team Fortress 2 Sniper class for a specific
 * user
 *
 * @author  Sebastian Staudt
 */
public class TF2Sniper extends TF2Class {

    private int maxHeadshots;

    /**
     * Creates a new instance of the Sniper class based on the given XML data
     *
     * @param classData The XML data for this Sniper
     */
    public TF2Sniper(XMLData classData) {
        super(classData);

        this.maxHeadshots = classData.getInteger("iheadshots");
    }

    /**
     * Returns the maximum number enemies killed with a headshot by the player
     * in single life as a Sniper
     *
     * @return Maximum number of headshots
     */
    public int getMaxHeadshots() {
        return this.maxHeadshots;
    }
}


text:
import { first } from "lodash"
import gravity from "lib/loaders/legacy/gravity"
import Sale from "schema/sale/index"
import Sales from "schema/sales"
import Bidder from "schema/bidder"
import { GraphQLList, GraphQLBoolean, GraphQLObjectType } from "graphql"

export const SaleRegistrationType = new GraphQLObjectType({
  name: "SaleRegistration",
  fields: () => ({
    bidder: {
      type: Bidder.type,
    },
    is_registered: {
      type: GraphQLBoolean,
    },
    sale: {
      type: Sale.type,
    },
  }),
})

export default {
  type: new GraphQLList(SaleRegistrationType),
  args: Sales.args,
  resolve: (root, options, request, { rootValue: { accessToken } }) => {
    return gravity("sales", options).then(sales => {
      return Promise.all(
        sales.map(sale => {
          return gravity.with(accessToken)("me/bidders", { sale_id: sale.id }).then(bidders => {
            return {
              sale,
              bidder: first(bidders),
              is_registered: bidders.length > 0,
            }
          })
        })
      )
    })
  },
}


text:
'use strict';

let counter = 0;

module.exports = (next) => {

    return next(null, --counter);
};


text:
// Forward declaration of the read4 API.
int read4(char *buf);

class Solution {
	public:
		/**
			* @param buf Destination buffer
			* @param n   Maximum number of characters to read
			* @return    The number of characters read
			*/
		int read(char *buf, int n) {
			int read_bytes = 0;
			for (int i = 0; i <= n/4; i++) {
				int size = read4(buf + read_bytes);
				read_bytes += size;
				if (size < 4) {
					break;
				}
			}
			return min(read_bytes, n);
		}
};


text:
package connmgr

import (
	"io"
	"log"
	"net"
	"sync"
	"time"

	"github.com/huin/artemis/counter"
	"github.com/huin/artemis/net/artproto"
)

var sampler *counter.Sampler

func init() {
	sampler = counter.NewSampler(time.Second * 1)
}

func ServeReverseProxy(manager *ConnManager, l net.Listener, serverAddr string) error {
	for {
		clientConn, err := l.Accept()
		if err != nil {
			return err
		}

		log.Printf("Got new connection %v from %#v", clientConn.RemoteAddr(), l)

		serverConn, err := net.Dial("tcp", serverAddr)
		if err != nil {
			log.Printf("Error establishing connection to server for %s: %v",
				clientConn.RemoteAddr(), err)
			clientConn.Close()
			continue
		}

		log.Printf("Passing new connection %v to manager", clientConn.RemoteAddr())
		manager.HandleNewConnection(serverConn, clientConn)
	}
}

type ConnManager struct {
	lock   sync.RWMutex
	conns  map[int64]*Connection
	nextID int64

	connIntercept ConnIntercept

	outgoingBytesSent *counter.Counter
	outgoingBytesRate *counter.Rate
	incomingBytesSent *counter.Counter
	incomingBytesRate *counter.Rate
}

type ConnIntercept func(idConn IDConnection, serverConn, clientConn net.Conn) (net.Conn, net.Conn)

func NewConnManager() *ConnManager {
	manager := &ConnManager{
		conns:             make(map[int64]*Connection),
		outgoingBytesSent: new(counter.Counter),
		incomingBytesSent: new(counter.Counter),
	}
	manager.outgoingBytesRate = sampler.StartSampling(manager.outgoingBytesSent)
	manager.incomingBytesRate = sampler.StartSampling(manager.incomingBytesSent)
	return manager
}

func (manager *ConnManager) SetConnIntercept(fn ConnIntercept) {
	manager.lock.Lock()
	defer manager.lock.Unlock()
	manager.connIntercept = fn
}

func (manager *ConnManager) HandleNewConnection(serverConn, clientConn net.Conn) {
	c := NewConnection()

	id := manager.addConnection(c)
	c.onClose = func() {
		manager.removeConnection(id)
	}

	if connIntercept := manager.getConnIntercept(); connIntercept != nil {
		serverConn, clientConn = connIntercept(IDConnection{id, c}, serverConn, clientConn)
	}

	c.Start(serverConn, clientConn, manager.outgoingBytesSent, manager.incomingBytesSent)
}

func (manager *ConnManager) getConnIntercept() ConnIntercept {
	manager.lock.RLock()
	defer manager.lock.RUnlock()
	return manager.connIntercept
}

type IDConnection struct {
	ID   int64
	Conn *Connection
}

func (manager *ConnManager) Connections() []IDConnection {
	manager.lock.RLock()
	defer manager.lock.RUnlock()

	conns := make([]IDConnection, 0, len(manager.conns))
	for id, c := range manager.conns {
		conns = append(conns, IDConnection{id, c})
	}
	return conns
}

func (manager *ConnManager) Connection(id int64) *Connection {
	manager.lock.RLock()
	defer manager.lock.RUnlock()
	return manager.conns[id]
}

func (manager *ConnManager) addConnection(c *Connection) int64 {
	manager.lock.Lock()
	id := manager.nextID
	manager.nextID++
	manager.conns[id] = c
	manager.lock.Unlock()
	return id
}

func (manager *ConnManager) removeConnection(id int64) {
	manager.lock.Lock()
	delete(manager.conns, id)
	manager.lock.Unlock()
}

type ConnManagerStats struct {
	BytesOut, BytesIn         int64
	BytesOutRate, BytesInRate float64
}

func (manager *ConnManager) Stats() ConnManagerStats {
	return ConnManagerStats{
		BytesOut:     manager.outgoingBytesSent.Get(),
		BytesIn:      manager.incomingBytesSent.Get(),
		BytesOutRate: manager.outgoingBytesRate.Get(),
		BytesInRate:  manager.incomingBytesRate.Get(),
	}
}

type Connection struct {
	Outgoing StatsWriter
	Incoming StatsWriter

	serverConn net.Conn
	clientConn net.Conn
	onClose    func()

	startTime time.Time

	lock   sync.Mutex
	closed bool
	data   interface{}
}

func NewConnection() *Connection {
	c := &Connection{
		startTime: time.Now(),
	}
	return c
}

func (c *Connection) Start(serverConn, clientConn net.Conn, outgoingBytesSent,
	incomingBytesSent *counter.Counter) {
	c.serverConn = serverConn
	c.clientConn = clientConn
	c.Outgoing.Init(clientConn, outgoingBytesSent)
	c.Incoming.Init(serverConn, incomingBytesSent)
	go c.handleHalf(&c.Outgoing, c.serverConn)
	go c.handleHalf(&c.Incoming, c.clientConn)
}

func (c *Connection) Close() {
	c.lock.Lock()
	defer c.lock.Unlock()

	if c.closed {
		return
	}

	c.serverConn.Close()
	c.clientConn.Close()
	if c.onClose != nil {
		c.onClose()
	}
	c.closed = true

	c.Outgoing.Stop()
	c.Incoming.Stop()
}

func (c *Connection) ClientAddr() net.Addr {
	return c.clientConn.RemoteAddr()
}

func (c *Connection) StartTime() time.Time {
	return c.startTime
}

// SetData stores some arbitrary data for the connection.
func (c *Connection) SetData(data interface{}) {
	c.lock.Lock()
	c.data = data
	c.lock.Unlock()
}

// Data returns data set via SetData.
func (c *Connection) Data() interface{} {
	c.lock.Lock()
	data := c.data
	c.lock.Unlock()
	return data
}

func (c *Connection) handleHalf(dest io.Writer, src io.Reader) {
	defer c.Close()
	r := artproto.NewFramedReader(src, 2048)
	if _, err := io.Copy(dest, r); err != io.EOF {
		c.reportError(err)
	}
}

func (c *Connection) reportError(err error) {
	c.lock.Lock()
	defer c.lock.Unlock()

	if c.closed {
		return
	}
	log.Print("Connection failed: ", err)
}

type StatsWriter struct {
	W                io.Writer
	CommonBytesSent  *counter.Counter
	BytesSent        *counter.Counter
	ByteRate         *counter.Rate
	WriteLatency     *counter.Counter
	WriteLatencyRate *counter.Rate
}

func (s *StatsWriter) Init(w io.Writer, commonBytesSent *counter.Counter) {
	s.W = w
	s.CommonBytesSent = commonBytesSent
	s.BytesSent = new(counter.Counter)
	s.ByteRate = sampler.StartSampling(s.BytesSent)
	s.WriteLatency = new(counter.Counter)
	s.WriteLatencyRate = sampler.StartSampling(s.WriteLatency)
}

func (s *StatsWriter) Write(p []byte) (n int, err error) {
	before := time.Now()
	log.SetFlags(log.LstdFlags | log.Lmicroseconds)
	n, err = s.W.Write(p)
	after := time.Now()
	s.CommonBytesSent.Add(int64(n))
	s.BytesSent.Add(int64(n))
	s.WriteLatency.Add(int64(after.Sub(before)))
	return n, err
}

func (s *StatsWriter) Stop() {
	sampler.StopSampling(s.BytesSent)
	sampler.StopSampling(s.WriteLatency)
}


text:
import { NativeScriptConfig } from '@nativescript/core'

export default {
  id: 'org.nativescript.firebasedemo',
  appResourcesPath: 'app_resources',
  android: {
    v8Flags: '--expose_gc',
    markingMode: 'none',
  },
  discardUncaughtJsExceptions: false,
  appPath: 'app',
} as NativeScriptConfig


text:
package au.gov.ga.geodesy.support.testng;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.orm.jpa.JpaSystemException;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.TestListenerAdapter;

public class TestListener extends TestListenerAdapter implements ITestListener {
    public void onTestFailure(ITestResult failure) {
        Throwable x = failure.getThrowable();
        // TODO: can we get the root cause polymorphicaly?
        if (x instanceof DataIntegrityViolationException) {
            ((DataIntegrityViolationException) x).getRootCause().printStackTrace();
        } else if (x instanceof JpaSystemException) {
            ((JpaSystemException) x).getRootCause().printStackTrace();
        } else if (x instanceof InvalidDataAccessResourceUsageException) {
            ((InvalidDataAccessResourceUsageException) x).getRootCause().printStackTrace();
        }
        super.onTestFailure(failure);
    }
}


text:
package com.leaf.downloads;

import android.app.DownloadManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.SystemClock;
import android.support.test.espresso.core.deps.guava.collect.ArrayListMultimap;
import android.support.test.espresso.core.deps.guava.collect.Maps;
import android.support.test.espresso.core.deps.guava.collect.Multimap;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;

import com.leaf.downloads.utils.DateTimeUtils;

import java.text.NumberFormat;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;

import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE;
import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED;
import static android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION;

/**
 * Update {@link NotificationManager} to reflect current {@link DownloadInfo}
 * states. Collapses similar downloads into a single notification, and builds
 * {@link PendingIntent} that launch towards {@link DownloadReceiver}.
 */
public class DownloadNotifier {
    private static final int TYPE_ACTIVE = 1;
    private static final int TYPE_WAITING = 2;
    private static final int TYPE_COMPLETE = 3;
    private final Context mContext;
    private final NotificationManager mNotifManager;
    /**
     * Currently active notifications, mapped from clustering tag to timestamp
     * when first shown.
     *
     * @see #buildNotificationTag(DownloadInfo)
     */
    private final HashMap<String, Long> mActiveNotifs = Maps.newHashMap();
    private static final HashMap<Long, Long> mDownloadSpeed = new HashMap<>();
    private final HashMap<Long, Long> mDownloadTouch = new HashMap<>();
    private static final String TAG = "DownloadNotifier";
    private static final boolean DEBUG = Constants.LOGV;

    public DownloadNotifier(Context context) {
        mContext = context;
        mNotifManager = (NotificationManager) context.getSystemService(
                Context.NOTIFICATION_SERVICE);
    }

    public void notifyDownloadSpeed(long id, long bytesPerSecond) {
        synchronized (mDownloadSpeed) {
            if (DEBUG) {
                Log.d(TAG, "notifyDownloadSpeed bytesPerSecond :" + bytesPerSecond);
            }
            if (bytesPerSecond != 0) {
                mDownloadSpeed.put(id, bytesPerSecond);
                mDownloadTouch.put(id, SystemClock.elapsedRealtime());
            } else {
                mDownloadSpeed.remove(id);
                mDownloadTouch.remove(id);
            }
        }
    }

    public static long getDownloadSpeed(long id) {
        if (mDownloadSpeed.containsKey(id)) {
            return mDownloadSpeed.get(id);
        }
        return 0;
    }

    /**
     * Update {@link NotificationManager} to reflect the given set of
     * {@link DownloadInfo}, adding, collapsing, and removing as needed.
     */
    public void updateWith(Collection<DownloadInfo> downloads) {
        synchronized (mActiveNotifs) {
            updateWithLocked(downloads);
        }
    }

    private void updateWithLocked(Collection<DownloadInfo> downloads) {
        final Resources res = mContext.getResources();
        // Cluster downloads together
        final Multimap<String, DownloadInfo> clustered = ArrayListMultimap.create();
        for (DownloadInfo info : downloads) {
            final String tag = buildNotificationTag(info);
            if (tag != null) {
                clustered.put(tag, info);
            }
        }
        // Build notification for each cluster
        for (String tag : clustered.keySet()) {
            final int type = getNotificationTagType(tag);
            final Collection<DownloadInfo> cluster = clustered.get(tag);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(mContext);
            // Use time when cluster was first shown to avoid shuffling
            final long firstShown;
            if (mActiveNotifs.containsKey(tag)) {
                firstShown = mActiveNotifs.get(tag);
            } else {
                firstShown = System.currentTimeMillis();
                mActiveNotifs.put(tag, firstShown);
            }
            builder.setWhen(firstShown);
            // Show relevant icon
            if (type == TYPE_ACTIVE) {
                builder.setSmallIcon(android.R.drawable.stat_sys_download);
            } else if (type == TYPE_WAITING) {
                builder.setSmallIcon(android.R.drawable.stat_sys_warning);
            } else if (type == TYPE_COMPLETE) {
                builder.setSmallIcon(android.R.drawable.stat_sys_download_done);
            }
            // Build action intents
            if (type == TYPE_ACTIVE || type == TYPE_WAITING) {
                final Intent intent = new Intent(Constants.ACTION_LIST,
                        null, mContext, DownloadReceiver.class);
                intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
                        getDownloadIds(cluster));
                builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0));
                builder.setOngoing(true);
            } else if (type == TYPE_COMPLETE) {
                builder.setAutoCancel(true);
                final DownloadInfo info = cluster.iterator().next();
                final Uri uri = ContentUris.withAppendedId(
                        Downloads.Impl.CONTENT_URI, info.mId);
                final String action;
                if (Downloads.Impl.isStatusError(info.mStatus)) {
                    action = Constants.ACTION_LIST;
                } else {
                    if (info.mDestination != Downloads.Impl.DESTINATION_SYSTEMCACHE_PARTITION) {
                        action = Constants.ACTION_OPEN;
                    } else {
                        action = Constants.ACTION_LIST;
                    }
                }
                final Intent intent = new Intent(action, uri, mContext, DownloadReceiver.class);
                intent.putExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS,
                        getDownloadIds(cluster));
                builder.setContentIntent(PendingIntent.getBroadcast(mContext, 0, intent, 0));
                final Intent hideIntent = new Intent(Constants.ACTION_HIDE,
                        uri, mContext, DownloadReceiver.class);
                builder.setDeleteIntent(PendingIntent.getBroadcast(mContext, 0, hideIntent, 0));
            }
            // Calculate and show progress
            String remainingText = null;
            String percentText = null;
            if (type == TYPE_ACTIVE) {
                long current = 0;
                long total = 0;
                long speed = 0;

                synchronized (mDownloadSpeed) {
                    for (DownloadInfo info : cluster) {
                        if (info.mTotalBytes != -1) {
                            current += info.mCurrentBytes;
                            total += info.mTotalBytes;
                            if (mDownloadSpeed != null && mDownloadSpeed.size() > 0) {
                                if (mDownloadSpeed.containsKey(info.mId)) {
                                    speed += mDownloadSpeed.get(info.mId);
                                } else {
                                    if (Constants.LOGV) {
                                        Log.d(TAG, "notifyDownloadSpeed mDownloadSpeed :" + mDownloadSpeed.size() + " info.mId:" + info.mId);
                                    }
                                }
                            }
                        }
                    }
                }
                if (total > 0) {
                    int percent = (int) ((current * 100) / total);
                    percentText =
                            NumberFormat.getPercentInstance().format((double) current / total);
                    if (speed > 0) {
                        final long remainingMillis = ((total - current) * 1000) / speed;
                        remainingText = res.getString(R.string.download_remaining,
                                DateTimeUtils.formatDuration(mContext, remainingMillis));
                    }
                    builder.setProgress(100, percent, false);
                } else {
                    builder.setProgress(100, 0, true);
                }
            }
            // Build titles and description
            final Notification notif;
            if (cluster.size() == 1) {
                final DownloadInfo info = cluster.iterator().next();
                builder.setContentTitle(getDownloadTitle(res, info));
                if (type == TYPE_ACTIVE) {
                    if (!TextUtils.isEmpty(info.mDescription)) {
                        builder.setContentText(info.mDescription);
                    } else {
                        builder.setContentText(remainingText);
                    }
                    builder.setContentInfo(percentText);
                } else if (type == TYPE_WAITING) {
                    builder.setContentText(
                            res.getString(R.string.notification_need_wifi_for_size));
                } else if (type == TYPE_COMPLETE) {
                    if (Downloads.Impl.isStatusError(info.mStatus)) {
                        builder.setContentText(res.getText(R.string.notification_download_failed));
                    } else if (Downloads.Impl.isStatusSuccess(info.mStatus)) {
                        builder.setContentText(
                                res.getText(R.string.notification_download_complete));
                    }
                }
                notif = builder.build();
            } else {
                final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(builder);
                for (DownloadInfo info : cluster) {
                    inboxStyle.addLine(getDownloadTitle(res, info));
                }
                if (type == TYPE_ACTIVE) {
                    builder.setContentTitle(res.getQuantityString(
                            R.plurals.notif_summary_active, cluster.size(), cluster.size()));
                    builder.setContentText(remainingText);
                    builder.setContentInfo(percentText);
                    inboxStyle.setSummaryText(remainingText);
                } else if (type == TYPE_WAITING) {
                    builder.setContentTitle(res.getQuantityString(
                            R.plurals.notif_summary_waiting, cluster.size(), cluster.size()));
                    builder.setContentText(
                            res.getString(R.string.notification_need_wifi_for_size));
                    inboxStyle.setSummaryText(
                            res.getString(R.string.notification_need_wifi_for_size));
                }
                notif = inboxStyle.build();
            }
            mNotifManager.notify(tag, 0, notif);
        }
        // Remove stale tags that weren't renewed
        final Iterator<String> it = mActiveNotifs.keySet().iterator();
        while (it.hasNext()) {
            final String tag = it.next();
            if (!clustered.containsKey(tag)) {
                mNotifManager.cancel(tag, 0);
                it.remove();
            }
        }
    }

    private static CharSequence getDownloadTitle(Resources res, DownloadInfo info) {
        if (!TextUtils.isEmpty(info.mTitle)) {
            return info.mTitle;
        } else {
            return res.getString(R.string.download_unknown_title);
        }
    }

    private long[] getDownloadIds(Collection<DownloadInfo> infos) {
        final long[] ids = new long[infos.size()];
        int i = 0;
        for (DownloadInfo info : infos) {
            ids[i++] = info.mId;
        }
        return ids;
    }

    /**
     * Build tag used for collapsing several {@link DownloadInfo} into a single
     * {@link Notification}.
     */
    private static String buildNotificationTag(DownloadInfo info) {
        if (info.mStatus == Downloads.Impl.STATUS_QUEUED_FOR_WIFI) {
            return TYPE_WAITING + ":" + info.mPackage;
        } else if (isActiveAndVisible(info)) {
            return TYPE_ACTIVE + ":" + info.mPackage;
        } else if (isCompleteAndVisible(info)) {
            // Complete downloads always have unique notifs
            return TYPE_COMPLETE + ":" + info.mId;
        } else {
            return null;
        }
    }

    /**
     * Return the cluster type of the given tag, as created by
     * {@link #buildNotificationTag(DownloadInfo)}.
     */
    private static int getNotificationTagType(String tag) {
        return Integer.parseInt(tag.substring(0, tag.indexOf(':')));
    }

    private static boolean isActiveAndVisible(DownloadInfo download) {
        return Downloads.Impl.isStatusInformational(download.mStatus) &&
                (download.mVisibility == VISIBILITY_VISIBLE
                        || download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }

    private static boolean isCompleteAndVisible(DownloadInfo download) {
        return Downloads.Impl.isStatusCompleted(download.mStatus) &&
                (download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_COMPLETED
                        || download.mVisibility == VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION);
    }

}


text:
"""
    thriftpy.thrift
    ~~~~~~~~~~~~~~~~~~

    Thrift simplified.
"""

from __future__ import absolute_import

import functools
import inspect

from ._compat import init_func_generator, with_metaclass

def args2kwargs(thrift_spec, *args):
    arg_names = [item[1][1] for item in sorted(thrift_spec.items())]
    return dict(zip(arg_names, args))

class TType(object):
    STOP = 0
    VOID = 1
    BOOL = 2
    BYTE = 3
    I08 = 3
    DOUBLE = 4
    I16 = 6
    I32 = 8
    I64 = 10
    STRING = 11
    UTF7 = 11
    BINARY = 11  # This here just for parsing. For all purposes, it's a string
    STRUCT = 12
    MAP = 13
    SET = 14
    LIST = 15
    UTF8 = 16
    UTF16 = 17

    _VALUES_TO_NAMES = {
        STOP: 'STOP',
        VOID: 'VOID',
        BOOL: 'BOOL',
        BYTE: 'BYTE',
        I08: 'BYTE',
        DOUBLE: 'DOUBLE',
        I16: 'I16',
        I32: 'I32',
        I64: 'I64',
        STRING: 'STRING',
        UTF7: 'STRING',
        BINARY: 'STRING',
        STRUCT: 'STRUCT',
        MAP: 'MAP',
        SET: 'SET',
        LIST: 'LIST',
        UTF8: 'UTF8',
        UTF16: 'UTF16'
    }

class TMessageType(object):
    CALL = 1
    REPLY = 2
    EXCEPTION = 3
    ONEWAY = 4

class TPayloadMeta(type):
    def __new__(cls, name, bases, attrs):
        if "default_spec" in attrs:
            attrs["__init__"] = init_func_generator(attrs.pop("default_spec"))
        return super(TPayloadMeta, cls).__new__(cls, name, bases, attrs)

def gen_init(cls, thrift_spec=None, default_spec=None):
    if thrift_spec is not None:
        cls.thrift_spec = thrift_spec

    if "default_spec" is not None:
        cls.__init__ = init_func_generator(default_spec)
    return cls

class TPayload(with_metaclass(TPayloadMeta, object)):

    def read(self, iprot):
        iprot.read_struct(self)

    def write(self, oprot):
        oprot.write_struct(self)

    def __repr__(self):
        l = ['%s=%r' % (key, value) for key, value in self.__dict__.items()]
        return '%s(%s)' % (self.__class__.__name__, ', '.join(l))

    def __str__(self):
        return repr(self)

    def __eq__(self, other):
        return isinstance(other, self.__class__) and \
            self.__dict__ == other.__dict__

    def __hash__(self):
        return super(TPayload, self).__hash__()

    def __ne__(self, other):
        return not self.__eq__(other)

class TClient(object):
    def __init__(self, service, iprot, oprot=None):
        self._service = service
        self._iprot = self._oprot = iprot
        if oprot is not None:
            self._oprot = oprot
        self._seqid = 0

    def __getattr__(self, _api):
        if _api in self._service.thrift_services:
            return functools.partial(self._req, _api)

        raise AttributeError("{} instance has no attribute '{}'".format(
            self.__class__.__name__, _api))

    def __dir__(self):
        return self._service.thrift_services

    def _req(self, _api, *args, **kwargs):
        _kw = args2kwargs(getattr(self._service, _api + "_args").thrift_spec,
                          *args)
        kwargs.update(_kw)
        result_cls = getattr(self._service, _api + "_result")

        self._send(_api, **kwargs)
        # wait result only if non-oneway
        if not getattr(result_cls, "oneway"):
            return self._recv(_api)

    def _send(self, _api, **kwargs):
        self._oprot.write_message_begin(_api, TMessageType.CALL, self._seqid)
        args = getattr(self._service, _api + "_args")()
        for k, v in kwargs.items():
            setattr(args, k, v)
        args.write(self._oprot)
        self._oprot.write_message_end()
        self._oprot.trans.flush()

    def _recv(self, _api):
        fname, mtype, rseqid = self._iprot.read_message_begin()
        if mtype == TMessageType.EXCEPTION:
            x = TApplicationException()
            x.read(self._iprot)
            self._iprot.read_message_end()
            raise x
        result = getattr(self._service, _api + "_result")()
        result.read(self._iprot)
        self._iprot.read_message_end()

        if hasattr(result, "success") and result.success is not None:
            return result.success

        # void api without throws
        if len(result.thrift_spec) == 0:
            return

        # check throws
        for k, v in result.__dict__.items():
            if k != "success" and v is not None:
                raise v

        # no throws & not void api
        if hasattr(result, "success"):
            raise TApplicationException(TApplicationException.MISSING_RESULT)

class TProcessor(object):
    """Base class for procsessor, which works on two streams."""

    def __init__(self, service, handler):
        self._service = service
        self._handler = handler

    def process_in(self, iprot):
        api, type, seqid = iprot.read_message_begin()
        if api not in self._service.thrift_services:
            iprot.skip(TType.STRUCT)
            iprot.read_message_end()
            return api, seqid, TApplicationException(TApplicationException.UNKNOWN_METHOD), None   # noqa

        args = getattr(self._service, api + "_args")()
        args.read(iprot)
        iprot.read_message_end()
        result = getattr(self._service, api + "_result")()

        # convert kwargs to args
        api_args = [args.thrift_spec[k][1]
                    for k in sorted(args.thrift_spec)]

        def call():
            return getattr(self._handler, api)(
                *(args.__dict__[k] for k in api_args)
            )

        return api, seqid, result, call

    def send_exception(self, oprot, api, exc, seqid):
        oprot.write_message_begin(api, TMessageType.EXCEPTION, seqid)
        exc.write(oprot)
        oprot.write_message_end()
        oprot.trans.flush()

    def send_result(self, oprot, api, result, seqid):
        oprot.write_message_begin(api, TMessageType.REPLY, seqid)
        result.write(oprot)
        oprot.write_message_end()
        oprot.trans.flush()

    def handle_exception(self, e, result):
        for k in sorted(result.thrift_spec):
            if result.thrift_spec[k][1] == "success":
                continue

            _, exc_name, exc_cls, _ = result.thrift_spec[k]
            if isinstance(e, exc_cls):
                setattr(result, exc_name, e)
                break
        else:
            raise

    def process(self, iprot, oprot):
        api, seqid, result, call = self.process_in(iprot)

        if isinstance(result, TApplicationException):
            return self.send_exception(oprot, api, result, seqid)

        try:
            result.success = call()
        except Exception as e:
            # raise if api don't have throws
            self.handle_exception(e, result)

        if not result.oneway:
            self.send_result(oprot, api, result, seqid)

class TMultiplexingProcessor(TProcessor):
    processors = {}
    service_map = {}

    def __init__(self):
        pass

    def register_processor(self, processor):
        service = processor._service
        module = inspect.getmodule(processor)
        name = '{0}:{1}'.format(module.__name__, service.__name__)
        if name in self.processors:
            raise TApplicationException(
                type=TApplicationException.INTERNAL_ERROR,
                message='processor for `{0}` already registered'.format(name))

        for srv in service.thrift_services:
            if srv in self.service_map:
                raise TApplicationException(
                    type=TApplicationException.INTERNAL_ERROR,
                    message='cannot multiplex processor for `{0}`; '
                            '`{1}` is already a registered method for `{2}`'
                            .format(name, srv, self.service_map[srv]))
            self.service_map[srv] = name

        self.processors[name] = processor

    def process_in(self, iprot):
        api, type, seqid = iprot.read_message_begin()
        if api not in self.service_map:
            iprot.skip(TType.STRUCT)
            iprot.read_message_end()
            e = TApplicationException(TApplicationException.UNKNOWN_METHOD)
            return api, seqid, e, None   # noqa

        proc = self.processors[self.service_map[api]]
        args = getattr(proc._service, api + "_args")()
        args.read(iprot)
        iprot.read_message_end()
        result = getattr(proc._service, api + "_result")()

        # convert kwargs to args
        api_args = [args.thrift_spec[k][1]
                    for k in sorted(args.thrift_spec)]

        def call():
            f = getattr(proc._handler, api)
            return f(*(args.__dict__[k] for k in api_args))

        return api, seqid, result, call

class TProcessorFactory(object):
    def __init__(self, processor_class, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs

        self.processor_class = processor_class

    def get_processor(self):
        return self.processor_class(*self.args, **self.kwargs)

class TException(TPayload, Exception):
    """Base class for all thrift exceptions."""

class TApplicationException(TException):
    """Application level thrift exceptions."""

    thrift_spec = {
        1: (TType.STRING, 'message', False),
        2: (TType.I32, 'type', False),
    }

    UNKNOWN = 0
    UNKNOWN_METHOD = 1
    INVALID_MESSAGE_TYPE = 2
    WRONG_METHOD_NAME = 3
    BAD_SEQUENCE_ID = 4
    MISSING_RESULT = 5
    INTERNAL_ERROR = 6
    PROTOCOL_ERROR = 7

    def __init__(self, type=UNKNOWN, message=None):
        super(TApplicationException, self).__init__()
        self.type = type
        self.message = message

    def __str__(self):
        if self.message:
            return self.message

        if self.type == self.UNKNOWN_METHOD:
            return 'Unknown method'
        elif self.type == self.INVALID_MESSAGE_TYPE:
            return 'Invalid message type'
        elif self.type == self.WRONG_METHOD_NAME:
            return 'Wrong method name'
        elif self.type == self.BAD_SEQUENCE_ID:
            return 'Bad sequence ID'
        elif self.type == self.MISSING_RESULT:
            return 'Missing result'
        else:
            return 'Default (unknown) TApplicationException'


text:
> *Show me your flowcharts and conceal your tables, and I shall continue to be mystified.
>  Show me your tables, and I won't usually need your flowcharts; they'll be obvious.*
>
> ------- <cite>Frederick Brooks, The Mythical Man-Month (1975)</cite>

###Introduction

Flowcharts are mostly about presenting **how to implement** algorithm, instead of presenting **the main idea** of algorithm.

There are a lot of ways to present algorithms ideas:

Basic idea of the insetion sort:
http://staff.ustc.edu.cn/~csli/graduate/algorithms/book6/3_a.gif

Insertion sort:
https://upload.wikimedia.org/wikipedia/commons/7/7e/Insertionsort-edited.png

Merge sort:
https://upload.wikimedia.org/wikipedia/commons/thumb/e/e6/Merge_sort_algorithm_diagram.svg/618px-Merge_sort_algorithm_diagram.svg.png

What if try to consider...
***Algorithm == set of changes applied to the input data to produce output data?***

???

https://git-scm.com/images/branching-illustration@2x.png

Definitely the purpose of git system differs a lot. But the main idea that data change itself much more simple to store
and to use than whole file storing.

### Main idea

So what if we could build the system that could:

- to move from the input data to the output data step by step.
- each step is a data change.
- data change could be displayed according to it's type (simplified case)

### Implementation steps

- **Choose source language - Python.**
    - Algorithm itself has a lot of difficulties, and there is no reason to add new.(not C-language)
    - Python is inside TOP-10 popular programming languages.
    - Python has a lot of tools to parse itself.
    - MIT choosed Python as an main language for the Introduction for to algorithms (2011)

- **Design structure**
    - Separate **Visualization** from **Logic**
    - Command-line component
    - Source code tranformer
    - Data changes analyser
    - Visualizations model builder
    - Visualizer

- **Implement components (using methodology)**

### Current state of the project

- Analyze the places where data changes should be collected ✅
- Transform source code to collect necessary data changes ✅
- Evaluate transformed source code ✅
- Build function calls models ✅
- Do filtration to remove unnecessary data
- Build visualiser models
- Implement drawing of the models

### Difficulties.

- Not all algorithms are suitable for the such approach
- A lot temporary variables that will also be found as a data change. (Filtration needed).
- Effective visualizations should consider grouping of the data changes (trees, flows)

### Questions?

### The End

### References

- http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-fall-2011/

Thank you for your time.

yury.lapitsky@gmail.com

https://github.com/skyylex/Luminous-proof-of-concept


text:
namespace ZetaResourceEditor.UI.Tools;

using Helper.Base;
using Properties;
using RuntimeUserInterface.Shell;

public partial class AboutForm :
    FormBase
{
    public AboutForm()
    {
        InitializeComponent();
    }

    private void AboutForm_Load(
        object sender,
        EventArgs e)
    {
        CenterToParent();

        label4.Text = label4.Text.
            Replace(@"{VersionNo}",
                Assembly.GetExecutingAssembly().GetName().Version.ToString()).
            Replace(@"{BuildDate}",
                File.GetLastWriteTime(Assembly.GetExecutingAssembly().Location).ToString(@"g"));
    }

    private void linkLabel1_Properties_Click(object sender, EventArgs e)
    {
        var sei =
            new ShellExecuteInformation
            {
                FileName =
                    Resources.SR_AboutForm_linkLabel1LinkClicked_Httpwwwzetasoftwaredelinkszrehome
            };
        sei.Execute();
    }

    private void linkLabel1_OpenLink(object sender, OpenLinkEventArgs e)
    {
        e.Handled = true;
        linkLabel1_Properties_Click(null, null);
    }
}


text:
hello_python
============

Scripts to learn the python language

This repo it a test repo to learn the usgae of git, and backup the python scripts when learn the Python online courses.

[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/haozai309/hello_python/trend.png)](https://bitdeli.com/free "Bitdeli Badge")


text:
'use strict';
var P = require('bluebird')
var Recaptcha = require('recaptcha').Recaptcha
var nodemailer = require('nodemailer')
var jade = require('jade')

var sequelize = require('../../helpers/sequelize')()

var ContactEmail = sequelize.models.ContactEmail

var config = require('../../config')

/**
 * Contact Us
 * @param {object} req
 * @param {object} res
 */
exports.index = function(req,res){
  var recaptcha = new Recaptcha(
    config.recaptcha.publicKey,
    config.recaptcha.privateKey
  )
  res.render('contact',{
    recaptcha: recaptcha.toHTML()
  })
}

/**
 * Save
 * @param {object} req
 * @param {object} res
 */
exports.save = function(req,res){
  var data = req.body
  var recaptcha = new Recaptcha(
    config.recaptcha.publicKey,
    config.recaptcha.privateKey,
    {
      remoteip: req.ip,
      challenge: req.body.recaptcha_challenge_field, // jshint ignore:line
      response: req.body.recaptcha_response_field // jshint ignore:line
    }
  )
  new P(function(resolve,reject){
    recaptcha.verify(function(success){
      if(success) return resolve()
      else reject('Captcha response invalid')
    })
  })
    .then(function(){
      ContactEmail.create({
        email: data.email,
        name: data.name,
        message: data.message
      })
    })
    .then(function(){
      var fn = jade.compileFile('main/themes/animegg/views/contactTemplate.jade')
      var html = fn({data: data})
      var transporter = nodemailer.createTransport({
        service: config.gmailcontact.service,
        auth: config.gmailcontact.auth
      });
      transporter.sendMail({
        from: config.gmailcontact.from,
        to: config.gmailcontact.to,
        subject: 'New Animegg Contact Email',
        html: html
      })
    })
    .then(function(){
      req.flash('success','Email sent successfully')
      res.redirect('/')
    })
    .catch(function(err){
      req.flash('error','There was an error filing the report ' + err)
      res.redirect('/')
    })
}


text:
MOVED TO https://github.com/vtex/ui-matter
=========


text:
fcViews.month = MonthView;

function MonthView(element, calendar) {
	var t = this;

	// exports
	t.render = render;

	// imports
	BasicView.call(t, element, calendar, 'month');
	var opt = t.opt;
	var renderBasic = t.renderBasic;
	var skipHiddenDays = t.skipHiddenDays;
	var getCellsPerWeek = t.getCellsPerWeek;
	var formatDate = calendar.formatDate;

	function render(date, delta) {

		if (delta) {
			addMonths(date, delta);
			date.setDate(1);
		}

		var firstDay = opt('firstDay');

		var start = cloneDate(date, true);
		start.setDate(1);

		var end = addMonths(cloneDate(start), 1);

		var visStart = cloneDate(start);
		addDays(visStart, -((visStart.getDay() - firstDay + 7) % 7));
		skipHiddenDays(visStart);

		var visEnd = cloneDate(end);
		addDays(visEnd, (7 - visEnd.getDay() + firstDay) % 7);
		skipHiddenDays(visEnd, -1, true);

		var colCnt = getCellsPerWeek();
		var rowCnt = Math.round(dayDiff(visEnd, visStart) / 7); // should be no need for Math.round

		if (opt('weekMode') == 'fixed') {
			addDays(visEnd, (6 - rowCnt) * 7); // add weeks to make up for it
			rowCnt = 6;
		}

		t.title = formatDate(start, opt('titleFormat'));

		t.start = start;
		t.end = end;
		t.visStart = visStart;
		t.visEnd = visEnd;

		renderBasic(rowCnt, colCnt, true);
	}

}


text:
require 'ffi'

module BCrypt
  class Engine
    extend FFI::Library

    BCRYPT_MAXSALT = 16
    BCRYPT_SALT_OUTPUT_SIZE = 7 + (BCRYPT_MAXSALT * 4 + 2) / 3 + 1
    BCRYPT_OUTPUT_SIZE = 128

    ffi_lib File.expand_path("../bcrypt_ext", __FILE__)

    attach_function :ruby_bcrypt, [:buffer_out, :string, :string], :string
    attach_function :ruby_bcrypt_gensalt, [:buffer_out, :uint8, :pointer], :string

    def self.__bc_salt(cost, seed)
      buffer_out = FFI::Buffer.alloc_out(BCRYPT_SALT_OUTPUT_SIZE, 1)
      seed_ptr = FFI::MemoryPointer.new(:uint8, BCRYPT_MAXSALT)
      seed.bytes.to_a.each_with_index { |b, i| seed_ptr.int8_put(i, b) }
      out = ruby_bcrypt_gensalt(buffer_out, cost, seed_ptr)
      seed_ptr.free
      buffer_out.free
      out || ""
    end

    def self.__bc_crypt(key, salt, cost)
      buffer_out = FFI::Buffer.alloc_out(BCRYPT_OUTPUT_SIZE, 1)
      out = ruby_bcrypt(buffer_out, key || "", salt)
      buffer_out.free
      out && out.any? ? out : nil
    end
  end
end


text:
var speech = angular.module('speech', []);

speech.factory('Speech', function ($log, $q) {

    var is_available = ('speechSynthesis' in window);

    var voices = [];
    speechSynthesis.onvoiceschanged = function (event) {
        voices = speechSynthesis.getVoices();
    };

    var get_voice_for_language = function (language) {
        var voice_matches_language = function (v) { return v.lang === language};
        var voices_for_lang = voices.filter(voice_matches_language);
        var preferred_voice = voices_for_lang.slice(-1)[0];
        if (!preferred_voice) {
            $log.warn('Could not select voice for "%s"', language);
        }
        return preferred_voice;
    };

    var service = {
        say: function (text) {
            var utterance = new SpeechSynthesisUtterance(text);
            var utterance_promise = $q(function (resolve, reject) {
                utterance.onend = resolve;
                utterance.onerror = reject;
            });
            var voice = get_voice_for_language(preferred_language);
            if (voice) {
                utterance.voice = voice;
            } else {
                utterance.lang = preferred_language;
            }
            speechSynthesis.speak(utterance);
            return utterance_promise;
        }
    };

    var preferred_language = null;
    Object.defineProperty(service, 'language', {
        get: function () { return preferred_language; },
        set: function (language) { preferred_language = language; },
        enumerable: true,
        configurable: true
    });

    return service;
});


text:
/*
 * Copyright 2001-2005 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sun.org.apache.xerces.internal.utils;

import java.io.InputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;

import java.util.Properties;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * This class is duplicated for each JAXP subpackage so keep it in sync.
 * It is package private and therefore is not exposed as part of the JAXP
 * API.
 *

 * This code is designed to implement the JAXP 1.1 spec pluggability
 * feature and is designed to run on JDK version 1.1 and
 * later, and to compile on JDK 1.2 and onward.
 * The code also runs both as part of an unbundled jar file and
 * when bundled as part of the JDK.
 *

 *
 * @version $Id: ObjectFactory.java,v 1.6 2010/04/23 01:44:34 joehw Exp $
 */
public final class ObjectFactory {

    //
    // Constants
    //

    // name of default properties file to look for in JDK's jre/lib directory
    private static final String DEFAULT_PROPERTIES_FILENAME = "xerces.properties";

    /** Set to true for debugging */
    private static final boolean DEBUG = isDebugEnabled();

    /**
     * Default columns per line.
     */
    private static final int DEFAULT_LINE_LENGTH = 80;

    /** cache the contents of the xerces.properties file.
     *  Until an attempt has been made to read this file, this will
     * be null; if the file does not exist or we encounter some other error
     * during the read, this will be empty.
     */
    private static Properties fXercesProperties = null;

    /***
     * Cache the time stamp of the xerces.properties file so
     * that we know if it's been modified and can invalidate
     * the cache when necessary.
     */
    private static long fLastModified = -1;

    //
    // static methods
    //

    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return Class object of factory, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    public static Object createObject(String factoryId, String fallbackClassName)
        throws ConfigurationError {
        return createObject(factoryId, null, fallbackClassName);
    } // createObject(String,String):Object

    /**
     * Finds the implementation Class object in the specified order.  The
     * specified order is the following:
     *

     *
query the system property using System.getProperty
     *
read $java.home/lib/propertiesFilename file
     *
read META-INF/services/factoryId file
     *
use fallback classname
     *

     *
     * @return Class object of factory, never null
     *
     * @param factoryId             Name of the factory to find, same as
     *                              a property name
     * @param propertiesFilename The filename in the $java.home/lib directory
     *                           of the properties file.  If none specified,
     *                           ${java.home}/lib/xerces.properties will be used.
     * @param fallbackClassName     Implementation class name, if nothing else
     *                              is found.  Use null to mean no fallback.
     *
     * @exception ObjectFactory.ConfigurationError
     */
    public static Object createObject(String factoryId,
                                      String propertiesFilename,
                                      String fallbackClassName)
        throws ConfigurationError
    {
        if (DEBUG) debugPrintln("debug is on");

        ClassLoader cl = findClassLoader();

        // Use the system property first
        try {
            String systemProp = SecuritySupport.getSystemProperty(factoryId);
            if (systemProp != null && systemProp.length() > 0) {
                if (DEBUG) debugPrintln("found system property, value=" + systemProp);
                return newInstance(systemProp, cl, true);
            }
        } catch (SecurityException se) {
            // Ignore and continue w/ next location
        }

        // JAXP specific change
        // always use fallback class to avoid the expense of constantly
        // "stat"ing a non-existent "xerces.properties" and jar SPI entry
        // see CR 6400863: Expensive creating of SAX parser in Mustang
        if (fallbackClassName == null) {
            throw new ConfigurationError(
                "Provider for " + factoryId + " cannot be found", null);
        }

        if (DEBUG) debugPrintln("using fallback, value=" + fallbackClassName);
        return newInstance(fallbackClassName, cl, true);

    } // createObject(String,String,String):Object

    //
    // Private static methods
    //

    /** Returns true if debug has been enabled. */
    private static boolean isDebugEnabled() {
        try {
            String val = SecuritySupport.getSystemProperty("xerces.debug");
            // Allow simply setting the prop to turn on debug
            return (val != null && (!"false".equals(val)));
        }
        catch (SecurityException se) {}
        return false;
    } // isDebugEnabled()

    /** Prints a message to standard error if debugging is enabled. */
    private static void debugPrintln(String msg) {
        if (DEBUG) {
            System.err.println("XERCES: " + msg);
        }
    } // debugPrintln(String)

    /**
     * Figure out which ClassLoader to use.  For JDK 1.2 and later use
     * the context ClassLoader.
     */
    public static ClassLoader findClassLoader()
        throws ConfigurationError
    {
        if (System.getSecurityManager()!=null) {
            //this will ensure bootclassloader is used
            return null;
        }
        // Figure out which ClassLoader to use for loading the provider
        // class.  If there is a Context ClassLoader then use it.
        ClassLoader context = SecuritySupport.getContextClassLoader();
        ClassLoader system = SecuritySupport.getSystemClassLoader();

        ClassLoader chain = system;
        while (true) {
            if (context == chain) {
                // Assert: we are on JDK 1.1 or we have no Context ClassLoader
                // or any Context ClassLoader in chain of system classloader
                // (including extension ClassLoader) so extend to widest
                // ClassLoader (always look in system ClassLoader if Xerces
                // is in boot/extension/system classpath and in current
                // ClassLoader otherwise); normal classloaders delegate
                // back to system ClassLoader first so this widening doesn't
                // change the fact that context ClassLoader will be consulted
                ClassLoader current = ObjectFactory.class.getClassLoader();

                chain = system;
                while (true) {
                    if (current == chain) {
                        // Assert: Current ClassLoader in chain of
                        // boot/extension/system ClassLoaders
                        return system;
                    }
                    if (chain == null) {
                        break;
                    }
                    chain = SecuritySupport.getParentClassLoader(chain);
                }

                // Assert: Current ClassLoader not in chain of
                // boot/extension/system ClassLoaders
                return current;
            }

            if (chain == null) {
                // boot ClassLoader reached
                break;
            }

            // Check for any extension ClassLoaders in chain up to
            // boot ClassLoader
            chain = SecuritySupport.getParentClassLoader(chain);
        };

        // Assert: Context ClassLoader not in chain of
        // boot/extension/system ClassLoaders
        return context;
    } // findClassLoader():ClassLoader

    /**
     * Create an instance of a class using the same classloader for the ObjectFactory by default
     * or bootclassloader when Security Manager is in place
     */
    public static Object newInstance(String className, boolean doFallback)
        throws ConfigurationError
    {
        if (System.getSecurityManager()!=null) {
            return newInstance(className, null, doFallback);
        } else {
            return newInstance(className,
                findClassLoader (), doFallback);
        }
    }

    /**
     * Create an instance of a class using the specified ClassLoader
     */
    public static Object newInstance(String className, ClassLoader cl,
                                      boolean doFallback)
        throws ConfigurationError
    {
        // assert(className != null);
        try{
            Class providerClass = findProviderClass(className, cl, doFallback);
            Object instance = providerClass.newInstance();
            if (DEBUG) debugPrintln("created new instance of " + providerClass +
                   " using ClassLoader: " + cl);
            return instance;
        } catch (ClassNotFoundException x) {
            throw new ConfigurationError(
                "Provider " + className + " not found", x);
        } catch (Exception x) {
            throw new ConfigurationError(
                "Provider " + className + " could not be instantiated: " + x,
                x);
        }
    }

    /**
     * Find a Class using the same classloader for the ObjectFactory by default
     * or bootclassloader when Security Manager is in place
     */
    public static Class findProviderClass(String className, boolean doFallback)
        throws ClassNotFoundException, ConfigurationError
    {
        if (System.getSecurityManager()!=null) {
            return Class.forName(className);
        } else {
            return findProviderClass (className,
                findClassLoader (), doFallback);
        }
    }
    /**
     * Find a Class using the specified ClassLoader
     */
    public static Class findProviderClass(String className, ClassLoader cl,
                                      boolean doFallback)
        throws ClassNotFoundException, ConfigurationError
    {
        //throw security exception if the calling thread is not allowed to access the package
        //restrict the access to package as speicified in java.security policy
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            final int lastDot = className.lastIndexOf(".");
            String packageName = className;
            if (lastDot != -1) packageName = className.substring(0, lastDot);
            security.checkPackageAccess(packageName);
        }
        Class providerClass;
        if (cl == null) {
            //use the bootstrap ClassLoader.
            providerClass = Class.forName(className);
        } else {
            try {
                providerClass = cl.loadClass(className);
            } catch (ClassNotFoundException x) {
                if (doFallback) {
                    // Fall back to current classloader
                    ClassLoader current = ObjectFactory.class.getClassLoader();
                    if (current == null) {
                        providerClass = Class.forName(className);
                    } else if (cl != current) {
                        cl = current;
                        providerClass = cl.loadClass(className);
                    } else {
                        throw x;
                    }
                } else {
                    throw x;
                }
            }
        }

        return providerClass;
    }

    /*
     * Try to find provider using Jar Service Provider Mechanism
     *
     * @return instance of provider class if found or null
     */
    private static Object findJarServiceProvider(String factoryId)
        throws ConfigurationError
    {
        String serviceId = "META-INF/services/" + factoryId;
        InputStream is = null;

        // First try the Context ClassLoader
        ClassLoader cl = findClassLoader();

        is = SecuritySupport.getResourceAsStream(cl, serviceId);

        // If no provider found then try the current ClassLoader
        if (is == null) {
            ClassLoader current = ObjectFactory.class.getClassLoader();
            if (cl != current) {
                cl = current;
                is = SecuritySupport.getResourceAsStream(cl, serviceId);
            }
        }

        if (is == null) {
            // No provider found
            return null;
        }

        if (DEBUG) debugPrintln("found jar resource=" + serviceId +
               " using ClassLoader: " + cl);

        // Read the service provider name in UTF-8 as specified in
        // the jar spec.  Unfortunately this fails in Microsoft
        // VJ++, which does not implement the UTF-8
        // encoding. Theoretically, we should simply let it fail in
        // that case, since the JVM is obviously broken if it
        // doesn't support such a basic standard.  But since there
        // are still some users attempting to use VJ++ for
        // development, we have dropped in a fallback which makes a
        // second attempt using the platform's default encoding. In
        // VJ++ this is apparently ASCII, which is a subset of
        // UTF-8... and since the strings we'll be reading here are
        // also primarily limited to the 7-bit ASCII range (at
        // least, in English versions), this should work well
        // enough to keep us on the air until we're ready to
        // officially decommit from VJ++. [Edited comment from
        // jkesselm]
        BufferedReader rd;
        try {
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"), DEFAULT_LINE_LENGTH);
        } catch (java.io.UnsupportedEncodingException e) {
            rd = new BufferedReader(new InputStreamReader(is), DEFAULT_LINE_LENGTH);
        }

        String factoryClassName = null;
        try {
            // XXX Does not handle all possible input as specified by the
            // Jar Service Provider specification
            factoryClassName = rd.readLine();
        } catch (IOException x) {
            // No provider found
            return null;
        }
        finally {
            try {
                // try to close the reader.
                rd.close();
            }
            // Ignore the exception.
            catch (IOException exc) {}
        }

        if (factoryClassName != null &&
            ! "".equals(factoryClassName)) {
            if (DEBUG) debugPrintln("found in resource, value="
                   + factoryClassName);

            // Note: here we do not want to fall back to the current
            // ClassLoader because we want to avoid the case where the
            // resource file was found using one ClassLoader and the
            // provider class was instantiated using a different one.
            return newInstance(factoryClassName, cl, false);
        }

        // No provider found
        return null;
    }

} // class ObjectFactory


text:
function html5_embed_renderer(tokens, idx, options, env, self, defaultRender) {
  var audioRE = /^.*\.(ogg|mp3)$/gi;
  var videoRE = /^.*\.(mp4|webm)$/gi;
  var token = tokens[idx];
  var aIndex = token.attrIndex('src');
//  console.log('aindex of idx' + idx);
//  console.log(aIndex);
  var matches_audio = audioRE.exec(token.attrs[aIndex][1]);
  var matches_video = videoRE.exec(token.attrs[aIndex][1]);
//  console.log(token.attrs[aIndex][1]);
  if (matches_audio !== null) {
//    console.log('matches audio')
    return ['
<audio width="320" controls class="audioplayer"',
      '<source type="audio/' + matches_audio[1] + '" src=' + matches_audio[0] + '></source>',
      '</audio>
'
    ].join('\n');
  } else if (matches_video !== null) {
//    console.log('matches video')
    return ['
<video width="320" height="240" class="audioplayer" controls>',
  '<source type="video/' + matches_video[1] + '" src=' + matches_video[0] + '></source>',
  '</video>
'
].join('\n');
  }else {
//    console.log('matches img')
    return defaultRender(tokens, idx, options, env, self);
  }
}

module.exports = function html5_embed_plugin(md, options) {
  var defaultRender = md.renderer.rules.image;
  md.renderer.rules.image = function(tokens, idx, opt, env, self) {
    return html5_embed_renderer(tokens, idx, opt, env, self, defaultRender);
  };
};


text:
#pragma once

#include <wtf/DoublyLinkedList.h>

namespace JSC {

class HandleSet;
class HandleNode;

class HandleBlock : public DoublyLinkedListNode<HandleBlock> {
    friend class WTF::DoublyLinkedListNode<HandleBlock>;
public:
    static HandleBlock* create(HandleSet*);
    static void destroy(HandleBlock*);
    static HandleBlock* blockFor(HandleNode*);

    static const size_t blockSize = 4 * KB;

    HandleSet* handleSet();

    HandleNode* nodes();
    HandleNode* nodeAtIndex(unsigned);
    unsigned nodeCapacity();

private:
    HandleBlock(HandleSet*);

    char* payload();
    char* payloadEnd();

    static const size_t s_blockMask = ~(blockSize - 1);

    HandleBlock* m_prev;
    HandleBlock* m_next;
    HandleSet* m_handleSet;
};

inline HandleBlock* HandleBlock::blockFor(HandleNode* node)
{
    return reinterpret_cast<HandleBlock*>(reinterpret_cast<size_t>(node) & s_blockMask);
}

inline HandleSet* HandleBlock::handleSet()
{
    return m_handleSet;
}

} // namespace JSC


text:
package com.elegion.rssreader;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;

/**
 * @author artyom on 10/09/14.
 */
@Root(name = "item")
public class NewsItem {
    @Element(name = "title")
    String mTitle;
    @Element(name = "description")
    String mDescription;
    @Element(name = "link")
    String mLink;

    @Override
    public String toString() {
        return mTitle;
    }
}


text:
<?php

namespace Magento\Install\Test\Block;

use Magento\Mtf\Block\Form;
use Magento\Mtf\Client\Locator;
use Magento\Mtf\Fixture\FixtureInterface;
use Magento\Mtf\Client\Element\SimpleElement;

/**
 * Database form.
 */
class Database extends Form
{
    /**
     * 'Test connection successful.' message.
     *
     * @var string
     */
    protected $successConnectionMessage = ".text-success";

    /**
     * 'Next' button.
     *
     * @var string
     */
    protected $next = "[ng-click*='testConnection']";

    /**
     * Fill database form.
     *
     * @param FixtureInterface $fixture
     * @param SimpleElement|null $element
     * @return $this
     */
    public function fill(FixtureInterface $fixture, SimpleElement $element = null)
    {
        $data = $fixture->getData();
        $dbData = [];
        foreach ($data as $key => $value) {
            if (strpos($key, 'db') === 0) {
                $dbData[$key] = $value;
            }
        }
        $mapping = $this->dataMapping($dbData);
        $this->_fill($mapping, $element);

        return $this;
    }

    /**
     * Get 'Test connection successful.' message.
     *
     * @return string
     */
    public function getSuccessConnectionMessage()
    {
        return $this->_rootElement->find($this->successConnectionMessage, Locator::SELECTOR_CSS)->getText();
    }

    /**
     * Click on 'Next' button.
     *
     * @return void
     */
    public function clickNext()
    {
        $this->_rootElement->find($this->next, Locator::SELECTOR_CSS)->click();
    }
}


text:
import './global-jasmine';
import 'jasmine-core/lib/jasmine-core/jasmine-html.js';
import 'jasmine-core/lib/jasmine-core/boot.js';

import './polyfills';

// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';

// Requires 'zone.js/dist/proxy.js' and 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';

import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting,
} from '@angular/platform-browser-dynamic/testing';

import './app/state/books.reducer.spec.ts';
import './app/state/collection.reducer.spec.ts';
import './app/state/books.selectors.spec.ts';
import './app/app.component.spec.ts';
import './app/integration.spec.ts';

jasmine.getEnv().configure({ random: false });
bootstrap();

function bootstrap() {
  if (window.jasmineRef) {
    location.reload();
    return;
  } else {
    window.onload();
    window.jasmineRef = jasmine.getEnv();
  }

  getTestBed().initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
  );
}


text:
package com.ibm.jbatch.tck.tests.jslxml;

import static com.ibm.jbatch.tck.utils.AssertionUtils.assertObjEquals;
import static com.ibm.jbatch.tck.utils.AssertionUtils.assertWithMessage;

import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Logger;

import javax.batch.runtime.BatchStatus;
import javax.batch.runtime.JobExecution;
import javax.batch.runtime.Metric;
import javax.batch.runtime.StepExecution;

import com.ibm.jbatch.tck.artifacts.reusable.MyBatchletImpl;
import com.ibm.jbatch.tck.artifacts.reusable.MyPersistentUserData;
import com.ibm.jbatch.tck.utils.JobOperatorBridge;

import org.junit.BeforeClass;
import org.testng.Reporter;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class StepExecutionTests {

	private final static Logger logger = Logger.getLogger(StepExecutionTests.class.getName());

	private static JobOperatorBridge jobOp;

	public static void setup(String[] args, Properties props) throws Exception {
		String METHOD = "setup";

		try {
			jobOp = new JobOperatorBridge();
		} catch (Exception e) {
			handleException(METHOD, e);
		}
	}

	@BeforeMethod
	@BeforeClass
	public static void setUp()throws Exception {
		jobOp = new JobOperatorBridge();
	}

	@AfterClass
	public static void cleanup() throws Exception {
	}

	private void begin(String str) {
		Reporter.log("Begin test method: " + str + "<p>");
	}

	/*
	 * @testName: testOneStepExecutionStatus
	 * @assertion: FIXME
	 * @test_Strategy: FIXME
	 */
	@Test
	@org.junit.Test
	public void testOneStepExecutionStatus() throws Exception {

		String METHOD = "testOneStepExecutionStatus";
		begin(METHOD);

		try {
			Reporter.log("Locate job XML file: job_batchlet_1step.xml<p>");

			Reporter.log("Invoke startJobAndWaitForResult for execution #1<p>");
			JobExecution jobExec = jobOp.startJobAndWaitForResult("job_batchlet_1step");

			Reporter.log("Obtaining StepExecutions for execution id: " + jobExec.getExecutionId() + "<p>");
			List<StepExecution> steps = jobOp.getStepExecutions(jobExec.getExecutionId());

			assertObjEquals(1, steps.size());

			for (StepExecution step : steps) {
				// make sure all steps finish successfully
				showStepState(step);
				Reporter.log("Step status = " + step.getBatchStatus() + "<p>");
				assertObjEquals(BatchStatus.COMPLETED, step.getBatchStatus());
			}

			Reporter.log("Job execution status = " + jobExec.getBatchStatus() + "<p>");
			assertObjEquals(BatchStatus.COMPLETED, jobExec.getBatchStatus());
		} catch (Exception e) {
			handleException(METHOD, e);
		}

	}

	/*
	 * @testName: testFourStepExecutionStatus
	 * @assertion: FIXME
	 * @test_Strategy: FIXME
	 */
	@Test
	@org.junit.Test
	public void testFourStepExecutionStatus() throws Exception {

		String METHOD = "testFourStepExecutionStatus";
		begin(METHOD);

		try {
			Reporter.log("Locate job XML file: job_batchlet_4steps.xml<p>");

			Reporter.log("Invoke startJobAndWaitForResult for execution #1<p>");
			JobExecution jobExec = jobOp.startJobAndWaitForResult("job_batchlet_4steps");

			Reporter.log("Obtaining StepExecutions for execution id: " + jobExec.getExecutionId() + "<p>");
			List<StepExecution> steps = jobOp.getStepExecutions(jobExec.getExecutionId());
			assertObjEquals(4, steps.size());

			Set<Long> stepExecutionsSeen = new HashSet<Long>();
			for (StepExecution step : steps) {
				// check that each step completed successfully
				showStepState(step);
				Reporter.log("Step status = " + step.getBatchStatus() + "<p>");
				assertObjEquals(BatchStatus.COMPLETED, step.getBatchStatus());

				// Let's also make sure all four have unique IDs, to make sure the JobExecution id isn't being used say
				assertWithMessage("New StepExecution id", !stepExecutionsSeen.contains(step.getStepExecutionId()));
				stepExecutionsSeen.add(step.getStepExecutionId());
			}
			Reporter.log("Job execution status = " + jobExec.getBatchStatus() + "<p>");
			assertObjEquals(BatchStatus.COMPLETED, jobExec.getBatchStatus());
		} catch (Exception e) {
			handleException(METHOD, e);
		}
	}

	/*
	 * @testName: testFailedStepExecutionStatus
	 * @assertion: FIXME
	 * @test_Strategy: FIXME
	 */
	@Test
	@org.junit.Test
	public void testFailedStepExecutionStatus() throws Exception {
		String METHOD = "testFailedStepExecutionStatus";
		begin(METHOD);

		try {
			Reporter.log("Locate job XML file: job_batchlet_failElement.xml<p>");

			Reporter.log("Invoke startJobAndWaitForResult for execution #1<p>");
			JobExecution jobExec = jobOp.startJobAndWaitForResult("job_batchlet_failElement");

			Reporter.log("Obtaining StepExecutions for execution id: " + jobExec.getExecutionId() + "<p>");
			List<StepExecution> steps = jobOp.getStepExecutions(jobExec.getExecutionId());
			assertObjEquals(1, steps.size());
			for (StepExecution step : steps) {
				// check that each step completed successfully
				// TODO: shouldn't the step status be failed here ???
				showStepState(step);
			}

			Reporter.log("Job execution getExitStatus()="+jobExec.getExitStatus()+"<p>");
			Reporter.log("Job execution getBatchStatus()="+jobExec.getBatchStatus()+"<p>");
			assertObjEquals("TEST_FAIL", jobExec.getExitStatus());
			assertObjEquals(BatchStatus.FAILED, jobExec.getBatchStatus());
		} catch (Exception e) {
			handleException(METHOD, e);
		}
	}

	/*
	 * @testName: testStoppedStepExecutionStatus
	 * @assertion: FIXME
	 * @test_Strategy: FIXME
	 */
	@Test
	@org.junit.Test
	public void testStoppedStepExecutionStatus() throws Exception {
		String METHOD = "testStoppedStepExecutionStatus";
		begin(METHOD);

		try {
			Reporter.log("Locate job XML file: job_batchlet_stopElement.xml<p>");

			Reporter.log("Invoke startJobAndWaitForResult for execution #1<p>");
			JobExecution jobExec = jobOp.startJobAndWaitForResult("job_batchlet_stopElement");

			Reporter.log("Obtaining StepExecutions for execution id: " + jobExec.getExecutionId() + "<p>");
			List<StepExecution> steps = jobOp.getStepExecutions(jobExec.getExecutionId());
			assertObjEquals(1, steps.size());
			for (StepExecution step : steps) {
				// check that each step completed successfully
				// TODO: shouldn't the step status be stopped here ???
				showStepState(step);
			}

			Reporter.log("Job execution getBatchStatus()="+jobExec.getBatchStatus()+"<p>");
			assertObjEquals(BatchStatus.STOPPED, jobExec.getBatchStatus());
		} catch (Exception e) {
			handleException(METHOD, e);
		}
	}

	/*
	 * @testName: testPersistedStepData
	 * @assertion: FIXME
	 * @test_Strategy: FIXME
	 */
	@Test
	@org.junit.Test
	public void testPersistedStepData() throws Exception {
		String METHOD = "testPersistedStepData";
		begin(METHOD);

		try {
			Reporter.log("Locate job XML file: job_batchlet_persistedData.xml<p>");

			Reporter.log("Create job parameters for execution #1:<p>");
			Properties jobParameters = new Properties();
			Reporter.log("force.failure=true<p>");
			jobParameters.setProperty("force.failure" , "true");

			Reporter.log("Invoke startJobAndWaitForResult for execution #1<p>");
			JobExecution jobExec = jobOp.startJobAndWaitForResult("job_batchlet_persistedData", jobParameters);

			Reporter.log("execution #1 JobExecution getBatchStatus()="+jobExec.getBatchStatus()+"<p>");
			assertObjEquals(BatchStatus.FAILED, jobExec.getBatchStatus());

			//This job should only have one step.
			Reporter.log("Obtaining StepExecutions for execution id: " + jobExec.getExecutionId() + "<p>");
			List<StepExecution> steps = jobOp.getStepExecutions(jobExec.getExecutionId());
			StepExecution stepExec = steps.get(0);
			assertObjEquals(1, steps.size());

			Reporter.log("execution #1 StepExecution getBatchStatus()="+jobExec.getBatchStatus()+"<p>");
			assertObjEquals(BatchStatus.FAILED, stepExec.getBatchStatus());
			assertObjEquals(4, ((MyPersistentUserData)stepExec.getPersistentUserData()).getData());

			//jobParameters.setProperty("force.failure" , "false");
			Reporter.log("Invoke restartJobAndWaitForResult with execution id: " + jobExec.getExecutionId() + "<p>");
			JobExecution restartedJobExec = jobOp.restartJobAndWaitForResult(jobExec.getExecutionId(),jobParameters);

			//This job should only have one step.

			steps = jobOp.getStepExecutions(restartedJobExec.getExecutionId());
			stepExec = steps.get(0);

			Reporter.log("execution #1 StepExecution getBatchStatus()="+jobExec.getBatchStatus()+"<p>");
			assertObjEquals(BatchStatus.COMPLETED, stepExec.getBatchStatus());
			assertObjEquals(5, ((MyPersistentUserData)stepExec.getPersistentUserData()).getData());

		} catch (Exception e) {
			handleException(METHOD, e);
		}

	}

	/*
	 * @testName: testStepExecutionExitStatus
	 * @assertion: FIXME
	 * @test_Strategy: FIXME
	 */
	@Test
	@org.junit.Test
	public void testStepExecutionExitStatus() throws Exception {
		String METHOD = "testStepExecutionExitStatus";
		begin(METHOD);

		try {
			Reporter.log("Locate job XML file: job_batchlet_failElement.xml<p>");

			Reporter.log("Invoke startJobAndWaitForResult for execution #1<p>");
			JobExecution jobExec = jobOp.startJobAndWaitForResult("job_batchlet_failElement");

			Reporter.log("Obtaining StepExecutions for execution id: " + jobExec.getExecutionId() + "<p>");
			List<StepExecution> steps = jobOp.getStepExecutions(jobExec.getExecutionId());
			assertObjEquals(1, steps.size());

			StepExecution step = steps.get(0);
			showStepState(step);
			assertWithMessage("Check step exit status", MyBatchletImpl.GOOD_EXIT_STATUS, step.getExitStatus());
			assertWithMessage("Check step batch status", BatchStatus.COMPLETED, step.getBatchStatus());
			Reporter.log("Job batch status =" + jobExec.getBatchStatus() + "<p>");
			Reporter.log("Job exit status =" + jobExec.getExitStatus() + "<p>");
			assertWithMessage("Check job batch status", BatchStatus.FAILED, jobExec.getBatchStatus());
			assertWithMessage("Check job exit status", "TEST_FAIL", jobExec.getExitStatus());
		} catch (Exception e) {
			handleException(METHOD, e);
		}
	}

	/*
	 * @testName: testStepInFlowStepExecution
	 * @assertion: FIXME
	 * @test_Strategy: FIXME
	 */
	@Test
	@org.junit.Test
	public void testStepInFlowStepExecution() throws Exception {
		String METHOD = "testStepInFlowStepExecution";
		begin(METHOD);

		try {
			Reporter.log("Locate job XML file: job_batchlet_failElement.xml<p>");
			Reporter.log("Invoke startJobAndWaitForResult for execution #1<p>");
			JobExecution jobExec = jobOp.startJobAndWaitForResult("flow_transition_to_step");

			Reporter.log("Obtaining StepExecutions for execution id: " + jobExec.getExecutionId() + "<p>");
			List<StepExecution> steps = jobOp.getStepExecutions(jobExec.getExecutionId());
			assertObjEquals(4, steps.size());
			for (StepExecution step : steps) {
				showStepState(step);
				// Conveniently all four steps have same exit and batch status.
				assertWithMessage("Check step exit status", MyBatchletImpl.GOOD_EXIT_STATUS, step.getExitStatus());
				assertWithMessage("Check step batch status", BatchStatus.COMPLETED, step.getBatchStatus());
			}

			// Now check job level status
			Reporter.log("Job batch status =" + jobExec.getBatchStatus() + "<p>");
			Reporter.log("Job exit status =" + jobExec.getExitStatus() + "<p>");
			assertWithMessage("Check job batch status", BatchStatus.COMPLETED, jobExec.getBatchStatus());
			assertWithMessage("Check job exit status", "flow1step1, flow1step2, flow1step3, step1", jobExec.getExitStatus());

		} catch (Exception e) {
			handleException(METHOD, e);
		}
	}

	/*
	 * @testName: testStepInFlowInSplitStepExecution
	 * @assertion: FIXME
	 * @test_Strategy: FIXME
	 */
	@Test
	@org.junit.Test
	public void testStepInFlowInSplitStepExecution() throws Exception {
		String METHOD = "testStepInFlowInSplitStepExecution";
		begin(METHOD);

		try {
			Reporter.log("Locate job XML file: split_batchlet_4steps.xml<p>");
			Reporter.log("Invoke startJobAndWaitForResult for execution #1<p>");
			JobExecution jobExec = jobOp.startJobAndWaitForResult("split_batchlet_4steps");

			// Saves debugging time to check these two first in case they fail
			assertWithMessage("Check job batch status", BatchStatus.COMPLETED, jobExec.getBatchStatus());
			assertWithMessage("Check job exit status", "COMPLETED", jobExec.getExitStatus());

			Reporter.log("Obtaining StepExecutions for execution id: " + jobExec.getExecutionId() + "<p>");
			List<StepExecution> steps = jobOp.getStepExecutions(jobExec.getExecutionId());
			assertObjEquals(4, steps.size());
			for (StepExecution step : steps) {
				showStepState(step);
				// Conveniently all four steps have same exit and batch status.
				assertWithMessage("Check step exit status", MyBatchletImpl.GOOD_EXIT_STATUS, step.getExitStatus());
				assertWithMessage("Check step batch status", BatchStatus.COMPLETED, step.getBatchStatus());
			}
			Reporter.log("Job batch status =" + jobExec.getBatchStatus() + "<p>");
			Reporter.log("Job exit status =" + jobExec.getExitStatus() + "<p>");

		} catch (Exception e) {
			handleException(METHOD, e);
		}
	}

	private void showStepState(StepExecution step) {
		Reporter.log("---------------------------<p>");
		Reporter.log("getStepName(): " + step.getStepName() + " - ");
		Reporter.log("getStepExecutionId(): " + step.getStepExecutionId() + " - ");
		Metric[] metrics = step.getMetrics();

		for (int i = 0; i < metrics.length; i++) {
			Reporter.log(metrics[i].getType() + ": " + metrics[i].getValue() + " - ");
		}

		Reporter.log("getStartTime(): " + step.getStartTime() + " - ");
		Reporter.log("getEndTime(): " + step.getEndTime() + " - ");
		Reporter.log("getBatchStatus(): " + step.getBatchStatus() + " - ");
		Reporter.log("getExitStatus(): " + step.getExitStatus()+"<p>");
		Reporter.log("---------------------------<p>");
	}

	private static void handleException(String methodName, Exception e) throws Exception {
		Reporter.log("Caught exception: " + e.getMessage()+"<p>");
		Reporter.log(methodName + " failed<p>");
		throw e;
	}

}