text:
#include "configuration.h"

#include <spdlog/spdlog.h>

#include <string>
#include <fstream>
#include <sstream>
#include <filesystem>
#include <regex>

using nlohmann::json;
namespace fs = std::filesystem;
using Point = b2Vec2;

namespace zombie {

	namespace {

		const std::string SettingsPath = "settings/settings.json";
		const std::string MapsPath = "settings/maps.json";
		const std::string MissilesPath = "settings/missiles";
		const std::string UnitsPath = "settings/units";
		const std::string CarsPath = "settings/cars";
		const std::string WeaponsPath = "settings/weapons";

	}

	namespace {

		// Takes a string as input and returns the point.
		// The string "POINT (x y)" the input should be defined
		// as "POINT (...)".
		Point loadPoint(std::string line) {
			std::stringstream stream(line);

			std::string word;
			stream >> word;
			assert(word == "POINT");

			char chr;
			stream >> chr;
			assert(chr == '(');
			Point point;
			stream >> point.x;
			stream >> point.y;
			return point;
		}

		// Takes a string as input and returns the points.
		// The string "POLYGON ((x1 y1, x2 y2, ...))" the input should be defined
		// as "POLYGON ((...))". The last point is assumed to be the same as the first, therefore
		// the last point will not be includeded in the returned vector.
		std::vector<Point> loadPolygon(std::string line) {
			std::stringstream stream(line);
			std::string word;

			stream >> word;
			assert(word == "POLYGON");

			char paranthes;
			stream >> paranthes;
			assert(paranthes == '(');
			stream >> paranthes;
			assert(paranthes == '(');

			Point point;
			std::vector<Point> points;

			while (stream >> point.x && stream >> point.y) {
				points.push_back(point);
				char comma;
				if (!(stream >> comma)) {
					break;
				}
			}
			points.pop_back();
			return points;
		}

		bool isJsonFile(const std::string name) {
			try {
				static const std::regex jsonRegex(R"(.*\.[Jj][Ss][Oo][Nn])");
				static const std::regex schemaRegex(R"(.*\.schema\.[Jj][Ss][Oo][Nn])");
				std::smatch match;
				if (std::regex_match(name, match, jsonRegex) && !std::regex_match(name, match, schemaRegex)) {
					return true;
				}
			} catch (const std::regex_error& error) {
				spdlog::critical("[zombie::Configuration] Programming error: {}", error.what());
				std::exit(1);
			}
			return false;
		}

	}

	Configuration::Configuration()
		: textureAtlas_{2048, 2048, []() {
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	}} {
		spdlog::info("[Configuration] Current path: {}", fs::current_path().string());

		spdlog::info("[Configuration] Load: {}", SettingsPath);
		if (std::ifstream file{SettingsPath}; file) {
			file >> settings_;
		} else {
			spdlog::critical("[Configuration] Failed to load: {}", SettingsPath);
			return;
		}

		auto map = settings_["settings"]["map"].get<std::string>();
		spdlog::info("[Configuration] Load: {}", map);
		if (std::ifstream file{map}; file) {
			file >> rootMap_;
		} else {
			spdlog::critical("[Configuration] Fail to load: {}", map);
			return;
		}

		loadAllWeaponProperties();
		loadAllMissileProperties();
		loadAllUnitProperties();
	}

	void Configuration::loadAllWeaponProperties() {
		for (const auto& fileName : fs::directory_iterator{WeaponsPath}) {
			if (fileName.is_regular_file() && isJsonFile(fileName.path().string())) {
				spdlog::info("[Configuration] Load: {}", fileName.path().string());
				if (std::ifstream file{fileName.path()}; file) {
					nlohmann::json weaponJson;
					file >> weaponJson;
					weaponPropertiesMap_[weaponJson["name"].get<std::string>()] = loadWeaponProperties(weaponJson);
				} else {
					spdlog::critical("[Configuration] Fail to load: {}", fileName.path().string());
				}
			}
		}
	}

	void Configuration::loadAllMissileProperties() {
		for (const auto& fileName : fs::directory_iterator{MissilesPath}) {
			if (fileName.is_regular_file() && isJsonFile(fileName.path().string())) {
				spdlog::info("[Configuration] Load: {}", fileName.path().string());
				if (std::ifstream file{fileName.path()}; file) {
					nlohmann::json missileJson;
					file >> missileJson;
					missilePropertiesMap_[missileJson["name"].get<std::string>()] = loadMissileProperties(missileJson);
				} else {
					spdlog::critical("[Configuration] Fail to load: {}", fileName.path().string());
				}
			}
		}
	}

	void Configuration::loadAllUnitProperties() {
		for (const auto& fileName : fs::directory_iterator(UnitsPath)) {
			if (fileName.is_regular_file() && isJsonFile(fileName.path().string())) {
				spdlog::info("[Configuration] Load: {}", fileName.path().string());
				if (std::ifstream file{fileName.path()}; file) {
					nlohmann::json unitJson;
					file >> unitJson;
					unitPropertiesMap_[unitJson["name"].get<std::string>()] = loadUnitProperties(unitJson);
				} else {
					spdlog::critical("[Configuration] Fail to load: {}", fileName.path().string());
				}
			}
		}
	}

	void Configuration::save() {
		std::ofstream out{SettingsPath};
		//settings_ >> out;
	}

