text:
<!-- Provide a general summary of the issue in the Title above -->

## Detailed description

Provide a detailed description of the change or addition you are proposing.

Make it clear if the issue is a bug, an enhancement or just a question.

## Context

Why is this change important to you? How would you use it?

How can it benefit other users?

## Possible implementation

Not obligatory, but suggest an idea for implementing addition or change.

## Your environment

Include as many relevant details about the environment you experienced the bug in and how to reproduce it.

* Version used (e.g. PHP 7.1, HHVM 3):
* Operating system and version (e.g. Ubuntu 16.04, Windows 7):
* Link to your project:
* ...
* ...


text:
<?php declare(strict_types=1);

namespace Application\Migrations;

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

/**
 * Auto-generated Migration: Please modify to your needs!
 */
final class Version20200114073433 extends AbstractMigration
{
    public function up(Schema $schema) : void
    {
        // 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('ALTER TABLE inloop_vrijwilligers DROP FOREIGN KEY FK_56110480EA9C84FE');
        $this->addSql('ALTER TABLE inloop_vrijwilligers ADD CONSTRAINT FK_56110480EA9C84FE FOREIGN KEY (medewerkerLocatie_id) REFERENCES medewerkers (id)');

    }

    public function down(Schema $schema) : void
    {
        // 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 inloop_vrijwilligers DROP FOREIGN KEY FK_56110480EA9C84FE');
        $this->addSql('ALTER TABLE inloop_vrijwilligers ADD CONSTRAINT FK_56110480EA9C84FE FOREIGN KEY (medewerkerLocatie_id) REFERENCES locaties (id)');

    }
}

redpajama_set_name: RedPajamaGithub


text:
//
//  EDMChooseViewController.m
//  EasyDecorationMaster
//
//  Created by lrb on 17/5/5.
//  Copyright © 2017年 aoshuo. All rights reserved.
//

#import "EDMChooseViewController.h"
#import "EDMUtils.h"
#import "AppDelegate.h"
#import "EDMLoginViewController.h"

@interface EDMChooseViewController ()

@end

