text:
---
layout: post
title:  "Yeniden dene kalıbı (retry pattern)"
date:   2015-09-12
description: Hata yakalamak üzere bir düzenek kurmanın, diğer bir deyişle bir **try** bloğu açmanın pratikte tek amacı vardır; hatanın üstesinden gelmek. Bu her zaman mümkün olmayabilir. Desen, hatanın tekrar edilince çözülebileceği durumlarda kullanılmak üzere bir düzenek önerir.
meta_description: Hata yakalamak üzere bir düzenek kurmanın, diğer bir deyişle bir **try** bloğu açmanın pratikte tek amacı vardır; hatanın üstesinden gelmek. Bu her zaman mümkün olmayabilir. Desen, hatanın tekrar edilince çözülebileceği durumlarda kullanılmak üzere bir düzenek önerir.
categories:
- Design Pattern
- Cloud
permalink: yeniden-dene-kalibi-retry-pattern
---

Hata yakalamak üzere bir düzenek kurmanın, diğer bir deyişle bir **try** bloğu açmanın pratikte amacı; hatanın üstesinden gelmektir.
C# dilinde *catch* bloğunda hata yakalanır ama genelde yakalanan hata üstesinden gelinebilecek bir hata olmadığından, sorun seyir defterine yazılır, amaca uygun bir şekilde ya yakalanan exception ya da başka bir exception'a dönüştürelerek fırlatılır.

Örneğin kod şöyledir;

```
            try
            {
                _service.DoSomething();
            }
            catch (Exception ex)
            {
                //Sorunu çöz.
            }
```

Sorunu çöz? Nasıl? Çözüm çok kolay olmayacağı için en çok görülen kod şöyledir.

```
        private static void MakeSomething ()
        {
            try
            {
                _service.DoSomething();
            }
            catch (Exception ex)
            {
                _logger.Error("MakeSomething failed.", ex);
                throw new ApplicationException(ex);
            }
        }
```

Harika! MakeSomething çalışmıyor log'landı. Peki bundan sonrası? MakeSomething çağıran da çalışmadı öncesi de...

Aslında bir yazılım pratiği olarak: bir exception'ı yakaladığınızda ne yapılacağı yani exception'ın nasıl kontrol edileceği bilinmiyorsa yakalamamak en iyisidir. Zaten yakaladığınız hatayı loglamaktan başka bir şey yapmıyorsanız buna hiç gerek yok. Hatanın istemci tarafından trace alınarak loglanması çok daha efektiftir. .NET Framework size trace'i kusursuz bir şekilde sunar.

Örneğin bir veri kaynağına erişmek isteniyor ama veri kaynağı beklenilen zamanda yanıt vermiyor. Bu durumda ağ kablolarını tamir edemeyeceğinize, ya da kapanan sunucuyu çalıştıramayacağınıza göre istenen işlemin sonlandırılmasından başka şansımız yok. Bu yüzden hatalar düzeltilemez. Tabii düzeltilemeyecek hatalara yüzlerce örnek bulmak mümkün; Ne yaparsanız yapın bir sayıyı sıfır'a (0) bölemezsiniz. Tarihe benzemeyen bir değeri tarih varsayıp DateTime türüne dönüştüremezsiniz...

Bir de geçici hatalar (**transient fault**) vardır. Örneğin, bağlantı noktası çağırdığınız anda kısa bir süre için yanıt veremeyecek kadar yoğundur, ya da bağlantı hızınız yine kısa bir süre için yavaşlamıştır. bu tür hataları aldığınızda istenen işlemi yeniden denemek, denemeler sırasında geçici sorunun giderilmesi durumunda uygulamanıza çabuk iyileşebilen (resilent) bir yetenek kazandırır.

[RepZone](https://www.repzone.com) gibi bulut uygulamaları erişilmesi gereken bir çok uzak kaynağı kullanır. Bu kaynaklar her zaman çok çabuk ve yerinde yanıt veremeyebilir. Uygulamanın her hatada işlemden hemen vazgeçmesi, uygulamayı çalışmaz hale getirecektir. Kendini  geçici hatalara karşı koruyan bir uygulamaya sahip olmak için **yeniden dene kalıbı** (retry pattern) geçici hataların belirli kurallarla yeniden denenmesini önerir.

Tam bu aşamada; genelde bir yöntem çağırdığımızda işlemin kusursuz tamamlanmasını beklediğimizi hatırlatayım. Herhangi bir başarısız işlem sonucunda, örneğin bir TimeOutException yakalandığında birkaç kez belirli aralıklarla denemek aslında hatayı çözmek için ne yapacağımızı bildiğimiz anlamına gelmiyor ama tekrar edersek yapılabilecek bir işlemin yapılmasını sağlayacak şık bir çözüm sağlıyor. Yeniden dene kalıbı da tam olarak bunu öneriyor; *Geçici olduğunu varsaydığın hatalarda işlemi belirli kurallarla tekrar dene.*

Şekli inceleyiniz. İlk iki deneme başarısız son deneme başarılı.

![retry pattern](/content/images/2015/07/retry.jpg)

Bu önerinin çok işe yarayan bir yararı da o hatalı işleme kadar yapılan işlemlerin de yok sayılmamasını sağlıyor. Sıradan bir hata ayıklama düzeneğinde hatanın yakalanmasıyla birlikte geriye doğru bütün işlemler hatalı olacaktır.

Kalıbın uygulanışı şöyle;

```
    public class RetryPattern
    {
        private readonly Action _action;
        private readonly ICollection<Type>
    _transientExceptions;
    private readonly int _maxRepeat;

    public RetryPattern (Action action,
    ICollection<Type>
        transientExceptions,
        int maxRepeat)
        {
        _action = action;
        _transientExceptions = transientExceptions;
        _maxRepeat = maxRepeat;
        }

        private async Task Operation (Action act)
        {
        await Task.Run(act);
        }

        private bool IsTransient (Exception ex)
        {
        return _transientExceptions.Any(t => t == ex.GetType());
        }
        }
        ```
        **RetryPattern** sınıfı kurucu üyeye bir servisin çağırılacağı **Action** bir de geçici hata listesi alıyor. IsTransient yöntemi parametre olarak verilen bir hatanın geçici bir hata olup olmadığını sınıyor.
        Şimdi asıl yönteme gelelim.  Bir döngü ile tekrar sayılacak buna gore geçici hata alındığı sürece verilen tekrar sayısına göre işlemi tekrar deneyecek.

        ```
        public async void Run()
        {
        int currentRetry = 0;
        while (true)
        {
        try
        {
        await Operation(_action);
        break;
        }
        catch (Exception ex)
        {
        currentRetry++;
        if (currentRetry > _maxRepeat || !IsTransient(ex))
        {
        throw;
        }
        }
        }
        }
        ```
        İşlem en fazla tekrar sayısı kadar geçici hata almaya izin veriyor sonrasında işlem ya yapılıyor ya da hata fırlatılıyor.

        Bu kod bloğu uygulamalarda pekala kullanılabilir ama DSL tutkusu şöyle bana bir kod hayal ettiriyor.

        ```
        _retry.When<TimeOutException>
            ()
            .When<ServiceHeavyLoadException>
                ()
                .Suspend(TimeSpan.FromMiliseconds(300))
                .Repeat(3)
                .With( _service.Method())
                .Throw ( ex => new ApplicationException( "x service error", ex) };
                ```
                Bu kaynak kodu elde edebileceğimiz bir açık kaynak kodlu projeye CodePlex'te başladım; [NeverGiveUp](https://nevergiveup.codeplex.com/) Katkı yapmak isteyenleri beklerim.


text:
ACCEPTED

#### According to
Integrated Taxonomic Information System

#### Published in
Novon 9:460. 1999

#### Original name
null

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
import numpy as np
from .stationary import Stationary
from .psi_comp import PSICOMP_RBF, PSICOMP_RBF_GPU
from ...core import Param
from paramz.transformations import Logexp

class RBF(Stationary):
    """
    Radial Basis Function kernel, aka squared-exponential, exponentiated quadratic or Gaussian kernel:

    .. math::

       k(r) = \sigma^2 \exp \\bigg(- \\frac{1}{2} r^2 \\bigg)

    """
    _support_GPU = True
    def __init__(self, input_dim, variance=1., lengthscale=None, ARD=False, active_dims=None, name='rbf', useGPU=False, inv_l=False):
        super(RBF, self).__init__(input_dim, variance, lengthscale, ARD, active_dims, name, useGPU=useGPU)
        if self.useGPU:
            self.psicomp = PSICOMP_RBF_GPU()
        else:
            self.psicomp = PSICOMP_RBF()
        self.use_invLengthscale = inv_l
        if inv_l:
            self.unlink_parameter(self.lengthscale)
            self.inv_l = Param('inv_lengthscale',1./self.lengthscale**2, Logexp())
            self.link_parameter(self.inv_l)

    def K_of_r(self, r):
        return self.variance * np.exp(-0.5 * r**2)

    def dK_dr(self, r):
        return -r*self.K_of_r(r)

    def dK2_drdr(self, r):
        return (r**2-1)*self.K_of_r(r)

    def dK2_drdr_diag(self):
        return -self.variance # as the diagonal of r is always filled with zeros
    def __getstate__(self):
        dc = super(RBF, self).__getstate__()
        if self.useGPU:
            dc['psicomp'] = PSICOMP_RBF()
            dc['useGPU'] = False
        return dc

    def __setstate__(self, state):
        self.use_invLengthscale = False
        return super(RBF, self).__setstate__(state)

    def spectrum(self, omega):
        assert self.input_dim == 1 #TODO: higher dim spectra?
        return self.variance*np.sqrt(2*np.pi)*self.lengthscale*np.exp(-self.lengthscale*2*omega**2/2)

    def parameters_changed(self):
        if self.use_invLengthscale: self.lengthscale[:] = 1./np.sqrt(self.inv_l+1e-200)
        super(RBF,self).parameters_changed()

    #---------------------------------------#
    #             PSI statistics            #
    #---------------------------------------#

    def psi0(self, Z, variational_posterior):
        return self.psicomp.psicomputations(self, Z, variational_posterior)[0]

    def psi1(self, Z, variational_posterior):
        return self.psicomp.psicomputations(self, Z, variational_posterior)[1]

    def psi2(self, Z, variational_posterior):
        return self.psicomp.psicomputations(self, Z, variational_posterior, return_psi2_n=False)[2]

    def psi2n(self, Z, variational_posterior):
        return self.psicomp.psicomputations(self, Z, variational_posterior, return_psi2_n=True)[2]

    def update_gradients_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):
        dL_dvar, dL_dlengscale = self.psicomp.psiDerivativecomputations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior)[:2]
        self.variance.gradient = dL_dvar
        self.lengthscale.gradient = dL_dlengscale
        if self.use_invLengthscale:
            self.inv_l.gradient = dL_dlengscale*(self.lengthscale**3/-2.)

    def gradients_Z_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):
        return self.psicomp.psiDerivativecomputations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior)[2]

    def gradients_qX_expectations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior):
        return self.psicomp.psiDerivativecomputations(self, dL_dpsi0, dL_dpsi1, dL_dpsi2, Z, variational_posterior)[3:]

    def update_gradients_diag(self, dL_dKdiag, X):
        super(RBF,self).update_gradients_diag(dL_dKdiag, X)
        if self.use_invLengthscale: self.inv_l.gradient =self.lengthscale.gradient*(self.lengthscale**3/-2.)

    def update_gradients_full(self, dL_dK, X, X2=None):
        super(RBF,self).update_gradients_full(dL_dK, X, X2)
        if self.use_invLengthscale: self.inv_l.gradient =self.lengthscale.gradient*(self.lengthscale**3/-2.)


