text:
/*
 * IQImageVerification.java
 *
 * Created on December 26, 2006, 1:44 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package scripteditor;
import javax.swing.*;
import java.awt.*;
import java.text.DecimalFormat;
import java.util.Random;

/**
 *
 * @author Administrator
 */
public class IQImageVerification {
    int mMode;
    JLabel mName;
    JLabel mNameLabel;
    boolean Running = true;
    boolean mPaused = false;
    IGradeImageVerification mGrade;
    static SessionInfo mSessionInfo;
    ImageScaler mScaler;
    boolean italic=false;//Added by preethy on 03-03-2012
    public IQImageVerification(SessionInfo session,boolean fontItalic){
        mSessionInfo = session;
        mScaler = new ImageScaler();
        italic=fontItalic;
        ImageVerification();
        mScaler = null;

    }

    private void ImageVerification(){

        if(mSessionInfo.mTaxa.length < 2){
            JOptionPane.showMessageDialog(mSessionInfo.mParentForm, "There must be more than one taxa selected for Image Verification.");
            return;
        }

//        //  Clear point-accumulating variables if not in testmode
//        if (!mSessionInfo.mIsTest) {
//            mGrade = new GradeImageVerificationQuiz(new QuizResultClass(4));
//        }
//        else{
//            mGrade = new GradeImageVerificationQuiz(new QuizResultClass(7));
//
//        }

        if (mSessionInfo.mIsTest)
            mGrade = GradeImageVerificationFactory.GetQuizGradeInstance(GradeImageVerificationFactory.ImageVerificationTest, new QuizResultClass(7, mSessionInfo.mFileNames.length, SessionInfo.SpellingValue, mSessionInfo.mDelay),italic);
        else
            mGrade = GradeImageVerificationFactory.GetQuizGradeInstance(GradeImageVerificationFactory.ImageVerificationQuiz, new QuizResultClass(4, mSessionInfo.mFileNames.length, SessionInfo.SpellingValue, mSessionInfo.mDelay),italic);

        //Random Pic for taxa!!
        Random generator = new Random();
        String[] myTwoAnswers = new String[2];
        int seed = mSessionInfo.mTaxa.length;
        Image image =  ImageScaler.VerifyImageSize(mSessionInfo.mImageCollection.getCurrentImage().getImage(), mSessionInfo.mDisplayLabel.getWidth(), mSessionInfo.mDisplayLabel.getHeight(), mSessionInfo.mDisplayLabel);
        String randomName = getParsedName(mSessionInfo.mTaxa[generator.nextInt(seed)]); // must be random to compare with image;
        String realName = getParsedName(mSessionInfo.mImageCollection.getImageName());

        while(realName.compareTo(randomName) == 0){
            randomName = getParsedName(mSessionInfo.mTaxa[generator.nextInt(seed)]);
        }
        myTwoAnswers[0] = randomName;
        myTwoAnswers[1] = realName;
        randomName = myTwoAnswers[generator.nextInt(2)];
        QuizResponseDialog dlgResponse = new QuizResponseDialog(mSessionInfo.mTaxaLevel, true);
        String answer; // response from user
        dlgResponse.setLocationRelativeTo(mSessionInfo.mParentForm);
        AddNameLabel();

        mNameLabel.setVisible(false);
        ImageIcon tempIcon = new ImageIcon(image);
        for(int i = 0; i < mSessionInfo.mFileNames.length; i++){
            ////  Use the mNameLabel as the fixation point
            /// Never set mSessionInfo.mDisplayLabel to null. Always have image loaded.
            /// Just set visable or not

             mGrade.getGradeInstance().BeginQuestion();
             while(true){
                answer = null;
                dlgResponse.forCloseResponse();
                mNameLabel.setText(randomName);
                ShowFixation();
                mSessionInfo.mDisplayLabel.setIcon(tempIcon);
                JCDelay(mSessionInfo.mDelay);
                mSessionInfo.mDisplayLabel.setIcon(null);
                mNameLabel.setVisible(true);
                JCDelay(1); // name shown for only 1 second!
                mNameLabel.setVisible(false);

                if(!Running){
                    break;
                }
                dlgResponse.setVisible(true);
                if(!dlgResponse.mRunning){
                    Running = false;
                    break;
                }
                answer = dlgResponse.getResponse();
                 if(answer == null )
                {
                    dlgResponse.mRunning = true;
                }
                else{
                dlgResponse.resetResponse();
                if(mGrade.Grade(answer, realName, randomName, mSessionInfo.mImageCollection.getImageName()) == true){
                        break;  //Don't repeat.
                }
             }
            }

            if (!Running) {
                mGrade.getGradeInstance().QuitEarly();
                break;
            }

            // Update progress class.

            //
            mSessionInfo.mImageCollection.MoveNext();
            image =  ImageScaler.VerifyImageSize(mSessionInfo.mImageCollection.getCurrentImage().getImage(), mSessionInfo.mDisplayLabel.getWidth(), mSessionInfo.mDisplayLabel.getHeight(), mSessionInfo.mDisplayLabel);
            tempIcon = new ImageIcon(image);
            realName = getParsedName(mSessionInfo.mImageCollection.getImageName());
            randomName = getParsedName(mSessionInfo.mTaxa[generator.nextInt(seed)]);

            while(realName.compareTo(randomName) == 0){
                randomName = getParsedName(mSessionInfo.mTaxa[generator.nextInt(seed)]);
            }
            myTwoAnswers[0] = randomName;
            myTwoAnswers[1] = realName;
            randomName = myTwoAnswers[generator.nextInt(2)];
        }
        mSessionInfo.mProgress.StoreResult(mGrade.getGradeInstance().getQuizResult(), String.valueOf(DecimalFormat.getPercentInstance().format(mGrade.getGradeInstance().NumberOfRightAnswers()/(double)mSessionInfo.mImageCollection.NumberOfImages())),italic); // Adds the result to the progress
    }

//    public void SaveResult() {
//        if(mSessionInfo.mIsTest){
//            Results rs = new Results("Test", "Image Verification", mSessionInfo.mTaxaLevel, mSessionInfo.mTaxa, mSessionInfo.mUserName, String.valueOf(mRightAnswers) + "/" + String.valueOf(mTotal), mDelay, mSessionInfo.mFixationTime);
//            rs.writeTestResults();
//        }else{
//            Results rs = new Results("Quiz", "Image Verification", mSessionInfo.mTaxaLevel, mSessionInfo.mTaxa, mSessionInfo.mUserName, mFirst, mSecond, mThird, m4orMore, mSkipped);
//            rs.writeQuizResults();
//        }
//
//    }

     public void SaveResult(){
        ScriptResult rs;
        if(mSessionInfo.mIsTest){
          rs =  new ScriptResult("Test-Image Verification", mSessionInfo.mTaxaLevel, mSessionInfo.mTaxa, mSessionInfo.mUserName,
                    mGrade.getGradeInstance().FinalGrade(),
                    "n/a", "n/a", mGrade.getGradeInstance().TotalQuestions(), mSessionInfo.mImageCollection.NumberOfImages(), null);

        } else{
             rs =  new ScriptResult("Quiz-Image Verification", mSessionInfo.mTaxaLevel, mSessionInfo.mTaxa, mSessionInfo.mUserName,
                    mGrade.getGradeInstance().FinalGrade(),
                    "n/a", "n/a",  mGrade.getGradeInstance().TotalQuestions(), mSessionInfo.mImageCollection.NumberOfImages(), null);
        }
        rs.writeResults(false);
    }

    private void AddNameLabel(){
        mNameLabel = new JLabel();
        mNameLabel.setHorizontalAlignment(JLabel.CENTER);

        if(italic){
           mNameLabel.setFont(new Font("Tahoma", Font.ITALIC, 30));
        }else{
        mNameLabel.setFont(new Font("Tahoma", Font.BOLD, 30));
        }
        mNameLabel.setSize(mSessionInfo.mParentForm.getWidth(), 6 * 30 / 5);
        mNameLabel.setOpaque(true);
        mNameLabel.setLocation(0, (int)mSessionInfo.mDisplayLabel.getSize().getHeight()/2);
        mSessionInfo.mDisplayLabel.add(mNameLabel);
    }

    private String getParsedName(String temp){
        int index = 0;

        if(mSessionInfo.mTaxaLevel.compareTo("Family") != 0){
            index = temp.indexOf(' ');
            temp = temp.substring(index + 1, temp.length());
        }
        return temp;
    }

    private void JCDelay(double de) {
        de = de * 1000;
        double startTime = System.currentTimeMillis();
        double stopTime = startTime + de;
        while(System.currentTimeMillis() < stopTime && Running){
            try{
                Thread.sleep(5);
            } catch(InterruptedException e){}
        }
    }

    private void ShowFixation(){
        mSessionInfo.mDisplayLabel.setText("+");
        JCDelay(mSessionInfo.mFixationTime);
        mSessionInfo.mDisplayLabel.setText("");
    }

    public static int ShowTryAgainDialog(){
        dlgTryAgain dlg = new dlgTryAgain();
        dlg.setLocationRelativeTo(mSessionInfo.mParentForm);
        dlg.setVisible(true);
        return dlg.getResponse();
    }
     //Added by preethy on 19-01-2012
     public static int ShowAgainDialog(){
        dlgTryAgain2 tf = new dlgTryAgain2();
        tf.setLocationRelativeTo(mSessionInfo.mParentForm);
        tf.setVisible(true);
        return tf.getResponse();
    }
     /***/

}


text:
package water;

import water.api.schemas3.KeyV3;
import water.fvec.*;
import water.util.Log;

/** Iced, with a Key.  Support for DKV removal. */
public abstract class Keyed<T extends Keyed> extends Iced<T> {
  /** Key mapping a Value which holds this object; may be null  */
  public Key<T> _key;
  public Keyed() { _key = null; } // NOTE: every Keyed that can come out of the REST API has to have a no-arg constructor.
  public Keyed( Key<T> key ) { _key = key; }

  public Key<T> getKey() {
    return _key;
  }

  // ---
  /** Remove this Keyed object, and all subparts; blocking. */
  public final void remove() {
    remove(true);
  }

  /** Remove this Keyed object, including all subparts if cascade = true; blocking. */
  public final void remove(boolean cascade) { remove(new Futures(), cascade).blockForPending(); }
  /** Remove this Keyed object, and all subparts.  */
  public final Futures remove( Futures fs ) {
    return remove(fs, true);
  }
  /** Remove this Keyed object, including all subparts if cascade = true.  */
  public final Futures remove( Futures fs, boolean cascade ) {
    fs = remove_self_key_impl(fs);
    return remove_impl(fs, cascade);
  }

  /**
   * @deprecated Better override {@link #remove_impl(Futures, boolean)} instead
   */
  @Deprecated
  protected Futures remove_impl(Futures fs) { return fs; }

  /** Override to remove subparts, but not self, of composite Keyed objects.
   *  Examples include {@link Vec} (removing associated {@link Chunk} keys)
   *  and {@link Frame} (removing associated {@link Vec} keys.) */
  protected Futures remove_impl(Futures fs, boolean cascade) { return remove_impl(fs); }

  /** Remove my own key from DKV.  */
  protected Futures remove_self_key_impl(Futures fs) {
    if (_key != null)
      DKV.remove(_key,fs);
    return fs;
  }

