text:
using extensions::Extension;

namespace errors = extension_manifest_errors;

TEST_F(ExtensionManifestTest, ManifestVersionError) {
  scoped_ptr<DictionaryValue> manifest1(new DictionaryValue());
  manifest1->SetString("name", "Miles");
  manifest1->SetString("version", "0.55");

  scoped_ptr<DictionaryValue> manifest2(manifest1->DeepCopy());
  manifest2->SetInteger("manifest_version", 1);

  scoped_ptr<DictionaryValue> manifest3(manifest1->DeepCopy());
  manifest3->SetInteger("manifest_version", 2);

  struct {
    const char* test_name;
    bool require_modern_manifest_version;
    DictionaryValue* manifest;
    bool expect_error;
  } test_data[] = {
    { "require_modern_with_default", true, manifest1.get(), true },
    { "require_modern_with_v1", true, manifest2.get(), true },
    { "require_modern_with_v2", true, manifest3.get(), false },
    { "dont_require_modern_with_default", false, manifest1.get(), false },
    { "dont_require_modern_with_v1", false, manifest2.get(), false },
    { "dont_require_modern_with_v2", false, manifest3.get(), false },
  };

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) {
    int create_flags = Extension::NO_FLAGS;
    if (test_data[i].require_modern_manifest_version)
      create_flags |= Extension::REQUIRE_MODERN_MANIFEST_VERSION;
    if (test_data[i].expect_error) {
        LoadAndExpectError(
            Manifest(test_data[i].manifest,
                     test_data[i].test_name),
            errors::kInvalidManifestVersionOld,
            extensions::Manifest::UNPACKED,
            create_flags);
    } else {
      LoadAndExpectSuccess(Manifest(test_data[i].manifest,
                                    test_data[i].test_name),
                           extensions::Manifest::UNPACKED,
                           create_flags);
    }
  }
}


text:
<?php

namespace Lthrt\ContactBundle\Command;

use Lthrt\ContactBundle\DataFixtures\FakePeopleLoader;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken as Token;

class LoadFakePeopleCommand extends ContainerAwareCommand
{
    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        $this
            ->setName('lthrt:load:fakePeople')
            ->setAliases(['lthrt:lo:fp'])
            ->setDescription('Loads fake people into database, skipping those already present')
            ->addOption('overwrite', null, InputOption::VALUE_NONE, 'Overwrite even if abbreviation exists')
            ->addOption('em', null, InputOption::VALUE_REQUIRED, 'entity manager')
            ->setHelp(<<<EOT
The <info>lthrt:load:fakePeople</info> Loads fake people into a database if they are not already present.

EOT
            );
    }

    /**
     * {@inheritDoc}
     */
    protected function execute(
        InputInterface  $input,
        OutputInterface $output
    ) {
        // For logging
        $token = new Token('Console', 'Console', 'Console');
        $this->getContainer()->get('security.token_storage')->setToken($token);

        $overwrite = $input->getOption('overwrite') ?: false;
        $emName    = $input->getOption('em');
        $manager   = $this->getContainer()->get('doctrine')->getManager($emName);
        $loader    = new FakePeopleLoader($manager);
        $result    = $loader->loadFakePeople($overwrite);
        if (isset($result['new']) && count($result['new'])) {
            $inserted = implode(",\n", array_keys($result['new']));
            $output->writeln("<info>" . $inserted . "</info>\nadded.");
            $output->writeln("");
        }
        if (isset($result['updates']) && count($result['updates'])) {
            $updated = implode(",\n", array_keys($result['updates']));
            $output->writeln("<info>" . $updated . "</info>\nupdated.");
            $output->writeln("");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.example.android.apis.graphics;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;

//Need the following import to get access to the app resources, since this
//class is in a sub-package.

/**
 * Demonstrates the handling of touch screen and trackball events to
 * implement a simple painting app.
 */
public class TouchPaint extends GraphicsActivity {
    /** Used as a pulse to gradually fade the contents of the window. */
    private static final int FADE_MSG = 1;

    /** Menu ID for the command to clear the window. */
    private static final int CLEAR_ID = Menu.FIRST;
    /** Menu ID for the command to toggle fading. */
    private static final int FADE_ID = Menu.FIRST+1;

    /** How often to fade the contents of the window (in ms). */
    private static final int FADE_DELAY = 100;

    /** The view responsible for drawing the window. */
    MyView mView;
    /** Is fading mode enabled? */
    boolean mFading;

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create and attach the view that is responsible for painting.
        mView = new MyView(this);
        setContentView(mView);
        mView.requestFocus();

        // Restore the fading option if we are being thawed from a
        // previously saved state.  Note that we are not currently remembering
        // the contents of the bitmap.
        mFading = savedInstanceState != null ? savedInstanceState.getBoolean("fading", true) : true;
    }

    @Override public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, CLEAR_ID, 0, "Clear");
        menu.add(0, FADE_ID, 0, "Fade").setCheckable(true);
        return super.onCreateOptionsMenu(menu);
    }

    @Override public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(FADE_ID).setChecked(mFading);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case CLEAR_ID:
                mView.clear();
                return true;
            case FADE_ID:
                mFading = !mFading;
                if (mFading) {
                    startFading();
                } else {
                    stopFading();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override protected void onResume() {
        super.onResume();
        // If fading mode is enabled, then as long as we are resumed we want
        // to run pulse to fade the contents.
        if (mFading) {
            startFading();
        }
    }

    @Override protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // Save away the fading state to restore if needed later.  Note that
        // we do not currently save the contents of the display.
        outState.putBoolean("fading", mFading);
    }

    @Override protected void onPause() {
        super.onPause();
        // Make sure to never run the fading pulse while we are paused or
        // stopped.
        stopFading();
    }

    /**
     * Start up the pulse to fade the screen, clearing any existing pulse to
     * ensure that we don't have multiple pulses running at a time.
     */
    void startFading() {
        mHandler.removeMessages(FADE_MSG);
        mHandler.sendMessageDelayed(
                mHandler.obtainMessage(FADE_MSG), FADE_DELAY);
    }

    /**
     * Stop the pulse to fade the screen.
     */
    void stopFading() {
        mHandler.removeMessages(FADE_MSG);
    }

    private Handler mHandler = new Handler() {
        @Override public void handleMessage(Message msg) {
            switch (msg.what) {
                // Upon receiving the fade pulse, we have the view perform a
                // fade and then enqueue a new message to pulse at the desired
                // next time.
                case FADE_MSG: {
                    mView.fade();
                    mHandler.sendMessageDelayed(
                            mHandler.obtainMessage(FADE_MSG), FADE_DELAY);
                    break;
                }
                default:
                    super.handleMessage(msg);
            }
        }
    };

    public class MyView extends View {
        private static final int FADE_ALPHA = 0x06;
        private static final int MAX_FADE_STEPS = 256/FADE_ALPHA + 4;
        private Bitmap mBitmap;
        private Canvas mCanvas;
        private final Rect mRect = new Rect();
        private final Paint mPaint;
        private final Paint mFadePaint;
        private boolean mCurDown;
        private int mCurX;
        private int mCurY;
        private float mCurPressure;
        private float mCurSize;
        private int mCurWidth;
        private int mFadeSteps = MAX_FADE_STEPS;

        public MyView(Context c) {
            super(c);
            mPaint = new Paint();
            mPaint.setAntiAlias(true);
            mPaint.setARGB(255, 255, 255, 255);
            mFadePaint = new Paint();
            mFadePaint.setDither(true);
            mFadePaint.setARGB(FADE_ALPHA, 0, 0, 0);
        }

        public void clear() {
            if (mCanvas != null) {
                mPaint.setARGB(0xff, 0, 0, 0);
                mCanvas.drawPaint(mPaint);
                invalidate();
                mFadeSteps = MAX_FADE_STEPS;
            }
        }

        public void fade() {
            if (mCanvas != null && mFadeSteps < MAX_FADE_STEPS) {
                mCanvas.drawPaint(mFadePaint);
                invalidate();
                mFadeSteps++;
            }
        }

        @Override protected void onSizeChanged(int w, int h, int oldw,
                int oldh) {
            int curW = mBitmap != null ? mBitmap.getWidth() : 0;
            int curH = mBitmap != null ? mBitmap.getHeight() : 0;
            if (curW >= w && curH >= h) {
                return;
            }

            if (curW < w) curW = w;
            if (curH < h) curH = h;

            Bitmap newBitmap = Bitmap.createBitmap(curW, curH,
                                                   Bitmap.Config.RGB_565);
            Canvas newCanvas = new Canvas();
            newCanvas.setBitmap(newBitmap);
            if (mBitmap != null) {
                newCanvas.drawBitmap(mBitmap, 0, 0, null);
            }
            mBitmap = newBitmap;
            mCanvas = newCanvas;
            mFadeSteps = MAX_FADE_STEPS;
        }

        @Override protected void onDraw(Canvas canvas) {
            if (mBitmap != null) {
                canvas.drawBitmap(mBitmap, 0, 0, null);
            }
        }

        @Override public boolean onTrackballEvent(MotionEvent event) {
            boolean oldDown = mCurDown;
            mCurDown = true;
            int N = event.getHistorySize();
            int baseX = mCurX;
            int baseY = mCurY;
            final float scaleX = event.getXPrecision();
            final float scaleY = event.getYPrecision();
            for (int i=0; i<N; i++) {
                //Log.i("TouchPaint", "Intermediate trackball #" + i
                //        + ": x=" + event.getHistoricalX(i)
                //        + ", y=" + event.getHistoricalY(i));
                drawPoint(baseX+event.getHistoricalX(i)*scaleX,
                        baseY+event.getHistoricalY(i)*scaleY,
                        event.getHistoricalPressure(i),
                        event.getHistoricalSize(i));
            }
            //Log.i("TouchPaint", "Trackball: x=" + event.getX()
            //        + ", y=" + event.getY());
            drawPoint(baseX+event.getX()*scaleX, baseY+event.getY()*scaleY,
                    event.getPressure(), event.getSize());
            mCurDown = oldDown;
            return true;
        }

        @Override public boolean onTouchEvent(MotionEvent event) {
            int action = event.getAction();
            mCurDown = action == MotionEvent.ACTION_DOWN
                    || action == MotionEvent.ACTION_MOVE;
            int N = event.getHistorySize();
            for (int i=0; i<N; i++) {
                //Log.i("TouchPaint", "Intermediate pointer #" + i);
                drawPoint(event.getHistoricalX(i), event.getHistoricalY(i),
                        event.getHistoricalPressure(i),
                        event.getHistoricalSize(i));
            }
            drawPoint(event.getX(), event.getY(), event.getPressure(),
                    event.getSize());
            return true;
        }

        private void drawPoint(float x, float y, float pressure, float size) {
            //Log.i("TouchPaint", "Drawing: " + x + "x" + y + " p="
            //        + pressure + " s=" + size);
            mCurX = (int)x;
            mCurY = (int)y;
            mCurPressure = pressure;
            mCurSize = size;
            mCurWidth = (int)(mCurSize*(getWidth()/3));
            if (mCurWidth < 1) mCurWidth = 1;
            if (mCurDown && mBitmap != null) {
                int pressureLevel = (int)(mCurPressure*255);
                mPaint.setARGB(pressureLevel, 255, 255, 255);
                mCanvas.drawCircle(mCurX, mCurY, mCurWidth, mPaint);
                mRect.set(mCurX-mCurWidth-2, mCurY-mCurWidth-2,
                        mCurX+mCurWidth+2, mCurY+mCurWidth+2);
                invalidate(mRect);
            }
            mFadeSteps = 0;
        }
    }
}


