text:
package info.pinlab.ttada.cache.disk;

import info.pinlab.ttada.core.cache.CacheLevel;
import info.pinlab.ttada.core.cache.LocalCache;
import info.pinlab.ttada.core.cache.Pointer;
import info.pinlab.ttada.core.ser.SimpleJsonSerializer;
import info.pinlab.utils.FileStringTools;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

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

/**
 *
 * Write data to local HDD
 *
 * Wraps DiskCacheHandler for put, get, remove
 *
 * @author Gabor Pinter
 *
 */
public class DiskCache implements LocalCache{
	public static final Logger logger = LoggerFactory.getLogger(DiskCache.class);
	public static final String SEP = FileStringTools.SEP; // System.getProperty("file.separator");
	public static final String EXT = ".gz";

	private final File rootDir;
	private final Map<Class<?>, Class<?>> interFaceMap;
	private final Map<String, Class<?>> tag2ClassMap;
	private SimpleJsonSerializer jsonAdapter;
	Map<Class<?>, TypeCacher<?>> typeMap;

	private static final CacheLevel level = new DiskCacheLevel();
	private static final class DiskCacheLevel implements CacheLevel{
		private static final String levelTag = "loc";
		@Override
		public String getPrefix() {
			return levelTag;
		}
	}

	private DiskCache(
			File rootDir,
			Map<Class<?>, Class<?>> ifMap,
			Map<String, Class<?>> tag2ClazzMap,
			SimpleJsonSerializer adapter
			){
		this.rootDir = rootDir;
		//-- create root dir if does not exist! --//
		if(!rootDir.exists()){
			if(!rootDir.mkdirs()){
				logger.error("Couldn't create root dir for cache! '" + rootDir.getAbsolutePath() +"'");
			}else{
				logger.info("Creating root dir for cache! '" + rootDir.getAbsolutePath() +"'");
			}
		}

		this.tag2ClassMap = tag2ClazzMap;
		this.interFaceMap = ifMap;
		this.jsonAdapter = adapter;

		typeMap = new HashMap<Class<?>, TypeCacher<?>>();
	}

	public static class DiskCacheBuilder{
		//-- default cache root --//
		private File root = null;
		//-- maps --//
		private Map<Class<?>, Class<?>> interFaceMap = new HashMap<Class<?>, Class<?>>();
		private Map<String, Class<?>> tag2ClassMap = new HashMap<String, Class<?>>();
		private SimpleJsonSerializer jsonAdapter = null;
//		private boolean isSaveTextResponseAsText = true;
//		private boolean isSaveWavResponseAsText = true;
//		private File responseTxtFile = null;

		public DiskCacheBuilder(){};

		/**
		 * Create cache builder with all the data give cache
		 *
		 * @param cache  copy settings from here
		 */
		public DiskCacheBuilder(DiskCache cache){
			this.root = cache.getRootDir();
			this.jsonAdapter = cache.jsonAdapter;
			this.interFaceMap = cache.interFaceMap;
			this.tag2ClassMap = cache.tag2ClassMap;
//			this.responseTxtFile = cache.getTextResponseFile();
//			this.isSaveTextResponseAsText = cache.isSaveTxtResp;
//			this.isSaveWavResponseAsText = cache.isSaveWavResp;
//			this.responseTxtFile = cache.getTextResponseFile();
		}

		public DiskCacheBuilder setDiskCacheRootPath(File root){
			if (root==null || root.getPath().isEmpty()){
				throw new IllegalArgumentException("Disk cache root dir can't be null!");
			}
			if(!root.isAbsolute()){
				throw new IllegalArgumentException("Only absolute path can be the Local Cache root! vs '" + root + "'");
			}
			this.root = root;
			return this;
		}
		public DiskCacheBuilder setTag2ClassMap(Map<String, Class<?>> map){
			this.tag2ClassMap = map;
			return this;
		}
		public DiskCacheBuilder setClassInterfaceMap(Map<Class<?>, Class<?>> map){
			this.interFaceMap = map;
			return this;
		}
		public DiskCacheBuilder setJsonAdapter(SimpleJsonSerializer adapter){
			jsonAdapter = adapter;
			return this;
		}

//		public DiskCacheBuilder isSaveRespTextOnTheFly(boolean b){
//			isSaveTextResponseAsText = b;
//			return this;
//		}
//		public DiskCacheBuilder isSaveRespWavOnTheFly(boolean b){
//			isSaveWavResponseAsText = b;
//			return this;
//		}
//		public DiskCacheBuilder setTxtResponseFile(File f){
//			if(f!=null){
//				isSaveTextResponseAsText = true;
//			}
//			responseTxtFile = f;
//			return this;
//		}

		/**
		 *
		 * @return Immutable {@link DiskCache} instance.
		 *
		 * @throws IllegalStateException if json adapter is not set. Json adapter is a compulsory.
		 */
		public DiskCache build(){
			if(this.jsonAdapter==null){
				throw new IllegalArgumentException("Json adapter cannot be null! Please setJsonAdapter()!");
			}

			if(root==null){
				//-- fallback disk cache folder, if not set --//
				root = new File(System.getProperty("user.home")+ DiskCache.SEP + ".pin" + DiskCache.SEP+ "cache" + DiskCache.SEP).getAbsoluteFile();
				setDiskCacheRootPath(root);
			}
			DiskCache cache = new DiskCache(
					root,
					interFaceMap, tag2ClassMap,
					jsonAdapter		);

			//-- house keeping --//
			cache.discoverDiskCache();

			return cache;
		}
	}

	void discoverDiskCache(){
		if(!rootDir.isDirectory()){
			logger.warn("No root directory for cache! '" + rootDir.getAbsolutePath() +"'");
			return;
		}

		for(String dir : rootDir.list()){
			File classCachePath = new File (rootDir + SEP  + dir);
			if(classCachePath.isDirectory()){
				try{
					Class<?> clazz = tag2ClassMap.get(dir);
					if (clazz!=null){
						if(interFaceMap.containsKey(clazz)){
							clazz = interFaceMap.get(clazz);
						}
						TypeCacher<?> cacher = this.getOrCreateTypeCacher(clazz);
						cacher.parseDir();
					}
				}catch(IllegalArgumentException e){
					logger.warn("Can't parse dir '" +dir +"'" , e);
					continue;
				}
			}
		}
	}

	@Override
	public CacheLevel getLevel() {
		return level;
	}

	@SuppressWarnings("unchecked")
	private <T> TypeCacher<T> getOrCreateTypeCacher(Class<T> clazz){
		if(typeMap.containsKey(clazz)){
			return (TypeCacher<T>)typeMap.get(clazz);
		}else{
			File typeRootDir = new File(rootDir + SEP + clazz.getSimpleName());
			TypeCacher<T> typeCacher = new TypeCacher<T>(clazz, typeRootDir, jsonAdapter);
			typeMap.put(clazz, typeCacher);
			return typeCacher;
		}
	}

	@Override
	public <T> Pointer put(T obj, Class<T> clazz){
		TypeCacher<T> cacher = getOrCreateTypeCacher(clazz);
		return cacher.put(obj);
	}

	@Override
	public <T> T get(Pointer ptr, Class<T> clazz) {
		TypeCacher<T> cacher = getOrCreateTypeCacher(clazz);
		return cacher.get(ptr);
	}

	@Override
	public <T> void remove(Pointer ptr, Class<T> clazz) {
		TypeCacher<T> cacher = getOrCreateTypeCacher(clazz);
		cacher.remove(ptr);
	}
	public static CacheLevel getCacheLevel(){
		return level;
	}

//	@Override
//	public void isSaveTextResponseAsText(boolean b) {
////		DiskCacheHandler.isSaveTextResponseAsText(b);
//		isSaveTextResponseAsText = b;
//	}
//
//	@Override
//	public void isSaveAudioResponseAsWav(boolean b) {
////		DiskCacheHandler.isSaveAudioResponseAsWav(b);
//		isSaveAudioResponseAsWav = b;
//
//	}

	@Override
	public File getRootDir() {
		return rootDir;
	}

//	@Override
//	public File getTextResponseFile() {
//		if(respSaver == null){
//			return null;
//		}
//		return respSaver.getResponseTxtFile();
//	}
//
//
//	@Override
//	public boolean isSaveTextResponse() {
//		return respSaver != null;
//	}
//
//	public void dispose(){
//		respSaver.dispose();
//	}
}


text:
package nguyengiap.vietitpro.tudienanhviet.com.model;

/**
 * Created by DungPT17 on 2016/06/16.
 */
public class EVEntity {
    private String word;
    private String means;
    private String phonic;
    private String simpleMeans;

    public EVEntity() {
    }

    public EVEntity(String word) {
        this.word = word;
    }

    public EVEntity(String word, String means) {
        this.word = word;
        this.means = means;
    }

    public EVEntity(String word, String means, String phonic) {
        this.word = word;
        this.means = means;
        this.phonic = phonic;
    }

