text:
package com.gmail.socraticphoenix.nebula.string.parser;

import com.gmail.socraticphoenix.nebula.string.parser.restrictions.AndRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.CompletedRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.LazyVariableRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.LiteralRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.RepeatingNonGreedyRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.RepeatingOrNoneNonGreedyRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.OptionalRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.OrRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.PredicateRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.RegexRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.RepeatingOrNoneRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.RepeatingRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.SequenceRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.SetAndUseRestriction;
import com.gmail.socraticphoenix.nebula.string.parser.restrictions.SetRestriction;

import java.util.Collection;
import java.util.function.BiFunction;

public class PatternRestrictions {

    public static PatternRestriction literal(String literal) {
        return new LiteralRestriction(literal);
    }

    public static PatternRestriction sequence(PatternRestriction... restrictions) {
        return new SequenceRestriction(restrictions);
    }

    public static PatternRestriction sequence(Collection<PatternRestriction> restrictions) {
        return PatternRestrictions.sequence(restrictions.toArray(new PatternRestriction[restrictions.size()]));
    }

    public static PatternRestriction and(PatternRestriction... restrictions) {
        return new AndRestriction(restrictions);
    }

    public static PatternRestriction and(Collection<PatternRestriction> restrictions) {
        return PatternRestrictions.and(restrictions.toArray(new PatternRestriction[restrictions.size()]));
    }

    public static PatternRestriction or(PatternRestriction... restrictions) {
        return new OrRestriction(restrictions);
    }

    public static PatternRestriction or(Collection<PatternRestriction> restrictions) {
        return PatternRestrictions.or(restrictions.toArray(new PatternRestriction[restrictions.size()]));
    }

    public static PatternRestriction oneOf(String... strings) {
        PatternRestriction[] restrictions = new PatternRestriction[strings.length];
        for (int i = 0; i < restrictions.length; i++) {
            restrictions[i] = PatternRestrictions.literal(strings[i]);
        }
        return PatternRestrictions.or(restrictions);
    }

    public static PatternRestriction repeating(PatternRestriction restriction) {
        return new RepeatingRestriction(restriction);
    }

    public static PatternRestriction repeatingOrNone(PatternRestriction restriction) {
        return new RepeatingOrNoneRestriction(restriction);
    }

    public static PatternRestriction repeatingOrNoneNonGreedy(PatternRestriction repeat, PatternRestriction next) {
        return new RepeatingOrNoneNonGreedyRestriction(repeat, next);
    }

    public static PatternRestriction repeatingNonGreedy(PatternRestriction repeat, PatternRestriction next) {
        return new RepeatingNonGreedyRestriction(repeat, next);
    }

    public static PatternRestriction optional(PatternRestriction restriction) {
        return new OptionalRestriction(restriction);
    }

    public static PatternRestriction lazy(String name) {
        return new LazyVariableRestriction(name);
    }

    public static PatternRestriction regex(String regex) {
        return new RegexRestriction(regex);
    }

    public static PatternRestriction predicate(PatternRestriction generalMatch, BiFunction<String, Integer, PatternResult> predicate) {
        return new PredicateRestriction(generalMatch, predicate);
    }

    public static PatternRestriction set(String name, PatternRestriction restriction) {
        return new SetRestriction(name, restriction);
    }

    public static PatternRestriction list(PatternRestriction element, PatternRestriction separator) {
        return PatternRestrictions.sequence(element, PatternRestrictions.repeatingOrNone(PatternRestrictions.sequence(separator, element)));
    }

    public static PatternRestriction setAndUse(String name, PatternRestriction restriction) {
        return new SetAndUseRestriction(name, restriction);
    }

    public static PatternRestriction completed(PatternRestriction restriction) {
        return new CompletedRestriction(restriction);
    }

}


text:
#include "config.h"
#include "client.h"
#include "clipboard.h"
#include "guac_handlers.h"
#include "telnet_client.h"
#include "terminal.h"

#include <langinfo.h>
#include <locale.h>
#include <pthread.h>
#include <regex.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

#include <guacamole/client.h>
#include <guacamole/protocol.h>
#include <guacamole/socket.h>

#define GUAC_TELNET_DEFAULT_FONT_NAME "monospace"
#define GUAC_TELNET_DEFAULT_FONT_SIZE 12
#define GUAC_TELNET_DEFAULT_PORT      "23"

/* Client plugin arguments */
const char* GUAC_CLIENT_ARGS[] = {
    "hostname",
    "port",
    "username",
    "username-regex",
    "password",
    "password-regex",
    "font-name",
    "font-size",
    "color-scheme",
    NULL
};

enum __TELNET_ARGS_IDX {

    /**
     * The hostname to connect to. Required.
     */
    IDX_HOSTNAME,

    /**
     * The port to connect to. Optional.
     */
    IDX_PORT,

    /**
     * The name of the user to login as. Optional.
     */
    IDX_USERNAME,

    /**
     * The regular expression to use when searching for the username/login prompt.
     * Optional.
     */
    IDX_USERNAME_REGEX,

    /**
     * The password to use when logging in. Optional.
     */
    IDX_PASSWORD,

    /**
     * The regular expression to use when searching for the password prompt.
     * Optional.
     */
    IDX_PASSWORD_REGEX,

    /**
     * The name of the font to use within the terminal.
     */
    IDX_FONT_NAME,

    /**
     * The size of the font to use within the terminal, in points.
     */
    IDX_FONT_SIZE,

    /**
     * The name of the color scheme to use. Currently valid color schemes are:
     * "black-white", "white-black", "gray-black", and "green-black", each
     * following the "foreground-background" pattern. By default, this will be
     * "gray-black".
     */
    IDX_COLOR_SCHEME,

    TELNET_ARGS_COUNT
};

/**
 * Compiles the given regular expression, returning NULL if compilation fails.
 */
static regex_t* __guac_telnet_compile_regex(guac_client* client, char* pattern) {

    int compile_result;
    regex_t* regex = malloc(sizeof(regex_t));

    /* Compile regular expression */
    compile_result = regcomp(regex, pattern,REG_EXTENDED | REG_NOSUB | REG_ICASE | REG_NEWLINE);

    /* Notify of failure to parse/compile */
    if (compile_result != 0) {
        guac_client_log(client, GUAC_LOG_ERROR, "Regular expression '%s' could not be compiled.", pattern);
        free(regex);
        return NULL;
    }

    return regex;
}