text:
package com.caseystella.pmml.config;

import com.caseystella.pmml.provider.ModelProvider;

import java.io.InputStream;

/**
 * Created by cstella on 1/30/15.
 */
public class Model  {
    String modelProviderClass;
    String modelLocation;
    public ModelProvider modelProvider() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //TODO: fill me in
        ModelProvider provider = (ModelProvider)(Class.forName(modelProviderClass).newInstance());
        return null;
    }

    public String getModelProviderClass() {
        return modelProviderClass;
    }

    public void setModelProviderClass(String modelProviderClass) {
        this.modelProviderClass = modelProviderClass;
    }

    public String getModelLocation() {
        return modelLocation;
    }

    public void setModelLocation(String modelLocation) {
        this.modelLocation = modelLocation;
    }

    public InputStream getModelStream() throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        return modelProvider().getModel(getModelLocation());
    }

}


text:
'use strict';
let // node modules
  httpProxy = require('http-proxy'),
  express = require('express'),
  debug = require('debug');

let // node stdLib
  fs = require('fs'),
  path = require('path'),
  url = require('url');

let
  server = express(),
  ad = httpProxy.createProxyServer({ changeOrigin: true }),
  dbgForward = debug('proxy:forward'),
  dbgServe = debug('proxy:serve');

const baseDir = 'build';
let dirs = ['fonts', 'libs', ''];

ad.on('proxyRes', function (proxyRes, req, res, options) {
  dbgForward(proxyRes.headers);

  // location header fix www.alldebrid.com -> localhost:3000
  if (proxyRes.headers.location) {
    let location = proxyRes.headers.location;
    if (!location.startsWith('http://www.alldebrid.com')) {
      proxyRes.headers.location = 'http://localhost:3000/ad';
      return;
    }

    let partialUrl = location.split('http://www.alldebrid.com')[1];
    dbgForward('fixing header Location', partialUrl);
    proxyRes.headers.location = 'http://localhost:3000/ad' + partialUrl;
  }
  // proxyRes.setHeader('X-Special-Proxy-Header', 'foobar');
});

/**
 * This section creates a list of urls to be served manually
 * by this script.
 * The array itself is an URL form, ex: /style.css or /libs/angular.js
 */
let localFiles = ['/'];
dirs.forEach(function (d) {
  let dirListing = fs.readdirSync(path.join(__dirname, baseDir, d))
  .map(function (file) {
    return [d, file].join('/');
  });
  localFiles = localFiles.concat(dirListing);
});
localFiles = localFiles.map(function (file) {
  return (file[0] === '/') ? file : '/' + file;
});

server.use(function (req, res, next) {
  let parsedUrl = url.parse(req.url);
  let pathname = parsedUrl.pathname;
  if (localFiles.indexOf(pathname) === -1) return next();
  dbgServe('Serving', pathname, 'by hand.');
  res.sendFile(pathname, { root: path.join(__dirname, 'build') });
});

server.use('/ad', function (req, res) {
  dbgForward('Forwarding request:', req.url);
  ad.web(req, res, { target: 'http://www.alldebrid.com' });
});

server.use('/torrent', function (req, res) {
  dbgForward('Forwarding request:', req.url);
  ad.web(req, res, { target: 'http://upload.alldebrid.com/uploadtorrent.php' });
});

if (require.main === module) {
  server.set('port', process.env.PORT || 3000);
  server.set('hostname', process.env.HOSTNAME || '127.0.0.1');

  let listen = server.listen(server.get('port'), server.get('hostname'), function () {
    console.log('\x1b[36m%s\x1b[0m %s', 'Express server listening on:', 'http://' + listen.address().address + ':' + listen.address().port + '/');
  });
}

module.exports = server;


text:
# Raw2HGui
Raw2H tool for Chaos Theory by Conspiracy

As I wanted to play around with "Chaos Theory" from Conspiracy I found that the raw2h tool was missing, so I coded m own tool.

Chaos Theory by Conspiracy.


text:
namespace dtn
{
	QuestAreaInfo * QuestAreaInfo::Instance=NULL;
	const string QuestAreaInfo::tag="QuestAreaInfo";
	const string QuestAreaInfo::host="127.0.0.1";
}


text:
package wvw.mobibench.devserv;

public interface DevServListener {

	public void ran();
}


text:
namespace app {
namespace Fuse {

::uEnumType* NodeEventMode__typeof();

}}

#endif


text:
'use strict';
const fs = require('fs');
const path = require('path');

fs.readdirSync(path.join(__dirname, 'api')).forEach((file) => {
	let f = path.join(__dirname, 'api', file);
	if (fs.statSync(f).isDirectory()) {
		exports[file] = require(f);
	}
});


text:
/* eslint-disable */
var fs = require('fs');
var path = require('path');
var babel = require('babel-core');
var origJs = require.extensions['.js'];

var cwd = process.cwd();
var fileNameRel, src, output;
var mockDir = path.join(__dirname, 'mocks');

// use babel for this node-modules
var nodeModulesBabel = [
  // add modules that require babel here
];