  /** Removes the Keyed object associated to the key, and all subparts; blocking. */
  public static void remove( Key k ) {
    if (k==null) return;
    Value val = DKV.get(k);
    if (val==null) return;
    ((Keyed)val.get()).remove();
  }
  public static void removeQuietly(Key k) {
    try {
      remove(k);
    } catch (Exception e) {
      String reason = e.getMessage() != null ? " Reason: " + e.getMessage() : "";
      Log.warn("Failed to correctly release memory associated with key=" + k + "." + reason);
      Log.debug("Failed to remove key " + k, e);
    }
  }
  /** Remove the Keyed object associated to the key, and all subparts. */
  public static Futures remove( Key k, Futures fs, boolean cascade) {
    if (k==null) return fs;
    Value val = DKV.get(k);
    if (val==null) return fs;
    return ((Keyed)val.get()).remove(fs, cascade);
  }

  // ---
  /** Write this Keyed object, and all nested Keys. */
  public AutoBuffer writeAll(AutoBuffer ab) { return writeAll_impl(ab.put(this)); }
  // Override this to write out subparts
  protected AutoBuffer writeAll_impl(AutoBuffer ab) { return ab; }

  /** Read a Keyed object, and all nested Keys.  Nested Keys are injected into the K/V store
   *  overwriting what was there before.  */
  public static Keyed readAll(AutoBuffer ab) {
    Futures fs = new Futures();
    Keyed k = ab.getKey(fs);
    fs.blockForPending();       // Settle out all internal Key puts
    return k;
  }
  // Override this to read in subparts
  protected Keyed readAll_impl(AutoBuffer ab, Futures fs) { return this; }

  /** High-quality 64-bit checksum of the <i>content</i> of the object.  Similar
   *  to hashcode(), but a long to reduce the chance of hash clashes.  For
   *  composite objects this should be defined using the subcomponents' checksums
   *  (or hashcodes if not available).  If two Keyed objects have the same
   *  checksum() there should be a 1 - 1/2^64 chance that they are the same
   *  object by value.
   */
  protected long checksum_impl() { throw H2O.fail("Checksum not implemented by class "+this.getClass()); }
  protected long checksum_impl(boolean noCache) { return checksum_impl(); }
  private long _checksum;
  // Efficiently fetch the checksum, setting on first access
  public final long checksum() {
    if( _checksum!=0 ) return _checksum;
    long x = checksum_impl(false);
    if( x==0 ) x=1;
    return (_checksum=x);
  }
  public final long checksum(boolean noCache) {
    if (noCache)
      return checksum_impl(noCache);
    return checksum();
  }

  // TODO: REMOVE THIS!  It's not necessary; we can do it with reflection.
  public Class<? extends KeyV3> makeSchema() { throw H2O.fail("Override in subclasses which can be the result of a Job"); }
}

redpajama_set_name: RedPajamaGithub


text:
import unittest

from .extended_attribute import ExtendedAttribute
from .extended_attribute import ExtendedAttributes
from .idl_type import IdlTypeFactory

class IdlTypesTest(unittest.TestCase):
    def test_property(self):
        factory = IdlTypeFactory()

        self.assertTrue(factory.simple_type('any').is_any)
        self.assertTrue(factory.simple_type('boolean').is_boolean)
        self.assertTrue(factory.simple_type('object').is_object)
        self.assertTrue(factory.simple_type('void').is_void)
        self.assertTrue(factory.simple_type('symbol').is_symbol)

        for x in ('byte', 'octet', 'short', 'unsigned short', 'long',
                  'unsigned long', 'long long', 'unsigned long long'):
            self.assertTrue(factory.simple_type(x).is_numeric)
            self.assertTrue(factory.simple_type(x).is_integer)
        for x in ('float', 'unrestricted float', 'double',
                  'unrestricted double'):
            self.assertTrue(factory.simple_type(x).is_numeric)
            self.assertFalse(factory.simple_type(x).is_integer)
        for x in ('DOMString', 'ByteString', 'USVString'):
            self.assertTrue(factory.simple_type(x).is_string)

        short_type = factory.simple_type('short')
        string_type = factory.simple_type('DOMString')
        self.assertTrue(factory.promise_type(short_type).is_promise)
        self.assertTrue(factory.record_type(short_type, string_type).is_record)
        self.assertTrue(factory.sequence_type(short_type).is_sequence)
        self.assertTrue(factory.frozen_array_type(short_type).is_frozen_array)
        self.assertTrue(factory.union_type([short_type, string_type]).is_union)
        self.assertTrue(factory.nullable_type(short_type).is_nullable)
        self.assertTrue(factory.variadic_type(short_type).is_variadic)

        self.assertFalse(factory.simple_type('long').is_string)
        self.assertFalse(factory.simple_type('DOMString').is_object)
        self.assertFalse(factory.simple_type('symbol').is_string)

        self.assertFalse(factory.nullable_type(short_type).is_numeric)
        self.assertFalse(factory.variadic_type(short_type).is_numeric)
        self.assertTrue(
            factory.nullable_type(short_type).inner_type.is_numeric)
        self.assertTrue(
            factory.variadic_type(short_type).element_type.is_numeric)

        ext_attrs = ExtendedAttributes([ExtendedAttribute('Clamp')])
        annotated_type = factory.simple_type(
            'short', extended_attributes=ext_attrs)
        self.assertTrue(annotated_type.extended_attributes)
        self.assertTrue(annotated_type.is_numeric)

        optional_type = factory.simple_type('DOMString', is_optional=True)
        self.assertTrue(optional_type.is_optional)
        self.assertTrue(optional_type.is_string)

        annotated_optional = factory.simple_type(
            'long', is_optional=True, extended_attributes=ext_attrs)
        self.assertTrue(annotated_optional.extended_attributes)
        self.assertTrue(annotated_optional.is_optional)
        self.assertTrue(annotated_optional.is_numeric)

    def test_type_name(self):
        factory = IdlTypeFactory()

        type_names = {
            'byte': 'Byte',
            'unsigned long long': 'UnsignedLongLong',
            'unrestricted double': 'UnrestrictedDouble',
            'DOMString': 'String',
            'ByteString': 'ByteString',
            'USVString': 'USVString',
            'any': 'Any',
            'boolean': 'Boolean',
            'object': 'Object',
            'void': 'Void',
            'symbol': 'Symbol',
        }
        for name, expect in type_names.items():
            self.assertEqual(expect, factory.simple_type(name).type_name)

        short_type = factory.simple_type('short')
        string_type = factory.simple_type('DOMString')
        self.assertEqual(
            'ShortOrString',
            factory.union_type([short_type, string_type]).type_name)
        self.assertEqual(
            'StringOrShort',
            factory.union_type([string_type, short_type]).type_name)
        self.assertEqual('ShortPromise',
                         factory.promise_type(short_type).type_name)
        self.assertEqual(
            'ShortStringRecord',
            factory.record_type(short_type, string_type).type_name)
        self.assertEqual('ShortSequence',
                         factory.sequence_type(short_type).type_name)
        self.assertEqual('ShortArray',
                         factory.frozen_array_type(short_type).type_name)
        self.assertEqual('ShortOrNull',
                         factory.nullable_type(short_type).type_name)

        ext_attrs = ExtendedAttributes(
            [ExtendedAttribute('TreatNullAs', 'EmptyString')])
        self.assertEqual(
            'StringTreatNullAs',
            factory.simple_type('DOMString',
                                extended_attributes=ext_attrs).type_name)

    def test_union_types(self):
        factory = IdlTypeFactory()

        # Test target: ((unrestricted double or object)? or
        #               [TreatNullAs=EmptyString] DOMString)
        treat_null_as = ExtendedAttribute('TreatNullAs', 'EmptyString')
        annotated_string = factory.simple_type(
            'DOMString',
            extended_attributes=ExtendedAttributes([treat_null_as]))
        obj = factory.simple_type('object')
        unrestricted_double = factory.simple_type('unrestricted double')
        union = factory.union_type(
            [factory.union_type([unrestricted_double, obj]), annotated_string])

        self.assertEqual(len(union.member_types), 2)
        # TODO(peria): Enable following tests.
        # self.assertEqual(len(union.flattened_member_types), 3)
        # self.assertTrue(union.does_include_nullable_type)

    # TODO(peria): Implement tests for ReferenceType, DefinitionType, and
    # TypeAlias


text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration,
    Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your need!
 */
class Version20121203141658 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql("ALTER TABLE denuncia CHANGE telefonos_denunciante telefono_denunciante VARCHAR(100) NOT NULL");
    }

    public function down(Schema $schema)
    {
        // this down() migration is autogenerated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != "mysql");

        $this->addSql("ALTER TABLE denuncia CHANGE telefono_denunciante telefonos_denunciante VARCHAR(100) NOT NULL");
    }
}


text:
var spawn = require('child_process').spawn;
var EventEmitter = require('events').EventEmitter;
module.exports = function(cmd, args) {
   var self = new EventEmitter;
   var child = spawn(cmd, args);
   var pauserefcount = 0;
   self.pause = function() {
       pauserefcount++;
       if (pauserefcount > 1)
          return;
       child.kill('SIGTSTP');
       self.paused = true;
   };
   self.resume = function() {
       pauserefcount--;
       if (pauserefcount>0)
         return;
       if (pauserefcount<0)
         throw new Error('resume() is called without calling pause()');
       child.kill('SIGCONT');
       self.paused = false;
   }
   child.stdout.on('data', function(data) {
       self.emit('data', data); // self.emit.bind(self, 'data') ???
   });
   child.on('exit', function(code, signal) {
       if (code === 0)
           self.emit('end');
       //else
       //    console.log(code, signal);
   });
   self.write = function(data) {
       return child.stdin.write(data);
   }
   child.stdin.on('drain', function() {
       self.emit('drain');
   });
   self.end = function() {
       child.kill('SIGKILL');
   };
   self.pipe = function(dest, opts) {
       dest.on('drain', function() {
           if (self.paused)
               self.resume();
       });
       self.on('data', function(data) {
           var buffered = !dest.write(data);
           if (buffered)
               self.pause();
       });

       if (!opts || (opts && opts.end === true) || (opts && typeof opts.end === 'undefined'))
           self.on('end', function() {
               dest.end();
           });

       self.emit('pipe');
       return dest;
   };
   return self;
}


text:
package com.github.dreambrother.hackernews.service;

import com.github.dreambrother.hackernews.client.HackernewsClient;
import com.github.dreambrother.hackernews.dao.PublishedItemsDao;
import com.github.dreambrother.hackernews.dto.HackernewsItem;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Arrays;
import java.util.List;

import static com.github.dreambrother.hackernews.fixture.HackernewsItems.twoItems;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

public class HackernewsServiceImplTest {

    private HackernewsServiceImpl sut = new HackernewsServiceImpl();

    @Mock
    private HackernewsClient hackernewsClientMock;
    @Mock
    private PublishedItemsDao publishedItemsDaoMock;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);
        sut.setMinPopularity(50);
        sut.setHackernewsClient(hackernewsClientMock);
        sut.setPublishedItemsDao(publishedItemsDaoMock);
    }

    @Test
    public void shouldGetMostPopularNews() {
        when(hackernewsClientMock.fetchNewsIds()).thenReturn(Arrays.asList(1l, 2l, 3l));
        when(publishedItemsDaoMock.getLastPublishedIds()).thenReturn(Arrays.asList(1l));
        when(hackernewsClientMock.fetchNewsItem(2l)).thenReturn(twoItems().get(0));
        when(hackernewsClientMock.fetchNewsItem(3l)).thenReturn(twoItems().get(1));

        List<HackernewsItem> mostPopularNews = sut.getMostPopularNonPublishedNews();

        assertEquals(Arrays.asList(twoItems().get(0)), mostPopularNews);
    }
}


