text:
package com.asksunny.batch.graph.transform;

import java.util.List;

import com.asksunny.batch.graph.AbstractWorkflowTask;

public class WorkflowTransformTask extends AbstractWorkflowTask {

	private RecordReader recordReader;
	private RecordTransformer[] transformers;

	public WorkflowTransformTask() {
	}

	@Override
	protected void executeTask() throws Exception {
		for (int i = 0; i < transformers.length; i++) {
			transformers[i].init(getFlowContext());
		}
		while (recordReader.next()) {
			Object transformee = recordReader.getNext();
			for (int i = 0; i < transformers.length; i++) {
				transformee = transformers[i].transform(transformee);
				if (transformee == null) {
					break;
				}
			}
		}
		for (int i = 0; i < transformers.length; i++) {
			transformers[i].shutdown();
		}
	}

	public RecordReader getRecordReader() {
		return recordReader;
	}

	public void setRecordReader(RecordReader recordReader) {
		this.recordReader = recordReader;
	}

	public RecordTransformer[] getTransformers() {
		return transformers;
	}

	public void setTransformers(RecordTransformer[] transformers) {
		this.transformers = transformers;
	}

	public void setTransformers(List<RecordTransformer> transformers) {
		this.transformers = transformers.toArray(new RecordTransformer[transformers.size()]);
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="Encoding">
    <file url="file://$PROJECT_DIR$/../cash-agent" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/base" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/id" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/spring-boot-starter-fastjson" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/spring-boot-starter-http" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/spring-boot-starter-log" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/spring-boot-starter-mybatis" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/spring-boot-starter-shiro" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/structure" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/task" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/util" charset="UTF-8" />
    <file url="file://$PROJECT_DIR$/zip" charset="UTF-8" />
    <file url="PROJECT" charset="UTF-8" />
  </component>
</project>

redpajama_set_name: RedPajamaGithub


text:
USE [ANTERO]
GO

/****** Object:  View [dw].[v_varda_vakajarjestajat_toimipaikat]    Script Date: 1.3.2022 11.06.57 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE or alter VIEW [dw].[v_varda_vakajarjestajat_toimipaikat] AS

        select tp.tilastovuosi,
		case when tp.toimipaikka_oid = '' then null else tp.toimipaikka_oid end as toimipaikka_oid,
		tp.vakajarjestaja_id,
		case when yl.yritys_tyyppi = 'Yksityinen' then NULL
		     else tp.vakajarjestaja_nimi
			 end as organisaatio_fi,
		case when yl.yritys_tyyppi = 'Yksityinen' then NULL
		     else tp.vakajarjestaja_nimi
			 end as organisaatio_en,
				case when yl.yritys_tyyppi = 'Yksityinen' then NULL
		     else tp.vakajarjestaja_nimi
			 end as organisaatio_sv,
	  yl.yritys_tyyppi as yritystyyppi,
	  yl.id as yritystyyppi_id,
	  ym.nimi_fi as yritysmuoto_fi,
	  ym.nimi_en as yritysmuoto_en,
	  ym.nimi_sv as yritysmuoto_sv,
	  alue3.kunta_fi as kotikunta_fi,
	  alue3.kunta_en as kotikunta_en,
	  alue3.kunta_sv as kotikunta_sv,
	  alue3.maakunta_fi as maakunta_fi,
	  alue3.maakunta_en as maakunta_en,
	  alue3.maakunta_sv as maakunta_sv,
	  alue3.kunta_koodi as kotikunta_koodi,

	  alue2.kunta_fi as vakajarjestaja_kunta_fi,
	  alue2.kunta_sv as vakajarjestaja_kunta_sv,
	  alue2.kunta_en as vakajarjestaja_kunta_en,
	  alue2.maakunta_fi as vakajarjestaja_maakunta_fi,
	  alue2.maakunta_en as vakajarjestaja_maakunta_en,
	  alue2.maakunta_sv as vakajarjestaja_maakunta_sv,
	  yl.nimi_fi as yritysluokitus_fi,
	  yl.nimi_en as yritysluokitus_en,
	  yl.nimi_sv as yritysluokitus_sv,
	  yl.yritysmuoto_ryhma_fi,
	  yl.yritysmuoto_ryhma_en,
	  yl.yritysmuoto_ryhma_sv,
	  kj.nimi_fi as kasvatusopillinen_jarjestelma_fi,
	  kj.nimi_en as kasvatusopillinen_jarjestelma_en,
	  kj.nimi_sv as kasvatusopillinen_jarjestelma_sv,
	  tm.nimi_fi as toimintamuoto_fi,
	  tm.nimi_en as toimintamuoto_en,
	  tm.nimi_sv as toimintamuoto_sv,
	  tl.nimi_fi as toimipaikka_luokittelu_fi,
	  tl.nimi_en as toimipaikka_luokittelu_en,
	  tl.nimi_sv as toimipaikka_luokittelu_sv,
	  tp.varhaiskasvatuspaikat,
	  vpl.nimi_fi as varhaiskasvatuspaikat_luokittelu_fi,
	  vpl.nimi_en as varhaiskasvatuspaikat_luokittelu_en,
	  vpl.nimi_sv as varhaiskasvatuspaikat_luokittelu_sv,
	  vpl.jarj_nro  as varhaiskasvatuspaikat_luokittelu_jarj,
	  tm.jarjestys as toimintamuoto_jarj,
	  case when tp.toimipaikka_oid = '' then null else CONCAT(tp.tilastovuosi, '_', tp.toimipaikka_oid) end as tilastovuosi_toimipaikkaoid,
	  c2.lapsia as lapsia,
	  CONCAT(tp.tilastovuosi,tp.toimipaikka_id) as tilastovuosi_toimipaikkaID

	  --faktat
	  FROM ANTERO.dw.f_varda_vakajarjestajat_toimipaikat tp

	  --dimensiot
	  --toimipaikat ja vakajarjestajat
	  left join dw.d_alueluokitus alue2 on alue2.kunta_koodi = d_alueluokitus_vakajarjestaja_kunta_id
	  left join dw.d_alueluokitus alue3 on alue3.id = tp.d_alueluokitus_toimipaikka_kunta_id
	  left join dw.d_varda_kasvatusopillinenjarjestelma kj on kj.id = tp.d_varda_toimipaikka_kasvatusopillinen_jarjestelma_id
	  left join dw.d_varda_toimintamuoto tm on tm.id = tp.d_varda_toimipaikka_toimintamuoto_id
		--LEFT JOIN dw.d_varda_jarjestamismuoto jm ON tp. = jm.id
	  left join dw.d_varda_yritysluokitus yl on yl.id = tp.d_varda_yritysluokitus_id
	  left join dw.d_yritysmuoto ym on ym.id = tp.d_yritysmuoto_id
	  left join dw.d_varda_toimipaikkaluokitus tl on tl.id = tp.d_varda_toimipaikkaluokitus_id
	  left join dw.d_varda_varhaiskasvatuspaikkaluokitus vpl on vpl.id = tp.d_varda_varhaiskasvatuspaikkaluokitus_id

		-- Lasten lkm toiseen tauluun
	  left join
			(select tilastovuosi, vakasuhde_toimipaikka_id, count(distinct henkilo_id) as lapsia
			from dw.f_varda_vakasuhteet_vakapaatokset
			group by tilastovuosi, vakasuhde_toimipaikka_id) c2
			on tp.tilastovuosi=c2.tilastovuosi and tp.toimipaikka_id=c2.vakasuhde_toimipaikka_id

	   where tp.tilastovuosi = 2021


text:
package net.pixomania.StatCrawl.db;

/**
 * This is so that there can only be one single database object all the time
 * @author galaxyAbstractor
 */
public class DbSingleton {
    private static Db db;

    private DbSingleton() {

    }

    /**
     * Returns the Database object
     * @return the database object
     */
    public static Db getDb(){
        if(db == null) db = new Db();
        return db;
    }

    /**
     * Reset the database if we change settings
     */
    public static void nullify(){
        db = null;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        throw new CloneNotSupportedException();
    }
}


text:
set -e

readonly tests_dir="$( cd "$( dirname `readlink -f ${BASH_SOURCE[0]}` )" && pwd )"
readonly scripts_dir=${tests_dir}/../scripts
source ${tests_dir}/test_common.sh

script=${scripts_dir}/files.sh

check_output "files 1" "" bash ${script} ESSENTIAL-COMPONENT
check_output "files 2" "install-manager/
install-manager/InstallManagerV2.jar
install-manager/inst-manager.bin
install-manager/tizen-sdk-installmanager.png
install-manager/tizen-sdk-menu.png" bash ${script} install-manager


text:
<?php

/**
 * @namespace
 */
namespace Zend\GData\Photos\Extension;

/**
 * Represents the gphoto:albumid element used by the API. This
 * class represents the ID of an album and is usually contained
 * within an instance of Zend_Gdata_Photos_AlbumEntry or CommentEntry.
 *
 * @uses       \Zend\GData\Extension
 * @uses       \Zend\GData\Photos
 * @category   Zend
 * @package    Zend_Gdata
 * @subpackage Photos
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class AlbumId extends \Zend\GData\Extension
{

    protected $_rootNamespace = 'gphoto';
    protected $_rootElement = 'albumid';

    /**
     * Constructs a new Zend_Gdata_Photos_Extension_AlbumId object.
     *
     * @param string $text (optional) The value to use for the Album ID.
     */
    public function __construct($text = null)
    {
        $this->registerAllNamespaces(\Zend\GData\Photos::$namespaces);
        parent::__construct();
        $this->setText($text);
    }

}


text:
<!doctype html>