text:
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

Google's direction API provides points along route segments as an encoded string. For example the encoded string:

    _p~iF~ps|U_ulLnnqC_mqNvxq`@

decodes to the coordinate points:

    (38.5, -120.2), (40.7, -120.95), (43.252, -126.453)

Full details of the algorithm used can be found [here](ttps://developers.google.com/maps/documentation/utilities/polylinealgorithm).

The Swift extensions provided here support encoding and decoding to and from the `String` and `MKPolyline` classes.

## Usage
Examples of usage
#### Decoding
Decoding throws `GooglePolylineError.InvalidPolylineString` if the string is not a valid Google polyline.

```
let googlePolyline = "`_p~iF~ps|U_ulLnnqC_mqNvxq`@"

// Get lazy sequence of CLLocationCoordinate2D
let seq = try googlePolyline.makeCoordinateSequenceFromGooglePolyline()

// Get array of CLLocationCoordinate2D
let array = try googlePolyline.makeCoordinateArrayFromGooglePolyline()

// Get MKPolyline
let polyline = try googlePolyline.makeMKPolylineFromGooglePolyline()
let anotherPolyline = try MKPolyline(encodedGooglePolyline:googlePolyline)
```
#### Encoding
```
let googlePolyline = "`_p~iF~ps|U_ulLnnqC_mqNvxq`@"
let polyline = MKPolyline(encodedGooglePolyline:googlePolyline)
let points = [
    CLLocationCoordinate2D(latitude: 38.5, longitude: -120.2),
    CLLocationCoordinate2D(latitude: 40.7, longitude: -120.95),
    CLLocationCoordinate2D(latitude: 43.252, longitude: -126.453)
]

// Encode from sequence of CLLocationCoordinate2D
let encodedFromPoints = String(googlePolylineLocationCoordinateSequence:points)

// Encode from sequence of MKMapPoint
let encodedFromMapPoints = String(googlePolylineMapPointSequence:
	points.map { MKMapPointForCoordinate($0) })