text:
The following list contains items with code blocks:

* List Item A

        This is a verbatim line
        and another one

        all of these should become
        part of the

        same verbatim block

    only these lines here

        should interrupt
        the

        verbatims blocks

* another List Items

and something completely different here


text:
export * from './notifications.component';
export * from './notifications.service';


text:
import {Component, NgModule, ViewChild,ViewContainerRef, ViewEncapsulation} from '@angular/core';
import {FormBuilder, FormGroup, Validators, FormControl} from '@angular/forms';
import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from "@angular/forms/src/directives";
//import {FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES} from '@angular/forms';
import {Routes, RouterModule, Router} from '@angular/router';
import {ModalModule} from "ng2-modal";
import {Headers,Http} from "@angular/http";
import {AppCommonservices} from  '../../services/app.commonservices'
import {CookieService} from 'angular2-cookie/core';

@Component({
    selector: 'my-app',
    //template: '<h1>Welcome to my First Angular 2 App </h1>'
    templateUrl:'app/pages/customercreditcard/home.html',
    providers: [AppCommonservices]
    //directives: [FORM_DIRECTIVES, REACTIVE_FORM_DIRECTIVES]
})
export class AppCustomercreditcard {
    // /@ViewChild(Modal) modal;
    customercreditform: FormGroup;
    myModal :ModalModule;
    data:any;

    http:Http;
    items:any;
    getExpyears:any;

    expMonths:any;
    getusastates:any;
    serverUrl:any;
    private customerInfo:CookieService;
    commonservices:AppCommonservices;
    customerinfo:any;
    private router: Router;
    package_image:any;
    details1:any;
    orderbyquery:any;
    orderbytype:any;

    constructor(fb: FormBuilder , http:Http ,commonservices: AppCommonservices,customerInfo:CookieService,router: Router ) {

        this.items = commonservices.getItems();
        this.getExpyears = commonservices.getExpyears();
        this.expMonths = commonservices.getMonths();
        //this.getusastates = commonservices.getusastates();
        this.customerinfo=customerInfo.getObject('customerInfo');
        console.log(this.customerinfo)
        this.customerInfo=customerInfo;
        this.http=http;
        this.router = router;
        this.serverUrl = this.items[0].serverUrl;

        this.http.get(this.serverUrl+'getusastates')
            .subscribe(data => {
                console.log(data);
               this.getusastates=data.json();
                console.log(this.getusastates);

            }, error => {
                console.log("Oooops!");
            });
        var parts = location.hostname.split('.');
        var sndleveldomain = parts[0];

        let ids = {username: sndleveldomain};
        this.http.post(this.serverUrl + 'editdealerbyusername', ids)
            .subscribe(data => {
                this.details1 = data.json()[0];
                console.log(this.details1);
                if(this.details1.filename) {
                    this.package_image = "http://probidbackend.influxiq.com/uploadedfiles/sharelinks/" + this.details1.filename;
                }
                else {
                    this.package_image ="images/re_logo2.png";
                }

            }, error => {
                console.log("Oooops!");
            });
console.log(this.customerinfo.username);
        this.customercreditform = fb.group({
            username: [this.customerinfo.username, Validators.required],
            address: ["", Validators.required],
            state: ["", Validators.required],
            expmonth: ["", Validators.required],
            city: ["", Validators.required],
            expyear: ["", Validators.required],
            ccno: ["", Validators.required],
            cvv: ["", Validators.required],
            fname: [this.customerinfo.fname, Validators.required],
            lname: [this.customerinfo.lname, Validators.required],
            email: [this.customerinfo.email, AppCustomercreditcard.validateEmail],
            phone: [this.customerinfo.phone, Validators.required],
            zip: [this.customerinfo.zip, Validators.required],
            term: [this.customerinfo.term]
        });
    }

    static validateTerms(control: FormControl){

        console.log('34324324');
        console.log(control.value);
        if(control.value==false){
            return { 'isTermsChecked': true };
        }

    }

    static validateEmail(control: FormControl){
        if (control.value=='' || !control.value.match(/[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/)) {

            return { 'invalidEmailAddress': true };
        }
     }

    static validateState(control: FormControl){

        console.log(control.value+'stateval');
        if (control.value=='') {

            return { 'invalidState': true };
        }

    }
    submitform(){
        let x:any;
        for(x in this.customercreditform.controls){
            this.customercreditform.controls[x].markAsTouched();

        }
        this.customercreditform.markAsDirty();
        //this.signupform.controls['fname'].markAsTouched();
        if(this.customercreditform.valid){

            //var headers = new Headers();
            //headers.append('Content-Type', 'application/x-www-form-urlencoded');

            //this.items = this.commonservices.getItems();
            let link = this.serverUrl+'updatecustomer';
            var submitdata = this.customercreditform.value;
            console.log(submitdata);
           this.http.post(link,submitdata)
                .subscribe(data => {
                    // /this.data1.response = data.json();
                    console.log(this.customercreditform.value);
                    this.customerInfo.putObject('customerInfo',this.customercreditform.value);
                    this.router.navigateByUrl('/retailcustomerconnect');
                   // this.router.navigate(['/retailcustomerconnect']);

                }, error => {
                    console.log("Oooops!");
                });
        }
    }

}


text:
from unittest import TestSuite, TestLoader

from flask import url_for
from flask.ext.security import url_for_security
from lxml.html import fromstring

from spkrepo.ext import db
from spkrepo.tests.common import BaseTestCase, BuildFactory, UserFactory

class IndexTestCase(BaseTestCase):
    def test_get_anonymous(self):
        response = self.client.get(url_for('frontend.index'))
        self.assert200(response)
        self.assertIn('Login', response.data.decode(response.charset))
        self.assertIn('Register', response.data.decode(response.charset))

    def test_get_logged_user(self):
        with self.logged_user():
            response = self.client.get(url_for('frontend.index'))
            self.assert200(response)
            self.assertIn('Logout', response.data.decode(response.charset))
            self.assertIn('Profile', response.data.decode(response.charset))

class PackagesTestCase(BaseTestCase):
    def test_get_active_stable(self):
        build = BuildFactory(version__report_url=None, active=True)
        db.session.commit()
        response = self.client.get(url_for('frontend.packages'))
        self.assert200(response)
        self.assertIn(build.version.displaynames['enu'].displayname, response.data.decode(response.charset))
        self.assertNotIn('beta', response.data.decode(response.charset))

    def test_get_active_not_stable(self):
        build = BuildFactory(active=True)
        db.session.commit()
        response = self.client.get(url_for('frontend.packages'))
        self.assert200(response)
        self.assertIn(build.version.displaynames['enu'].displayname, response.data.decode(response.charset))
        self.assertIn('beta', response.data.decode(response.charset))

    def test_get_not_active_not_stable(self):
        build = BuildFactory(active=False)
        db.session.commit()
        response = self.client.get(url_for('frontend.packages'))
        self.assert200(response)
        self.assertNotIn(build.version.displaynames['enu'].displayname, response.data.decode(response.charset))
        self.assertNotIn('beta', response.data.decode(response.charset))

    def test_get_not_active_stable(self):
        build = BuildFactory(active=False)
        db.session.commit()
        response = self.client.get(url_for('frontend.packages'))
        self.assert200(response)
        self.assertNotIn(build.version.displaynames['enu'].displayname, response.data.decode(response.charset))
        self.assertNotIn('beta', response.data.decode(response.charset))

class PackageTestCase(BaseTestCase):
    def test_get(self):
        build = BuildFactory(version__package__author=UserFactory(), version__report_url=None, active=True)
        db.session.commit()
        response = self.client.get(url_for('frontend.package', name=build.version.package.name))
        self.assert200(response)
        for a in build.architectures:
            self.assertIn(a.code, response.data.decode(response.charset))
        self.assertIn(build.version.package.author.username, response.data.decode(response.charset))
        self.assertIn(build.version.displaynames['enu'].displayname, response.data.decode(response.charset))
        self.assertIn(build.version.descriptions['enu'].description, response.data.decode(response.charset))

    def test_get_no_package(self):
        response = self.client.get(url_for('frontend.package', name='no-package'))
        self.assert404(response)

class ProfileTestCase(BaseTestCase):
    def test_get_anonymous(self):
        self.assert302(self.client.get(url_for('frontend.profile')))

    def test_get_user(self):
        with self.logged_user():
            response = self.client.get(url_for('frontend.profile'))
            self.assert200(response)
            self.assertNotIn('API key', response.data.decode(response.charset))

    def test_get_developer(self):
        with self.logged_user('developer'):
            response = self.client.get(url_for('frontend.profile'))
            self.assert200(response)
            self.assertIn('API key', response.data.decode(response.charset))

    def test_get_no_api_key_by_default(self):
        with self.logged_user('developer', api_key=None):
            response = self.client.get(url_for('frontend.profile'))
            html = fromstring(response.data.decode(response.charset))
            self.assertTrue(html.forms[0].fields['api_key'] == '')

    def test_post_generate_api_key_developer(self):
        with self.logged_user('developer', api_key=None):
            response = self.client.post(url_for('frontend.profile'), data=dict(),
                                        follow_redirects=True)
            self.assert200(response)
            html = fromstring(response.data.decode(response.charset))
            self.assertTrue(html.forms[0].fields['api_key'] != '')

    def test_post_generate_api_key_not_developer(self):
        with self.logged_user(api_key=None):
            response = self.client.post(url_for('frontend.profile'), data=dict())
            self.assert200(response)

class RegisterTestCase(BaseTestCase):
    def test_unique_user_username(self):
        data = dict(username='test', email='test@test.com', password='password', password_confirm='password')
        self.client.post(url_for_security('register'), data=data)
        response = self.client.post(url_for_security('register'), data=data)
        self.assertIn('Username already taken', response.data.decode(response.charset))

def suite():
    suite = TestSuite()
    suite.addTest(TestLoader().loadTestsFromTestCase(IndexTestCase))
    suite.addTest(TestLoader().loadTestsFromTestCase(PackagesTestCase))
    suite.addTest(TestLoader().loadTestsFromTestCase(PackageTestCase))
    suite.addTest(TestLoader().loadTestsFromTestCase(ProfileTestCase))
    suite.addTest(TestLoader().loadTestsFromTestCase(RegisterTestCase))
    return suite


text:
<?php namespace eBussola\Feedback\Models;

use Model;
use October\Rain\Database\Traits\Validation;

/**
 * Feedback Model
 */
class Feedback extends Model
{
    use Validation;

    /**
     * @var string The database table used by the model.
     */
    public $table = 'ebussola_feedback_feedbacks';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [
        'name',
        'email',
        'message',
        'channel_id'
    ];

    /**
     * @var array The rules to be applied to the data.
     */
    public $rules = [
        'name' => '',
        'email' => 'email|required',
        'message' => 'required',
        'channel_id' => 'integer|required'
    ];

    /**
     * @var array The array of custom attribute names.
     */
    public $attributeNames = [
        'name' => 'ebussola.feedback::lang.feedback.name',
        'email' => 'ebussola.feedback::lang.feedback.email',
        'message' => 'ebussola.feedback::lang.feedback.message'
    ];