int guac_client_init(guac_client* client, int argc, char** argv) {

    guac_socket* socket = client->socket;

    guac_telnet_client_data* client_data = malloc(sizeof(guac_telnet_client_data));

    /* Init client data */
    client->data = client_data;
    client_data->telnet = NULL;
    client_data->socket_fd = -1;
    client_data->naws_enabled = 0;
    client_data->echo_enabled = 1;

    if (argc != TELNET_ARGS_COUNT) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR, "Wrong number of arguments");
        return -1;
    }

    /* Set locale and warn if not UTF-8 */
    setlocale(LC_CTYPE, "");
    if (strcmp(nl_langinfo(CODESET), "UTF-8") != 0)
        guac_client_log(client, GUAC_LOG_INFO, "Current locale does not use UTF-8. Some characters may not render correctly.");

    /* Read parameters */
    strcpy(client_data->hostname,  argv[IDX_HOSTNAME]);
    strcpy(client_data->username,  argv[IDX_USERNAME]);
    strcpy(client_data->password,  argv[IDX_PASSWORD]);

    /* Set username regex, if needed */
    if (client_data->username[0] != 0) {

        /* Compile regular expression */
        if (argv[IDX_USERNAME_REGEX][0] != 0)
            client_data->username_regex = __guac_telnet_compile_regex(client, argv[IDX_USERNAME_REGEX]);
        else
            client_data->username_regex = __guac_telnet_compile_regex(client, GUAC_TELNET_DEFAULT_USERNAME_REGEX);

    }
    else
        client_data->username_regex = NULL;

    /* Set password regex, if needed */
    if (client_data->password[0] != 0) {

        /* Compile regular expression */
        if (argv[IDX_PASSWORD_REGEX][0] != 0)
            client_data->password_regex = __guac_telnet_compile_regex(client, argv[IDX_PASSWORD_REGEX]);
        else
            client_data->password_regex = __guac_telnet_compile_regex(client, GUAC_TELNET_DEFAULT_PASSWORD_REGEX);

    }
    else
        client_data->password_regex = NULL;

    /* Read port */
    if (argv[IDX_PORT][0] != 0)
        strcpy(client_data->port, argv[IDX_PORT]);
    else
        strcpy(client_data->port, GUAC_TELNET_DEFAULT_PORT);

    /* Read font name */
    if (argv[IDX_FONT_NAME][0] != 0)
        strcpy(client_data->font_name, argv[IDX_FONT_NAME]);
    else
        strcpy(client_data->font_name, GUAC_TELNET_DEFAULT_FONT_NAME );

    /* Read font size */
    if (argv[IDX_FONT_SIZE][0] != 0)
        client_data->font_size = atoi(argv[IDX_FONT_SIZE]);
    else
        client_data->font_size = GUAC_TELNET_DEFAULT_FONT_SIZE;

    /* Create terminal */
    client_data->term = guac_terminal_create(client,
            client_data->font_name, client_data->font_size,
            client->info.optimal_resolution,
            client->info.optimal_width, client->info.optimal_height,
            argv[IDX_COLOR_SCHEME]);

    /* Fail if terminal init failed */
    if (client_data->term == NULL) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR, "Terminal initialization failed");
        return -1;
    }

    /* Send initial name */
    guac_protocol_send_name(socket, client_data->hostname);

    guac_socket_flush(socket);

    /* Set basic handlers */
    client->handle_messages   = guac_telnet_client_handle_messages;
    client->key_handler       = guac_telnet_client_key_handler;
    client->mouse_handler     = guac_telnet_client_mouse_handler;
    client->size_handler      = guac_telnet_client_size_handler;
    client->free_handler      = guac_telnet_client_free_handler;
    client->clipboard_handler = guac_telnet_clipboard_handler;

    /* Start client thread */
    if (pthread_create(&(client_data->client_thread), NULL, guac_telnet_client_thread, (void*) client)) {
        guac_client_abort(client, GUAC_PROTOCOL_STATUS_SERVER_ERROR, "Unable to start telnet client thread");
        return -1;
    }

    /* Success */
    return 0;

}

redpajama_set_name: RedPajamaGithub


text:
from kitsune.products.tests import ProductFactory, TopicFactory
from kitsune.sumo.tests import TestCase

class TopicModelTests(TestCase):
    def test_path(self):
        """Verify that the path property works."""
        p = ProductFactory(slug="p")
        t1 = TopicFactory(product=p, slug="t1")
        t2 = TopicFactory(product=p, slug="t2", parent=t1)
        t3 = TopicFactory(product=p, slug="t3", parent=t2)

        self.assertEqual(t1.path, [t1.slug])
        self.assertEqual(t2.path, [t1.slug, t2.slug])
        self.assertEqual(t3.path, [t1.slug, t2.slug, t3.slug])

    def test_absolute_url(self):
        p = ProductFactory()
        t = TopicFactory(product=p)
        expected = "/products/{p}/{t}".format(p=p.slug, t=t.slug)
        actual = t.get_absolute_url()
        self.assertEqual(actual, expected)

    def test_absolute_url_subtopic(self):
        p = ProductFactory()
        t1 = TopicFactory(product=p)
        t2 = TopicFactory(parent=t1, product=p)
        expected = "/products/{p}/{t1}/{t2}".format(p=p.slug, t1=t1.slug, t2=t2.slug)
        actual = t2.get_absolute_url()
        self.assertEqual(actual, expected)

class ProductModelTests(TestCase):
    def test_absolute_url(self):
        p = ProductFactory()
        expected = "/products/{p}".format(p=p.slug)
        actual = p.get_absolute_url()
        self.assertEqual(actual, expected)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  Copyright 2013 ESRI

  All rights reserved under the copyright laws of the United States
  and applicable international laws, treaties, and conventions.

  You may freely redistribute and use this sample code, with or
  without modification, provided you include the original copyright
  notice and use restrictions.

  See the use restrictions
  http://help.arcgis.comensdk10.0usageRestrictions.htm.
-->

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".UnionDifferenceActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <RadioGroup
            android:id="@+id/operationtype"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="@android:dimen/app_icon_size"
            android:layout_weight="0.03"
            android:orientation="horizontal" >

            <RadioButton
                android:id="@+id/union"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="Union" />

            <RadioButton
                android:id="@+id/difference"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Difference" />

        </RadioGroup>

        <TextView
                android:id="@+id/textView1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text=" "
                android:textStyle="bold"
                android:textAppearance="?android:attr/textAppearanceSmall" />

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.03"
            android:text=" "
            android:textStyle="bold"
            android:textAppearance="?android:attr/textAppearanceSmall" />

        <Button
            android:id="@+id/secgeometry"
            style="?android:attr/buttonStyleSmall"
            android:textStyle="bold"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.03"
            android:text="+" />

        <Button
            android:id="@+id/reset"
            style="?android:attr/buttonStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.03"
            android:text="Reset" />
    </LinearLayout>

    <!-- MapView layout and initial extent -->
    <com.esri.android.map.MapView
        android:id="@+id/map"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>


text:
package me.roryclaasen.rorysmod.block;

import java.util.ArrayList;
import java.util.Random;

import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.MathHelper;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import net.minecraftforge.common.util.ForgeDirection;
import me.roryclaasen.rorysmod.block.base.BlockBaseContainer;
import me.roryclaasen.rorysmod.block.tile.TileEntityPoweredChest;
import me.roryclaasen.rorysmod.core.RorysMod;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

public class BlockPoweredChest extends BlockBaseContainer implements ITileEntityProvider {

	private final Random random = new Random();