    public EVEntity(String word, String means, String phonic, String simpleMeans) {
        this.word = word;
        this.means = means;
        this.phonic = phonic;
        this.simpleMeans = simpleMeans;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public String getMeans() {
        return means;
    }

    public void setMeans(String means) {
        this.means = means;
    }

    public String getPhonic() {
        return phonic;
    }

    public void setPhonic(String phonic) {
        this.phonic = phonic;
    }

    public String getSimpleMeans() {
        return simpleMeans;
    }

    public void setSimpleMeans(String simpleMeans) {
        this.simpleMeans = simpleMeans;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Org\Schema\Thing\Place\LocalBusiness;

/**
 * Class ShoppingCenter
 * A shopping center or mall.
 * @author      AppBels <app.bels@gmail.com>
 * @name        ShoppingCenter
 * @namespace   Org\Schema\Thing\Place\LocalBusiness
 * @package     Org\Schema
 * @see         https://schema.org/ShoppingCenter
 * Date         09/04/2017
 */
class ShoppingCenter extends \Org\Schema\Thing\Place\LocalBusiness
{

	/**
	 * ShoppingCenter constructor.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\LocalBusiness::__construct()
	 */
	public function __construct ()
	{
		parent::__construct();
	}

	/**
	 * ShoppingCenter toString.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\LocalBusiness::__toString()
	 *
	 * @return  string
	 */
	public function __toString ()
	{
		return parent::__toString();
	}

	/**
	 * ShoppingCenter destructor.
	 * @access  public
	 * @see     \Org\Schema\Thing\Place\LocalBusiness::__destruct()
	 */
	public function __destruct ()
	{
		parent::__destruct();
	}

}

?>


text:
var gulp = require('gulp');
var _ = require('underscore');
var batch = require('gulp-batch');
var Elixir = require('laravel-elixir');

/*
 |----------------------------------------------------------------
 | Watcher
 |----------------------------------------------------------------
 |
 | When you want to keep an eye on your files for changes, and
 | then re-trigger Gulp, then you should use the gulp watch
 | command. This way, you can auto-compile on each save!
 |
 */

gulp.task('watch', function() {
    var tasks = _.sortBy(Elixir.tasks, 'name');
    var mergedTasks = {};

    if (isWatchingBrowserify(tasks)) {
        Elixir.config.js.browserify.watchify.enabled = true;

        gulp.start('browserify');
    }

    tasks.forEach(function(task) {
        if (task.name in mergedTasks) {
            return mergedTasks[task.name].watchers = _.union(mergedTasks[task.name].watchers, task.watchers);
        }

        mergedTasks[task.name] = {
            name: task.name,
            watchers: Array.isArray(task.watchers) ? task.watchers : [task.watchers]
        };
    });

    _.sortBy(mergedTasks, 'name').forEach(function(task) {
        if (task.watchers.length > 0) {
            gulp.watch(task.watchers, batch(Elixir.config.batchOptions, function(events) {
                events.on('end', gulp.start(task.name));
            }));
        }
    });
});

/**
 * Determine if Browserify is included in the list.
 *
 * @param  {object} tasks
 * @return {boolean}
 */
var isWatchingBrowserify = function(tasks) {
    return _.contains(_.pluck(tasks, 'name'), 'browserify');
};


text:
#pragma once

#include <generatorBase/masterGeneratorBase.h>

#include "iotikGeneratorBaseDeclSpec.h"

namespace iotik {

/// Master generator base implementation for every generator from IoTik kit
class ROBOTS_IOTIK_GENERATOR_BASE_EXPORT IotikMasterGeneratorBase : public generatorBase::MasterGeneratorBase
{
public:
	IotikMasterGeneratorBase(const qrRepo::RepoApi &repo
			, qReal::ErrorReporterInterface &errorReporter
			, const utils::ParserErrorReporter &parserErrorReporter
			, const kitBase::robotModel::RobotModelManagerInterface &robotModelManager
			, qrtext::LanguageToolboxInterface &textLanguage
			, const qReal::Id &diagramId
			, const QStringList &pathsToTemplates);

protected:
	generatorBase::GeneratorCustomizer *createCustomizer() override;
	void afterGeneration() override;

private:
	const QString inputCode(const QString &path);
	void renameThreads(QString &code);

	const QStringList mPathsToTemplates;
};

}


text:
package org.praisenter.ui.slide;

import org.praisenter.data.TextItem;
import org.praisenter.data.TextType;
import org.praisenter.data.TextVariant;
import org.praisenter.data.slide.Slide;
import org.praisenter.ui.GlobalContext;

import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;

final class SlideListCell extends ListCell<Slide> {
	private static final String SLIDE_LIST_CELL_CLASS = "p-slide-list-cell";
	private static final String SLIDE_LIST_CELL_SLIDE_VIEW_CLASS = "p-slide-list-cell-slide-view";

	private final SlideView view;

	public SlideListCell(GlobalContext context) {
		this.getStyleClass().add(SLIDE_LIST_CELL_CLASS);

		this.view = new SlideView(context);
		this.view.setAutoHideEnabled(false);
		this.view.setCheckeredBackgroundEnabled(true);
		this.view.setFitToWidthEnabled(true);
		this.view.setFitToHeightEnabled(true);
		this.view.setViewMode(SlideMode.VIEW);
		this.view.setViewScaleAlignCenter(true);
		this.view.getStyleClass().add(SLIDE_LIST_CELL_SLIDE_VIEW_CLASS);

		this.setText(null);
		this.setGraphic(null);
		this.setContentDisplay(ContentDisplay.BOTTOM);

		this.itemProperty().addListener((obs, oldItem, newItem) -> {
	        if (newItem != null) {
	        	String name = newItem.getName();
	        	if (newItem.hasPlaceholders()) {
	        		TextItem txt = newItem.getPlaceholderData().get(TextVariant.PRIMARY, TextType.TITLE);
	        		if (txt != null) {
	        			String replacedName = txt.getText();
	        			if (replacedName != null && !replacedName.isBlank()) {
	        				name = replacedName;
	        			}
	        		}
	        	}
	        	this.setText(name);
	        	this.view.setSlide(newItem);
	        }
	    });

	    this.emptyProperty().addListener((obs, wasEmpty, isEmpty) -> {
	        if (isEmpty) {
	        	this.setText(null);
	            this.setGraphic(null);
	        } else {
	            this.setGraphic(this.view);
	        }
	    });
	}
}


text:
goog.provide('goog.net.FileDownloaderTest');
goog.setTestOnly('goog.net.FileDownloaderTest');

goog.require('goog.fs.Error');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.FileDownloader');
goog.require('goog.net.XhrIo');
goog.require('goog.testing.PropertyReplacer');
goog.require('goog.testing.TestCase');
goog.require('goog.testing.fs');
goog.require('goog.testing.fs.FileSystem');
goog.require('goog.testing.jsunit');
goog.require('goog.testing.net.XhrIoPool');

var xhrIoPool, xhr, fs, dir, downloader;

function setUpPage() {
  goog.testing.fs.install(new goog.testing.PropertyReplacer());
  goog.testing.TestCase.getActiveTestCase().promiseTimeout = 10000;  // 10s
}

function setUp() {
  xhrIoPool = new goog.testing.net.XhrIoPool();
  xhr = xhrIoPool.getXhr();
  fs = new goog.testing.fs.FileSystem();
  dir = fs.getRoot();
  downloader = new goog.net.FileDownloader(dir, xhrIoPool);
}

function tearDown() {
  goog.dispose(downloader);
}

function testDownload() {
  var promise = downloader.download('/foo/bar').then(function(blob) {
    var fileEntry = dir.getFileSync('`3fa/``2Ffoo`2Fbar/`bar');
    assertEquals('data', blob.toString());
    assertEquals('data', fileEntry.fileSync().toString());
  });

  xhr.simulateResponse(200, 'data');
  assertEquals('/foo/bar', xhr.getLastUri());
  assertEquals(goog.net.XhrIo.ResponseType.ARRAY_BUFFER, xhr.getResponseType());

  return promise;
}

function testGetDownloadedBlob() {
  var promise =
      downloader.download('/foo/bar')
          .then(function() { return downloader.getDownloadedBlob('/foo/bar'); })
          .then(function(blob) { assertEquals('data', blob.toString()); });

  xhr.simulateResponse(200, 'data');
  return promise;
}

function testGetLocalUrl() {
  var promise =
      downloader.download('/foo/bar')
          .then(function() { return downloader.getLocalUrl('/foo/bar'); })
          .then(function(url) { assertMatches(/\/`bar$/, url); });

  xhr.simulateResponse(200, 'data');
  return promise;
}

function testLocalUrlWithContentDisposition() {
  var promise =
      downloader.download('/foo/bar')
          .then(function() { return downloader.getLocalUrl('/foo/bar'); })
          .then(function(url) { assertMatches(/\/`qux`22bap$/, url); });

  xhr.simulateResponse(
      200, 'data', {'Content-Disposition': 'attachment; filename="qux\\"bap"'});
  return promise;
}

function testIsDownloaded() {
  var promise =
      downloader.download('/foo/bar')
          .then(function() { return downloader.isDownloaded('/foo/bar'); })
          .then(assertTrue)
          .then(function(isDownloaded) {
            return downloader.isDownloaded('/foo/baz');
          })
          .then(assertFalse);

  xhr.simulateResponse(200, 'data');
  return promise;
}

function testRemove() {
  var promise =
      downloader.download('/foo/bar')
          .then(function() { return downloader.remove('/foo/bar'); })
          .then(function() { return downloader.isDownloaded('/foo/bar'); })
          .then(assertFalse)
          .then(function() { return downloader.getDownloadedBlob('/foo/bar'); })
          .then(
              function() {
                fail('Should not be able to download a missing blob.');
              },
              function(err) {
                assertEquals(goog.fs.Error.ErrorCode.NOT_FOUND, err.code);
                var download = downloader.download('/foo/bar');
                xhr.simulateResponse(200, 'more data');
                return download;
              })
          .then(function() { return downloader.isDownloaded('/foo/bar'); })
          .then(assertTrue)
          .then(function() { return downloader.getDownloadedBlob('/foo/bar'); })
          .then(function(blob) { assertEquals('more data', blob.toString()); });

  xhr.simulateResponse(200, 'data');
  return promise;
}

function testSetBlob() {
  return downloader.setBlob('/foo/bar', goog.testing.fs.getBlob('data'))
      .then(function() { return downloader.isDownloaded('/foo/bar'); })
      .then(assertTrue)
      .then(function() { return downloader.getDownloadedBlob('/foo/bar'); })
      .then(function(blob) { assertEquals('data', blob.toString()); });
}

function testSetBlobWithName() {
  return downloader.setBlob('/foo/bar', goog.testing.fs.getBlob('data'), 'qux')
      .then(function() { return downloader.getLocalUrl('/foo/bar'); })
      .then(function(url) { assertMatches(/\/`qux$/, url); });
}
function testDownloadDuringDownload() {
  var download1 = downloader.download('/foo/bar');
  var download2 = downloader.download('/foo/bar');

  var promise =
      download1.then(function() { return download2; })
          .then(function() { return downloader.getDownloadedBlob('/foo/bar'); })
          .then(function(blob) { assertEquals('data', blob.toString()); });

  // There should only need to be one response for both downloads, since the
  // second should return the same deferred as the first.
  xhr.simulateResponse(200, 'data');
  return promise;
}

function testGetDownloadedBlobDuringDownload() {
  var hasDownloaded = false;
  downloader.download('/foo/bar').then(function() { hasDownloaded = true; });

  var promise =
      downloader.waitForDownload('/foo/bar')
          .then(function() { return downloader.getDownloadedBlob('/foo/bar'); })
          .then(function(blob) {
            assertTrue(hasDownloaded);
            assertEquals('data', blob.toString());
          });

  xhr.simulateResponse(200, 'data');
  return promise;
}

function testIsDownloadedDuringDownload() {
  var hasDownloaded = false;
  downloader.download('/foo/bar').then(function() { hasDownloaded = true; });

  var promise =
      downloader.waitForDownload('/foo/bar')
          .then(function() { return downloader.isDownloaded('/foo/bar'); })
          .then(assertTrue);

  xhr.simulateResponse(200, 'data');
  return promise;
}

function testRemoveDuringDownload() {
  var hasDownloaded = false;
  downloader.download('/foo/bar').then(function() { hasDownloaded = true; });

  var promise =
      downloader.waitForDownload('/foo/bar')
          .then(function() { return downloader.remove('/foo/bar'); })
          .then(function() { assertTrue(hasDownloaded); })
          .then(function() { return downloader.isDownloaded('/foo/bar'); })
          .then(assertFalse);

  xhr.simulateResponse(200, 'data');
  return promise;
}

function testSetBlobDuringDownload() {
  var download = downloader.download('/foo/bar');

  var promise =
      downloader.waitForDownload('/foo/bar')
          .then(function() {
            return downloader.setBlob(
                '/foo/bar', goog.testing.fs.getBlob('blob data'));
          })
          .then(
              function() {
                fail('Should not be able to set blob during a download.');
              },
              function(err) {
                assertEquals(
                    goog.fs.Error.ErrorCode.INVALID_MODIFICATION,
                    err.fileError.code);
                return download;
              })
          .then(function() { return downloader.getDownloadedBlob('/foo/bar'); })
          .then(function(b) { assertEquals('xhr data', b.toString()); });

  xhr.simulateResponse(200, 'xhr data');
  return promise;
}

function testDownloadCanceledBeforeXhr() {
  var download = downloader.download('/foo/bar');

  var promise =
      download
          .then(
              function() { fail('Download should have been canceled.'); },
              function() {
                assertEquals('/foo/bar', xhr.getLastUri());
                assertEquals(goog.net.ErrorCode.ABORT, xhr.getLastErrorCode());
                assertFalse(xhr.isActive());

                return downloader.isDownloaded('/foo/bar');
              })
          .then(assertFalse);

  download.cancel();
  return promise;
}

function testDownloadCanceledAfterXhr() {
  var download = downloader.download('/foo/bar');
  xhr.simulateResponse(200, 'data');
  download.cancel();

  return download
      .then(
          function() { fail('Should not succeed after cancellation.'); },
          function() {
            assertEquals('/foo/bar', xhr.getLastUri());
            assertEquals(goog.net.ErrorCode.NO_ERROR, xhr.getLastErrorCode());
            assertFalse(xhr.isActive());

            return downloader.isDownloaded('/foo/bar');
          })
      .then(assertFalse);
}

function testFailedXhr() {
  var promise =
      downloader.download('/foo/bar')
          .then(
              function() { fail('Download should not have succeeded.'); },
              function(err) {
                assertEquals('/foo/bar', err.url);
                assertEquals(404, err.xhrStatus);
                assertEquals(goog.net.ErrorCode.HTTP_ERROR, err.xhrErrorCode);
                assertUndefined(err.fileError);

                return downloader.isDownloaded('/foo/bar');
              })
          .then(assertFalse);

  xhr.simulateResponse(404);
  return promise;
}

function testFailedDownloadSave() {
  var promise =
      downloader.download('/foo/bar')
          .then(function() {
            var download = downloader.download('/foo/bar');
            xhr.simulateResponse(200, 'data');
            return download;
          })
          .then(
              function() {
                fail('Should not be able to modify an active download.');
              },
              function(err) {
                assertEquals('/foo/bar', err.url);
                assertUndefined(err.xhrStatus);
                assertUndefined(err.xhrErrorCode);
                assertEquals(
                    goog.fs.Error.ErrorCode.INVALID_MODIFICATION,
                    err.fileError.code);
              });

  xhr.simulateResponse(200, 'data');
  return promise;
}

function testFailedGetDownloadedBlob() {
  return downloader.getDownloadedBlob('/foo/bar')
      .then(
          function() { fail('Should not be able to get a missing blob.'); },
          function(err) {
            assertEquals(goog.fs.Error.ErrorCode.NOT_FOUND, err.code);
          });
}

function testFailedRemove() {
  return downloader.remove('/foo/bar')
      .then(
          function() { fail('Should not be able to remove a missing file.'); },
          function(err) {
            assertEquals(goog.fs.Error.ErrorCode.NOT_FOUND, err.code);
          });
}

function testIsDownloading() {
  assertFalse(downloader.isDownloading('/foo/bar'));
  var promise = downloader.download('/foo/bar').then(function() {
    assertFalse(downloader.isDownloading('/foo/bar'));
  });

  assertTrue(downloader.isDownloading('/foo/bar'));
  xhr.simulateResponse(200, 'data');
  return promise;
}

function testIsDownloadingWhenCancelled() {
  assertFalse(downloader.isDownloading('/foo/bar'));
  var deferred = downloader.download('/foo/bar').addErrback(function() {
    assertFalse(downloader.isDownloading('/foo/bar'));
  });

  assertTrue(downloader.isDownloading('/foo/bar'));
  deferred.cancel();
}

function assertMatches(expected, actual) {
  assert(
      'Expected "' + actual + '" to match ' + expected, expected.test(actual));
}


text:
package uk.co.n3tw0rk.droidcart.carts.repository;

import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import uk.co.n3tw0rk.droidcart.carts.domain.Cart;
import uk.co.n3tw0rk.droidcart.support.domain.Sequence;

import java.util.List;

import static junit.framework.TestCase.assertNotNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MongoCartRepositoryTests {

    private static final Integer CART_ID = 132;
    private static final int LIMIT = 10;
    private static final int OFFSET = 0;

    @Mock
    private MongoTemplate mongoTemplateMock;
    @Mock
    private Cart cartMock;
    @Mock
    private Sequence sequenceMock;
    @InjectMocks
    private MongoCartRepository mongoCartRepository;
    @Captor
    private ArgumentCaptor<Integer> integerArgumentCaptor;
    @Captor
    private ArgumentCaptor<Cart> cartArgumentCaptor;
    @Captor
    private ArgumentCaptor<Query> queryArgumentCaptor;

    private List<Cart> cartList = Lists.newArrayList();

    @Before
    public void preFlight() {
        cartList.add(cartMock);
        when(mongoTemplateMock.find(
                any(Query.class),
                eq(Cart.class)
        )).thenReturn(cartList);
    }

    @Test
    public void findAllTest() {
        List<Cart> returnedList = mongoCartRepository.findAll(LIMIT, OFFSET);
        verify(mongoTemplateMock).find(
                queryArgumentCaptor.capture(),
                eq(Cart.class)
        );

        Query queryArgument = queryArgumentCaptor.getValue();
        assertNotNull(queryArgument);
        assertThat(queryArgument.getLimit(), is(LIMIT));
        assertThat((int)queryArgument.getSkip(), is(OFFSET));
        assertThat(returnedList, is(cartList));
    }

}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2018.02.17 at 03:46:58 PM CET
//

package no.api.meteo.jaxb.textforecast.v1_6;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <attribute name="src" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="par" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="pos" use="required" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="run" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="vfrom" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="vto" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="format" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="lang" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *       <attribute name="symbolset" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "value")
public class Value {

    @XmlAttribute(name = "src", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected String src;
    @XmlAttribute(name = "par", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected String par;
    @XmlAttribute(name = "pos", required = true)
    @XmlSchemaType(name = "anySimpleType")
    protected String pos;
    @XmlAttribute(name = "run")
    @XmlSchemaType(name = "anySimpleType")
    protected String run;
    @XmlAttribute(name = "vfrom")
    @XmlSchemaType(name = "anySimpleType")
    protected String vfrom;
    @XmlAttribute(name = "vto")
    @XmlSchemaType(name = "anySimpleType")
    protected String vto;
    @XmlAttribute(name = "format")
    @XmlSchemaType(name = "anySimpleType")
    protected String format;
    @XmlAttribute(name = "lang")
    @XmlSchemaType(name = "anySimpleType")
    protected String lang;
    @XmlAttribute(name = "symbolset")
    @XmlSchemaType(name = "anySimpleType")
    protected String symbolset;

    /**
     * Gets the value of the src property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSrc() {
        return src;
    }

    /**
     * Sets the value of the src property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSrc(String value) {
        this.src = value;
    }

    /**
     * Gets the value of the par property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPar() {
        return par;
    }

    /**
     * Sets the value of the par property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPar(String value) {
        this.par = value;
    }

    /**
     * Gets the value of the pos property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getPos() {
        return pos;
    }

    /**
     * Sets the value of the pos property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setPos(String value) {
        this.pos = value;
    }

    /**
     * Gets the value of the run property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getRun() {
        return run;
    }

    /**
     * Sets the value of the run property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setRun(String value) {
        this.run = value;
    }

    /**
     * Gets the value of the vfrom property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getVfrom() {
        return vfrom;
    }

    /**
     * Sets the value of the vfrom property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setVfrom(String value) {
        this.vfrom = value;
    }

    /**
     * Gets the value of the vto property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getVto() {
        return vto;
    }

    /**
     * Sets the value of the vto property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setVto(String value) {
        this.vto = value;
    }

    /**
     * Gets the value of the format property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getFormat() {
        return format;
    }

    /**
     * Sets the value of the format property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setFormat(String value) {
        this.format = value;
    }

    /**
     * Gets the value of the lang property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getLang() {
        return lang;
    }

    /**
     * Sets the value of the lang property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setLang(String value) {
        this.lang = value;
    }

    /**
     * Gets the value of the symbolset property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getSymbolset() {
        return symbolset;
    }

    /**
     * Sets the value of the symbolset property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setSymbolset(String value) {
        this.symbolset = value;
    }

}


text:
import scala.io.StdIn

/*

Sort a list and print the difference between the maximum variation among the elements. Highest variation is the absolute difference
between the maximum/largest and smallest/minimum element of the list.

Print variation for each test case. Each test case consists of two lines.
First line contains an integer value N, denoting the number of elements in the list.
Next line contains N space separated integers, of the list.

Output has 't' lines, each line prints the maximum variation.

*/

object HelloWorld {
    def main(args: Array[String]) {

        val t = StdIn.readInt()
        for(i <- 1 to t){
            val n = StdIn.readInt()
            val nums = StdIn.readLine()

            val arr = nums.split(" ").map(_.toInt).sorted
            println(arr.last - arr.head)
        }

    }
}


text:
module MogileImageStore
  class Attachment
    attr_reader :options, :content, :name, :size, :extension, :width, :height

    def initialize(data, options={})
      @options = options.symbolize_keys
      @content = data
      @name = Digest::MD5.hexdigest(data)
      @size = @content.size
      @extension = extension_for(options[:filename] || '')
    end

    def attributes
      {size: size,
       image_type: extension,
       width: width,
       height: height}
    end

    def extension_for(filename)
      (MIME::Types.type_for(filename).first || MIME::Type.new('application/octet-stream')).
        extensions.find{|e| e.length <= 3} || 'bin'
    end

    def persist(mogile_image)
      mogile_image.attributes = attributes
      MogileImage.mogilefs_connection.store_content mogile_image.filename, MogileImageStore.backend['class'], content
    end

    def preprocess!
      imglist = ::Magick::ImageList.new
      begin
        imglist.from_blob(@content)
      rescue
        raise InvalidImage
      end
      if (filter = ::MogileImageStore.options[:image_filter]) && filter.is_a?(Proc)
        filter.call(imglist)
      end
      resize = false
      resize = true if ::MogileImageStore.options[:maxwidth] &&
          imglist.first.columns > ::MogileImageStore.options[:maxwidth].to_i
      resize = true if ::MogileImageStore.options[:maxheight] &&
          imglist.first.rows > ::MogileImageStore.options[:maxheight].to_i

      strip = (!options[:keep_exif] &&
                  imglist.inject([]){|r,i| r.concat(i.get_exif_by_entry()) }.any?)
      if filter || resize || strip
        if resize
          imglist.each do |i|
            i.resize_to_fit!(MogileImageStore.options[:maxwidth],
                             MogileImageStore.options[:maxheight])
          end
        end
        if strip
          # strip exif info
          imglist.each{|i| i.strip! }
        end
        @content = imglist.to_blob
      end
      img = imglist.first
      @size = content.size
      @extension = TO_EXTENSION[img.format.to_s] or raise UnsupportedImage
      @width = img.columns
      @height = img.rows
      self
    end
  end
end


text:
<?php

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
AdminUIHelper::startAdminArea($this);

/* Load some variables */
$search_date = vRequest::getVar('search_date', null); // Changed search by date
$now = getdate();
$nowstring = $now["hours"].":".substr('0'.$now["minutes"], -2).' '.$now["mday"].".".$now["mon"].".".$now["year"];
$search_order = vRequest::getVar('search_order', '>');
$search_type = vRequest::getVar('search_type', 'product');
// OSP in view.html.php $virtuemart_category_id = vRequest::getInt('virtuemart_category_id', false);
if ($product_parent_id=vRequest::getInt('product_parent_id', false))   $col_product_name='COM_VIRTUEMART_PRODUCT_CHILDREN_LIST'; else $col_product_name='COM_VIRTUEMART_PRODUCT_NAME';

?>
<form action="index.php" method="post" name="adminForm" id="adminForm">

			<?php echo vmText::_('COM_VIRTUEMART_FILTER') ?>:
				<select class="inputbox" id="virtuemart_category_id" name="virtuemart_category_id" onchange="this.form.submit(); return false;">
					<option value=""><?php echo vmText::sprintf( 'COM_VIRTUEMART_SELECT' ,  vmText::_('COM_VIRTUEMART_CATEGORY')) ; ?></option>
					<?php echo $this->category_tree; ?>
				</select>
					 <?php echo JHtml::_('select.genericlist', $this->manufacturers, 'virtuemart_manufacturer_id', 'class="inputbox" onchange="document.adminForm.submit(); return false;"', 'value', 'text',
					 	$this->model->virtuemart_manufacturer_id );
					?>

				<?php echo vmText::_('COM_VIRTUEMART_PRODUCT_LIST_SEARCH_BY_DATE') ?>
					<input type="text" value="<?php echo vRequest::getVar('filter_product'); ?>" name="filter_product" size="25" />
				<?php
					echo $this->lists['search_type'];
					echo $this->lists['search_order'];
					echo vmJsApi::jDate(vRequest::getVar('search_date', $nowstring), 'search_date');
				?>
				<button  class="btn btn-small" onclick="this.form.submit();"><?php echo vmText::_('COM_VIRTUEMART_GO'); ?></button>
				<button  class="btn btn-small" onclick="document.adminForm.filter_product.value=''; document.adminForm.search_type.options[0].selected = true;"><?php echo vmText::_('COM_VIRTUEMART_RESET'); ?></button>

<?php echo $this->pagination->getResultsCounter(); ?>

<?php
// $this->productlist

$imgWidth = VmConfig::get('img_width');
if(empty($imgWidth)) $imgWidth = 80;
?>

		<input type="checkbox" name="toggle" value="" onclick="Joomla.checkAll(this)" />

		<?php echo $this->sort('product_name',$col_product_name) ?>
		<?php if (!$product_parent_id ) { ?>
                <?php echo $this->sort('product_parent_id','COM_VIRTUEMART_PRODUCT_CHILDREN_OF'); ?>
                <?php } ?>
                <?php echo vmText::_('COM_VIRTUEMART_PRODUCT_PARENT_LIST_CHILDREN'); ?>
                <th style="min-width:<?php echo $imgWidth ?>px;width:5%;"><?php echo vmText::_('COM_VIRTUEMART_PRODUCT_MEDIA'); ?>
		<?php echo $this->sort('product_sku') ?>
		<?php echo $this->sort('product_price', 'COM_VIRTUEMART_PRODUCT_PRICE_TITLE') ; ?>
<?php /*		<?php echo JHtml::_('grid.sort', 'COM_VIRTUEMART_CATEGORY', 'c.category_name', $this->lists['filter_order_Dir'], $this->lists['filter_order'] ); ?>	 */ ?>
<?php echo vmText::_( 'COM_VIRTUEMART_CATEGORY'); ?>

		<?php
		$num_rows = 0;
		if( $this->virtuemart_category_id ) { ?>

				<?php echo $this->sort('pc.ordering', 'COM_VIRTUEMART_FIELDMANAGER_REORDER'); ?>
				<?php echo JHtml::_('grid.order', $this->productlist); //vmCommonHTML::getSaveOrderButton( $num_rows, 'changeordering' ); ?>

		<?php } ?>
		<?php echo $this->sort('mf_name', 'COM_VIRTUEMART_MANUFACTURER_S') ; ?>
		<?php echo vmText::_('COM_VIRTUEMART_REVIEW_S'); ?>
		<?php echo $this->sort('product_special', 'COM_VIRTUEMART_PRODUCT_FORM_SPECIAL'); ?>
		<?php echo $this->sort('published') ; ?>
	    <?php echo $this->sort('p.virtuemart_product_id', 'COM_VIRTUEMART_ID')  ?>

	<?php
	$total = $this->pagination->total;

	if ($totalList = count($this->productlist) ) {
		$i = 0;
		$k = 0;
		$keyword = vRequest::getCmd('keyword');
		foreach ($this->productlist as $key => $product) {
			$checked = JHtml::_('grid.id', $i , $product->virtuemart_product_id,null,'virtuemart_product_id');
			$published = JHtml::_('grid.published', $product, $i );
			$published = $this->gridPublished( $product, $i );

			$is_featured = $this->toggle($product->product_special, $i,'toggle.product_special');
			$link = 'index.php?option=com_virtuemart&view=product&task=edit&virtuemart_product_id='.$product->virtuemart_product_id;
			?>
			<tr class="row<?php echo $k ; ?>">

				<?php echo $checked; ?>

				">

  				<?php
				if(empty($product->product_name)){
					$product->product_name = 'Language Missing id '.$product->virtuemart_product_id;
				}
				echo JHtml::_('link', JRoute::_($link), $product->product_name, array('title' => vmText::_('COM_VIRTUEMART_EDIT').' '. htmlentities($product->product_name))); ?>

                <?php if (!$product_parent_id ) { ?>
				<?php
					if ($product->product_parent_id  ) {
						VirtuemartViewProduct::displayLinkToParent($product->product_parent_id);
					}
					?>

                                <?php } ?>
				<?php
						 VirtuemartViewProduct::displayLinkToChildList($product->virtuemart_product_id , $product->product_name);
                                                 ?>

				<?php
					// Create URL
					$link = JRoute::_('index.php?view=media&virtuemart_product_id='.$product->virtuemart_product_id.'&option=com_virtuemart');
				?>

					<?php
					// We show the images only when less than 21 products are displayeed -->
					$mediaLimit = (int)VmConfig::get('mediaLimit',20);
					if($this->pagination->limit<=$mediaLimit or $totalList<=$mediaLimit){
						// Product list should be ordered
						$this->model->addImages($product,1);
						$img = '('.$product->mediaitems.')'.$product->images[0]->displayMediaThumb('class="vm_mini_image"',false );
						//echo JHtml::_('link', $link, $img,  array('title' => vmText::_('COM_VIRTUEMART_MEDIA_MANAGER').' '.$product->product_name));
					} else {
						//echo JHtml::_('link', $link, ' ('.$product->mediaitems.')', array('title' => vmText::_('COM_VIRTUEMART_MEDIA_MANAGER').' '.$product->product_name) );
						$img = ' ('.$product->mediaitems.')';
					}
					echo JHtml::_('link', $link, $img,  array('title' => vmText::_('COM_VIRTUEMART_MEDIA_MANAGER').' '.htmlentities($product->product_name)));
					?>

				<?php echo $product->product_sku; ?>

				<?php
					if(isset($product->product_price_display)) {
						echo $product->product_price_display;
					}
				?>

				<?php
					echo $product->categoriesList;
				?>

				<?php if ($this->virtuemart_category_id ) { ?>

						<?php echo $this->pagination->vmOrderUpIcon( $i, $product->ordering, 'orderup', vmText::_('COM_VIRTUEMART_MOVE_UP')  ); ?>
						<?php echo $this->pagination->vmOrderDownIcon( $i, $product->ordering, $total , true, 'orderdown', vmText::_('COM_VIRTUEMART_MOVE_DOWN') ); ?>
						<input class="ordering" type="text" name="order[<?php echo $product->id?>]" id="order[<?php echo $i?>]" size="5" value="<?php echo $product->ordering; ?>" style="text-align: center" />

						<?php // echo vmCommonHTML::getOrderingField( $product->ordering ); ?>

				<?php }  ?>

				<?php
					echo $product->manuList;

				?>

				<?php $link = 'index.php?option=com_virtuemart&view=ratings&task=listreviews&virtuemart_product_id='.$product->virtuemart_product_id; ?>
				<?php echo JHtml::_('link', $link, $product->reviews); ?>

					<?php
						echo $is_featured;
					?>

				<?php echo $published; ?>

				<?php echo $product->virtuemart_product_id; // echo $product->vendor_name; ?>

		<?php
			$k = 1 - $k;
			$i++;
		}
	}
	?>

			<?php echo $this->pagination->getListFooter(); ?>

<input type="hidden" name="product_parent_id" value="<?php echo vRequest::getInt('product_parent_id', 0); ?>" />
	<?php echo $this->addStandardHiddenToForm(); ?>
</form>

<?php AdminUIHelper::endAdminArea();

// DONE BY stephanbais
/// DRAG AND DROP PRODUCT ORDER HACK
if ($this->virtuemart_category_id ) { ?>

<?php }

/// END PRODUCT ORDER HACK
?>


text:
require 'rbconfig'
require 'finder/base'
require 'finder/roll'
require 'finder/gem'
require 'finder/site'

module Finder

  # Find module is the main interface for Finder library.
  #
  module Find
    extend self

    # TODO: expand on extensions
    EXTENSIONS = %w{.rb .rbx .so}

    # Find matching paths, searching through Rolled libraries, Gem-installed libraries
    # and site locations in `$LOAD_PATH` and `RbConfig::CONFIG['datadir']`.
    #
    # @param [String] match
    #   File glob to match against.
    #
    # @example
    #   Find.path('lib/foo/*')
    #
    def path(match, options={})
      found = []
      systems.each do |system|
        found.concat system.path(match, options)
      end
      found.uniq
    end

    # Shortcut for #path.
    #
    #   Find['lib/foo/*']
    #
    alias_method :[], :path

    # Searching through all systems for matching data paths.
    #
    # @param [String] match
    #   File glob to match against.
    #
    # @example
    #   Find.data_path('bar/*')
    #
    def data_path(match, options={})
      found = []
      systems.each do |system|
        found.concat system.data_path(match, options)
      end
      found.uniq
    end

    # Searching through all systems for matching load paths.
    #
    # @param [String] match
    #   File glob to match against.
    #
    # @example
    #   Find.load_path('bar/*')
    #
    def load_path(match, options={})
      found = []
      systems.each do |system|
        found.concat system.load_path(match, options)
      end
      found.uniq
    end

    ## Searching through all systems for matching load paths.
    ##
    ## @param [String] match
    ##   File glob to match against.
    ##
    ## @example
    ##   Find.require_path('bar/*')
    ##
    #def require_path(match, options={})
    #  found = []
    #  systems.each do |system|
    #    found.concat system.require_path(match, options)
    #  end
    #  found.uniq
    #end

    # Searching through all systems for matching requirable feature files.
    #
    # @param [String] match
    #   File glob to match against.
    #
    # @example
    #   Find.feature('ostruct')
    #
    def feature(match, options={})
      found = []
      systems.each do |system|
        found.concat system.feature(match, options)
      end
      found.uniq
    end

    #
    # List of supported library management systems.
    #
    def systems
      @systems ||= (
        systems = []
        systems << Roll if defined?(::Library)
        systems << Gem  if defined?(::Gem)
        systems << Site
        systems
      )
    end

  end

end


text:
<?php

namespace Tests\Linting\Linters;

use PHPUnit\Framework\TestCase;
use Tighten\TLint\Linters\ConcatenationSpacing;
use Tighten\TLint\TLint;

class ConcatenationSpacingTest extends TestCase
{
    /** @test */
    public function catches_concat_without_spaces()
    {
        $file = <<<file
<?php

echo "foo bar . ".\$baz;

file;

        $lints = (new TLint)->lint(
            new ConcatenationSpacing($file)
        );

        $this->assertEquals(3, $lints[0]->getNode()->getLine());
    }

    /** @test */
    public function catches_concat_with_too_many_spaces()
    {
        $file = <<<file
<?php

echo "foo bar . "  . \$baz;

file;

        $lints = (new TLint)->lint(
            new ConcatenationSpacing($file)
        );

        $this->assertEquals(3, $lints[0]->getNode()->getLine());
    }

    /** @test */
    public function catches_concat_with_space_on_one_side()
    {
        $file = <<<file
<?php

echo "foo bar . ". \$baz;
echo "foo bar . " .\$baz;

file;

        $lints = (new TLint)->lint(
            new ConcatenationSpacing($file)
        );

        $this->assertEquals(3, $lints[0]->getNode()->getLine());
        $this->assertEquals(4, $lints[1]->getNode()->getLine());
    }

    /** @test */
    public function does_not_trigger_on_concat_with_spaces()
    {
        $file = <<<file
<?php

echo "foo bar . " . \$baz;

file;

        $lints = (new TLint)->lint(
            new ConcatenationSpacing($file)
        );

        $this->assertEmpty($lints);
    }

    /** @test */
    public function handles_valid_multiline_concat()
    {
        $file = <<<file
<?php

echo '! ' . \$this->linter->getLintDescription() . PHP_EOL
                . \$this->node->getLine() . ' : `' . \$this->linter->getCodeLine(\$this->node->getLine()) . '`';

file;

        $lints = (new TLint)->lint(
            new ConcatenationSpacing($file)
        );

        $this->assertEmpty($lints);
    }

    /** @test */
    public function triggers_on_multiline_concat()
    {
        $file = <<<file
<?php

echo getcwd() . '/'
    .\$a;

file;

        $lints = (new TLint)->lint(
            new ConcatenationSpacing($file)
        );

        $this->assertEquals(3, $lints[0]->getNode()->getLine());
    }

    /** @test */
    public function triggers_on_multiline_concat_where_lines_do_not_start_with_concat()
    {
        $file = <<<file
<?php

       \$directory = 'images/articles' . DIRECTORY_SEPARATOR .
            date('Y') . DIRECTORY_SEPARATOR .
            date('m') . DIRECTORY_SEPARATOR .
            date('d') . DIRECTORY_SEPARATOR;

file;

        $lints = (new TLint)->lint(
            new ConcatenationSpacing($file)
        );

        $this->assertEquals(1, count($lints));
        $this->assertEquals(3, $lints[0]->getNode()->getLine());
    }
}


text:
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.contrib.auth.decorators import login_required

from pokemon.models import (
    Pokemon, Sprite, Move, Description, Game,
    EggGroup, Type, Ability, MovePokemon
)

from hits.models import ResourceView

def _total_site_data():
    """
    Compute the total count of objects on the site

    Using count() is drastically cheaper than len(objects.all())
    """

    data = dict(
        pokemon=Pokemon.objects.count(),
        sprites=Sprite.objects.count(),
        moves=Move.objects.count(),
        descriptions=Description.objects.count(),
        games=Game.objects.count(),
        egg_groups=EggGroup.objects.count(),
        types=Type.objects.count(),
        abilities=Ability.objects.count(),
        move_pokes=MovePokemon.objects.count()
    )

    t = 0
    for i in data.iteritems():
        t += i[1]

    data['total_items'] = t

    return data

@login_required
def moderate(request):

    return render_to_response(
        'pages/moderate.html',
        {}, context_instance=RequestContext(request))

def about(request):

    site_data = _total_site_data()

    total_views = ResourceView.objects.total_count()

    average_day = int(round(total_views / ResourceView.objects.count()))

    return render_to_response(
        'pages/about.html',
        {
            'total': total_views,
            'average_day': average_day,
            'site_data': site_data,
        },
        context_instance=RequestContext(request)
    )

def home(request):

    total_views = ResourceView.objects.total_count()

    if total_views > 100:
        total_views = int(round(total_views, -2))

    return render_to_response(
        'pages/home.html',
        {
            'total_views': total_views,
        },
        context_instance=RequestContext(request)
    )

def twilio(request):

    return render_to_response(
        'pages/twilio.html',
        {}, context_instance=RequestContext(request))


text:
package org.apache.ambari.server.controller.internal;

import java.util.Collections;
import java.util.Map;
import java.util.Set;

import org.apache.ambari.server.api.predicate.InvalidQueryException;
import org.apache.ambari.server.stack.NoSuchStackException;
import org.apache.ambari.server.topology.Blueprint;
import org.apache.ambari.server.topology.Configuration;
import org.apache.ambari.server.topology.HostGroupInfo;
import org.apache.ambari.server.topology.InvalidTopologyTemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A request for a scaling an existing cluster.
 */
public class ScaleClusterRequest extends BaseClusterRequest {

  private static final Logger LOGGER = LoggerFactory.getLogger(ScaleClusterRequest.class);

  /**
   * cluster name
   */
  private String clusterName;

  /**
   * Constructor.
   *
   * @param propertySet  set of request properties
   *
   * @throws InvalidTopologyTemplateException if any validation of properties fails
   */
  public ScaleClusterRequest(Set<Map<String, Object>> propertySet) throws InvalidTopologyTemplateException {
    for (Map<String, Object> properties : propertySet) {
      // can only operate on a single cluster per logical request
      if (getClusterName() == null) {
        setClusterName(String.valueOf(properties.get(HostResourceProvider.HOST_CLUSTER_NAME_PROPERTY_ID)));
      }
      // currently don't allow cluster scoped configuration in scaling operation
      setConfiguration(new Configuration(Collections.emptyMap(),
          Collections.emptyMap()));

      parseHostGroups(properties);
    }
  }

  public String getClusterName() {
    return clusterName;
  }

  public void setClusterName(String clusterName) {
    this.clusterName = clusterName;
  }

  @Override
  public Long getClusterId() {
    return clusterId;
  }

  public void setClusterId(Long clusterId) {
    this.clusterId = clusterId;
  }

  @Override
  public Type getType() {
    return Type.SCALE;
  }

  @Override
  public String getDescription() {
    return String.format("Scale Cluster '%s' (+%s hosts)", clusterName, getTotalRequestedHostCount());
  }

  /**
   * Parse and set host group information.
   *
   * @param properties  request properties
   * @throws InvalidTopologyTemplateException if any property validation fails
   */
  //todo: need to use fully qualified host group name.  For now, disregard name collisions across BP's
  private void parseHostGroups(Map<String, Object> properties) throws InvalidTopologyTemplateException {
    String blueprintName = String.valueOf(properties.get(HostResourceProvider.BLUEPRINT_PROPERTY_ID));
    if (blueprintName == null || blueprintName.equals("null")) {
      throw new InvalidTopologyTemplateException("Blueprint name must be specified for all host groups");
    }

    String hgName = String.valueOf(properties.get(HostResourceProvider.HOST_GROUP_PROPERTY_ID));
    if (hgName == null || hgName.equals("null")) {
      throw new InvalidTopologyTemplateException("A name must be specified for all host groups");
    }

    Blueprint blueprint = getBlueprint();
    if (getBlueprint() == null) {
      blueprint = parseBlueprint(blueprintName);
      setBlueprint(blueprint);
    } else if (! blueprintName.equals(blueprint.getName())) {
      throw new InvalidTopologyTemplateException(
          "Currently, a scaling request may only refer to a single blueprint");
    }

    String hostName = HostResourceProvider.getHostNameFromProperties(properties);
    boolean containsHostCount = properties.containsKey(HostResourceProvider.HOST_COUNT_PROPERTY_ID);
    boolean containsHostPredicate = properties.containsKey(HostResourceProvider.HOST_PREDICATE_PROPERTY_ID);

    if (hostName != null && (containsHostCount || containsHostPredicate)) {
      throw new InvalidTopologyTemplateException(
          "Can't specify host_count or host_predicate if host_name is specified in hostgroup: " + hgName);
    }

    if (hostName == null && ! containsHostCount) {
      throw new InvalidTopologyTemplateException(
          "Must specify either host_name or host_count for hostgroup: " + hgName);
    }

    HostGroupInfo hostGroupInfo = getHostGroupInfo().get(hgName);
    if (hostGroupInfo == null) {
      if (blueprint.getHostGroup(hgName) == null) {
        throw new InvalidTopologyTemplateException("Invalid host group specified in request: " + hgName);
      }
      hostGroupInfo = new HostGroupInfo(hgName);
      getHostGroupInfo().put(hgName, hostGroupInfo);
    }

    // specifying configuration is scaling request isn't permitted
    hostGroupInfo.setConfiguration(new Configuration(Collections.emptyMap(),
        Collections.emptyMap()));

    // process host_name and host_count
    if (containsHostCount) {
      //todo: host_count and host_predicate up one level
      if (containsHostPredicate) {
        String predicate = String.valueOf(properties.get(HostResourceProvider.HOST_PREDICATE_PROPERTY_ID));
        validateHostPredicateProperties(predicate);
        try {
          hostGroupInfo.setPredicate(predicate);
        } catch (InvalidQueryException e) {
          throw new InvalidTopologyTemplateException(
              String.format("Unable to compile host predicate '%s': %s", predicate, e), e);
        }
      }

      if (! hostGroupInfo.getHostNames().isEmpty()) {
        throw new InvalidTopologyTemplateException(
            "Can't specify both host_name and host_count for the same hostgroup: " + hgName);
      }
      hostGroupInfo.setRequestedCount(Integer.parseInt(String.valueOf(
          properties.get(HostResourceProvider.HOST_COUNT_PROPERTY_ID))));
    } else {
      if (hostGroupInfo.getRequestedHostCount() != hostGroupInfo.getHostNames().size()) {
        // host_name specified in one host block and host_count in another for the same group
        throw new InvalidTopologyTemplateException("Invalid host group specified in request: " + hgName);
      }
      hostGroupInfo.addHost(hostName);
      hostGroupInfo.addHostRackInfo(hostName, processRackInfo(properties));
    }
  }

  private String processRackInfo(Map<String, Object> properties) {
    String rackInfo = null;
    if (properties.containsKey(HostResourceProvider.HOST_RACK_INFO_PROPERTY_ID)) {
      rackInfo = (String) properties.get(HostResourceProvider.HOST_RACK_INFO_PROPERTY_ID);
    } else if (properties.containsKey(HostResourceProvider.RACK_INFO_PROPERTY_ID)) {
      rackInfo = (String) properties.get(HostResourceProvider.RACK_INFO_PROPERTY_ID);
    } else {
      LOGGER.debug("No rack info provided");
    }
    return rackInfo;
  }

  /**
   * Parse blueprint.
   *
   * @param blueprintName  blueprint name
   * @return blueprint instance
   *
   * @throws InvalidTopologyTemplateException if specified blueprint or stack doesn't exist
   */
  private Blueprint parseBlueprint(String blueprintName) throws InvalidTopologyTemplateException  {
    Blueprint blueprint;
    try {
      blueprint = getBlueprintFactory().getBlueprint(blueprintName);
    } catch (NoSuchStackException e) {
      throw new InvalidTopologyTemplateException("Invalid stack specified in the blueprint: " + blueprintName);
    }

    if (blueprint == null) {
      throw new InvalidTopologyTemplateException("The specified blueprint doesn't exist: " + blueprintName);
    }
    return blueprint;
  }

  /**
   * Get the total number of requested hosts for the request.
   * @return  total requested host count
   */
  private int getTotalRequestedHostCount() {
    int count = 0;
    for (HostGroupInfo groupInfo : getHostGroupInfo().values()) {
      count += groupInfo.getRequestedHostCount();
    }
    return count;
  }
}


text:
PBXBuildPhase::~PBXBuildPhase() {}

PBXBuildPhase::PBXBuildPhase() {}

void PBXBuildPhase::initFromPlist(const String& id, const Plist::dictionary_type& plist, const PBXDocument* pbxDoc)
{
  // Call super init
  PBXObject::initFromPlist(id, plist, pbxDoc);

  // Get files
  getStringVectorForKey(plist, "files", m_fileIds, VALUE_REQUIRED, m_parseER);
}

void PBXBuildPhase::resolvePointers()
{
  // Get files ptrs
  convertObjectIdList(m_pbxDoc, m_fileIds, m_filePtrs);
}


text:
package org.apache.flink.contrib.streaming.state;

import org.apache.flink.runtime.state.CheckpointStorage;
import org.apache.flink.runtime.state.StateBackendMigrationTestBase;
import org.apache.flink.runtime.state.storage.FileSystemCheckpointStorage;
import org.apache.flink.runtime.state.storage.JobManagerCheckpointStorage;
import org.apache.flink.util.function.SupplierWithException;

import org.junit.ClassRule;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/** Tests for the partitioned state part of {@link EmbeddedRocksDBStateBackend}. */
@RunWith(Parameterized.class)
public class EmbeddedRocksDBStateBackendMigrationTest
        extends StateBackendMigrationTestBase<EmbeddedRocksDBStateBackend> {

    @ClassRule public static final TemporaryFolder TEMP_FOLDER = new TemporaryFolder();

    @Parameterized.Parameters
    public static List<Object[]> modes() {
        return Arrays.asList(
                new Object[][] {
                    {
                        true,
                        (SupplierWithException<CheckpointStorage, IOException>)
                                JobManagerCheckpointStorage::new
                    },
                    {
                        false,
                        (SupplierWithException<CheckpointStorage, IOException>)
                                () -> {
                                    String checkpointPath =
                                            TEMP_FOLDER.newFolder().toURI().toString();
                                    return new FileSystemCheckpointStorage(checkpointPath);
                                }
                    }
                });
    }

    @Parameterized.Parameter(value = 0)
    public boolean enableIncrementalCheckpointing;

    @Parameterized.Parameter(value = 1)
    public SupplierWithException<CheckpointStorage, IOException> storageSupplier;

    @Override
    protected EmbeddedRocksDBStateBackend getStateBackend() throws Exception {
        return new EmbeddedRocksDBStateBackend(enableIncrementalCheckpointing);
    }

    @Override
    protected CheckpointStorage getCheckpointStorage() throws Exception {
        return storageSupplier.get();
    }
}


text:
namespace vk {

SwapchainKHR::SwapchainKHR(const VkSwapchainCreateInfoKHR *pCreateInfo, void *mem)
    : surface(vk::Cast(pCreateInfo->surface))
    , images(reinterpret_cast<PresentImage *>(mem))
    , imageCount(pCreateInfo->minImageCount)
    , retired(false)
{
	memset(reinterpret_cast<void *>(images), 0, imageCount * sizeof(PresentImage));
}

void SwapchainKHR::destroy(const VkAllocationCallbacks *pAllocator)
{
	for(uint32_t i = 0; i < imageCount; i++)
	{
		PresentImage &currentImage = images[i];
		if(currentImage.exists())
		{
			surface->detachImage(&currentImage);
			currentImage.clear();
		}
	}

	if(!retired)
	{
		surface->disassociateSwapchain();
	}

	vk::deallocate(images, pAllocator);
}

size_t SwapchainKHR::ComputeRequiredAllocationSize(const VkSwapchainCreateInfoKHR *pCreateInfo)
{
	return pCreateInfo->minImageCount * sizeof(PresentImage);
}

void SwapchainKHR::retire()
{
	if(!retired)
	{
		retired = true;
		surface->disassociateSwapchain();

		for(uint32_t i = 0; i < imageCount; i++)
		{
			PresentImage &currentImage = images[i];
			if(currentImage.isAvailable())
			{
				surface->detachImage(&currentImage);
				currentImage.clear();
			}
		}
	}
}

void SwapchainKHR::resetImages()
{
	for(uint32_t i = 0; i < imageCount; i++)
	{
		images[i].clear();
	}
}

VkResult SwapchainKHR::createImages(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo)
{
	resetImages();

	VkImageCreateInfo imageInfo = {};
	imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;

	if(pCreateInfo->flags & VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR)
	{
		imageInfo.flags |= VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT;
	}

	if(pCreateInfo->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR)
	{
		imageInfo.flags |= VK_IMAGE_CREATE_PROTECTED_BIT;
	}

	imageInfo.imageType = VK_IMAGE_TYPE_2D;
	imageInfo.format = pCreateInfo->imageFormat;
	imageInfo.extent.height = pCreateInfo->imageExtent.height;
	imageInfo.extent.width = pCreateInfo->imageExtent.width;
	imageInfo.extent.depth = 1;
	imageInfo.mipLevels = 1;
	imageInfo.arrayLayers = pCreateInfo->imageArrayLayers;
	imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
	imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
	imageInfo.usage = pCreateInfo->imageUsage;
	imageInfo.sharingMode = pCreateInfo->imageSharingMode;
	imageInfo.pQueueFamilyIndices = pCreateInfo->pQueueFamilyIndices;
	imageInfo.queueFamilyIndexCount = pCreateInfo->queueFamilyIndexCount;
	imageInfo.initialLayout = VK_IMAGE_LAYOUT_GENERAL;

	VkMemoryAllocateInfo allocInfo = {};
	allocInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
	allocInfo.allocationSize = 0;
	allocInfo.memoryTypeIndex = 0;

	VkResult status;
	for(uint32_t i = 0; i < imageCount; i++)
	{
		PresentImage &currentImage = images[i];

		status = currentImage.allocateImage(device, imageInfo);
		if(status != VK_SUCCESS)
		{
			return status;
		}

		allocInfo.allocationSize = currentImage.getImage()->getMemoryRequirements().size;

		status = currentImage.allocateAndBindImageMemory(device, allocInfo);
		if(status != VK_SUCCESS)
		{
			return status;
		}

		surface->attachImage(&currentImage);
	}

	return VK_SUCCESS;
}

uint32_t SwapchainKHR::getImageCount() const
{
	return imageCount;
}

VkResult SwapchainKHR::getImages(uint32_t *pSwapchainImageCount, VkImage *pSwapchainImages) const
{
	uint32_t i;
	for(i = 0; i < std::min(*pSwapchainImageCount, imageCount); i++)
	{
		pSwapchainImages[i] = images[i].asVkImage();
	}

	*pSwapchainImageCount = i;

	if(*pSwapchainImageCount < imageCount)
	{
		return VK_INCOMPLETE;
	}

	return VK_SUCCESS;
}

VkResult SwapchainKHR::getNextImage(uint64_t timeout, BinarySemaphore *semaphore, Fence *fence, uint32_t *pImageIndex)
{
	for(uint32_t i = 0; i < imageCount; i++)
	{
		PresentImage &currentImage = images[i];
		if(currentImage.isAvailable())
		{
			currentImage.setStatus(DRAWING);
			*pImageIndex = i;

			if(semaphore)
			{
				semaphore->signal();
			}

			if(fence)
			{
				fence->complete();
			}

			return VK_SUCCESS;
		}
	}

	return (timeout > 0) ? VK_TIMEOUT : VK_NOT_READY;
}

VkResult SwapchainKHR::present(uint32_t index)
{
	auto &image = images[index];
	image.setStatus(PRESENTING);
	VkResult result = surface->present(&image);
	image.setStatus(AVAILABLE);

	if(retired)
	{
		surface->detachImage(&image);
		image.clear();
	}

	return result;
}

}  // namespace vk


text:
* Redes neurais e backpropagation
* LSTM, Deep learning e RNN
* NLP e Representação (word2vec)

## Redes neurais

* O paradigma simbólico e sua limitação
* A resposta das RNA a essa limitação
* Especificação do modelo básico de uma RNA
* Backpropagation e como o aprendizado ocorre

O paradigma simbólico na inteligência artificial requer que o conhecimento
especializado seja especificado e programado para a resolução de uma
determinada tarefa. Neste paradigma, é necessário um trabalho de engenharia
do domínio para especificar esse conhecimento e programá-lo. Uma clara
limitação desse paradigma é o fato de que, em muitos domínios, não existe
uma definição que torne possível a especificação de um algoritmo para o
problema que se queira resolver.

O uso de redes neurais artificiais são uma possível solução para essa
limitação, uma vez que não é necessário especificar os passos para a
realização de uma tarefa. A ideia é que o sistema "aprenda" a resolver
o problema dado a partir de um grande número de exemplos de
entrada com suas respectivas saídas esperadas. Após a repetida exposição
do sistema a diferentes exemplos de entrada com a saída esperada, o
sistema se torna capaz de "prever" qual seria a saída esperada para um
exemplo de entrada inédito.

O surgimento das Redes Neurais Artificiais (RNA) foi, de certa forma, inspirado
pelo funcionamento do Sistema Nervoso Central (SNC). No cérebro humano, os
neurônios funcionam de modo integrado, de maneira que a ativação de um
neurônio afeta os diversos neurônios aos quais ele está ligado. Similarmente,
nas RNA, existem unidades computacionais relativamente simples que são ligadas
umas as outras. Assim como no SNC, a atividade de uma dessas unidades
influencia a atividades das unidades às quais ela está ligada.

Basicamente, um modelo de rede neural artificial pode ser representado como
um grafo que tem suas unidades (neurônios) distribuídas em camadas.
A primeira camada, de input recebe os respectivos estímulos a
partir dos dados de entrada. Os neurônios dessa camada exercem
influência nos neurônios da camada seguinte até que se chegue à última
camada - output. A influência de um neurônio sobre o próximo é modulada por meio
de pesos, que são valores relacionados a cada aresta no grafo. Para calcular
o valor que um neurônio passará aos neurônios da camada seguinte dois conceitos
são importantes: o _bias_ e a _função de ativação_.
O _bias_ é o valor que será subtraído do somatório de ativações dos neurônios
que estão ligados a ele e está relacionado ao limiar de ativação dos neurônios
no SNC. A função de ativação é a transformação que uma dada unidade fará com
o valor resultante do somatório dos valores das ativações dos neurônios da
camada anterior multiplicados com os respectivos pesos e subtraído do _bias_.

O processo de aprendizagem de uma rede pode ser entendido como a sucessiva
atualização dos pesos de modo que se chegue aos valores que permitam prever
melhor o output para um input inédito. Esse processo ocorre por meio da
iteração sobre um conjunto de dados de treino. Os pesos são inicializados
aleatóriamente (entre outras maneiras possíveis) e o primeiro dado é "inputado"
na rede, que passa os estímulos de uma camada à outra até o output. O output
gerado pela rede é então comparado ao resultado esperado por meio de uma função
de custo e com base nessa função os pesos são atualizados para a próxima iteração
até que se obtenha a configuração de pesos ótima.

A atualização dos pesos da rede, que é o centro do processo de aprendizagem, se
dá por meio do algoritmo de _backpropagation_. Esse algoritmo parte da função de
custo e atualiza cada peso com base no gradiente da função de custo, de modo a
minimizar o erro para a próxima iteração. O quanto cada peso será atualizado é
controlado pelo _learning rate_.

## Deep Learning, RNN e LSTM

_Deep Learning_ é o nome dado a uma rede neural que contenha "muitas" camadas.
Embora o conceito de uma rede com várias camadas já tivesse sido considerado desde
a década de 1980, o uso de _backpropagation_ com esse tipo de rede só se tornou
possível na prática a partir da década de 2000 com o surgimento das GPUs.

As redes neurais recorrentes são uma arquitetura importante para o processamento de
dados sequenciais, como audio ou linguagem natural. Nesse tipo de rede, há um loop da
saída da rede para a entrada na análise do próximo item da sequência, permitindo que
informações dos itens anteriores possam influenciar os itens seguintes. As RNNs
já existem há muito tempo (referência), mas o seu sucesso nos trabalhos mais recentes
está geralmente associado às LSTMs.

Embora teoricamente as RNNs sejam capazes de guardar informações por um longo espaço
de tempo, na prática isso se mostrou uma limitação das RNNs (citação Bengio 1994).
A Long Term Short Memory permite que as informações sejam guardadas por um longo
período de tempo. A cada item que passa pela rede, algumas informações podem ser
armazenadas para uso posterior, outras podem ser desprezadas e as informações
que estão guardadas (de passagens anteriores) podem influenciar a saída da rede.

O uso de LSTM com RNNs tem permitido um grande progresso em diversos domínios da
Aprendizagem de Máquina (exemplos...).

## NLP e Representação


text:
package com.github.drxaos.jvmvm.tests.interpretable.third;

import java.util.*;
import java.util.Map.Entry;

/**
 * Write a function to check if the given chemical equation is balanced or not?
 * Ex: Cu + S = CuS
 * 2H2 + 02 = 2H2O
 *
 * @author ksjeyabarani
 */
public class ChemicalEquation {

    private String LHS;

    private String RHS;

    private String equation;

    private String[] equationSides;

    private List<ChemicalFormula> lhsParts;

    private List<ChemicalFormula> rhsParts;

    private Map<String, Integer> lhsTotalChemicalCountmap;

    private Map<String, Integer> rhsTotalChemicalCountmap;

    private boolean isBalanced;

    public ChemicalEquation(String equation) throws Exception {

        super();

        this.equation = equation;

        if ((null != equation) && (!equation.equals(""))) {

            equationSides = equation.split("=");

            if (equationSides.length != 2)
                throw new Exception("This is not a valid equation");

            LHS = equationSides[0];
            RHS = equationSides[1];

            lhsParts = getParts(LHS);
            rhsParts = getParts(RHS);

        }

        this.equationSides = this.getEquationSides();

        List<ChemicalFormula> lhsParts = this.getParts(this.equationSides[0]);
        List<ChemicalFormula> rhsParts = this.getParts(this.equationSides[1]);

        this.lhsTotalChemicalCountmap = totalChemicalCountForTheGivenSide(lhsParts);
        this.rhsTotalChemicalCountmap = totalChemicalCountForTheGivenSide(rhsParts);

        this.isBalanced = true;

        if (lhsTotalChemicalCountmap.size() != rhsTotalChemicalCountmap.size())
            this.isBalanced = false;

        Iterator<Entry<String, Integer>> iterator = this.lhsTotalChemicalCountmap.entrySet().iterator();

        while (iterator.hasNext()) {

            Map.Entry<String, Integer> pairs = (Map.Entry<String, Integer>) iterator.next();

            if (this.lhsTotalChemicalCountmap.get(pairs.getKey()) != this.rhsTotalChemicalCountmap.get(pairs.getKey())) {
                this.isBalanced = false;
            }

        }

    }

    public List<ChemicalFormula> getParts(String equationSide) throws Exception {

        String[] parts;

        if ((null != equationSide) && (!equationSide.equals(""))) {

            parts = equationSide.split("-");

            List<ChemicalFormula> list = new LinkedList<ChemicalFormula>();

            for (int i = 0; i < parts.length; i++) {
                list.add(new ChemicalFormula(parts[i]));
            }

            return list;
        }

        return null;
    }

    public Map<String, Integer> totalChemicalCountForTheGivenSide(List<ChemicalFormula> parts) {

        Map<String, Integer> givenSideChemicalCount = new HashMap<String, Integer>();

        if ((null != parts) && (!parts.isEmpty())) {

            for (int i = 0; i < parts.size(); i++) {

                ChemicalFormula formula = parts.get(i);
                int count = formula.getCount();

                Map<String, Integer> map = formula.elementCountMap;

                Iterator<Entry<String, Integer>> iterator = map.entrySet().iterator();

                while (iterator.hasNext()) {

                    Map.Entry<String, Integer> pairs = (Map.Entry<String, Integer>) iterator.next();

                    if (null == givenSideChemicalCount.get(pairs.getKey())) {
                        String ch = (String) pairs.getKey();
                        int totalCount = count * (Integer) pairs.getValue();
                        givenSideChemicalCount.put(ch, totalCount);
                    } else {
                        String ch = (String) pairs.getKey();
                        int totalCount = (count * (Integer) pairs.getValue()) + givenSideChemicalCount.get(pairs.getKey());
                        givenSideChemicalCount.put(ch, totalCount);
                    }

                }
            }

        } else {
            givenSideChemicalCount = null;
        }

        return givenSideChemicalCount;

    }

    public Map<String, Integer> getLhsTotalChemicalCountmap() {
        return lhsTotalChemicalCountmap;
    }

    public void setLhsTotalChemicalCountmap(
            Map<String, Integer> lhsTotalChemicalCountmap) {
        this.lhsTotalChemicalCountmap = lhsTotalChemicalCountmap;
    }

    public Map<String, Integer> getRhsTotalChemicalCountmap() {
        return rhsTotalChemicalCountmap;
    }

    public void setRhsTotalChemicalCountmap(
            Map<String, Integer> rhsTotalChemicalCountmap) {
        this.rhsTotalChemicalCountmap = rhsTotalChemicalCountmap;
    }

    public boolean isBalanced() throws Exception {
        return this.isBalanced;
    }

    public String getLHS() {
        return LHS;
    }

    public void setLHS(String lHS) {
        LHS = lHS;
    }

    public String getRHS() {
        return RHS;
    }

    public void setRHS(String rHS) {
        RHS = rHS;
    }

    public String[] getEquationSides() {
        return equationSides;
    }

    public void setEquationSides(String[] equationSides) {
        this.equationSides = equationSides;
    }

    public String getEquation() {
        return equation;
    }

    public void setEquation(String equation) {
        this.equation = equation;
    }

    @Override
    public String toString() {
        return "ChemicalEquation [equation=" + equation + ", equationSides="
                + Arrays.toString(equationSides) + ", lhsParts=" + lhsParts
                + ", rhsParts=" + rhsParts + ", lhsTotalChemicalCountmap="
                + lhsTotalChemicalCountmap + ", rhsTotalChemicalCountmap="
                + rhsTotalChemicalCountmap + ", isBalanced=" + isBalanced + "]";
    }

    private static class ChemicalFormula {

        String formula;
        int count;
        Map<String, Integer> elementCountMap = new HashMap<String, Integer>();

        public String getFormula() {
            return formula;
        }

        public void setFormula(String formula) {
            this.formula = formula;
        }

        public Map<String, Integer> getElementCountMap() {
            return elementCountMap;
        }

        public void setElementCountMap(Map<String, Integer> elementCount) {
            this.elementCountMap = elementCount;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public ChemicalFormula(String formula) throws Exception {

            if ((null != formula) && (!formula.equals(""))) {

                this.formula = formula;

                formula = formula.trim();

                int formulaSize = formula.length();

                boolean notADigit = false;
                int x = 0;

                // get count
                if (Character.isDigit(Character.valueOf(formula.charAt(0)))) {

                    x = 1;
                    StringBuilder countStringBuilder = new StringBuilder("" + Character.valueOf(formula.charAt(0)));

                    while (true) {
                        if (notADigit || (x >= formulaSize)) {
                            break;
                        }

                        if (Character.isDigit(Character.valueOf(formula.charAt(x)))) {
                            countStringBuilder.append("" + Character.valueOf(formula.charAt(x)));
                            x++;
                        } else {
                            notADigit = true;
                        }

                    }
                    count = Integer.parseInt(countStringBuilder.toString());
                }

                String key = "";
                Integer value = null;
                boolean previousWasASymbol = false;

                while (x < formulaSize) {

                    value = null;

                    if (Character.isDigit(Character.valueOf(formula.charAt(x)))) {

                        StringBuilder countStringBuilder = new StringBuilder("");

                        while ((x < formulaSize) && (Character.isDigit(Character.valueOf(formula.charAt(x))))) {
                            countStringBuilder.append("" + Character.valueOf(formula.charAt(x)));
                            x++;
                        }

                        value = Integer.parseInt(countStringBuilder.toString());
                        elementCountMap.put(key, value);

                    } else {

                        key = "";

                        StringBuilder elementStringBuilder = null;
                        elementStringBuilder = new StringBuilder("");

                        if (Character.isUpperCase(Character.valueOf(formula.charAt(x)))) {

                            elementStringBuilder.append("" + Character.valueOf(formula.charAt(x)));
                            x++;

                            while ((x < formulaSize) && (Character.isLowerCase(Character.valueOf(formula.charAt(x))))) {
                                elementStringBuilder.append(Character.valueOf(formula.charAt(x)));
                                x++;
                            }

                        }
                        key = elementStringBuilder.toString();
                        previousWasASymbol = true;

                    }
                    if (!(key.equals("") || (null == key)) && (null != value)) {
                        elementCountMap.put(key, value);
                    }
                    if (previousWasASymbol && (null == value)) {
                        elementCountMap.put(key, new Integer(1));
                    }

                }
            }

            if (count == 0) {
                count = 1;
            }

        }

        @Override
        public String toString() {
            return "ChemicalFormula [formula=" + formula + ", count=" + count
                    + ", elementCountMap=" + elementCountMap + "]";
        }

    }

    public static String run() throws Exception {
        ChemicalEquation equation = new ChemicalEquation("NaOH-H2SO4=NaSHO4-H2O");
        return equation + " => " + equation.isBalanced;
    }

}


text:
Titanium.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Titanium.UI.createTabGroup();

//déclaration des différentes fenetres de l'app

//la splashView (page sur laquelle on tombe en lancant l'app)
var splashView = Titanium.UI.createWindow({
    title:'SplashView',
    backgroundColor:'#fff',
    url: 'views/splash.js'
});

//la page home
var homeView = Titanium.UI.createWindow({
    title:'homeView',
    backgroundColor:'#fff',
    url: 'views/home.js'
});

//la page news
var newsView = Titanium.UI.createWindow({
    title:'newsView',
    backgroundColor:'#fff',
    url: 'views/news.js'
});

//la page products
var productsView = Titanium.UI.createWindow({
    title:'productsView',
    backgroundColor:'#fff',
    url: 'views/products.js'
});

//la page contact
var contactView = Titanium.UI.createWindow({
    title:'contactView',
    backgroundColor:'#fff',
    url: 'views/contact.js'
});

//on ajoute ici les tabs btns de la tabbar menant directement aux pages
// nb: pas de tab pour accéder au splash ;p !

var homeTab = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'accueil',
    window: homeView
});

var newsTab = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'actualité',
    window: newsView ,

});

var productsTab = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'produits',
    window: productsView
});