		<title>Zabuun - Learn Arabic for English Speakers</title>
		<meta name="description" content="">
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?>

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?>

			<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?>

						Modern Standard Arabic (MSA) | Egyptian Colloquial Arabic (ECA) | Both

Eating Out

A Good Table

  A: Is this table okay?
 B: No, it's too close to the kitchen door.
  A: How about this table?
 B: No, it's too close to the front door.
 A: This looks like a nice table.
 B: No, it's too close to the salad bar.
  A: Okay, I give up.
 B: Well, there is one good table.
 A: Great. Which one?
 B: That one. A group of eight just sat down at it.

		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?>
		<?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?>


text:
<?php

include_once 'phing/types/DataType.php';
include_once 'phing/Project.php';
include_once 'phing/util/regexp/Regexp.php';

/*
 * A regular expression datatype.  Keeps an instance of the
 * compiled expression for speed purposes.  This compiled
 * expression is lazily evaluated (it is compiled the first
 * time it is needed).  The syntax is the dependent on which
 * regular expression type you are using.
 *
 * @author    Yannick Lecaillez
 * @version   $Revision: 1.6 $ $Date: 2007-12-20 16:44:58 +0100 (jeu 20 déc 2007) $
 * @access    public
 * @see       phing.util.regex.RegexMatcher
 * @package   phing.types
*/
class RegularExpression extends DataType {

    private $regexp   = null;
    private $ignoreCase = false;

    function __construct() {
        $this->regexp  = new Regexp();
    }

    function setPattern($pattern) {
        $this->regexp->setPattern($pattern);
    }

    function setReplace($replace) {
        $this->regexp->setReplace($replace);
    }

    function getPattern($p) {
        if ( $this->isReference() ) {
            $ref = $this->getRef($p);
            return $ref->getPattern($p);
        }
        return $this->regexp->getPattern();
    }

    function getReplace($p) {
        if ( $this->isReference() ) {
            $ref = $this->getRef($p);
            return $ref->getReplace($p);
        }

        return $this->regexp->getReplace();
    }

    function setIgnoreCase($bit) {
        $this->regexp->setIgnoreCase($bit);
    }

    function getIgnoreCase() {
        return $this->regexp->getIgnoreCase();
    }

    function getRegexp(Project $p) {
        if ( $this->isReference() ) {
            $ref = $this->getRef($p);
            return $ref->getRegexp($p);
        }
        return $this->regexp;
    }

    function getRef(Project $p) {
        if ( !$this->checked ) {
            $stk = array();
            array_push($stk, $this);
            $this->dieOnCircularReference($stk, $p);
        }

        $o = $this->ref->getReferencedObject($p);
        if ( !($o instanceof RegularExpression) ) {
            throw new BuildException($this->ref->getRefId()." doesn't denote a RegularExpression");
        } else {
            return $o;
        }
    }
}


text:
#include <cairo.h>
#include <math.h>

/* The application program may override these before including
 * cairo-tutorial.h in order to get a window of a different size. */
#ifndef WIDTH
#define WIDTH 400
#endif

#ifndef HEIGHT
#define HEIGHT 400
#endif

#ifdef CAIRO_TUTORIAL_GTK
#include "cairo-tutorial-gtk.h"
#elif CAIRO_TUTORIAL_XLIB
#include "cairo-tutorial-xlib.h"
#elif CAIRO_TUTORIAL_PDF
#include "cairo-tutorial-pdf.h"
#elif CAIRO_TUTORIAL_PNG
#include "cairo-tutorial-png.h"
#endif


text:
"""Module providing views for a contentpage section"""
from Acquisition import aq_inner
from Acquisition import aq_parent
from Products.Five.browser import BrowserView
from zope.component import getUtility

from giri.sitecontent.interfaces import IResponsiveImagesTool

class PageSectionView(BrowserView):
    """ Page Section default view """

    def __call__(self):
        return self.render()

    def render(self):
        return self.index()

    def parent_page(self):
        return aq_parent(aq_inner(self.context))

    def rendered_page_snippet(self):
        context = aq_inner(self.context)
        snippet = context.restrictedTraverse('@@pagesection-snippet')()
        return snippet

class PageSectionSnippet(BrowserView):
    """ Embeddable section content snippet """

    def field_has_data(self, fieldname):
        """ Check wether a given schema key returns a value"""
        context = aq_inner(self.context)
        try:
            video_link = getattr(context, fieldname, None)
        except AttributeError:
            video_link = None
        if video_link is not None:
            return True
        return False

    def has_video_link(self):
        return self.field_has_data('videoLink')

    def has_external_image(self):
        return self.field_has_data('externalImage')

    def show_image(self):
        display = True
        if self.has_video_link() or self.has_external_image():
            display = False
        return display

    def get_image_data(self, uuid):
        tool = getUtility(IResponsiveImagesTool)
        return tool.create(uuid)


text:
from tempest.api.identity import base
from tempest.common.utils import data_utils
from tempest.test import attr

class PoliciesTestJSON(base.BaseIdentityAdminTest):
    _interface = 'json'

    def _delete_policy(self, policy_id):
        resp, _ = self.policy_client.delete_policy(policy_id)
        self.assertEqual(204, resp.status)

    @attr(type='smoke')
    def test_list_policies(self):
        # Test to list policies
        policy_ids = list()
        fetched_ids = list()
        for _ in range(3):
            blob = data_utils.rand_name('BlobName-')
            policy_type = data_utils.rand_name('PolicyType-')
            resp, policy = self.policy_client.create_policy(blob,
                                                            policy_type)
            # Delete the Policy at the end of this method
            self.addCleanup(self._delete_policy, policy['id'])
            policy_ids.append(policy['id'])
        # List and Verify Policies
        resp, body = self.policy_client.list_policies()
        self.assertEqual(resp['status'], '200')
        for p in body:
            fetched_ids.append(p['id'])
        missing_pols = [p for p in policy_ids if p not in fetched_ids]
        self.assertEqual(0, len(missing_pols))

    @attr(type='smoke')
    def test_create_update_delete_policy(self):
        # Test to update policy
        blob = data_utils.rand_name('BlobName-')
        policy_type = data_utils.rand_name('PolicyType-')
        resp, policy = self.policy_client.create_policy(blob, policy_type)
        self.addCleanup(self._delete_policy, policy['id'])
        self.assertIn('id', policy)
        self.assertIn('type', policy)
        self.assertIn('blob', policy)
        self.assertIsNotNone(policy['id'])
        self.assertEqual(blob, policy['blob'])
        self.assertEqual(policy_type, policy['type'])
        resp, fetched_policy = self.policy_client.get_policy(policy['id'])
        self.assertEqual(resp['status'], '200')
        # Update policy
        update_type = data_utils.rand_name('UpdatedPolicyType-')
        resp, data = self.policy_client.update_policy(
            policy['id'], type=update_type)
        self.assertIn('type', data)
        # Assertion for updated value with fetched value
        resp, fetched_policy = self.policy_client.get_policy(policy['id'])
        self.assertIn('id', fetched_policy)
        self.assertIn('blob', fetched_policy)
        self.assertIn('type', fetched_policy)
        self.assertEqual(fetched_policy['id'], policy['id'])
        self.assertEqual(fetched_policy['blob'], policy['blob'])
        self.assertEqual(update_type, fetched_policy['type'])

class PoliciesTestXML(PoliciesTestJSON):
    _interface = 'xml'


text:
using System;
using System.Linq;
using NUnitReportMerge.Input;
using NUnitReportMerge.Out;

namespace NUnitReportMerge.Model
{
  public class NUnitResultSummary
  {
    NUnitResultSummary()
    {

    }

    public int Total { get; private set; }
    int Errors { get; set; }
    int Failures { get; set; }
    int NotRun { get; set; }
    int Inconclusive { get; set; }
    int Ignored { get; set; }
    int Skipped { get; set; }
    int Invalid { get; set; }
    DateTime DateTime { get; set; }

    public void Add(NUnitResultSummary summary)
    {
      Total += summary.Total;
      Errors += summary.Errors;
      Failures += summary.Failures;
      NotRun += summary.NotRun;
      Inconclusive += summary.Inconclusive;
      Ignored += summary.Ignored;
      Skipped += summary.Skipped;
      Invalid += summary.Invalid;
      DateTime = (new[] {DateTime, summary.DateTime}).Min();
    }

    public static NUnitResultSummary Empty()
    {
      return new NUnitResultSummary()
      {
        DateTime = DateTime.MaxValue
      };
    }

    public static NUnitResultSummary From(ResultSummary nUnitTestResults)
    {
      return new NUnitResultSummary
      {

        Total = nUnitTestResults.Total(),
        Errors = nUnitTestResults.Errors(),
        Failures = nUnitTestResults.Failures(),
        NotRun = nUnitTestResults.NotRun(),
        Inconclusive = nUnitTestResults.Inconclusive(),
        Ignored = nUnitTestResults.Ignored(),
        Skipped = nUnitTestResults.Skipped(),
        Invalid = nUnitTestResults.Invalid(),
        DateTime = nUnitTestResults.DateTimeValue()
      };
    }