	public BlockPoweredChest(Material material, String unlocalizedName) {
		super(material, unlocalizedName);
		this.setHardness(2.5F);
		this.setStepSound(soundTypeWood);
		this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F);
	}

	@Override
	public boolean isOpaqueCube() {
		return false;
	}

	@Override
	public boolean renderAsNormalBlock() {
		return false;
	}

	@Override
	public int getRenderType() {
		return 22;
	}

	@Override
	public void onBlockAdded(World world, int x, int y, int z) {
		super.onBlockAdded(world, x, y, z);
		world.markBlockForUpdate(x, y, z);
	}

	@Override
	public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase entityliving, ItemStack itemStack) {
		byte chestFacing = 0;
		int facing = MathHelper.floor_double((entityliving.rotationYaw * 4F) / 360F + 0.5D) & 3;

		if (facing == 0) chestFacing = 2;
		if (facing == 1) chestFacing = 5;
		if (facing == 2) chestFacing = 3;
		if (facing == 3) chestFacing = 4;

		TileEntity te = world.getTileEntity(x, y, z);
		if (te != null && te instanceof TileEntityPoweredChest) {
			TileEntityPoweredChest teic = (TileEntityPoweredChest) te;
			teic.wasPlaced(entityliving, itemStack);
			teic.setFacing(chestFacing);
			world.markBlockForUpdate(x, y, z);
		}
	}

	@Override
	public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float lx, float ly, float lz) {
		if (world.isRemote) return true;
		if (world.isSideSolid(x, y + 1, z, ForgeDirection.DOWN)) return true;

		TileEntity tile = world.getTileEntity(x, y, z);
		if (tile != null && tile instanceof TileEntityPoweredChest) {
			TileEntityPoweredChest te = ((TileEntityPoweredChest) tile);
			if (te.isUseableByPlayer(player)) {
				world.playSoundEffect(x, y, z, "random.chestopen", 0.5F, world.rand.nextFloat() * 0.1F + 0.9F);
				player.openGui(RorysMod.instance, RorysMod.GUIS.CHEST_POWERED.getId(), world, x, y, z);
				((TileEntityPoweredChest) tile).openInventory();
				return true;
			} else {
				player.addChatComponentMessage(new ChatComponentText(StatCollector.translateToLocal("message.rorysmod.chest.state.locked")));
			}
		}
		return true;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void breakBlock(World world, int x, int y, int z, Block block, int par6) {
		if (world.isRemote) return;
		ArrayList drops = new ArrayList();
		TileEntity teRaw = world.getTileEntity(x, y, z);
		if (teRaw != null && teRaw instanceof TileEntityPoweredChest) {
			TileEntityPoweredChest te = (TileEntityPoweredChest) teRaw;
			for (int i = 0; i < te.getSizeInventory(); i++) {
				ItemStack stack = te.getStackInSlot(i);
				if (stack != null) drops.add(stack.copy());
			}
		}
		for (int i = 0; i < drops.size(); i++) {
			EntityItem item = new EntityItem(world, x + 0.5, y + 0.5, z + 0.5, (ItemStack) drops.get(i));
			item.setVelocity((random.nextDouble() - 0.5) * 0.25, random.nextDouble() * 0.5 * 0.25, (random.nextDouble() - 0.5) * 0.25);
			world.spawnEntityInWorld(item);
		}
	}

	public TileEntity createNewTileEntity(World world, int par2) {
		return new TileEntityPoweredChest();
	}

	@SideOnly(Side.CLIENT)
	public void registerBlockIcons(IIconRegister p_149651_1_) {
		this.blockIcon = p_149651_1_.registerIcon("planks_oak");
	}
}


text:
<?php

namespace app\models;

use FPDI;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
use yii\web\UploadedFile;

/**
 * This is the model class for table "student_information".
 *
 * @property integer $id
 * @property string $college_admission_test_number
 * @property string $official_receipt_number
 * @property string $date_taken
 * @property string $application_status
 * @property string $is_first_time
 * @property string $is_first_time_location
 * @property string $title
 * @property string $firstName
 * @property string $middleName
 * @property string $lastName
 * @property string $phoneNumber
 * @property string $houseNumber
 * @property string $permanent_address_house_number
 * @property string $permanent_address_street
 * @property string $permanent_address_purok
 * @property string $permanent_address_barangay
 * @property string $permanent_address_town
 * @property string $permanent_address_province
 * @property string $permanent_address_postalCode
 * @property string $residential_address_house_number
 * @property string $residential_address_street
 * @property string $residential_address_purok
 * @property string $residential_address_barangay
 * @property string $residential_address_town
 * @property string $residential_address_province
 * @property string $residential_address_postalCode
 * @property string $birthday
 * @property integer $age
 * @property string $place_of_birth
 * @property string $civil_status
 * @property string $gender
 * @property string $ethnic_origin
 * @property string $citizenship
 * @property string $signature_image
 * @property string $student_picture
 * @property string $requirement_certificate
 * @property string $serial_number
 * @property string $created_at
 * @property string $updated_at
 */