@implementation EDMChooseViewController
/** 点击"客户端" */
- (IBAction)clientBtnClicked:(UIButton *)sender {
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setValue:IDTYPE_CUSTOMER forKey:IDTYPE];
    UIStoryboard *entrySB = [UIStoryboard storyboardWithName:SB_ID_ENTRY bundle:nil];
    EDMLoginViewController *loginVC = [entrySB instantiateViewControllerWithIdentifier:SB_VC_ID_LOGIN];
    [self.navigationController pushViewController:loginVC animated:YES];
}
/** 点击"师傅端" */
- (IBAction)masterBtnClicked:(UIButton *)sender {
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setValue:IDTYPE_MASTER forKey:IDTYPE];
    UIStoryboard *entrySB = [UIStoryboard storyboardWithName:SB_ID_ENTRY bundle:nil];
    EDMLoginViewController *loginVC = [entrySB instantiateViewControllerWithIdentifier:SB_VC_ID_LOGIN];
    [self.navigationController pushViewController:loginVC animated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
package nl.esciencecenter.osmium.job;

import static com.yammer.dropwizard.testing.JsonHelpers.fromJson;
import static com.yammer.dropwizard.testing.JsonHelpers.jsonFixture;
import static org.fest.assertions.api.Assertions.assertThat;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

import nl.esciencecenter.osmium.job.XenonConfiguration;
import nl.esciencecenter.osmium.job.PollConfiguration;
import nl.esciencecenter.osmium.job.SandboxConfiguration;
import nl.esciencecenter.osmium.job.SchedulerConfiguration;

import org.junit.Test;

import com.google.common.collect.ImmutableMap;

public class XenonConfigurationTest {
    public XenonConfiguration sampleConfig() throws URISyntaxException {
        SchedulerConfiguration scheduler = new SchedulerConfiguration("local", null, "multi", null);
        SandboxConfiguration sandbox = new SandboxConfiguration("file", null, "/tmp/sandboxes", null);
        ImmutableMap<String, String> prefs = ImmutableMap.of(
                "xenon.adaptors.local.queue.multi.maxConcurrentJobs", "1");
        PollConfiguration pollConf = new PollConfiguration();
        XenonConfiguration config = new XenonConfiguration(scheduler, sandbox, prefs, pollConf);
        return config;
    }

    @Test
    public void testGetPreferences_Filled() throws URISyntaxException {
        ImmutableMap<String, String> prefs = ImmutableMap.of(
                "xenon.adaptors.local.queue.multi.maxConcurrentJobs", "1");

        XenonConfiguration config = sampleConfig();

        assertThat(config.getPreferences()).isEqualTo(prefs);
    }

    @Test
    public void testGetPreferences_Empty() {
        XenonConfiguration g = new XenonConfiguration();
        ImmutableMap<String, String> expected = ImmutableMap.of();
        assertThat(g.getPreferences()).isEqualTo(expected);
    }

    @Test
    public void testSetPreferences() {
        XenonConfiguration g = new XenonConfiguration();
        ImmutableMap<String, String> prefs = ImmutableMap.of("mykey", "myval");
        g.setPreferences(prefs);
        assertThat(g.getPreferences()).isEqualTo(prefs);
    }

    @Test
    public void deserializesFromJson() throws IOException, URISyntaxException {
        XenonConfiguration actual = fromJson(jsonFixture("fixtures/xenon.json"),
                XenonConfiguration.class);

        ImmutableMap<String, String> emptyProps = ImmutableMap.of();
        SchedulerConfiguration expectedScheduler = new SchedulerConfiguration("local", null, "multi", emptyProps);
        assertThat(actual.getScheduler()).isEqualTo(expectedScheduler);

        SandboxConfiguration expectedSandbox = new SandboxConfiguration("file", "/", "/tmp/sandboxes", emptyProps);
        assertThat(actual.getSandbox()).isEqualTo(expectedSandbox);

        ImmutableMap<String, String> prefs = ImmutableMap.of(
                "xenon.adaptors.local.queue.multi.maxConcurrentJobs", "4");
        assertThat(actual.getPreferences()).isEqualTo(prefs);
        PollConfiguration expected_poll = new PollConfiguration(500, 3600000, 43200000);
        assertThat(actual.getPoll()).isEqualTo(expected_poll);
    }

    @Test
    public void validateFromJson() throws IOException {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        XenonConfiguration actual = fromJson(jsonFixture("fixtures/xenon.json"),
                XenonConfiguration.class);

        Set<ConstraintViolation<XenonConfiguration>> constraintViolations = validator.validateProperty(actual, "scheduler");

        assertThat(constraintViolations.size()).isEqualTo(0);
    }

    @Test
    public void testToString() throws URISyntaxException {
        XenonConfiguration config = sampleConfig();
        String expected = "XenonConfiguration{SchedulerConfiguration{local, multi, null, null}, SandboxConfiguration{file, /tmp/sandboxes, null, null}, {xenon.adaptors.local.queue.multi.maxConcurrentJobs=1}, PollConfiguration{30000, 3600000, 43200000}}";
        assertThat(config.toString()).isEqualTo(expected);
    }

    @Test
    public void testHashCode() throws URISyntaxException {
        XenonConfiguration config = sampleConfig();
        int expected = -318369353;
        assertThat(config.hashCode()).isEqualTo(expected);
    }

    @Test
    public void testEquals_SameObj_equal() throws URISyntaxException {
        XenonConfiguration config = sampleConfig();
        assertThat(config.equals(config)).isTrue();
    }

    @Test
    public void testEquals_DiffClass_unequal() throws URISyntaxException {
        XenonConfiguration config = sampleConfig();
        URI uri = new URI("local:///");
        assertThat(config.equals(uri)).isFalse();
    }

    @Test
    public void testEquals_SameContent_equal() throws URISyntaxException {
        XenonConfiguration config1 = sampleConfig();
        XenonConfiguration config2 = sampleConfig();
        assertThat(config1.equals(config2)).isTrue();
    }
}


text:
int main(int argc, char** argv) {
#if BUILDFLAG(IS_CHROMEOS_ASH)
  ash::AshTestSuite test_suite(argc, argv);
#else
  exo::test::ExoTestSuiteAura test_suite(argc, argv);
#endif

#if !BUILDFLAG(IS_IOS)
  mojo::core::Init();
#endif

  return base::LaunchUnitTests(
      argc, argv,
      base::BindOnce(&base::TestSuite::Run, base::Unretained(&test_suite)));
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
	backupGlobals="false"
	backupStaticAttributes="false"
	colors="true"
	convertErrorsToExceptions="true"
	convertNoticesToExceptions="true"
	convertWarningsToExceptions="true"
	processIsolation="false"
	stopOnFailure="false"
	syntaxCheck="false"
	bootstrap="tests/bootstrap.php"
>
	<php>
		<ini name="suhosin.executor.include.whitelist" value="data,phar"/>
		<ini name="allow_url_include" value="on"/>
	</php>
	<testsuites>
		<testsuite name="Litter Test Suite">
			<directory>./tests/Litter/</directory>
		</testsuite>
	</testsuites>
</phpunit>


text:
#include "dcgf.h"
#include "BSurfaceSDL.h"
#include "BRenderSDL.h"
#include "SdlUtil.h"

//////////////////////////////////////////////////////////////////////////
CBSurfaceSDL::CBSurfaceSDL(CBGame* inGame) : CBSurface(inGame)
{
	m_Texture = NULL;
	m_AlphaMask = NULL;

	CachedPixels = NULL;
	m_LockPixels = NULL;
	m_LockPitch = 0;

	m_MaskX = 0;
	m_MaskY = 0;
}

//////////////////////////////////////////////////////////////////////////
CBSurfaceSDL::~CBSurfaceSDL()
{
	if (m_Texture) SDL_DestroyTexture(m_Texture);
	SAFE_DELETE_ARRAY(m_AlphaMask);
	SAFE_DELETE_ARRAY(CachedPixels);
	Game->AddMem(-m_Width * m_Height * 4);
}

/////////////////////////////////////////////////////////////////////////////////

HRESULT CBSurfaceSDL::Create(char* Filename, bool default_ck, BYTE ck_red, BYTE ck_green, BYTE ck_blue, int LifeTime, bool KeepLoaded, bool KeepSurfaceCached)
{
	CBRenderSDL* renderer = static_cast<CBRenderSDL*>(Game->m_Renderer);

	FreeImageIO io;
	io.read_proc = CBSurfaceSDL::ReadProc;
	io.write_proc = NULL;
	io.seek_proc = CBSurfaceSDL::SeekProc;
	io.tell_proc = CBSurfaceSDL::TellProc;

	CBFile* file = Game->m_FileManager->OpenFile(Filename);
	if (!file) return E_FAIL;

	if(default_ck)
	{
		ck_red   = 255;
		ck_green = 0;
		ck_blue  = 255;
	}

	FREE_IMAGE_FORMAT imgFormat = FreeImage_GetFileTypeFromHandle(&io, (fi_handle)file, 0);
	FIBITMAP* img = FreeImage_LoadFromHandle(imgFormat, &io, (fi_handle)file, 0);
	Game->m_FileManager->CloseFile(file);

	if (!img) return E_FAIL;

	m_Width = FreeImage_GetWidth(img);
	m_Height = FreeImage_GetHeight(img);

	bool isSaveGameGrayscale = CBPlatform::strnicmp(Filename, "savegame:", 9)==0 && (Filename[strlen(Filename)-1]=='g' || Filename[strlen(Filename)-1]=='G');
	if (isSaveGameGrayscale)
	{
		FIBITMAP* newImg = FreeImage_ConvertToGreyscale(img);
		if (newImg)
		{
			FreeImage_Unload(img);
			img = newImg;
		}
	}

	// convert 32-bit BMPs to 24-bit or they appear totally transparent (does any app actually write alpha in BMP properly?)
	if (FreeImage_GetBPP(img) != 32 || (imgFormat == FIF_BMP && FreeImage_GetBPP(img) != 24))
	{
		FIBITMAP* newImg = FreeImage_ConvertTo24Bits(img);
		if (newImg)
		{
			FreeImage_Unload(img);
			img = newImg;
		}
		else
		{
			FreeImage_Unload(img);
			return -1;
		}
	}

	FreeImage_FlipVertical(img);

	void* inPtr = FreeImage_GetBits(img);
	SDL_Surface* surf = SDL_CreateRGBSurfaceFrom(inPtr, m_Width, m_Height, FreeImage_GetBPP(img), FreeImage_GetPitch(img), FI_RGBA_RED_MASK, FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, FI_RGBA_ALPHA_MASK);

	// m_SdlSurface = surf;

	// no alpha, set color key
	if (FreeImage_GetBPP(img) != 32)
		SDL_SetColorKey(surf, SDL_TRUE, SDL_MapRGB(surf->format, ck_red, ck_green, ck_blue));

	SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "best");
	//m_Texture = SdlUtil::CreateTextureFromSurface(renderer->GetSdlRenderer(), surf);

	if (KeepSurfaceCached)
	{
		m_SdlSurface = surf;
		CreateStreamedTextureFromSurface();
	}
	else
		m_Texture = SDL_CreateTextureFromSurface(renderer->GetSdlRenderer(), surf);

	if (!m_Texture)
	{
		SDL_FreeSurface(surf);
		FreeImage_Unload(img);
		return E_FAIL;
	}

	GenAlphaMask(surf);

	if (!KeepSurfaceCached)
		SDL_FreeSurface(surf);

	FreeImage_Unload(img);

	m_CKDefault = default_ck;
	m_CKRed = ck_red;
	m_CKGreen = ck_green;
	m_CKBlue = ck_blue;

	if (!m_Filename || CBPlatform::stricmp(m_Filename, Filename) !=0)
	{
		SetFilename(Filename);
	}

	if(m_LifeTime==0 || LifeTime==-1 || LifeTime>m_LifeTime)
		m_LifeTime = LifeTime;

	m_KeepLoaded = KeepLoaded;
	if(m_KeepLoaded) m_LifeTime = -1;

	m_Valid = true;

	Game->AddMem(m_Width * m_Height * 4);

	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
void CBSurfaceSDL::GenAlphaMask(SDL_Surface* surface)
{
	SAFE_DELETE_ARRAY(m_AlphaMask);
	if (!surface) return;

	SDL_LockSurface(surface);

	bool hasColorKey;
	Uint32 colorKey;
	Uint8 ckRed, ckGreen, ckBlue;
	if (SDL_GetColorKey(surface, &colorKey) == 0)
	{
		hasColorKey = true;
		SDL_GetRGB(colorKey, surface->format, &ckRed, &ckGreen, &ckBlue);
	}
	else hasColorKey = false;

	m_AlphaMask = new BYTE[surface->w * surface->h];

	bool hasTransparency = false;
	for (int y = 0; y < surface->h; y++)
	{
		for (int x = 0; x < surface->w; x++)
		{
			Uint32 pixel = GetPixel(surface, x, y);

			Uint8 r, g, b, a;
			SDL_GetRGBA(pixel, surface->format, &r, &g, &b, &a);

			if (hasColorKey && r == ckRed && g == ckGreen && b == ckBlue)
				a = 0;

			m_AlphaMask[y * surface->w + x] = a; // a
			if (a < 255) hasTransparency = true;
		}
	}

	SDL_UnlockSurface(surface);

	if (!hasTransparency)
    {
        SAFE_DELETE_ARRAY(m_AlphaMask);
    }
}

//////////////////////////////////////////////////////////////////////////
Uint32 CBSurfaceSDL::GetPixel(SDL_Surface *surface, int x, int y)
{
	int bpp = surface->format->BytesPerPixel;
	/* Here p is the address to the pixel we want to retrieve */
	Uint8* p = (Uint8*)surface->pixels + y * surface->pitch + x * bpp;

	switch(bpp)
	{
	case 1:
		return *p;
		break;

	case 2:
		return *(Uint16 *)p;
		break;

	case 3:
		if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
			return p[0] << 16 | p[1] << 8 | p[2];
		else
			return p[0] | p[1] << 8 | p[2] << 16;
		break;

	case 4:
		return *(Uint32 *)p;
		break;

	default:
		return 0;       /* shouldn't happen, but avoids warnings */
	}
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::Create(int Width, int Height)
{
	CBRenderSDL* renderer = static_cast<CBRenderSDL*>(Game->m_Renderer);
	m_Texture = SDL_CreateTexture(renderer->GetSdlRenderer(), SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STREAMING, Width, Height);

	m_Width = Width;
	m_Height = Height;
	EmptyTexture();

	Game->AddMem(m_Width * m_Height * 4);

	m_Valid = true;

	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::CreateFromSDLSurface(SDL_Surface* surface)
{
	CBRenderSDL* renderer = static_cast<CBRenderSDL*>(Game->m_Renderer);
	m_Texture = SDL_CreateTextureFromSurface(renderer->GetSdlRenderer(), surface);

	m_Width = surface->w;
	m_Height = surface->h;

	Game->AddMem(m_Width * m_Height * 4);

	m_Valid = true;

	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
bool CBSurfaceSDL::IsTransparentAt(int X, int Y)
{
	int access;
	int width, height;
	SDL_QueryTexture(m_Texture, NULL, &access, &width, &height);
	//if (access != SDL_TEXTUREACCESS_STREAMING) return false;
	if (X < 0 || X >= width || Y < 0 || Y >= height) return true;

	StartPixelOp();
	bool ret = IsTransparentAtLite(X, Y);
	EndPixelOp();

	return ret;
}

//////////////////////////////////////////////////////////////////////////
bool CBSurfaceSDL::IsTransparentAtLite(int X, int Y)
{
	//if (!m_LockPixels) return false;

	Uint32 format;
	int access;
	int width, height;
	SDL_QueryTexture(m_Texture, &format, &access, &width, &height);
	if (X < 0 || X >= width || Y < 0 || Y >= height) return true;

	if (!m_AlphaMask) return false;
	else return m_AlphaMask[Y * width + X] <= 128;
}

//////////////////////////////////////////////////////////////////////////
BYTE CBSurfaceSDL::GetAlphaAt(int x, int y)
{
	Uint32 format;
	int access;
	int width, height;
	SDL_QueryTexture(m_Texture, &format, &access, &width, &height);
	if (x < 0 || x >= width || y < 0 || y >= height) return 0;

	if (!m_AlphaMask) return 0;
	else return m_AlphaMask[y * width + x];
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::StartPixelOp()
{
	//SDL_LockTexture(m_Texture, NULL, &m_LockPixels, &m_LockPitch);
	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::EndPixelOp()
{
	//SDL_UnlockTexture(m_Texture);
	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::Display(int X, int Y, RECT rect, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return DrawSprite(X, Y, &rect, 100, 100, 0xFFFFFFFF, true, BlendMode, MirrorX, MirrorY);
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::DisplayTrans(int X, int Y, RECT rect, DWORD Alpha, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return DrawSprite(X, Y, &rect, 100, 100, Alpha, false, BlendMode, MirrorX, MirrorY);
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::DisplayTransOffset(int X, int Y, RECT rect, DWORD Alpha, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY, int offsetX, int offsetY)
{
	return DrawSprite(X, Y, &rect, 100, 100, Alpha, false, BlendMode, MirrorX, MirrorY, offsetX, offsetY);
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::DisplayTransZoom(int X, int Y, RECT rect, float ZoomX, float ZoomY, DWORD Alpha, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return DrawSprite(X, Y, &rect, ZoomX, ZoomY, Alpha, false, BlendMode, MirrorX, MirrorY);
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::DisplayZoom(int X, int Y, RECT rect, float ZoomX, float ZoomY, DWORD Alpha, bool Transparent, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return DrawSprite(X, Y, &rect, ZoomX, ZoomY, Alpha, !Transparent, BlendMode, MirrorX, MirrorY);
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::DisplayTransform(int X, int Y, int HotX, int HotY, RECT Rect, float ZoomX, float ZoomY, DWORD Alpha, float Rotate, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY)
{
	return DrawSprite(X, Y, &Rect, ZoomX, ZoomY, Alpha, false, BlendMode, MirrorX, MirrorY, 0, 0, HotX, HotY, Rotate);
}

//////////////////////////////////////////////////////////////////////////
HRESULT CBSurfaceSDL::DrawSprite(int X, int Y, RECT* Rect, float ZoomX, float ZoomY, DWORD Alpha, bool AlphaDisable, TSpriteBlendMode BlendMode, bool MirrorX, bool MirrorY, int offsetX, int offsetY, int originX, int originY, float angle)
{
	CBRenderSDL* renderer = static_cast<CBRenderSDL*>(Game->m_Renderer);

	 if (renderer->m_ForceAlphaColor != 0)
		Alpha = renderer->m_ForceAlphaColor;

//	renderer->m_ForceAlphaColor = 0;

//	AlphaDisable = false;

	BYTE r = D3DCOLGetR(Alpha);
	BYTE g = D3DCOLGetG(Alpha);
	BYTE b = D3DCOLGetB(Alpha);
	BYTE a = D3DCOLGetA(Alpha);

	SDL_SetTextureColorMod(m_Texture, r, g, b);
	SDL_SetTextureAlphaMod(m_Texture, a);

	if (AlphaDisable)
		SDL_SetTextureBlendMode(m_Texture, SDL_BLENDMODE_NONE);
	else if (BlendMode == 1)
		SDL_SetTextureBlendMode(m_Texture, SDL_BLENDMODE_ADD);
	else
		 SDL_SetTextureBlendMode(m_Texture, SDL_BLENDMODE_BLEND);

	SDL_Rect srcRect;
	srcRect.x = Rect->left;
	srcRect.y = Rect->top;
	srcRect.w = Rect->right - Rect->left;
	srcRect.h = Rect->bottom - Rect->top;

	SDL_Rect position;
	position.x = X;
	position.y = Y;
	position.w = (float)srcRect.w * ZoomX / 100.f;
	position.h = (float)srcRect.h * ZoomY / 100.f;

	renderer->ModTargetRect(&position);

	position.x += offsetX;
	position.y += offsetY;

	if (angle == 0.0f && !MirrorX && !MirrorY) SDL_RenderCopy(renderer->GetSdlRenderer(), m_Texture, &srcRect, &position);
	else
	{
		SDL_Point origin;
		origin.x = originX * ZoomX / 100.f;
		origin.y = originY * ZoomY / 100.f;
		renderer->ModOrigin(&origin);

		int flip = SDL_FLIP_NONE;
		if (MirrorX) flip |= SDL_FLIP_HORIZONTAL;
		if (MirrorY) flip |= SDL_FLIP_VERTICAL;

		SDL_RenderCopyEx(renderer->GetSdlRenderer(), m_Texture, &srcRect, &position, angle, &origin, (SDL_RendererFlip)flip);
	}

	return S_OK;
}

//////////////////////////////////////////////////////////////////////////
unsigned CBSurfaceSDL::ReadProc(void *buffer, unsigned size, unsigned count, fi_handle handle)
{
	CBFile* file = static_cast<CBFile*>(handle);
	file->Read(buffer, size * count);
	return count;
}

//////////////////////////////////////////////////////////////////////////
int CBSurfaceSDL::SeekProc(fi_handle handle, long offset, int origin)
{
	CBFile* file = static_cast<CBFile*>(handle);
	file->Seek(offset, (TSeek)origin);
	return 0;
}

//////////////////////////////////////////////////////////////////////////
long CBSurfaceSDL::TellProc(fi_handle handle)
{
	CBFile* file = static_cast<CBFile*>(handle);
	return file->GetPos();
}

//////////////////////////////////////////////////////////////////////////
void CBSurfaceSDL::FillTexture(const void* pixelData, int pitch, CBSurfaceSDL* alphaTexture)
{
	if (!alphaTexture) SDL_UpdateTexture(m_Texture, NULL, pixelData, pitch);
	else
	{
		BYTE* texPixels;
		int texPitch;
		SDL_LockTexture(m_Texture, NULL, (void**)&texPixels, &texPitch);

		for (int row = 0; row < m_Height; row++)
		{
			for (int col = 0; col < m_Width; col++)
			{
				BYTE* source = &((BYTE*)pixelData)[row * pitch + 4 * col];
				BYTE* target = &texPixels[row * texPitch + 4 * col];

				target[0] = alphaTexture->GetAlphaAt(col, row);
				target[1] = source[1];
				target[2] = source[2];
				target[3] = source[3];
			}
		}
		SDL_UnlockTexture(m_Texture);
	}
}

void CBSurfaceSDL::EmptyTexture()
{
		BYTE* texPixels;
		int texPitch;

		SDL_LockTexture(m_Texture, NULL, (void**)&texPixels, &texPitch);

		for (int row = 0; row < m_Height; row++)
		{
			for (int col = 0; col < m_Width; col++)
			{
				BYTE* target = &texPixels[row * texPitch + 4 * col];

				target[0] = 0;
				target[1] = 0;
				target[2] = 0;
				target[3] = 0;
			}
		}

		SDL_UnlockTexture(m_Texture);
}

void CBSurfaceSDL::CreateStreamedTextureFromSurface()
{
	if (m_Texture) SDL_DestroyTexture(m_Texture);
	CBRenderSDL* renderer = static_cast<CBRenderSDL*>(Game->m_Renderer);
	m_Texture = SDL_CreateTexture(renderer->GetSdlRenderer(), SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, this->m_SdlSurface->w, this->m_SdlSurface->h);
	CopyPixelsToTexture(m_SdlSurface, m_Texture);
}

void CBSurfaceSDL::CopyPixelsToTexture(SDL_Surface* surface, SDL_Texture *texture, CBSurface* alphaMask)
{
	BYTE* texPixels;
	int texPitch;

	if (CachedPixels == NULL)
	{
		CachedPixels = new BYTE[m_SdlSurface->pitch*m_SdlSurface->h];
		memcpy(CachedPixels,m_SdlSurface->pixels,m_SdlSurface->pitch*m_SdlSurface->h);
	}

	int result = SDL_LockTexture(texture, NULL, (void**)&texPixels, &texPitch);

	memcpy(texPixels,CachedPixels,m_SdlSurface->pitch*m_SdlSurface->h);

	if (alphaMask != NULL)
	{
		for (int row=0;row<alphaMask->GetHeight();row++)
		{
			for (int col=0;col<alphaMask->GetWidth();col++)
			{
				int py = row + alphaMask->m_MaskY;
				int px = col + alphaMask->m_MaskX;

				if (px < m_SdlSurface->w && py < m_SdlSurface->h && px >=0 && py >=0)
				{
					BYTE* target = &texPixels[(py * m_SdlSurface->pitch) + (4 * px)];
					target[3] = ((CBSurfaceSDL *)alphaMask)->GetAlphaAt(row,col);
				}
			}
		}
	}

	SDL_UnlockTexture(texture);
}

void CBSurfaceSDL::ApplyTextureMask(CBSurface* alphaMask)
{
	if (alphaMask == NULL || m_SdlSurface == NULL || m_Texture == NULL) return;
	//CreateStreamedTextureFromSurface();
	CopyPixelsToTexture(m_SdlSurface,m_Texture, alphaMask);
}


text:
.class Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;
.super Lcom/android/internal/util/State;
.source "SupplicantStateTracker.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/wifi/SupplicantStateTracker;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "DefaultState"
.end annotation

# instance fields
.field final synthetic this$0:Lcom/android/server/wifi/SupplicantStateTracker;

# direct methods
.method constructor <init>(Lcom/android/server/wifi/SupplicantStateTracker;)V
    .locals 0
    .param p1, "this$0"    # Lcom/android/server/wifi/SupplicantStateTracker;

    .prologue
    .line 218
    iput-object p1, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-direct {p0}, Lcom/android/internal/util/State;-><init>()V

    return-void
.end method

# virtual methods
.method public enter()V
    .locals 3

    .prologue
    .line 221
    invoke-static {}, Lcom/android/server/wifi/SupplicantStateTracker;->-get0()Z

    move-result v0

    if-eqz v0, :cond_0

    const-string/jumbo v0, "SupplicantStateTracker"

    new-instance v1, Ljava/lang/StringBuilder;

    invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {p0}, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->getName()Ljava/lang/String;

    move-result-object v2

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    const-string/jumbo v2, "\n"

    invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v1

    invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 220
    :cond_0
    return-void
.end method

.method public processMessage(Landroid/os/Message;)Z
    .locals 7
    .param p1, "message"    # Landroid/os/Message;

    .prologue
    const/4 v6, 0x0

    const/4 v5, 0x1

    .line 225
    invoke-static {}, Lcom/android/server/wifi/SupplicantStateTracker;->-get0()Z

    move-result v2

    if-eqz v2, :cond_0

    const-string/jumbo v2, "SupplicantStateTracker"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {p0}, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->getName()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {p1}, Landroid/os/Message;->toString()Ljava/lang/String;

    move-result-object v4

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    const-string/jumbo v4, "\n"

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I

    .line 226
    :cond_0
    iget v2, p1, Landroid/os/Message;->what:I

    sparse-switch v2, :sswitch_data_0

    .line 249
    const-string/jumbo v2, "SupplicantStateTracker"

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v4, "Ignoring "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-static {v2, v3}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;)I

    .line 252
    :goto_0
    return v5

    .line 228
    :sswitch_0
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v2}, Lcom/android/server/wifi/SupplicantStateTracker;->-get3(Lcom/android/server/wifi/SupplicantStateTracker;)I

    move-result v3

    add-int/lit8 v3, v3, 0x1

    invoke-static {v2, v3}, Lcom/android/server/wifi/SupplicantStateTracker;->-set2(Lcom/android/server/wifi/SupplicantStateTracker;I)I

    .line 229
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v2, v5}, Lcom/android/server/wifi/SupplicantStateTracker;->-set1(Lcom/android/server/wifi/SupplicantStateTracker;Z)Z

    goto :goto_0

    .line 232
    :sswitch_1
    iget-object v1, p1, Landroid/os/Message;->obj:Ljava/lang/Object;

    check-cast v1, Lcom/android/server/wifi/StateChangeResult;

    .line 233
    .local v1, "stateChangeResult":Lcom/android/server/wifi/StateChangeResult;
    iget-object v0, v1, Lcom/android/server/wifi/StateChangeResult;->state:Landroid/net/wifi/SupplicantState;

    .line 234
    .local v0, "state":Landroid/net/wifi/SupplicantState;
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    iget-object v3, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v3}, Lcom/android/server/wifi/SupplicantStateTracker;->-get2(Lcom/android/server/wifi/SupplicantStateTracker;)Z

    move-result v3

    invoke-static {v2, v0, v3}, Lcom/android/server/wifi/SupplicantStateTracker;->-wrap2(Lcom/android/server/wifi/SupplicantStateTracker;Landroid/net/wifi/SupplicantState;Z)V

    .line 235
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v2, v6}, Lcom/android/server/wifi/SupplicantStateTracker;->-set1(Lcom/android/server/wifi/SupplicantStateTracker;Z)Z

    .line 236
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v2, v1}, Lcom/android/server/wifi/SupplicantStateTracker;->-wrap3(Lcom/android/server/wifi/SupplicantStateTracker;Lcom/android/server/wifi/StateChangeResult;)V

    goto :goto_0

    .line 239
    .end local v0    # "state":Landroid/net/wifi/SupplicantState;
    .end local v1    # "stateChangeResult":Lcom/android/server/wifi/StateChangeResult;
    :sswitch_2
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    iget-object v3, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v3}, Lcom/android/server/wifi/SupplicantStateTracker;->-get5(Lcom/android/server/wifi/SupplicantStateTracker;)Lcom/android/internal/util/State;

    move-result-object v3

    invoke-static {v2, v3}, Lcom/android/server/wifi/SupplicantStateTracker;->-wrap4(Lcom/android/server/wifi/SupplicantStateTracker;Lcom/android/internal/util/IState;)V

    goto :goto_0

    .line 242
    :sswitch_3
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v2, v5}, Lcom/android/server/wifi/SupplicantStateTracker;->-set3(Lcom/android/server/wifi/SupplicantStateTracker;Z)Z

    .line 243
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v2, v6}, Lcom/android/server/wifi/SupplicantStateTracker;->-set0(Lcom/android/server/wifi/SupplicantStateTracker;I)I

    goto :goto_0

    .line 246
    :sswitch_4
    iget-object v2, p0, Lcom/android/server/wifi/SupplicantStateTracker$DefaultState;->this$0:Lcom/android/server/wifi/SupplicantStateTracker;

    invoke-static {v2}, Lcom/android/server/wifi/SupplicantStateTracker;->-get1(Lcom/android/server/wifi/SupplicantStateTracker;)I

    move-result v3

    add-int/lit8 v3, v3, 0x1

    invoke-static {v2, v3}, Lcom/android/server/wifi/SupplicantStateTracker;->-set0(Lcom/android/server/wifi/SupplicantStateTracker;I)I

    goto :goto_0

    .line 226
    :sswitch_data_0
    .sparse-switch
        0x2006f -> :sswitch_2
        0x24006 -> :sswitch_1
        0x24007 -> :sswitch_0
        0x2402b -> :sswitch_4
        0x25001 -> :sswitch_3
    .end sparse-switch
.end method


text:
/**
 * @provides phui-tag-view-css
 */

.phui-tag-view {
  font-weight: bold;
  text-decoration: none;
  position: relative;
  -webkit-font-smoothing: antialiased;
  white-space: nowrap;
}

a.phui-tag-view:hover {
  text-decoration: none;
}

.phui-tag-core-closed {
  text-decoration: line-through;
  color: rgba(0,0,0,0.5);
}

.phui-tag-core-closed:hover {
  text-decoration: none;
}

.phui-tag-core {
  color: inherit;
  border: 1px solid transparent;
  border-radius: 3px;
  padding: 0 4px;
}

.phui-tag-type-state .phui-tag-core {
  padding: 1px 6px;
}

.phui-tag-view.phui-tag-type-state .phui-icon-view {
  margin: 0 6px 0 0;
}

.phui-tag-view .phui-icon-view {
  display: inline-block;
  margin: 0 4px 0 2px;
}

.phui-tag-dot {
  position: relative;
  display: inline-block;
  width: 6px;
  height: 6px;
  margin-right: 4px;
  top: -1px;
  border-radius: 6px;
  border: 1px solid transparent;
}

.phui-tag-type-state {
  color: #ffffff;
  text-shadow: rgba(100, 100, 100, 0.40) 0px -1px 1px;
}

.phui-tag-type-object,
a.phui-tag-type-object,
a.phui-tag-type-object:link,
.phui-tag-core-closed .phui-tag-color-object {
  color: #000;
}

.phui-tag-type-person {
  white-space: nowrap;
  color: #19558d;
}

.phui-tag-color-red {
  background-color: {$red};
  border-color: {$red};
}

.phui-tag-color-orange {
  background-color: {$orange};
  border-color: {$orange};
}

.phui-tag-color-yellow {
  background-color: {$yellow};
  border-color: {$yellow};
}

.phui-tag-color-blue {
  background-color: {$blue};
  border-color: {$blue};
}

.phui-tag-color-indigo {
  background-color: {$indigo};
  border-color: {$indigo};
}

.phui-tag-color-green {
  background-color: {$green};
  border-color: {$green};
}

.phui-tag-color-violet {
  background-color: {$violet};
  border-color: {$violet};
}

.phui-tag-color-black {
  background-color: #333333;
  border-color: #333333;
}

.phui-tag-color-grey {
  background-color: {$lightgreytext};
  border-color: {$lightgreytext};
}

.phui-tag-color-white {
  background-color: #f7f7f7;
  border-color: #f7f7f7;
}

.phui-tag-color-object {
  background-color: #e7e7e7;
  border-color: #e7e7e7;
}

.phui-tag-color-person {
  background-color: #f1f7ff;
  border-color: #f1f7ff;
}

a.phui-tag-view:hover
  .phui-tag-core.phui-tag-color-person {
  border-color: #d9ebfd;
}

a.phui-tag-view:hover
  .phui-tag-core.phui-tag-color-object {
  border-color: #d7d7d7;
}

.phabricator-handle-tag-list-item + .phabricator-handle-tag-list-item {
  margin-top: 4px;
}

.phui-object-item .phabricator-handle-tag-list {
  display: inline;
}

.phui-object-item .phabricator-handle-tag-list-item {
  display: inline-block;
  margin: 0 4px 2px 0;
}

/* - Shaded Tags ---------------------------------------------------------------

  For object representation inside text areas and lists.

*/

.phui-tag-shade {
  font-weight: normal;
}

.phui-tag-shade .phui-icon-view {
  font-size: 12px;
}

.phui-tag-shade-slim .phui-icon-view {
  font-size: 11px;
}

.phui-tag-shade-slim .phui-tag-core {
  font-size: {$smallerfontsize};
}

/* - Red -------------------------------------------------------------------- */

.phui-tag-shade-red .phui-tag-core,
.jx-tokenizer-token.red {
  background: {$sh-redbackground};
  border-color: {$sh-lightredborder};
  color: {$sh-redtext};
}

.phui-tag-shade-red .phui-icon-view,
.jx-tokenizer-token.red .phui-icon-view,
.jx-tokenizer-token.red .jx-tokenizer-x {
  color: {$sh-redicon};
}

a.phui-tag-view:hover.phui-tag-shade-red .phui-tag-core,
.jx-tokenizer-token.red:hover {
  border-color: {$sh-redborder};
}

/* - Orange ----------------------------------------------------------------- */

.phui-tag-shade-orange .phui-tag-core,
.jx-tokenizer-token.orange {
  background: {$sh-orangebackground};
  border-color: {$sh-lightorangeborder};
  color: {$sh-orangetext};
}

.phui-tag-shade-orange .phui-icon-view,
.jx-tokenizer-token.orange .phui-icon-view,
.jx-tokenizer-token.orange .jx-tokenizer-x {
  color: {$sh-orangeicon};
}

a.phui-tag-view:hover.phui-tag-shade-orange .phui-tag-core,
.jx-tokenizer-token.orange:hover {
  border-color: {$sh-orangeborder};
}

/* - Yellow ----------------------------------------------------------------- */

.phui-tag-shade-yellow .phui-tag-core,
.jx-tokenizer-token.yellow {
  background: {$sh-yellowbackground};
  border-color: {$sh-lightyellowborder};
  color: {$sh-yellowtext};
}

.phui-tag-shade-yellow .phui-icon-view,
.jx-tokenizer-token.yellow .phui-icon-view,
.jx-tokenizer-token.yellow .jx-tokenizer-x {
  color: {$sh-yellowicon};
}

a.phui-tag-view:hover.phui-tag-shade-yellow .phui-tag-core,
.jx-tokenizer-token.yellow:hover {
  border-color: {$sh-yellowborder};
}

/* - Blue ------------------------------------------------------------------- */

.phui-tag-shade-blue .phui-tag-core,
.jx-tokenizer-token.blue {
  background: {$sh-bluebackground};
  border-color: {$sh-lightblueborder};
  color: {$sh-bluetext};
}

.phui-tag-shade-blue .phui-icon-view,
.jx-tokenizer-token.blue .phui-icon-view,
.jx-tokenizer-token.blue .jx-tokenizer-x {
  color: {$sh-blueicon};
}

a.phui-tag-view:hover.phui-tag-shade-blue .phui-tag-core,
.jx-tokenizer-token.blue:hover {
  border-color: {$sh-blueborder};
}

/* - Indigo ----------------------------------------------------------------- */

.phui-tag-shade-indigo .phui-tag-core,
.jx-tokenizer-token.indigo {
  background: {$sh-indigobackground};
  border-color: {$sh-lightindigoborder};
  color: {$sh-indigotext};
}

.phui-tag-shade-indigo .phui-icon-view,
.jx-tokenizer-token.indigo .phui-icon-view,
.jx-tokenizer-token.indigo .jx-tokenizer-x {
  color: {$sh-indigoicon};
}

a.phui-tag-view:hover.phui-tag-shade-indigo .phui-tag-core,
.jx-tokenizer-token.indigo:hover {
  border-color: {$sh-indigoborder};
}

/* - Green ------------------------------------------------------------------ */

.phui-tag-shade-green .phui-tag-core,
.jx-tokenizer-token.green {
  background: {$sh-greenbackground};
  border-color: {$sh-lightgreenborder};
  color: {$sh-greentext};
}

.phui-tag-shade-green .phui-icon-view,
.jx-tokenizer-token.green .phui-icon-view,
.jx-tokenizer-token.green .jx-tokenizer-x {
  color: {$sh-greenicon};
}

a.phui-tag-view:hover.phui-tag-shade-green .phui-tag-core,
.jx-tokenizer-token.green:hover {
  border-color: {$sh-greenborder};
}

/* - Violet ----------------------------------------------------------------- */

.phui-tag-shade-violet .phui-tag-core,
.jx-tokenizer-token.violet {
  background: {$sh-violetbackground};
  border-color: {$sh-lightvioletborder};
  color: {$sh-violettext};
}

.phui-tag-shade-violet .phui-icon-view,
.jx-tokenizer-token.violet .phui-icon-view,
.jx-tokenizer-token.violet .jx-tokenizer-x {
  color: {$sh-violeticon};
}

a.phui-tag-view:hover.phui-tag-shade-violet .phui-tag-core,
.jx-tokenizer-token.violet:hover {
  border-color: {$sh-violetborder};
}

/* - Pink ------------------------------------------------------------------- */

.phui-tag-shade-pink .phui-tag-core,
.jx-tokenizer-token.pink {
  background: {$sh-pinkbackground};
  border-color: {$sh-lightpinkborder};
  color: {$sh-pinktext};
}

.phui-tag-shade-pink .phui-icon-view,
.jx-tokenizer-token.pink .phui-icon-view,
.jx-tokenizer-token.pink .jx-tokenizer-x {
  color: {$sh-pinkicon};
}

a.phui-tag-view:hover.phui-tag-shade-pink .phui-tag-core,
.jx-tokenizer-token.pink:hover {
  border-color: {$sh-pinkborder};
}

/* - Grey ------------------------------------------------------------------- */

.phui-tag-shade-grey .phui-tag-core,
.jx-tokenizer-token.grey {
  background: {$sh-greybackground};
  border-color: {$sh-lightgreyborder};
  color: {$sh-greytext};
}

.phui-tag-shade-grey .phui-icon-view,
.jx-tokenizer-token.grey .phui-icon-view,
.jx-tokenizer-token.grey .jx-tokenizer-x {
  color: {$sh-greyicon};
}

a.phui-tag-view:hover.phui-tag-shade-grey .phui-tag-core,
.jx-tokenizer-token.grey:hover {
  border-color: {$sh-greyborder};
}

/* - Checkered -------------------------------------------------------------- */

.phui-tag-shade-checkered .phui-tag-core,
.jx-tokenizer-token.checkered {
  background: url(/rsrc/image/checker_lighter.png);
  border-style: dashed;
  border-color: {$sh-greyborder};
  color: {$sh-greytext};
  text-shadow: 1px 1px #fff;
}

.phui-tag-shade-checkered .phui-icon-view,
.jx-tokenizer-token.checkered .phui-icon-view,
.jx-tokenizer-token.checkered .jx-tokenizer-x {
  color: {$sh-greyicon};
}

a.phui-tag-view:hover.phui-tag-shade-checkered .phui-tag-core,
.jx-tokenizer-token.checkered:hover {
  border-style: solid;
  border-color: {$sh-greyborder};
}

/* - Disabled --------------------------------------------------------------- */

.phui-tag-shade-disabled .phui-tag-core {
  background-color: {$sh-disabledbackground};
  border-color: {$sh-lightdisabledborder};
  color: {$sh-disabledtext};
}

.phui-tag-shade-disabled .phui-icon-view {
  color: {$sh-disabledicon};
}

a.phui-tag-view:hover.phui-tag-shade-disabled .phui-tag-core {
  border-color: {$sh-disabledborder};
}


text:
dbn-cifar-10
============

Python implementation of DBN (Deep Belief Network) for CIFAR-10 datasets.


text:
class UserMailer < ApplicationMailer
   default from: 'geraldinagalvarez@gmail.com'

  def welcome_email(user)
    @user = user
    @url  = 'http://google.com'
    mail(to: @user.email, subject: 'Welcome to Local Tour Guide')
  end

  def tour_request_email(user)
    @user = user
    @url = 'http://google.com'
    mail(to: @user.email, subject: 'You have a new request for a tour')
  end

end


text:
"""The various output plugins for GenericHunts."""

import csv
import threading
import urllib

from grr.lib import aff4
from grr.lib import config_lib
from grr.lib import email_alerts
from grr.lib import export
from grr.lib import rdfvalue
from grr.lib import registry
from grr.lib import rendering
from grr.lib import utils
from grr.proto import flows_pb2

class HuntOutputPlugin(object):
  """The base class for output plugins.

  The way output plugins work is that for each result a hunt produces, all its
  registered output plugins get handed the result to store it in the respective
  format in turn. The methods a plugin has to provide are ProcessResponse which
  gets handed the actual result to process and Flush which is called before
  the output plugin is about to be pickled and stored in the database.
  """

  __metaclass__ = registry.MetaclassRegistry

  name = ""
  description = ""
  args_type = None

  def __init__(self, collection_urn, args=None, token=None, state=None):
    """HuntOutputPlugin constructor.

    HuntOutputPlugin constructor is called during StartHuntFlow and therefore
    runs with security checks enabled (if they're enabled in the config).
    Therefore it's a bad idea to write anything to AFF4 in the constructor.

    Args:
      collection_urn: URN of the collection which results are going to be
                      processed.
      args: This plugin's arguments.
      token: Security token.
      state: Instance of rdfvalue.FlowState. Represents plugin's state. If this
             is passed, no initialization will be performed, only the state will
             be applied.
    Raises:
      ValueError: when state argument is passed together with args or token
                  arguments.
    """
    if state and (token or args):
      raise ValueError("'state' argument can't be passed together with 'args' "
                       "or 'token'.")

    if not state:
      self.state = state or rdfvalue.FlowState()
      self.state.Register("collection_urn", collection_urn)
      self.state.Register("args", args)
      self.state.Register("token", token)
      self.Initialize()
    else:
      self.state = state

    self.args = self.state.args
    self.token = self.state.token

    self.lock = threading.RLock()

  def Initialize(self):
    """Initializes the hunt output plugin.

    Initialize() is called when hunt is created. It can be used to register
    state variables. It's called on the worker, so no security checks apply.
    """

  def ProcessResponses(self, responses):
    """Processes bunch of responses.

    Multiple ProcessResponses() calls can be done in a row. They're *always*
    followed by a Flush() call. ProcessResponses() is called on the worker,
    so no security checks apply.

    NOTE: this method should be thread-safe as it may be called from multiple
    threads to improve hunt output performance.

    Args:
      responses: GrrMessages from the hunt results collection.
    """
    raise NotImplementedError()

  def Flush(self):
    """Flushes the output plugin's state.

    Flush is *always* called after a series of ProcessResponses() calls.
    Flush() is called on the worker, so no security checks apply.

    NOTE: This method doesn't have to be thread-safe as it's called after all
    ProcessResponses() calls are complete.
    """
    pass

class EmailPluginArgs(rdfvalue.RDFProtoStruct):
  protobuf = flows_pb2.EmailPluginArgs

class EmailPlugin(HuntOutputPlugin):
  """An output plugin that sends an email for each response received."""

  name = "email"
  description = "Send an email for each result."
  args_type = EmailPluginArgs

  template = """

GRR Hunt's results collection %(collection_urn)s got a new result.

  Grr Hunt's results collection %(collection_urn)s just got a response from client %(client_id)s
  (%(hostname)s):

  %(response)s

  Click  here  to
  access this machine.

  This notification was created by %(creator)s.

%(additional_message)s

Thanks,

%(signature)s

"""

  too_many_mails_msg = ("
 This hunt has now produced %d results so the "
                        "sending of emails will be disabled now.
")

  def Initialize(self):
    self.state.Register("emails_sent", 0)
    super(EmailPlugin, self).Initialize()

  def ProcessResponse(self, response):
    """Sends an email for each response."""

    if self.state.emails_sent >= self.state.args.email_limit:
      return

    client_id = response.source
    client = aff4.FACTORY.Open(client_id, token=self.token)
    hostname = client.Get(client.Schema.HOSTNAME) or "unknown hostname"

    subject = ("GRR Hunt results collection %s got a new result." %
               self.state.collection_urn)

    url = urllib.urlencode((("c", client_id),
                            ("main", "HostInformation")))

    response_htm = rendering.FindRendererForObject(response).RawHTML()

    self.state.emails_sent += 1
    if self.state.emails_sent == self.state.args.email_limit:
      additional_message = self.too_many_mails_msg % self.state.args.email_limit
    else:
      additional_message = ""

    email_alerts.SendEmail(
        self.state.args.email, "grr-noreply",
        subject,
        self.template % dict(
            client_id=client_id,
            admin_ui=config_lib.CONFIG["AdminUI.url"],
            hostname=hostname,
            urn=url,
            creator=self.token.username,
            collection_urn=self.state.collection_urn,
            response=response_htm,
            additional_message=additional_message,
            signature=config_lib.CONFIG["Email.signature"]
        ),
        is_html=True)

  @utils.Synchronized
  def ProcessResponses(self, responses):
    for response in responses:
      self.ProcessResponse(response)

class CSVOutputPluginArgs(rdfvalue.RDFProtoStruct):
  protobuf = flows_pb2.CSVOutputPluginArgs

class CSVOutputPlugin(HuntOutputPlugin):
  """Hunt output plugin that writes hunt's results to CSV file on AFF4.

  CSV files are written incrementally. After every batch of results is written,
  the file can be downloaded.

  TODO(user): add support for zipped CSV files. Produce compressed CSV
  files while retaining the capability to do incremental updates and have files
  in downloadable state after every update is not exactly trivial.
  """

  name = "csv"
  description = "Write CSV file to AFF4"
  args_type = CSVOutputPluginArgs

  def Initialize(self):
    super(CSVOutputPlugin, self).Initialize()
    self.state.Register("files_by_type", {})
    self.state.Register("last_updated", rdfvalue.RDFDatetime().Now())

  def ProcessResponses(self, responses):
    default_metadata = rdfvalue.ExportedMetadata(
        annotations=u",".join(self.state.args.export_options.annotations),
        source_urn=self.state.collection_urn)

    if self.state.args.convert_values:
      # This is thread-safe - we just convert the values.
      converted_responses = export.ConvertValues(
          default_metadata, responses, token=self.state.token,
          options=self.state.args.export_options)
    else:
      converted_responses = responses

    # This is not thread-safe, therefore WriteValueToCSVFile is synchronized.
    self.WriteValuesToCSVFile(converted_responses)

  def GetCSVHeader(self, value_class, prefix=""):
    header = []
    for type_info in value_class.type_infos:
      if type_info.__class__.__name__ == "ProtoEmbedded":
        header.extend(
            self.GetCSVHeader(type_info.type, prefix=type_info.name + "."))
      else:
        header.append(prefix + type_info.name)

    return header

  def WriteCSVHeader(self, output_file, value_type):
    value_class = rdfvalue.RDFValue.classes[value_type]
    csv.writer(output_file).writerow(self.GetCSVHeader(value_class))

  def GetCSVRow(self, value):
    row = []
    for type_info in value.__class__.type_infos:
      if type_info.__class__.__name__ == "ProtoEmbedded":
        row.extend(self.GetCSVRow(value.Get(type_info.name)))
      else:
        row.append(value.Get(type_info.name))

    return row

  def WriteCSVRow(self, output_file, value):
    csv.writer(output_file).writerow(self.GetCSVRow(value))

  def GetOutputFile(self, value_type):
    """Initializes output AFF4Image for a given value type."""
    try:
      output_file = self.state.files_by_type[value_type]
    except KeyError:
      if self.state.args.output_dir:
        output_urn = self.state.args.output_dir.Add(value_type + ".csv")
        output_file = aff4.FACTORY.Create(output_urn, "AFF4Image",
                                          token=self.token)
      else:
        output_file = aff4.FACTORY.Create(None, "TempImageFile",
                                          token=self.token)
        output_file.urn = output_file.urn.Add(value_type + ".csv")

      self.WriteCSVHeader(output_file, value_type)
      self.state.files_by_type[value_type] = output_file

    return output_file

  @utils.Synchronized
  def WriteValuesToCSVFile(self, values):
    for value in values:
      output_file = self.GetOutputFile(value.__class__.__name__)
      self.WriteCSVRow(output_file, value)

  def Flush(self):
    for output_file in self.state.files_by_type.values():
      output_file.Flush()
    self.last_updated = rdfvalue.RDFDatetime().Now()

class OutputPlugin(rdfvalue.RDFProtoStruct):
  """A proto describing the output plugin to create."""
  protobuf = flows_pb2.OutputPlugin

  def GetPluginArgsClass(self):
    plugin_cls = HuntOutputPlugin.classes.get(self.plugin_name)
    if plugin_cls is not None:
      return plugin_cls.args_type

  def GetPluginForHunt(self, hunt_obj):
    cls = HuntOutputPlugin.classes.get(self.plugin_name)
    if cls is None:
      raise KeyError("Unknown output plugin %s" % self.plugin_name)

    return cls(hunt_obj.state.context.results_collection_urn,
               args=self.plugin_args, token=hunt_obj.token)

  def GetPluginForState(self, plugin_state):
    cls = HuntOutputPlugin.classes.get(self.plugin_name)
    if cls is None:
      raise KeyError("Unknown output plugin %s" % self.plugin_name)

    return cls(None, state=plugin_state)


text:
layout: default
title: PostgreSQL JDBC About
resource: /media
nav: /
---

{% include submenu_about.html %}

About

						PostgreSQL JDBC Driver (PgJDBC for short) allows Java programs to connect to a PostgreSQL database using standard,
						database independent Java code. Is an open source JDBC driver written in Pure Java (Type 4), and communicates in
						the PostgreSQL native network protocol.

						The current version of the driver should be compatible with PostgreSQL 8.2 and higher,
						and Java 8 (JDBC 4.2) and higher.

Features

						The driver provides a reasonably complete implementation of the JDBC specification in addition
						to some PostgreSQL specific extensions. Our goal is nothing short of full compliance, but we're not
						there yet. Some features require additional backend support and others just need someone to implement
						them. For a list of what still needs to be done see our Todo
						list.


text:
import pytz

from textwrap import wrap

from django.core.management.base import BaseCommand

from events.models import Ticket
from workshops.models import Workshop

# Workshop notes, indexed by workshop.pk
workshop_notes = {
    2:  # Metagrokking Elixir
        """
This is a talk-only kind of workshop. There will be no hands-on exercises,
so having a laptop is not required.
        """,
    4:  # Writing Superpowers for Geeks
        """
Please bring your favourite writing instrument, whether that is a laptop,
tablet, or paper and pencil.
        """,
    3:  # Logo Design Crash Course
        """
Bring your favorite sketching tools (sketchbook + pen, or a tablet with a
stylus).
        """,
    5:  # The Reset: Rethinking Float, Flex, Grid, and Web Layouts
        """
This workshop requires a laptop with a code editor of your choice and Firefox
Nightly, which can be downloaded here:
https://www.mozilla.org/en-US/firefox/channel/desktop/
        """,
    6:  # Learning WebGL by breaking stuff
        """
For this workshop you will need a laptop with git, Node.js, and a few other
tools installed, please have them installed before the workshop. OS-specific
requirements and instructions can be found here:
https://github.com/mapbox/mapbox-gl-js/blob/master/CONTRIBUTING.md#preparing-your-development-environment
        """,
    7:  # Keechma - Going Beyond Redux
        """
This is a talk-only kind of workshop. There will be no hands-on exercises,
so having a laptop is not required.

We will use the https://github.com/gothinkster/realworld as an example app. It
would be great if you're familiar with the implemenation in your framework of
choice, so we can talk about the differences.
        """,
    8:  # Flying Drones with NodeJS
        """
This workshop requires a laptop with Node.js, Git and a code editor of your
choice, so please have them installed before the workshop.
        """,

}

class Command(BaseCommand):
    help = "My shiny new management command."

    def add_arguments(self, parser):
        parser.add_argument('event_id')

    def handle(self, *args, **options):

        workshops = Workshop.objects.filter(event_id=options['event_id'])

        for workshop in workshops:
            self.generate_notification(workshop)

    def recipients(self, tickets):
        for t in tickets:
            yield "{} {} <{}>".format(t.first_name, t.last_name, t.email)

    def generate_notification(self, workshop):
        tickets = Ticket.objects.filter(category__startswith=workshop.title)
        recipients = ", ".join(self.recipients(tickets))

        # For some reason Django returns date in UTC
        starts_at = (workshop.starts_at
            .astimezone(pytz.timezone('Europe/Zagreb'))
            .strftime("%A, %Y-%m-%d @ %H:%M"))

        notes = workshop_notes.get(workshop.pk).strip()

        intro = """This is a reminder that you have an upcoming workshop: "{workshop.title}"
held on {starts_at} on the first floor of the Plaza Event Centar
(ex Hypo Center), Slavonska avenija 6.""".format(workshop=workshop, starts_at=starts_at)
        intro = "\n".join(wrap(intro)).strip()

        body = """From: WebCamp Zagreb <info@webcampzg.org>
To: WebCamp Zagreb <info@webcampzg.org>
Reply-To: WebCamp Zagreb <info@webcampzg.org>
Bcc: {recipients}
Subject: {workshop.title}

{intro}

{notes}

Please come 10 minutes earlier to allow for registration. If you also have
tickets for the conference, take them with you so you can register in
advance so you don't have to wait in line on Friday.

Best regards,
WebCamp Zagreb Team
""".format(recipients=recipients, workshop=workshop, intro=intro, notes=notes)

        filename = workshop.slug + ".eml"
        with open(filename, "w") as f:
            print("Writing: {}".format(filename))
            f.write(body)


text:
/* TPF needs its own version of gthr-*.h because TPF always links to
   the thread library.  However, for performance reasons we still do not
   want to issue thread api calls unless a check is made to see that we
   are running as a thread.  */

#ifndef GCC_GTHR_TPF_H
#define GCC_GTHR_TPF_H

/* POSIX threads specific definitions.
   Easy, since the interface is just one-to-one mapping.  */

#define __GTHREADS 1

/* Some implementations of <pthread.h> require this to be defined.  */
#ifndef _REENTRANT
#define _REENTRANT 1
#endif

#include <pthread.h>
#include <unistd.h>

typedef pthread_key_t __gthread_key_t;
typedef pthread_once_t __gthread_once_t;
typedef pthread_mutex_t __gthread_mutex_t;
typedef pthread_mutex_t __gthread_recursive_mutex_t;

#if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
#define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER
#elif defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
#define __GTHREAD_RECURSIVE_MUTEX_INIT PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
#endif

#define __GTHREAD_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER
#define __GTHREAD_ONCE_INIT PTHREAD_ONCE_INIT
#define __GTHREAD_RECURSIVE_MUTEX_INIT_FUNCTION __gthread_recursive_mutex_init_function

#define NOTATHREAD   00
#define ECBBASEPTR (unsigned long int) *(unsigned int *)0x00000514u
#define ECBPG2PTR  ECBBASEPTR + 0x1000
#define CE2THRCPTR *((unsigned char *)(ECBPG2PTR + 16))
#define __tpf_pthread_active() (CE2THRCPTR != NOTATHREAD)

#if SUPPORTS_WEAK && GTHREAD_USE_WEAK
# define __gthrw(name) \
  static __typeof(name) __gthrw_ ## name __attribute__ ((__weakref__(#name)));
# define __gthrw_(name) __gthrw_ ## name
#else
# define __gthrw(name)
# define __gthrw_(name) name
#endif

__gthrw(pthread_once)
__gthrw(pthread_key_create)
__gthrw(pthread_key_delete)
__gthrw(pthread_getspecific)
__gthrw(pthread_setspecific)
__gthrw(pthread_create)

__gthrw(pthread_mutex_lock)
__gthrw(pthread_mutex_trylock)
__gthrw(pthread_mutex_unlock)
__gthrw(pthread_mutexattr_init)
__gthrw(pthread_mutexattr_settype)
__gthrw(pthread_mutexattr_destroy)
__gthrw(pthread_mutex_init)
__gthrw(pthread_mutex_destroy)

static inline int
__gthread_active_p (void)
{
  return 1;
}

static inline int
__gthread_once (__gthread_once_t *__once, void (*__func) (void))
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_once) (__once, __func);
  else
    return -1;
}

static inline int
__gthread_key_create (__gthread_key_t *__key, void (*__dtor) (void *))
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_key_create) (__key, __dtor);
  else
    return -1;
}

static inline int
__gthread_key_delete (__gthread_key_t __key)
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_key_delete) (__key);
  else
    return -1;
}