// Encode from MKPolyline
let encodedFromPolyline = String(googlePolylineMKPolyline:polyline)
let anotherEncodedFromPolyline = polyline.googlePolyline
```
## Credits
This library has been created by Mark Woollard and has been made available under the **MIT License**. Please see the `LICENSE` file for more information.


text:
import random, time, sys, socket, threading, queue, socketserver, os
from PIL import Image

# If Pi = False the script runs in simulation mode using pygame lib
PI = False
import pygame
from pygame.locals import *
if PI:
    import serial
    import max7219.led as led
    from max7219.font import proportional, SINCLAIR_FONT, TINY_FONT, CP437_FONT

# only modify this two values for size adaption!
PIXEL_X=10
PIXEL_Y=20

SIZE= 20
FPS = 15
BOXSIZE = 20
WINDOWWIDTH = BOXSIZE * PIXEL_X
WINDOWHEIGHT = BOXSIZE * PIXEL_Y
BOARDWIDTH = PIXEL_X
BOARDHEIGHT = PIXEL_Y
BLANK = '.'
MOVESIDEWAYSFREQ = 0.15
MOVEDOWNFREQ = 0.15
FALLING_SPEED = 0.8

#               R    G    B
WHITE       = (255, 255, 255)
GRAY        = (185, 185, 185)
BLACK       = (  0,   0,   0)
RED         = (255,   0,   0)
LIGHTRED    = (175,  20,  20)
GREEN       = (  0, 255,   0)
LIGHTGREEN  = ( 20, 175,  20)
BLUE        = (  0,   0, 255)
LIGHTBLUE   = ( 20,  20, 175)
YELLOW      = (255, 255,   0)
LIGHTYELLOW = (175, 175,  20)
CYAN        = (  0, 255, 255)
MAGENTA     = (255,   0, 255)
ORANGE      = (255, 100,   0)

SCORES =(0,40,100,300,1200)

BORDERCOLOR = BLUE
BGCOLOR = BLACK
TEXTCOLOR = WHITE
TEXTSHADOWCOLOR = GRAY
COLORS      = (BLUE,GREEN,RED,YELLOW,CYAN,MAGENTA,ORANGE)
LIGHTCOLORS = (LIGHTBLUE, LIGHTGREEN, LIGHTRED, LIGHTYELLOW)
#assert len(COLORS) == len(LIGHTCOLORS) # each color must have light color

BUTTON_BLUE=4
BUTTON_GREEN=5
BUTTON_RED=6
BUTTON_YELLOW=7

TEMPLATEWIDTH = 5
TEMPLATEHEIGHT = 5

S_SHAPE_TEMPLATE = [['.....',
                     '.....',
                     '..OO.',
                     '.OO..',
                     '.....'],
                    ['.....',
                     '..O..',
                     '..OO.',
                     '...O.',
                     '.....']]

Z_SHAPE_TEMPLATE = [['.....',
                     '.....',
                     '.OO..',
                     '..OO.',
                     '.....'],
                    ['.....',
                     '..O..',
                     '.OO..',
                     '.O...',
                     '.....']]

I_SHAPE_TEMPLATE = [['..O..',
                     '..O..',
                     '..O..',
                     '..O..',
                     '.....'],
                    ['.....',
                     '.....',
                     'OOOO.',
                     '.....',
                     '.....']]

O_SHAPE_TEMPLATE = [['.....',
                     '.....',
                     '.OO..',
                     '.OO..',
                     '.....']]

J_SHAPE_TEMPLATE = [['.....',
                     '.O...',
                     '.OOO.',
                     '.....',
                     '.....'],
                    ['.....',
                     '..OO.',
                     '..O..',
                     '..O..',
                     '.....'],
                    ['.....',
                     '.....',
                     '.OOO.',
                     '...O.',
                     '.....'],
                    ['.....',
                     '..O..',
                     '..O..',
                     '.OO..',
                     '.....']]

L_SHAPE_TEMPLATE = [['.....',
                     '...O.',
                     '.OOO.',
                     '.....',
                     '.....'],
                    ['.....',
                     '..O..',
                     '..O..',
                     '..OO.',
                     '.....'],
                    ['.....',
                     '.....',
                     '.OOO.',
                     '.O...',
                     '.....'],
                    ['.....',
                     '.OO..',
                     '..O..',
                     '..O..',
                     '.....']]

T_SHAPE_TEMPLATE = [['.....',
                     '..O..',
                     '.OOO.',
                     '.....',
                     '.....'],
                    ['.....',
                     '..O..',
                     '..OO.',
                     '..O..',
                     '.....'],
                    ['.....',
                     '.....',
                     '.OOO.',
                     '..O..',
                     '.....'],
                    ['.....',
                     '..O..',
                     '.OO..',
                     '..O..',
                     '.....']]

PIECES = {'S': S_SHAPE_TEMPLATE,
          'Z': Z_SHAPE_TEMPLATE,
          'I': I_SHAPE_TEMPLATE,
          'J': J_SHAPE_TEMPLATE,
          'L': L_SHAPE_TEMPLATE,
          'O': O_SHAPE_TEMPLATE,
          'T': T_SHAPE_TEMPLATE}

PIECES_ORDER = {'S': 0,'Z': 1,'I': 2,'J': 3,'L': 4,'O': 5,'T': 6}

# snake constants #
UP = 'up'
DOWN = 'down'
LEFT = 'left'
RIGHT = 'right'

HEAD = 0 # syntactic sugar: index of the worm's head

# font clock #

clock_font = [
  0x1F, 0x11, 0x1F,
  0x00, 0x00, 0x1F,
  0x1D, 0x15, 0x17,
  0x15, 0x15, 0x1F,
  0x07, 0x04, 0x1F,
  0x17, 0x15, 0x1D,
  0x1F, 0x15, 0x1D,
  0x01, 0x01, 0x1F,
  0x1F, 0x15, 0x1F,
  0x17, 0x15, 0x1F]

theTetrisFont = [
    0x78,0x78,0x1E,0x1E, #S
    0x1E,0x1E,0x78,0x78, #Z
    0x00,0xFF,0xFF,0x00, #I
    0x06,0x06,0x7E,0x7E, #J
    0x7E,0x7E,0x06,0x06, #L
    0x3C,0x3C,0x3C,0x3C, #O
    0x7E,0x7E,0x18,0x18, #T
]

# serial port pi #

if PI:
    serport=serial.Serial("/dev/ttyAMA0",baudrate= 500000,timeout=3.0)
    device = led.matrix(cascaded=4)

# key server for controller #

QKEYDOWN=0
QKEYUP=1
myQueue = queue.Queue()
mask = bytearray([1,2,4,8,16,32,64,128])

class qEvent:
   def __init__(self, key, type):
        self.key = key
        self.type = type

class ThreadedTCPRequestHandler(socketserver.BaseRequestHandler):

    def handle(self):
        oldstr=b'\x80'  #create event on connection start (0x80 != 0x00)
        while RUNNING:
            data = self.request.recv(1)
            #cur_thread = threading.current_thread()
            #response = bytes("{}: {}".format(cur_thread.name, data), 'ascii')
            if data:
                if data!=oldstr:
                    #print(str(time.time()) + ' -- ' + str(oldstr))
                    for i in range (0,8):
                        if (bytes(data[0]&mask[i])!=bytes(oldstr[0]&mask[i])) :
                            if (bytes(data[0]&mask[i])):
                                myQueue.put(qEvent(i,QKEYDOWN))
                            else:
                                myQueue.put(qEvent(i,QKEYUP))
                oldstr = data
                #print(data)
            #self.request.sendall(response)

class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
    pass

def client(ip, port, message):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((ip, port))
    try:
        sock.sendall(bytes(message, 'ascii'))
        response = str(sock.recv(1024), 'ascii')
        print("Received: {}".format(response))
    finally:
        sock.close()

# main #

def main():

    global FPSCLOCK, DISPLAYSURF, BASICFONT, BIGFONT
    global a1_counter ,RUNNING
    a1_counter=0
    RUNNING=True

    if not PI:
        pygame.init()
        FPSCLOCK = pygame.time.Clock()
        DISPLAYSURF = pygame.display.set_mode((PIXEL_X*SIZE, PIXEL_Y*SIZE))
        BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
        BIGFONT = pygame.font.Font('freesansbold.ttf', 100)
        pygame.display.set_caption('Pi Games')
    else:
        # audio disabled
#        os.environ["SDL_VIDEODRIVER"] = "dummy" #dummy display for pygame audio
#        pygame.init()
#        pygame.mixer.music.load('tetrisb.mid')
        device.brightness(1)
        device.show_message("Waiting for controller...", font=proportional(CP437_FONT),delay=0.015)

    # Port 0 means to select an arbitrary unused port

    HOST, PORT = '', 4711

    server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler)
    ip, port = server.server_address

    # Start a thread with the server -- that thread will then start one
    # more thread for each request
    server_thread = threading.Thread(target=server.serve_forever)
    # Exit the server thread when the main thread terminates
    server_thread.daemon = True
    server_thread.start()
    print("Server loop running in thread:", server_thread.name)
    clearScreen()

    drawClock(1)
    if PI:
        device.show_message("Let's play", font=proportional(CP437_FONT),delay=0.03)

    while True:

        clearScreen()
        drawSymbols()
        while myQueue.empty():
            time.sleep(.1)
            a1_counter+=1
            updateScreen()
            if not PI:
                checkForQuit()
            time.sleep(.1)

        event = myQueue.get()

        if event.type == QKEYDOWN:
            if (event.key == BUTTON_BLUE):
                runSnakeGame()
            elif (event.key == BUTTON_YELLOW):
#                if PI:
#                    pygame.mixer.music.play(-1,0.0)
                runTetrisGame()
#                if PI:
#                    pygame.mixer.music.stop()
            elif (event.key == BUTTON_RED):
                runPongGame()
            elif (event.key == BUTTON_GREEN):
                drawClock(1)

    terminate()

# gaming main routines #

def runPongGame():
    down = 0
    up = 1
    left = 0
    right = 1
    lowerbarx = PIXEL_X//2
    upperbarx = PIXEL_X//2
    score1 = 0
    score2 = 0
    ballx = PIXEL_X//2
    bally = PIXEL_Y//2
    directiony = down
    directionx = left
    movingRightUpper = False
    movingLeftUpper = False
    movingRightLower = False
    movingLeftLower = False
    restart=False
    lastLowerMoveSidewaysTime = time.time()
    lastUpperMoveSidewaysTime = time.time()

    while True: # main game loop
        while not myQueue.empty():
            event = myQueue.get()
            if event.type == QKEYDOWN:
                if (event.key == 0):
                    movingLeftLower = True
                    movingRightLower = False
                elif (event.key == 1):
                    movingLeftLower = False
                    movingRightLower = True
                elif (event.key == BUTTON_YELLOW):
                    movingLeftUpper = True
                    movingRightUpper = False
                elif (event.key == BUTTON_GREEN):
                    movingLeftUpper = False
                    movingRightUpper = True
                elif event.key == BUTTON_RED:
                     return
            if event.type == QKEYUP:
                if (event.key == 0):
                    movingLeftLower =False
                elif (event.key == 1):
                    movingRightLower = False
                elif (event.key == BUTTON_YELLOW):
                    movingLeftUpper = False
                elif (event.key == BUTTON_GREEN):
                    movingRightUpper = False

        if (movingLeftLower) and time.time() - lastLowerMoveSidewaysTime > MOVESIDEWAYSFREQ:
            if lowerbarx >1:
                lowerbarx-=1;
            lastLowerMoveSidewaysTime = time.time()
        if (movingRightLower) and time.time() - lastLowerMoveSidewaysTime > MOVESIDEWAYSFREQ:
            if lowerbarx <PIXEL_X-2:
                lowerbarx+=1;
            lastLowerMoveSidewaysTime = time.time()
        if (movingLeftUpper) and time.time() - lastUpperMoveSidewaysTime > MOVESIDEWAYSFREQ:
            if upperbarx >1:
                upperbarx-=1;
            lastUpperMoveSidewaysTime = time.time()
        if (movingRightUpper) and time.time() - lastUpperMoveSidewaysTime > MOVESIDEWAYSFREQ:
            if upperbarx <PIXEL_X-2:
                upperbarx+=1;
            lastUpperMoveSidewaysTime = time.time()

        if not PI:
                checkForQuit()

        if (directiony == up):
            if (bally>1):
                bally-=1
            else:
                if (abs(ballx-upperbarx)<2):
                    directiony = down
                    if (ballx==upperbarx+1):
                        if (directionx==left):
                            directionx=right
                    if (ballx==upperbarx-1):
                        if (directionx==right):
                            directionx=left
                elif ((ballx-upperbarx==2) and (directionx==left)):
                    directionx=right
                    directiony = down
                elif ((ballx-upperbarx==-2) and (directionx==right)):
                    directionx=left
                    directiony = down
                else:
                    bally-=1
                    score1+=1
                    restart = True
        else:
            if (bally<PIXEL_Y-2):
                bally+=1
            else:
                if (abs(ballx-lowerbarx)<2):
                    directiony = up
                    if (ballx==lowerbarx+1):
                        if (directionx==left):
                            directionx=right
                    if (ballx==lowerbarx-1):
                        if (directionx==right):
                            directionx=left
                elif ((ballx-lowerbarx==2) and (directionx==left)):
                    directionx=right
                    directiony = up
                elif ((ballx-lowerbarx==-2) and (directionx==right)):
                    directionx=left
                    directiony = up
                else:
                    bally+=1
                    score2+=1
                    restart = True

        if (directionx == left):
            if (ballx>0):
                ballx-=1
            else:
                directionx = right
                ballx+=1
                if(directiony == up):
                    if(bally>2):
                        bally-=1
                if(directiony == down):
                    if(bally<PIXEL_Y-2):
                        bally+=1
        else:
            if (ballx<PIXEL_X-1):
                ballx+=random.randint(1,2)
            else:
                directionx = left
                ballx-=random.randint(1,2)
                if(directiony == up):
                    if(bally>3):
                        bally-=random.randint(0,2)
                if(directiony == down):
                    if(bally<PIXEL_Y-3):
                        bally+=random.randint(0,2)

        clearScreen()
        drawBall(ballx,bally)
        drawBar(upperbarx,0)
        drawBar(lowerbarx,PIXEL_Y-1)
        twoscoreText(score1,score2)
        updateScreen()

        if (score1 == 9) or (score2 == 9):
            time.sleep(3)
            return

        if restart:
            time.sleep(1)
            ballx=PIXEL_X//2
            bally=PIXEL_Y//2
            if directiony==down:
                directiony = up
            else:
                directiony = down
            restart=False
        else:
            time.sleep(.1)

def runSnakeGame():
    # Set a random start point.
    startx = random.randint(2, BOARDWIDTH-2 )
    starty = random.randint(2, BOARDHEIGHT -2 )
    wormCoords = [{'x': startx,     'y': starty},
                  {'x': startx - 1, 'y': starty},
                  {'x': startx - 2, 'y': starty}]
    direction = RIGHT
    score = 0

    # Start the apple in a random place.
    apple = getRandomLocation()

    while True: # main game loop
        if not myQueue.empty():
            event = myQueue.get()
            # take only one input per run
            while not myQueue.empty():
                myQueue.get()
            if event.type == QKEYDOWN:
                if (event.key == 0) and direction != RIGHT:
                    direction = LEFT
                elif (event.key == 1) and direction != LEFT:
                    direction = RIGHT
                elif (event.key == 2) and direction != DOWN:
                    direction = UP
                elif (event.key == 3) and direction != UP:
                    direction = DOWN
                elif (event.key == BUTTON_RED):
                     return

        # check if the worm has hit itself or the edge
        if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == BOARDWIDTH or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == BOARDHEIGHT:
            time.sleep(1.5)
            return # game over
        for wormBody in wormCoords[1:]:
            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
                time.sleep(1.5)
                return # game over

        # check if worm has eaten an apple
        if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
            # don't remove worm's tail segment
            score += 1
            apple = getRandomLocation() # set a new apple somewhere
        else:
            del wormCoords[-1] # remove worm's tail segment

        # move the worm by adding a segment in the direction it is moving
        if direction == UP:
            if wormCoords[HEAD]['y'] == 0 :
                newHead = {'x': wormCoords[HEAD]['x'], 'y': BOARDHEIGHT-1}
            else:
                newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}
        elif direction == DOWN:
            if wormCoords[HEAD]['y'] == BOARDHEIGHT-1 :
                newHead = {'x': wormCoords[HEAD]['x'], 'y': 0}
            else:
                newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}
        elif direction == LEFT:
            if wormCoords[HEAD]['x'] == 0 :
                newHead = {'x': BOARDWIDTH -1, 'y': wormCoords[HEAD]['y'] }
            else:
                newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}
        elif direction == RIGHT:
            if wormCoords[HEAD]['x'] == BOARDWIDTH-1:
                newHead = {'x': 0, 'y': wormCoords[HEAD]['y']}
            else:
                newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
        if not PI:
            checkForQuit()
        wormCoords.insert(0, newHead)
        clearScreen()
        drawWorm(wormCoords)
        drawApple(apple)
        scoreText(score)
        updateScreen()
        time.sleep(.15)

def runTetrisGame():
    # setup varia
    # bles for the start of the game
    if PI:
        device.brightness(1)
        device.flush()
    board = getBlankBoard()
    lastMoveDownTime = time.time()
    lastMoveSidewaysTime = time.time()
    lastFallTime = time.time()
    movingDown = False # note: there is no movingUp variable
    movingLeft = False
    movingRight = False
    score = 0
    oldscore = -1
    oldpiece = 10
    lines = 0
    level, fallFreq = calculateLevelAndFallFreq(lines)

    fallingPiece = getNewPiece()
    nextPiece = getNewPiece()

    while True: # game loop

        #if not myQueue.empty():
        #    print(myQueue.get().type)

        if fallingPiece == None:
            # No falling piece in play, so start a new piece at the top
            fallingPiece = nextPiece
            nextPiece = getNewPiece()
            lastFallTime = time.time() # reset lastFallTime

            if not isValidPosition(board, fallingPiece):
                time.sleep(2)
                return # can't fit a new piece on the board, so game over
        if not PI:
            checkForQuit()

        while not myQueue.empty():
            event = myQueue.get()
            if event.type == QKEYUP:
                if (event.key == 7):

                    lastFallTime = time.time()
                    lastMoveDownTime = time.time()
                    lastMoveSidewaysTime = time.time()
                elif (event.key == 0):
                    movingLeft = False
                elif (event.key == 1):
                    movingRight = False
                elif (event.key == 3):
                    movingDown = False

            elif event.type == QKEYDOWN:
                # moving the piece sideways
                if (event.key == 0) and isValidPosition(board, fallingPiece, adjX=-1):
                    fallingPiece['x'] -= 1
                    movingLeft = True
                    movingRight = False
                    lastMoveSidewaysTime = time.time()

                elif (event.key == 1) and isValidPosition(board, fallingPiece, adjX=1):
                    fallingPiece['x'] += 1
                    movingRight = True
                    movingLeft = False
                    lastMoveSidewaysTime = time.time()

                # rotating the piece (if there is room to rotate)
                elif (event.key == 2):
                    fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])
                    if not isValidPosition(board, fallingPiece):
                        fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
                elif (event.key == 5): # rotate the other direction
                    fallingPiece['rotation'] = (fallingPiece['rotation'] - 1) % len(PIECES[fallingPiece['shape']])
                    if not isValidPosition(board, fallingPiece):
                        fallingPiece['rotation'] = (fallingPiece['rotation'] + 1) % len(PIECES[fallingPiece['shape']])

                # making the piece fall faster with the down key
                elif (event.key == 3):
                    movingDown = True
                    if isValidPosition(board, fallingPiece, adjY=1):
                        fallingPiece['y'] += 1
                    lastMoveDownTime = time.time()

                # move the current piece all the way down
                elif event.key == 4:
                    movingDown = False
                    movingLeft = False
                    movingRight = False
                    for i in range(1, BOARDHEIGHT):
                        if not isValidPosition(board, fallingPiece, adjY=i):
                            break
                    score+=i #TODO: more digits on numbercounter, more scores
                    fallingPiece['y'] += i - 1

        # handle moving the piece because of user input
        if (movingLeft or movingRight) and time.time() - lastMoveSidewaysTime > MOVESIDEWAYSFREQ:
            if movingLeft and isValidPosition(board, fallingPiece, adjX=-1):
                fallingPiece['x'] -= 1
            elif movingRight and isValidPosition(board, fallingPiece, adjX=1):
                fallingPiece['x'] += 1
            lastMoveSidewaysTime = time.time()

        if movingDown and time.time() - lastMoveDownTime > MOVEDOWNFREQ and isValidPosition(board, fallingPiece, adjY=1):
            fallingPiece['y'] += 1
            lastMoveDownTime = time.time()

        # let the piece fall if it is time to fall
        if time.time() - lastFallTime > fallFreq:
            # see if the piece has landed
            if not isValidPosition(board, fallingPiece, adjY=1):
                # falling piece has landed, set it on the board
                addToBoard(board, fallingPiece)
                remLine = removeCompleteLines(board)
                # count lines for level calculation
                lines += remLine
                # more lines, more points per line
                score += SCORES[remLine]*level
                level, fallFreq = calculateLevelAndFallFreq(lines)
                fallingPiece = None
            else:
                # piece did not land, just move the piece down
                fallingPiece['y'] += 1
                lastFallTime = time.time()

        # drawing everything on the screen
        clearScreen()
        drawBoard(board)
        #scoreText(score)
        if score>oldscore:
            scoreTetris(score,level,PIECES_ORDER.get(nextPiece['shape']))
            oldscore = score
        if oldpiece!=PIECES_ORDER.get(nextPiece['shape']):
            scoreTetris(score,level,PIECES_ORDER.get(nextPiece['shape']))
            oldpiece=PIECES_ORDER.get(nextPiece['shape'])
        #drawStatus(score, level)
        #drawNextPiece(nextPiece)
        if fallingPiece != None:
            drawPiece(fallingPiece)

        updateScreen()
        #FPSCLOCK.tick(FPS)
        time.sleep(.05)

def drawSymbols():
     #snbake symbol
    drawPixel(1,2,0)
    drawPixel(2,2,0)
    drawPixel(1,3,0)
    drawPixel(1,4,0)
    drawPixel(2,3,0)
    drawPixel(2,4,0)
    drawPixel(5,3,2)
    drawPixel(6,3,1)
    drawPixel(7,3,1)
    drawPixel(8,3,1)
    drawPixel(8,2,1)
    drawPixel(8,1,1)

    #pong symbol
    drawPixel(1,9,2)
    drawPixel(2,9,2)
    drawPixel(1,10,2)
    drawPixel(2,10,2)
    drawPixel(1,11,2)
    drawPixel(2,11,2)
    drawPixel(5,9,1)
    drawPixel(6,9,1)
    drawPixel(7,9,1)
    drawPixel(6,11,0)

    #tetris symbol
    drawPixel(1,16,3)
    drawPixel(2,16,3)
    drawPixel(1,17,3)
    drawPixel(1,18,3)
    drawPixel(2,17,3)
    drawPixel(2,18,3)
    drawPixel(7,16,0)
    drawPixel(6,16,0)
    drawPixel(6,17,0)
    drawPixel(6,18,0)

def drawClock(color):

    if PI:
        device.clear();
        device.flush();

    hour =  time.localtime().tm_hour
    minute= time.localtime().tm_min
    second= time.localtime().tm_sec

    while True:
        while not myQueue.empty():
            event = myQueue.get()
            if event.type == QKEYDOWN:
                if (event.key == 5):
                    # Pausing the game
                    return;
            elif event.type == QKEYUP:
                if (event.key == 7):
                    # Pausing the game
                    return;
        if not PI:
                checkForQuit()

        ltime =  time.localtime()
        hour = ltime.tm_hour
        minute= ltime.tm_min
        second= ltime.tm_sec
        clearScreen()

        drawnumber(int(hour/10),2,1,color)
        drawnumber(int(hour%10),6,1,color)
        drawnumber(int(minute/10),2,8,color)
        drawnumber(int(minute%10),6,8,color)
        drawnumber(int(second/10),2,15,color)
        drawnumber(int(second%10),6,15,color)

        updateScreen()
        time.sleep(.2)

def drawImage(filename):
    im = Image.open(filename)
    for row in range(0,BOARDHEIGHT):
        for col in range(0,BOARDWIDTH):
            r,g,b = im.getpixel((col,row))
            drawPixelRgb(col,row,r,g,b)
    updateScreen()

def drawHalfImage(filename,offset):
    im = Image.open(filename)
    if offset>10:
        offset = 10
    for row in range(0,10):
        for col in range(0,10):
            r,g,b = im.getpixel((col,row))
            drawPixelRgb(col,row+offset,r,g,b)

# drawing #

def clearScreen():
    if PI:
        serport.write(bytearray([32]))
    else:
        DISPLAYSURF.fill(BGCOLOR)

def updateScreen():
    if PI:
        serport.write(bytearray([30]))
    else:
        pygame.display.update()

def drawPixel(x,y,color):
    if color == BLANK:
        return
    if PI:
        if (x>=0 and y>=0 and color >=0):
            serport.write(bytearray([26,x,y,color]))
    else:
        pygame.draw.rect(DISPLAYSURF, COLORS[color], (x*SIZE+1, y*SIZE+1, SIZE-2, SIZE-2))

def drawPixelRgb(x,y,r,g,b):
    if PI:
        if (x>=0 and y>=0):
            serport.write(bytearray([24,x,y,r,g,b]))
    else:
        pygame.draw.rect(DISPLAYSURF, (r,g,b), (x*SIZE+1, y*SIZE+1, SIZE-2, SIZE-2))

def drawnumber(number,offsetx,offsety,color):
    for x in range(0,3):
        for y in range(0,5):
            if clock_font[3*number + x]&mask[y]:
                drawPixel(offsetx+x,offsety+y,color)

def drawnumberMAX7219(number,offsetx,offsety):
    for x in range(0,3):
        for y in range(0,5):
            if clock_font[3*number+2- x]&mask[y]:
                drawScorePixel(offsetx+x,offsety+y,1)
            elif clock_font[3*number+2- x]&mask[y]:
                drawScorePixel(offsetx+x,offsety+y,0)

def drawTetrisMAX7219(piece,offsetx,offsety):
    for x in range(0,4):
        for y in range(0,8):
            if theTetrisFont[4*piece + x]&mask[y]:
                drawScorePixel(offsetx+x,offsety+y,1)
            elif theTetrisFont[4*piece + x]&mask[y]:
                drawScorePixel(offsetx+x,offsety+y,0)

def drawScorePixel(x,y,on):
    if PI:
        device.pixel(31-x,y,on,False)
    else:
        pygame.draw.rect(DISPLAYSURF, COLORS[2], (64-2*x, 410+2*y,2,2))

def makeTextObjs(text, font, color):
    surf = font.render(text, True, color)
    return surf, surf.get_rect()

def scrollText(text):
    if PI:
        device.show_message(text, font=proportional(CP437_FONT))
    else:
        titleSurf, titleRect = makeTextObjs(str(text), BASICFONT, TEXTCOLOR)
        titleRect.center = (int(WINDOWWIDTH / 2) - 3, int(WINDOWHEIGHT / 2) - 3)
        DISPLAYSURF.blit(titleSurf, titleRect)

def scoreText(score):
    _score=score
    if _score>9999:
        _score = 9999
    if PI:
        for i in range(0,4):
            device.letter(3-i, ord('0') + (_score%10))
            _score //=10
    else:
        titleSurf, titleRect = makeTextObjs(str(_score), BASICFONT, TEXTCOLOR)
        titleRect.center = (int(WINDOWWIDTH / 2) - 3, int(WINDOWHEIGHT / 2) - 3)
        DISPLAYSURF.blit(titleSurf, titleRect)

def scoreTetris(score,level,nextpiece):
    if PI:
        device.clear()
    _score=score
    if _score>999999:
        _score = 999999

    # one point per level
    for i in range(0,level):
        drawScorePixel(i*2,7,1)

    # score as 6 digit value
    for i in range(0,6):
        drawnumberMAX7219(_score%10,i*4,0)
        _score //=10

    # draw next piece
    drawTetrisMAX7219(nextpiece,27,0)

    if PI:
        device.flush()

def twoscoreText(score1,score2):
    _score1=score1
    _score2=score2
    if _score1>9:
        _score1 = 9
    if _score2>9:
        _score2 = 9
    if PI:
        device.letter(0, ord('0') + (_score1))
        device.letter(1, ord(':'))
        device.letter(2, ord('0') + (_score2))
        device.letter(3, ord(' '))
    else:
        titleSurf, titleRect = makeTextObjs(str(_score1)+':'+str(_score2), BASICFONT, TEXTCOLOR)
        titleRect.center = (int(WINDOWWIDTH / 2) - 3, int(WINDOWHEIGHT / 2) - 3)
        DISPLAYSURF.blit(titleSurf, titleRect)

# program flow #

def terminate():
    RUNNING = False
    if not PI:
        pygame.quit()
    sys.exit()

def checkForQuit():
    for event in pygame.event.get(QUIT): # get all the QUIT events
        terminate() # terminate if any QUIT events are present
    for event in pygame.event.get(KEYUP): # get all the KEYUP events
        if event.key == K_ESCAPE:
            terminate() # terminate if the KEYUP event was for the Esc key
        pygame.event.post(event) # put the other KEYUP event objects back

# tetris subroutines #

def calculateLevelAndFallFreq(lines):
    # Based on the score, return the level the player is on and
    # how many seconds pass until a falling piece falls one space.
    level = int(lines / 10) + 1
    # limit level to 10
    if level >10:
        level = 10
    fallFreq = FALLING_SPEED - (level * 0.05)
    if fallFreq <= 0.05:
        fallFreq = 0.05
    return level, fallFreq

def getNewPiece():
    # return a random new piece in a random rotation and color
    shape = random.choice(list(PIECES.keys()))
    newPiece = {'shape': shape,
                'rotation': random.randint(0, len(PIECES[shape]) - 1),
                'x': int(BOARDWIDTH / 2) - int(TEMPLATEWIDTH / 2),
                'y': -2, # start it above the board (i.e. less than 0)
                'color': PIECES_ORDER.get(shape)}
    return newPiece

def addToBoard(board, piece):
    # fill in the board based on piece's location, shape, and rotation
    for x in range(TEMPLATEWIDTH):
        for y in range(TEMPLATEHEIGHT):
            if PIECES[piece['shape']][piece['rotation']][y][x] != BLANK:
                board[x + piece['x']][y + piece['y']] = piece['color']

def isOnBoard(x, y):
    return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT

def isValidPosition(board, piece, adjX=0, adjY=0):
    # Return True if the piece is within the board and not colliding
    for x in range(TEMPLATEWIDTH):
        for y in range(TEMPLATEHEIGHT):
            isAboveBoard = y + piece['y'] + adjY < 0
            if isAboveBoard or PIECES[piece['shape']][piece['rotation']][y][x] == BLANK:
                continue
            if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY):
                return False
            if board[x + piece['x'] + adjX][y + piece['y'] + adjY] != BLANK:
                return False
    return True

def isCompleteLine(board, y):
    # Return True if the line filled with boxes with no gaps.
    for x in range(BOARDWIDTH):
        if board[x][y] == BLANK:
            return False
    return True

def removeCompleteLines(board):
    # Remove any completed lines on the board, move everything above them down, and return the number of complete lines.
    numLinesRemoved = 0
    y = BOARDHEIGHT - 1 # start y at the bottom of the board
    while y >= 0:
        if isCompleteLine(board, y):
            # Remove the line and pull boxes down by one line.
            for pullDownY in range(y, 0, -1):
                for x in range(BOARDWIDTH):
                    board[x][pullDownY] = board[x][pullDownY-1]
            # Set very top line to blank.
            for x in range(BOARDWIDTH):
                board[x][0] = BLANK
            numLinesRemoved += 1
            # Note on the next iteration of the loop, y is the same.
            # This is so that if the line that was pulled down is also
            # complete, it will be removed.
        else:
            y -= 1 # move on to check next row up
    return numLinesRemoved

def drawBoard(matrix):
    for i in range(0,BOARDWIDTH):
        for j in range(0,BOARDHEIGHT):
            drawPixel(i,j,matrix[i][j])

def getBlankBoard():
    # create and return a new blank board data structure
    board = []
    for i in range(BOARDWIDTH):
        board.append([BLANK] * BOARDHEIGHT)
    return board

def drawPiece(piece, pixelx=None, pixely=None):
    shapeToDraw = PIECES[piece['shape']][piece['rotation']]
    if pixelx == None and pixely == None:
        # if pixelx & pixely hasn't been specified, use the location stored in the piece data structure
        pixelx=piece['x']
        pixely=piece['y']

    # draw each of the boxes that make up the piece
    for x in range(TEMPLATEWIDTH):
        for y in range(TEMPLATEHEIGHT):
            if shapeToDraw[y][x] != BLANK:
                drawPixel( pixelx+ x , pixely+y,piece['color'])

# snake subroutines #

def getRandomLocation():
    return {'x': random.randint(0, BOARDWIDTH - 1), 'y': random.randint(0, BOARDHEIGHT - 1)}

def drawWorm(wormCoords):
    for coord in wormCoords:
        x = coord['x']
        y = coord['y']
        drawPixel(x,y,1)

def drawApple(coord):
    x = coord['x']
    y = coord['y']
    drawPixel(x,y,2)

# pong subroutines #

def drawBar(x,y):
    drawPixel(x-1,y,1)
    drawPixel(x,y,1)
    drawPixel(x+1,y,1)

def drawBall(x,y):
    drawPixel(x,y,0)

if __name__ == '__main__':
    main()


text:
CREATE TABLE OrleansRemindersTable
(
    ServiceId NVARCHAR(150) NOT NULL,
    GrainId VARCHAR(150) NOT NULL,
    ReminderName NVARCHAR(150) NOT NULL,
    StartTime DATETIME NOT NULL,
    Period BIGINT NOT NULL,
    GrainHash INT NOT NULL,
    Version INT NOT NULL,

    CONSTRAINT PK_RemindersTable_ServiceId_GrainId_ReminderName PRIMARY KEY(ServiceId, GrainId, ReminderName)
);

INSERT INTO OrleansQuery(QueryKey, QueryText)
VALUES
(
    'UpsertReminderRowKey','
    INSERT INTO OrleansRemindersTable
    (
        ServiceId,
        GrainId,
        ReminderName,
        StartTime,
        Period,
        GrainHash,
        Version
    )
    VALUES
    (
        @ServiceId,
        @GrainId,
        @ReminderName,
        @StartTime,
        @Period,
        @GrainHash,
        last_insert_id(0)
    )
    ON DUPLICATE KEY
    UPDATE
        StartTime = @StartTime,
        Period = @Period,
        GrainHash = @GrainHash,
        Version = last_insert_id(Version+1);

    SELECT last_insert_id() AS Version;
');

INSERT INTO OrleansQuery(QueryKey, QueryText)
VALUES
(
    'ReadReminderRowsKey','
    SELECT
        GrainId,
        ReminderName,
        StartTime,
        Period,
        Version
    FROM OrleansRemindersTable
    WHERE
        ServiceId = @ServiceId AND @ServiceId IS NOT NULL
        AND GrainId = @GrainId AND @GrainId IS NOT NULL;
');

INSERT INTO OrleansQuery(QueryKey, QueryText)
VALUES
(
    'ReadReminderRowKey','
    SELECT
        GrainId,
        ReminderName,
        StartTime,
        Period,
        Version
    FROM OrleansRemindersTable
    WHERE
        ServiceId = @ServiceId AND @ServiceId IS NOT NULL
        AND GrainId = @GrainId AND @GrainId IS NOT NULL
        AND ReminderName = @ReminderName AND @ReminderName IS NOT NULL;
');

INSERT INTO OrleansQuery(QueryKey, QueryText)
VALUES
(
    'ReadRangeRows1Key','
    SELECT
        GrainId,
        ReminderName,
        StartTime,
        Period,
        Version
    FROM OrleansRemindersTable
    WHERE
        ServiceId = @ServiceId AND @ServiceId IS NOT NULL
        AND GrainHash > @BeginHash AND @BeginHash IS NOT NULL
        AND GrainHash <= @EndHash AND @EndHash IS NOT NULL;
');

INSERT INTO OrleansQuery(QueryKey, QueryText)
VALUES
(
    'ReadRangeRows2Key','
    SELECT
        GrainId,
        ReminderName,
        StartTime,
        Period,
        Version
    FROM OrleansRemindersTable
    WHERE
        ServiceId = @ServiceId AND @ServiceId IS NOT NULL
        AND ((GrainHash > @BeginHash AND @BeginHash IS NOT NULL)
        OR (GrainHash <= @EndHash AND @EndHash IS NOT NULL));
');

INSERT INTO OrleansQuery(QueryKey, QueryText)
VALUES
(
    'DeleteReminderRowKey','
    DELETE FROM OrleansRemindersTable
    WHERE
        ServiceId = @ServiceId AND @ServiceId IS NOT NULL
        AND GrainId = @GrainId AND @GrainId IS NOT NULL
        AND ReminderName = @ReminderName AND @ReminderName IS NOT NULL
        AND Version = @Version AND @Version IS NOT NULL;
    SELECT ROW_COUNT();
');

INSERT INTO OrleansQuery(QueryKey, QueryText)
VALUES
(
    'DeleteReminderRowsKey','
    DELETE FROM OrleansRemindersTable
    WHERE
        ServiceId = @ServiceId AND @ServiceId IS NOT NULL;
');


text:
package org.hl7.fhir.instance.model.valuesets;

// Generated on Tue, Jul 21, 2015 10:37-0400 for FHIR v0.5.0

public enum ListItemFlag {

        /**
         * No change has been made to the status of this medicine item.
         */
        _01,
        /**
         * The medicine item has changed. The change may be described in an extension (not defined yet)
         */
        _02,
        /**
         * The prescription for this medicine item was cancelled by an authorized health care provider. The patient may be advised to complete the course of the prescribed medicine. This advice is a clinical decision made based on assessment of the patient"s clinical condition.
         */
        _03,
        /**
         * A new medicine item has been prescribed
         */
        _04,
        /**
         * Administration of this medication item that the patient is currently taking is stopped or recommended to be stopped (i.e. instructed to be ceased by a health care provider). This cessation is anticipated to be permanent. The Change Description should describe the reason for cessation. Example uses: the medication in question is considered ineffective or has caused serious adverse effects. This value applies both to the cessation of a medication that is prescribed by another healthcare provider or patient self-administration of OTC medicines.
         */
        _05,
        /**
         * Administration of this medication item that the patient is currently taking is on hold, or instructed or recommended by a health care provider to be temporarily stopped, or subject to clinical review (i.e. the stop may be temporary or permanent depending on the outcome of clinical review), or temporarily suspended as a pre-requisite to certain surgical or diagnostic procedures.
         */
        _06,
        /**
         * added to help the parsers
         */
        NULL;
        public static ListItemFlag fromCode(String codeString) throws Exception {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("01".equals(codeString))
          return _01;
        if ("02".equals(codeString))
          return _02;
        if ("03".equals(codeString))
          return _03;
        if ("04".equals(codeString))
          return _04;
        if ("05".equals(codeString))
          return _05;
        if ("06".equals(codeString))
          return _06;
        throw new Exception("Unknown ListItemFlag code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case _01: return "01";
            case _02: return "02";
            case _03: return "03";
            case _04: return "04";
            case _05: return "05";
            case _06: return "06";
            default: return "?";
          }
        }
        public String getSystem() {
          return "urn:oid:1.2.36.1.2001.1001.101.104.16592";
        }
        public String getDefinition() {
          switch (this) {
            case _01: return "No change has been made to the status of this medicine item.";
            case _02: return "The medicine item has changed. The change may be described in an extension (not defined yet)";
            case _03: return "The prescription for this medicine item was cancelled by an authorized health care provider. The patient may be advised to complete the course of the prescribed medicine. This advice is a clinical decision made based on assessment of the patient"s clinical condition.";
            case _04: return "A new medicine item has been prescribed";
            case _05: return "Administration of this medication item that the patient is currently taking is stopped or recommended to be stopped (i.e. instructed to be ceased by a health care provider). This cessation is anticipated to be permanent. The Change Description should describe the reason for cessation. Example uses: the medication in question is considered ineffective or has caused serious adverse effects. This value applies both to the cessation of a medication that is prescribed by another healthcare provider or patient self-administration of OTC medicines.";
            case _06: return "Administration of this medication item that the patient is currently taking is on hold, or instructed or recommended by a health care provider to be temporarily stopped, or subject to clinical review (i.e. the stop may be temporary or permanent depending on the outcome of clinical review), or temporarily suspended as a pre-requisite to certain surgical or diagnostic procedures.";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case _01: return "Unchanged";
            case _02: return "Changed";
            case _03: return "Cancelled";
            case _04: return "Prescribed";
            case _05: return "Ceased";
            case _06: return "Suspended";
            default: return "?";
          }
    }

}


text:
<?php

class Helper
{
    public static function value($value)
    {
        return $value instanceof Closure ? $value() : $value;
    }
}


text:
namespace SampleApp
{
	partial class SimpleExample
	{
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing && (components != null))
			{
				components.Dispose();
			}
			base.Dispose(disposing);
		}

		#region Component Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			this._addRoot = new System.Windows.Forms.Button();
			this._clear = new System.Windows.Forms.Button();
			this._addChild = new System.Windows.Forms.Button();
			this._deleteNode = new System.Windows.Forms.Button();
			this._timer = new System.Windows.Forms.Timer(this.components);
			this._autoRowHeight = new System.Windows.Forms.CheckBox();
			this._fontSize = new System.Windows.Forms.NumericUpDown();
			this.label1 = new System.Windows.Forms.Label();
			this._performanceTest = new System.Windows.Forms.CheckBox();
			this.button1 = new System.Windows.Forms.Button();
			this.button2 = new System.Windows.Forms.Button();
			this.button3 = new System.Windows.Forms.Button();
			this._tree2 = new Aga.Controls.Tree.TreeViewAdv();
			this.nodeTextBox1 = new Aga.Controls.Tree.NodeControls.NodeTextBox();
			this._tree = new Aga.Controls.Tree.TreeViewAdv();
			this._nodeCheckBox = new Aga.Controls.Tree.NodeControls.NodeCheckBox();
			this._nodeStateIcon = new Aga.Controls.Tree.NodeControls.NodeStateIcon();
			this._nodeTextBox = new Aga.Controls.Tree.NodeControls.NodeTextBox();
			((System.ComponentModel.ISupportInitialize)(this._fontSize)).BeginInit();
			this.SuspendLayout();
			//
			// _addRoot
			//
			this._addRoot.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this._addRoot.Location = new System.Drawing.Point(377, 3);
			this._addRoot.Name = "_addRoot";
			this._addRoot.Size = new System.Drawing.Size(108, 23);
			this._addRoot.TabIndex = 1;
			this._addRoot.Text = "Add Root";
			this._addRoot.UseVisualStyleBackColor = true;
			this._addRoot.Click += new System.EventHandler(this.AddRootClick);
			//
			// _clear
			//
			this._clear.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this._clear.Location = new System.Drawing.Point(377, 90);
			this._clear.Name = "_clear";
			this._clear.Size = new System.Drawing.Size(108, 23);
			this._clear.TabIndex = 2;
			this._clear.Text = "Clear Tree";
			this._clear.UseVisualStyleBackColor = true;
			this._clear.Click += new System.EventHandler(this.ClearClick);
			//
			// _addChild
			//
			this._addChild.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this._addChild.Location = new System.Drawing.Point(377, 32);
			this._addChild.Name = "_addChild";
			this._addChild.Size = new System.Drawing.Size(108, 23);
			this._addChild.TabIndex = 3;
			this._addChild.Text = "Add Child";
			this._addChild.UseVisualStyleBackColor = true;
			this._addChild.Click += new System.EventHandler(this.AddChildClick);
			//
			// _deleteNode
			//
			this._deleteNode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this._deleteNode.Location = new System.Drawing.Point(377, 61);
			this._deleteNode.Name = "_deleteNode";
			this._deleteNode.Size = new System.Drawing.Size(108, 23);
			this._deleteNode.TabIndex = 5;
			this._deleteNode.Text = "Delete Node";
			this._deleteNode.UseVisualStyleBackColor = true;
			this._deleteNode.Click += new System.EventHandler(this.DeleteClick);
			//
			// _timer
			//
			this._timer.Interval = 1;
			this._timer.Tick += new System.EventHandler(this._timer_Tick);
			//
			// _autoRowHeight
			//
			this._autoRowHeight.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this._autoRowHeight.AutoSize = true;
			this._autoRowHeight.Checked = true;
			this._autoRowHeight.CheckState = System.Windows.Forms.CheckState.Checked;
			this._autoRowHeight.Location = new System.Drawing.Point(378, 251);
			this._autoRowHeight.Name = "_autoRowHeight";
			this._autoRowHeight.Size = new System.Drawing.Size(101, 17);
			this._autoRowHeight.TabIndex = 7;
			this._autoRowHeight.Text = "AutoRowHeight";
			this._autoRowHeight.UseVisualStyleBackColor = true;
			this._autoRowHeight.Click += new System.EventHandler(this._autoRowHeight_Click);
			//
			// _fontSize
			//
			this._fontSize.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this._fontSize.Location = new System.Drawing.Point(438, 225);
			this._fontSize.Maximum = new decimal(new int[] {
            30,
            0,
            0,
            0});
			this._fontSize.Minimum = new decimal(new int[] {
            9,
            0,
            0,
            0});
			this._fontSize.Name = "_fontSize";
			this._fontSize.Size = new System.Drawing.Size(48, 20);
			this._fontSize.TabIndex = 8;
			this._fontSize.Value = new decimal(new int[] {
            9,
            0,
            0,
            0});
			this._fontSize.ValueChanged += new System.EventHandler(this._fontSize_ValueChanged);
			//
			// label1
			//
			this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.label1.AutoSize = true;
			this.label1.Location = new System.Drawing.Point(378, 227);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(54, 13);
			this.label1.TabIndex = 9;
			this.label1.Text = "Font Size:";
			//
			// _performanceTest
			//
			this._performanceTest.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this._performanceTest.AutoSize = true;
			this._performanceTest.Location = new System.Drawing.Point(378, 274);
			this._performanceTest.Name = "_performanceTest";
			this._performanceTest.Size = new System.Drawing.Size(109, 17);
			this._performanceTest.TabIndex = 10;
			this._performanceTest.Text = "Measure Perform.";
			this._performanceTest.UseVisualStyleBackColor = true;
			this._performanceTest.Click += new System.EventHandler(this._performanceTest_Click);
			//
			// button1
			//
			this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.button1.Location = new System.Drawing.Point(377, 148);
			this.button1.Name = "button1";
			this.button1.Size = new System.Drawing.Size(108, 23);
			this.button1.TabIndex = 12;
			this.button1.Text = "Refresh";
			this.button1.UseVisualStyleBackColor = true;
			this.button1.Click += new System.EventHandler(this.button1_Click);
			//
			// button2
			//
			this.button2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.button2.Location = new System.Drawing.Point(377, 119);
			this.button2.Name = "button2";
			this.button2.Size = new System.Drawing.Size(108, 23);
			this.button2.TabIndex = 13;
			this.button2.Text = "Expand/Collapse";
			this.button2.UseVisualStyleBackColor = true;
			this.button2.Click += new System.EventHandler(this.button2_Click);
			//
			// button3
			//
			this.button3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.button3.Location = new System.Drawing.Point(377, 177);
			this.button3.Name = "button3";
			this.button3.Size = new System.Drawing.Size(108, 23);
			this.button3.TabIndex = 14;
			this.button3.Text = "button3";
			this.button3.UseVisualStyleBackColor = true;
			this.button3.Click += new System.EventHandler(this.button3_Click);
			//
			// _tree2
			//
			this._tree2.AllowDrop = true;
			this._tree2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this._tree2.BackColor = System.Drawing.SystemColors.Window;
			this._tree2.Cursor = System.Windows.Forms.Cursors.Default;
			this._tree2.DefaultToolTipProvider = null;
			this._tree2.DisplayDraggingNodes = true;
			this._tree2.DragDropMarkColor = System.Drawing.Color.Black;
			this._tree2.LineColor = System.Drawing.SystemColors.ControlDark;
			this._tree2.Location = new System.Drawing.Point(0, 229);
			this._tree2.Model = null;
			this._tree2.Name = "_tree2";
			this._tree2.NodeControls.Add(this.nodeTextBox1);
			this._tree2.Search.BackColor = System.Drawing.Color.Pink;
			this._tree2.Search.FontColor = System.Drawing.Color.Black;
			this._tree2.SelectedNode = null;
			this._tree2.Size = new System.Drawing.Size(371, 155);
			this._tree2.TabIndex = 11;
			this._tree2.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this._tree2_ItemDrag);
			//
			// nodeTextBox1
			//
			this.nodeTextBox1.DataPropertyName = "Text";
			this.nodeTextBox1.ParentColumn = null;
			//
			// _tree
			//
			this._tree.AllowDrop = true;
			this._tree.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
						| System.Windows.Forms.AnchorStyles.Left)
						| System.Windows.Forms.AnchorStyles.Right)));
			this._tree.AutoRowHeight = true;
			this._tree.BackColor = System.Drawing.SystemColors.Window;
			this._tree.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
			this._tree.Cursor = System.Windows.Forms.Cursors.Default;
			this._tree.DefaultToolTipProvider = null;
			this._tree.DisplayDraggingNodes = true;
			this._tree.DragDropMarkColor = System.Drawing.Color.Black;
			this._tree.GridLines = true;
			this._tree.LineColor = System.Drawing.SystemColors.ControlDark;
			this._tree.Location = new System.Drawing.Point(0, 0);
			this._tree.Model = null;
			this._tree.Name = "_tree";
			this._tree.NodeControls.Add(this._nodeCheckBox);
			this._tree.NodeControls.Add(this._nodeStateIcon);
			this._tree.NodeControls.Add(this._nodeTextBox);
			this._tree.Search.BackColor = System.Drawing.Color.Orange;
			this._tree.Search.FontColor = System.Drawing.Color.Black;
			this._tree.SelectedNode = null;
			this._tree.SelectionMode = Aga.Controls.Tree.TreeSelectionMode.MultiSameParent;
			this._tree.ShowNodeToolTips = true;
			this._tree.Size = new System.Drawing.Size(371, 223);
			this._tree.TabIndex = 0;
			this._tree.NodeMouseDoubleClick += new System.EventHandler<Aga.Controls.Tree.TreeNodeAdvMouseEventArgs>(this._tree_NodeMouseDoubleClick);
			this._tree.DragDrop += new System.Windows.Forms.DragEventHandler(this._tree_DragDrop);
			this._tree.SelectionChanged += new System.EventHandler(this._tree_SelectionChanged);
			this._tree.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this._tree_ItemDrag);
			this._tree.DragOver += new System.Windows.Forms.DragEventHandler(this._tree_DragOver);
			//
			// _nodeCheckBox
			//
			this._nodeCheckBox.DataPropertyName = "CheckState";
			this._nodeCheckBox.IncrementalSearchEnabled = false;
			this._nodeCheckBox.ParentColumn = null;
			this._nodeCheckBox.ThreeState = true;
			//
			// _nodeStateIcon
			//
			this._nodeStateIcon.IncrementalSearchEnabled = false;
			this._nodeStateIcon.ParentColumn = null;
			//
			// _nodeTextBox
			//
			this._nodeTextBox.DataPropertyName = "Text";
			this._nodeTextBox.EditEnabled = true;
			this._nodeTextBox.ParentColumn = null;
			//
			// SimpleExample
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.Controls.Add(this.button3);
			this.Controls.Add(this.button2);
			this.Controls.Add(this.button1);
			this.Controls.Add(this._tree2);
			this.Controls.Add(this._performanceTest);
			this.Controls.Add(this.label1);
			this.Controls.Add(this._fontSize);
			this.Controls.Add(this._autoRowHeight);
			this.Controls.Add(this._deleteNode);
			this.Controls.Add(this._addChild);
			this.Controls.Add(this._clear);
			this.Controls.Add(this._addRoot);
			this.Controls.Add(this._tree);
			this.Name = "SimpleExample";
			this.Size = new System.Drawing.Size(499, 387);
			((System.ComponentModel.ISupportInitialize)(this._fontSize)).EndInit();
			this.ResumeLayout(false);
			this.PerformLayout();

		}

		#endregion

		private Aga.Controls.Tree.TreeViewAdv _tree;
		private System.Windows.Forms.Button _addRoot;
		private System.Windows.Forms.Button _clear;
		private Aga.Controls.Tree.NodeControls.NodeCheckBox _nodeCheckBox;
		private System.Windows.Forms.Button _addChild;
		private System.Windows.Forms.Button _deleteNode;
		private Aga.Controls.Tree.NodeControls.NodeStateIcon _nodeStateIcon;
		private Aga.Controls.Tree.NodeControls.NodeTextBox _nodeTextBox;
		private System.Windows.Forms.Timer _timer;
		private System.Windows.Forms.CheckBox _autoRowHeight;
		private System.Windows.Forms.NumericUpDown _fontSize;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.CheckBox _performanceTest;
		private Aga.Controls.Tree.TreeViewAdv _tree2;
		private Aga.Controls.Tree.NodeControls.NodeTextBox nodeTextBox1;
		private System.Windows.Forms.Button button1;
		private System.Windows.Forms.Button button2;
		private System.Windows.Forms.Button button3;
	}
}


text:
<?php

namespace Basho\Riak\Command\DataType\Set;

use Basho\Riak\Command;
use Basho\Riak\CommandInterface;
use Basho\Riak\Location;

/**
 * Stores a write update to a set
 *
 * @author Christopher Mancini <cmancini at basho d0t com>
 */
class Store extends Command implements CommandInterface
{
    protected $method = 'POST';

    /**
     * @var array
     */
    protected $add_all = [];

    /**
     * @var array
     */
    protected $remove_all = [];

    /**
     * @var Command\DataType\Set\Response|null
     */
    protected $response = NULL;

    /**
     * @var Location|null
     */
    protected $location = NULL;

    public function __construct(Command\Builder\UpdateSet $builder)
    {
        parent::__construct($builder);

        $this->add_all = $builder->getAddAll();
        $this->remove_all = $builder->getRemoveAll();
        $this->bucket = $builder->getBucket();
        $this->location = $builder->getLocation();
    }

    public function getLocation()
    {
        return $this->location;
    }

    public function getEncodedData()
    {
        return json_encode($this->getData());
    }

    public function getData()
    {
        return ['add_all' => $this->add_all, 'remove_all' => $this->remove_all];
    }

    /**
     * @return Command\DataType\Set\Response
     */
    public function execute()
    {
        return parent::execute();
    }
}


text:
package io.badgeup.sponge.util;

import com.github.benmanes.caffeine.cache.AsyncLoadingCache;
import com.github.benmanes.caffeine.cache.Caffeine;
import io.badgeup.sponge.service.AchievementPersistenceService;
import io.badgeup.sponge.service.AwardPersistenceService;
import okhttp3.Response;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;

import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

public class ResourceCache {

    private Logger logger;
    private AsyncLoadingCache<String, Optional<JSONObject>> awardsCache;
    private AsyncLoadingCache<String, Optional<JSONObject>> achievementsCache;

    public ResourceCache(Logger logger) {
        this.logger = logger;

        this.awardsCache = Caffeine.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .buildAsync((key, executor) -> getAwardById(key, executor));

        this.achievementsCache = Caffeine.newBuilder()
                .maximumSize(100)
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .buildAsync((key, executor) -> getAchievementById(key, executor));
    }

    public CompletableFuture<Optional<JSONObject>> getAwardById(String awardId) {
        return this.awardsCache.get(awardId);
    }

    public CompletableFuture<Optional<JSONObject>> getAchievementById(String achievementId) {
        return this.achievementsCache.get(achievementId);
    }

    private CompletableFuture<Optional<JSONObject>> getAwardById(String key, Executor executor) {
        return CompletableFuture.supplyAsync(() -> {
            try (Response response = HttpUtils.get("/awards/" + key)) {
                if (response.code() != HttpUtils.STATUS_OK) {
                    this.logger.error("Got " + response.code() + " response getting the award \"" + key + "\"");

                    if (response.code() == HttpUtils.STATUS_NOT_FOUND) {
                        this.logger.info("Got 404 for award \"" + key + "\". Removing from storage");
                        AwardPersistenceService aps = Sponge.getServiceManager().provideUnchecked(AwardPersistenceService.class);
                        aps.remove(key);
                    }
                    return Optional.empty();
                }

                return Optional.of(HttpUtils.parseBody(response));
            } catch (IOException e) {
                e.printStackTrace();
                return Optional.empty();
            }
        }, executor);
    }

    private CompletableFuture<Optional<JSONObject>> getAchievementById(String key, Executor executor) {
        return CompletableFuture.supplyAsync(() -> {
            try (Response response = HttpUtils.get("/achievements/" + key)) {
                if (response.code() != HttpUtils.STATUS_OK) {
                    this.logger.error("Got " + response.code() + " response getting the achievement \"" + key + "\"");

                    if (response.code() == HttpUtils.STATUS_NOT_FOUND) {
                        this.logger.info("Got 404 for award \"" + key + "\". Removing from storage");
                        AchievementPersistenceService aps = Sponge.getServiceManager().provideUnchecked(AchievementPersistenceService.class);
                        aps.remove(key);
                    }
                    return Optional.empty();
                }

                return Optional.of(HttpUtils.parseBody(response));
            } catch (IOException e) {
                e.printStackTrace();
                return Optional.empty();
            }
        }, executor);
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RadioGroup
        android:id="@+id/module_hitokoto_activity_radiogroup"
        android:checkedButton="@+id/module_hitokoto_activity_type_random"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:divider="?android:attr/dividerHorizontal"
        android:showDividers="middle"
        android:paddingLeft="16dp"
        android:paddingRight="16dp">
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/module_hitokoto_activity_type_random"
            android:text="@string/module_hitokoto_activity_type_random"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/module_hitokoto_activity_type_anime"
            android:text="@string/module_hitokoto_activity_type_anime"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/module_hitokoto_activity_type_comic"
            android:text="@string/module_hitokoto_activity_type_comic"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/module_hitokoto_activity_type_game"
            android:text="@string/module_hitokoto_activity_type_game"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/module_hitokoto_activity_type_novel"
            android:text="@string/module_hitokoto_activity_type_novel"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/module_hitokoto_activity_type_myself"
            android:text="@string/module_hitokoto_activity_type_myself"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/module_hitokoto_activity_type_internet"
            android:text="@string/module_hitokoto_activity_type_internet"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/module_hitokoto_activity_type_other"
            android:text="@string/module_hitokoto_activity_type_other"
            android:textAppearance="?android:attr/textAppearanceMedium"/>
    </RadioGroup>
</LinearLayout>


text:
<!DOCTYPE html>
<html>
<head>
    <title>Soft wheel demo - p2.js physics engine</title>
    <script src="../build/p2.js"></script>
    <script src="../build/p2.renderer.js"></script>
    <link href="css/demo.css" rel="stylesheet"/>
    <meta name="description" content="Soft wheel demo.">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
    <script>

        var N = 15, // Number of capsules in a wheel
            r = 1, // Radius of the wheel
            thickness = 0.18, // Thickness of the wheel capsules
            GROUND = Math.pow(2, 1),
            CHASSIS = Math.pow(2, 2),
            WHEELS = Math.pow(2, 3);

        var app = new p2.WebGLRenderer(function(){

            // Create the world
            var world = new p2.World({
                gravity : [0,-5]
            });
            this.setWorld(world);

            // Create a contact material between ground and wheels
            // We need to do this to add some extra friction
            var groundMaterial = new p2.Material();
            var wheelMaterial = new p2.Material();
            var groundWheelContactMaterial = new p2.ContactMaterial(groundMaterial, wheelMaterial, {
                friction: 30
            });
            world.addContactMaterial(groundWheelContactMaterial);

            // Create wheels
            var wheelBodyA = createWheel(world, [-2.2 * r, 0], wheelMaterial);
            var wheelBodyB = createWheel(world, [2.2 * r, 0], wheelMaterial);

            // Create chassis
            var chassisBody = new p2.Body({ mass : 1, position:[-0.3 * r, 2.2 * r] });
            chassisBody.addShape(new p2.Capsule({ // Capsule below the chassis
                length: 1.8 * r,
                radius: r * 0.6,
                collisionGroup: CHASSIS,
                collisionMask: GROUND
            }), [r * 0.5,-r * 0.4], -0.1);
            chassisBody.addShape(new p2.Capsule({ // First capsule above the trunk
                length: 1.8 * r,
                radius: r * 0.1,
                collisionGroup: CHASSIS,
                collisionMask: GROUND
            }), [-r*0.4,r*0.6], Math.PI/2);
            chassisBody.addShape(new p2.Capsule({ // Second capsule above the trunk
                length: 1.8 * r,
                radius: r * 0.1,
                collisionGroup: CHASSIS,
                collisionMask: GROUND
            }), [-r*0.2,r*0.6], Math.PI/2);
            chassisBody.addShape(new p2.Capsule({ // Inclined capsule above the trunk
                length: 1.8 * r,
                radius: r * 0.1,
                collisionGroup: CHASSIS,
                collisionMask: GROUND
            }), [-r*1.4,r*1], Math.PI/7);
            chassisBody.addShape(new p2.Convex({ // Main chassis shape
                vertices: [
                    [3.5*r, -0.6*r],
                    [3.7*r, -0.4*r],
                    [3.6*r, 0.5*r],
                    [3.3*r, 0.6*r],
                    [-3.5*r, 0.6*r],
                    [-3.55*r, -0.1*r],
                    [-3.4*r, -0.6*r]
                ],
                width: 3.5*r*2,
                height: 0.6 * r * 2,
                collisionGroup: CHASSIS,
                collisionMask: GROUND
            }));
            chassisBody.addShape(new p2.Convex({ // Top "window"
                vertices: [
                    [r, -0.5 * r],
                    [0.3 * r, 0.5 * r],
                    [-r, 0.5 * r],
                    [-r * 1.1, -0.5 * r]
                ],
                collisionGroup: CHASSIS,
                collisionMask: GROUND
            }), [r,0.55 * r * 2], 0);
            world.addBody(chassisBody);

            // Constrain wheels to chassis: let them move vertically and rotate using a prismatic
            var c1 = new p2.PrismaticConstraint(chassisBody,wheelBodyA,{
                localAnchorA : [
                    wheelBodyA.position[0] - chassisBody.position[0],
                    wheelBodyA.position[1] - chassisBody.position[1]
                ],
                localAnchorB : [0,0],
                localAxisA : [0,1],
                disableRotationalLock : true
            });
            var c2 = new p2.PrismaticConstraint(chassisBody,wheelBodyB,{
                localAnchorA : [
                    wheelBodyB.position[0] - chassisBody.position[0],
                    wheelBodyB.position[1] - chassisBody.position[1]
                ],
                localAnchorB : [0,0],
                localAxisA : [0,1],
                disableRotationalLock : true
            });
            c1.setLimits(-0.5, 0.4); // Don't let the wheels move too much
            c2.setLimits(-0.5, 0.4);
            world.addConstraint(c1);
            world.addConstraint(c2);

            // Suspension: create "springs" that let the wheels move up and down a bit
            world.addConstraint(new p2.DistanceConstraint(wheelBodyA, chassisBody, {
                maxForce: 6
            }));
            world.addConstraint(new p2.DistanceConstraint(wheelBodyB, chassisBody, {
                maxForce: 6
            }));

            // Create ground plane
            groundBody = new p2.Body({
                position: [0, -r * 2]
            });
            groundBody.addShape(new p2.Plane({
                material: groundMaterial,
                collisionGroup: GROUND,
                collisionMask: WHEELS | CHASSIS | GROUND
            }));
            world.addBody(groundBody);

            // Add circle bumps along the ground
            for(var i=0; i<10; i++){
                circleBody = new p2.Body({
                    position:[6+6*i + Math.random()*3, -2] // Set initial position
                });
                circleBody.addShape(new p2.Circle({
                    radius: 5*Math.random(),
                    material: groundMaterial,
                    collisionGroup: GROUND,
                    collisionMask: WHEELS | GROUND | CHASSIS
                }));
                world.addBody(circleBody);
            }

            // Apply current engine torque after each step
            var left=0, right=0;
            world.on("postStep",function(evt){
                wheelBodyA.angularForce += (left - right) * 30;
                wheelBodyB.angularForce += (left - right) * 30;
            });
            this.on("keydown",function(evt){
                switch(evt.keyCode){
                    case 39:
                        right = 1;
                        break;
                    case 37:
                        left = 1;
                        break;
                }
            }).on("keyup",function(evt){
                switch(evt.keyCode){
                    case 39:
                        right = 0;
                        break;
                    case 37:
                        left = 0;
                        break;
                }
            });

            app.followBody = chassisBody; // Make camera follow

            this.frame(0, 0, 10, 10);
        });

        // Creates a soft wheel in the given world at the given position.
        // Returns the center body.
        function createWheel(world, position, material){

            // Create the center circle body
            var wheelBody = new p2.Body({
                mass: 1,
                position: position
            });
            wheelBody.addShape(new p2.Circle({
                radius: r/2,
                collisionGroup: GROUND,
                collisionMask: GROUND | WHEELS | CHASSIS
            }));
            world.addBody(wheelBody);

            // Create a chain of capsules around the center.
            var lastBody, firstBody;
            var linkLength = Math.sqrt(r*r + r*r - 2*r*r*Math.cos(2 * Math.PI / N));
            for(var i=0; i<N; i++){

                // Create a capsule body
                var angle = i / N * Math.PI * 2;
                var x = r * Math.cos(angle) + position[0];
                var y = r * Math.sin(angle) + position[1];
                var body = new p2.Body({
                    mass: 0.1,
                    position: [x,y],
                    angle: angle + Math.PI / 2
                });
                body.addShape(new p2.Capsule({
                    radius: thickness/2,
                    length: linkLength,
                    material: material,
                    collisionGroup: WHEELS,
                    collisionMask: GROUND
                }));
                world.addBody(body);

                // Constrain the capsule body to the center body.
                // A prismatic constraint lets it move radially from the center body along one axis
                var prismatic = new p2.PrismaticConstraint(wheelBody, body, {
                    localAnchorA :  [0, 0],
                    localAnchorB :  [0, 0],
                    localAxisA :    [Math.cos(angle), Math.sin(angle)],
                    disableRotationalLock: true, // Let the capsule rotate around its own axis
                    collideConnected: true
                });
                world.addConstraint(prismatic);

                // Make a "spring" that keeps the body from the center body at a given distance with some flexing
                world.addConstraint(new p2.DistanceConstraint(wheelBody, body, {
                    maxForce: 4, // Allow flexing
                    collideConnected: true
                }));

                if(lastBody){
                    // Constrain the capsule to the previous one.
                    var c = new p2.RevoluteConstraint(body, lastBody, {
                        localPivotA: [-linkLength/2, 0],
                        localPivotB: [linkLength/2, 0],
                        collideConnected: false
                    });
                    world.addConstraint(c);
                } else {
                    firstBody = body;
                }

                lastBody = body;
            }

            // Close the capsule circle
            world.addConstraint(new p2.RevoluteConstraint(firstBody, lastBody, {
                localPivotA: [-linkLength/2, 0],
                localPivotB: [linkLength/2, 0],
                collideConnected: false
            }));

            return wheelBody;
        }

    </script>
</body>
</html>


text:
using namespace std;

//the program can be in one of three states.
enum mode{LEARNING, ACTIVE, UNREADY, TRAINING};

class CController
{

private:

  //the neural network
  CNeuralNet*     m_pNet;

  //this class holds all the training data
  CData*          m_pData;

  //the user mouse gesture paths - raw and smoothed
  vector<POINTS> m_vecPath;
  vector<POINTS> m_vecSmoothPath;

  //the smoothed path transformed into vectors
  vector<double> m_vecVectors;

  //true if user is gesturing
  bool    m_bDrawing;

  //the highest output the net produces. This is the most
  //likely candidate for a matched gesture.
  double  m_dHighestOutput;

  //the best match for a gesture based on m_dHighestOutput
  int     m_iBestMatch;

  //if the network has found a pattern this is the match
  int     m_iMatch;

  //the raw mouse data is smoothed to this number of points
  int     m_iNumSmoothPoints;

  //the number of patterns in the database;
  int     m_iNumValidPatterns;

  //the current state of the program
  mode    m_Mode;

  //local copy of the application handle
  HWND    m_hwnd;

  //clears the mouse data vectors
  void    Clear();

  //given a series of points whis method creates a path of
  //normalized vectors
  void    CreateVectors();

  //preprocesses the mouse data into a fixed number of points
  bool    Smooth();

  //tests for a match with a prelearnt gesture
  bool    TestForMatch();

  //dialog box procedure. A dialog box is spawned when the user
  //enters a new gesture.
  static BOOL CALLBACK DialogProc(HWND   hwnd,
                                  UINT   msg,
                                  WPARAM wParam,
                                  LPARAM lParam);

  //this temporarily holds any newly created pattern names
  static string m_sPatternName;

public:

  CController(HWND hwnd);

  ~CController();

  //call this to train the network using backprop with the current data
  //set
  bool TrainNetwork();

  //renders the mouse gestures and relevant data such as the number
  //of training epochs and training error
  void Render(HDC &surface, int cxClient, int cyClient);

  //returns whether or not the mouse is currently drawing
  bool Drawing()const{return m_bDrawing;}

  //this is called whenever the user depresses or releases the right
  //mouse button.
  //If val is true then the right mouse button has been depressed so all
  //mouse data is cleared ready for the next gesture. If val is false a
  //gesture has just been completed. The gesture is then either added to
  //the current data set or it is tested to see if it matches an existing
  //pattern.
  //The hInstance is required so a dialog box can be created as a child
  //window of the main app instance. The dialog box is used to grab the
  //name of any user defined gesture
  bool Drawing(bool val, HINSTANCE hInstance);

  void LearningMode();

  //call this to add a point to the mouse path
  void AddPoint(POINTS p)
  {
    m_vecPath.push_back(p);
  }
};

#endif


text:
<code_scheme name="Default" version="173">
  <codeStyleSettings language="JAVA">
    <option name="KEEP_LINE_BREAKS" value="false" />
    <option name="ALIGN_MULTILINE_PARAMETERS" value="false" />
    <option name="ALIGN_MULTILINE_PARAMETERS_IN_CALLS" value="true" />
    <option name="ALIGN_MULTILINE_EXTENDS_LIST" value="true" />
    <option name="SPACE_BEFORE_IF_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_WHILE_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_FOR_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_TRY_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_CATCH_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_SWITCH_PARENTHESES" value="false" />
    <option name="SPACE_BEFORE_SYNCHRONIZED_PARENTHESES" value="false" />
    <option name="KEEP_SIMPLE_BLOCKS_IN_ONE_LINE" value="true" />
    <option name="KEEP_SIMPLE_METHODS_IN_ONE_LINE" value="true" />
    <option name="KEEP_SIMPLE_LAMBDAS_IN_ONE_LINE" value="true" />
    <option name="KEEP_SIMPLE_CLASSES_IN_ONE_LINE" value="true" />
    <option name="IF_BRACE_FORCE" value="3" />
    <option name="DOWHILE_BRACE_FORCE" value="3" />
    <option name="WHILE_BRACE_FORCE" value="3" />
    <option name="FOR_BRACE_FORCE" value="3" />
  </codeStyleSettings>
</code_scheme>


text:
def longest_string(list_of_words)
  return nil if list_of_words == []
  longest = list_of_words[0]
  for string in list_of_words
  	if string.length > longest.length
  		longest = string
  	end
  end
  return longest
end


text:
package org.apache.camel.component.google.calendar;

import java.util.Map;

import com.google.api.client.googleapis.services.AbstractGoogleClientRequest;

import org.apache.camel.Processor;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.component.google.calendar.internal.GoogleCalendarApiName;
import org.apache.camel.util.IntrospectionSupport;
import org.apache.camel.util.component.AbstractApiConsumer;

/**
 * The GoogleCalendar consumer.
 */
public class GoogleCalendarConsumer extends AbstractApiConsumer<GoogleCalendarApiName, GoogleCalendarConfiguration> {

    public GoogleCalendarConsumer(GoogleCalendarEndpoint endpoint, Processor processor) {
        super(endpoint, processor);
    }

    @Override
    protected Object doInvokeMethod(Map<String, Object> properties) throws RuntimeCamelException {
        AbstractGoogleClientRequest request = (AbstractGoogleClientRequest) super.doInvokeMethod(properties);
        try {
            setProperty(properties, request, "q");
            setProperty(properties, request, "maxResults");
            setProperty(properties, request, "pageToken");
            return request.execute();
        } catch (Exception e) {
            throw new RuntimeCamelException(e);
        }
    }

    private void setProperty(Map<String, Object> properties, AbstractGoogleClientRequest request, String key) throws Exception {
        if (properties.containsKey(key)) {
            IntrospectionSupport.setProperty(getEndpoint().getCamelContext().getTypeConverter(), request, key, properties.get(key));
        }
    }
}


text:
var gulp       = require("gulp");
var istanbul   = require("gulp-istanbul");
var mocha      = require("gulp-mocha");
var plumber    = require("gulp-plumber");
var jshint     = require("gulp-jshint");
var uglify     = require("gulp-uglify");
var jscs       = require("gulp-jscs");
var coveralls  = require("gulp-coveralls");
var rename     = require("gulp-rename");
var options    = require("yargs").argv;

var pkg = require("./package");

/**
 */

var paths = {
  testFiles  : ["test/**/*-test.js"],
  appFiles   : ["sift.js"],
  allFiles   : ["test/**/*-test.js", "sift.js"]
};

/**
 */

var mochaOptions = {
  bail     : options.bail     !== 'false',
  reporter : options.reporter || 'dot',
  grep     : options.grep   || options.only,
  timeout  : 500
}

/**
 */

gulp.task("test-coverage", function (complete) {
  gulp.
  src(paths.appFiles).
  pipe(istanbul()).
  pipe(istanbul.hookRequire()).
  on("finish", function () {
    gulp.
    src(paths.testFiles).
    pipe(plumber()).
    pipe(mocha(mochaOptions)).
    pipe(istanbul.writeReports({
        reporters: ["text","text-summary", "lcov"]
    })).
    on("end", complete);
  });
});

/**
 */

gulp.task("test-coveralls", ["test-coverage"], function () {
  return gulp.
  src("coverage/**/lcov.info").
  pipe(coveralls());
});
/**
 */

gulp.task("minify", function() {
  return gulp.
  src("./" + pkg.name + ".js").
  pipe(uglify()).
  pipe(rename(function(path) {
      path.basename += ".min";
  })).
  pipe(gulp.dest("./"));
});

/**
 */

gulp.task("lint", function() {
  return gulp.run(["jshint", "jscs"]);
});

/**
 */

gulp.task("jscs", function() {
  return gulp.
  src(paths.allFiles).
  pipe(jscs({
    "preset": "google",
    "requireParenthesesAroundIIFE": true,
    "maximumLineLength": 200,
    "validateLineBreaks": "LF",
    "validateIndentation": 2,
    "validateQuoteMarks": "\"",

    "disallowKeywords": ["with"],
    "disallowSpacesInsideObjectBrackets": null,
    "disallowImplicitTypeConversion": ["string"],
    "requireCurlyBraces": [],

    "safeContextKeyword": "self"
  }));
});

/**
 */

gulp.task("jshint", function() {
    return gulp.
    src(paths.allFiles).
    pipe(jshint({
      es3: true,
      evil: true
    })).
    pipe(jshint.reporter('default'));
});

/**
 */

gulp.task("test", function (complete) {
  gulp.
  src(paths.testFiles, { read: false }).
  pipe(plumber()).
  pipe(mocha(mochaOptions)).
  on("error", complete).
  on("end", complete);
});

var iofwatch = process.argv.indexOf("watch");

/**
 * runs previous tasks (1 or more)
 */

gulp.task("watch", function () {
  gulp.watch(paths.allFiles, process.argv.slice(2, iofwatch));
});

/**
 */

gulp.task("default", function () {
  return gulp.run("test-coverage");
});

/**
 */

gulp.doneCallback = function (err) {

  // a bit hacky, but fixes issue with testing where process
  // doesn't exist process. Also fixes case where timeout / interval are set (CC)
  if (!~iofwatch) process.exit(err ? 1 : 0);
};