class StudentInformation extends \yii\db\ActiveRecord
{
    const NEW_STUDENT_REGISTERED = 'NEW_STUDENT_REGISTERED';

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'student_information';
    }

    public static function findValedictoriansArr()
    {
        /*high school*/
        $sqlCommand = <<<EOL
        select student.*
        from student_information as student
        inner join educational_attainment as educ on educ.student_id = student.id
        inner join awards_received as awards on awards.education_attainment_id = educ.id
        where awards.awards_name = "valedictorian"
        and educ.education = "Secondary"
EOL;
        return Yii::$app->db->createCommand($sqlCommand)->queryAll();
    }

    public static function findSalutatoriansArr()
    {
        /*high school*/
        $sqlCommand = <<<EOL
        select student.*
        from student_information as student
        inner join educational_attainment as educ on educ.student_id = student.id
        inner join awards_received as awards on awards.education_attainment_id = educ.id
        where awards.awards_name = "salutatorian"
        and educ.education = "Secondary"

EOL;
        return Yii::$app->db->createCommand($sqlCommand)->queryAll();
    }

    public static function findAthletesArr()
    {
        /*high school*/
        $sqlCommand = <<<EOL
        select student.*
        from student_information as student
        inner join educational_attainment as educ on educ.student_id = student.id
        inner join awards_received as awards on awards.education_attainment_id = educ.id
        where awards.awards_name = "athlete"
        and educ.education = "Secondary"
EOL;
        return Yii::$app->db->createCommand($sqlCommand)->queryAll();
    }

    public static function getAllEthnicity()
    {
        $sqlCommand = <<<EOL
        select distinct student.ethnic_origin
        from student_information as student
EOL;
        return Yii::$app->db->createCommand($sqlCommand)->queryAll();
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'firstName', 'lastName', 'gender', 'age', 'civil_status', 'citizenship', 'requirement_certificate'], 'required'],
            [['requirement_certificate', 'student_picture', 'date_taken', 'birthday', 'created_at', 'updated_at', 'application_status', 'college_admission_test_number', 'official_receipt_number', 'is_first_time', 'is_first_time_location'], 'safe'],
            [['age'], 'number'],
            [['serial_number', 'college_admission_test_number', 'official_receipt_number', 'application_status', 'is_first_time', 'is_first_time_location', 'title', 'firstName', 'middleName', 'lastName', 'phoneNumber', 'houseNumber', 'permanent_address_house_number', 'permanent_address_street', 'permanent_address_purok', 'permanent_address_barangay', 'permanent_address_town', 'permanent_address_province', 'permanent_address_postalCode', 'residential_address_house_number', 'residential_address_street', 'residential_address_purok', 'residential_address_barangay', 'residential_address_town', 'residential_address_province', 'residential_address_postalCode', 'place_of_birth', 'civil_status', 'gender', 'ethnic_origin', 'citizenship', 'signature_image'], 'string', 'max' => 255],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'college_admission_test_number' => 'College Admission Test Number',
            'official_receipt_number' => 'Official Receipt Number',
            'date_taken' => 'Date Taken',
            'application_status' => 'Application Status',
            'is_first_time' => 'Is first time',
            'is_first_time_location' => 'Place NVSU-CAT took place',
            'title' => 'Title',
            'firstName' => 'First Name',
            'middleName' => 'Middle Name',
            'lastName' => 'Last Name',
            'phoneNumber' => 'Phone Number',
            'houseNumber' => 'House Number',
            'permanent_address_house_number' => 'House Number',
            'permanent_address_street' => 'Street',
            'permanent_address_purok' => 'Purok',
            'permanent_address_barangay' => 'Barangay',
            'permanent_address_town' => 'Town',
            'permanent_address_province' => 'Province',
            'permanent_address_postalCode' => 'Postal Code',
            'residential_address_house_number' => 'House Number',
            'residential_address_street' => 'Street',
            'residential_address_purok' => 'Purok',
            'residential_address_barangay' => 'Barangay',
            'residential_address_town' => 'Town',
            'residential_address_province' => 'Province',
            'residential_address_postalCode' => 'Postal Code',
            'birthday' => 'Birthday',
            'age' => 'Age',
            'place_of_birth' => 'Place Of Birth',
            'civil_status' => 'Civil Status',
            'gender' => 'Gender',
            'ethnic_origin' => 'Ethnic Origin',
            'citizenship' => 'Citizenship',
            'signature_image' => 'Signature Image',
            'serial_number' => 'Identification Number',
            'created_at' => 'Created At',
            'updated_at' => 'Updated At',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => new Expression('NOW()')
            ],
        ];
    }

    public function beforeSave($insert)
    {
        if ($this->isNewRecord || $this->scenario == "update") {
            $this->date_taken = date("Y-m-d h:i:s", strtotime($this->date_taken));
            $this->birthday = date("Y-m-d h:i:s", strtotime($this->birthday));
        }
        if ($this->isNewRecord) {
            //generate serial number
            do {
                $this->serial_number = substr(uniqid(), -8);
            } while (StudentInformation::find()->where(['serial_number' => $this->serial_number])->exists());

        }
        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        if ($this->isNewRecord) {
            $this->trigger(StudentInformation::NEW_STUDENT_REGISTERED);
        }
        parent::afterSave($insert, $changedAttributes);
    }

    public function beforeDelete()
    {
        $allEducationalAttainments = EducationalAttainment::find()->where(['student_id' => $this->id])->all();
        /**
         * @var $currentEducationalAttainment EducationalAttainment
         * @vara $currentAward AwardsReceived
         */
        foreach ($allEducationalAttainments as $currentEducationalAttainment) {
            $allawards = AwardsReceived::find()->where(['education_attainment_id' => $currentEducationalAttainment->id])->all();
            foreach ($allawards as $currentAward) {
                $currentAward->delete();
            }
            $currentEducationalAttainment->delete();
        }
        return parent::beforeDelete();
    }

    /**
     *
     * @return \yii\db\ActiveQuery
     */
    public function geteducational_attainment()
    {
        return $this->hasMany(EducationalAttainment::className(), ['student_id' => 'id']);
    }

    public static function getMaleCount()
    {
        return StudentInformation::find()->where([
            'gender' => 'Male'
        ])->count();
    }

    public static function getFemaleCount()
    {
        return StudentInformation::find()->where([
            'gender' => 'Female'
        ])->count();
    }

    public function getPrefferedCourses()
    {
        /*get student courses*/
        $coursesCollection = [];
        $pref = StudentCourse::find()->where(['student_id' => $this->id])->all();
        foreach ($pref as $currentPref) {
            $coursesCollection[] = $currentPref->course;
        }
        return $coursesCollection;
    }

    public function getstudent_course()
    {
        return $this
            ->hasMany(StudentCourse::className(), ['student_id' => 'id'])
            ->from(['student_course_2' => StudentCourse::tableName()]);

    }

    public function getcourse()
    {
        return $this
            ->hasMany(Course::className(), ['id' => 'course_id'])
            ->viaTable('student_course', ['student_id' => 'id']);
    }

    public function getawards_received()
    {
        return $this
            ->hasMany(AwardsReceived::className(), ['id' => 'student_id'])
            ->viaTable(EducationalAttainment::tableName(), ['student_id' => 'id'], function ($q) {
                $q->from("educational_attainment ed2");
            });
    }

    /**
     * @param $pdfTemplate
     * @return FPDI
     */
    public function exportTestingPermit($pdfTemplate){
        $exportedFile = '';
        class_exists('TCPDF', true);
        $pdf = new FPDI();
        $pdf->addPage();
        $pdf->SetFont("Helvetica",'',8);
        $pdf->setSourceFile($pdfTemplate);
        $tplIdx = $pdf->importPage(1);
        $pdf->useTemplate($tplIdx, 0, 0, 0, 0, true);
        $pdf->SetTextColor(0,0,0);
        $pdf->SetXY(  50 , 33);
        $pdf->Write( 0 , $this->serial_number);
        $pdf->SetXY(  73 , 93.5);
        $pdf->Write(0, sprintf("%s %s %s  %s",$this->title,$this->firstName ,$this->middleName,$this->lastName));
        $pdf->SetXY(  103 , 98);
        $pdf->Write(0, date("l jS \of F Y",time()). " 8:00 AM"  );//date
        $pdf->SetXY(  35 , 106);
        $pdf->Write(0, 'Testing Center');//time
        return $pdf;

    }

    public function saveStudentPicture(UploadedFile $uploadedFile)
    {
        //get photo name
        $uploadedImagesPath = Yii::getAlias('@app/uploads/student_pictures');
        //rename photoname using format Y_m_d_title_firstname_middlename_lastname_random
        $finalImagename = sprintf("%s_%s_%s_%s_%s_%s.%s", date("Y_m_d"), $this->title, $this->firstName, $this->middleName, $this->lastName, uniqid(),$uploadedFile->extension);
        $uploadedFile->saveAs($uploadedImagesPath .DIRECTORY_SEPARATOR. $finalImagename);
        $this->student_picture = $finalImagename;
        return $uploadedImagesPath .DIRECTORY_SEPARATOR. $finalImagename;
    }

    public function saveStudentCeritificateRequirement(UploadedFile $uploadedFile)
    {
        $uploadedImagesPath = Yii::getAlias('@app/uploads/certificates');
        //rename photoname using format Y_m_d_title_firstname_middlename_lastname_serialNumber
        $finalImagename = sprintf("%s_%s_%s_%s_%s_%s.%s", date("Y_m_d"), $this->title, $this->firstName, $this->middleName, $this->lastName, uniqid(),$uploadedFile->extension);
        $uploadedFile->saveAs($uploadedImagesPath .DIRECTORY_SEPARATOR. $finalImagename);
        $this->requirement_certificate = $finalImagename;
        return $uploadedImagesPath .DIRECTORY_SEPARATOR. $finalImagename;
    }

}


text:
package test;

import static org.junit.Assert.assertTrue;

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

import org.apache.commons.io.FileUtils;
import org.junit.Test;

import sorter.Main;
import sorter.MergeSorter;
import sorter.threads.Cores;
import sorter.threads.MergeSorterDriver;
import words.WordReader;

public class TimeMeasureTest {

	private final String inputFile = "test_dir/big_file.txt";

	private static void print(List<? extends Comparable> values) {
		for (Comparable value : values) {
			System.out.println(value);
		}
	}

	@Test
	public void SingleCoreMobyDickWithThreads() throws InterruptedException, IOException {
		WordReader wordReader = new WordReader(inputFile);
		List<String> wordList = wordReader.readInWords();

		MergeSorter<String> sorter = new MergeSorter<String>(wordList);
		long startTime = System.currentTimeMillis();
		MergeSorterDriver driver = new MergeSorterDriver(wordList, Cores.SINGLE);
		driver.runSortinParallel();
		long endTime = System.currentTimeMillis();

		System.out.println("Sorting-Duration (singlecore): " + inputFile + " in millsec: "
				+ (endTime - startTime));

		Main.printInFile(wordList, inputFile + "_single.out");
	}

	@Test
	public void DualCoreMobyDickWithThreads() throws InterruptedException, IOException {
		WordReader wordReader = new WordReader(inputFile);
		List<String> wordList = wordReader.readInWords();

		MergeSorter<String> sorter = new MergeSorter<String>(wordList);
		long startTime = System.currentTimeMillis();
		MergeSorterDriver driver = new MergeSorterDriver(wordList, Cores.DUAL);
		driver.runSortinParallel();
		long endTime = System.currentTimeMillis();

		System.out.println("Sorting-Duration (dualcore): " + inputFile + " in millsec: "
				+ (endTime - startTime));

		Main.printInFile(wordList, inputFile + "_dual.out");
	}

	@Test
	public void QuadCoreMobyDickWithThreads() throws InterruptedException, IOException {
		WordReader wordReader = new WordReader(inputFile);
		List<String> wordList = wordReader.readInWords();

		MergeSorter<String> sorter = new MergeSorter<String>(wordList);
		long startTime = System.currentTimeMillis();
		MergeSorterDriver driver = new MergeSorterDriver(wordList, Cores.QUAD);
		driver.runSortinParallel();
		long endTime = System.currentTimeMillis();

		System.out.println("Sorting-Duration (quadcore): " + inputFile + " in millsec: "
				+ (endTime - startTime));

		Main.printInFile(wordList, inputFile + "_quad.out");
	}