    public void AddTo(OutResultsBuilder outResultsBuilder)
    {
      outResultsBuilder.AddSummary(Total, Errors, Failures, NotRun, Inconclusive, Skipped, Invalid, DateTime);
    }
  }
}


text:
var PaginatedCollection = Backbone.Collection.extend({
  action: "",
  controller: "",
  initialize: function(options){
    this.initializePages()
  },
  url: function(){
    return "/" + this.controller + "/" + this.action + ".json?page=" + this.page
  },
  initializePages: function(){
    _.bindAll(this, "nextPage")
    this.page = 1
  },
  nextPage: function(){
    this.page++
    this.fetch()
  }
})


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<title>Python: module gdata.tlslite.constants</title>

<big><big>gdata.tlslite.constants</big></big>	index
/usr/local/google/home/afshar/src/external-gdata-release/google3/src/gdata/tlslite/constants.py

<tt>Constants used in various places.</tt>

<big>Classes</big>

<tt>      </tt>

AlertDescription

AlertLevel

CertificateType

CipherSuite

ContentType

Fault

HandshakeType

class AlertDescription

<tt>   </tt>
<tt>@cvar bad_record_mac: A TLS record failed to decrypt properly.

If this occurs during a shared-key or SRP handshake it most likely

indicates a bad password.  It may also indicate an implementation

error, or some tampering with the data in transit.

This alert will be signalled by the server if the SRP password is bad.  It

may also be signalled by the server if the SRP username is unknown to the

server, but it doesn't wish to reveal that fact.

This alert will be signalled by the client if the shared-key username is

bad.

@cvar handshake_failure: A problem occurred while handshaking.

This typically indicates a lack of common ciphersuites between client and

server, or some other disagreement (about SRP parameters or key sizes,

for example).

@cvar protocol_version: The other party's SSL/TLS version was unacceptable.

This indicates that the client and server couldn't agree on which version

of SSL or TLS to use.

@cvar user_canceled: The handshake is being cancelled for some reason.
 </tt>

Data and other attributes defined here:

access_denied = 49

bad_certificate = 42

bad_record_mac = 20

certificate_expired = 45

certificate_revoked = 44

certificate_unknown = 46

close_notify = 0

decode_error = 50

decompression_failure = 30

decrypt_error = 51

decryption_failed = 21

export_restriction = 60

handshake_failure = 40

illegal_parameter = 47

insufficient_security = 71

internal_error = 80

missing_srp_username = 121

no_certificate = 41

no_renegotiation = 100

protocol_version = 70

record_overflow = 22

unexpected_message = 10

unknown_ca = 48

unknown_srp_username = 120

unsupported_certificate = 43

untrusted_srp_parameters = 122

user_canceled = 90

class AlertLevel

<tt>   </tt>
Data and other attributes defined here:

fatal = 2

warning = 1

class CertificateType

<tt>   </tt>
Data and other attributes defined here:

cryptoID = 2

openpgp = 1

x509 = 0

class CipherSuite

<tt>   </tt>
Static methods defined here:

getRsaSuites(ciphers)

getSrpRsaSuites(ciphers)

getSrpSuites(ciphers)

Data and other attributes defined here:

TLS_RSA_WITH_3DES_EDE_CBC_SHA = 10

TLS_RSA_WITH_AES_128_CBC_SHA = 47

TLS_RSA_WITH_AES_256_CBC_SHA = 53

TLS_RSA_WITH_RC4_128_SHA = 5

TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA = 81

TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA = 84

TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA = 87

TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA = 80

TLS_SRP_SHA_WITH_AES_128_CBC_SHA = 83

TLS_SRP_SHA_WITH_AES_256_CBC_SHA = 86

aes128Suites = [83, 84, 47]

aes256Suites = [86, 87, 53]

rc4Suites = [5]

rsaSuites = [10, 47, 53, 5]

srpRsaSuites = [81, 84, 87]

srpSuites = [80, 83, 86]

tripleDESSuites = [80, 81, 10]

class ContentType

<tt>   </tt>
Data and other attributes defined here:

alert = 21

all = (20, 21, 22, 23)

application_data = 23

change_cipher_spec = 20

handshake = 22

class Fault

<tt>   </tt>
Data and other attributes defined here:

badA = 103

badB = 201

badFinished = 300

badIdentifier = 401

badMAC = 301

badPadding = 302

badPassword = 102

badPremasterPadding = 501

badSharedKey = 402

badUsername = 101

badVerifyMessage = 601

clientCertFaults = [601]

clientNoAuthFaults = [501, 502]

clientSharedKeyFaults = [401, 402]

clientSrpFaults = [101, 102, 103]

faultAlerts = {101: (120, 20), 102: (20,), 103: (47,), 300: (51,), 301: (20,), 302: (20,), 401: (40,), 402: (20,), 501: (20,), 502: (20,), ...}

faultNames = {101: 'bad username', 102: 'bad password', 103: 'bad A', 300: 'bad finished message', 301: 'bad MAC', 302: 'bad padding', 401: 'bad identifier', 402: 'bad sharedkey', 501: 'bad premaster padding', 502: 'short premaster secret', ...}

genericFaults = [300, 301, 302]

serverFaults = [201]

shortPremasterSecret = 502

class HandshakeType

<tt>   </tt>
Data and other attributes defined here:

certificate = 11

certificate_request = 13

certificate_verify = 15

client_hello = 1

client_key_exchange = 16

finished = 20

hello_request = 0

server_hello = 2

server_hello_done = 14

server_key_exchange = 12


text:
import analyzer.markov as markov
import sympy
from sympy.matrices import SparseMatrix

class Chain(markov.Chain):

    def _create_matrix(self):
        return SparseMatrix([0])

    def _grow_matrix(self, matrix):
        new_row = sympy.zeros(1, matrix.cols)
        matrix = matrix.row_insert(matrix.rows, new_row)
        new_col = sympy.zeros(matrix.rows, 1)
        matrix = matrix.col_insert(matrix.cols, new_col)
        return matrix

    def _matrix_size(self, matrix):
        return matrix.cols

    def _zero_diagnoal(self, matrix):
        matrix = matrix.copy()
        for row in range(matrix.rows):
            matrix[row, row] = 0
        return matrix

    def _fill_in_diagonal_transistions(self, trans):
        matrix = self._zero_diagnoal(self.matrix)
        for col in range(matrix.cols):
            matrix[col, col] = 1 - sum(matrix[:,col])
        return matrix

    def _set_transition(self, matrix, row, col, chance):
        matrix[row, col] = chance

    def _is_zero(self, trans):
        return trans.is_zero

    def _inverse(self, matrix):
        return matrix.inv()

    def _eye(self, size):
        return sympy.eye(size)

    def steady_state(self, start_state=None):
        # Initialize the probabilities for transisions to the same state
        matrix = self._fill_in_diagonal_transistions(self.matrix)

        # Subtract the identity matrix
        matrix = matrix - self._eye(matrix.rows)

        # Add a row at the bottom of the matrix for the equation that all
        # variable probabilities must add up to 1
        matrix = matrix.row_insert(matrix.rows, sympy.ones(1, matrix.cols))

        # Add a column for the target values
        matrix = matrix.col_insert(matrix.cols, sympy.zeros(matrix.rows, 1))
        matrix[matrix.rows-1, matrix.cols-1] = 1

        symbols = []
        for col in range(self._matrix_size(self.matrix)):
            symbols.append(sympy.Symbol("col_" + str(col)))
        solution = sympy.solve_linear_system(matrix, *symbols)

        result = {}
        for state in self.states:
            state_index = self.states[state]
            result[state] = solution[symbols[state_index]]

        return result


text: require "inherited_resources_views"


text:
require 'test_helper'

class BaseControllerTest < ActionController::TestCase

  test "base template and partials are rendered for inherited" do
    get :inherited
    assert_match /^inherited base$/i, @response.body
    assert_match /^inherited partial base$/i, @response.body
    assert_match /^overriden partial base$/i, @response.body
  end

  test "base template and partials are rendered for override" do
    get :overriden
    assert_match /^overriden base$/i, @response.body
    assert_match /^inherited partial base$/i, @response.body
    assert_match /^overriden partial base$/i, @response.body
  end

  test "base template and partials are rendered for inherited format js" do
    get :inherited, :format => :js
    assert_match /inherited base js/i, @response.body
    assert_match /inherited partial base/i, @response.body
    assert_match /overriden partial base/i, @response.body
  end