    /**
     * @var array The array of custom error messages.
     */
    public $customMessages = [
        'email' => 'ebussola.feedback::lang.component.onSend.error.email.email'
    ];

    /**
     * @var array Relations
     */
    public $hasOne = [];
    public $hasMany = [];
    public $belongsTo = [
        'channel' => '\eBussola\Feedback\Models\Channel'
    ];
    public $belongsToMany = [];
    public $morphTo = [];
    public $morphOne = [];
    public $morphMany = [];
    public $attachOne = [];
    public $attachMany = [];

    public static function archive($query)
    {
        $query->update(['archived' => true]);
    }

}


text:
require 'diplomat'

Puppet::Type.type(:key_value_config).provide(:consul) do
  confine feature: :consul

  mk_resource_methods

  def exists?
    Puppet.info("Checking if key #{name} exists")
    begin
      resp = Diplomat.get(name)
      resp == resource[:value]
    rescue Faraday::ResourceNotFound
      false
    end
  end

  def create
    Puppet.info("Setting #{name} to #{resource[:value]}")
    Diplomat.put(name, resource[:value])
  end

  def destroy
    Puppet.info("Deleting #{name}")
    Diplomat.delete(name)
  end
end


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
Repert. Spec. Nov. Regni Veg. 8:281. 1910

#### Original name
null

### Remarks
null


text:
Eliminate waste

      Eliminating waste is the most fundamental lean principle,