var contactTab = Titanium.UI.createTab({
    icon:'KS_nav_views.png',
    title:'contact',
    window: contactView
});

//je crée ici un label pour la splash (et même peut etre une image de background/image tt court ...)
var splashLabel = Titanium.UI.createLabel({
	color:'#999',
	text:'I am a Splash!',
	font:{fontSize:20,fontFamily:'Helvetica Neue'},
	textAlign:'center',
	width:'auto'
});
// et je lui ajoute ici
splashView.add(splashLabel);

//j'ajoute les différents tabs btns
tabGroup.addTab(homeTab);
tabGroup.addTab(newsTab);
tabGroup.addTab(productsTab);
tabGroup.addTab(contactTab);

// on  ouvre le groupe des tabs (il faut apparement faire comme ceci ...?! )
tabGroup.open();


text:
import { Path } from '../path';
import { ResolverHost } from './resolver';
export declare type ReplacementFunction = (path: Path) => Path;
/**
 */
export declare class PatternMatchingHost<StatsT extends object = {}> extends ResolverHost<StatsT> {
    protected _patterns: Map<RegExp, ReplacementFunction>;
    addPattern(pattern: string | string[], replacementFn: ReplacementFunction): void;
    protected _resolve(path: Path): Path;
}


text:
package com.book.system.spi;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map.Entry;