	@Test public void CompareOutFiles() throws IOException {
		File singleFile = new File(inputFile + "_single.out");
		File dualFile = new File(inputFile + "_dual.out");
		File quadFile = new File(inputFile + "_quad.out");

		assertTrue(FileUtils.contentEquals(singleFile, dualFile));
		assertTrue(FileUtils.contentEquals(singleFile, quadFile));
	}
}


text:
require "google_maps_api/directions/version"
require "google_maps_api/core"
require "google_maps_api/directions/request"
require "google_maps_api/directions/route"
require "google_maps_api/directions/bounds"
require "google_maps_api/directions/leg"
require "google_maps_api/directions/step"
require "google_maps_api/directions/encoded_polyline"
require "google_maps_api/directions/response"
require "google_maps_api/directions/exceptions"

module GoogleMapsAPI
  module Directions
    def self.route(origin, destination, options = {})
      request = Request.build(origin, destination, options)
      request.perform
    end
  end
end


text:
/*
 * Licensed 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.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.datalabeling.v1beta1.model;

/**
 * Model definition for GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Data Labeling API. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry extends com.google.api.client.json.GenericJson {

  /**
   * Threshold used for this entry. For classification tasks, this is a classification threshold: a
   * predicted label is categorized as positive or negative (in the context of this point on the PR
   * curve) based on whether the label's score meets this threshold. For image object detection
   * (bounding box) tasks, this is the [intersection-over-union (IOU)](/vision/automl/object-
   * detection/docs/evaluate#intersection-over-union) threshold for the context of this point on the
   * PR curve.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float confidenceThreshold;

  /**
   * Harmonic mean of recall and precision.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float f1Score;

  /**
   * The harmonic mean of recall_at1 and precision_at1.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float f1ScoreAt1;

  /**
   * The harmonic mean of recall_at5 and precision_at5.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float f1ScoreAt5;

  /**
   * Precision value.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float precision;

  /**
   * Precision value for entries with label that has highest score.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float precisionAt1;

  /**
   * Precision value for entries with label that has highest 5 scores.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float precisionAt5;

  /**
   * Recall value.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float recall;

  /**
   * Recall value for entries with label that has highest score.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float recallAt1;

  /**
   * Recall value for entries with label that has highest 5 scores.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.Float recallAt5;

  /**
   * Threshold used for this entry. For classification tasks, this is a classification threshold: a
   * predicted label is categorized as positive or negative (in the context of this point on the PR
   * curve) based on whether the label's score meets this threshold. For image object detection
   * (bounding box) tasks, this is the [intersection-over-union (IOU)](/vision/automl/object-
   * detection/docs/evaluate#intersection-over-union) threshold for the context of this point on the
   * PR curve.
   * @return value or {@code null} for none
   */
  public java.lang.Float getConfidenceThreshold() {
    return confidenceThreshold;
  }

  /**
   * Threshold used for this entry. For classification tasks, this is a classification threshold: a
   * predicted label is categorized as positive or negative (in the context of this point on the PR
   * curve) based on whether the label's score meets this threshold. For image object detection
   * (bounding box) tasks, this is the [intersection-over-union (IOU)](/vision/automl/object-
   * detection/docs/evaluate#intersection-over-union) threshold for the context of this point on the
   * PR curve.
   * @param confidenceThreshold confidenceThreshold or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setConfidenceThreshold(java.lang.Float confidenceThreshold) {
    this.confidenceThreshold = confidenceThreshold;
    return this;
  }

  /**
   * Harmonic mean of recall and precision.
   * @return value or {@code null} for none
   */
  public java.lang.Float getF1Score() {
    return f1Score;
  }

  /**
   * Harmonic mean of recall and precision.
   * @param f1Score f1Score or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setF1Score(java.lang.Float f1Score) {
    this.f1Score = f1Score;
    return this;
  }

  /**
   * The harmonic mean of recall_at1 and precision_at1.
   * @return value or {@code null} for none
   */
  public java.lang.Float getF1ScoreAt1() {
    return f1ScoreAt1;
  }

  /**
   * The harmonic mean of recall_at1 and precision_at1.
   * @param f1ScoreAt1 f1ScoreAt1 or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setF1ScoreAt1(java.lang.Float f1ScoreAt1) {
    this.f1ScoreAt1 = f1ScoreAt1;
    return this;
  }

  /**
   * The harmonic mean of recall_at5 and precision_at5.
   * @return value or {@code null} for none
   */
  public java.lang.Float getF1ScoreAt5() {
    return f1ScoreAt5;
  }

  /**
   * The harmonic mean of recall_at5 and precision_at5.
   * @param f1ScoreAt5 f1ScoreAt5 or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setF1ScoreAt5(java.lang.Float f1ScoreAt5) {
    this.f1ScoreAt5 = f1ScoreAt5;
    return this;
  }

  /**
   * Precision value.
   * @return value or {@code null} for none
   */
  public java.lang.Float getPrecision() {
    return precision;
  }

  /**
   * Precision value.
   * @param precision precision or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setPrecision(java.lang.Float precision) {
    this.precision = precision;
    return this;
  }

  /**
   * Precision value for entries with label that has highest score.
   * @return value or {@code null} for none
   */
  public java.lang.Float getPrecisionAt1() {
    return precisionAt1;
  }

  /**
   * Precision value for entries with label that has highest score.
   * @param precisionAt1 precisionAt1 or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setPrecisionAt1(java.lang.Float precisionAt1) {
    this.precisionAt1 = precisionAt1;
    return this;
  }

  /**
   * Precision value for entries with label that has highest 5 scores.
   * @return value or {@code null} for none
   */
  public java.lang.Float getPrecisionAt5() {
    return precisionAt5;
  }

  /**
   * Precision value for entries with label that has highest 5 scores.
   * @param precisionAt5 precisionAt5 or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setPrecisionAt5(java.lang.Float precisionAt5) {
    this.precisionAt5 = precisionAt5;
    return this;
  }

  /**
   * Recall value.
   * @return value or {@code null} for none
   */
  public java.lang.Float getRecall() {
    return recall;
  }

  /**
   * Recall value.
   * @param recall recall or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setRecall(java.lang.Float recall) {
    this.recall = recall;
    return this;
  }

  /**
   * Recall value for entries with label that has highest score.
   * @return value or {@code null} for none
   */
  public java.lang.Float getRecallAt1() {
    return recallAt1;
  }

  /**
   * Recall value for entries with label that has highest score.
   * @param recallAt1 recallAt1 or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setRecallAt1(java.lang.Float recallAt1) {
    this.recallAt1 = recallAt1;
    return this;
  }

  /**
   * Recall value for entries with label that has highest 5 scores.
   * @return value or {@code null} for none
   */
  public java.lang.Float getRecallAt5() {
    return recallAt5;
  }

  /**
   * Recall value for entries with label that has highest 5 scores.
   * @param recallAt5 recallAt5 or {@code null} for none
   */
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry setRecallAt5(java.lang.Float recallAt5) {
    this.recallAt5 = recallAt5;
    return this;
  }

  @Override
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry set(String fieldName, Object value) {
    return (GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry clone() {
    return (GoogleCloudDatalabelingV1beta1ConfidenceMetricsEntry) super.clone();
  }

}


text:
<!DOCTYPE html>
<html <?php language_attributes(); ?>>

  <meta charset="<?php bloginfo( 'charset' ); ?>">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
<?php if(is_single()): ?>
  <title><?php wp_title('|', true, 'right'); echo strtoupper(get_post_type()).' | '; bloginfo('name'); ?></title>
<?php else: ?>
  <title><?php wp_title('|', true, 'right'); bloginfo('name'); ?></title>
<?php endif; ?>
  <meta name="description" content="">
  <meta name="keyword" content="">
<?php if(is_single()): ?>
  <meta property="og:title" content="<?php wp_title('|', true, 'right'); echo strtoupper(get_post_type()).' | '; bloginfo('name'); ?>">
<?php else: ?>
  <meta property="og:title" content="<?php wp_title('|', true, 'right'); ?><?php bloginfo('name'); ?>">
<?php endif; ?>
  <meta property="og:site_name" content="<?php bloginfo('name'); ?>">
  <meta property="og:type" content="website">
  <meta property="og:url" content="">
  <meta property="og:image" content="">
  <meta property="og:description" content="">
  <meta property="og:locale" content="ja_JP">
  <meta name="twitter:card" content="summary_large_image">
  <link rel="stylesheet" href="/assets/css/site.default.css">

<?php
$post_type = get_post_type() ? get_post_type() : get_query_var('post_type');

if(is_front_page()){
  echo '<link rel="stylesheet" href="/assets/css/site.top.css">';
} else {
  echo '<link rel="stylesheet" href="/assets/css/site.in.css">';
}

if(is_archive() || is_single()){
  if($post_type == 'news' || $post_type == 'info'){
    echo '<link rel="stylesheet" href="/assets/css/site.news.css">';
  } elseif($post_type == 'works' || $post_type == 'work'){
    echo '<link rel="stylesheet" href="/assets/css/site.works.css">';
  } else {
    echo '<link rel="stylesheet" href="/assets/css/site.'.$post_type.'.css">';
  }
} else if(get_post_type() == 'page'){
  $page = get_post( get_the_ID() );
  $slug = $page->post_name;

  $parent_id = $post->post_parent; // 親ページのIDを取得
  $parent_slug = get_post($parent_id)->post_name; // 親ページのスラッグを取得

  echo '<link rel="stylesheet" href="/assets/css/site.'.$parent_slug.'.css">';
}
?>

<?php if (get_post_type() != 'post' && get_post_type() != 'page'): ?>
<?php elseif(get_the_category()[0] -> slug == 'template' && is_front_page() == false): ?>
<?php elseif(get_post_type() == 'post'): ?>
<?php elseif(get_post_type() == 'page'): ?>
<?php endif; ?>

<?php wp_head(); ?>

<?php
if (is_user_logged_in()) {
  echo '
';
  echo '  管理者としてログイン中';
  echo '
';
}
?>

<?php get_sidebar('header'); ?>
<?php get_sidebar('widget'); ?>


text:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/colorAccent" />
    <corners android:radius="30dp" />
    <stroke android:color="@color/colorDarkGray"  android:width="1dp"/>
</shape>


text:
package gov.opm.scrd.services;

import gov.opm.scrd.entities.application.DeductionValidationRequest;
import gov.opm.scrd.entities.application.DeductionValidationResponse;

/**
 *

 * DeductionValidationRuleService provides methods to execute rules to validation
 * service periods
 *

 *
 *

 *  Thread Safety:  Implementations must be effectively thread safe.
 * Refer to ADS 1.3.4 for general assumptions and notes on thread safety.
 *

 *
 * @author albertwang, TCSASSEMBLER
 * @version 1.0
 */
public interface DeductionValidationRuleService
    extends RuleService<DeductionValidationRequest, DeductionValidationResponse> {
}


text:
package org.sagebionetworks.web.client.view.users;

import static org.sagebionetworks.web.client.DisplayConstants.AUTOCOMPLETE_ATTRIBUTE;
import static org.sagebionetworks.web.client.DisplayConstants.AUTOCOMPLETE_VALUE_CURRENT_PASSWORD;
import static org.sagebionetworks.web.client.DisplayConstants.AUTOCOMPLETE_VALUE_NEW_PASSWORD;
import static org.sagebionetworks.web.client.DisplayConstants.AUTOCOMPLETE_VALUE_USERNAME;

import com.google.gwt.dom.client.DivElement;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import org.gwtbootstrap3.client.ui.Alert;
import org.gwtbootstrap3.client.ui.Button;
import org.gwtbootstrap3.client.ui.Heading;
import org.gwtbootstrap3.client.ui.TextBox;
import org.gwtbootstrap3.client.ui.html.Div;
import org.sagebionetworks.web.client.DisplayConstants;
import org.sagebionetworks.web.client.DisplayUtils;
import org.sagebionetworks.web.client.widget.FullWidthAlert;
import org.sagebionetworks.web.client.widget.header.Header;

public class PasswordResetViewImpl
  extends Composite
  implements PasswordResetView {

  public interface PasswordResetViewImplUiBinder
    extends UiBinder<Widget, PasswordResetViewImpl> {}

  @UiField
  DivElement resetPasswordForm;

  @UiField
  DivElement sendPasswordChangeForm;

  @UiField
  FullWidthAlert passwordResetRequired;

  @UiField
  PasswordTextBox currentPasswordField;

  @UiField
  PasswordTextBox password1Field;

  @UiField
  PasswordTextBox password2Field;

  @UiField
  TextBox emailAddressField;

  @UiField
  DivElement currentPassword;

  @UiField
  DivElement password1;

  @UiField
  DivElement password2;

  @UiField
  Div emailAddress;

  @UiField
  DivElement currentPasswordError;

  @UiField
  DivElement password1Error;

  @UiField
  DivElement password2Error;

  @UiField
  Alert emailAddressError;

  @UiField
  Heading pageTitle;

  @UiField
  SimplePanel loadingPanel;

  @UiField
  Button submitBtn;

  @UiField
  SpanElement contentHtml;

  @UiField
  Div synAlertContainer;

  private Presenter presenter;
  private Header headerWidget;

  private boolean isShowingResetUI;

  @Inject
  public PasswordResetViewImpl(
    PasswordResetViewImplUiBinder binder,
    Header headerWidget
  ) {
    initWidget(binder.createAndBindUi(this));
    this.headerWidget = headerWidget;

    headerWidget.configure();
    init();

    loadingPanel.setVisible(false);
    showRequestForm();
  }

  private boolean checkEmail() {
    emailAddressError.setVisible(false);
    if (DisplayUtils.isDefined(emailAddressField.getValue())) {
      return true;
    } else {
      emailAddressError.setText(DisplayConstants.ERROR_ALL_FIELDS_REQUIRED);
      emailAddressError.setVisible(true);
      return false;
    }
  }

  private boolean checkCurrentPassword() {
    DisplayUtils.hideFormError(currentPassword, currentPasswordError);
    if (!DisplayUtils.isDefined(currentPasswordField.getText())) {
      currentPasswordError.setInnerHTML(
        DisplayConstants.ERROR_ALL_FIELDS_REQUIRED
      );
      DisplayUtils.showFormError(currentPassword, currentPasswordError);
      return false;
    } else return true;
  }

  private boolean checkPassword1() {
    DisplayUtils.hideFormError(password1, password1Error);
    if (!DisplayUtils.isDefined(password1Field.getText())) {
      password1Error.setInnerHTML(DisplayConstants.ERROR_ALL_FIELDS_REQUIRED);
      DisplayUtils.showFormError(password1, password1Error);
      return false;
    } else return true;
  }

  private boolean checkPassword2() {
    DisplayUtils.hideFormError(password2, password2Error);
    if (!DisplayUtils.isDefined(password2Field.getText())) {
      password2Error.setInnerHTML(DisplayConstants.ERROR_ALL_FIELDS_REQUIRED);
      DisplayUtils.showFormError(password2, password2Error);
      return false;
    } else return true;
  }

  private boolean checkPasswordMatch() {
    DisplayUtils.hideFormError(password2, password2Error);
    if (!password1Field.getValue().equals(password2Field.getValue())) {
      password2Error.setInnerHTML(DisplayConstants.PASSWORDS_MISMATCH);
      DisplayUtils.showFormError(password2, password2Error);
      return false;
    } else return true;
  }

  public void init() {
    isShowingResetUI = false;
    KeyDownHandler submit = new KeyDownHandler() {
      @Override
      public void onKeyDown(KeyDownEvent event) {
        if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
          submitBtn.click();
        }
      }
    };
    password1Field.addKeyDownHandler(submit);
    password2Field.addKeyDownHandler(submit);
    emailAddressField.addKeyDownHandler(submit);
    submitBtn.addClickHandler(
      new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
          if (isShowingResetUI) {
            // validate passwords are filled in and match
            if (
              checkCurrentPassword() &&
              checkPassword1() &&
              checkPassword2() &&
              checkPasswordMatch()
            ) {
              submitBtn.setEnabled(false);
              presenter.resetPassword(
                currentPasswordField.getValue(),
                password1Field.getValue()
              );
            }
          } else {
            // validate email address is filled in
            if (checkEmail()) {
              submitBtn.setEnabled(false);
              presenter.requestPasswordReset(emailAddressField.getValue());
            }
          }
        }
      }
    );

    emailAddressField
      .getElement()
      .setAttribute("placeholder", "Email address -or- username");
    password1Field.getElement().setAttribute("placeholder", "Enter password");
    password2Field.getElement().setAttribute("placeholder", "Confirm password");

    emailAddressField
      .getElement()
      .setAttribute(AUTOCOMPLETE_ATTRIBUTE, AUTOCOMPLETE_VALUE_USERNAME);
    currentPasswordField
      .getElement()
      .setAttribute(
        AUTOCOMPLETE_ATTRIBUTE,
        AUTOCOMPLETE_VALUE_CURRENT_PASSWORD
      );
    password1Field
      .getElement()
      .setAttribute(AUTOCOMPLETE_ATTRIBUTE, AUTOCOMPLETE_VALUE_NEW_PASSWORD);
    password2Field
      .getElement()
      .setAttribute(AUTOCOMPLETE_ATTRIBUTE, AUTOCOMPLETE_VALUE_NEW_PASSWORD);

    emailAddressField.addBlurHandler(
      new BlurHandler() {
        @Override
        public void onBlur(BlurEvent event) {
          checkEmail();
        }
      }
    );
    password1Field.addBlurHandler(
      new BlurHandler() {
        @Override
        public void onBlur(BlurEvent event) {
          checkPassword1();
        }
      }
    );

    password2Field.addBlurHandler(
      new BlurHandler() {
        @Override
        public void onBlur(BlurEvent event) {
          checkPassword2();
        }
      }
    );
  }

  @Override
  public void setPresenter(Presenter presenter) {
    this.presenter = presenter;
    headerWidget.refresh();
  }

  @Override
  public void showRequestForm() {
    clear();
    pageTitle.setText(DisplayConstants.SEND_PASSWORD_CHANGE_REQUEST);
    submitBtn.setText("Reset my password");
    DisplayUtils.show(sendPasswordChangeForm);
    isShowingResetUI = false;
    submitBtn.setVisible(true);
  }

  @Override
  public void showResetForm() {
    clear();
    pageTitle.setText(DisplayConstants.SET_PASSWORD);
    submitBtn.setText("Set my password");
    DisplayUtils.show(resetPasswordForm);
    isShowingResetUI = true;
    submitBtn.setVisible(true);
  }

  @Override
  public void clear() {
    if (contentHtml != null) contentHtml.setInnerHTML("");
    loadingPanel.setVisible(false);
    submitBtn.setText("Submit");
    DisplayUtils.hide(sendPasswordChangeForm);
    DisplayUtils.hide(resetPasswordForm);
    submitBtn.setEnabled(true);
    submitBtn.setVisible(false);
    password1Field.setValue("");
    password2Field.setValue("");
    emailAddressField.setValue("");
    emailAddressError.setVisible(false);
    DisplayUtils.hideFormError(password1, password1Error);
    DisplayUtils.hideFormError(password2, password2Error);
    headerWidget.configure();
    passwordResetRequired.setVisible(false);
  }

  @Override
  public void showPasswordResetSuccess() {
    clear();
    pageTitle.setText(DisplayConstants.SUCCESS);
    contentHtml.setInnerHTML(
      DisplayUtils.getInfoHtml(DisplayConstants.PASSWORD_HAS_BEEN_CHANGED)
    );
  }

  @Override
  public void showErrorMessage(String errorMessage) {
    submitBtn.setEnabled(true);
    DisplayUtils.showErrorMessage(errorMessage);
  }

  @Override
  public void showRequestSentSuccess() {
    clear();
    pageTitle.setText(DisplayConstants.REQUEST_SENT);
    contentHtml.setInnerHTML(
      DisplayUtils.getInfoHtml(DisplayConstants.PASSWORD_RESET_SENT)
    );
  }

  @Override
  public void showLoading() {
    loadingPanel.setWidget(DisplayUtils.getSmallLoadingWidget());
    loadingPanel.setVisible(true);
  }

  @Override
  public void showInfo(String message) {
    DisplayUtils.showInfo(message);
  }

  @Override
  public void showExpiredRequest() {
    loadingPanel.setVisible(false);
    pageTitle.setText(DisplayConstants.REQUEST_EXPIRED);
    contentHtml.setInnerHTML(DisplayConstants.SET_PASSWORD_EXPIRED);
  }

  public void setSynAlertWidget(Widget w) {
    synAlertContainer.clear();
    synAlertContainer.add(w);
  }

  @Override
  public void setSubmitButtonEnabled(boolean enabled) {
    submitBtn.setEnabled(enabled);
  }

  @Override
  public void showPasswordResetRequired() {
    passwordResetRequired.setVisible(true);
  }
}