  test "base template and partials are rendered for override format js" do
    get :overriden, :format => :js
    assert_match /overriden base js/i, @response.body
    assert_match /inherited partial base/i, @response.body
    assert_match /overriden partial base/i, @response.body
  end

end


text:
namespace Test.Service.HelloWorld
{
    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello()
        {
            return "SayHello";
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<datasources xmlns="http://www.jboss.org/ironjacamar/schema"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.jboss.org/ironjacamar/schema http://docs.jboss.org/ironjacamar/schema/datasources_1_0.xsd">
    <datasource jndi-name="java:jboss/datasources/jdd-ds" pool-name="jdd-ds" enabled="true" use-java-context="true">
        <connection-url>jdbc:h2:mem:jdddb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
        <driver>h2</driver>
        <security>
            <user-name>sa</user-name>
            <password>sa</password>
        </security>
    </datasource>
</datasources>


text:
#ifndef FWMATH_H
#define FWMATH_H

//
// Support functions for mathematical operations
//

#include <math.h>
#include "INETDefs.h"

/* windows math.h doesn't define the PI variable so we have to do it by hand*/
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif

/* windows math.h doesn't define sqrt(2) so we have to do it by hand. */
#ifndef M_SQRT2
#define M_SQRT2 1.41421356237309504880
#endif

/* Constant for comparing doubles. Two doubles at most epsilon apart
   are declared equal.*/
#ifndef EPSILON
#define EPSILON 0.001
#endif

/**
 * @brief Support functions for mathematical operations.
 *
 * This class contains all kind of mathematical support functions
 *
 * @ingroup basicUtils
 * @ingroup utils
 * @author Christian Frank
 */
class INET_API FWMath {

 public:

  /**
   * Returns the rest of a whole-numbered division.
   */
  static double mod(double dividend, double divisor) {
      double i;
      return modf(dividend/divisor, &i)*divisor;
  }

  /**
   * Returns the result of a whole-numbered division.
   */
  static double div(double dividend, double divisor) {
      double i;
      modf(dividend/divisor, &i);
      return i;
  }

  /**
   * Returns the remainder r on division of dividend a by divisor n,
   * using floored division. The remainder r has the same sign as the divisor n.
   */
  static double modulo(double a, double n) { return (a - n * floor(a/n)); }

  /**
   * Tests whether two doubles are close enough to be declared equal.
   * Returns true if parameters are at most epsilon apart, false
   * otherwise
   */
  static bool close(double one, double two) { return fabs(one-two)<EPSILON; }

  /**
   * Returns 0 if i is close to 0, 1 if i is positive and greater than epsilon,
   * or -1 if it is negative and less than epsilon.
   */
  static int stepfunction(double i) { return (i>EPSILON) ? 1 : close(i, 0) ? 0 :-1; };

  /**
   * Returns 1 if the parameter is greater or equal to zero, -1 otherwise
   */
  static int sign(double i) { return (i>=0)? 1 : -1; };

  /**
   * Returns an integer that corresponds to rounded double parameter
   */
  static int round(double d) { return (int)(ceil(d-0.5)); }

  /**
   * Discards the fractional part of the parameter, e.g. -3.8 becomes -3
   */
  static double floorToZero(double d) { return (d >= 0.0)? floor(d) : ceil(d); }

  /**
   * Returns the greater of the given parameters
   */
  static double max(double a, double b) { return (a<b)? b : a; }

  /**
   * Converts a dBm value into milliwatts
   */
  static double dBm2mW(double dBm) { return pow(10.0, dBm/10.0); }

  /**
   * Convert a mW value to dBm.
   */
  static double mW2dBm(double mW) { return (10 * log10(mW)); }
};

#endif


text:
LEARNINGS
=========

This document includes all the techinichal/non-technical things I discover and learn while building this framework.


text:
import javascript from 'src/js/parser/javascript/parser.js';
import Snap from 'snapsvg';
import _ from 'lodash';

describe('parser/javascript/root.js', function() {

  _.forIn({
    'test': {
      flags: [],
      regexp: jasmine.objectContaining({ textValue: 'test' })
    },
    '/test/': {
      flags: [],
      regexp: jasmine.objectContaining({ textValue: 'test' })
    },
    '/test/i': {
      flags: ['Ignore Case'],
      regexp: jasmine.objectContaining({ textValue: 'test' })
    },
    '/test/g': {
      flags: ['Global'],
      regexp: jasmine.objectContaining({ textValue: 'test' })
    },
    '/test/m': {
      flags: ['Multiline'],
      regexp: jasmine.objectContaining({ textValue: 'test' })
    },
    '/test/mgi': {
      flags: ['Global', 'Ignore Case', 'Multiline'],
      regexp: jasmine.objectContaining({ textValue: 'test' })
    }
  }, (content, str) => {
    it(`parses "${str}" as a Root`, function() {
      var parser = new javascript.Parser(str);
      expect(parser.__consume__root()).toEqual(jasmine.objectContaining(content));
    });
  });

  describe('#_render', function() {

    beforeEach(function() {
      this.textElement = jasmine.createSpyObj('text', ['getBBox']);
      this.textElement.getBBox.and.returnValue({
        height: 20
      });

      this.node = new javascript.Parser('test').__consume__root();
      this.node.container = jasmine.createSpyObj('container', [
        'addClass',
        'text',
        'group',
        'path',
        'circle'
      ]);
      this.node.container.text.and.returnValue(this.textElement);
      this.node.container.group.and.returnValue('group element');

      this.node.regexp = jasmine.createSpyObj('regexp', [
        'render',
        'transform',
        'getBBox'
      ]);

      this.renderDeferred = this.testablePromise();
      this.node.regexp.render.and.returnValue(this.renderDeferred.promise);
    });

    it('renders the regexp', function() {
      this.node._render();
      expect(this.node.regexp.render).toHaveBeenCalledWith('group element');
    });

    describe('when there are flags', function() {

      beforeEach(function() {
        this.node.flags = ['example', 'flags'];
      });

      it('renders a text element', function() {
        this.node._render();
        expect(this.node.container.text).toHaveBeenCalledWith(0, 0, 'Flags: example, flags');
      });

    });

    describe('when there are no flags', function() {

      beforeEach(function() {
        this.node.flags = [];
      });

      it('does not render a text element', function() {
        this.node._render();
        expect(this.node.container.text).not.toHaveBeenCalled();
      });

    });

    describe('positioning of elements', function() {

      beforeEach(function() {
        this.renderDeferred.resolve();

        this.node.regexp.getBBox.and.returnValue({
          ax: 1,
          ay: 2,
          ax2: 3,
          x2: 4
        });
      });

      it('renders a path element to lead in and out of the regexp', function(done) {
        this.node._render()
          .then(() => {
            expect(this.node.container.path).toHaveBeenCalledWith('M1,2H0M3,2H14');
            done();
          });
      });

      it('renders circle elements before and after the regexp', function(done) {
        this.node._render()
          .then(() => {
            expect(this.node.container.circle).toHaveBeenCalledWith(0, 2, 5);
            expect(this.node.container.circle).toHaveBeenCalledWith(14, 2, 5);
            done();
          });
      });

      describe('when there are flags', function() {

        beforeEach(function() {
          this.node.flags = ['example'];
        });

        it('moves the regexp below the flag text', function(done) {
          this.node._render()
            .then(() => {
              expect(this.node.regexp.transform).toHaveBeenCalledWith(Snap.matrix()
                .translate(10, 20));
              done();
            });
        });

      });

      describe('when there are no flags', function() {

        beforeEach(function() {
          this.node.flags = [];
        });

        it('positions the regexp', function(done) {
          this.node._render()
            .then(() => {
              expect(this.node.regexp.transform).toHaveBeenCalledWith(Snap.matrix()
                .translate(10, 0));
              done();
            });
        });

      });

    });

  });

});


text:
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased][unreleased]
### Changed
- Nothing yet.

## [0.0.11] - 2015-07-19
### Fixed
- Localisation of animation properties.

## [0.0.10] - 2015-06-17
### Added
- Localised at-rules.

## [0.0.9] - 2015-06-12
### Changed
- Using global selectors outside of a global context no longer triggers warnings. Instead, this functionality will be provided by a CSS Modules linter.

### Fixed
- Keyframe rules.

## [0.0.8] - 2015-06-11
### Added
- Pure mode where only local scope is allowed.

### Changed
- Using global selectors outside of a global context now triggers warnings.

## [0.0.7] - 2015-05-30
### Changed
- Migrated to `css-selector-tokenizer`.

## [0.0.6] - 2015-05-28
### Changed
- Renamed project to `postcss-modules-local-by-default`.

## [0.0.5] - 2015-05-22
### Added
- Support for css-loader [inheritance](https://github.com/webpack/css-loader#inheriting) and [local imports](https://github.com/webpack/css-loader#importing-local-class-names).

## [0.0.4] - 2015-05-22
### Changed
- Hide global leak detection behind undocumented `lint` option until it's more robust.

## [0.0.3] - 2015-05-22
### Changed
- Transformer output now uses the new `:local(.identifier)` syntax.

### Added
- Simple global leak detection. Non-local selectors like `input{}` and `[data-foobar]` now throw when not marked as global.

## [0.0.2] - 2015-05-14
### Added
- Support for global selectors appended directly to locals, e.g. `.foo:global(.bar)`

## 0.0.1 - 2015-05-12
### Added
- Automatic local classes
- Explicit global selectors with `:global`

[unreleased]: https://github.com/postcss-modules-local-by-default/compare/v0.0.10...HEAD
[0.0.2]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.1...v0.0.2
[0.0.3]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.2...v0.0.3
[0.0.4]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.3...v0.0.4
[0.0.5]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.4...v0.0.5
[0.0.6]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.5...v0.0.6
[0.0.7]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.6...v0.0.7
[0.0.8]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.7...v0.0.8
[0.0.9]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.8...v0.0.9
[0.0.10]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.9...v0.0.10
[0.0.11]:      https://github.com/postcss-modules-local-by-default/compare/v0.0.10...v0.0.11


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.

==========
 Glossary
==========

.. glossary::
   :sorted:

   API server
     HTTP REST API service for heat.

   CFN
     An abbreviated form of "AWS CloudFormation".

   Constraint
     Defines valid input :term:`parameters` for a :term:`template`.

   Dependency
     When a :term:`resource` must wait for another resource to finish
     creation before being created itself. Heat adds an implicit
     dependency when a resource references another resource or one of
     its :term:`attributes <resource attribute>`. An explicit
     dependency can also be created by the user in the template
     definition.

   Environment
     Used to affect the run-time behavior of the template. Provides a
     way to override the default resource implementation and
     parameters passed to Heat. See :ref:`Environments`.

   Heat Orchestration Template
     A particular :term:`template` format that is native to Heat.
     Heat Orchestration Templates are expressed in YAML and are not
     backwards-compatible with CloudFormation templates.

   HOT
     An acronym for ":term:`Heat Orchestration Template`".

   Input parameters
     See :term:`Parameters`.

   Metadata
     May refer to :term:`Resource Metadata`, :term:`Nova Instance
     metadata`, or the :term:`Metadata service`.

   Metadata service
     A Compute service that enables virtual machine instances to
     retrieve instance-specific data. See `Metadata
     service (OpenStack Cloud Admin Guide)`_.

     .. _Metadata service (OpenStack Cloud Admin Guide): http://docs.openstack.org/admin-guide-cloud/content/section_metadata-service.html

   Multi-region
     A feature of Heat that supports deployment to multiple regions.

   Nested resource
     A :term:`resource` instantiated as part of a :term:`nested
     stack`.

   Nested stack
     A :term:`template` referenced by URL inside of another template.
     Used to reduce redundant resource definitions and group complex
     architectures into logical groups.

   Nova Instance metadata
     User-provided *key:value* pairs associated with a Compute
     Instance. See `Instance specific data (OpenStack Compute Admin
     Guide)`_.

     .. _Instance specific data (OpenStack Compute Admin Guide): http://docs.openstack.org/grizzly/openstack-compute/admin/content/instance-data.html#inserting_metadata

   OpenStack
     Open source software for building private and public clouds.

   Orchestrate
     Arrange or direct the elements of a situation to produce a
     desired effect.

   Outputs
     A top-level block in a :term:`template` that defines what data
     will be returned by a stack after instantiation.

   Parameters
     A top-level block in a :term:`template` that defines what data
     can be passed to customise a template when it is used to create
     or update a :term:`stack`.

   Provider resource
     A :term:`resource` implemented by a :term:`provider
     template`. The parent resource's properties become the
     :term:`nested stack's <nested stack>` parameters. See `What are
     "Providers"? (Openstack Wiki)`_.

     .. _`What are "Providers"? (Openstack Wiki)`: https://wiki.openstack.org/wiki/Heat/Providers#What_are_.22Providers.22.3F

   Provider template
     Allows user-definable :term:`resource providers <resource
     provider>` to be specified via :term:`nested stacks <nested
     stack>`. The nested stack's :term:`outputs` become the parent
     stack's :term:`attributes <resource attribute>`.

   Resource
     An element of OpenStack infrastructure instantiated from a
     particular :term:`resource provider`. See also :term:`Nested
     resource`.

   Resource attribute
     Data that can be obtained from a :term:`resource`, e.g. a
     server's public IP or name. Usually passed to another resource's
     :term:`properties <resource property>` or added to the stack's
     :term:`outputs`.

   Resource group
     A :term:`resource provider` that creates one or more identically
     configured :term:`resources <resource>` or :term:`nested
     resources <nested resource>`.

   Resource Metadata
     A :term:`resource property` that contains CFN-style template
     metadata. See `AWS::CloudFormation::Init (AWS CloudFormation User Guide)`_

     .. _AWS::CloudFormation::Init (AWS CloudFormation User Guide): http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-init.html

   Resource plugin
     Python code that understands how to instantiate and manage a
     :term:`resource`. See `Heat Resource Plugins (OpenStack wiki)`_.

     .. _Heat Resource Plugins (OpenStack wiki): https://wiki.openstack.org/wiki/Heat/Plugins#Heat_Resource_Plugins

   Resource property
     Data utilized for the instantiation of a :term:`resource`. Can be
     defined statically in a :term:`template` or passed in as
     :term:`input parameters <parameters>`.

   Resource provider
     The implementation of a particular resource type. May be a
     :term:`Resource plugin` or a :term:`Provider template`.

   Stack
     A collection of instantiated :term:`resources <resource>` that
     are defined in a single :term:`template`.

   Stack resource
     A :term:`resource provider` that allows the management of a
     :term:`nested stack` as a :term:`resource` in a parent stack.

   Template
     An orchestration document that details everything needed to carry
     out an :term:`orchestration <orchestrate>`.

   Template resource
     See :term:`Provider resource`.

   User data
     A :term:`resource property` that contains a user-provided data
     blob. User data gets passed to `cloud-init`_ to automatically
     configure instances at boot time. See also `User data (OpenStack
     End User Guide)`_.

     .. _User data (OpenStack End User Guide): http://docs.openstack.org/user-guide/content/user-data.html#d6e2415
     .. _cloud-init: https://help.ubuntu.com/community/CloudInit

   Wait condition
     A :term:`resource provider` that provides a way to communicate
     data or events from servers back to the orchestration
     engine. Most commonly used to pause the creation of the
     :term:`stack` while the server is being configured.


text:
@interface TSAssetsLoader : TSBaseLoader
@property (nonatomic, readonly) NSArray *fetchedAssets;

- (void)fetchAssetsFromAlbum:(NSString *)album block:(void (^)(NSArray *loadedAssets, NSError *error))block;

@end


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>Class IonAuth\IonAuth\Entities\LoginAttempt</title>

	<link rel="stylesheet" href="resources/style.css?e99947befd7bf673c6b43ff75e9e0f170c88a60e">

		Overview

Namespaces

						IonAuth

						IonAuth

						Commands

						Checks

						Config

						Parser

						Db

						Entities

						Helper

						Lang

						Utilities

						Collection

						spec

						IonAuth

						IonAuth

						Auth

						Commands

						Config

						Parser

						Db

						Db

						Entities

						Lang

						Utilities

						Collection

Classes

Group

LoginAttempt

Password

User

	<form id="search">
		<input type="hidden" name="cx" value="">
		<input type="hidden" name="ie" value="UTF-8">
		<input type="text" name="q" class="text" placeholder="Search">
	</form>

				Overview

				Namespace

Class

Class LoginAttempt

Created by PhpStorm.
User: kayladnls
Date: 1/19/15
Time: 12:07 AM

IonAuth\IonAuth\Entities\LoginAttempt
			 implements
				IonAuth\IonAuth\Utilities\Collection\CollectionItem

		Namespace: IonAuth\IonAuth\Entities

			Located at src/Entities/LoginAttempt.php

Methods summary

			 public

			mixed

		#
		getId( )

Returns

					mixed

Implementation of

IonAuth\IonAuth\Utilities\Collection\CollectionItem::getId()

			 public

		#
		increaseLoginAttempts( string <var>$identity</var> )

Function: increaseLoginAttempts()

increase_login_attempts
Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)

Function: increaseLoginAttempts()

increase_login_attempts
Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)

Parameters

<var>$identity</var>