import com.book.system.Book;
import com.book.system.BookForSale;
import com.book.system.SaleShelf;
import com.book.system.Seller;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;
import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.users.User;
import com.google.appengine.api.utils.SystemProperty;

/**
 * Defines v1 of a BookForSale resource as part of the bookSystem API, which provides
 * clients the ability to insert and list books for sale.
 */
@Api(
		name = "bookSystem",
		version = "v1",
		clientIds = {Ids.WEB_CLIENT_ID, Ids.ANDROID_CLIENT_ID},
		audiences = {Ids.ANDROID_AUDIENCE}
		)
public class BookForSaleV1 {

	private static final String DEFAULT_LIMIT = "10";

	@ApiMethod(name = "bookforsale.list")
	public SaleShelf list() throws OAuthRequestException,
	IOException {
		SaleShelf booksForSale = new SaleShelf();

		String url = null;
		try {
			if (SystemProperty.environment.value() ==
					SystemProperty.Environment.Value.Production) {
				// Load the class that provides the new "jdbc:google:mysql://" prefix.
				Class.forName("com.mysql.jdbc.GoogleDriver");
				url = "jdbc:google:mysql://mac-books:books/book-system?user=root&password=karma4YOU";
			} else {
				// Local MySQL instance to use during development.
				Class.forName("com.mysql.jdbc.Driver");
				url = "jdbc:mysql://173.194.81.34:3306/book-system?user=root&password=karma4YOU";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		try {
			Connection conn = DriverManager.getConnection(url);
			PreparedStatement stmt = null;
			PreparedStatement getPersonStmt = null;
			PreparedStatement getBookStmt = null;
			ResultSet resultSet = null;
			ResultSet resultSetBook = null;
			ResultSet resultSetPerson = null;
			try {
				String statement = "SELECT * FROM Book_For_Sale";
				stmt = conn.prepareStatement(statement);

				String getPerson = "SELECT * FROM Person WHERE Person_ID=?";
				getPersonStmt = conn.prepareStatement(getPerson);
				String getBook = "SELECT * FROM Book WHERE ISBN=?";
				getBookStmt = conn.prepareStatement(getBook);

				Book book = null;
				Seller seller = null;
				BookForSale bfs = null;

				resultSet = stmt.executeQuery();

				while (resultSet.next()) {
					String ISBN = resultSet.getString("ISBN");
					getBookStmt.setString(1, ISBN);
					resultSetBook = getBookStmt.executeQuery();
					resultSetBook.next();

					int personId = resultSet.getInt("Person_ID");
					getPersonStmt.setInt(1, personId);
					resultSetPerson = getPersonStmt.executeQuery();
					resultSetPerson.next();

					String title = resultSetBook.getString("Title");
					String author = resultSetBook.getString("Author");

					String firstName = resultSetPerson.getString("First_Name");
					String lastName = resultSetPerson.getString("Last_Name");
					String email = resultSetPerson.getString("Email");

					book = new Book(ISBN, author, title);
					seller = new Seller(personId, email, firstName, lastName);
					bfs = new BookForSale(book,seller);
					booksForSale.addToShelf(bfs);
					book = null;
					seller = null;
					bfs = null;
				}

			} finally {
				if(conn!=null)
					conn.close();
				if(stmt!=null)
					stmt.close();
				if(getPersonStmt!=null)
					getPersonStmt.close();
				if(getBookStmt!=null)
					getBookStmt.close();
				if(resultSet!=null)
					resultSet.close();
				if(resultSetBook!=null)
					resultSetBook.close();
				if(resultSetPerson!=null)
					resultSetPerson.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		//for(Entry<Long, List<BookForSale>> b : booksForSale.getSellerIdToList().entrySet()){
		//		System.out.println(b);
		//}

		return booksForSale;
	}

}


text:
package ir.co.dpq.pluf.test.user;

import static ir.co.dpq.pluf.test.TestCoreConstant.*;
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Test;

import ir.co.dpq.pluf.PException;
import ir.co.dpq.pluf.user.IPUserDao;
import ir.co.dpq.pluf.user.PUser;

public abstract class PUserDaoTest {

	private IPUserDao usr;

	@Before
	public void createService() {
		usr = getUserDaoInstance();
	}

	protected abstract IPUserDao getUserDaoInstance();

	@Test
	public void getSessionUser() {
		PUser user = usr.getSessionUser();
		assertNotNull(user);
	}

	@Test
	public void login() {
		PUser user = usr.login(ADMIN_LOGIN, ADMIN_PASSWORD);
		assertNotNull(user);
		assertEquals(ADMIN_LOGIN, user.getLogin());
	}

	@Test
	public void login01() {
		PUser user = usr.login(ADMIN_LOGIN, ADMIN_PASSWORD);
		assertNotNull(user);
		assertEquals(ADMIN_LOGIN, user.getLogin());
		assertNotNull(user.getLastLogin());
	}

	@Test(expected = PException.class)
	public void loginFail() {
		PUser user = usr.login("Non user name", "bad password");
		assertNotNull(user);
		assertEquals("admin", user.getLogin());
	}

	@Test
	public void logout() {
		PUser user = usr.login(ADMIN_LOGIN, ADMIN_PASSWORD);
		assertNotNull(user);
		assertEquals("admin", user.getLogin());

		usr.logout();
	}

	@Test
	public void updateUserFirstName() {
		PUser user = usr.login(ADMIN_LOGIN, ADMIN_PASSWORD);
		assertNotNull(user);
		assertEquals("admin", user.getLogin());

		String name = "maostafa" + Math.random();
		user.setFirstName(name);

		PUser nuser = usr.update(user);
		assertNotNull(nuser);
		assertEquals(name, nuser.getFirstName());
	}

	@Test
	public void updateUserEmail() {
		PUser user = usr.login(ADMIN_LOGIN, ADMIN_PASSWORD);
		assertNotNull(user);
		assertEquals(ADMIN_LOGIN, user.getLogin());

		String email = "mostafa.barmshory@dpq.co.ir";
		user.setEmail(email);

		PUser nuser = usr.update(user);
		assertNotNull(nuser);
	}

	@Test
	public void signupUserTest00() {
		usr.logout();

		String pass = "pass" + Math.random();

		PUser user = new PUser();
		user.setLogin("login" + Math.random());
		user.setFirstName("first name");
		user.setLastName("last name");
		user.setEmail("mostafa.barmshory@dpq.co.ir");
		user.setPassword(pass);

		PUser nuser = usr.signup(user);
		assertNotNull(nuser);

		PUser u = usr.login(user.getLogin(), pass);
		assertNotNull(u);
		assertEquals(user.getLogin(), u.getLogin());

		usr.logout();
	}
}


text:
import functools
import os
import stat

import smoke_zephyr.utilities

from king_phisher import constants
from king_phisher.server import pylibc

def _resolve_target_ids(user, group):
	if user is None and (group is constants.AUTOMATIC or group is None):
		raise ValueError('either user or group must be specified')

	uid = None
	gid = None
	if isinstance(user, str):
		struct_passwd = pylibc.getpwnam(user)
		uid = struct_passwd.pw_uid
		if group is constants.AUTOMATIC:
			gid = struct_passwd.pw_gid
	elif user is constants.AUTOMATIC:
		uid = os.getuid()
	elif user is None:
		uid = None
	elif isinstance(user, int):
		if user < 0:
			raise ValueError('owner must be a (zero inclusive) natural number or a user name')
		uid = user
	else:
		raise TypeError('the user argument type is unsupported')

	if isinstance(group, str):
		struct_group = pylibc.getgrnam(group)
		gid = struct_group.gr_gid
	elif group is constants.AUTOMATIC:
		if uid is None:
			raise ValueError('can not resolve a group without a uid')
		if gid is None:  # check if this was resolved already before calling into libc
			struct_passwd = pylibc.getpwuid(uid)
			gid = struct_passwd.pw_gid
	elif group is None:
		gid = None
	elif isinstance(group, int):
		if group < 0:
			raise ValueError('group must be a (zero inclusive) natural number or a group name')
		gid = group
	return uid, gid

def _test_mode(st_mode, mode, ir_flag, iw_flag, ix_flag):
	test_flags = 0
	if mode & os.R_OK:
		test_flags |= ir_flag
	if mode & os.W_OK:
		test_flags |= iw_flag
	if mode & os.X_OK:
		test_flags |= ix_flag
	return (st_mode & test_flags) == test_flags

def chown(path, user=None, group=constants.AUTOMATIC, recursive=True):
	"""
	This is a high-level wrapper around :py:func:`os.chown` to provide
	additional functionality. ``None`` can be specified as the *user* or *group*
	to leave the value unchanged. At least one of either *user* or *group* must
	be specified.

	.. versionadded:: 1.14.0

	:param str path: The path to change the owner information for.
	:param user: The new owner to set for the path. If set to
		:py:class:`~king_phisher.constants.AUTOMATIC`, the process's current uid
		will be used.
	:type user: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC`
	:param group: The new group to set for the path. If set to
		:py:class:`~king_phisher.constants.AUTOMATIC`, the group that *user*
		belongs too will be used.
	:type group: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC`
	:param bool recursive: Whether or not to recurse into directories.
	"""
	uid, gid = _resolve_target_ids(user, group)
	if uid is None:
		uid = -1
	if gid is None:
		gid = -1
	if recursive:
		# set *filter_func* to skip paths that may have come from broken links
		iterator = smoke_zephyr.utilities.FileWalker(path, filter_func=os.path.exists)
	else:
		iterator = (path,)
	for path in iterator:
		os.chown(path, uid, gid)

def access(path, mode, user=constants.AUTOMATIC, group=constants.AUTOMATIC):
	"""
	This is a high-level wrapper around :py:func:`os.access` to provide
	additional functionality. Similar to `os.access` this high-level wrapper
	will test the given path for a variety of access modes. Additionally *user*
	or *group* can be specified to test access for a specific user or group.

	.. versionadded:: 1.14.0

	:param str path: The path to test access for.
	:param int mode: The mode to test access for. Set to `os.R_OK` to test for
		readability, `os.W_OK` for writability and `os.X_OK` to determine if
		path can be executed.
	:param user: The user to test permissions for. If set to
		:py:class:`~king_phisher.constants.AUTOMATIC`, the process's current uid
		will be used.
	:type user: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC`
	:param group: The group to test permissions for. If set to
		:py:class:`~king_phisher.constants.AUTOMATIC`, the group that *user*
		belongs too will be used.
	:type group: int, str, ``None``, :py:class:`~king_phisher.constants.AUTOMATIC`
	:return: Returns ``True`` only if the user or group has the mode of
		permission specified else returns ``False``.
	:rtype: bool
	"""
	uid, gid = _resolve_target_ids(user, group)
	file_info = os.stat(path)

	# If there are no permissions to check for then yes the user has no more than no permissions.
	if not mode:
		return True

	__test_mode = functools.partial(_test_mode, file_info.st_mode, mode)

	# Other checks
	if __test_mode(stat.S_IROTH, stat.S_IWOTH, stat.S_IXOTH):
		return True

	# User Checks
	if file_info.st_uid == uid and __test_mode(stat.S_IRUSR, stat.S_IWUSR, stat.S_IXUSR):
		return True

	# Group checks
	if file_info.st_gid == gid and __test_mode(stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP):
		return True

	# If there were no groups specified then enumerate all of the users gids and test them all.
	if group == constants.AUTOMATIC:
		if not isinstance(user, str):
			user = pylibc.getpwuid(uid).pw_name
		# Check all the groups
		if file_info.st_gid in pylibc.getgrouplist(user) and __test_mode(stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP):
			return True
	return False


text:
package studentclass2805cwk1;

/**
 *
 * @author MyDocs
 */
public class StudentAddress extends Student{
    private String address;

    //Default Constructor
    public StudentAddress(){

    }

    public StudentAddress(String address){
        this.address = address;
    }

    public void setAddress(String address){
        this.address = address;
    }

    public String getAddress(){
        return address;
    }

}