static inline void *
__gthread_getspecific (__gthread_key_t __key)
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_getspecific) (__key);
  else
    return NULL;
}

static inline int
__gthread_setspecific (__gthread_key_t __key, const void *__ptr)
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_setspecific) (__key, __ptr);
  else
    return -1;
}

static inline int
__gthread_mutex_destroy (__gthread_mutex_t *__mutex)
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_mutex_destroy) (__mutex);
  else
    return 0;
}

static inline int
__gthread_mutex_lock (__gthread_mutex_t *__mutex)
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_mutex_lock) (__mutex);
  else
    return 0;
}

static inline int
__gthread_mutex_trylock (__gthread_mutex_t *__mutex)
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_mutex_trylock) (__mutex);
  else
    return 0;
}

static inline int
__gthread_mutex_unlock (__gthread_mutex_t *__mutex)
{
  if (__tpf_pthread_active ())
    return __gthrw_(pthread_mutex_unlock) (__mutex);
  else
    return 0;
}

static inline int
__gthread_recursive_mutex_lock (__gthread_recursive_mutex_t *__mutex)
{
  if (__tpf_pthread_active ())
    return __gthread_mutex_lock (__mutex);
  else
    return 0;
}

static inline int
__gthread_recursive_mutex_trylock (__gthread_recursive_mutex_t *__mutex)
{
  if (__tpf_pthread_active ())
    return __gthread_mutex_trylock (__mutex);
  else
    return 0;
}