	const sdl::Font& Configuration::loadFont(const std::string& file, int fontSize) {
		auto size = fonts_.size();
		std::string key = file;
		key += fontSize;
		sdl::Font& font = fonts_[key];

		// Font not found?
		if (fonts_.size() > size) {
			font = sdl::Font{file, fontSize};
		}

		return font;
	}

	sdl::Sound Configuration::loadSound(const std::string& file) {
		auto size = sounds_.size();
		sdl::Sound& sound = sounds_[file];

		// Sound not found?
		if (sounds_.size() > size) {
			sound = sdl::Sound{file};
		}

		return sound;
	}

	sdl::Music Configuration::loadMusic(const std::string& file) {
		auto size = musics_.size();
		sdl::Music& music = musics_[file];

		// Music not found?
		if (musics_.size() > size) {
			music = sdl::Music{file};
		}

		return music;
	}

	sdl::TextureView Configuration::loadSprite(const std::string& file) {
		return textureAtlas_.add(file, 1).getTextureView();
	}

	const sdl::Font& Configuration::getDefaultFont(int size) {
		return loadFont(settings_["window"]["font"].get<std::string>(), size);
	}

	void Configuration::bindTextureFromAtlas() {
		textureAtlas_.bind();
	}

	int Configuration::getWindowPositionX() {
		return settings_["window"]["positionX"].get<int>();
	}

	int Configuration::getWindowPositionY() {
		return settings_["window"]["positionY"].get<int>();
	}

	void Configuration::setWindowPositionX(int x) {
		settings_["window"]["positionX"] = x;
	}

	void Configuration::setWindowPositionY(int y) {
		settings_["window"]["positionY"] = y;
	}

	int Configuration::getWindowWidth() {
		return settings_["window"]["width"].get<int>();
	}

	int Configuration::getWindowHeight() {
		return settings_["window"]["height"].get<int>();
	}

	void Configuration::setWindowWidth(int width) {
		settings_["window"]["width"] = width;
	}

	void Configuration::setWindowHeight(int height) {
		settings_["window"]["height"] = height;
	}

	bool Configuration::isWindowResizable() {
		return settings_["window"]["resizeable"].get<bool>();
	}

	void Configuration::setWindowResizable(bool resizeable) {
		settings_["window"]["resizeable"] = resizeable;
	}

	int Configuration::getWindowMinWidth() {
		return settings_["window"]["minWidth"].get<int>();
	}

	int Configuration::getWindowMinHeight() {
		return settings_["window"]["minHeight"].get<int>();
	}

	std::string Configuration::getWindowIcon() {
		return settings_["window"]["icon"].get<std::string>();
	}

	bool Configuration::isWindowBordered() {
		return settings_["window"]["border"].get<bool>();
	}

	void Configuration::setWindowBordered(bool border) {
		settings_["window"]["border"] = border;
	}

	bool Configuration::isWindowMaximized() {
		return settings_["window"]["maximized"].get<bool>();
	}

	void Configuration::setWindowMaximized(bool maximized) {
		settings_["window"]["maximized"] = maximized;
	}

	bool Configuration::isWindowVsync() {
		return settings_["window"]["vsync"].get<bool>();
	}

	void Configuration::setWindowVsync(bool activate) {
		settings_["window"]["vsync"] = activate;
	}

	bool Configuration::isMusicOn() {
		return settings_["music"]["switch"].get<bool>();
	}

	void Configuration::setMusicOn(bool maximized) {
		settings_["music"]["music"] = maximized;
	}

	float Configuration::getMusicVolume() {
		return settings_["music"]["volume"].get<float>();
	}

	void Configuration::setMusicVolume(float volume) {
		settings_["music"]["volume"] = volume;
	}

	sdl::Music Configuration::getMusicTrack() {
		return loadMusic(settings_["music"]["track"].get<std::string>());
	}

	sdl::TextureView Configuration::getTreeImage() {
		return loadSprite(settings_["tree"].get<std::string>());
	}

	sdl::TextureView Configuration::getBuildingWallImage() {
		return loadSprite(settings_["buildings"]["wallImage"].get<std::string>());
	}

	float Configuration::getSettingsImpulseThreshold() {
		return settings_["settings"]["impulseThreshold"].get<float>();
	}

	float Configuration::getSettingsTimeStep() {
		return settings_["settings"]["timeStep"].get<float>();
	}

	float Configuration::getSettingsInnerSpawnRadius() {
		return settings_["settings"]["innerSpawnRadius"].get<float>();
	}

	float Configuration::getSettingsOuterSpawnRadius() {
		return settings_["settings"]["outerSpawnRadius"].get<float>();
	}

	int Configuration::getSettingsUnitLevel() {
		return settings_["settings"]["unitLevel"].get<int>();
	}

	int Configuration::getSettingsUnitLimit() {
		return settings_["settings"]["unitLimit"].get<int>();
	}

	std::string Configuration::getSettingsMap() {
		return settings_["settings"]["map"].get<std::string>();
	}

	sdl::Sound Configuration::getMenuSoundChoice() {
		return loadSound(settings_["menu"]["soundChoice"].get<std::string>());
	}

	sdl::Sound Configuration::getMenuSoundHighlited() {
		return loadSound(settings_["menu"]["soundHighlited"].get<std::string>());
	}