			 public

		#
		clearLoginAttempts( string <var>$identity</var>,  <var>$expire_period</var> = 86400 )

clear_login_attempts

Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)

clear_login_attempts

Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)

Parameters

<var>$identity</var>

<var>$expire_period</var>

			 public

			integer

		#
		getNumberOfAttempts( IonAuth\IonAuth\Entities\User <var>$user</var> )

Function: getNumberOfAttempts()

Get number of attempts to login occured from given IP-address or identity
Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)

Function: getNumberOfAttempts()

Get number of attempts to login occured from given IP-address or identity
Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)

Parameters

<var>$user</var>

$identity

Returns

					integer

			 public

			integer

		#
		getLastAttemptTime( IonAuth\IonAuth\Entities\User <var>$user</var> )

Parameters

<var>$user</var>

Returns

					integer

			 public

			boolean

		#
		isMaxLoginAttemptsExceeded( string <var>$identity</var>,… )

is_max_login_attempts_exceeded
Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)

is_max_login_attempts_exceeded
Based on code from Tank Auth, by Ilya Konyukhov (https://github.com/ilkon/Tank-Auth)

Parameters

<var>$identity</var>,…

Returns

					boolean

			 public

		#
		getIpAddress( )

		 API documentation generated by ApiGen


text:
package br.com.daniel.jdbc.teste.dao;

import java.sql.ResultSet;

import org.junit.Assert;
import org.junit.Test;

import br.com.daniel.jdbc.conexao.Conexao;
import br.com.daniel.jdbc.dao.Dao;
import br.com.daniel.jdbc.exception.ExceptionDatabase;

public class DaoTest {

	@Test
	public void deveraRealizarUmSelect() throws ExceptionDatabase, Exception{
		Dao dao = new Dao();
		ResultSet result = dao.sid()
				.dql(new Conexao("propriedades.properties").conectarMysql())
				.select("SELECT idade, nome FROM teste.teste")
				.execute();

		String nome = null;
		Integer idade = null;

		while (result.next()) {
			nome = result.getString("nome");
			idade = result.getInt("idade");
			break;
		}

		Assert.assertEquals("Daniel", nome);
		Assert.assertEquals(Integer.valueOf(27), idade);
	}

	@Test
	public void deveraRealizarUmSelectComParametros() throws ExceptionDatabase, Exception{
		Dao dao = new Dao();
		ResultSet result = dao.sid()
				.dql(new Conexao("propriedades.properties").conectarMysql())
				.select("SELECT idade, nome FROM teste.teste WHERE idade = ? AND nome = ?", 27, "Daniel")
				.execute();

		String nome = null;
		Integer idade = null;

		while (result.next()) {
			nome = result.getString("nome");
			idade = result.getInt("idade");
			break;
		}

		Assert.assertEquals("Daniel", nome);
		Assert.assertEquals(Integer.valueOf(27), idade);
	}

	@Test
	public void deveraRealizarUmInsertNaBaseDeDados() throws ExceptionDatabase, Exception{
 		Dao dao = new Dao();

 		Boolean result = dao.sid().dml(new Conexao("propriedades.properties").conectarMysql())
 				.insert("INSERT INTO `teste`.`teste` (`nome`, `idade`) VALUES (?, ?);", "Teste", 10)
 				.execute();

 		Assert.assertEquals(true, result);

 		ResultSet resultado = dao.sid().dql(new Conexao("propriedades.properties").conectarMysql())
 				.select("SELECT nome, idade FROM teste.teste WHERE nome = ? AND idade = ?", "Teste", 10)
 				.execute();

 		String nome = null;
 		Integer idade = null;

 		while (resultado.next()) {
 			nome = resultado.getString("nome");
 			idade = resultado.getInt("idade");
 		}

 		Assert.assertEquals("Teste", nome);
 		Assert.assertEquals(Integer.valueOf(10), idade);
	}

	@Test
	public void deveraAtualizarUmRegistroNaBaseDeDados() throws ExceptionDatabase, Exception{
		Dao dao = new Dao();
		Integer id = null;
		String nomeSemUpdate = null;
		Integer idadeSemUpdate = null;

		String nomeAtualizado = null;
		Integer idadeAtualizada = null;

		// Busca usuário a ser alterado na Base de dados

		ResultSet result1 = dao.sid().dql(new Conexao("propriedades.properties").conectarMysql())
				.select("SELECT * FROM teste.teste WHERE nome = ? AND idade = ?", "Teste", 10)
				.execute();

		while (result1.next()) {
			nomeSemUpdate = result1.getString("nome");
			idadeSemUpdate = result1.getInt("idade");
			id = result1.getInt("id");
		}

		Assert.assertEquals("Teste", nomeSemUpdate);
		Assert.assertEquals(Integer.valueOf(10), idadeSemUpdate);
		result1.close();

		// Atualiza dados

		Boolean response = dao.sid().dml(new Conexao("propriedades.properties").conectarMysql())
				.update("UPDATE `teste`.`teste` SET `nome`= ?, `idade`= ? WHERE `id`= ? ","Teste2", 22, id)
				.execute();

		Assert.assertEquals(true, response);

		// Verifica se os dados estão atualizados

		result1 = dao.sid().dql(new Conexao("propriedades.properties").conectarMysql())
				.select("SELECT * FROM teste.teste WHERE nome = ? AND idade = ?", "Teste2", 22)
				.execute();

		while (result1.next()) {
			nomeAtualizado = result1.getString("nome");
			idadeAtualizada = result1.getInt("idade");
		}

		Assert.assertNotEquals(nomeSemUpdate, nomeAtualizado);
		Assert.assertNotEquals(idadeSemUpdate, idadeAtualizada);

		Assert.assertEquals("Teste2", nomeAtualizado);
		Assert.assertEquals(Integer.valueOf(22), idadeAtualizada);

	}

	@Test
	public void deveraExcluirUmRegistro() throws ExceptionDatabase, Exception {
		Dao dao = new Dao();
		int quantidadeDeRegistros = 0;

		// Busca um registro para ver se ele existe, caso ele exista o retorno será 1 caso contrário 0

		ResultSet result = dao.sid().dql(new Conexao("propriedades.properties").conectarMysql())
				.select("SELECT count(id) AS quant FROM teste.teste WHERE nome = ? AND idade = ?", "Teste2", 22)
				.execute();

		while (result.next()) {
			quantidadeDeRegistros = result.getInt("quant");
		}

		result.close();
		Assert.assertEquals(1, quantidadeDeRegistros);

		// Exclui o registro

		Boolean response = dao.sid().dml(new Conexao("propriedades.properties").conectarMysql())
				.delete("DELETE FROM `teste`.`teste` WHERE nome = ? AND idade = ?", "Teste2", 22)
				.execute();

		Assert.assertEquals(true, response);

		/* Verifica se o dado realmente foi excluido, se for excluido retorna 0 caso contrário
		* retorna 1
		*/

		result = dao.sid().dql(new Conexao("propriedades.properties").conectarMysql())
				.select("SELECT count(id) AS quant FROM teste.teste WHERE nome = ? AND idade = ?", "Teste2", 22)
				.execute();

		while (result.next()) {
			quantidadeDeRegistros = result.getInt("quant");
		}

		result.close();
		Assert.assertEquals(0, quantidadeDeRegistros);

	}
}


text:
import React, { Component } from 'react'
import Router from 'next/router'

let count = 0

export default class SelfReload extends Component {
  static getInitialProps({ res }) {
    if (res) return { count: 0 }
    count += 1

    return { count }
  }

  handleAClick = () => {
    Router.push(
      '/nav/hash-changes-with-state',
      '/nav/hash-changes-with-state#',
      {
        historyCount: (window.history.state.options.historyCount || 0) + 1,
        shallowHistoryCount: window.history.state.options.shallowHistoryCount,
      }
    )
  }

  handleAShallowClick = () => {
    Router.push(
      '/nav/hash-changes-with-state#',
      '/nav/hash-changes-with-state#',
      {
        shallow: true,
        historyCount: window.history.state.options.historyCount,
        shallowHistoryCount:
          (window.history.state.options.shallowHistoryCount || 0) + 1,
      }
    )
  }

  render() {
    return (

COUNT: {this.props.count}

          Increment history count

          HISTORY COUNT:{' '}
          {typeof window !== 'undefined' &&
            window.history.state.options.historyCount}

          Increment shallow history count

          SHALLOW HISTORY COUNT:{' '}
          {typeof window !== 'undefined' &&
            window.history.state.options.shallowHistoryCount}

    )
  }
}


text:
"""LVAPP RAN Manager."""

import empower.managers.ranmanager.lvapp as lvapp

from empower.managers.ranmanager.ranmanager import RANManager
from empower.managers.ranmanager.lvapp.wtphandler import WTPHandler
from empower.managers.ranmanager.lvapp.lvaphandler import LVAPHandler
from empower.managers.ranmanager.lvapp.lvappconnection import LVAPPConnection
from empower.managers.ranmanager.lvapp.wtp import WTP

DEFAULT_PORT = 4433

class LVAPPManager(RANManager):
    """LVAPP RAN Manager

    Parameters:
        port: the port on which the TCP server should listen (optional,
            default: 4433)
    """

    HANDLERS = [LVAPHandler, WTPHandler]

    def __init__(self, context, service_id, port):

        super().__init__(context=context,
                         service_id=service_id,
                         device_type=WTP,
                         connection_type=LVAPPConnection,
                         proto=lvapp,
                         port=port)

        self.lvaps = {}
        self.vaps = {}

def launch(context, service_id, port=DEFAULT_PORT):
    """ Initialize the module. """

    return LVAPPManager(context=context, service_id=service_id, port=port)


text:
#ifndef BABYLON_ENGINES_INSTANCING_ATTRIBUTE_INFO_H
#define BABYLON_ENGINES_INSTANCING_ATTRIBUTE_INFO_H

#include <babylon/babylon_api.h>
#include <babylon/interfaces/igl_rendering_context.h>

namespace BABYLON {

/**
 * @brief Interface for attribute information associated with buffer instanciation.
 */
struct BABYLON_SHARED_EXPORT InstancingAttributeInfo {
  /**
   * Name of the GLSL attribute
   * if attribute index is not specified, this is used to retrieve the index from the effect
   */
  std::string attributeName;

  /**
   * Index/offset of the attribute in the vertex shader
   * if not specified, this will be computes from the name.
   */
  std::optional<unsigned int> index = std::nullopt;

  /**
   * size of the attribute, 1, 2, 3 or 4
   */
  int attributeSize = 0;

  /**
   * Offset of the data in the Vertex Buffer acting as the instancing buffer
   */
  int offset = 0;

  /**
   * Modifies the rate at which generic vertex attributes advance when rendering multiple instances
   * default to 1
   */
  std::optional<unsigned int> divisor = std::nullopt;

  /**
   * type of the attribute, gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.FIXED,
   * gl.FLOAT. default is FLOAT
   */
  std::optional<unsigned int> attributeType = std::nullopt;

  /**
   * normalization of fixed-point data. behavior unclear, use FALSE, default is FALSE
   */
  std::optional<bool> normalized = std::nullopt;

}; // end of struct InstancingAttributeInfo

} // end of namespace BABYLON

#endif // end of BABYLON_ENGINES_INSTANCING_ATTRIBUTE_INFO_H


text:
import { Button } from '@blueprintjs/core';
import { IconNames } from '@blueprintjs/icons';
import React, { useState } from 'react';

import { useInterval } from '../../../hooks';

import './query-timer.scss';

// This is roughly the time in ms that it takes the component to mount and unmount, without this the timer appears to over count a little bit
const FUDGE_OFFSET = 150;

export const QueryTimer = React.memo(function QueryTimer() {
  const [startTime] = useState(Date.now() + FUDGE_OFFSET);
  const [currentTime, setCurrentTime] = useState(Date.now());

  useInterval(() => {
    setCurrentTime(Date.now());
  }, 25);

  const elapsed = currentTime - startTime;
  if (elapsed <= 0) return null;
  return (
    <div className="query-timer">
      {`${(elapsed / 1000).toFixed(2)}s`}
      <Button icon={IconNames.STOPWATCH} minimal />
    </div>
  );
});


text:
package com.afwsamples.testdpc.provision;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;
import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES;
import static android.app.admin.DevicePolicyManager.EXTRA_PROVISIONING_MODE;
import static android.app.admin.DevicePolicyManager.PROVISIONING_MODE_FULLY_MANAGED_DEVICE;
import static android.app.admin.DevicePolicyManager.PROVISIONING_MODE_MANAGED_PROFILE;
import static android.app.admin.DevicePolicyManager.PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE;
import static com.google.common.truth.Truth.assertThat;
import static org.robolectric.Shadows.shadowOf;

import android.content.Intent;
import android.os.Build.VERSION_CODES;
import android.view.View;
import androidx.test.core.app.ActivityScenario;
import com.afwsamples.testdpc.R;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

@RunWith(RobolectricTestRunner.class)
@Config(minSdk = VERSION_CODES.S)
public class GetProvisioningModeActivityTest {

  @Test
  public void onPoButtonClick_shouldFinishWithCorrectIntent() {
    ActivityScenario.launch(GetProvisioningModeActivity.class)
        .onActivity(
            activity -> {
              activity.findViewById(R.id.po_selection_button).performClick();

              assertThat(shadowOf(activity).getResultCode()).isEqualTo(RESULT_OK);
              assertThat(
                      shadowOf(activity).getResultIntent().getIntExtra(EXTRA_PROVISIONING_MODE, -1))
                  .isEqualTo(PROVISIONING_MODE_MANAGED_PROFILE);
            });
  }

  @Test
  public void onDoButtonClick_shouldFinishWithCorrectIntent() {
    ActivityScenario.launch(GetProvisioningModeActivity.class)
        .onActivity(
            activity -> {
              activity.findViewById(R.id.do_selection_button).performClick();

              assertThat(shadowOf(activity).getResultCode()).isEqualTo(RESULT_OK);
              assertThat(
                      shadowOf(activity).getResultIntent().getIntExtra(EXTRA_PROVISIONING_MODE, -1))
                  .isEqualTo(PROVISIONING_MODE_FULLY_MANAGED_DEVICE);
            });
  }

  @Test
  public void onBackPressed_shouldSetResultToCancelled() {
    ActivityScenario.launch(GetProvisioningModeActivity.class)
        .onActivity(
            activity -> {
              activity.onBackPressed();

              assertThat(shadowOf(activity).getResultCode()).isEqualTo(RESULT_CANCELED);
            });
  }

  @Test
  public void onCreate_withDoAllowedProvisioningMode_showsOnlyDoOption() {
    GetProvisioningModeActivity activity =
        launchActivityWithAllowedProvisioningModes(PROVISIONING_MODE_FULLY_MANAGED_DEVICE);

    assertThat(activity.findViewById(R.id.do_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.po_option).getVisibility()).isEqualTo(View.GONE);
    assertThat(activity.findViewById(R.id.divider).getVisibility()).isEqualTo(View.GONE);
  }

  @Test
  public void onCreate_withPoAllowedProvisioningMode_showsOnlyPoOption() {
    GetProvisioningModeActivity activity =
        launchActivityWithAllowedProvisioningModes(PROVISIONING_MODE_MANAGED_PROFILE);

    assertThat(activity.findViewById(R.id.do_option).getVisibility()).isEqualTo(View.GONE);
    assertThat(activity.findViewById(R.id.po_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.divider).getVisibility()).isEqualTo(View.GONE);
  }

  @Test
  public void onCreate_withByodAllowedProvisioningMode_showsOnlyPoOption() {
    GetProvisioningModeActivity activity =
        launchActivityWithAllowedProvisioningModes(
            PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE);

    assertThat(activity.findViewById(R.id.do_option).getVisibility()).isEqualTo(View.GONE);
    assertThat(activity.findViewById(R.id.po_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.divider).getVisibility()).isEqualTo(View.GONE);
  }

  @Test
  public void onCreate_withPoAndDoAllowedProvisioningModes_showsPoAndDoOptions() {
    GetProvisioningModeActivity activity =
        launchActivityWithAllowedProvisioningModes(
            PROVISIONING_MODE_FULLY_MANAGED_DEVICE, PROVISIONING_MODE_MANAGED_PROFILE);

    assertThat(activity.findViewById(R.id.do_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.po_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.divider).getVisibility()).isEqualTo(View.VISIBLE);
  }

  @Test
  public void onCreate_withByodAndDoAllowedProvisioningMode_showsPoAndDoOptions() {
    GetProvisioningModeActivity activity =
        launchActivityWithAllowedProvisioningModes(
            PROVISIONING_MODE_FULLY_MANAGED_DEVICE,
            PROVISIONING_MODE_MANAGED_PROFILE_ON_PERSONAL_DEVICE);

    assertThat(activity.findViewById(R.id.do_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.po_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.divider).getVisibility()).isEqualTo(View.VISIBLE);
  }

  @Test
  public void onCreate_withNoAllowedProvisioningModes_showsPoAndDoOptions() {
    GetProvisioningModeActivity activity = launchActivityWithAllowedProvisioningModes();

    assertThat(activity.findViewById(R.id.do_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.po_option).getVisibility()).isEqualTo(View.VISIBLE);
    assertThat(activity.findViewById(R.id.divider).getVisibility()).isEqualTo(View.VISIBLE);
  }

  private GetProvisioningModeActivity launchActivityWithAllowedProvisioningModes(
      Integer... allowedProvisioningModes) {
    Intent intent = new Intent();
    ArrayList<Integer> arr = new ArrayList<>(Arrays.asList(allowedProvisioningModes));
    intent.putExtra(EXTRA_PROVISIONING_ALLOWED_PROVISIONING_MODES, arr);
    return Robolectric.buildActivity(GetProvisioningModeActivity.class, intent).create().get();
  }
}


text:
=begin Original before refactoring

def count_between(list_of_integers, lower_bound, upper_bound)
  count = 0
  list_of_integers.each do |i|
  	if (i >= lower_bound.to_i) && (i <= upper_bound.to_i)
  		count += 1
  	end
  end
  return count
end

=end
# Refactored soluition
def count_between(list_of_integers, lower_bound, upper_bound)
	list_of_integers.count {|i| i >= lower_bound && i <= upper_bound}
end


text:
'use strict';

const _ = require('lodash');
const BbPromise = require('bluebird');
const getLogs = require('../lib/get-logs');
const helpers = require('../lib/helpers');

class KubelessLogs {
  constructor(serverless, options) {
    this.serverless = serverless;
    this.options = options || {};
    this.provider = this.serverless.getProvider('kubeless');
    this.commands = {
      logs: {
        usage: 'Output the logs of a deployed function',
        lifecycleEvents: [
          'logs',
        ],
        options: {
          count: {
            usage: 'Number of lines to print',
            shortcut: 'n',
          },
        },
      },
    };
    this.hooks = {
      'logs:logs': () => BbPromise.bind(this)
        .then(this.validate)
        .then(this.printLogs),
    };
  }

  validate() {
    const unsupportedOptions = ['stage', 'region', 'interval'];
    helpers.warnUnsupportedOptions(
      unsupportedOptions,
      this.options,
      this.serverless.cli.log.bind(this.serverless.cli)
    );
    if (_.isUndefined(this.serverless.service.functions[this.options.function])) {
      throw new Error(
        `The function ${this.options.function} is not present in the current description`
      );
    }
    return BbPromise.resolve();
  }

  printLogs(options) {
    const opts = _.defaults({}, options, {
      startTime: this.options.startTime,
      count: this.options.count,
      filter: this.options.filter,
      silent: false,
      tail: this.options.tail,
      namespace: this.serverless.service.functions[this.options.function].namespace ||
        this.serverless.service.provider.namespace,
    });
    return getLogs(this.options.function, opts);
  }
}

module.exports = KubelessLogs;


text:
"""Command line arguments parser.

(C) 2016-2019 1024jp
"""

import argparse
import io
import logging
import os
import sys

try:
    from . import __version__ as version
except ImportError:
    version = 'n/a'

class Parser(argparse.ArgumentParser):
    description = 'Translate coordinates in a picture to the real world.'
    datafile_name = 'source'

    def __init__(self):
        argparse.ArgumentParser.__init__(self, description=self.description)
        self.init_arguments()

    def init_arguments(self):
        """Setup arguments of command.
        """
        # argument
        self.add_argument('file',
                          type=argparse.FileType('rb'),
                          metavar='FILE',
                          nargs='?',
                          help="path to source file"
                          )

        # define options
        self.add_argument('--version',
                          action='version',
                          version=version
                          )
        self.add_argument('-t', '--test',
                          action='store_true',
                          default=False,
                          help="test the program"
                          )
        self.add_argument('-v', '--verbose',
                          action='store_true',
                          default=False,
                          help="display debug info to standard output"
                               " (default: %(default)s)"
                          )

        output = self.add_argument_group('output options')
        output.add_argument('--out',
                            type=argparse.FileType('w'),
                            default=sys.stdout,
                            metavar='FILE',
                            help="path to output file"
                                 " (default: display to standard output)"
                            )

        input_ = self.add_argument_group('input options')
        input_.add_argument('--location',
                            type=str,
                            default=None,
                            metavar='FILE',
                            help="path to location file"
                                 " (default: Localiton.csv in the same"
                                 " directory of source file)"
                            )
        input_.add_argument('--camera',
                            type=argparse.FileType('rb'),
                            default=None,
                            metavar='FILE',
                            help="path to camera model file for undistortion"
                                 " (default: points in source file are used)"
                            )

        # format values
        fileformat = self.add_argument_group('format options')
        fileformat.add_argument('--size',
                                type=int,
                                nargs=2,
                                default=(3840, 2160),
                                metavar=('WIDTH', 'HEIGHT'),
                                help=("dimension of the image"
                                      " (default: %(default)s)")
                                )
        fileformat.add_argument('--in_cols',
                                type=int,
                                nargs=2,
                                default=[2, 3],
                                metavar='INDEX',
                                help=("column positions of x, y in file "
                                      " (default: %(default)s)")
                                )
        fileformat.add_argument('--z_col',
                                type=int,
                                default=None,
                                metavar='INDEX',
                                help=("column position of z in file "
                                      " (default: %(default)s)")
                                )
        fileformat.add_argument('--out_cols',
                                type=int,
                                nargs=2,
                                default=None,
                                metavar='INDEX',
                                help=("column positions of x, y in file for"
                                      " calibrated data"
                                      " (default: same as in_cols)")
                                )

    @property
    def datafile(self):
        """Path to data file.

        Return:
        datafile (file) -- File to process, given as a command argument.
        """
        args = super(Parser, self).parse_args()
        return args.file

    def parse_args(self, **kwargs):
        """Parse command arguments and return.

        Return:
        args (namespace) -- a simple object holding command arguments.
        """
        args = super(Parser, self).parse_args(**kwargs)

        if len(kwargs) > 0:
            return args

        if not args.test and not args.file:
            self.error('This script requires a path to a {} file.\n'.format(
                    self.datafile_name))

        # size to tuple instead of list
        args.size = tuple(args.size)

        # set logging level
        if args.verbose:
            logging.basicConfig(level=logging.DEBUG,
                                format='[%(levelname)s] %(module)s -'
                                       '%(message)s (%(relativeCreated)4dms)')
            display(args)

        return args

def display(args):
    """Display input arguments for test use.
    """
    print('[arguments]')
    for key, arg in vars(args).items():
        if isinstance(arg, io.IOBase):
            arg = arg.name
        print('    {:10s} {}'.format(key + ':', arg))

if __name__ == "__main__":
    parser = Parser()
    display(parser.parse_args())


text:
"""Manage Project SDK installation, NOT REALATED to 'cros_sdk'."""

from __future__ import print_function

import os
import tempfile

from chromite.cbuildbot import constants
from chromite.cbuildbot import repository
from chromite.cli import command
from chromite.lib import bootstrap_lib
from chromite.lib import commandline
from chromite.lib import cros_build_lib
from chromite.lib import cros_logging as logging
from chromite.lib import git
from chromite.lib import gs
from chromite.lib import osutils
from chromite.lib import project_sdk
from chromite.lib import workspace_lib

_BRILLO_SDK_NO_UPDATE = 'BRILLO_SDK_NO_UPDATE'

# To fake the repo command into accepting a simple manifest, we
# have to put that manifest into a git repository. This is the
# name of that repo.
_BRILLO_SDK_LOCAL_MANIFEST_REPO = '.local_manifest_repo'

def _GetSdkManifestUrl(version):
  """Get the GS URL for the SDK |version| manifest."""
  return os.path.join(constants.BRILLO_RELEASE_MANIFESTS_URL,
                      '%s.xml' % version)

def _ResolveLatest(gs_ctx):
  """Find the 'latest' SDK release."""
  return gs_ctx.Cat(constants.BRILLO_LATEST_RELEASE_URL,
                    debug_level=logging.DEBUG).strip()

def _SdkVersionExists(gs_ctx, bootstrap_path, version):
  """Checks that |version| is a valid SDK version.

  Valid SDK versions are "latest", "tot", anything already downloaded
  to the bootstrap SDK directory, or anything that has a manifest
  available from GS.

  Args:
    gs_ctx: GSContext object to use.
    bootstrap_path: Bootstrap path to check for local SDK versions.
    version: SDK version to check.

  Returns:
    True if |version| is a valid SDK version.
  """
  if not version:
    return False
  return (
      version in ('latest', 'tot') or
      os.path.exists(bootstrap_lib.ComputeSdkPath(bootstrap_path, version)) or
      gs_ctx.Exists(_GetSdkManifestUrl(version), debug_level=logging.DEBUG))

def _DownloadSdk(gs_ctx, sdk_dir, version):
  """Downloads the specified SDK to |sdk_dir|.

  Args:
    gs_ctx: GS Context to use.
    sdk_dir: Directory in which to create a repo.
    version: Project SDK version to sync. Can be a version number or 'tot';
      'latest' should be resolved before calling this.
  """
  try:
    # Create the SDK dir, if it doesn't already exist.
    osutils.SafeMakedirs(sdk_dir)

    repo_cmd = os.path.join(constants.BOOTSTRAP_DIR, 'repo')

    logging.notice('Fetching files. This could take a few minutes...')
    # TOT is a special case, handle it first.
    if version.lower() == 'tot':
      # Init new repo.
      repo = repository.RepoRepository(
          constants.MANIFEST_URL, sdk_dir, groups='project_sdk',
          repo_cmd=repo_cmd)
      # Sync it.
      repo.Sync()
      return

    with tempfile.NamedTemporaryFile() as manifest:
      # Fetch manifest into temp file.
      gs_ctx.Copy(_GetSdkManifestUrl(version), manifest.name,
                  debug_level=logging.DEBUG)

      manifest_git_dir = os.path.join(sdk_dir, _BRILLO_SDK_LOCAL_MANIFEST_REPO)

      # Convert manifest into a git repository for the repo command.
      repository.PrepManifestForRepo(manifest_git_dir, manifest.name)

      # Fetch the SDK.
      repo = repository.RepoRepository(manifest_git_dir, sdk_dir, depth=1,
                                       repo_cmd=repo_cmd)
      repo.Sync()

    # TODO(dgarrett): Embed this step into the manifest itself.
    # Write out the SDK Version.
    sdk_version_file = project_sdk.VersionFile(sdk_dir)
    osutils.WriteFile(sdk_version_file, version)
  except:
    # If we fail for any reason, remove the partial/corrupt SDK.
    osutils.RmDir(sdk_dir, ignore_missing=True)
    raise

def _UpdateBootstrap(bootstrap_path):
  """Update the bootstrap repository."""
  # If our bootstrap is part of a repository, we shouldn't update.
  if project_sdk.FindRepoRoot(bootstrap_path):
    return

  # If the 'skip update' variable is set, we shouldn't update.
  if os.environ.get(_BRILLO_SDK_NO_UPDATE):
    return

  # Perform the git pull to update our bootstrap.
  logging.info('Updating SDK bootstrap...')
  git.RunGit(bootstrap_path, ['pull'])

  # Prevent updating again, after we restart.
  logging.debug('Re-exec...')
  os.environ[_BRILLO_SDK_NO_UPDATE] = "1"
  commandline.ReExec()

def _UpdateWorkspaceSdk(gs_ctx, bootstrap_path, workspace_path, version):
  """Install SDK |version| and attach it to a workspace.

  Args:
    gs_ctx: GSContext object to use.
    bootstrap_path: Path to bootstrap location.
    workspace_path: Path to workspace location.
    version: Project SDK version to sync. Can be a version number, 'tot', or
      'latest'.
  """
  # This is only possible if this script was reached without the brillo wrapper.
  if not bootstrap_path:
    cros_build_lib.Die('You are bootstrapping chromite from a repo checkout.\n'
                       'You must use a git clone. (brbug.com/580: link docs)')

  # Resolve 'latest' into a concrete version.
  if version.lower() == 'latest':
    version = _ResolveLatest(gs_ctx)

  sdk_path = bootstrap_lib.ComputeSdkPath(bootstrap_path, version)

  # If this version already exists, no need to reinstall it.
  if not os.path.exists(sdk_path) or version == 'tot':
    _DownloadSdk(gs_ctx, sdk_path, version)

  # Store the new version in the workspace.
  workspace_lib.SetActiveSdkVersion(workspace_path, version)

def _PrintWorkspaceSdkVersion(workspace_path, to_stdout=False):
  """Prints a workspace SDK version.

  If an SDK version can't be found, calls cros_build_lib.Die().

  Args:
    workspace_path: workspace directory path.
    to_stdout: True to print to stdout, False to use the logger.
  """
  # Print the SDK version.
  sdk_version = workspace_lib.GetActiveSdkVersion(workspace_path)
  if sdk_version is None:
    cros_build_lib.Die(
        'This workspace does not have an SDK.\n'
        'Use `brillo sdk --update latest` to attach to the latest SDK.')
  if to_stdout:
    print(sdk_version)
  else:
    logging.notice('Workspace SDK version is %s.', sdk_version)

@command.CommandDecorator('sdk')
class SdkCommand(command.CliCommand):
  """Manage Project SDK installations."""

  @classmethod
  def AddParser(cls, parser):
    super(cls, SdkCommand).AddParser(parser)
    parser.add_argument(
        '--update', help='Update the SDK to version 1.2.3, tot, or latest.')
    parser.add_argument('--version', default=False, action='store_true',
                        help='Display current version.')

  def Run(self):
    """Run brillo sdk."""
    self.options.Freeze()

    # Must run outside the chroot.
    cros_build_lib.AssertOutsideChroot()

    workspace_path = workspace_lib.WorkspacePath()
    if not workspace_path:
      cros_build_lib.Die('You must be in a workspace.')

    # Perform the update.
    if self.options.update:
      # Shared GSContext object to use.
      gs_ctx = gs.GSContext()

      bootstrap_path = bootstrap_lib.FindBootstrapPath()

      # Check this first so we don't do a bootstrap update then error out.
      if not _SdkVersionExists(gs_ctx, bootstrap_path, self.options.update):
        cros_build_lib.Die('Invalid SDK version "%s".' % self.options.update)

      logging.info('Update bootstrap...')
      _UpdateBootstrap(bootstrap_path)

      # Verify environment after _UpdateBootstrap() so we could potentially
      # fix some problems automatically.
      if not project_sdk.VerifyEnvironment():
        cros_build_lib.Die('Environment verification failed.')

      logging.notice('Updating SDK...')
      _UpdateWorkspaceSdk(gs_ctx, bootstrap_path, workspace_path,
                          self.options.update)

    # The --version argument should print to stdout for consumption by scripts.
    _PrintWorkspaceSdkVersion(workspace_path, to_stdout=self.options.version)