static inline int
__gthread_recursive_mutex_unlock (__gthread_recursive_mutex_t *__mutex)
{
  if (__tpf_pthread_active ())
    return __gthread_mutex_unlock (__mutex);
  else
    return 0;
}

static inline int
__gthread_recursive_mutex_init_function (__gthread_recursive_mutex_t *__mutex)
{
  if (__tpf_pthread_active ())
    {
      pthread_mutexattr_t __attr;
      int __r;

      __r = __gthrw_(pthread_mutexattr_init) (&__attr);
      if (!__r)
	__r = __gthrw_(pthread_mutexattr_settype) (&__attr,
						   PTHREAD_MUTEX_RECURSIVE);
      if (!__r)
	__r = __gthrw_(pthread_mutex_init) (__mutex, &__attr);
      if (!__r)
	__r = __gthrw_(pthread_mutexattr_destroy) (&__attr);
      return __r;
    }
  return 0;
}

#endif /* ! GCC_GTHR_TPF_H */


text: New Website for TTU FSAE


text:
"""
Provides authorization functions for Mojang's login and session servers
"""

import hashlib
import json
# This is for python2 compatibility
try:
    import urllib.request as request
    from urllib.error import URLError
except ImportError:
    import urllib2 as request
    from urllib2 import URLError