      the one from which all the other principles follow.


text:
Combat has several factors that make the challenges unique:

* Combatants wear *armor* that reduce damage taken and deflect blows
* Your choice of *weapon* alters the damage you can do and the frequency with which you can attack, as well as adding a range component
* You take both short term *impact* and long term *damage* and can even die.

## Weapons

Hand to hand combat usually involves weapons which have unique characteristics:

* They have *leverage* which increases your effect
* They have a variety of impact point shapes and materials that add to your effect
* Some weapons are less balanced or require reloading, reducing the frequency with which you can attack
* Some weapons are armor piercing, reducing the effect of armor against them.

### Leverage and strength

Hand weapons leverage depending on its size and manner of use. Leverage ranges from 1 to 2 depending on weapon length and usage.

Weapons also have a strength which is added in after the leverage multiplier, reflecting the nature and lethality of the head.
Weapon strength varies from -1 to 4.

Some weapons -- guns and bombs -- have fixed strengths as they don't depend on musclepower.

### Penetration

Penetration reflects a weapons ability to pierce into the body and cause permanant damage even with less base impact.
Penetration ranges from -1 to 3.

### Ready Time

Some weapons take one or more rounds to ready after use. You can still defend with them while unready
but you cannot defend with them until you've spent the requred rounds readying them.

<weapons-table></weapons-table>

## Armor

Armor has two qualities that make it useful in combat:

* It absorbs a measure of incoming impact
* It deflects some blows completely, adding to your defensive rank

<armor-table></armor-table>

## Attacks

Attacks are contests of weapon skill vs. defense.

### Defense Skill

Hand weapons can be defended against using hand weapons, even if they are unready, or dodged using your base Body.
Ranged weapons can only be dodged using Body.

## Impact of Blows

The effect of a blow are calculated from the basic Impact/effect as described in Challenges.

1. Subtract Armor from the Impact.
2. Take Impact past (Body - Penetration) as Damage; take the rest as Shock.
3. If the Damage from a single blow is greater than your Body you are instantly Dead.
4. If you are not dead, and the accumulated sum of your Damage is your Body,
   the remained is taken as Trauma and you are Bleeding Out.

### Shock

Shock is short term pain. You can accumulate up to 2x your Body in Shock, past that all impact is Damage.
However *for a single blow* you can only take up to Body - Penetration Impact in Shock: the remainder of the Impact is Damage.

Shock is recovered at a rate of 1 point per round, at the end of your round.
You cannot recover shock automatically if you have any Damage.
You can recover 1 point of Shock at the end of a round if you do not act (or are unconscious), unless you bleed out.

#### Knockout

If you accumulate Body Wounds (Stun + Damage) and fail a Will check on your round you are knocked out.
Your Will is halved if your Injuries are above Body × 2

Knockout lasts for an hour per point of Damage plus 15 minutes per point of Shock.

Anyone knocked out (or sleeping) can be killed in two rounds.

### Damage

Damage takes longer to recover. It cannot be recovered in the timespan of a battle.

### Trauma

If you accumulate Damage past your Body it is converted to Trauma.
You are bleeding out, and will ultimately die without aid.

### Injury

Injury is the sum of your Damage and Trauma.
If your Injury is greater than 2 × your Body, you die.
Ordinarily, this situation is equal to your trauma being equal to your Body; however with bleedout and medical care,
that equation won't always be equivalent.

#### Bleeding Out

If you have any Trauma at the start of every round, draw a card.
If the card is below your current Trauma you bleed out, and cannot recover any Shock that round.
You are not necessarily unconscious, but you will be soon.

* If it is red, take an extra point of Damage.
* If it is a Face Card take an extra point of Trauma.
* If it is black, take an extra point of Shock.

### Wounds

Your Wounds are the sum of your accumulated Shock, Trauma and Damage.

* If your accumulated Wounds are greater than your Body you must make a Will check every round or pass out.
  You cannot act other than to attempt to reduce your Shock.
* If your accumulated Wounds are greater than twice your Body, you are automatically knocked out.

<wounds></wounds>

## Death

You can die if:

* You take Damage from a single blow equal to your Body
* You accumulate your Body in Trauma

A surgeon can cure death, as described below.

### Destruction

Destruction is a special kind of death where the body is so ripped apart that you are unmistakably, permanantly dead.

### Your Hand and Injury

You must discard all cards in your hand if you take any Injury past Armor's absorption.
You cannot replenish your hand if you have any Wounds.

## Emergency Medicine

To provide emergency medicine, you must be:

1. Out of the line of fire for ranged weapons
2. At least 5 meters from enemy combatants and either out of direct line of sight or with your forces between you and your enemy.
3. Able to get at the wounds
4. Have bandages ready

Armor takes 1 round to remove for every 2 points of deflection, rounded down.
Bandages can be jury-rigged from clothing, but it takes an extra round per point of Trauma to rip up the bandages.
Which can be done by assistants.

Up to two EMTs can work on a single patient at once.

### Healing Damage

An EMT can bandage up to 1/2 your damage (round up) if you have not taken Trauma on a successful contest of
EMT skill vs. Damage. Once this contest has been made,
the remaining damage cannot be fixed with short term EMT aid, so track damage taken at each battle separately.

### Stabilizing Trauma

When you have Trauma your greatest threat is moment by moment bleeding.
With a successful contest of EMT vs. Trauma, you can stabilize 2 points of Trauma per round.
This contest can be made multiple times until the all Trauma is converted to Damage.

Once the EMT is successful, the victim does not have to make continued blood loss checks.
However, the patient cannot have damage actually reduced by an EMT through EMT Care if they have Damage above their Body.

### Self Care

You can provde self care if you must at half your EMT (or 1/4 your Mind), if you can stay conscious.

Bob gets hit for four points of damage; his Body is 6. Rick the EMT successfully heals two points of damage; leaving two
points that Bob must keep til he rests.

Bob is then hit for three more points of damage.
His total damage is five, including the two non-healed points from before.
Rick again heals him successfully curing two of the three new points of damage. note that's 3/2, not 5/2.

Rick is now at 3 points of Damage. He takes 5 points of damage and now has 8 points of Damage. He takes four points of damage. Since one of those is Trauma
he can no longer get patched up with short term EMT care.

Fixing Light Damage takes one second per accumulated Wounds, and also removes all Shock.
It must be done outside of direct combat.

Once someone has taken Trauma an EMT cannot reduce their damage at all.
However they can convert Trauma to regular damage to stop the bleeding.

## Long Term Healing

You can recover from shock after battle in a few seconds. Damage takes longer to heal.

In good care you automatically heal one point of damage if you make a contest of Body vs. Damage.

If you have competent healers looking after you, every day you fail to heal a point of damage, they can make a second
contest of their EMT skills vs. your Damage to heal a point of damage.

### Healing Trauma

If a surgeon is present within a half hour of an injury, they can heal up to 1/2 of Trauma (once it is stabilized)
through a contest of Surgery vs. Trauma.

#### Getting Worse

If you have Injury greater than your Body, the margin is considered Major Damage.
You have to draw over your Major Damage to avoid bleeding for a point of Damage,
and if you do, you have no opportunity to heal that day (as above). This can kill you.

### Healing in Difficult Circumstances

Healing requires safety, warmth, food and occasional care.
Without these conditions, you will at minimum not get an automatic point of healing.
In the worst conditions you may only get a chance to heal every other day,
and will have to make a contest vs. half your Damage (all of it, not just Trauma)
to avoid bleeding out for an extra point of Damage every day.

### Cheating Death

A dead person who is brought to a surgeon within a 1/2 hour can be brought back from the dead.
The surgeon must make a successful contest between their skill and your Injury.
If this check fails, a hero can make a final check against their base Will to reover long enough for a Dramatic last speech.

A surgeon's skill at fixing death is halved in primitive times,
or if they don't have access to modern tools and a supply of blood and drugs.
and a support team (at least one other EMT or Surgeon.

It takes at least 1/2 hour to fix death, plus an extra 1/2 hour for every point of trauma.


text:
You are signed up to use the Tree of Life Web Services.

In order to use the web services you must provide the User Key listed below:

Web Services User Key:

Please have a look at the Tree of Life Web Services documentation for information about our response format and content of ToL response documents:
http://webservices.tolweb.org/

For instructions on how to use the Tree of Life Web Services, please see the quickstart tutorial:
http://tolweb.org/tree/home.pages/webservicestutorial.html

We thank you for your interest in using our content.

The Tree of Life team: http://tolweb.org/tree/home.pages/homepeople.html


text:
@interface FSProfileLoader : NSObject

+ (FSProfileLoader *)sharedLoader;

- (void)loginWithUsername:(NSString *)username
                 password:(NSString *)password
        completionHandler:(void (^)(FSProfileInfo *profileInfo, NSError *error))completionHandler;

- (void)registerWithUsername:(NSString *)username
                    password:(NSString *)password
           completionHandler:(void (^)(BOOL success, NSError *error))completionHandler;

- (void)logoutWithCompletionHandler:(void (^)(BOOL success, NSError *error))completionHandler;

- (void)cancel;

@end


text:
export class CommonVO {

    public static Pages = {
        Home: 'home',
        Profile: 'profile/:user'
    }

}


text:
namespace arthr.ViewModels.Core
{
    #region Usings

    using System.Collections.Generic;
    using Models.Core;

    #endregion

    public class ProjectTools
    {
        #region Properties

        public List<MasterSite> MasterSites { get; set; }

        #endregion
    }
}


text:
import sys, os, subprocess

delimit='#!'

# Get cmd line argument
if len(sys.argv) < 2:
    print("Usage: multi filename")
    sys.exit()

filename = sys.argv[1]

# Parse out sections
with open(filename, 'r') as content_file:
    content = content_file.read()

sections = filter(None,content.split(delimit))

for idx, section in enumerate(sections):
    # Get first line of each section (the command to run)
    split_section = section.split('\n',1)
    tmpfilename = 'tmpfile' + str(idx)
    f = open(tmpfilename,'w')
    f.write('#!'+ split_section[0] + split_section[1])
    f.close()
    os.chmod(tmpfilename,0b111101101)
    result = subprocess.check_output([split_section[0].strip(), './' + tmpfilename])
    sys.stdout.write(result)
    os.remove(tmpfilename)


text:
layout:     post
title:      Playing with upsert
date:       2016-04-22 13:00:00
summary:    In this post we will explore upsert, a new feature provided by
            PostgreSQL 9.5. What is it and what can we do with it?
categories: sql
---

It is not news that every new version of PostgreSQL provides multiple features.
In this post we will explore Upsert, one of the few major features that was missing
from this amazing database.

In simple terms, upsert is nothing more than an insert with new possibilities in case
of a conflict. It is worth to remember that we can always refer to the amazing
[documentation](http://www.postgresql.org/docs/9.5/static/sql-insert.html) that
is provided when in doubt.

To start our exploration, let's create a simple table with a few records:

~~~ sql
CREATE TABLE games (
  game_id serial PRIMARY KEY,
  name varchar(100) NOT NULL UNIQUE,
  price integer NOT NULL
);

INSERT INTO games(name, price)
VALUES ('Final Fantasy IX', 50),
       ('Tales of Abyss', 35),
       ('Breath of Fire IV', 20);

select * from games;

 game_id |         name          | price
---------+-----------------------+-------
       1 | Final Fantasy IX      |    50
       2 | Tales of Abyss        |    35
       3 | Breath of Fire IV     |    20
(3 rows)
~~~

Let's begin with a traditional insert with a conflict.

~~~ sql
INSERT INTO games(name, price)
VALUES ('Final Fantasy IX', 50);

ERROR:  duplicate key value violates unique constraint "games_name_key"
DETAIL:  Key (name)=(Final Fantasy IX) already exists.
~~~

We got an error as expected since we already have this name in our table.
Now suppose a new business rule specified that conflicts like this should be
ignored, we could `rescue` (or `catch`) an exception in our application and
life goes on, but now we have another option:

~~~ sql
INSERT INTO games(name, price)
VALUES ('Final Fantasy IX', 50)
ON CONFLICT DO NOTHING;
INSERT 0 0
~~~

The `INSERT 0 0` hints us that nothing was inserted, which is exactly what we
wanted. Everyone is happy for a while, but the rules change and now in case
of a conflict the `price` need to be updated! Fear not, is what you say to
your manager:

~~~ sql
INSERT INTO games(name, price)
VALUES ('Final Fantasy IX', 75)
ON CONFLICT (name)
DO UPDATE SET price = EXCLUDED.price;
INSERT 0 1
Time: 1.786 ms

SELECT * FROM games WHERE name = 'Final Fantasy IX';
 game_id |       name       | price
---------+------------------+-------
       1 | Final Fantasy IX |    75
~~~

Notice that we use the `EXCLUDED` keyword to specify the updated price.
In this case we also specified the type of conflict, if a different conflict
occurs it will not be "rescued" as we can see below:

~~~ sql
INSERT INTO games(game_id, name, price)
VALUES (1, 'New Game', 10)
ON CONFLICT (name)
DO UPDATE SET price = EXCLUDED.price;

ERROR:  duplicate key value violates unique constraint "games_pkey"
DETAIL:  Key (game_id)=(1) already exists.
~~~

Suddenly the players start complaining that the games are getting expensive
and by consequence the sales in our store are decreasing, the new rule is
that the price should be updated only if the game gets cheaper.

~~~ sql
INSERT INTO games(name, price)
VALUES ('Final Fantasy IX', 80)
ON CONFLICT (name)
DO UPDATE SET price = EXCLUDED.price
WHERE EXCLUDED.price < games.price;
INSERT 0 0

SELECT * FROM games WHERE name = 'Final Fantasy IX';
 game_id |       name       | price
---------+------------------+-------
       1 | Final Fantasy IX |    75

INSERT INTO games(name, price)
VALUES ('Final Fantasy IX', 60)
ON CONFLICT (name)
DO UPDATE SET price = EXCLUDED.price
WHERE EXCLUDED.price < games.price;
INSERT 0 1

SELECT * FROM games WHERE name = 'Final Fantasy IX';
 game_id |       name       | price
---------+------------------+-------
       1 | Final Fantasy IX |    60
~~~

We can specify the name of our constraint in `ON CONFLICT`, but it is recommended
to use column names and let postgres specify the type of the index for you.
Let's see an example just in case:

~~~ sql
\dS games
                                    Table "public.games"
 Column  |          Type          |                        Modifiers
---------+------------------------+---------------------------------------------------------
 game_id | integer                | not null default
nextval('games_game_id_seq'::regclass)
 name    | character varying(100) | not null
 price   | integer                | not null
Indexes:
    "games_pkey" PRIMARY KEY, btree (game_id)
    "games_name_key" UNIQUE CONSTRAINT, btree (name)

INSERT INTO games(name, price)
VALUES ('Final Fantasy IX', 50)
ON CONFLICT ON CONSTRAINT games_name_key DO NOTHING;
INSERT 0 0
~~~

If we had a composite index or a partial index we could also specify
a condition in our `ON CONFLICT` clause. For example, if we had a composite
index on (name, year), we could do:

~~~ sql
INSERT INTO games(name, price)
VALUES ('Final Fantasy XV', 100)
ON CONFLICT (name, year)
WHERE year = 2016
DO NOTHING;
~~~

That's it for now, if you have further questions or suggestions
feel free to leave me a tweet or email so we can discuss things further!

See you in the next post!


text:
package com.facebook.imagepipeline.producers;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;

import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.net.Uri;
import com.facebook.common.memory.PooledByteBuffer;
import com.facebook.common.memory.PooledByteBufferFactory;
import com.facebook.imagepipeline.common.Priority;
import com.facebook.imagepipeline.core.ImagePipelineConfig;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.testing.FakeClock;
import com.facebook.imagepipeline.testing.TestExecutorService;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import org.junit.*;
import org.junit.runner.*;
import org.mockito.*;
import org.mockito.invocation.*;
import org.mockito.stubbing.*;
import org.robolectric.*;
import org.robolectric.annotation.Config;

/** Basic tests for LocalResourceFetchProducer */
@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public class LocalResourceFetchProducerTest {

  private static final String PRODUCER_NAME = LocalResourceFetchProducer.PRODUCER_NAME;
  private static final int TEST_ID = 1337;
  private static final int TEST_DATA_LENGTH = 337;

  @Mock public Resources mResources;
  @Mock public AssetFileDescriptor mAssetFileDescriptor;
  @Mock public PooledByteBufferFactory mPooledByteBufferFactory;
  @Mock public Consumer<EncodedImage> mConsumer;
  @Mock public ImageRequest mImageRequest;
  @Mock public ProducerListener2 mProducerListener;
  @Mock public Exception mException;
  @Mock public ImagePipelineConfig mConfig;

  private TestExecutorService mExecutor;
  private SettableProducerContext mProducerContext;
  private final String mRequestId = "mRequestId";
  private LocalResourceFetchProducer mLocalResourceFetchProducer;
  private EncodedImage mCapturedEncodedImage;

  @Before
  public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    when(mResources.openRawResourceFd(eq(TEST_ID))).thenReturn(mAssetFileDescriptor);
    when(mAssetFileDescriptor.getLength()).thenReturn((long) TEST_DATA_LENGTH);

    mExecutor = new TestExecutorService(new FakeClock());
    mLocalResourceFetchProducer =
        new LocalResourceFetchProducer(mExecutor, mPooledByteBufferFactory, mResources);

    mProducerContext =
        new SettableProducerContext(
            mImageRequest,
            mRequestId,
            mProducerListener,
            mock(Object.class),
            ImageRequest.RequestLevel.FULL_FETCH,
            false,
            true,
            Priority.MEDIUM,
            mConfig);
    when(mImageRequest.getSourceUri()).thenReturn(Uri.parse("res:///" + TEST_ID));
    doAnswer(
            new Answer() {
              @Override
              public Object answer(InvocationOnMock invocation) throws Throwable {
                mCapturedEncodedImage =
                    EncodedImage.cloneOrNull(((EncodedImage) invocation.getArguments()[0]));
                return null;
              }
            })
        .when(mConsumer)
        .onNewResult(notNull(EncodedImage.class), anyInt());
  }

  @After
  public void tearDown() throws Exception {
    verify(mPooledByteBufferFactory, atMost(1))
        .newByteBuffer(any(InputStream.class), eq(TEST_DATA_LENGTH));
  }

  @Test
  public void testFetchLocalResource() throws Exception {
    PooledByteBuffer pooledByteBuffer = mock(PooledByteBuffer.class);
    when(mPooledByteBufferFactory.newByteBuffer(any(InputStream.class), eq(TEST_DATA_LENGTH)))
        .thenReturn(pooledByteBuffer);
    when(mResources.openRawResource(eq(TEST_ID)))
        .thenReturn(new ByteArrayInputStream(new byte[TEST_DATA_LENGTH]));

    mLocalResourceFetchProducer.produceResults(mConsumer, mProducerContext);
    mExecutor.runUntilIdle();

    assertEquals(
        2,
        mCapturedEncodedImage
            .getByteBufferRef()
            .getUnderlyingReferenceTestOnly()
            .getRefCountTestOnly());
    assertSame(pooledByteBuffer, mCapturedEncodedImage.getByteBufferRef().get());
    verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
    verify(mProducerListener).onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, null);
    verify(mProducerListener).onUltimateProducerReached(mProducerContext, PRODUCER_NAME, true);
  }

  @Test(expected = RuntimeException.class)
  public void testFetchLocalResourceFailsByThrowing() throws Exception {
    when(mResources.openRawResource(eq(TEST_ID))).thenThrow(mException);
    mLocalResourceFetchProducer.produceResults(mConsumer, mProducerContext);
    mExecutor.runUntilIdle();
    verify(mConsumer).onFailure(mException);
    verify(mProducerListener).onProducerStart(mProducerContext, PRODUCER_NAME);
    verify(mProducerListener)
        .onProducerFinishWithFailure(mProducerContext, PRODUCER_NAME, mException, null);
    verify(mProducerListener).onUltimateProducerReached(mProducerContext, PRODUCER_NAME, false);
  }
}


text:
/*
 * ResourceRevision.java
 * Creation date: Dec 9, 2004.
 * By: Edward Lam
 */
package org.openquark.cal.services;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.openquark.cal.compiler.ModuleName;

/**
 * Warning- this class should only be used by the CAL services implementation. It is not part of the
 * external API of the CAL platform.
 * <p>
 * A simple wrapper around a module resource, its feature name, and its revision.
 *
 * This class exists because vaults may keep revisions of module resources, independently of revisions for modules themselves.
 * eg. in the standard vault, there is only ever one revision of a module and its resources, but the actual resource revision number
 * changes as the resources are modified.  The revisions associated with the most up-to-date resources may be different for the
 * different resources.
 *
 * @author Edward Lam
 */
public class ResourceRevision {

    /** The resource identifier. */
    private final ResourceIdentifier resourceIdentifier;

    /** The revision number. */
    private final long revisionNumber;