text:
layout:     post
title:      CAS 6.1.0 RC5 Feature Release
summary:    ...in which I present an overview of CAS 6.1.0 RC5 release.
tags:       [CAS, Releases]
---

  Collaborate
The blog is managed and hosted on GitHub. If you wish to update the contents of this post or if you have found an inaccuracy and wish to make corrections, we recommend that you please submit a pull request to this repository.

The official CAS `6.0.0` GA was released on [December 28th, 2018](https://github.com/apereo/cas/releases/tag/v6.0.0). Since then, the project has been moving forward with the development of the next feature release that is tagged as `6.1.0`. Please review the [release policy](https://apereo.github.io/cas/developer/Release-Policy.html) to learn more about the scope of the release. This post intends to highlight some of the improvements and enhancements packed into the **fifth** release candidate in the `6.1.0` series.

You can read about the previous release candidate [here](https://apereo.github.io/2019/06/07/610rc4-release/).

* A markdown unordered list which will be replaced with the ToC
{:toc}

## Get Involved

- Start your CAS deployment today. Try out features and [share feedback](https://apereo.github.io/cas/Mailing-Lists.html).
- Better yet, [contribute patches](https://apereo.github.io/cas/developer/Contributor-Guidelines.html).
- Suggest and apply documentation improvements.

### Shake Well Before Use

We strongly recommend that you take advantage of the release candidates as they come out. Waiting for a `GA` release is only going to set you up for unpleasant surprises. A `GA` is simply [a tag and nothing more](https://apereo.github.io/2017/03/08/the-myth-of-ga-rel/). Note that CAS releases are *strictly* time-based releases; they are not scheduled or based on specific benchmarks, statistics or completion of features. To gain confidence in a particular release, it is strongly recommended that you start early by experimenting with release candidates and/or follow-up snapshots.

In order to start experimenting with release candidates, at any given time, you should be able to append `-SNAPSHOT` to the CAS version specified in order to take advantage of snapshot builds as changes are made and published.

## Resources

- [Documentation](https://apereo.github.io/cas/development/)
- [Release Schedule](https://github.com/apereo/cas/milestones)
- [Release Policy](https://apereo.github.io/cas/developer/Release-Policy.html)

## Overlay

In the `gradle.properties` of [the overlay](https://github.com/apereo/cas-overlay-template), adjust the following setting:

```properties
casVersion=6.1.0-RC5
```

  System Requirements
There are no changes to the minimum system/platform requirements for this release.

## New & Noteworthy

### Redis Authentication

User accounts can now be authenticated against [Redis](https://apereo.github.io/cas/development/installation/Redis-Authentication.html). Likewise,
the integration is also allowed to fetch attributes from Redis databases without or without authentication against Redis.

### Password History Tracking

[Password Management](https://apereo.github.io/cas/development/password_management/Password-Management.html) in CAS
gains the ability to also track password history and prevent recycling old passwords where appropriate.

### Scripting Authentication via Groovy

Designing a new authentication handler can now be done via [a Groovy script](https://apereo.github.io/cas/development/installation/Groovy-Authentication.html) without having
to tap into CAS internal APIs.

### Attribute Consent via Redis

Attribute consent decisions can now be tracked and stored inside [Redis](https://apereo.github.io/cas/development/integration/Attribute-Release-Consent.html).

### MFA Trusted Devices Bypass

The [multifactor trusted device](https://apereo.github.io/cas/development/mfa/Multifactor-TrustedDevice-Authentication.html) capability gains the ability to specify bypass options per application.

### U2F MFA Trusted Devices

The [multifactor trusted device](https://apereo.github.io/cas/development/mfa/Multifactor-TrustedDevice-Authentication.html) capability
can now be automatically applied to U2F MFA flows.

### Scripted Attribute Value Filters

  ×
  Beware
This may be a breaking change. Please examine your external scripted attribute value filters to make sure
  the script body matches the structure required by the filter component. You may simply need to write the script around a run
  method with arguments passed as an Object[].

[Scripted attribute value filters](https://apereo.github.io/cas/development/integration/Attribute-Value-Release-Policies.html) are now pre-compiled
and cached to deliver better performance when it comes to parsing and running Groovy scripts.

Additionally, most if not all scripting functionality is revisited to ensure compiled scripts can be cached as efficiently as possible
to improve execution performance.

### Actuator Endpoint Exposure

Actuator endpoints provided by CAS and/or Spring Boot are now tagged with `@ConditionalOnAvailableEndpoint` instead of the now-deprecated `@ConditionalOnEnabledEndpoint`,
which makes sure endpoints are both enabled and exposed.

  WATCH OUT!
While we do not anticipate this to be a breaking change for CAS overlays, you do need to make sure
  the endpoints that are enabled are also exposed either via web or jmx before they can be functional.

### Webflow Error Handling

Handling of webflow exceptions and errors is now generalized into implementations of `CasWebflowExceptionHandler` to allow
modules in CAS and custom code outside CAS maximum flexibility when it comes to modifying error messages or handling exceptions.

### U2F Redis Device Registration

[FIDO U2F devices](https://apereo.github.io/cas/development/mfa/FIDO-U2F-Authentication.html) can now be stored inside a Redis database/cluster.

### Shared Webapp Resources

Shared web application resources such as configuration files and HTML views are now moved into a separate CAS module `cas-server-webapp-resources`.
This should not require a change to how the overlay works. If the resources are in a jar then they can still be overridden by resources in the webapp's
`WEB-INF\classes` folder (i.e. `src\main\resources` of the overlay). This is possible because `WEB-INF\classes` is first in classpath before `WEB-INF\lib*.jar`.

The CAS overlay is also modified to comply with this change, when asked to fetch resources from the exploded CAS web application.

  WATCH OUT!
While we do not anticipate this to be a breaking change for CAS overlays, you do need to make sure
  the overlay is updated to match and include the provided task definitions that recognize the new module.

### Acceptable Usage Policy via Redis

Acceptable Usage Policy decisions can now tracked and stored inside [Redis](https://apereo.github.io/cas/development/webflow/Webflow-Customization-AUP.html).

### JMX Integration

A number of CAS components can be [registered and exposed over JMX](https://apereo.github.io/cas/development/integration/JMX-Integration.html) to provide remote insight into the running CAS software.

### Fewer Bundled Webapp Modules

  WATCH OUT!
This might be a breaking change. Consult the CAS documentation to verify details.

The following CAS feature modules are extracted and moved out of the default CAS web application bundle to reduce configuration overhead and improve startup time. You will
need to expressly list them in your CAS overlay build script to activate the feature:

- `cas-server-support-pm-webflow`: Password Management Webflow configuration
- `cas-server-support-throttle`: Authentication Throttling core configuration
- `cas-server-support-geolocation`: Geolocation Core configuration; generally pulled in automatically depending on the method of geotracking.
- `cas-server-support-reports`: CAS Actuator endpoints backed by Spring Boot; must be pulled in if you rely on the old `status` endpoint.
- `cas-server-core-events`: Authentication Events tracking and configuration
- `cas-server-core-events-configuration`: Core configuration and event listeners for rebinding CAS settings for hot reloads.
- `cas-server-core-monitor`: Configuration for simple CAS `HealthIndicator`s on memory and ticket state.
- `cas-server-core-configuration-metadata-repository`: CAS configuration metadata endpoint and repository.

### MFA Trusted Devices GeoLocation Fingerprint

Device fingerprints may now also be calculated using geolocation data provided by browser, when working with the [multifactor trusted device](https://apereo.github.io/cas/development/mfa/Multifactor-TrustedDevice-Authentication.html) feature.

### Ticket Registry Expiration Policies

Core refinements are made internally to the construction of ticket registry expiration policy components to allow values to become refreshable via `@RefreshScope`
without interfering with object serialization with cache-based ticket registries such as Memcached, Hazelcast, etc.

## Other Stuff

- [Cassandra as a ticket registry](https://apereo.github.io/cas/development/ticketing/Cassandra-Ticket-Registry.html) is improved to take advantage of distinct tables for ticket types per the CAS ticket catalog.
- Principal transformation via Groovy can now detect and load changes to the external Groovy script automatically.
- LDAP search queries can now process paged responses, instructed by CAS configuration, to fully obtain LDAP results from a query.
- Minor fixes to properties and relevant documentation for typos, etc.
- Incremental and performance improvements to MongoDb acting as a [service registry](https://apereo.github.io/cas/development/services/MongoDb-Service-Management.html) and a [ticket registry](https://apereo.github.io/cas/development/ticketing/MongoDb-Ticket-Registry.html).
- Minor fixes to [Passwordless AuthN](https://apereo.github.io/cas/development/installation/Passwordless-Authentication.html) in terms of error handling and webflow navigation.
- Dynamic Spring Webflow Configurers are now made into conditional beans to provider an easier channel for overrides.
- The `cas-server-support-validation` module is broken apart separate auto-configuration from core components.
- Delegated authentication to SAML2 identity providers gains the ability to specify signed authentication requests, multiple context classes, etc.

## Library Upgrades

- BounctCastle
- Amazon SDK
- Gradle
- Apache Tomcat
- Spring Boot
- Nexmo
- Hazelcast
- Spring
- Spring Integration
- Spring Security
- Log4j
- Infinispan
- MariaDb Driver
- Pac4j
- Guava
- FontAwesome
- Nimbus
- Apache Ignite

## Credits

Big thanks to all who participate in the development of this release to submit patches and contribute improvements. Keep'em coming!

[Misagh Moayyed](https://fawnoos.com)