import logging
import os

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import padding

from spockbot.mcp import yggdrasil
from spockbot.plugins.base import PluginBase, pl_announce

logger = logging.getLogger('spockbot')
backend = default_backend()

# This function courtesy of barneygale
def java_hex_digest(digest):
    d = int(digest.hexdigest(), 16)
    if d >> 39 * 4 & 0x8:
        d = "-%x" % ((-d) & (2 ** (40 * 4) - 1))
    else:
        d = "%x" % d
    return d

class AuthCore(object):
    def __init__(self, authenticated, event):
        self.event = event
        self.authenticated = authenticated
        self.username = None
        self.selected_profile = None
        self.shared_secret = None
        self.ygg = yggdrasil.YggAuth()

    def start_session(self, username, password=''):
        rep = {}
        if self.authenticated:
            logger.debug("AUTHCORE: Attempting login with username: %s",
                         username)
            rep = self.ygg.authenticate(username, password)
            if rep is None or 'error' in rep:
                logger.error('AUTHCORE: Login Unsuccessful, Response: %s', rep)
                self.event.emit('auth_login_error')
                return rep
            if 'selectedProfile' in rep:
                self.selected_profile = rep['selectedProfile']
                self.username = rep['selectedProfile']['name']
                logger.debug("AUTHCORE: Logged in as: %s", self.username)
                logger.debug("AUTHCORE: Selected Profile: %s",
                             self.selected_profile)
            else:
                self.username = username
        else:
            self.username = username
        return rep

    def gen_shared_secret(self):
        self.shared_secret = os.urandom(16)
        return self.shared_secret