require.extensions['.js'] = function (module, fileName) {
  output = null;

  // strip off current working dir from path
  fileNameRel = fileName.replace(cwd + path.sep, '');

  // mock all requires of image-files
  if(fileName.search(/.*\.(png|jpg)$/gi) > -1) {
    return '';
  }

  // check if mock exists for file
  var mockFile = path.join(mockDir, fileNameRel);

  if(fs.existsSync(mockFile)) {
    src = fs.readFileSync(mockFile, 'utf8');
    output = babel.transform(src, {
      filename: fileName
    }).code;

    return module._compile(output, fileName);
  }

  // use nodemodules directly without babel
  if (fileName.search(/node_modules\//g) > -1) {
    // check if the nodemodule should explicit be compiled with babel
    var match = fileName.match(/node_modules\/([^\/]*)\//);

    if(!(match && match[1] && nodeModulesBabel.indexOf(match[1]) > -1)) {
      return (origJs || require.extensions['.js'])(module, fileName);
    }
  }

  // compile with babel
  src = fs.readFileSync(fileName, 'utf8');
  output = babel.transform(src, {
    filename: fileName
  }).code;

  return module._compile(output, fileName);
};
/* eslint-enable */


text:
package co.cask.tephra.persist;

import co.cask.tephra.TxConstants;
import co.cask.tephra.snapshot.DefaultSnapshotCodec;
import co.cask.tephra.snapshot.SnapshotCodecProvider;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.io.IOException;

/**
 * Runs transaction persistence tests against the {@link LocalFileTransactionStateStorage} and
 * {@link LocalFileTransactionLog} implementations.
 */
public class LocalTransactionStateStorageTest extends AbstractTransactionStateStorageTest {
  @ClassRule
  public static TemporaryFolder tmpDir = new TemporaryFolder();

  @Override
  protected Configuration getConfiguration(String testName) throws IOException {
    File testDir = tmpDir.newFolder(testName);
    Configuration conf = HBaseConfiguration.create();
    conf.set(TxConstants.Manager.CFG_TX_SNAPSHOT_LOCAL_DIR, testDir.getAbsolutePath());
    conf.set(TxConstants.Persist.CFG_TX_SNAPHOT_CODEC_CLASSES, DefaultSnapshotCodec.class.getName());

    return conf;
  }

  @Override
  protected AbstractTransactionStateStorage getStorage(Configuration conf) {
    return new LocalFileTransactionStateStorage(conf, new SnapshotCodecProvider(conf));
  }
}


text:
define(["app", "./PageLayout"], function(app, PageLayout){
	var layout = new PageLayout();

	app.container.show(layout);

	return layout;

});


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Graduate Research Fellowship Program</AwardTitle>
    <AwardEffectiveDate>11/01/2010</AwardEffectiveDate>
    <AwardExpirationDate>10/31/2017</AwardExpirationDate>
    <AwardAmount>1206667</AwardAmount>
    <AwardInstrument>
      <Value>Fellowship</Value>
    </AwardInstrument>
    <Organization>
      11010101
      <Directorate>
        <LongName>Direct For Education and Human Resources</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Graduate Education</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Gisele T. Muller-Parker</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration/>
    <MinAmdLetterDate>11/03/2010</MinAmdLetterDate>
    <MaxAmdLetterDate>12/16/2016</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1102689</AwardID>
    <Investigator>
      <FirstName>Jonathan</FirstName>
      <LastName>Cumming</LastName>
      <EmailAddress>jcumming@wvu.edu</EmailAddress>
      <StartDate>11/03/2010</StartDate>
      <EndDate>05/09/2013</EndDate>
      <RoleCode>Former Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>West Virginia University Research Corporation</Name>
      <CityName>Morgantown</CityName>
      <ZipCode>265066845</ZipCode>
      <PhoneNumber>3042933998</PhoneNumber>
      <StreetAddress>P.O. Box 6845</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>West Virginia</StateName>
      <StateCode>WV</StateCode>
    </Institution>
    <ProgramElement>
      7172
      <Text>GRADUATE RESEARCH FELLOWSHIPS</Text>
    </ProgramElement>
    <ProgramReference>
      7172
      <Text>GRADUATE FELLOWSHIPS</Text>
    </ProgramReference>
    <ProgramReference>
      9179
      <Text>GRADUATE INVOLVEMENT</Text>
    </ProgramReference>
    <ProgramReference>
      SMET
      <Text>SCIENCE, MATH, ENG & TECH EDUCATION</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
static inline CGFloat IFTTTMaxContentOffsetXForScrollView(UIScrollView *scrollView)
{
    return scrollView.contentSize.width + scrollView.contentInset.right - CGRectGetWidth(scrollView.bounds);
}

@interface IFTTTAnimatedScrollViewController ()
{
    CGFloat contentOffsetX_;
    CADisplayLink *timer_;
}

@property (nonatomic, assign) BOOL isAtEnd;

@end

@implementation IFTTTAnimatedScrollViewController

- (id)init
{
    if ((self = [super init])) {
        _isAtEnd = NO;
        self.animator = [IFTTTAnimator new];
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    contentOffsetX_ = self.scrollView.contentOffset.x;
//    self.scrollView.delegate = self;
    [self.view addSubview:self.scrollView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    timer_ = [CADisplayLink displayLinkWithTarget:self selector:@selector(scrollViewTimer)];
    [timer_ addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}

- (void)scrollViewTimer
{
    NSInteger time = (NSInteger)self.scrollView.contentOffset.x;
    [self.animator animate:time];

    self.isAtEnd = (self.scrollView.contentOffset.x >= IFTTTMaxContentOffsetXForScrollView(self.scrollView));

    id delegate = self.delegate;

    if (self.isAtEnd && [delegate respondsToSelector:@selector(animatedScrollViewControllerDidScrollToEnd:)]) {
        [delegate animatedScrollViewControllerDidScrollToEnd:self];
    }

    contentOffsetX_ += 5;
    CGPoint contentOffset = self.scrollView.contentOffset;
    self.scrollView.contentOffset = CGPointMake(contentOffsetX_, contentOffset.y);
    if (self.scrollView.contentSize.width <= contentOffsetX_) {
        [timer_ invalidate];
        timer_ = nil;
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)aScrollView
{
    NSInteger time = (NSInteger)aScrollView.contentOffset.x;
    [self.animator animate:time];

    self.isAtEnd = (aScrollView.contentOffset.x >= IFTTTMaxContentOffsetXForScrollView(aScrollView));

    id delegate = self.delegate;

    if (self.isAtEnd && [delegate respondsToSelector:@selector(animatedScrollViewControllerDidScrollToEnd:)]) {
        [delegate animatedScrollViewControllerDidScrollToEnd:self];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    id delegate = self.delegate;

    if (self.isAtEnd && [delegate respondsToSelector:@selector(animatedScrollViewControllerDidEndDraggingAtEnd:)]) {
        [delegate animatedScrollViewControllerDidEndDraggingAtEnd:self];
    }
}

@end


text:
class PiecesController < ApplicationController
	before_filter :get_piece_by_id, only: [ :show,
                                            :edit,
                                            :update,
                                            :destroy]

  def index
  	@pieces = Piece.all
  end

  def new
    @piece = Piece.new
  end

  def create
    @Piece = Piece.new(piece_params)

    if @Piece.save
      flash[:notice] = "Piece #{@Piece.title} has been created."
      redirect_to @Piece
    else
      flash[:alert] = "Piece has not been created."
      render "new"
    end
  end

  def edit
  end

  def update
    @piece.update(piece_params)
    flash[:notice] = "Piece #{@piece.title} has been updated."
    redirect_to @piece
  end

  def destroy
    piece_title=@piece.title
    @piece.destroy
    flash[:notice] = "Piece #{piece_title} has been deleted."
    redirect_to pieces_path
  end

  def show
  end

private
  def get_piece_by_id
  	@piece = Piece.where(:id => params[:id] ).first

    if !@piece
      flash[:alert] = "The piece you were looking for could not be found."
      redirect_to pieces_path
  	end
  end

  def piece_params
    params.require(:piece).permit(
      :title,
      :published,
      :instrumentation,
      :duration,
      :last_performed,
      :notes)
  end

end


text:
/**
 * LocalSvcLocator.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.2.1 Jun 14, 2005 (09:15:57 EDT) WSDL2Java emitter.
 */

package com.avalara.avatax.services.local;

import java.net.URL;
import java.net.MalformedURLException;

public class LocalSvcLocator extends org.apache.axis.client.Service implements com.avalara.avatax.services.local.LocalSvc {

    public LocalSvcLocator() {
    }

    public LocalSvcLocator(org.apache.axis.EngineConfiguration config) {
        super(config);
    }

    public LocalSvcLocator(java.lang.String wsdlLoc, javax.xml.namespace.QName sName) throws javax.xml.rpc.ServiceException {
        super(wsdlLoc, sName);
    }

    // Use to get a proxy class for LocalSvcSoap
    private java.lang.String LocalSvcSoap_address = "http://localhost:8080/AvaTaxLocal/Local/LocalSvc";

    public java.lang.String getLocalSvcSoapAddress() {
        return LocalSvcSoap_address;
    }

    // The WSDD service name defaults to the port name.
    private java.lang.String LocalSvcSoapWSDDServiceName = "LocalSvcSoap";

    public java.lang.String getLocalSvcSoapWSDDServiceName() {
        return LocalSvcSoapWSDDServiceName;
    }

    public void setLocalSvcSoapWSDDServiceName(java.lang.String name) {
        LocalSvcSoapWSDDServiceName = name;
    }

    public com.avalara.avatax.services.local.LocalSvcSoap getLocalSvcSoap() throws javax.xml.rpc.ServiceException {
       java.net.URL endpoint;
        try {
            endpoint = new java.net.URL(LocalSvcSoap_address);
        }
        catch (java.net.MalformedURLException e) {
            throw new javax.xml.rpc.ServiceException(e);
        }
        return getLocalSvcSoap(endpoint);
    }

    public com.avalara.avatax.services.local.LocalSvcSoap getLocalSvcSoap(java.net.URL portAddress) throws javax.xml.rpc.ServiceException {
        try {
             // BEGIN CUSTOM
            String path = portAddress.toString();
            path += "/local/localsvc";
            portAddress = new URL(path);
            // END CUSTOM
            com.avalara.avatax.services.local.LocalSvcSoapStub _stub = new com.avalara.avatax.services.local.LocalSvcSoapStub(portAddress, this);
            _stub.setPortName(getLocalSvcSoapWSDDServiceName());
            return _stub;
        }
        catch (org.apache.axis.AxisFault e) {
            return null;
        }
        // BEGIN CUSTOM
        catch (MalformedURLException e)
        {
            return null;
        }
        // END CUSTOM
    }

    public void setLocalSvcSoapEndpointAddress(java.lang.String address) {
        LocalSvcSoap_address = address;
    }

    /**
     * For the given interface, get the stub implementation.
     * If this service has no port for the given interface,
     * then ServiceException is thrown.
     */
    public java.rmi.Remote getPort(Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
        try {
            if (com.avalara.avatax.services.local.LocalSvcSoap.class.isAssignableFrom(serviceEndpointInterface)) {
                com.avalara.avatax.services.local.LocalSvcSoapStub _stub = new com.avalara.avatax.services.local.LocalSvcSoapStub(new java.net.URL(LocalSvcSoap_address), this);
                _stub.setPortName(getLocalSvcSoapWSDDServiceName());
                return _stub;
            }
        }
        catch (java.lang.Throwable t) {
            throw new javax.xml.rpc.ServiceException(t);
        }
        throw new javax.xml.rpc.ServiceException("There is no stub implementation for the interface:  " + (serviceEndpointInterface == null ? "null" : serviceEndpointInterface.getName()));
    }

    /**
     * For the given interface, get the stub implementation.
     * If this service has no port for the given interface,
     * then ServiceException is thrown.
     */
    public java.rmi.Remote getPort(javax.xml.namespace.QName portName, Class serviceEndpointInterface) throws javax.xml.rpc.ServiceException {
        if (portName == null) {
            return getPort(serviceEndpointInterface);
        }
        java.lang.String inputPortName = portName.getLocalPart();
        if ("LocalSvcSoap".equals(inputPortName)) {
            return getLocalSvcSoap();
        }
        else  {
            java.rmi.Remote _stub = getPort(serviceEndpointInterface);
            ((org.apache.axis.client.Stub) _stub).setPortName(portName);
            return _stub;
        }
    }

    public javax.xml.namespace.QName getServiceName() {
        return new javax.xml.namespace.QName("http://avatax.avalara.com/services", "LocalSvc");
    }

    private java.util.HashSet ports = null;

    public java.util.Iterator getPorts() {
        if (ports == null) {
            ports = new java.util.HashSet();
            ports.add(new javax.xml.namespace.QName("http://avatax.avalara.com/services", "LocalSvcSoap"));
        }
        return ports.iterator();
    }

    /**
    * Set the endpoint address for the specified port name.
    */
    public void setEndpointAddress(java.lang.String portName, java.lang.String address) throws javax.xml.rpc.ServiceException {

if ("LocalSvcSoap".equals(portName)) {
            setLocalSvcSoapEndpointAddress(address);
        }
        else
{ // Unknown Port Name
            throw new javax.xml.rpc.ServiceException(" Cannot set Endpoint Address for Unknown Port" + portName);
        }
    }

    /**
    * Set the endpoint address for the specified port name.
    */
    public void setEndpointAddress(javax.xml.namespace.QName portName, java.lang.String address) throws javax.xml.rpc.ServiceException {
        setEndpointAddress(portName.getLocalPart(), address);
    }

}


text:
package storm.cookbook;

import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * User: domenicosolazzo
 */
public class RepeatVisitBolt extends BaseRichBolt {

    private OutputCollector collector;

    private Jedis jedis;
    private String host;
    private int port;

    @Override
    public void prepare(Map conf, TopologyContext topologyContext, OutputCollector outputCollector) {
        this.collector = outputCollector;
        host = conf.get(Conf.REDIS_HOST_KEY).toString();
        port = Integer.valueOf(conf.get(Conf.REDIS_PORT_KEY).toString());
        connectToRedis();
    }

    private void connectToRedis(){
        jedis = new Jedis(host, port);
        jedis.connect();
    }

    public boolean isConnected(){
        if(jedis == null){
            return false;
        }
        return jedis.isConnected();
    }

    @Override
    public void execute(Tuple tuple) {
        String ip = tuple.getStringByField(storm.cookbook.Fields.IP);
        String clientKey = tuple.getStringByField(Fields.CLIENT_KEY);
        String url = tuple.getStringByField(storm.cookbook.Fields.URL);
        String key = url + ":" + clientKey;
        String value = jedis.get(key);
        if(value == null){
            jedis.set(key, "visited");
            collector.emit(new Values(clientKey, Boolean.TRUE.toString()));
        }else{
            collector.emit(new Values(clientKey, Boolean.FALSE.toString()));
        }
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer) {
        outputFieldsDeclarer.declare(new backtype.storm.tuple.Fields(Fields.CLIENT_KEY,
                Fields.URL, Fields.UNIQUE));
    }
}


text:
package org.apache.lucene.analysis.uima;

import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.uima.analysis_engine.AnalysisEngineProcessException;
import org.apache.uima.cas.CASException;
import org.apache.uima.cas.FeaturePath;
import org.apache.uima.cas.Type;
import org.apache.uima.cas.text.AnnotationFS;

import java.io.IOException;
import java.io.Reader;

/**
 * A {@link Tokenizer} which creates token from UIMA Annotations filling also their {@link TypeAttribute} according to
 * {@link org.apache.uima.cas.FeaturePath}s specified
 */
public final class UIMATypeAwareAnnotationsTokenizer extends BaseUIMATokenizer {

  private final TypeAttribute typeAttr;

  private final CharTermAttribute termAttr;

  private final OffsetAttribute offsetAttr;

  private final String tokenTypeString;

  private final String typeAttributeFeaturePath;

  private FeaturePath featurePath;

  private int finalOffset = 0;

  public UIMATypeAwareAnnotationsTokenizer(String descriptorPath, String tokenType, String typeAttributeFeaturePath, Reader input) {
    super(input, descriptorPath);
    this.tokenTypeString = tokenType;
    this.termAttr = addAttribute(CharTermAttribute.class);
    this.typeAttr = addAttribute(TypeAttribute.class);
    this.offsetAttr = addAttribute(OffsetAttribute.class);
    this.typeAttributeFeaturePath = typeAttributeFeaturePath;
  }

  protected void initializeIterator() throws IOException {
    try {
      analyzeInput();
    } catch (AnalysisEngineProcessException e) {
      throw new IOException(e);
    }
    featurePath = cas.createFeaturePath();
    try {
      featurePath.initialize(typeAttributeFeaturePath);
    } catch (CASException e) {
      featurePath = null;
      throw new IOException(e);
    }
    finalOffset = correctOffset(cas.getDocumentText().length());
    Type tokenType = cas.getTypeSystem().getType(tokenTypeString);
    iterator = cas.getAnnotationIndex(tokenType).iterator();

  }

  @Override
  public boolean incrementToken() throws IOException {
    if (iterator == null) {
      initializeIterator();
    }
    if (iterator.hasNext()) {
      clearAttributes();
      AnnotationFS next = iterator.next();
      termAttr.append(next.getCoveredText());
      offsetAttr.setOffset(correctOffset(next.getBegin()), correctOffset(next.getEnd()));
      typeAttr.setType(featurePath.getValueAsString(next));
      return true;
    } else {
      return false;
    }
  }

  @Override
  public void end() throws IOException {
    offsetAttr.setOffset(finalOffset, finalOffset);
    super.end();
  }

}


text:
const moment              = require('moment');
const Client              = require('../../../../base/client');
const toJapanTimeIfNeeded = require('../../../../base/clock').toJapanTimeIfNeeded;
const formatCurrency      = require('../../../../common/currency').formatCurrency;
const formatMoney         = require('../../../../common/currency').formatMoney;
const localize            = require('../../../../../_common/localize').localize;
const toTitleCase         = require('../../../../../_common/string_util').toTitleCase;

const Statement = (() => {
    const getStatementData = (statement, currency, jp_client) => {
        const date_obj   = new Date(statement.transaction_time * 1000);
        const moment_obj = moment.utc(date_obj);
        const date_str   = moment_obj.format('YYYY-MM-DD');
        const time_str   = `${moment_obj.format('HH:mm:ss')} GMT`;
        const payout     = parseFloat(statement.payout);
        const amount     = parseFloat(statement.amount);
        const balance    = parseFloat(statement.balance_after);
        const is_ico_bid = /binaryico/i.test(statement.shortcode); // TODO: remove ico exception when all ico contracts are removed

        let action = toTitleCase(statement.action_type);
        if (is_ico_bid) {
            action = /buy/i.test(statement.action_type) ? localize('Bid') : localize('Closed Bid');
        }

        return {
            action,
            date   : jp_client ? toJapanTimeIfNeeded(+statement.transaction_time) : `${date_str}\n${time_str}`,
            ref    : statement.transaction_id,
            payout : isNaN(payout) || is_ico_bid || !+payout ? '-' : formatMoney(currency, payout, !jp_client),
            amount : isNaN(amount) ? '-' : formatMoney(currency, amount, !jp_client),
            balance: isNaN(balance) ? '-' : formatMoney(currency, balance, !jp_client),
            desc   : statement.longcode.replace(/\n/g, '
'),
            id     : statement.contract_id,
            app_id : statement.app_id,
        };
    };

    const generateCSV = (all_data, jp_client) => {
        const columns  = ['date', 'ref', 'payout', 'action', 'desc', 'amount', 'balance'];
        const header   = ['Date', 'Reference ID', 'Potential Payout', 'Action', 'Description', 'Credit/Debit'].map(str => (localize(str)));
        const currency = Client.get('currency');
        header.push(localize('Balance') + (jp_client || !currency ? '' : ` (${currency})`));
        const sep = ',';
        let csv   = [header.join(sep)];
        if (all_data && all_data.length > 0) {
            // eslint-disable-next-line no-control-regex
            csv = csv.concat(all_data.map(data => columns.map(key => (data[key] ? data[key].replace(formatCurrency(currency), '¥').replace(new RegExp(sep, 'g'), '').replace(new RegExp('\n|
', 'g'), ' ') : '')).join(sep)));
        }
        return csv.join('\r\n');
    };

    return {
        getStatementData,
        generateCSV,
    };
})();

module.exports = Statement;


text:
'''Move a resource from one parent client to another

Usage:
    exo [options] move <cik> <rid> <destinationrid>

Command Options:
    --no-aliases  If present then do not move aliases

Command Options:
{{ helpoption }}
'''

class Plugin():
    def command(self):
        return 'move'

    def run(self, cmd, args, options):
        rpc = options['rpc']
        cik = options['cik']
        rid = options['rids'][0]
        destinationrid = args['<destinationrid>']
        noaliases = args['--no-aliases']
        if noaliases:
            rpc.move(cik, rid, destinationrid, {'aliases': False})
        else:
            rpc.move(cik, rid, destinationrid, {'aliases': True})


text: .u,.typography u{display:inline;text-decoration:underline;@apply (--u)}


text:
import imp
import config
import database

from bottle import view
from bottle import route
from bottle import request
from bottle import response
from bottle import redirect
from bottle import mako_view as view
from bottle import mako_template as template

from services.installer import installservice
from services.datetimehelper import dthelper

@route("/install", method="GET")
@route("/install", method="POST")
@view("install.html")
def install():
	if "btnSubmit" in request.all:
		installservice.setupConfigFile(
			dbServer      = request.all["databaseServer"],
			dbName        = request.all["databaseName"],
			dbUser        = request.all["databaseUserName"],
			dbPass        = request.all["databasePassword"],
			blogTitle     = request.all["blogTitle"],
			postsPerPage  = request.all["postsPerPage"],
			hashKey1      = request.all["hashKey1"],
			hashKey2      = request.all["hashKey2"],
			encryptionKey = request.all["encryptionKey"],
			encryptionIV  = request.all["encryptionIV"]
		)

		installservice.setupDatabase(
			dbServer  = request.all["databaseServer"],
			dbPort    = 3306,
			dbName    = request.all["databaseName"],
			dbUser    = request.all["databaseUserName"],
			dbPass    = request.all["databasePassword"],
			email     = request.all["adminEmail"],
			password  = request.all["adminPassword"],
			firstName = request.all["adminFirstName"],
			lastName  = request.all["adminLastName"],
			timezone  = request.all["timezone"],
			hashKey1  = request.all["hashKey1"],
			hashKey2  = request.all["hashKey2"],
		)

		database.disconnect()
		imp.reload(config)

		database.connect(
			engine   = "mysql",
			host     = config.ENVIRONMENT["DB_HOST"],
			port     = config.ENVIRONMENT["DB_PORT"],
			database = config.ENVIRONMENT["DB_NAME"],
			user     = config.ENVIRONMENT["DB_USER"],
			password = config.ENVIRONMENT["DB_PASSWORD"]
		)

		redirect("/installcomplete")

	return {
		"timezones": dthelper.getTimezoneArray()
	}

@route("/installcomplete", method="GET")
@view("installcomplete.html")
def installComplete():
	return {}


text:
using System;
using UnityEngine;

namespace AppCenterEditor
{
    class LocalLogger: IEdExLogger
    {
        public void LogWithTimeStamp(string message)
        {
            Debug.Log(GetUniqueMessage(message));
        }

        public void LogWarning(string message)
        {
            Debug.LogWarning(GetUniqueMessage(message));
        }

        public void LogError(string message)
        {
            Debug.LogError(GetUniqueMessage(message));
        }

        public void Log(string message)
        {
            Debug.Log(message);
        }

        private string GetUniqueMessage(string message)
        {
            // Return unique message in order to distinguish similar messages.
            return string.Format("[App Center EdEx MSG{0}] {1}", DateTime.Now.Millisecond, message);
        }
    }
}


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-for',
  templateUrl: './for.component.html'
})
export class ForComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}


text:
Kate Rakelly, Aurick Zhou, Deirdre Quillen, Chelsea Finn, Sergey Levine
(Submitted on 19 Mar 2019)
Deep reinforcement learning algorithms require large amounts of experience to learn an individual task.

While in principle meta-reinforcement learning (meta-RL) algorithms enable agents to learn new skills from small amounts of experience, several major challenges preclude their practicality.

Current methods rely heavily on on-policy experience, limiting their sample efficiency.

They also lack mechanisms to reason about task uncertainty when adapting to new tasks, limiting their effectiveness in sparse reward problems.

In this paper, we address these challenges by developing an off-policy meta-RL algorithm that disentangles task inference and control.

In our approach, we perform online probabilistic filtering of latent task variables to infer how to solve a new task from small amounts of experience.

This probabilistic interpretation enables posterior sampling for structured and efficient exploration.

We demonstrate how to integrate these task variables with off-policy RL algorithms to achieve both meta-training and adaptation efficiency.

Our method outperforms prior algorithms in sample efficiency by 20-100X as well as in asymptotic performance on several meta-RL benchmarks.


text: export { Tram20 as default } from "../../";


text:
module Peek
  class ResultsController < ApplicationController
    before_filter :restrict_non_access

    def show
      respond_to do |format|
        format.json do
          if request.xhr?
            render :json => Peek.adapter.get(params[:request_id])
          else
            render :nothing => true, :status => :not_found
          end
        end
      end
    end

    private

    def restrict_non_access
      unless peek_enabled?
        raise ActionController::RoutingError.new('Not Found')
      end
    end
  end
end


text:
class OrnithologyException(Exception):
    pass

class NoJobEventLog(OrnithologyException):
    pass

class DaemonLogParsingFailed(OrnithologyException):
    pass


text:
#include "Parser.h"
#include "Builder.h"
#include "Completion.h"
#include "Program.h"
#include <zlib.h>
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;

#include "output/GringoOutput.h"
#include "output/StreamCreator.h"
#include "output/WBOOutput.h"

void SIGINT_interrupt(int) {
    bool ret = false;
    sleep(1);
    exit(ret ? 10 : 1);
}

void printIncoherence(const preasp::Program& program) {
    switch( program.options.printOption()) {
        case PRINT_GRINGO: {
            preasp::GringoOutput g;
            g.printIncoherentProgram(cout);
        }
            break;

        case PRINT_EXTENDED_DIMACS: {
            preasp::StreamCreator s(cout);
            s.printIncoherence();
        }
            break;

        case PRINT_WBO: {
            preasp::WBOOutput o(cout);
            o.printIncoherence();
        }
            break;

        default:
            break;
    }
}

unsigned int buildExtendedDimacs(preasp::Program& program) {
    preasp::Completion c(new preasp::StreamCreator(cout));
    c.execute(program);
    return 0;
}

unsigned int buildWBO(preasp::Program& program) {
    if(!program.tight()) { cerr << "Error: only tight programs are supported for opb format." << endl; exit(-1); }

    preasp::Completion c(new preasp::WBOOutput(cout));
    c.execute(program);
    return 0;
}

unsigned int printGringoProgram(preasp::Program& program) {
    preasp::GringoOutput g;
    g.printCoherentProgram(program, cout);
    return 0;
}

bool pre(gzFile& input_stream, preasp::Program& program) {
    preasp::StreamBuffer in(input_stream);
    preasp::Builder builder(program);
    preasp::Parser parser(in, builder);
    if(program.options.verbosity()>=1) cerr << "Start parser" << endl;
    parser.parseGringo();
    if(program.options.verbosity()>=1) cerr << "End parser" << endl;
    gzclose(input_stream);

    if(!builder.simplify()) { printIncoherence(program); return false; }
    if(program.options.printOption() != PRINT_GRINGO) builder.computeSCC();

    return true;
}

int main(int argc, char** argv) {
    if(argc > 2) { cerr << "Extra argument: " << argv[2] << endl; exit(-1); }
    gzFile input_stream = argc == 1 ? gzdopen(0, "rb") : gzopen(argv[1], "rb");
    if(input_stream == NULL) cerr << "Cannot open file " << (argc == 1 ? "STDIN" : argv[1]) << endl, exit(-1);
    preasp::Program program;
    if(!pre(input_stream, program)) return 0;

    if(program.options.printOption() == PRINT_WBO) return buildWBO(program);
    if(program.options.printOption() == PRINT_EXTENDED_DIMACS) return buildExtendedDimacs(program);
    return printGringoProgram(program);
}


text:
'use strict';
angular.module('datatablesSampleApp').controller('apiCtrl', function($scope, DTOptionsBuilder) {
    $scope.dtOptions = DTOptionsBuilder.newOptions()
        .withDisplayLength(10)
        .withColReorder()
        .withColVis()
        .withOption('bAutoWidth', false)
        .withTableTools('../../vendor/datatables-tabletools/swf/copy_csv_xls_pdf.swf');
});


text:
title: Using GitHub AMQP Hook
tags: [IT, GitHub, AMQP, Ruby, WebSockets, Redis]
---

#1 RabbitMQ & GitHub

RabbitMQ

Install RabbitMQ. On Debian, it's apt-get install rabbitmq-server.

RabbitMQ provides a default user guest with password guest. It's a good thing for development, but in production you want to remove the default user because of security. You can do so by running rabbitmqctl delete_user guest.

Of course you need a user, so let's create one: rabbitmqctl add_user github_notificator password.

GitHub Hooks

#2 Client Daemon

#!/usr/bin/env ruby
# encoding: utf-8

require "json"
require "amq/client"
require "amq/client/adapters/event_machine"
require "amq/client/queue"
require "em-websocket"

EM.run do
  AMQ::Client::EventMachineClient.connect do |client|
    channel = AMQ::Client::Channel.new(client, 1)
    channel.open do |method|
      Subscription.slugs.each do |slug|
        queue = AMQ::Client::Queue.new(client, channel, slug)
        queue.consume(true)
        queue.on_delivery do |method, header, body|
          data = JSON.parse(body)["payload"]
          Subscription.get(queue.name) << data
        end
      end
    end
  end
end

#3 Redis

# encoding: utf-8

require "redis"
require "json"

class Subscription
  # @return [Redis] Cached redis instance.
  def self.redis
    @redis ||= Redis.new
  end

  def self.slugs
    self.redis.lrange("slugs", 0, -1)
  end

  # @return [Subscription] New Subscription instance with commits.
  def self.get(slug)
    key  = self.redis.hget(slug, "pattern")
    data = self.redis.lrange(key, 0, -1)
    data.map! { |json| JSON.parse(json) }
    self.new(key, data)
  end

  # {slug => {name: name, pattern: pattern}}
  def self.create(name, slug, pattern)
    self.redis.multi do
      @redis.rpush("slugs", slug)
      @redis.hset(slug, "name", name)
      @redis.hset(slug, "pattern", pattern)
    end

    self.amqp_subscribe(slug, pattern)
  end

  def self.amqp_subscribe(queue_name, routing_pattern)
    require "amq/client"
    require "amq/client/adapters/event_machine"
    require "amq/client/queue"

    EM.run do
      AMQ::Client::EventMachineClient.connect do |client|
        channel = AMQ::Client::Channel.new(client, 1)
        channel.open do |method|
          queue = AMQ::Client::Queue.new(client, channel, queue_name)
          queue.declare(false, true) do |method|
            queue.bind("github", routing_pattern) do |method|
              EM.stop
            end
          end
        end
      end
    end
  end

  attr_reader :data
  def initialize(key, data = Array.new)
    @key, @data = key, data
  end

  def push(commit)
    index = self.class.redis.rpush(@key, commit.to_json)
    self.class.redis.ltrim(@key, 0, 20 - 2)
    return commit
  end
  alias_method :<<, :push

  def destroy
    self.class.redis.del(@key)
  end
end

#4 WebSockets

#!/usr/bin/env ruby
# encoding: utf-8

require "json"
require "amq/client"
require "amq/client/adapters/event_machine"
require "amq/client/queue"
require "em-websocket"

EM.run do
  EM::WebSocket.start(host: "0.0.0.0", port: 8080) do |socket|
    AMQ::Client::EventMachineClient.connect do |client|
      channel = AMQ::Client::Channel.new(client, 1)
      channel.open do |method|
        Subscription.slugs.each do |slug|
          queue = AMQ::Client::Queue.new(client, channel, slug)
          queue.consume(true)
          queue.on_delivery do |method, header, body|
            data = JSON.parse(body)["payload"]

            # 1) Store to Redis.
            Subscription.get(queue.name) << data

            # 2) Notify clients via websockets.
            socket.send({slug => data}.to_json)
          end
        end
      end
    end
  end
end


text:
class BlockManager : public ActorManager
{
    public:
        BlockManager();
        ~BlockManager();

        void Initialize();
        virtual bool IsColliding(const Actor &actor, ActorPtr collider) override;

        //
        // Events
        //
        void OnFireExtinguished(IEventPtr pEvent);
};

typedef std::shared_ptr<BlockManager> BlockManagerPtr;

#endif //__BLOCKMANAGER_H_


text:
getFieldName() }}">{{ $field->getLabel() }}
<input type="password"
       class="form-control"
       id="{{ $field->getFieldName() }}"
       name="{{ $field->getFieldName() }}">
@if ($errors->has($field->getFieldName()))

        {{ $errors->first($field->getFieldName()) }}

@endif


text:
//
//  SDLSendLocation.h
//  SmartDeviceLink

#import "SDLRPCRequest.h"

#import <CoreGraphics/CGBase.h>

#import "SDLDateTime.h"
#import "SDLDeliveryMode.h"
#import "SDLImage.h"
#import "SDLOasisAddress.h"

NS_ASSUME_NONNULL_BEGIN

@interface SDLSendLocation : SDLRPCRequest

- (instancetype)initWithLongitude:(double)longitude latitude:(double)latitude locationName:(nullable NSString *)locationName locationDescription:(nullable NSString *)locationDescription address:(nullable NSArray<NSString *> *)address phoneNumber:(nullable NSString *)phoneNumber image:(nullable SDLImage *)image;

- (instancetype)initWithLongitude:(double)longitude latitude:(double)latitude locationName:(nullable NSString *)locationName locationDescription:(nullable NSString *)locationDescription displayAddressLines:(nullable NSArray<NSString *> *)displayAddressLines phoneNumber:(nullable NSString *)phoneNumber image:(nullable SDLImage *)image deliveryMode:(nullable SDLDeliveryMode)deliveryMode timeStamp:(nullable SDLDateTime *)timeStamp address:(nullable SDLOasisAddress *)address;

/**
 * The longitudinal coordinate of the location.
 *
 * Float, Required, -180.0 - 180.0
 */
@property (nullable, copy, nonatomic) NSNumber<SDLFloat> *longitudeDegrees;

/**
 * The latitudinal coordinate of the location.
 *
 * Float, Required, -90.0 - 90.0
 */
@property (nullable, copy, nonatomic) NSNumber<SDLFloat> *latitudeDegrees;

/**
 * Name / title of intended location
 *
 * Optional, Maxlength = 500 char
 */
@property (nullable, copy, nonatomic) NSString *locationName;

/**
 * Description of the intended location / establishment
 *
 * Optional, MaxLength = 500 char
 */
@property (nullable, copy, nonatomic) NSString *locationDescription;

/**
 * Location address for display purposes only
 *
 * Contains String, Optional, Max Array Length = 4, Max String Length = 500
 */
@property (nullable, copy, nonatomic) NSArray<NSString *> *addressLines;

/**
 * Phone number of intended location / establishment
 *
 * Optional, Max Length = 500
 */
@property (nullable, copy, nonatomic) NSString *phoneNumber;

/**
 * Image / icon of intended location
 *
 * Optional
 */
@property (nullable, strong, nonatomic) SDLImage *locationImage;

/**
 * Mode in which the sendLocation request is sent
 *
 * Optional
 */
@property (nullable, strong, nonatomic) SDLDeliveryMode deliveryMode;

/**
 * Arrival time of Location. If multiple SendLocations are sent, this will be used for sorting as well.
 *
 * Optional
 */
@property (nullable, strong, nonatomic) SDLDateTime *timeStamp;

/**
 * Address to be used for setting destination
 *
 * Optional
 */
@property (nullable, strong, nonatomic) SDLOasisAddress *address;

@end

NS_ASSUME_NONNULL_END


text:
"""Runs football_env on OpenAI's ppo2."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import multiprocessing
import os
from absl import app
from absl import flags
from baselines import logger
from baselines.bench import monitor
from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv
from baselines.ppo2 import ppo2
import gfootball.env as football_env
from gfootball.examples import models

FLAGS = flags.FLAGS

flags.DEFINE_string('level', 'academy_empty_goal_close',
                    'Defines type of problem being solved')
flags.DEFINE_enum('state', 'extracted_stacked', ['extracted',
                                                 'extracted_stacked'],
                  'Observation to be used for training.')
flags.DEFINE_enum('reward_experiment', 'scoring',
                  ['scoring', 'scoring,checkpoints'],
                  'Reward to be used for training.')
flags.DEFINE_enum('policy', 'cnn', ['cnn', 'lstm', 'mlp', 'impala_cnn',
                                    'gfootball_impala_cnn'],
                  'Policy architecture')
flags.DEFINE_integer('num_timesteps', int(2e6),
                     'Number of timesteps to run for.')
flags.DEFINE_integer('num_envs', 8,
                     'Number of environments to run in parallel.')
flags.DEFINE_integer('nsteps', 128, 'Number of environment steps per epoch; '
                     'batch size is nsteps * nenv')
flags.DEFINE_integer('noptepochs', 4, 'Number of updates per epoch.')
flags.DEFINE_integer('nminibatches', 8,
                     'Number of minibatches to split one epoch to.')
flags.DEFINE_integer('save_interval', 100,
                     'How frequently checkpoints are saved.')
flags.DEFINE_integer('seed', 0, 'Random seed.')
flags.DEFINE_float('lr', 0.00008, 'Learning rate')
flags.DEFINE_float('ent_coef', 0.01, 'Entropy coeficient')
flags.DEFINE_float('gamma', 0.993, 'Discount factor')
flags.DEFINE_float('cliprange', 0.27, 'Clip range')
flags.DEFINE_float('max_grad_norm', 0.5, 'Max gradient norm (clipping)')
flags.DEFINE_bool('render', False, 'If True, environment rendering is enabled.')
flags.DEFINE_bool('dump_full_episodes', False,
                  'If True, trace is dumped after every episode.')
flags.DEFINE_bool('dump_scores', False,
                  'If True, sampled traces after scoring are dumped.')
flags.DEFINE_string('load_path', None, 'Path to load initial checkpoint from.')

def create_single_football_env(iprocess):
  """Creates gfootball environment."""
  env = football_env.create_environment(
      env_name=FLAGS.level, stacked=('stacked' in FLAGS.state),
      rewards=FLAGS.reward_experiment,
      logdir=logger.get_dir(),
      write_goal_dumps=FLAGS.dump_scores and (iprocess == 0),
      write_full_episode_dumps=FLAGS.dump_full_episodes and (iprocess == 0),
      render=FLAGS.render and (iprocess == 0),
      dump_frequency=50 if FLAGS.render and iprocess == 0 else 0)
  env = monitor.Monitor(env, logger.get_dir() and os.path.join(logger.get_dir(),
                                                               str(iprocess)))
  return env

def train(_):
  """Trains a PPO2 policy."""
  vec_env = SubprocVecEnv([
      (lambda _i=i: create_single_football_env(_i))
      for i in range(FLAGS.num_envs)
  ], context=None)

  # Import tensorflow after we create environments. TF is not fork sake, and
  # we could be using TF as part of environment if one of the players is
  # controlled by an already trained model.
  import tensorflow.compat.v1 as tf
  ncpu = multiprocessing.cpu_count()
  config = tf.ConfigProto(allow_soft_placement=True,
                          intra_op_parallelism_threads=ncpu,
                          inter_op_parallelism_threads=ncpu)
  config.gpu_options.allow_growth = True
  tf.Session(config=config).__enter__()

  ppo2.learn(network=FLAGS.policy,
             total_timesteps=FLAGS.num_timesteps,
             env=vec_env,
             seed=FLAGS.seed,
             nsteps=FLAGS.nsteps,
             nminibatches=FLAGS.nminibatches,
             noptepochs=FLAGS.noptepochs,
             max_grad_norm=FLAGS.max_grad_norm,
             gamma=FLAGS.gamma,
             ent_coef=FLAGS.ent_coef,
             lr=FLAGS.lr,
             log_interval=1,
             save_interval=FLAGS.save_interval,
             cliprange=FLAGS.cliprange,
             load_path=FLAGS.load_path)

if __name__ == '__main__':
  app.run(train)


text:
AmaranJS jQuery Notification Plugin
============
Nice, sleek and stylish notifications.

[Demo & Documentation](http://hakanersu.github.io/AmaranJS/)

> [AmaranJS Laravel 5 Package](https://github.com/hakanersu/amaran-laravel)

You can test  AmaranJS & Animate.css effects [ Test Tool ](http://codepen.io/hakanersu/pen/iqzJA)

## What is new and What is changed

 * Blur Theme ,Rounded Theme and Read More theme removed.
 * All javascript codes ported to coffee and css to sass.
 * [Animate.css](http://daneden.github.io/animate.css/) and options added for alternative css3 effects.

## Some Features

Here is the some basic features of AmaranJS.But i  recommend that review the examples and check demos.

 * Easy notification creation.
 * Unique notification animations.
 * Included stylish themes.
 * Easily adapt your own themes.
 * Callbacks

## Installation

Go to dist directory and copy all the folders to a new destination, which will be your project home.

It's not required, but i recommend placing CSS files in ```<head>``` and JavaScript files and initialization code in the footer of your site (before the closing ```</body>``` tag).

jQuery required for **Amaran JS**.If you already have jquery.js on your site, don't include it a second time, or use **jQuery.noConflict();** mode

```html
<link rel="stylesheet" href="/css/amaran.min.css">
```
You can add jQuery via Google CDN

```html
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
```

Place Amaran JS after jQuery

```html
<script src="/js/jquery.amaran.js"></script>
```
So minimalistic setup look like this

```html
<!DOCTYPE html>
<html>
<head>
    <title>My Web Page</title>
    <link rel="stylesheet" href="/css/amaran.min.css">
</head>
<body>
    <p>My Content</p>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="/js/jquery.amaran.js"></script>
</body>
</html>
```

### Optional Steps

 * Awesome theme uses fontawesome if you want to use  awesome theme you have to include fontawesome.

```html
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
```
 * If you want to use [Animate.css](http://daneden.github.io/animate.css/) effects you have to include [Animate.css](http://daneden.github.io/animate.css/) . [Animate.css](http://daneden.github.io/animate.css/) already included dist/css folder.

```html
<link rel="stylesheet" href="/css/animate.min.css">
```
## Usage
AmaranJS included 4 theme (for now).

Very basic usage ,not include any theme.
```javascript
$(function(){
    $.amaran({'message':'My first example!'});
});
```
If you want to use included themes , you have to pass content object with desired fields.

Awesome theme usage.

```javascript
$.amaran({
    content:{
        title:'My first funcy example!',
        message:'1.4 GB',
        info:'my_birthday.mp4',
        icon:'fa fa-download'
    },
    theme:'awesome ok'
});

```


text:
require "stractor/parser"
require "stractor/template"
require "stractor/version"

module Stractor
  def self.parse(content, template)
    Stractor::Parser.new(content, Template.new(template)).matches
  end
end


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.github.somi92.seecsk.gui;

import com.github.somi92.seecsk.data.Sesija;
import com.github.somi92.seecsk.data.report.NalogZaUplatu;
import com.github.somi92.seecsk.data.report.ReportGenerator;
import com.github.somi92.seecsk.util.email.EmailContainer;
import com.github.somi92.seecskcommon.domain.Clan;
import com.github.somi92.seecskcommon.domain.Clanarina;
import com.github.somi92.seecskcommon.util.Config;
import com.github.somi92.seecskcommon.util.Constants;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.MouseMotionListener;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import net.sf.jasperreports.engine.JRException;
import org.apache.pdfbox.pdfviewer.PDFPagePanel;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

/**
 *
 * @author milos
 */
public class FInvoice extends javax.swing.JDialog {

    private Clan clan;
    private List<Clanarina> clanarine;
    private String uplatnicaFile;

    /**
     * Creates new form FInvoice
     */
    public FInvoice(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        clan = (Clan) Sesija.vratiInstancu().vratiMapuSesije().get(Sesija.CLAN);
        clanarine = (List<Clanarina>) Sesija.vratiInstancu().vratiMapuSesije().get(Sesija.LISTA);
        Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.CLAN, null);
        Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.LISTA, null);
        initForm();
//        jpnlUplatnica.setVisible(false);
//        setSize(getSize().width, getSize().height-320);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jcmbClanarina = new javax.swing.JComboBox();
        jtxtIznos = new javax.swing.JTextField();
        jtxtZiroRacun = new javax.swing.JTextField();
        jtxtModel = new javax.swing.JTextField();
        jtxtPozivNaBroj = new javax.swing.JTextField();
        jbtnKreirajUplatnicu = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtxtSvrhaUplate = new javax.swing.JTextArea();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtxtPrimalac = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        jtxtUplatilac = new javax.swing.JTextArea();
        jPanel2 = new javax.swing.JPanel();
        jpnlUplatnica = new javax.swing.JPanel();
        jbtnPosalji = new javax.swing.JButton();
        jbtnNazad = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Kreiraj uplatnicu");
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Za članarinu:");

        jLabel2.setText("Iznos:");

        jLabel3.setText("Žiro račun:");

        jLabel4.setText("Model:");

        jLabel5.setText("Poziv na broj:");

        jcmbClanarina.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        jcmbClanarina.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcmbClanarinaActionPerformed(evt);
            }
        });

        jtxtIznos.setHorizontalAlignment(javax.swing.JTextField.TRAILING);

        jtxtZiroRacun.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        jtxtModel.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        jtxtPozivNaBroj.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        jtxtPozivNaBroj.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtxtPozivNaBrojActionPerformed(evt);
            }
        });

        jbtnKreirajUplatnicu.setText("Kreiraj uplatnicu");
        jbtnKreirajUplatnicu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnKreirajUplatnicuActionPerformed(evt);
            }
        });

        jLabel6.setText("Uplatilac:");

        jLabel7.setText("Svrha uplate:");

        jLabel8.setText("Primalac:");

        jtxtSvrhaUplate.setColumns(20);
        jtxtSvrhaUplate.setLineWrap(true);
        jtxtSvrhaUplate.setRows(5);
        jtxtSvrhaUplate.setWrapStyleWord(true);
        jScrollPane1.setViewportView(jtxtSvrhaUplate);

        jtxtPrimalac.setColumns(20);
        jtxtPrimalac.setLineWrap(true);
        jtxtPrimalac.setRows(5);
        jtxtPrimalac.setWrapStyleWord(true);
        jScrollPane2.setViewportView(jtxtPrimalac);

        jtxtUplatilac.setColumns(20);
        jtxtUplatilac.setLineWrap(true);
        jtxtUplatilac.setRows(5);
        jtxtUplatilac.setWrapStyleWord(true);
        jScrollPane3.setViewportView(jtxtUplatilac);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addComponent(jLabel8, javax.swing.GroupLayout.DEFAULT_SIZE, 112, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jtxtZiroRacun, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(jtxtIznos, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addComponent(jcmbClanarina, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jtxtModel, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(57, 57, 57)
                                .addComponent(jbtnKreirajUplatnicu, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jtxtPozivNaBroj, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jLabel5))))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(15, 15, 15)
                        .addComponent(jLabel1)
                        .addGap(39, 39, 39)
                        .addComponent(jLabel6))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jcmbClanarina, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtxtIznos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(33, 33, 33)
                                .addComponent(jLabel7)
                                .addGap(49, 49, 49)
                                .addComponent(jLabel8))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jtxtZiroRacun, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(78, 78, 78)
                                        .addComponent(jbtnKreirajUplatnicu))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(18, 18, 18)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jLabel4)
                                            .addComponent(jLabel5))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(jtxtModel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(jtxtPozivNaBroj, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))))))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jpnlUplatnica.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        javax.swing.GroupLayout jpnlUplatnicaLayout = new javax.swing.GroupLayout(jpnlUplatnica);
        jpnlUplatnica.setLayout(jpnlUplatnicaLayout);
        jpnlUplatnicaLayout.setHorizontalGroup(
            jpnlUplatnicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jpnlUplatnicaLayout.setVerticalGroup(
            jpnlUplatnicaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 345, Short.MAX_VALUE)
        );

        jbtnPosalji.setText("Pošalji uplatnicu");
        jbtnPosalji.setEnabled(false);
        jbtnPosalji.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnPosaljiActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpnlUplatnica, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jbtnPosalji, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jpnlUplatnica, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbtnPosalji)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        jbtnNazad.setText("Nazad");
        jbtnNazad.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNazadActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jbtnNazad, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jbtnNazad)
                .addContainerGap(9, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jtxtPozivNaBrojActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtxtPozivNaBrojActionPerformed

    }//GEN-LAST:event_jtxtPozivNaBrojActionPerformed

    private void jcmbClanarinaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcmbClanarinaActionPerformed
        popuniSvrhuUplate();
    }//GEN-LAST:event_jcmbClanarinaActionPerformed

    private void jbtnKreirajUplatnicuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnKreirajUplatnicuActionPerformed
        try {
            String uplatilac = jtxtUplatilac.getText().trim();
            String svrhaUplate = jtxtSvrhaUplate.getText().trim();
            String primalac = jtxtPrimalac.getText().trim();
            String ziroRacun = jtxtZiroRacun.getText().trim();
            String model = jtxtModel.getText().trim();
            String poziv = jtxtPozivNaBroj.getText().trim();
            double iznos = Double.parseDouble(jtxtIznos.getText().trim());

            if(uplatilac == null || uplatilac.isEmpty() || svrhaUplate == null || svrhaUplate.isEmpty() ||
                    primalac == null || primalac.isEmpty() || ziroRacun == null ||  ziroRacun.isEmpty() ||
                    model == null || model.isEmpty() || poziv == null || poziv.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Sva polja moraju biti popunjena!");
                return;
            }

            NalogZaUplatu n = new NalogZaUplatu();
            n.setId(clan.getIdClan());
            n.setUplatilac(uplatilac);
            n.setPrimalac(primalac);
            n.setSvrhaUplate(svrhaUplate);
            n.setIznos(iznos);
            n.setRacunPrimaoca(ziroRacun);
            n.setModel(model);
            n.setPozivNaBroj(poziv);

            ReportGenerator.generateInvoice(n);

//            dispose();

//            jpnlUplatnica.setVisible(true);
//            setSize(getSize().width, getSize().height+320);

            uplatnicaFile = Constants.LocationConfigKeys.TEMP_INVOICE_LOCATION+"uplatnica_"+clan.getIdClan()+".pdf";
            File pdfFile = new File(uplatnicaFile);
            PDDocument doc = PDDocument.load(pdfFile);
            List<PDPage> pages = doc.getDocumentCatalog().getAllPages();
            PDPage page = (PDPage) pages.get(0);

            PDFPagePanel pdfPanel = new PDFPagePanel();
            pdfPanel.setPage(page);

            JInternalFrame iFrame = new JInternalFrame();

            BasicInternalFrameUI ui = (BasicInternalFrameUI) iFrame.getUI();
            Component np = ui.getNorthPane();
            Container cont = (Container) np;
            cont.remove(0);
            cont.validate();
            cont.repaint();
            MouseMotionListener[] mmlisteners = (MouseMotionListener[]) np.getListeners(MouseMotionListener.class);
            for(MouseMotionListener mml : mmlisteners) {
                np.removeMouseMotionListener(mml);
            }
            iFrame.setEnabled(false);

            iFrame.setBounds(0, 0, jpnlUplatnica.getWidth(), jpnlUplatnica.getHeight());
            jpnlUplatnica.add(iFrame);
            iFrame.add(pdfPanel);
            iFrame.setVisible(true);
            iFrame.setResizable(false);
            iFrame.setSelected(false);

            pdfPanel.setVisible(true);
            jbtnPosalji.setEnabled(true);

        } catch (NumberFormatException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Neispravno unet iznos.", "Greška", JOptionPane.ERROR_MESSAGE);
        } catch (PropertyVetoException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "Sistem ne može učitati uplatnicu (PVE).", "Greška", JOptionPane.ERROR_MESSAGE);
        } catch (IOException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "Sistem ne može učitati uplatnicu (IO).", "Greška", JOptionPane.ERROR_MESSAGE);
        } catch (JRException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "Sistem ne može učitati uplatnicu (JRE).", "Greška", JOptionPane.ERROR_MESSAGE);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, "Sistem ne može učitati uplatnicu (CNF).", "Greška", JOptionPane.ERROR_MESSAGE);
        } catch (RuntimeException ex){
            ex.printStackTrace();
            JOptionPane.showMessageDialog(this, ex.getMessage(), "Greška", JOptionPane.ERROR_MESSAGE);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_jbtnKreirajUplatnicuActionPerformed

    private void jbtnPosaljiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnPosaljiActionPerformed
        EmailContainer ec = new EmailContainer();
        ec.setToEmail(clan.getEmail());
        ec.setFromEmail(Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_EMAIL));
        ec.setSubject(Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_NAME)+
                " - Podsetnik za članarinu");
        ec.setMessage((clan.getPol()=='M' ? "Poštovani" : "Poštovana") +
                ", \n\nObaveštavamo Vas da imate neizmirena dugovanja za članarinu. U prilogu ove poruke"
                + " imate primer ispravno popunjene uplatnice sa detaljnijim informacijama o dugovanju. "
                + "Molimo Vas da u najkraćem roku izvršite uplatu. Više informacija možete dobiti na email"
                + " "+Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_EMAIL)+" ili "
                + "pozivom na broj "+Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_PHONE_NUMBER)+
                        ".\n\nSrdačan pozdrav,\n"+Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_NAME));
        ec.setAttachmentPath(uplatnicaFile);
        Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.EMAIL, ec);
        FEmailSender femail = new FEmailSender(null, true);
        femail.setVisible(true);
        boolean res = femail.getReturnValue();
        if(res) {
            dispose();
        }
    }//GEN-LAST:event_jbtnPosaljiActionPerformed

    private void jbtnNazadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNazadActionPerformed
        dispose();
    }//GEN-LAST:event_jbtnNazadActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JButton jbtnKreirajUplatnicu;
    private javax.swing.JButton jbtnNazad;
    private javax.swing.JButton jbtnPosalji;
    private javax.swing.JComboBox jcmbClanarina;
    private javax.swing.JPanel jpnlUplatnica;
    private javax.swing.JTextField jtxtIznos;
    private javax.swing.JTextField jtxtModel;
    private javax.swing.JTextField jtxtPozivNaBroj;
    private javax.swing.JTextArea jtxtPrimalac;
    private javax.swing.JTextArea jtxtSvrhaUplate;
    private javax.swing.JTextArea jtxtUplatilac;
    private javax.swing.JTextField jtxtZiroRacun;
    // End of variables declaration//GEN-END:variables

    private void initForm() {

        setTitle("Uplatnica za: "+clan.getImePrezime());

        jcmbClanarina.removeAllItems();
        jcmbClanarina.addItem("Sve članarine");
        for(Clanarina clanarina : clanarine) {
            jcmbClanarina.addItem(clanarina);
        }
        jtxtZiroRacun.setText("321-1199232593211-32");
        jtxtModel.setText("93");
//        jtxtPozivNaBroj.setText("442133214");
        String pozivNaBroj = "01125";
        pozivNaBroj = clan.getIdClan() + pozivNaBroj;
        int rest = 12-pozivNaBroj.length();
        if(rest>0) {
            for(int i=0; i<rest; i++) {
                pozivNaBroj = "0"+pozivNaBroj;
            }
        }
        jtxtPozivNaBroj.setText(pozivNaBroj);
        jtxtIznos.setText("2000.0");

        jtxtUplatilac.setText(clan.getImePrezime()+", "+clan.getAdresa());
        jtxtPrimalac.setText(Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_NAME)+", "
                + Config.vratiInstancu().vratiVrednost(Constants.OrgInfoConfigKeys.ORGANISATION_ADDRESS));

        popuniSvrhuUplate();
    }

    private void popuniSvrhuUplate() {
        if(clanarine != null) {
            Object o = jcmbClanarina.getSelectedItem();
            if(o != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy.");
                if(jcmbClanarina.getSelectedItem() instanceof String) {
                    jtxtSvrhaUplate.setText("Članarina za period "+sdf.format(clanarine.get(0).getDatumOd())+
                        " - "+sdf.format(clanarine.get(clanarine.size()-1).getDatumDo()));
                } else {
                    Clanarina c = (Clanarina) jcmbClanarina.getSelectedItem();
                    jtxtSvrhaUplate.setText("Članarina za period "+sdf.format(c.getDatumOd())+
                            " - "+sdf.format(c.getDatumDo()));
                }
            }
        }
    }
}


text:
// -*-  Mode:ObjC; c-basic-offset:4; tab-width:8; indent-tabs-mode:nil -*-

// Web API

#define ENABLE_KAKAKUCOM   0
#define ENABLE_RAKUTEN     1

#import <UIKit/UIKit.h>
#import "Common.h"
#import "Item.h"
#import "HttpClient.h"

@class WebApi;

// error codes
#define WEBAPI_ERROR_NETWORK	0
#define WEBAPI_ERROR_NOTFOUND	1
#define WEBAPI_ERROR_BADREPLY   2
#define WEBAPI_ERROR_BADPARAM   3

// service ids
enum {
    AmazonUS = 0,
    AmazonCA,
    AmazonUK,
    AmazonFR,
    AmazonDE,
    AmazonJP,
#if ENABLE_RAKUTEN
    Rakuten,
#endif
    Yahoo,
#if ENABLE_KAKAKUCOM
    KakakuCom,
#endif

    MaxServiceId
};

// search key types
typedef NS_ENUM(unsigned int, SearchKeyType) {
    SearchKeyCode = 0,
    SearchKeyTitle,
    SearchKeyAuthor,
    SearchKeyArtist,
    SearchKeyAll
};

/**
   Web API delegate protocol
*/
@protocol WebApiDelegate
/**
   Called when web API is successfully finished

   @param[in] webApi webApi instance
   @param[in] items Found items array
*/
-(void)webApiDidFinish:(WebApi*)webApi items:(NSMutableArray*)items;

/**
   Called when web API is failed.

   @param[in] webApi WebApi instance
   @param[in] reason Reason code
   @param[in] message Error message
*/
-(void)webApiDidFailed:(WebApi*)amazonApi reason:(NSInteger)reason message:(NSString *)message;
@end

/**
   Web API factory
*/
@interface WebApiFactory : NSObject {
    NSInteger serviceId;
    BOOL isCodeSearch;
}

@property(nonatomic, assign) NSInteger serviceId;

+ (WebApiFactory *)webApiFactory;
- (void)setCodeSearch;
- (void)loadDefaults;
- (void)saveDefaults;
- (NSInteger)_fallbackServiceId;
- (NSInteger)serviceIdFromCountryCode:(NSString*)country;
- (WebApi*)allocWebApi;
- (NSArray*)serviceIdStrings;
- (NSString*)serviceIdString;

+ (NSString *)detailUrl:(Item *)item isMobile:(BOOL)isMobile;

@end

/**
   Web API

   Base class of web api (amazon, kakaku.com etc.)

   To search items, create the instance of derived class of WebApi.
   set delegate, set parameters, then call itemSearch.

   The result will be passed with webApiDelegate protocol.
*/
@interface WebApi : NSObject <HttpClientDelegate> {
    id<WebApiDelegate> __unsafe_unretained delegate;

    NSInteger serviceId;      	///< serviceId

    NSString *searchKey;        ///< Key for search (barcode / title / any keyword)
    SearchKeyType searchKeyType;
    NSString *searchIndex;      ///< Search index (category)

    HttpClient *mHttpClient;
}

@property(nonatomic, unsafe_unretained) id<WebApiDelegate> delegate;
@property(nonatomic, strong) NSString *searchKey;
@property(nonatomic, assign) SearchKeyType searchKeyType;
@property(nonatomic, strong) NSString *searchIndex;

- (void)itemSearch;
- (void)setServiceId:(NSInteger)sid;

- (NSArray *)categoryStrings;
- (NSInteger)defaultCategoryIndex;

// used by derived class
- (void)sendHttpRequest:(NSURL*)url;

@end