    /**
     * Constructor for a ResourceRevision.
     * @param resourceIdentifier
     * @param revision
     */
    public ResourceRevision(ResourceIdentifier resourceIdentifier, long revision) {
        this.resourceIdentifier = resourceIdentifier;
        this.revisionNumber = revision;
    }

    /**
     * @return the resource type.
     */
    public String getResourceType() {
        return resourceIdentifier.getResourceType();
    }

    /**
     * @return the resource identifier.
     */
    public ResourceIdentifier getIdentifier() {
        return resourceIdentifier;
    }

    /**
     * @return the revision.
     */
    public long getRevisionNumber() {
        return revisionNumber;
    }

    /**
     * The revision info for a group of resources.
     * @author Edward Lam
     */
    public static class Info {

        /**
         * The map which tracks resource revisions.
         * Map from resource type to a map for that type. The map for the type maps ResourceName to ResourceRevision for that type.
         */
        private final Map<String, Map<ResourceName, ResourceRevision>> resourceRevisionMap = new HashMap<String, Map<ResourceName,ResourceRevision>>();

        /**
         * Constructor for a Info.
         * @param revisionList
         */
        public Info(List<ResourceRevision> revisionList) {

            for (final ResourceRevision resourceRevision : revisionList) {
                updateResourceRevision(resourceRevision);
            }
        }

        /**
         * Constructor for a Info.
         */
        public Info() {
            this(Collections.<ResourceRevision>emptyList());
        }

        /**
         * @return the resource types in this object.
         */
        public String[] getResourceTypes() {
            Set<String> resourceTypeSet = resourceRevisionMap.keySet();
            String[] returnVal = new String[resourceTypeSet.size()];
            return resourceTypeSet.toArray(returnVal);
        }

        /**
         * Get the revision for a given resource.
         * @param resourceIdentifier the identifier of the resource.
         * @return the revision number of that resource, or 0L if that resource is not in this object.
         */
        public long getResourceRevision(ResourceIdentifier resourceIdentifier) {
            Map<ResourceName,ResourceRevision> resourceTypeMap = resourceRevisionMap.get(resourceIdentifier.getResourceType());
            if (resourceTypeMap == null) {
                return 0L;
            }

            ResourceRevision resourceRevision = resourceTypeMap.get(resourceIdentifier.getResourceName());
            if (resourceRevision == null) {
                return 0L;
            }

            return resourceRevision.getRevisionNumber();
        }

        /**
         * Get the resource revisions for a given resource type.
         * @param resourceType the type for which the resource revisions should be returned.
         * @return the resource revisions for that type.  Empty if there aren't any.
         */
        public Set<ResourceRevision> getResourceRevisions(String resourceType) {
            Map<ResourceName,ResourceRevision> resourceTypeMap = resourceRevisionMap.get(resourceType);
            if (resourceTypeMap == null) {
                return Collections.emptySet();
            }
            return new HashSet<ResourceRevision>(resourceTypeMap.values());
        }

        /**
         * Update some revision info in this object.
         * @param resourceRevision an updated revision.
         */
        void updateResourceRevision(ResourceRevision resourceRevision) {
            String resourceType = resourceRevision.getResourceType();
            ResourceName resourceName = resourceRevision.getIdentifier().getResourceName();

            Map<ResourceName, ResourceRevision> resourceTypeMap = resourceRevisionMap.get(resourceType);
            if (resourceTypeMap == null) {
                resourceTypeMap = new HashMap<ResourceName, ResourceRevision>();
                resourceRevisionMap.put(resourceType, resourceTypeMap);
            }

            resourceTypeMap.put(resourceName, resourceRevision);
        }

        /**
         * Update some revision info in this object.
         * @param resourceIdentifier the identifier of the resource.
         * @param resourceRevisionNum the updated revision number.
         */
        void updateResourceRevision(ResourceIdentifier resourceIdentifier, long resourceRevisionNum) {
            updateResourceRevision(new ResourceRevision(resourceIdentifier, resourceRevisionNum));
        }

        /**
         * Update some revision info in this object.
         * @param updatedInfo some updated revision info.
         */
        void updateResourceRevisionInfo(Info updatedInfo) {
            for (final String updatedFeatureType : updatedInfo.resourceRevisionMap.keySet()) {
                Map<ResourceName,ResourceRevision> updatedFeatureNameToSyncTimeMap = updatedInfo.resourceRevisionMap.get(updatedFeatureType);

                for (final ResourceRevision updatedRevision : updatedFeatureNameToSyncTimeMap.values()) {
                    updateResourceRevision(updatedRevision);
                }
            }
        }

        /**
         * @param resourceIdentifier the identifier of the resource whose revision info should be removed.
         * @return true if there was a resource revision to remove.
         */
        public boolean removeResourceRevision(ResourceIdentifier resourceIdentifier) {
            Map<ResourceName,ResourceRevision> resourceTypeMap = resourceRevisionMap.get(resourceIdentifier.getResourceType());
            if (resourceTypeMap != null) {
                return resourceTypeMap.remove(resourceIdentifier.getResourceName()) != null;
            }
            return false;
        }

        /**
         * Helper class to remove info associated with a module.
         * @param moduleName the name of the module whose info to remove
         */
        public void removeModule(ModuleName moduleName) {

            // Iterate over the maps for the resource types.
            for (final Map<ResourceName,ResourceRevision> resourceNameToRevisionMap : resourceRevisionMap.values()) {
                // Iterate over the mappings in the map for that resource type.
                for (Iterator<ResourceName> it = resourceNameToRevisionMap.keySet().iterator(); it.hasNext(); ) {
                    ResourceName resourceName = it.next();
                    FeatureName featureName = resourceName.getFeatureName();
                    if (!(featureName instanceof CALFeatureName)) {
                        continue;
                    }
                    CALFeatureName calFeatureName = (CALFeatureName)featureName;

                    // Check that the feature name has a module name which is the same as the one we're looking for.
                    if (calFeatureName.hasModuleName() && calFeatureName.toModuleName().equals(moduleName)) {
                        it.remove();
                    }
                }
            }
        }

        /**
         * Clear all revision info from this object.
         */
        void clear() {
            resourceRevisionMap.clear();
        }
    }

}


text:
package uk.nhs.careconnect.ri.stu3.dao;

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.annotation.ConditionalUrlParam;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.param.ReferenceParam;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.param.TokenParam;
import org.hl7.fhir.dstu3.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import uk.nhs.careconnect.fhir.OperationOutcomeException;
import uk.nhs.careconnect.ri.stu3.dao.transforms.ListEntityToFHIRListResourceTransformer;
import uk.nhs.careconnect.ri.database.daointerface.*;
import uk.nhs.careconnect.ri.database.entity.codeSystem.ConceptEntity;
import uk.nhs.careconnect.ri.database.entity.condition.ConditionEntity;
import uk.nhs.careconnect.ri.database.entity.documentReference.DocumentReferenceEntity;
import uk.nhs.careconnect.ri.database.entity.encounter.EncounterEntity;
import uk.nhs.careconnect.ri.database.entity.observation.ObservationEntity;
import uk.nhs.careconnect.ri.database.entity.patient.PatientEntity;
import uk.nhs.careconnect.ri.database.entity.practitioner.PractitionerEntity;
import uk.nhs.careconnect.ri.database.entity.questionnaireResponse.QuestionnaireResponseEntity;
import uk.nhs.careconnect.ri.database.entity.list.ListEntity;
import uk.nhs.careconnect.ri.database.entity.list.ListIdentifier;
import uk.nhs.careconnect.ri.database.entity.list.ListItem;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.*;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Repository
@Transactional
public class ListDao implements ListRepository {

    @PersistenceContext
    EntityManager em;

    @Autowired
    PatientRepository patientDao;

    @Autowired
    PractitionerRepository practitionerDao;

    @Autowired
            @Lazy
    CarePlanRepository carePlanDao;

    @Autowired
    @Lazy
    EncounterRepository encounterDao;

    @Autowired
    EpisodeOfCareRepository episodeDao;

    @Autowired
    QuestionnaireRepository questionnaireDao;

    @Autowired
    @Lazy
    ConceptRepository conceptDao;

    @Autowired
    ConditionRepository conditionDao;

    @Autowired
    ObservationRepository observationDao;

    @Autowired
    QuestionnaireResponseRepository formDao;

    @Autowired
    DocumentReferenceRepository documentDao;

    @Autowired
    private LibDao libDao;

    @Autowired
    private ListEntityToFHIRListResourceTransformer listEntityToFHIRListResourceTranslister;

    @Autowired
    private CodeSystemRepository codeSystemSvc;

    private static final Logger log = LoggerFactory.getLogger(ListDao.class);

    @Override
    public void save(FhirContext ctx, ListEntity list) throws OperationOutcomeException {
        em.persist(list);
    }

    @Override
    public ListResource read(FhirContext ctx,IdType theId) {
        if (daoutils.isNumeric(theId.getIdPart())) {
            ListEntity listEntity = (ListEntity) em.find(ListEntity.class, Long.parseLong(theId.getIdPart()));

            return listEntity == null
                    ? null
                    : listEntityToFHIRListResourceTranslister.transform(listEntity);

        } else {
            return null;
        }
    }

    @Override
    public List<ListResource> searchListResource(FhirContext ctx, TokenParam identifier, StringParam id, ReferenceParam patient) {
        List<ListEntity> qryResults = searchListEntity(ctx, identifier, id,  patient);
        List<ListResource> results = new ArrayList<>();

        for (ListEntity list : qryResults)
        {
            // log.trace("HAPI Custom = "+doc.getId());
            ListResource questionnaireResponse = listEntityToFHIRListResourceTranslister.transform(list);
            results.add(questionnaireResponse);
        }

        return results;
    }

    @Override
    public List<ListEntity> searchListEntity(FhirContext ctx, TokenParam identifier, StringParam resid, ReferenceParam patient) {

            List<ListEntity> qryResults = null;

            CriteriaBuilder builder = em.getCriteriaBuilder();

            CriteriaQuery<ListEntity> criteria = builder.createQuery(ListEntity.class);

            Root<ListEntity> root = criteria.from(ListEntity.class);

            List<Predicate> predList = new LinkedList<Predicate>();
            List<Questionnaire> results = new ArrayList<Questionnaire>();

            if (identifier !=null)
            {
                Join<ListEntity, ListIdentifier> join = root.join("identifiers", JoinType.LEFT);

                Predicate p = builder.equal(join.get("value"),identifier.getValue());
                predList.add(p);
                // TODO predList.add(builder.equal(join.get("system"),identifier.getSystem()));

            }
            if (resid != null) {
                Predicate p = builder.equal(root.get("id"),resid.getValue());
                predList.add(p);
            }

            if (patient != null) {
                if (daoutils.isNumeric(patient.getIdPart())) {
                    Join<ListEntity, PatientEntity> join = root.join("patient", JoinType.LEFT);

                    Predicate p = builder.equal(join.get("id"), patient.getIdPart());
                    predList.add(p);
                } else {
                    Join<ListEntity, PatientEntity> join = root.join("patient", JoinType.LEFT);

                    Predicate p = builder.equal(join.get("id"), -1);
                    predList.add(p);
                }
            }

            Predicate[] predArray = new Predicate[predList.size()];
            predList.toArray(predArray);
            if (predList.size()>0)
            {
                criteria.select(root).where(predArray);
            }
            else
            {
                criteria.select(root);
            }

            qryResults = em.createQuery(criteria).setMaxResults(daoutils.MAXROWS).getResultList();
            return qryResults;
        }