@pl_announce('Auth')
class AuthPlugin(PluginBase):
    requires = ('Event', 'Net')
    defaults = {
        'authenticated': True,
        'auth_quit': True,
        'sess_quit': True,
    }
    events = {
        'auth_login_error': 'handle_auth_error',
        'auth_session_error': 'handle_session_error',
        'LOGIN<Encryption Request': 'handle_encryption_request',
    }

    def __init__(self, ploader, settings):
        super(AuthPlugin, self).__init__(ploader, settings)
        self.authenticated = self.settings['authenticated']
        self.auth_quit = self.settings['auth_quit']
        self.sess_quit = self.settings['sess_quit']
        self.auth = AuthCore(self.authenticated, self.event)
        self.auth.gen_shared_secret()
        ploader.provides('Auth', self.auth)

    def handle_auth_error(self, name, data):
        if self.auth_quit:
            self.event.kill()

    def handle_session_error(self, name, data):
        if self.sess_quit:
            self.event.kill()

    # Encryption Key Request - Request for client to start encryption
    def handle_encryption_request(self, name, packet):
        pubkey_raw = packet.data['public_key']
        if self.authenticated:
            serverid = java_hex_digest(hashlib.sha1(
                packet.data['server_id'].encode('ascii') +
                self.auth.shared_secret +
                pubkey_raw
            ))
            logger.debug(
                "AUTHPLUGIN: Attempting to authenticate session with "
                "sessionserver.mojang.com")
            url = "https://sessionserver.mojang.com/session/minecraft/join"
            data = json.dumps({
                'accessToken': self.auth.ygg.access_token,
                'selectedProfile': self.auth.selected_profile,
                'serverId': serverid,
            }).encode('utf-8')
            headers = {'Content-Type': 'application/json'}
            req = request.Request(url, data, headers)
            try:
                rep = request.urlopen(req).read().decode('ascii')
            except URLError:
                rep = 'Couldn\'t connect to sessionserver.mojang.com'
            if rep != "":
                logger.warning("AUTHPLUGIN: %s", rep)
                self.event.emit('auth_session_error')
            else:
                logger.debug("AUTHPLUGIN: Session authentication successful")
        pubkey = serialization.load_der_public_key(pubkey_raw, backend)

        def encrypt(data):
            return pubkey.encrypt(data, padding.PKCS1v15())

        self.net.push_packet(
            'LOGIN>Encryption Response',
            {
                'shared_secret': encrypt(self.auth.shared_secret),
                'verify_token': encrypt(packet.data['verify_token']),
            }
        )
        self.net.enable_crypto(self.auth.shared_secret)


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Lichenologist 33(4): 298 (2001)