	sdl::TextureView Configuration::getMenuBackgroundImage() {
		return loadSprite(settings_["menu"]["backgroundImage"].get<std::string>());
	}

	sdl::TextureView Configuration::getWaterSeeFloorImage() {
		return loadSprite(settings_["water"]["seeFloorImage"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadIntersection() {
		return loadSprite(settings_["roads"]["intersection"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadStraight0() {
		return loadSprite(settings_["roads"]["straight0"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadStraight90() {
		return loadSprite(settings_["roads"]["straight90"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadTurn0() {
		return loadSprite(settings_["roads"]["turn0"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadTurn90() {
		return loadSprite(settings_["roads"]["turn90"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadTurn180() {
		return loadSprite(settings_["roads"]["turn180"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadTurn270() {
		return loadSprite(settings_["roads"]["turn270"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadTurnIntersection0() {
		return loadSprite(settings_["roads"]["tintersection0"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadTurnIntersection90() {
		return loadSprite(settings_["roads"]["tintersection90"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadTurnIntersection180() {
		return loadSprite(settings_["roads"]["tintersection180"].get<std::string>());
	}

	sdl::TextureView Configuration::getRoadTurntersection270() {
		return loadSprite(settings_["roads"]["tintersection270"].get<std::string>());
	}

	/*
	ExplosionProperties Configuration::getExplosionProperties() {
		float timeDelay = settings_["explosion"]["timeDelay"].get<float>();
		float speed = settings_["explosion"]["speed"].get<float>();
		sdl::Sound sound = loadSound(settings_["explosion"]["sound"].get<std::string>());
		Animation animation = loadAnimation(settings_["explosion"]["animation"]);
		animation.setLooping(false);
		return ExplosionProperties(animation, sound, timeDelay);
	}
	*/

	UnitProperties Configuration::getHumanProperties() {
		return unitPropertiesMap_[std::string("human")];
	}

	UnitProperties Configuration::getZombieProperties() {
		return unitPropertiesMap_[std::string("zombie")];
	}

	/*
	Animation Configuration::loadAnimation(const json& animationTag) {
		float defaultDeltaTime = 1.f;
		try {
			defaultDeltaTime = animationTag.at("deltaTime").get<float>();
		} catch (nlohmann::detail::out_of_range) {
			// Do nothing.
		}

		float defaultBodyWidth = 1.f;
		try {
			defaultBodyWidth = animationTag.at("bodyWidth").get<float>();
		} catch (nlohmann::detail::out_of_range) {
			// Do nothing.
		}

		Animation animation;
		try {
			for (const auto& child : animationTag.at("frames")) {
				float bodyWidth = defaultBodyWidth;
				try {
					bodyWidth = child.at("bodyWidth").get<float>();
				} catch (nlohmann::detail::out_of_range) {
					// Do nothing.
				}

				float deltaTime = defaultDeltaTime;
				try {
					deltaTime = child.at("time").get<float>();
				} catch (nlohmann::detail::out_of_range) {
					// Do nothing.
				}

				auto n = child["image"].get<std::string>();
				animation.add(loadSprite(child["image"].get<std::string>()), bodyWidth, deltaTime);
			}
		} catch (nlohmann::detail::out_of_range) {
			// Do nothing.
		}

		return animation;
	}
	*/

	MissileProperties Configuration::getMissileProperties() {
		try {
			return missilePropertiesMap_.at(std::string("missile"));
		} catch (const std::out_of_range&) {
			return {};
		}
	}

	UnitProperties Configuration::loadUnitProperties(const json& unitTag) {
		UnitProperties unitProperties;
		//unitProperties.hitSound = loadSound(unitTag["hitSound"].get<std::string>());
		//unitProperties.dieSound = loadSound(unitTag["dieSound"].get<std::string>());
		//unitProperties.moveAnimation_ = loadAnimation(unitTag["moveAnimation"]);
		//unitProperties.dieAnimation_ = loadAnimation(unitTag["dieAnimation"]);
		//unitProperties.injuredAnimation_ = loadAnimation(unitTag["injuredAnimation"]);
		//unitProperties.grip = Position(unitTag["moveImageGripX"].get<float>(), unitTag["moveImageGripY"].get<float>());
		unitProperties.mass = unitTag["mass"].get<float>();
		unitProperties.radius = unitTag["radius"].get<float>();
		unitProperties.life = unitTag["life"].get<float>();
		unitProperties.walkingSpeed = unitTag["walkingSpeed"].get<float>();
		unitProperties.runningSpeed = unitTag["runningSpeed"].get<float>();
		//unitProperties.stamina = unitTag["stamina"].get<float>();
		//unitProperties.weaponProperties = loadWeaponProperties(unitTag["weapon"].get<std::string>());
		return unitProperties;
	}

	WeaponProperties Configuration::loadWeaponProperties(std::string weaponName) {
		try {
			return weaponPropertiesMap_.at(weaponName);
		} catch (const std::out_of_range&) {
			return WeaponProperties();
		}
	}

	WeaponProperties Configuration::loadWeaponProperties(const json& unitTag) {
		WeaponProperties properties;
		//properties.name = unitTag["name"].get<std::string>();
		properties.type = WeaponProperties::Type::Bullet;
		auto s = unitTag["type"].get<std::string>();
		if (unitTag["type"].get<std::string>() == "BULLET") {
			properties.type = WeaponProperties::Type::Bullet;
		} else if (unitTag["type"].get<std::string>() == "MISSILE") {
			properties.type = WeaponProperties::Type::Missile;
		} else {
			throw 1;
		}
		//properties.symbolImage = loadSprite(unitTag["symbolImage"].get<std::string>());
		properties.timeBetweenShots = unitTag["timeBetweenShots"].get<float>();
		properties.clipSize = unitTag["clipSize"].get<int>();
		//properties.shootSound = loadSound(unitTag["shootSound"].get<std::string>());
		//properties.reloadSound = loadSound(unitTag["reloadSound"].get<std::string>());
		//properties.moveAnimation_ = loadAnimation(unitTag["moveAnimation"]);
		properties.size = unitTag["size"].get<float>();
		properties.moveImageGrip = Position(unitTag["moveImageGripX"].get<float>(), unitTag["moveImageGripY"].get<float>());

		// Projectile properties.
		properties.damage = unitTag["projectile"]["damage"].get<float>();
		properties.range = unitTag["projectile"]["range"].get<float>();
		properties.laserSight = unitTag["laserSight"].get<bool>();
		switch (properties.type) {
			case WeaponProperties::Type::Bullet:
				break;
			case WeaponProperties::Type::Missile:
				properties.damageRadius = unitTag["projectile"]["damageRadius"].get<float>();
				properties.deathTime = unitTag["projectile"]["deathTime"].get<float>();
				properties.speed = unitTag["projectile"]["speed"].get<float>();
				properties.force = unitTag["projectile"]["force"].get<float>();
				properties.missileProperties = loadMissileProperties(std::string("missile"));
				break;
		}

		return properties;
	}

	MissileProperties Configuration::loadMissileProperties(std::string missileName) {
		for (const auto& child : settings_["missiles"]) {
			std::string name = child["name"].get<std::string>();
			if (name == missileName) {
				return loadMissileProperties(child);
			}
		}
		return MissileProperties();
	}

	MissileProperties Configuration::loadMissileProperties(const json& unitTag) {
		MissileProperties properties;
		//properties.name = unitTag["name"].get<std::string>();
		properties.mass = unitTag["mass"].get<float>();
		properties.width = unitTag["width"].get<float>();
		properties.length = unitTag["length"].get<float>();
		//properties.animation_ = loadAnimation(unitTag["animation"]);
		//properties.moveSound = loadSound(unitTag["moveSound"].get<std::string>());
		return properties;
	}

}


text:
import jss from '../jss'
import * as utils from '../utils'
import * as markerTpl from './marker-tpl'
import {rules} from './style'

const sheet = jss.createStyleSheet(rules)

/**
 * Returns true if integer.
 *
 * @param {Number} n
 * @return {Boolean}
 */
function isInt(n) {
  return n % 1 === 0
}

/**
 * Get PM/AM suffix.
 *
 * @param {Number} min
 * @return {String}
 */
function getSuffix(min) {
  const h = min / 60
  if (!isInt(h)) return false
  if (h < 12) return 'AM'
  return 'PM'
}

/**
 * Format time according the layout.
 *
 * @param {Number} min
 * @return {String}
 */
function formatTime(min) {
  let h = min / 60
  if (h > 12.5) h -= 12
  return isInt(h) ? `${h}:00` : `${Math.floor(h)}:30`
}

export default class Timeline {
  /**
   * Creates a timeline view.
   */
  constructor(options) {
    this.element = null
    this.start = options.start
    this.end = options.end
  }

  /**
   * Creates timeline elements.
   *
   * @return {Timeline}
   */
  create() {
    sheet.attach()
    this.element = utils.createElement('div', {
      class: sheet.classes.timeline
    })

    const fragment = document.createDocumentFragment()
    for (let min = this.start; min < this.end; min += 30) {
      fragment.appendChild(
        this.createMarker({
          suffix: getSuffix(min),
          time: formatTime(min),
          min
        })
      )
    }
    this.element.appendChild(fragment)
    return this
  }

  /**
   * Create time marker element.
   *
   * @param {Obejct} options
   * @return {Element}
   */
  createMarker(options) {
    const element = utils.createElement('div', {
      class: sheet.classes.timeContainer
    })
    element.style.top = `${utils.minToY(options.min - this.start)}px`
    element.innerHTML = markerTpl.compile({
      time: options.time,
      classes: sheet.classes,
      suffix: options.suffix
    })
    return element
  }
}

redpajama_set_name: RedPajamaGithub


text:
package tk.charlieuk.didactic_octo_tribble;

import android.os.*;

public class Backgrounder extends AsyncTask<Void, Void, Void> {

    public Thread main, post;

    public Backgrounder( Thread main, Thread post) {
        this.main=main;
        this.post=post;
    }

    public Void doInBackground(Void... Void) {
        if(main != null)
            main.run();

        return null;
    }

    public void onPostExecute(Void Void) {
        if(post != null)
            post.run();
    }
}


text:
package org.lemsml.jlems.core.type.procedure;

import org.lemsml.jlems.core.run.ExecutablePrint;
import org.lemsml.jlems.core.run.ExecutableStatement;
import org.lemsml.jlems.core.sim.ContentError;
import org.lemsml.jlems.core.type.Lems;

public class Print extends Statement {

	public String template;

	@Override
	public ExecutableStatement makeExecutableStatement(Lems lems) throws ContentError {
		ExecutablePrint ep = new ExecutablePrint(template, lems);
		return ep;
	}

}


text:
package cn.edu.zjnu.acm.judge.controller.submission;

import cn.edu.zjnu.acm.judge.data.dto.SubmissionDetailDTO;
import cn.edu.zjnu.acm.judge.domain.Contest;
import cn.edu.zjnu.acm.judge.domain.Submission;
import cn.edu.zjnu.acm.judge.exception.BusinessCode;
import cn.edu.zjnu.acm.judge.exception.BusinessException;
import cn.edu.zjnu.acm.judge.mapper.ContestMapper;
import cn.edu.zjnu.acm.judge.service.SubmissionService;
import cn.edu.zjnu.acm.judge.util.ResultType;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import static org.springframework.http.MediaType.TEXT_HTML_VALUE;

/**
 * @author zhanhb
 */
@Controller
@RequestMapping(produces = TEXT_HTML_VALUE)
@RequiredArgsConstructor
public class ShowSubmissionDetailsController {

    private final ContestMapper contestMapper;
    private final SubmissionService submissionService;

    @GetMapping("showsolutiondetails")
    public String showSolutionDetails(
            HttpServletRequest request,
            @RequestParam("solution_id") long submissionId) {
        Submission submission = submissionService.findById(submissionId);
        Long contestId = submission.getContest();
        if (contestId != null) {
            Contest contest = contestMapper.findOne(contestId);
            if (contest != null) {
                request.setAttribute("contestId", contest.getId());
            }
        }
        if (!submissionService.canView(request, submission)) {
            throw new BusinessException(BusinessCode.VIEW_SOURCE_PERMISSION_DENIED, submissionId);
        }
        List<SubmissionDetailDTO> details = submissionService.getSubmissionDetail(submissionId);
        request.setAttribute("details", details);
        request.setAttribute("user", submission.getUser());
        request.setAttribute("problem", submission.getProblem());
        request.setAttribute("result", ResultType.getResultDescription(submission.getScore()));
        request.setAttribute("score", submission.getScore());
        request.setAttribute("time", submission.getTime());
        request.setAttribute("memory", submission.getMemory());
        return "submissions/detail";
    }

}


text:
package servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

import user.User;

public abstract class BasicServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static UserService userService = UserServiceFactory.getUserService();

	protected PrintWriter out;
	protected User user;
	protected HttpServletRequest request;
	protected HttpServletResponse response;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		this.request = req;
		this.response = resp;
		resp.setContentType("text/html");
		user = User.getCurrentUser();
		out = resp.getWriter();
		validateUser();
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		this.request = req;
		this.response = resp;
		resp.setContentType("text/html");
		user = User.getCurrentUser();
		out = resp.getWriter();
		validateUser();
	}

	private void validateUser() throws IOException{
		if (user == null) {
			redirectToLogin();
			throw new IOException();
		}
	}

	private void redirectToLogin() {
		out.write("You are not logged in! Login <a href='" + userService.createLoginURL(request.getRequestURI()) + "'> here </a>");

	}
}


text:
using System;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using SignalRDashboard.Data.Core.Pollers;
using SignalRDashboard.Data.Milliman.DataSources;
using SignalRDashboard.Data.Milliman.Hubs;
using SignalRDashboard.Data.Milliman.Hubs.Models;

namespace SignalRDashboard.Data.Milliman.Pollers
{
    public class TwitterStatusPoller : DatasourcePoller<TwitterStatus, TwitterStatusHub>
    {
        private static readonly Lazy<TwitterStatusPoller> PollerInstance = new Lazy<TwitterStatusPoller>(() => new TwitterStatusPoller(GlobalHost.ConnectionManager.GetHubContext<TwitterStatusHub>().Clients));
        private readonly TwitterStatusProvider _provider;
        private int _lastTweetId;
        private DateTime _lastTweetDateTime = DateTime.Now;

        private TwitterStatusPoller(IHubConnectionContext<dynamic> clients)
            : base(clients, TimeSpan.FromSeconds(10), new PollWhereUsersAreConnectedOrNotStrategy())
        {
            _provider = new TwitterStatusProvider();
        }

        public static TwitterStatusPoller Instance => PollerInstance.Value;

        protected override void RefreshData(TwitterStatus model)
        {
            var data = _provider.GetTwitterStatus();
            var lastTweet = data.LastTweet.Trim();
            var lastTweetId = data.LastTweetId;
            var lastTweetTime = $"{data.LastTweetDateTime:t}";
            var lastTweetDateTime = data.LastTweetDateTime.ToUniversalTime();
            model.TweetIsNew = false;

            if (lastTweetDateTime > _lastTweetDateTime)
            {
                model.TweetIsNew = _lastTweetId > 0;
                model.LastTweet = lastTweet;
                model.LastTweetTime = lastTweetTime;
                _lastTweetId = lastTweetId;
                _lastTweetDateTime = lastTweetDateTime;
            }
        }

        protected override void BroadcastData(TwitterStatus model)
        {
            Clients.All.updateTwitterStatus(model);
        }
    }
}


text:
import React, {Component} from 'react';

export default class Snippet extends Component{
  constructor(props){
    super(props);
    this.trackClick = this.trackClick.bind(this);
  }
  trackClick(){
    ga('send', 'event', 'View Snippet Source', 'click', this.props.name);
  }
  render(){
    const sourceUrl = this.props.githubUrl + "/tree/master/src/components/snippets/" + this.props.name;
    return(

{this.props.name}

{this.props.description}

            {this.props.children}

          View Snippet Source

    );
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://camel.apache.org/schema/spring
       http://camel.apache.org/schema/spring/camel-spring.xsd
	http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">

  <camelContext xmlns="http://camel.apache.org/schema/spring">
    <endpoint id="start" uri="direct:start"/>
    <endpoint id="result" uri="mock:end"/>
  </camelContext>

  <bean id="explicitlyDefinedRoute" class="org.apache.camel.spring.config.scan.route.MyRouteBuilder" autowire="byType" />
  <bean id="explicitlyDefinedButExcludedRoute" class="org.apache.camel.spring.config.unscanned.MyExplicitlyDefinedButExcludedRouteBuilder" />

  <context:component-scan base-package="org.apache.camel.spring.config.scan.component" />

</beans>


text:
export type Difficulty = "Easy" | "Hard";
export type PlayerColor = "Red" | "Black";
export type Cell = {
    col: number
    row: number
    value: PlayerColor | "Empty"
}
export type Board = Array<Array<Cell>>;
export type Move = {
    player: PlayerColor,
    column: number
}
export type AIPlayer = {
    difficulty: Difficulty
    my_color: PlayerColor
}
export type Game = {
    board: Board
    moves: Array<Move>;
    winner: PlayerColor | null
}
export type State = {
    game: Game | null
    ai: AIPlayer | null
}


text:
<?php

/**
 * @file
 * Contains \FastFrame\Utility\NestedArrayHelper
 */

namespace FastFrame\Utility;

/**
 * Utility functions for dealing with nested arrays
 *
 * This uses dotted notation (some.where.over.the.rainbow)
 *
 * @package FastFrame\Utility
 */
class NestedArrayHelper
{
	const DEFAULT_SEPARATOR = '.';

	/**
	 * The separator to split strings
	 *
	 * @var string
	 */
	protected static $separator = self::DEFAULT_SEPARATOR;

	/**
	 * Changes the separator used in {convertToArray()}
	 *
	 * @param string $separator
	 */
	public static function setSeparator($separator = self::DEFAULT_SEPARATOR)
	{
		static::$separator = $separator;
	}

	/**
	 * Returns the value at the given path
	 *
	 * Returns the default value if not specified
	 *
	 * @param array        $ary
	 * @param string|array $key
	 * @param null         $alt
	 * @return array|null
	 */
	public static function &get(array &$ary, $key, $alt = null)
	{
		$key   = self::convertToArray($key);
		$ref   =& $ary;
		$found = false;
		while (($node = array_shift($key)) !== null) {
			if (is_array($ref) && array_key_exists($node, $ref)) {
				$ref   =& $ref[$node];
				$found = true;
				continue;
			}

			$found = false;
			break;
		}

		if ($found) {
			return $ref;
		}

		return $alt;
	}

	/**
	 * Sets the value at the given path
	 *
	 * @param array        $ary
	 * @param string|array $key
	 * @param mixed        $value
	 */
	public static function set(array &$ary, $key, $value)
	{
		$key = self::convertToArray($key);
		while (($node = array_shift($key)) !== null) {
			if (is_array($ary) && array_key_exists($node, $ary)) {
				if (!empty($key)) {
					$ary =& $ary[$node];
					continue;
				}
			}
			elseif (!empty($key)) {
				$ary[$node] = [];
				$ary        =& $ary[$node];
				continue;
			}

			$ary[$node] = $value;
		}
	}

	/**
	 * Returns whether or not the array has the given key
	 *
	 * If you are going to use the value it's better to use NestedArray::get() instead of this function
	 *
	 * @param array        $ary
	 * @param string|array $key
	 * @return bool
	 */
	public static function has(array &$ary, $key)
	{
		$key = self::convertToArray($key);
		while (($node = array_shift($key)) !== null) {
			if (is_array($ary) && array_key_exists($node, $ary)) {
				$ary =& $ary[$node];
				continue;
			}

			return false;
		}

		return true;
	}

	/**
	 * Merges arrays better than array_merge_recursive
	 *
	 * The first array becomes the base for comparison on merge.
	 *
	 * @param array ...$arys
	 * @return array|mixed
	 */
	public static function deepMerge()
	{
		$arys  = func_get_args();
		$prime = array_shift($arys);

		while ($ary = array_shift($arys)) {
			$copy = array_diff_key($ary, $prime);
			foreach ($ary as $key => $value) {
				if (!array_key_exists($key, $copy) && (is_array($prime[$key]) || is_array($value))) {
					$prime[$key] = self::deepMerge((array)$prime[$key], (array)$value);
					continue;
				}
				$prime[$key] = $value;
			}
		}

		return $prime;
	}

	/**
	 * Expands the array from dotted notation
	 *
	 * @param array $ary
	 * @return array
	 */
	public static function expand(array &$ary)
	{
		$newAry = [];
		foreach ($ary as $key => $value) {
			self::set($newAry, $key, $value);
		}

		return $newAry;
	}

	/**
	 * Compresses the array into dotted notation
	 *
	 * @param array $ary
	 * @return array
	 */
	public static function compress(array &$ary)
	{
		$newAry = [];
		foreach ($ary as $k1 => $v1) {
			if (is_array($v1)) {
				foreach (self::compress($v1) as $k2 => $v2) {
					$newAry["$k1.$k2"] = $v2;
				}
				continue;
			}

			self::set($newAry, $k1, $v1);
		}

		return $newAry;
	}

	/**
	 * Plucks the requested value from the array into an array
	 *
	 * @param array       $ary
	 * @param string      $value
	 * @param string|null $key
	 * @return array
	 */
	public static function pluck(array &$ary, $value, $key = null)
	{
		$values = [];
		foreach ($ary as $itemKey => $item) {
			if (static::has($item, $value) &&
				($key === null || ($itemKey = static::get($item, $key)) !== null)
			) {
				$values[$itemKey] = static::get($item, $value);
			}
		}

		return $values;
	}

	/**
	 * Converts the given nodes into an array if needed
	 *
	 * @param string|array $key
	 * @return array
	 */
	protected static function convertToArray($key)
	{
		return is_array($key) ? $key : explode(static::$separator, $key);
	}
}


text:
package org.apache.activemq.artemis.spi.core.security.jaas;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.activemq.artemis.core.server.ActiveMQServerLogger;
import org.jboss.logging.Logger;

public class ReloadableProperties {

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

   private Properties props = new Properties();
   private Map<String, String> invertedProps;
   private Map<String, Set<String>> invertedValueProps;
   private long reloadTime = -1;
   private final PropertiesLoader.FileNameKey key;

   public ReloadableProperties(PropertiesLoader.FileNameKey key) {
      this.key = key;
   }

   public synchronized Properties getProps() {
      return props;
   }

   public synchronized ReloadableProperties obtained() {
      if (reloadTime < 0 || (key.isReload() && hasModificationAfter(reloadTime))) {
         props = new Properties();
         try {
            load(key.file(), props);
            invertedProps = null;
            invertedValueProps = null;
            if (key.isDebug()) {
               logger.debug("Load of: " + key);
            }
         } catch (IOException e) {
            ActiveMQServerLogger.LOGGER.failedToLoadProperty(e, key.toString(), e.getLocalizedMessage());
            if (key.isDebug()) {
               logger.debug("Load of: " + key + ", failure exception" + e);
            }
         }
         reloadTime = System.currentTimeMillis();
      }
      return this;
   }

   public synchronized Map<String, String> invertedPropertiesMap() {
      if (invertedProps == null) {
         invertedProps = new HashMap<>(props.size());
         for (Map.Entry<Object, Object> val : props.entrySet()) {
            invertedProps.put((String) val.getValue(), (String) val.getKey());
         }
      }
      return invertedProps;
   }

   public synchronized Map<String, Set<String>> invertedPropertiesValuesMap() {
      if (invertedValueProps == null) {
         invertedValueProps = new HashMap<>(props.size());
         for (Map.Entry<Object, Object> val : props.entrySet()) {
            String[] userList = ((String) val.getValue()).split(",");
            for (String user : userList) {
               Set<String> set = invertedValueProps.get(user);
               if (set == null) {
                  set = new HashSet<>();
                  invertedValueProps.put(user, set);
               }
               set.add((String) val.getKey());
            }
         }
      }
      return invertedValueProps;
   }

   private void load(final File source, Properties props) throws IOException {
      try (FileInputStream in = new FileInputStream(source)) {
         props.load(in);
         //            if (key.isDecrypt()) {
         //                try {
         //                    EncryptionSupport.decrypt(this.props);
         //                } catch (NoClassDefFoundError e) {
         //                    // this Happens whe jasypt is not on the classpath..
         //                    key.setDecrypt(false);
         //                    ActiveMQServerLogger.LOGGER.info("jasypt is not on the classpath: password decryption disabled.");
         //                }
         //            }

      }
   }

   private boolean hasModificationAfter(long reloadTime) {
      return key.file.lastModified() > reloadTime;
   }

}


text:
package ru.job4j.pecs;

public class Class3 extends Class2 {
}


text:
<?php

namespace Application\Migrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20160415144958 extends AbstractMigration
{
    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('CREATE TABLE synapse_page (id INT AUTO_INCREMENT NOT NULL, root_id INT DEFAULT NULL, parent_id INT DEFAULT NULL, name VARCHAR(255) NOT NULL, title VARCHAR(255) NOT NULL, path VARCHAR(255) NOT NULL, meta LONGTEXT NOT NULL COMMENT \'(DC2Type:json_array)\', open_graph LONGTEXT NOT NULL COMMENT \'(DC2Type:json_array)\', lft INT NOT NULL, rgt INT NOT NULL, lvl INT NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME NOT NULL, UNIQUE INDEX UNIQ_8FBCACD0B548B0F (path), INDEX IDX_8FBCACD079066886 (root_id), INDEX IDX_8FBCACD0727ACA70 (parent_id), INDEX path_index (path), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB');
        $this->addSql('ALTER TABLE synapse_page ADD CONSTRAINT FK_8FBCACD079066886 FOREIGN KEY (root_id) REFERENCES synapse_page (id) ON DELETE CASCADE');
        $this->addSql('ALTER TABLE synapse_page ADD CONSTRAINT FK_8FBCACD0727ACA70 FOREIGN KEY (parent_id) REFERENCES synapse_page (id) ON DELETE CASCADE');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE synapse_page DROP FOREIGN KEY FK_8FBCACD079066886');
        $this->addSql('ALTER TABLE synapse_page DROP FOREIGN KEY FK_8FBCACD0727ACA70');
        $this->addSql('DROP TABLE synapse_page');
    }
}


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

@Component({
  selector: 'button-visual',
  templateUrl: './button-visual.component.html'
})
export class ButtonVisualComponent { }


text:
/* author Sylvain Jaume, Julien Gein */

#ifndef SO_ITK_MATRIX_H
# define SO_ITK_MATRIX_H

# include <xip/inventor/itk/xipivitk.h>
# include <Inventor/engines/SoSubEngine.h>
# include <Inventor/fields/SoSFEnum.h>
# include <Inventor/fields/SoSFShort.h>
# include <Inventor/fields/SoMFFloat.h>

class SoItkDataMatrix;

class SoItkMatrix : public SoEngine
{
	SO_ENGINE_HEADER( SoItkMatrix );

public:
	enum ValueTypeEnum
	{
		UNSIGNED_SHORT,
		FLOAT,
		DOUBLE
	};

    enum MatrixTypeEnum
	{
		_2x2,
		_3x3,
		_4x4
	};

	SoItkMatrix();

	static void initClass();

	SoSFEnum ValueType;
	SoSFEnum MatrixType;
	SoMFFloat Values;

	SoEngineOutput Output; // SoItkSFDataMatrix

protected:
	~SoItkMatrix();

	virtual void inputChanged( SoField* field );
	virtual void evaluate();

	SoItkDataMatrix* mOutput;

};

#endif // SO_ITK_MATRIX_H


text:
package org.hl7.types.impl;

import org.hl7.types.ANY;
import org.hl7.types.BL;
import org.hl7.types.CD;
import org.hl7.types.CR;
import org.hl7.types.CS;
import org.hl7.types.ED;
import org.hl7.types.LIST;
import org.hl7.types.NullFlavor;
import org.hl7.types.SET;
import org.hl7.types.ST;
import org.hl7.types.UID;

/**
 * Minimal implementation of CS as a model we can use for all other type. This one is only used to convey NULL values.
 * Again, we have static values of it, so we don't create so many objects in a running program.
 *
 * FIXME: this and all other C*null classes must have a code system for at least the OTH null value.
 */
public final class CSnull extends ANYimpl implements CS {
	public static final CSnull NI = new CSnull(NullFlavorImpl.NI);
	public static final CSnull NA = new CSnull(NullFlavorImpl.NA);
	public static final CSnull UNK = new CSnull(NullFlavorImpl.UNK);
	public static final CSnull NASK = new CSnull(NullFlavorImpl.NASK);
	public static final CSnull ASKU = new CSnull(NullFlavorImpl.ASKU);
	public static final CSnull NAV = new CSnull(NullFlavorImpl.NAV);
	public static final CSnull OTH = new CSnull(NullFlavorImpl.OTH);
	public static final CSnull PINF = new CSnull(NullFlavorImpl.PINF);
	public static final CSnull NINF = new CSnull(NullFlavorImpl.NINF);

	private CSnull(final NullFlavor nf) {
		super(nf);
	}

	/**
	 * Get the a null value according to the null flavor code.
	 */
	public static CSnull valueOf(final String nullFlavor) {
	    return ANYimpl.nullValueOf(CSnull.class, nullFlavor);
	}

	/**
	 * the equal will tell whether the given ANY is equal to this object.
	 *
	 * @param that
	 * @return BLimpl.TRUE if that is equal to this object.
	 */
	@Override
    public BL equal(final ANY that) {
		/**
		 * The contract of equal shall be carried no matter the semantics value of the class itself.
		 */
		if (that instanceof CSnull) {
			final CSnull thatObj = (CSnull) that;
			return thatObj.nullFlavor().equal(this.nullFlavor());
		} else {
			return BLimpl.FALSE;
		}
	}

	// equals() method has been overriden in ANYimpl class
	/**
	 * override hashCode() method.
	 *
	 * @return hashCode
	 */
	@Override
    public int hashCode() {
		return this.nullFlavor().hashCode();
	}

	/** CD interface */
	public ST code() {
		return STnull.NA;
	}

	public ST displayName() {
		return STnull.NA;
	}

	public UID codeSystem() {
		return UIDnull.NA;
	}

	public ST codeSystemName() {
		return STnull.NA;
	}

	public ST codeSystemVersion() {
		return STnull.NA;
	}

	public ED originalText() {
		return EDnull.NA;
	}

	public BL implies(final CD x) {
		return BLimpl.NA;
	}

	public CD mostSpecificGeneralization(final CD x) {
		return CDnull.NA;
	}

	public LIST<CR> qualifier() {
		throw new UnsupportedOperationException();
	}

	public SET<CD> translation() {
		throw new UnsupportedOperationException();
	}

	@Override
    public String toString() {
		return nullFlavor().code().toString();
	}
};