    @Override
    public Long count() {

        CriteriaBuilder qb = em.getCriteriaBuilder();
        CriteriaQuery<Long> cq = qb.createQuery(Long.class);
        cq.select(qb.count(cq.from(ListEntity.class)));
        //cq.where(/*your stuff*/);
        return em.createQuery(cq).getSingleResult();
    }

    @Override
    public ListEntity readEntity(FhirContext ctx, IdType theId) {
        if (daoutils.isNumeric(theId.getIdPart())) {
            ListEntity listEntity = (ListEntity) em.find(ListEntity.class, Long.parseLong(theId.getIdPart()));

            return listEntity;

        } else {
            return null;
        }
    }

    @Override
    public ListResource create(FhirContext ctx,ListResource list, @IdParam IdType theId, @ConditionalUrlParam String theConditional) throws OperationOutcomeException {

        ListEntity listEntity = null;
        log.debug("Called ListResource Create Condition Url: "+theConditional);
        if (theId != null) {
                listEntity =  readEntity(ctx,theId);
        }

        if (listEntity == null) {
            listEntity = new ListEntity();
        }

        listEntity.setStatus(list.getStatus());

        if (list.hasMode()) {
            listEntity.setMode(list.getMode());
        }

        if (list.hasTitle()) {
            listEntity.setTitle(list.getTitle());
        }
        if (list.hasCode()) {
            ConceptEntity code = conceptDao.findAddCode(list.getCode().getCoding().get(0));
            if (code != null) { listEntity.setCode(code); }
        }

        if (list.hasSubject()) {
            if (list.getSubject().getReference().contains("Patient")) {
                PatientEntity patientEntity = null;
                patientEntity = patientDao.readEntity(ctx, new IdType(list.getSubject().getReference()));
                listEntity.setPatient(patientEntity);
            }
        }

        if (list.hasEncounter()) {

            EncounterEntity encounterEntity = encounterDao.readEntity(ctx, new IdType(list.getEncounter().getReference()));
            listEntity.setContextEncounter(encounterEntity);

        }

        if (list.hasDate()) {
            listEntity.setDateTime(list.getDate());
        }

        if (list.hasSource()) {
            if (list.getSource().getReference().contains("Patient")) {
                PatientEntity patientEntity = null;
                patientEntity = patientDao.readEntity(ctx, new IdType(list.getSource().getReference()));
                listEntity.setSourcePatient(patientEntity);
            }
            if (list.getSource().getReference().contains("Practitioner")) {
                PractitionerEntity practitionerEntity = null;
                practitionerEntity = practitionerDao.readEntity(ctx, new IdType(list.getSource().getReference()));
                listEntity.setSourcePractitioner(practitionerEntity);
            }
        }

        if (list.hasNote()) {
            listEntity.setNote(list.getNote().get(0).getText());
        }

        em.persist(listEntity);

        for (Identifier ident : list.getIdentifier()) {

            log.debug("ListResource SDS = " + ident.getValue() + " System =" + ident.getSystem());
            ListIdentifier listIdentifier = null;

            for (ListIdentifier orgSearch : listEntity.getIdentifiers()) {
                if (ident.getSystem().equals(orgSearch.getSystemUri()) && ident.getValue().equals(orgSearch.getValue())) {
                    listIdentifier = orgSearch;
                    break;
                }
            }
            if (listIdentifier == null) {
                listIdentifier = new ListIdentifier();
                listIdentifier.setList(listEntity);

            }

            listIdentifier= (ListIdentifier) libDao.setIdentifier(ident,  listIdentifier);
            log.debug("ListResource System Code: " + listIdentifier.getSystemUri());

            em.persist(listIdentifier);
        }

        for (ListItem item : listEntity.getItems()) {
            em.remove(item);
        }
        for (ListResource.ListEntryComponent item : list.getEntry()) {
            ListItem itemEntity = new ListItem();
            itemEntity.setList(listEntity);
            if (item.hasDate()) {
                itemEntity.setItemDateTime(item.getDate());
            }
            if (item.hasDeleted()) {
                itemEntity.setItemDeleted(item.getDeleted());
            }
            buildItem(ctx, item, itemEntity);
        }

       // log.info("Called PERSIST id="+listEntity.getId().toString());
        list.setId(listEntity.getId().toString());

        return list;
    }

    private void buildItem(FhirContext ctx,ListResource.ListEntryComponent item, ListItem itemEntity ) {

        if (item.getItem().getReference().contains("Condition")) {

            ConditionEntity conditionEntity = conditionDao.readEntity(ctx, new IdType(item.getItem().getReference()));
            itemEntity.setReferenceCondition(conditionEntity);

        } else if (item.getItem().getReference().contains("Observation")) {

            ObservationEntity observationEntity = observationDao.readEntity(ctx, new IdType(item.getItem().getReference()));
            itemEntity.setReferenceObservation(observationEntity);
        } else if (item.getItem().getReference().contains("QuestionnaireResponse")) {

            QuestionnaireResponseEntity
                    questionnaireEntity = formDao.readEntity(ctx, new IdType(item.getItem().getReference()));
            itemEntity.setReferenceForm(questionnaireEntity);

        } else if (item.getItem().getReference().contains("List")) {

            ListEntity listEntity = readEntity(ctx, new IdType(item.getItem().getReference()));
            itemEntity.setReferenceListResource(listEntity);

        } else if (item.getItem().getReference().contains("List")) {

            DocumentReferenceEntity documentReferenceEntity = documentDao.readEntity(ctx, new IdType(item.getItem().getReference()));
            itemEntity.setReferenceDocumentReference(documentReferenceEntity);

        }
        em.persist(itemEntity);

    }

}


text:
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">

Sites

SitePoint

Learnable

Flippa


text:
<?PHP

    require_once '_include/inc_database_mysqli.php';
    require_once '_include/inc_lodo.php';

    $db = new DbActra();
    $db->Connect();

    /* Interface to Lodo system */
    $lodo = new Lodo();

    /* Add a new project type to this client */
    if ( $_REQUEST['cmd'] == "add" )
    {
        /* Add a new project type */
        $values = array(
            "ext_client_id" => $lodo->currentClientId,
            "hourly_cost" => intval($_REQUEST['hourly_cost']),
            "name" => trim($_REQUEST['name'])
        );
        $sqlStr = "INSERT INTO timer_projecttype " . $db->BuildSQLString( $db->BUILD_INSERT, $values );
        $db->Query( $sqlStr );

        header("Location: " . $MY_SELF . "\n\n");
    }
    /* Delete this project type (THIS elseif must be above the one that checks if the projecttype should be updated) */
    elseif ( $_REQUEST['delete'] != "" )
    {
        $sqlStr = "DELETE FROM timer_projecttype WHERE projecttype_id=" . $_REQUEST['projecttype_id'];
        $db->Query( $sqlStr );

            header("Location: " . $MY_SELF . "\n\n");
    }
    elseif ( $_REQUEST['save'] != "" )
    {
        $values = array(
            "hourly_cost" => intval($_REQUEST['hourly_cost']),
            "name" => trim($_REQUEST['name'])
        );
        $sqlStr = "UPDATE timer_projecttype SET " . $db->BuildSQLString( $db->BUILD_UPDATE, $values ) . " WHERE projecttype_id=" . $_REQUEST['projecttype_id'];
        $db->Query( $sqlStr );

        header("Location: " . $MY_SELF . "\n\n");
    }
    print $_lib['sess']->doctype;
?>

    <title>Empatix - salary list</title>
    <meta name="cvs"                content="$Id: list.php,v 1.41 2005/01/30 12:35:04 thomasek Exp $" />
    <? includeinc('head') ?>

Prosjekttyper

    Navn
    Timepris

<?PHP
    $sqlStr = "SELECT * FROM timer_projecttype WHERE ext_client_id=" . $lodo->currentClientId;
    if ( ($rs = $db->Query( $sqlStr )) )
    {
        while ( ($row = $db->NextRow( $rs )) )
        {
?>

<form action="<?php echo( $MY_SELF );?>" onsubmit="return AskDelete();" method="post">
<input type="hidden" name="projecttype_id" value="<?PHP echo( $row['projecttype_id'] );?>" />
    <input type="submit" name="delete" value="Slett linjen" />
</form>
<form action="<?php echo( $MY_SELF );?>" method="post">
<input type="hidden" name="cmd" value="update" />
<input type="hidden" name="projecttype_id" value="<?PHP echo( $row['projecttype_id'] );?>" />
    <input name="name" value="<?PHP echo( $row['name'] );?>" size="20" />
    <input name="hourly_cost" value="<?PHP echo( $row['hourly_cost'] );?>" size="4" />
    <input type="submit" name="save" value="Lagre linjen" />

</form>
<?PHP
        }
        $db->EndQuery($rs );
    }
?>