#### Original name
Pannaria emodii P. M. Jørg.

### Remarks
null


text:
module Formtastic
  module Inputs
    # Outputs a country select input, wrapping around a regular country_select helper.
    # Rails doesn't come with a `country_select` helper by default any more, so you'll need to do
    # one of the following:
    #
    # * install the [country_select](https://github.com/stefanpenner/country_select) gem
    # * install any other country_select plugin that behaves in a similar way
    # * roll your own `country_select` helper with the same args and options as the Rails one
    #
    # Formtastic supports both 1.x and 2.x of stefanpenner/country_select, but if you're upgrading
    # from 1.x, they behave quite differently, so please see their [upgrade instructions](https://github.com/stefanpenner/country_select/blob/master/UPGRADING.md).
    #
    # By default, Formtastic includes a handful of English-speaking countries as "priority
    # countries", which can be set in the `priority_countries` configuration array in the
    # formtastic.rb initializer to suit your market and user base (see README for more info on
    # configuration). Additionally, it is possible to set the :priority_countries on a per-input
    # basis through the `:priority_countries` option. These priority countries will be passed down
    # to the `country_select` helper of your choice, and may or may not be used by the helper.
    #
    # @example Basic example with full form context using `priority_countries` from config
    #
    #   <%= semantic_form_for @user do |f| %>
    #     <%= f.inputs do %>
    #       <%= f.input :nationality, :as => :country %>
    #     <% end %>
    #   <% end %>
    #
    #

    #     Country
    #     <select id="user_nationality" name="user[nationality]">
    #       <option value="...">...</option>
    #       # ...
    #

    #
    # @example `:priority_countries` set on a specific input (country_select 1.x)
    #
    #   <%= semantic_form_for @user do |f| %>
    #     <%= f.inputs do %>
    #       <%= f.input :nationality, :as => :country, :priority_countries => ["Australia", "New Zealand"] %>
    #     <% end %>
    #   <% end %>
    #
    #

    #     Country
    #     <select id="user_nationality" name="user[nationality]">
    #       <option value="...">...</option>
    #       # ...
    #

    #
    # @example `:priority_countries` set on a specific input (country_select 2.x)
    #
    #   <%= semantic_form_for @user do |f| %>
    #     <%= f.inputs do %>
    #       <%= f.input :nationality, :as => :country, :priority_countries => ["AU", "NZ"] %>
    #     <% end %>
    #   <% end %>
    #
    #

    #     Country
    #     <select id="user_nationality" name="user[nationality]">
    #       <option value="...">...</option>
    #       # ...
    #

    #
    # @see Formtastic::Helpers::InputsHelper#input InputsHelper#input for full documentation of all possible options.
    class CountryInput
      include Base

      CountrySelectPluginMissing = Class.new(StandardError)

      def to_html
        raise CountrySelectPluginMissing, "To use the :country input, please install a country_select plugin, like this one: https://github.com/stefanpenner/country_select" unless builder.respond_to?(:country_select)
        input_wrapping do
          label_html <<
          builder.country_select(method, priority_countries, input_options, input_html_options)
        end
      end

      def priority_countries
        options[:priority_countries] || builder.priority_countries
      end

    end
  end
end


text:
<?php

require_once dirname(__DIR__) . '/Exceptions/UniqueSignupException.php';

class SignupsController extends EntityAPIController {

  protected $ignore_global_user = FALSE;

  // @TODO: dosomething_signup.inc didn't have this call to the parent construct
  // and not sure if it's an issue if added.
  public function __construct() {
    parent::__construct('signup');
  }

  /**
   * Overrides buildContent() method.
   *
   * Adds Signup properties into Signup entity's render.
   */
  public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = []) {
    // Load user to get username.
    $account = user_load($entity->uid);
    $build = parent::buildContent($entity, $view_mode, $langcode, $content);
    $build['nid'] = [
      '#type' => 'markup',
      '#markup' => '
Nid: ' . l($entity->nid, 'node/' . $entity->nid . '/signups') . '
',
    ];
    $build['username'] = [
      '#type' => 'markup',
      '#markup' => '
User: ' . l($account->name, 'user/' . $account->uid) . '
',
    ];
    $build['timestamp'] = [
      '#type' => 'markup',
      '#markup' => '
Signed up: ' . format_date($entity->timestamp, 'short') . '
',
    ];
    if ($entity->signup_data_form_timestamp) {
      $build['signup_data_form_submitted'] = [
        '#type' => 'markup',
        '#markup' => '
Signup Data Form Submitted: ' . format_date($entity->signup_data_form_timestamp, 'short') . '
',
      ];
      if ($entity->signup_data_form_response != NULL) {
        $build['signup_data_form_response'] = [
          '#type' => 'markup',
          '#markup' => '
Signup Data Form Response: ' . $entity->signup_data_form_response . '
',
        ];
      }
      $reset_form = drupal_get_form('dosomething_signup_reset_signup_data_form', $entity->sid);
      $build['reset_form'] = $reset_form;
    }
    if ($entity->why_signedup) {
      $build['why_signedup'] = [
        '#type' => 'markup',
        '#markup' => '
Signup Reason: ' . check_plain($entity->why_signedup) . '
',
      ];
    }
    if ($entity->source) {
      $build['source'] = [
        '#type' => 'markup',
        '#markup' => '
Source: ' . check_plain($entity->source) . '
',
      ];
    }
    return $build;
  }

  /**
   * Automagically create a new record.
   *
   * @param  array   $values
   * @return bool|Exception
   *
   * @todo   Eventually change this into just a create() method that overrides
   * the parent EntityAPIController method, and doesn't break dosomething_signup_create()
   * which does not instantiate the SignupController object, so it has no access to
   * the $this->save() method below.
   */
  public function magick_create(array $values = []) {
    $signup = parent::create($values);

    // The $this->save() overriden method depends on the use of the
    // global $user, and then does a check against this user with the user
    // on the newly created Signup entity. If they don't match then the
    // signup fails. The ignore_global_user property is set to true so the
    // afformentioned conditional check on global $user does not happen.
    $this->ignore_global_user = TRUE;

    try {
      $record = $this->save($signup);

      // @TODO: eventually return the actual signup record. S'okay for now.
      return TRUE;
    } catch (UniqueSignupException $error) {
      throw new UniqueSignupException;
    } catch (Exception $error) {
      throw new Exception('There was an error attempting to create the new signup record.');
    }
  }

  /**
   * Overrides save() method.
   *
   * Populates timestamp and uid automatically.
   */
  public function save($entity, DatabaseTransaction $transaction = NULL) {
    global $user;

    if (isset($entity->is_new)) {
      if (!isset($entity->timestamp)) {
        $entity->timestamp = REQUEST_TIME;
      }
      if (!isset($entity->uid)) {
        global $user;
        $entity->uid = $user->uid;
      }
    }

    // Make sure a uid exists.
    if (!isset($entity->uid)) {
      return FALSE;
    }

    // @TODO: We should probably clean this up a bit...
    // @see https://github.com/DoSomething/phoenix/issues/7024
    if (!$this->ignore_global_user) {
      // If the entity uid doesnt belong to current user:
      if ($entity->uid != $user->uid) {
        // And current user can't edit any reportback:
        if (!user_access('edit any signup') && !drupal_is_cli()) {
          watchdog('dosomething_signup', 'Attempted uid override for @entity by User @uid',
            [
              '@entity' => json_encode($entity),
              '@uid' => $user->uid,
            ], WATCHDOG_WARNING);
          return FALSE;
        }
      }
    }

    try {
      $signup_record = parent::save($entity, $transaction);

      if ($signup_record && DOSOMETHING_SIGNUP_LOG_SIGNUPS) {
        watchdog('dosomething_signup', json_encode($entity));
      }

      return $signup_record;
    } catch (Exception $error) {
      if ($error->getCode() === '23000') {
        throw new UniqueSignupException;
      }

      throw $error;
    }
  }

}