    <form action="<?php echo( $MY_SELF );?>" method="post">
<input type="hidden" name="cmd" value="add" /><input name="name" value="<?PHP echo( $row['name'] );?>" size="20" />
    <input name="hourly_cost" value="<?PHP echo( $row['hourly_cost'] );?>" size="4" />
    <input type="submit" value="Legg til ny" /></form>

Lukk vindu

<?PHP
    $db->Disconnect();
?>


text:
Full Page Screen Capture
========================

A simple Google Chrome extension that takes a screen capture of a full web page. Every extension I tried couldn't do this on Chrome 22 on Mac OSX Lion. So, I built this one to reliably do it. (Not tested, yet, on any other configurations.)

### To Install

For development:

1. Clone this repo
2. Open up Chrome and go to the extensions page (Window → Extensions)
3. Enable developer mode (if it's not already)
4. Click on "Load unpacked extension…"
5. Select the folder for this app

From the webstore:

Find the [Full Page Screen Capture App](https://chrome.google.com/webstore/detail/full-page-screen-capture/fdpohaocaechififmbbbbbknoalclacl) in the Chrome Webstore and click install. (NOTE: the webstore version is now running on a private branch of this repo and will have more updates.)

### Extra notes:

*   Please report any bugs that you find as issues on the project
*   More details on [this blog post](http://mrcoles.com/full-page-screen-capture-chrome-extension/)
*   Thank you to [terrycojones](https://github.com/terrycojones) & [gleitz](https://github.com/gleitz) for contributions!


text:
<!DOCTYPE HTML>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Free 404 White for Iphone, Android & Smartphone Mobile Website Template | Home :: w3layouts</title>

        <img src="<?php echo base_url(); ?>/assets/web/images/404.png" alt=""  />

Go back to Home

	Design by - W3Layouts


text:
title: "PuppetDB 5.0: Installing PuppetDB via Puppet module"
layout: default
---

[module]: http://forge.puppet.com/puppetlabs/puppetdb
[config_with_module]: ./configure.html#playing-nice-with-the-puppetdb-module

> **Note:** If you are running Puppet Enterprise version 3.0 or later, you do
> not need to install PuppetDB, as it is already installed as part of PE.

You can install and configure all of PuppetDB's components and prerequisites
(including PuppetDB itself, PostgreSQL, firewall rules on RedHat-like systems,
and the PuppetDB-termini for your Puppet master) using
[the PuppetDB module][module] from the Puppet Forge.

* If you are **already familiar with Puppet** and have a working Puppet
  deployment, this is the easiest method for installing PuppetDB. In this guide,
  we expect that you already know how to assign Puppet classes to nodes.
* If you are **just getting started with Puppet,** you may find it easier to
  follow our guide to
  [installing PuppetDB from packages](./install_from_packages.html).

Step 1: Enable the Puppet Collection package repository
-----

If you haven't done so already, you will need to do **one** of the following:

* [Enable the Puppet Collection package repository]({{puppet}}/puppet_collections.html)
  on your PuppetDB server and Puppet master server.
* Grab the PuppetDB and PuppetDB-termini packages, and import them into your
  site's local package repos.

Step 2: Assign classes to nodes
-----

Using the normal methods for your site, assign the PuppetDB module's classes to
your servers. You have three main options for deploying PuppetDB:

* If you are installing PuppetDB on the same server as your Puppet master,
  assign the `puppetdb` and `puppetdb::master::config` classes to it.
* If you want to run PuppetDB on its own server with a local PostgreSQL
  instance, assign the `puppetdb` class to it, and assign the
  `puppetdb::master::config` class to your Puppet master. Make sure to set the
  class parameters as necessary.
* If you want PuppetDB and PostgreSQL to each run on their own servers, assign
  the `puppetdb::server` class and the `puppetdb::database::postgresql` classes
  to different servers, and the `puppetdb::master::config` class to your Puppet
  master. Make sure to set the class parameters as necessary.

Note: By default, the module sets up the PuppetDB dashboard to be accessible
only via `localhost`. If you'd like to allow access to the PuppetDB dashboard
via an external network interface, set the `listen_address` parameter on either
of the `puppetdb` or `puppetdb::server` classes as follows:

    class { 'puppetdb':
        listen_address => 'example.foo.com'
    }

These classes automatically configure most aspects of PuppetDB. If you need to
adjust additional settings (to change the `node_ttl`, for example), see
[the "Playing nice with the PuppetDB module" section][config_with_module] of the
"Configuring PuppetDB" page.

For full details on how to use the module, see the
[PuppetDB module documentation](http://forge.puppetlabs.com/puppetlabs/puppetdb)
on Puppet Forge. The module also includes some sample manifests in the `tests`
directory that demonstrate its basic usage.


text:
class SimpleModel

  include JSONMapper

  json_attribute :id, Integer
  json_attribute :money, Float
  json_attribute :title, String
  json_attribute :boolean, Boolean
  json_attribute :datetime, DateTime

end

class ComplexModel

  include JSONMapper

  json_attribute :id, [ :id, :attribute_id ], Integer
  json_attribute :model_title, :title, String
  json_attribute :datetime, DateTime
  json_attribute :simple, SimpleModel
  json_attribute :nested_test, { :nested => :test }, String
  json_attributes :simples, SimpleModel
  json_attributes :integers, Integer
  json_attributes :delimited, DelimitedString, :delimiter => ","

  json_attribute :self_referential, "self", SimpleModel

end


text:
package org.apache.bcel.generic;

/**
 * ISTORE - Store int from stack into local variable
 *
 * <PRE>
 * Stack: ..., value -> ...
 * </PRE>
 */
public class ISTORE extends StoreInstruction {

    /**
     * Empty constructor needed for Instruction.readInstruction. Not to be used otherwise.
     */
    ISTORE() {
        super(org.apache.bcel.Const.ISTORE, org.apache.bcel.Const.ISTORE_0);
    }

    /**
     * Store int into local variable
     *
     * @param n index of local variable
     */
    public ISTORE(final int n) {
        super(org.apache.bcel.Const.ISTORE, org.apache.bcel.Const.ISTORE_0, n);
    }

    /**
     * Call corresponding visitor method(s). The order is: Call visitor methods of implemented interfaces first, then call
     * methods according to the class hierarchy in descending order, i.e., the most specific visitXXX() call comes last.
     *
     * @param v Visitor object
     */
    @Override
    public void accept(final Visitor v) {
        super.accept(v);
        v.visitISTORE(this);
    }
}


text: Software related to the "Red Buggy" / FSAE car for UNCA Motorsports


text:
module Rails
  module Upgrading
    module FakeRouter
      module ActionController
        module Routing
          class Routes
            def self.setup
              @redrawer = Rails::Upgrading::RouteRedrawer.new
            end

            def self.redrawer
              @redrawer
            end

            def self.draw
              yield @redrawer
            end
          end
        end
      end
    end

    class RoutesUpgrader
      def generate_new_routes
        if has_routes_file?
          upgrade_routes
        else
          raise FileNotFoundError, "Can't find your routes file [config/routes.rb]!"
        end
      end

      def has_routes_file?
        File.exists?("config/routes.rb")
      end

      def routes_code
        File.read("config/routes.rb")
      end

      def upgrade_routes
        FakeRouter::ActionController::Routing::Routes.setup

        # Read and eval the file; our fake route mapper will capture
        # the calls to draw routes and generate new route code
        FakeRouter.module_eval(routes_code)

        # Give the route set to the code generator and get its output
        generator = RouteGenerator.new(FakeRouter::ActionController::Routing::Routes.redrawer.routes)
        generator.generate
      end
    end

    class RouteRedrawer
      attr_accessor :routes

      def self.stack
        @stack
      end

      def self.stack=(val)
        @stack = val
      end

      def initialize
        @routes = []

        # The old default route was actually two routes; we generate the new style
        # one only if we haven't generated it for the first old default route.
        @default_route_generated = false

        # Setup the stack for parents; used use proper indentation
        self.class.stack = [@routes]
      end

      def root(options)
        debug "mapping root"
        @routes << FakeRoute.new("/", options)
      end

      def connect(path, options={})
        debug "connecting #{path}"

        if (path == ":controller/:action/:id.:format" || path == ":controller/:action/:id")
          if !@default_route_generated
            current_parent << FakeRoute.new("/:controller(/:action(/:id))", {:default_route => true})

            @default_route_generated = true
          end
        else
          current_parent << FakeRoute.new(path, options)
        end
      end

      def resources(*args, &block)
        _res(FakeResourceRoute, args, &block)
      end

      def resource(*args, &block)
        _res(FakeSingletonResourceRoute, args, &block)
      end

      def _res(klass, args)
        if args.last.is_a?(Hash)
          options = args.pop
          debug "options  #{options.inspect}"
        end

        args.each do |a|
          current_parent << klass.new(a, options || {})
          debug "mapping resources #{current_parent.last.name}"

          if block_given?
            parent = current_parent.last

            parent = stack(parent) do
              yield(self)
            end
          end
        end
      end

      def namespace(name, options = {})
        debug "mapping namespace #{name}"
        namespace = FakeNamespace.new(name, options)

        namespace = stack(namespace) do
          yield(self)
        end

        current_parent << namespace
      end

      def method_missing(m, *args)
        debug "named route: #{m}"
        current_parent << FakeRoute.new(args.shift, args.pop, m.to_s)
      end

      def self.indent
        ' ' * ((stack.length) * 2)
      end

    private
      def debug(txt)
        puts txt if ENV['DEBUG']
      end

      def stack(obj)
        self.class.stack << obj
        yield
        self.class.stack.pop
      end

      def current_parent
        self.class.stack.last
      end
    end

    class RouteObject
      def indent_lines(code_lines)
        if code_lines.length > 1
          code_lines.flatten.map {|l| "#{@indent}#{l.chomp}"}.join("\n") + "\n"
        else
          "#{@indent}#{code_lines.shift}"
        end
      end

      def opts_to_string(opts)
        opts.is_a?(Hash) ? opts.map {|k, v|
          ":#{k} => " + (v.is_a?(Hash) ? ('{ ' + opts_to_string(v) + ' }') : "#{value_to_string(v)}")
        }.join(", ") : opts.to_s
      end

      def value_to_string(value)
        case value
        when Regexp, Symbol, Array then value.inspect
        when String then "'" + value.to_s + "'"
        else value.to_s
        end
      end
    end

    class FakeNamespace < RouteObject
      attr_accessor :routes, :name, :options

      def initialize(name, options = {})
        @routes = []
        @name, @options = name, options
        @indent = RouteRedrawer.indent
      end

      def to_route_code
        if !@options.empty?
          options = ', ' + opts_to_string(@options)
        else
          options = ''
        end

        lines = ["namespace :#{@name}#{options} do", @routes.map {|r| r.to_route_code}, "end"]

        indent_lines(lines)
      end

      def <<(val)
        @routes << val
      end

      def last
        @routes.last
      end
    end

    class FakeRoute < RouteObject
      attr_accessor :name, :path, :options

      def initialize(path, options, name = "")
        @path = path
        @options = options || {}
        @name = name
        @indent = RouteRedrawer.indent
      end

      def to_route_code
        if @options[:default_route]
          indent_lines ["match '#{@path}'"]
        else
          base = "match '%s' => '%s#%s'"
          extra_options = []

          if not name.empty?
            extra_options << ":as => :#{name}"
          end

          if @options[:requirements]
            @options[:constraints] = @options.delete(:requirements)
          end

          if @options[:conditions]
            @options[:via] = @options.delete(:conditions).delete(:method)
          end

          @options ||= {}
          base = (base % [@path, @options.delete(:controller), (@options.delete(:action) || "index")])
          opts = opts_to_string(@options)

          route_pieces = ([base] + extra_options + [opts])
          route_pieces.delete("")

          indent_lines [route_pieces.join(", ")]
        end
      end
    end

    class FakeResourceRoute < RouteObject
      attr_accessor :name, :children

      def initialize(name, options = {})
        @name = name
        @children = []
        @options = options
        @indent = RouteRedrawer.indent
      end

      def to_route_code
        # preserve :only & :except options
        copied_options = @options.reject { |k,v| ![:only, :except].member?(k) }
        unless copied_options.empty?
          copied_options_str = ", " + copied_options.map { |k, v| "#{k.inspect} => #{v.inspect}" }.join(",")
        end

        if !@children.empty? || @options.has_key?(:collection) || @options.has_key?(:member)
          prefix = ["#{route_method} :#{@name}#{copied_options_str} do"]
          lines = prefix + custom_methods + [@children.map {|r| r.to_route_code}.join("\n"), "end"]

          indent_lines(lines)
        else
          base = "#{route_method} :%s#{copied_options_str}"
          indent_lines [base % [@name]]
        end
      end

      def custom_methods
        collection_code = generate_custom_methods_for(:collection)
        member_code = generate_custom_methods_for(:member)
        [collection_code, member_code]
      end

      def generate_custom_methods_for(group)
        return "" unless @options[group]

        method_code = []

        RouteRedrawer.stack << self
        @options[group].each do |name, methods|
          [*methods].each do |method|
            method_code << "#{method} :#{name}"
          end
        end
        RouteRedrawer.stack.pop

        indent_lines ["#{group} do", method_code, "end"].flatten
      end

      def route_method
        "resources"
      end

      def <<(val)
        @children << val
      end

      def last
        @children.last
      end
    end

    class FakeSingletonResourceRoute < FakeResourceRoute
      def route_method
        "resource"
      end
    end

    class RouteGenerator
      def initialize(routes)
        @routes = routes
        @new_code = ""
      end

      def generate
        @new_code = @routes.map do |r|
          r.to_route_code
        end.join("\n")

        "#{app_name.underscore.classify}::Application.routes.draw do\n#{@new_code}\nend\n"
      end

    private
      def app_name
        File.basename(Dir.pwd)
      end
    end
  end
end