text:
/**
 * Created by ila on 5/24/2015.
 */
"use strict"
class DBStore {
    static exportDB() {
        let waitList = [];
        let data = {};
        return localforage.keys().then(function(keys) {
            keys.forEach(function(key) {
                let promiseChild = new Promise(function(resolve, reject) {
                    localforage.getItem(key).then(function(v) {
                        data[key] = v;
                        resolve(data);
                    });
                });
                waitList.push(promiseChild);
            });

            return new Promise(function(resolve, reject) {
                return Promise.all(waitList).then(function() {
                    resolve(data);
                });
            })
        });
    }
    static importDB(data) {
        var waitList = [];
        for(let key in data) {
            let promiseChild = new Promise(function(resolve, reject) {
                localforage.setItem(key, data[key]).then(function() {
                    resolve();
                });
            });
            waitList.push(promiseChild);
        }
        return Promise.all(waitList);
    }
}


text:
/*global require, describe, it */
'use strict';

var Ractive = require( '../../ractive' );
var assert = require( 'assert' );

describe( 'ractive.toCSS()', function() {

	it( 'should render CSS with a single component instance', function() {

		var Component = Ractive.extend( {
			template: '

',
			css: '\n\t\t\t\t.green {\n\t\t\t\t\tcolor: green\n\t\t\t\t}\n\t\t'
		} );

		var app = new Component( {} );

		var cssId = Component.prototype.cssId;
		var css = app.toCSS();

		// Look for the selector
		assert( !!~css.indexOf( '.green[data-ractive-css~="{' + cssId + '}"], [data-ractive-css~="{' + cssId + '}"] .green', '.green selector for ' + cssId + ' should exist' ) );

		app.teardown();
	} );

	it( 'should render CSS with nested component instances', function() {

		var GrandChildComponent = Ractive.extend( {
			template: '

',
			css: '\n\t\t\t\t.green {\n\t\t\t\t\tcolor: green;\n\t\t\t\t}\n\t\t'
		} );

		var ChildComponent = Ractive.extend( {
			template: '\n\t\t\t\t

\n\t\t\t\t<GrandChildComponent />\n\t\t\t',
			css: '\n\t\t\t\t.red {\n\t\t\t\t\tcolor: red;\n\t\t\t\t}\n\t\t',
			components: {
				GrandChildComponent: GrandChildComponent
			}
		} );

		var ParentComponent = Ractive.extend( {
			template: '\n\t\t\t\t

\n\t\t\t\t<ChildComponent />\n\t\t\t',
			css: '\n\t\t\t\t.blue{\n\t\t\t\t\tcolor: blue;\n\t\t\t\t}\n\t\t\t',
			components: {
				ChildComponent: ChildComponent
			}
		} );

		var app = new ParentComponent( {} );

		var css = app.toCSS();
		var grandChildCssId = GrandChildComponent.prototype.cssId;
		var childCssId = ChildComponent.prototype.cssId;
		var parentCssId = ParentComponent.prototype.cssId;

		// Look for the selectors
		assert( !!~css.indexOf( '.green[data-ractive-css~="{' + grandChildCssId + '}"], [data-ractive-css~="{' + grandChildCssId + '}"] .green' ), '.green selector for ' + grandChildCssId + ' should exist' );

		assert( !!~css.indexOf( '.red[data-ractive-css~="{' + childCssId + '}"], [data-ractive-css~="{' + childCssId + '}"] .red' ), '.red selector for ' + childCssId + ' should exist' );

		assert( !!~css.indexOf( '.blue[data-ractive-css~="{' + parentCssId + '}"], [data-ractive-css~="{' + parentCssId + '}"] .blue' ), '.blue selector for ' + parentCssId + ' should exist' );

		app.teardown();
	} );

	it( 'should NEVER render CSS with a Ractive instance', function() {

		var app = new Ractive( {
			template: '

',
			css: '\n\t\t\t\t.green {\n\t\t\t\t\tcolor: green\n\t\t\t\t}\n\t\t\t'
		} );

		var css = app.toCSS();

		assert( !~css.indexOf( '.green[data-ractive-css~="{' + app.cssId + '}"], [data-ractive-css~="{' + app.cssId + '}"] .green', '.green selector for ' + app.cssId + ' should NEVER exist' ) );

		app.teardown();
	} );
} );


text:
<!DOCTYPE HTML>

  <title>Tinto Alapatt | {{ page.title }}</title>
  <link rel="author" href="https://plus.google.com/114410283342848298766">
  <meta property="article:published_time" content="{{ page.date | date_to_xmlschema }}">
  <meta property="article:author" content="https://www.facebook.com/tintoanto">
  <meta property="article:section" content="developer">
  <meta property="og:url" content="{{ site.github.url }}{{ page.url }}">
  <meta property="og:type" content="article">
  <meta property="og:title" content="{{ page.title }}">
  <meta property="og:locale" content="en_US">
  <meta property="og:image" content="{{ site.github.url }}/img/portrait.png">
  <meta property="og:description" content="{{ site.excerpt }}">
  <meta property="og:site_name" content="Tinto Alapatt">
  {% include head.html %}

      {% include sidebar.html %}

{{ page.title }}

<time property="datePublished" datetime="{{ page.date | date_to_xmlschema }}">{{ page.date | date_to_string }}</time>

∞

          {{ content }}

      {% include comments.html %}


text:
var test = require("tape");
var React = require("react");
var TestUtils = require("react-addons-test-utils");
var CheckBox = require("../lib/CheckBox");

var person = { name: "Tom", hasId: true, isActive: "TRUE" };

test("lib/CheckBox - renders", function (assert) {
	var renderer = TestUtils.createRenderer();
	var props = { object: person, field: "hasId", label: "Has ID?" };
	renderer.render(React.createElement(CheckBox, props));

	var Div = renderer.getRenderOutput();
	renderer.render(Div);
	var div = renderer.getRenderOutput();

	assert.equal(div.type, "div", "The main HMTL element is a div");
	assert.equal(div.props.className, "checkbox", "Bootstrap CSS class");

	renderer.render(div.props.children);
	var label = renderer.getRenderOutput();
	assert.equal(label.type, "label", "Label HTML element");
	assert.equal(label.props.children[0].type, "input", "The first child is the input");
	assert.equal(label.props.children[2], props.label, "The third is the label");
	assert.end();
});

test("lib/CheckBox - checked value with mappings", function (assert) {
	var props = { object: person, field: "isActive", label: "Is active?", mappings: { true: "TRUE", false: "FALSE" } };

	var renderer = TestUtils.createRenderer();
	renderer.render(React.createElement(CheckBox, props));
	var Div = renderer.getRenderOutput();
	renderer.render(Div);
	var div = renderer.getRenderOutput();
	renderer.render(div.props.children);
	var inputCheckbox = renderer.getRenderOutput().props.children[0];

	assert.equal(inputCheckbox.props.checked, true, "It must be checked");
	assert.end();
});

test("lib/CheckBox - unchecked value with mappings", function (assert) {
	var props = { object: person, field: "isActive", label: "Is active?", mappings: { true: "FALSE", false: "TRUE" } };

	var renderer = TestUtils.createRenderer();
	renderer.render(React.createElement(CheckBox, props));
	var Div = renderer.getRenderOutput();
	renderer.render(Div);
	var div = renderer.getRenderOutput();
	renderer.render(div.props.children);
	var inputCheckbox = renderer.getRenderOutput().props.children[0];

	assert.equal(inputCheckbox.props.checked, false, "It mustn't be checked");
	assert.end();
});

test("lib/CheckBox - inline", function (assert) {
	var renderer = TestUtils.createRenderer();
	var props = { object: person, field: "hasId", label: "Has ID?", inline: true };
	renderer.render(React.createElement(CheckBox, props));
	var Label = renderer.getRenderOutput();
	renderer.render(Label);
	var label = renderer.getRenderOutput();
	assert.equal(label.type, "label", "The main HTML element is label");
	assert.equal(label.props.className, "checkbox-inline", "The CSS class");
	assert.equal(label.props.children[0].type, "input", "Inside the label is the input");
	assert.end();
});

test("lib/CheckBox - uses ALL provided props", function (assert) {
	var renderer = TestUtils.createRenderer();
	var props = { object: person, field: "hasId", label: "Has ID?", autoFocus: true };
	renderer.render(React.createElement(CheckBox, props));
	var checkbox = renderer.getRenderOutput();

	assert.ok(checkbox.props.autoFocus, "Has the autoFocus set");
	assert.end();
});

test("lib/CheckBox - true / false mappings", function (assert) {
	var renderer = TestUtils.createRenderer();
	var props = { object: person, field: "isActive", label: "Is active?", mappings: { true: "TRUE", false: "FALSE" } };
	assert.plan(1);
	props.onChangeValue = function (newValue) {
		assert.equal(newValue, "FALSE", "Returns the mapping value");
	};
	renderer.render(React.createElement(CheckBox, props));
	var Div = renderer.getRenderOutput();
	renderer.render(Div);
	var div = renderer.getRenderOutput();
	renderer.render(div.props.children);
	var label = renderer.getRenderOutput();

	label.props.children[0].props.onChange({ target: { checked: false }});
});

test("lib/CheckBox - onChangeObject", function (assert) {
	var renderer = TestUtils.createRenderer();
	var props = { object: person, field: "hasId", label: "Has ID?" };
	assert.plan(2);
	props.onChangeObject = function (newPerson) {
		assert.notDeepEqual(person, newPerson, "The given object mustn't be changed");
		assert.notOk(newPerson.hasId, "The new person shouldn't have ID");
	};

	renderer.render(React.createElement(CheckBox, props));
	var Div = renderer.getRenderOutput();
	renderer.render(Div);
	var div = renderer.getRenderOutput();
	renderer.render(div.props.children);
	var label = renderer.getRenderOutput();

	label.props.children[0].props.onChange({ target: { checked: false }});
});

test("lib/CheckBox - onChangeValue", function (assert) {
	var renderer = TestUtils.createRenderer();
	var props = { object: person, field: "hasId", label: "Has ID?" };
	assert.plan(1);
	props.onChangeValue = function (newValue) {
		assert.notOk(newValue, "The new value is false");
	};

	renderer.render(React.createElement(CheckBox, props));
	var Div = renderer.getRenderOutput();
	renderer.render(Div);
	var div = renderer.getRenderOutput();
	renderer.render(div.props.children);
	var label = renderer.getRenderOutput();

	label.props.children[0].props.onChange({ target: { checked: false }});
});