text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

		<meta http-equiv="content-type" content="text/html; charset=utf-8" />
		<meta name="generator" content="JsDoc Toolkit" />

		<title>jsrsasign 4.8.7 JavaScript API Reference - ASN1HEX</title>

  jsrsasign JavaScript API Reference

Class Index
| File Index

Classes

global__

ASN1HEX

Base64x

KEYUTIL

KJUR

KJUR.asn1

KJUR.asn1.ASN1Object

KJUR.asn1.ASN1Util

KJUR.asn1.cades

KJUR.asn1.cades.CAdESUtil

KJUR.asn1.cades.CompleteCertificateRefs

KJUR.asn1.cades.OtherCertID

KJUR.asn1.cades.OtherHash

KJUR.asn1.cades.OtherHashAlgAndValue

KJUR.asn1.cades.SignaturePolicyIdentifier

KJUR.asn1.cades.SignatureTimeStamp

KJUR.asn1.cms

KJUR.asn1.cms.Attribute

KJUR.asn1.cms.AttributeList

KJUR.asn1.cms.CMSUtil

KJUR.asn1.cms.ContentInfo

KJUR.asn1.cms.ContentType

KJUR.asn1.cms.EncapsulatedContentInfo

KJUR.asn1.cms.IssuerAndSerialNumber

KJUR.asn1.cms.MessageDigest

KJUR.asn1.cms.SignedData

KJUR.asn1.cms.SignerInfo

KJUR.asn1.cms.SigningCertificate

KJUR.asn1.cms.SigningCertificateV2

KJUR.asn1.cms.SigningTime

KJUR.asn1.csr

KJUR.asn1.csr.CertificationRequest

KJUR.asn1.csr.CertificationRequestInfo

KJUR.asn1.csr.CSRUtil

KJUR.asn1.DERAbstractString

KJUR.asn1.DERAbstractStructured

KJUR.asn1.DERAbstractTime

KJUR.asn1.DERBitString

KJUR.asn1.DERBoolean

KJUR.asn1.DEREnumerated

KJUR.asn1.DERGeneralizedTime

KJUR.asn1.DERIA5String

KJUR.asn1.DERInteger

KJUR.asn1.DERNull

KJUR.asn1.DERNumericString

KJUR.asn1.DERObjectIdentifier

KJUR.asn1.DEROctetString

KJUR.asn1.DERPrintableString

KJUR.asn1.DERSequence

KJUR.asn1.DERSet

KJUR.asn1.DERTaggedObject

KJUR.asn1.DERTeletexString

KJUR.asn1.DERUTCTime

KJUR.asn1.DERUTF8String

KJUR.asn1.tsp

KJUR.asn1.tsp.AbstractTSAAdapter

KJUR.asn1.tsp.Accuracy

KJUR.asn1.tsp.FixedTSAAdapter

KJUR.asn1.tsp.MessageImprint

KJUR.asn1.tsp.PKIFailureInfo

KJUR.asn1.tsp.PKIFreeText

KJUR.asn1.tsp.PKIStatus

KJUR.asn1.tsp.PKIStatusInfo

KJUR.asn1.tsp.SimpleTSAAdapter

KJUR.asn1.tsp.TimeStampReq

KJUR.asn1.tsp.TimeStampResp

KJUR.asn1.tsp.TSPUtil

KJUR.asn1.tsp.TSTInfo

KJUR.asn1.x509

KJUR.asn1.x509.AlgorithmIdentifier

KJUR.asn1.x509.AttributeTypeAndValue

KJUR.asn1.x509.AuthorityKeyIdentifier

KJUR.asn1.x509.BasicConstraints

KJUR.asn1.x509.Certificate

KJUR.asn1.x509.CRL

KJUR.asn1.x509.CRLDistributionPoints

KJUR.asn1.x509.CRLEntry

KJUR.asn1.x509.DistributionPoint

KJUR.asn1.x509.DistributionPointName

KJUR.asn1.x509.Extension

KJUR.asn1.x509.ExtKeyUsage

KJUR.asn1.x509.GeneralName

KJUR.asn1.x509.GeneralNames

KJUR.asn1.x509.KeyUsage

KJUR.asn1.x509.OID

KJUR.asn1.x509.RDN

KJUR.asn1.x509.SubjectPublicKeyInfo

KJUR.asn1.x509.TBSCertificate

KJUR.asn1.x509.TBSCertList

KJUR.asn1.x509.Time

KJUR.asn1.x509.X500Name

KJUR.asn1.x509.X509Util

KJUR.crypto

KJUR.crypto.DSA

KJUR.crypto.ECDSA

KJUR.crypto.ECParameterDB

KJUR.crypto.Mac

KJUR.crypto.MessageDigest

KJUR.crypto.OID

KJUR.crypto.Signature

KJUR.crypto.Util

KJUR.jws

KJUR.jws.IntDate

KJUR.jws.JWS

KJUR.jws.JWSJS

KJUR.lang.String

PKCS5PKEY

RSAKey

X509

				Class ASN1HEX

				ASN.1 DER encoded hexadecimal string utility class

Defined in:  asn1hex-1.1.js.

Class Summary

						Constructor Attributes
						Constructor Name and Description

								ASN1HEX()

ASN.1 DER encoded hexadecimal string utility class
This class provides a parser for hexadecimal string of
DER encoded ASN.1 binary data.

Method Summary

							Method Attributes
							Method Name and Description

							<static>

ASN1HEX.dump(hex, associative, idx, indent)

get string of simple ASN.1 dump from hexadecimal ASN.1 data
This method will get an ASN.1 dump from
hexadecmal string of ASN.1 DER encoded data.

							<static>

ASN1HEX.getByteLengthOfL_AtObj(s, pos)

get byte length for ASN.1 L(length) bytes

							<static>

ASN1HEX.getDecendantHexTLVByNthList(h, currentIndex, nthList)

get hexadecimal string of ASN.1 TLV refered by current index and nth index list.

							<static>

ASN1HEX.getDecendantHexVByNthList(h, currentIndex, nthList)

get hexadecimal string of ASN.1 V refered by current index and nth index list.

							<static>

ASN1HEX.getDecendantIndexByNthList(h, currentIndex, nthList)

get string index of nth child object of ASN.1 object refered by h, idx

							<static>

ASN1HEX.getHexOfL_AtObj(s, pos)

get hexadecimal string for ASN.1 L(length) bytes

							<static>

ASN1HEX.getHexOfTLV_AtObj(s, pos)

get hexadecimal string of ASN.1 TLV at

							<static>

ASN1HEX.getHexOfV_AtObj(s, pos)

get hexadecimal string of ASN.1 V(value)

							<static>

ASN1HEX.getIntOfL_AtObj(s, pos)

get integer value of ASN.1 length for ASN.1 data

							<static>

ASN1HEX.getNthChildIndex_AtObj(h, idx, nth)

get string index of nth child object of ASN.1 object refered by h, idx

							<static>

ASN1HEX.getPosArrayOfChildren_AtObj(s, start)

get array of indexes of child ASN.1 objects

							<static>

ASN1HEX.getPosOfNextSibling_AtObj(s, pos)

get next sibling starting index for ASN.1 object string

							<static>

ASN1HEX.getStartPosOfV_AtObj(s, pos)

get ASN.1 value starting string position for ASN.1 object refered by index 'idx'.

							<static>

ASN1HEX.hextooidstr(hex)

get OID string from hexadecimal encoded value

							<static>

ASN1HEX.isASN1HEX(hex)

check wheather the string is ASN.1 hexadecimal string or not
This method checks wheather the argument 'hex' is a hexadecimal string of
ASN.1 data or not.

					Class Detail

						ASN1HEX()

					ASN.1 DER encoded hexadecimal string utility class
This class provides a parser for hexadecimal string of
DER encoded ASN.1 binary data.
Here are major methods of this class.

ACCESS BY POSITION

ASN1HEX.getHexOfTLV_AtObj - get ASN.1 TLV at specified position

ASN1HEX.getHexOfV_AtObj - get ASN.1 V at specified position

ASN1HEX.getHexOfL_AtObj - get hexadecimal ASN.1 L at specified position

ASN1HEX.getIntOfL_AtObj - get integer ASN.1 L at specified position

ASN1HEX.getStartPosOfV_AtObj - get ASN.1 V position from its ASN.1 TLV position

ACCESS FOR CHILD ITEM

ASN1HEX.getNthChildIndex_AtObj - get nth child index at specified position

ASN1HEX.getPosArrayOfChildren_AtObj - get indexes of children

ASN1HEX.getPosOfNextSibling_AtObj - get position of next sibling

ACCESS NESTED ASN.1 STRUCTURE

ASN1HEX.getDecendantHexTLVByNthList - get ASN.1 TLV at specified list index

ASN1HEX.getDecendantHexVByNthList - get ASN.1 V at specified list index

ASN1HEX.getDecendantIndexByNthList - get index at specified list index

UTILITIES

ASN1HEX.dump - dump ASN.1 structure

ASN1HEX.isASN1HEX - check whether ASN.1 hexadecimal string or not

ASN1HEX.hextooidstr - convert hexadecimal string of OID to dotted integer list

Since:

jsrsasign 1.1

					Method Detail

<static>

					{String}
					ASN1HEX.dump(hex, associative, idx, indent)

						get string of simple ASN.1 dump from hexadecimal ASN.1 data
This method will get an ASN.1 dump from
hexadecmal string of ASN.1 DER encoded data.
Here are features:

ommit long hexadecimal string

dump encapsulated OCTET STRING (good for X.509v3 extensions)

structured/primitive context specific tag support (i.e. [0], [3] ...)

automatic decode for implicit primitive context specific tag
(good for X.509v3 extension value)

if hex starts '68747470'(i.e. http) it is decoded as utf8 encoded string.

if it is in 'subjectAltName' extension value and is '[2]'(dNSName) tag
  value will be encoded as utf8 string

otherwise it shows as hexadecimal string

// ASN.1 INTEGER
ASN1HEX.dump('0203012345')
↓
INTEGER 012345

// ASN.1 Object Identifier
ASN1HEX.dump('06052b0e03021a')
↓
ObjectIdentifier sha1 (1 3 14 3 2 26)

// ASN.1 SEQUENCE
ASN1HEX.dump('3006020101020102')
↓
SEQUENCE
  INTEGER 01
  INTEGER 02

// ASN.1 DUMP FOR X.509 CERTIFICATE
ASN1HEX.dump(X509.pemToHex(certPEM))
↓
SEQUENCE
  SEQUENCE
    [0]
      INTEGER 02
    INTEGER 0c009310d206dbe337553580118ddc87
    SEQUENCE
      ObjectIdentifier SHA256withRSA (1 2 840 113549 1 1 11)
      NULL
    SEQUENCE
      SET
        SEQUENCE
          ObjectIdentifier countryName (2 5 4 6)
          PrintableString 'US'
            :

Parameters:

									{String} hex

hexadecmal string of ASN.1 data

									{Array} associative

array of flags for dump (OPTION)

									{Number} idx

string index for starting dump (OPTION)

									{String} indent

string (OPTION)

Since:

jsrsasign 4.8.3 asn1hex 1.1.6

Returns:

{String} string of simple ASN.1 dump

<static>

					ASN1HEX.getByteLengthOfL_AtObj(s, pos)

						get byte length for ASN.1 L(length) bytes

Parameters:

									{String} s

hexadecimal string of ASN.1 DER encoded data

									{Number} pos

string index

Returns:

byte length for ASN.1 L(length) bytes

<static>

					{Number}
					ASN1HEX.getDecendantHexTLVByNthList(h, currentIndex, nthList)

						get hexadecimal string of ASN.1 TLV refered by current index and nth index list.

Parameters:

									{String} h

hexadecimal string of ASN.1 DER encoded data

									{Number} currentIndex

start string index of ASN.1 object

									{Array of Number} nthList

array list of nth

Since:

1.1

Returns:

{Number} hexadecimal string of ASN.1 TLV refered by nthList

<static>

					{Number}
					ASN1HEX.getDecendantHexVByNthList(h, currentIndex, nthList)

						get hexadecimal string of ASN.1 V refered by current index and nth index list.

Parameters:

									{String} h

hexadecimal string of ASN.1 DER encoded data

									{Number} currentIndex

start string index of ASN.1 object

									{Array of Number} nthList

array list of nth

Since:

1.1

Returns:

{Number} hexadecimal string of ASN.1 V refered by nthList

<static>

					{Number}
					ASN1HEX.getDecendantIndexByNthList(h, currentIndex, nthList)

						get string index of nth child object of ASN.1 object refered by h, idx

The "nthList" is a index list of structured ASN.1 object
reference. Here is a sample structure and "nthList"s which
refers each objects.

SQUENCE               -
  SEQUENCE            - [0]
    IA5STRING 000     - [0, 0]
    UTF8STRING 001    - [0, 1]
  SET                 - [1]
    IA5STRING 010     - [1, 0]
    UTF8STRING 011    - [1, 1]

Parameters:

									{String} h

hexadecimal string of ASN.1 DER encoded data

									{Number} currentIndex

start string index of ASN.1 object

									{Array of Number} nthList

array list of nth

Since:

1.1

Returns:

{Number} string index refered by nthList

<static>

					{String}
					ASN1HEX.getHexOfL_AtObj(s, pos)

						get hexadecimal string for ASN.1 L(length) bytes

Parameters:

									{String} s

hexadecimal string of ASN.1 DER encoded data

									{Number} pos

string index

Returns:

{String} hexadecimal string for ASN.1 L(length) bytes

<static>

					{String}
					ASN1HEX.getHexOfTLV_AtObj(s, pos)

						get hexadecimal string of ASN.1 TLV at

Parameters:

									{String} s

hexadecimal string of ASN.1 DER encoded data

									{Number} pos

string index

Since:

1.1

Returns:

{String} hexadecimal string of ASN.1 TLV.

<static>

					{String}
					ASN1HEX.getHexOfV_AtObj(s, pos)

						get hexadecimal string of ASN.1 V(value)

Parameters:

									{String} s

hexadecimal string of ASN.1 DER encoded data

									{Number} pos

string index

Returns:

{String} hexadecimal string of ASN.1 value.

<static>

					ASN1HEX.getIntOfL_AtObj(s, pos)

						get integer value of ASN.1 length for ASN.1 data

Parameters:

									{String} s

hexadecimal string of ASN.1 DER encoded data

									{Number} pos

string index

Returns:

ASN.1 L(length) integer value

<static>

					{Number}
					ASN1HEX.getNthChildIndex_AtObj(h, idx, nth)

						get string index of nth child object of ASN.1 object refered by h, idx

Parameters:

									{String} h

hexadecimal string of ASN.1 DER encoded data

									{Number} idx

start string index of ASN.1 object

									{Number} nth

for child

Since:

1.1

Returns:

{Number} string index of nth child.

<static>

					{Array of Number}
					ASN1HEX.getPosArrayOfChildren_AtObj(s, start)

						get array of indexes of child ASN.1 objects

Parameters:

									{String} s

hexadecimal string of ASN.1 DER encoded data

									{Number} start

string index of ASN.1 object

Returns:

{Array of Number} array of indexes for childen of ASN.1 objects

<static>

					ASN1HEX.getPosOfNextSibling_AtObj(s, pos)

						get next sibling starting index for ASN.1 object string

Parameters:

									{String} s

hexadecimal string of ASN.1 DER encoded data

									{Number} pos

string index

Returns:

next sibling starting index for ASN.1 object string

<static>

					ASN1HEX.getStartPosOfV_AtObj(s, pos)

						get ASN.1 value starting string position for ASN.1 object refered by index 'idx'.

Parameters:

									{String} s

hexadecimal string of ASN.1 DER encoded data

									{Number} pos

string index

<static>

					{String}
					ASN1HEX.hextooidstr(hex)

						get OID string from hexadecimal encoded value

Parameters:

									{String} hex

hexadecmal string of ASN.1 DER encoded OID value

Since:

asn1hex 1.1.5

Returns:

{String} OID string (ex. '1.2.3.4.567')

<static>

					{Boolean}
					ASN1HEX.isASN1HEX(hex)

						check wheather the string is ASN.1 hexadecimal string or not
This method checks wheather the argument 'hex' is a hexadecimal string of
ASN.1 data or not.

ASN1HEX.isASN1HEX('0203012345') → true // PROPER ASN.1 INTEGER
ASN1HEX.isASN1HEX('0203012345ff') → false // TOO LONG VALUE
ASN1HEX.isASN1HEX('02030123') → false // TOO SHORT VALUE
ASN1HEX.isASN1HEX('fa3bcd') → false // WRONG FOR ASN.1

Parameters:

									{String} hex

string to check whether it is hexadecmal string for ASN.1 DER or not

Since:

jsrsasign 4.8.3 asn1hex 1.1.6

Returns:

{Boolean} true if it is hexadecimal string of ASN.1 data otherwise false

                        © 2012-2015 Kenji Urushima, All rights reserved

			Documentation generated by JsDoc Toolkit 2.4.0


text:
<?php

namespace ZQuintana\LaraSwag\RouteDescriber;

use EXSyst\Component\Swagger\Swagger;
use Illuminate\Routing\Route;

/**
 * Class RouteMetadataDescriber
 */
final class RouteMetadataDescriber implements RouteDescriberInterface
{
    use RouteDescriberTrait;

    /**
     * {@inheritdoc}
     */
    public function describe(Swagger $api, Route $route, \ReflectionMethod $reflectionMethod)
    {
        foreach ($this->getOperations($api, $route, $reflectionMethod) as $operation) {
            $operation->merge(['schemes' => [$route->secure() ? 'https' : 'http']]);

//            $requirements = $route->getRequirements();

            // Don't include host requirements
            foreach ($route->parameterNames() as $pathVariable) {
                if ('_format' === $pathVariable) {
                    continue;
                }

                $parameter = $operation->getParameters()->get($pathVariable, 'path');
                $parameter->setRequired(true);
                $parameter->setType('string');

//                if (isset($requirements[$pathVariable])) {
//                    $parameter->setFormat($requirements[$pathVariable]);
//                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="title_text">Settings Deployment for Kodi</string>
    <string name="action_settings">Settings</string>
    <string name="app_name">Kodi TheWiz Pack</string>
    <string name="the_wiz">TheWiz</string>
    <string name="kodi_deploy">Settings Deployment for Kodi</string>
    <string name="found_xbmc">Found XBMC!</string>
    <string name="found_kodi">Found Kodi!</string>
    <string name="found_nothing">Could not locate XBMC/Kodi</string>
    <string name="deploy_success">Deployment successful</string>
    <string name="deploy_fail">Deployment failed</string>
    <string name="work_type_downloading">Downloading...</string>
    <string name="work_type_extracting">Extracting...</string>

</resources>


text:
# install_generator.rb

module Bootstrapenhanced
  module Generators
    class InstallGenerator < ::Rails::Generators::Base

      source_root File.expand_path("../templates", __FILE__)
      desc "This generator installs Bootstrap Enhanced"
      argument :language_type, :type => :string, :default => 'de', :banner => '*de or other language'
      class_option :about_file, :type => :string
      class_option :contact_file, :type => :string

      # def run_other_generators
      #   generate "bootstrap:install"
      # end

      def adjust_application_html_file
        insert_into_file "app/views/layouts/application.html.erb", :before => "<%= yield %>\n" do
          "    <%= render 'layouts/menu' %>\n" +
          "
\n" +
          "      <% flash.each do |name, msg| %>\n" +
          "        <%= content_tag(:div, msg, class: \"alert alert-info\") %>\n" +
          "      <% end %>\n" +
          "  "
        end
        insert_into_file "app/views/layouts/application.html.erb", :after => "<%= yield %>\n" do
          "
\n"
        end
      end

      def insert_menu_bar_and_default_pages
        copy_file "_menu.html.erb", "app/views/layouts/_menu.html.erb"
        empty_directory "app/views/pages"
        if Dir.exist? "doc/pages"
          files = Dir.glob("doc/pages/*") - ['backup']
          FileUtils.cp_r files, "app/views/pages"
          puts "      Pages installed"
        else
          about_file = "pages/about.html.erb"
          if options[:about_file]
            about_file = options[:about_file]
          end
          copy_file about_file, "app/views/pages/about.html.erb"

          contact_file = "pages/contact.html.erb"
          if options[:contact_file]
            contact_file = options[:contact_file]
          end
          copy_file contact_file, "app/views/pages/contact.html.erb"
        end
      end

      def switch_to_sass
        if FileTest.file? "app/assets/stylesheets/application.css"
          FileUtils.move "app/assets/stylesheets/application.css", "app/assets/stylesheets/application.scss"
        end
      end

      def adjust_application_scss
        gsub_file "app/assets/stylesheets/application.scss",
          " *= require_tree .\n *= require_self\n */\n",
          " */\n\n@import \"bootstrap\";\n"
      end

      def adjust_application_js
        insert_into_file "app/assets/javascripts/application.js", :after => "//= require jquery\n" do
          "//= require bootstrap\n"
        end
      end

      def adjust_forms_file
        if FileTest.file? "lib/templates/erb/scaffold/_form.html.erb"
          # Block 1
          gsub_file "lib/templates/erb/scaffold/_form.html.erb",
            "    <%%= f.label :<%= attribute.singular_name %> %>\n" +
            "    <%%= f.collection_select :<%= attribute.column_name %>, <%= attribute.singular_name.camelize %>.all, :id, :foreignkey_value, prompt: true %>\n",
            "
\n" +
            "      <%%= f.label :<%= attribute.singular_name %>, class: \"col-sm-2 form-control-label\" %>\n" +
            "
\n" +
            "        <%%= f.collection_select :<%= attribute.column_name %>, <%= attribute.singular_name.camelize %>.all, :id, :foreignkey_value, prompt: true %>\n" +
            "
\n" +
            "
\n"

          # Block 2
          gsub_file "lib/templates/erb/scaffold/_form.html.erb",
            "    <%%= f.label :<%= attribute.name %> %>\n" +
            "    <%%= f.<%= attribute.field_type %> :<%= attribute.name %> %>\n",
            "
\n" +
            "      <%%= f.label :<%= attribute.name %>, class: \"col-sm-2 form-control-label\" %>\n" +
            "
\n" +
            "        <%%= f.<%= attribute.field_type %> :<%= attribute.name %>, class: \"form-control\" %>\n" +
            "
\n" +
            "
\n"

          # Block 3
          gsub_file "lib/templates/erb/scaffold/_form.html.erb",
            "    <%%= f.label :<%= attribute.name %> %>\n"+
            "    <%%= f.number_field :<%= attribute.name %>, step: <%= 1.to_f / 10 ** attribute.attr_options[:scale] %> %>\n",
            "
\n" +
            "      <%%= f.label :<%= attribute.name %>, class: \"col-sm-2 form-control-label\" %>\n" +
            "
\n" +
            "        <%%= f.number_field :<%= attribute.name %>, step: <%= 1.to_f / 10 ** attribute.attr_options[:scale] %> %>\n" +
            "
\n" +
            "
\n"

          # Block 4
          insert_into_file  "lib/templates/erb/scaffold/_form.html.erb",
            " :class => \"btn btn-success btn-mini\"",
            :after => "    <%%= f.submit"

          # Block 5
          gsub_file "lib/templates/erb/scaffold/_form.html.erb",
"            \"  <%= f.label :\#{a.name} %\\>\\n\" +\n" +
"            \"  <%= f.\#{a.field_type} :\#{a.name} %\\>\\n\"",
"            \"
\\n\" +\n" +
"            \"    <%= f.label :\#{a.name}, class: \\\"col-sm-2 form-control-label\\\" %\\>\\n\" +\n" +
"            \"
\\n\" +\n" +
"            \"      <%= f.\#{a.field_type} :\#{a.name}, class: \\\"form-control\\\",  placeholder: \#{table_name.classify}.human_attribute_name(:\#{a.name}) %\\>\\n\" +\n" +
"            \"
\\n\" +\n" +
"            \"
\\n\""

          # Block 6
          gsub_file "lib/templates/erb/scaffold/_form.html.erb",
"            \"  <%= f.label :\#{a.name} %\\>\\n\" +\n" +
"            \"  <%= f.number_field :\#{a.name}, step: \#{1.to_f / 10 ** a.attr_options[:scale]} %\\>\\n\"",
"            \"
\\n\" +\n" +
"            \"    <%= f.label :\#{a.name}, class: \\\"col-sm-2 form-control-label\\\" %\\>\\n\" +\n" +
"            \"
\\n\" +\n" +
"            \"      <%= f.number_field :\#{a.name}, step: \#{1.to_f / 10 ** a.attr_options[:scale]}, class: \\\"form-control\\\" %\\>\\n\" +\n" +
"            \"
\\n\" +\n" +
"            \"
\\n\""

          # Block 7
          gsub_file "lib/templates/erb/scaffold/_form.html.erb",
"            \"  <%= f.label :\#{a.name} %\\>\\n\" \n" +
"            \"  <%= f.\#{a.field_type} :\#{a.name} %\\>\\n\"",
"            \"
\\n\" +\n"
        end
      end

      def adjust_template_new
        if FileTest.file? "lib/templates/erb/scaffold/new.html.erb"
          gsub_file "lib/templates/erb/scaffold/new.html.erb",
            "<%%= link_to t('helpers.links.back'), <%= index_helper %>_path %>",
            "<%%= link_to t('helpers.links.back'), <%= index_helper %>_path, :class => \"btn btn-success btn-mini\" %>"
        end
      end

      def adjust_template_edit
        if FileTest.file? "lib/templates/erb/scaffold/edit.html.erb"
          gsub_file "lib/templates/erb/scaffold/edit.html.erb",
            "<%= link_to t('helpers.links.show'), @project %> |\n" +
            "<%= link_to t('helpers.links.back'), projects_path %>",
            "<%= link_to t('helpers.links.show'), @project, :class => \"btn btn-success btn-mini\" %> |\n" +
            "<%= link_to t('helpers.links.back'), projects_path, :class => \"btn btn-success btn-mini\" %>"
        end
      end

      def adjust_template_index
        if FileTest.file? "lib/templates/erb/scaffold/index.html.erb"
          gsub_file "lib/templates/erb/scaffold/index.html.erb",
            "
<%= link_to t('helpers.titles.new', model: Project.model_name.human ), new_project_path %>
",
            "
<%= link_to t('helpers.titles.new', model: Project.model_name.human ), new_project_path, :class => \"btn btn-success btn-mini\" %>
"
        end
      end

      def add_bootstrap_language_files
        if FileTest.file? "config/locales/en.bootstrap.yml"
          FileUtils.move "config/locales/en.bootstrap.yml", "config/locales/en/en.bootstrap.yml"
        end
        copy_file "de.bootstrap.yml", "config/locales/#{language_type}/#{language_type}.bootstrap.yml"
        copy_file "de.bootstrap-enhanced.yml", "config/locales/#{language_type}/#{language_type}.bootstrap-enhanced.yml"
      end

      # def change_table_class
      #   gsub_file "lib/templates/erb/scaffold/index.html.erb", "
", "
"
      # end

      def add_default_images
        if Dir.exist? "doc/images"
          files = Dir.glob("doc/images/*")
          FileUtils.cp_r files, "app/assets/images"
          puts "      Images installed"
        end
      end

      def add_default_stylesheets
        if Dir.exist? "doc/stylesheets"
          files = Dir.glob("doc/stylesheets/*") - ['backup']
          FileUtils.cp_r files, "app/assets/stylesheets"
          puts "      Stylesheets installed"
        end
      end

      def add_default_application_helper
        if File.exist? "doc/helpers/application_helper.rb"
          if File.exist? "app/helpers/application_helper.rb"
            FileUtils.remove "app/helpers/application_helper.rb"
          end
          files = Dir.glob("doc/helpers/*")
          FileUtils.cp_r files, "app/helpers"
          puts "      Helpers installed"
        end
      end

      def add_default_layouts
        if Dir.exist? "doc/layouts"
          files = Dir.glob("doc/layouts/*")
          FileUtils.cp_r files, "app/views/layouts"
          puts "      Layouts installed"
        end
      end

      def add_default_shared
        if Dir.exist? "doc/shared"
          empty_directory "app/views/shared"
          files = Dir.glob("doc/shared/*")
          FileUtils.cp_r files, "app/views/shared"
          puts "      Shared installed"
        end
      end

      def add_default_locales
        if Dir.exist? "doc/locales"
          files = Dir.glob("doc/locales/*")
          FileUtils.cp_r files, "config/locales/de"
          puts "      Locales installed"
        end
      end

    end
  end
end


text:
(function( $ ) {

var simulateKeyDownUp = TestHelpers.spinner.simulateKeyDownUp;

module( "spinner: methods" );

test( "destroy", function() {
	expect( 1 );
	domEqual( "#spin", function() {
		$( "#spin" ).spinner().spinner( "destroy" );
	});
});

test( "disable", function() {
	expect( 14 );
	var element = $( "#spin" ).val( 2 ).spinner(),
		wrapper = $( "#spin" ).spinner( "widget" );

	ok( !wrapper.hasClass( "ui-spinner-disabled" ), "before: wrapper does not have ui-spinner-disabled class" );
	ok( !element.is( ":disabled" ), "before: input does not have disabled attribute" );

	element.spinner( "disable" );
	ok( wrapper.hasClass( "ui-spinner-disabled" ), "after: wrapper has ui-spinner-disabled class" );
	ok( element.is( ":disabled"), "after: input has disabled attribute" );

	simulateKeyDownUp( element, $.ui.keyCode.UP );
	equal( 2, element.val(), "keyboard - value does not change on key UP" );

	simulateKeyDownUp( element, $.ui.keyCode.DOWN );
	equal( 2, element.val(), "keyboard - value does not change on key DOWN" );

	simulateKeyDownUp( element, $.ui.keyCode.PAGE_UP );
	equal( 2, element.val(), "keyboard - value does not change on key PGUP" );

	simulateKeyDownUp( element, $.ui.keyCode.PAGE_DOWN );
	equal( 2, element.val(), "keyboard - value does not change on key PGDN" );

	wrapper.find( ".ui-spinner-up" ).trigger( "mousedown" ).trigger( "mouseup" );
	equal( 2, element.val(), "mouse - value does not change on clicking up button" );

	wrapper.find( ".ui-spinner-down" ).trigger( "mousedown" ).trigger( "mouseup" );
	equal( 2, element.val(), "mouse - value does not change on clicking down button" );

	element.spinner( "stepUp", 6 );
	equal( 8, element.val(), "script - stepUp 6 steps changes value");

	element.spinner( "stepDown" );
	equal( 7, element.val(), "script - stepDown 1 step changes value" );

	element.spinner( "pageUp" );
	equal( 17, element.val(), "script - pageUp 1 page changes value" );

	element.spinner( "pageDown" );
	equal( 7, element.val(), "script - pageDown 1 page changes value" );
});

test( "enable", function() {
	expect( 5 );
	var element = $( "#spin" ).val( 1 ).spinner({ disabled: true }),
		wrapper = element.spinner( "widget" );

	ok( wrapper.hasClass( "ui-spinner-disabled" ), "before: wrapper has ui-spinner-disabled class" );
	ok( element.is( ":disabled" ), "before: input has disabled attribute" );

	element.spinner( "enable" );

	ok( !wrapper.hasClass( ".ui-spinner-disabled" ), "after: wrapper does not have ui-spinner-disabled class" );
	ok( !element.is( ":disabled" ), "after: input does not have disabled attribute" );

	simulateKeyDownUp( element, $.ui.keyCode.UP );
	equal( 2, element.val(), "keyboard - value changes on key UP" );
});

test( "pageDown", function() {
	expect( 4 );
	var element = $( "#spin" ).val( -12 ).spinner({
		page: 20,
		min: -100
	});

	element.spinner( "pageDown" );
	equal( element.val(), -32, "pageDown 1 page" );

	element.spinner( "pageDown", 3 );
	equal( element.val(), -92, "pageDown 3 pages" );

	element.spinner( "pageDown" );
	equal( element.val(), -100, "value close to min and pageDown 1 page" );

	element.spinner( "pageDown", 10 );
	equal( element.val(), -100, "value at min and pageDown 10 pages" );
});

test( "pageUp", function() {
	expect( 4 );
	var element = $( "#spin" ).val( 12 ).spinner({
		page: 20,
		max: 100
	});

	element.spinner( "pageUp" );
	equal( element.val(), 32, "pageUp 1 page" );

	element.spinner( "pageUp", 3 );
	equal( element.val(), 92, "pageUp 3 pages" );

	element.spinner( "pageUp" );
	equal( element.val(), 100, "value close to max and pageUp 1 page" );

	element.spinner( "pageUp", 10 );
	equal( element.val(), 100, "value at max and pageUp 10 pages" );
});

test( "stepDown", function() {
	expect( 4 );
	var element = $( "#spin" ).val( 0 ).spinner({
		step: 2,
		min: -15
	});

	element.spinner( "stepDown" );
	equal( element.val(), "-1", "stepDown 1 step" );

	element.spinner( "stepDown", 5 );
	equal( element.val(), "-11", "stepDown 5 steps" );

	element.spinner( "stepDown", 4 );
	equal( element.val(), "-15", "close to min and stepDown 4 steps" );

	element.spinner( "stepDown" );
	equal( element.val(), "-15", "at min and stepDown 1 step" );
});

test( "stepUp", function() {
	expect( 4 );
	var element = $( "#spin" ).val( 0 ).spinner({
		step: 2,
		max: 16
	});

	element.spinner( "stepUp" );
	equal( element.val(), 2, "stepUp 1 step" );

	element.spinner( "stepUp", 5 );
	equal( element.val(), 12, "stepUp 5 steps" );

	element.spinner( "stepUp", 4 );
	equal( element.val(), 16, "close to min and stepUp 4 steps" );

	element.spinner( "stepUp" );
	equal( element.val(), 16, "at max and stepUp 1 step" );
});

test( "value", function() {
	expect( 2 );
	var element = $( "#spin" ).val( 0 ).spinner({
		step: 3
	});

	element.spinner( "value", 10 );
	equal( element.val(), 9, "change value via value method" );

	equal( element.spinner( "value" ), 9, "get value via value method" );
});

test( "widget", function() {
	expect( 2 );
	var element = $( "#spin" ).spinner(),
		widgetElement = element.spinner( "widget" );
	equal( widgetElement.length, 1, "one element" );
	strictEqual( widgetElement[ 0 ], element.parent()[ 0 ], "parent element" );
});

})( jQuery );


text:
using Chinchilla.Logging;

namespace Chinchilla
{
    public class RequesterFactory : TrackableFactory<Trackable>, IRequesterFactory
    {
        private readonly ILogger logger = Logger.Create<RequesterFactory>();

        public IRequester<TRequest, TResponse> Create<TRequest, TResponse>(IBus bus)
            where TRequest : ICorrelated
            where TResponse : ICorrelated
        {
            logger.InfoFormat(
                "Creating Requester for {0} responding to {1}",
                typeof(TRequest).Name,
                typeof(TResponse).Name);

            var requester = new Requester<TRequest, TResponse>(bus);

            requester.Start();

            Track(requester);

            return requester;
        }
    }
}


text:
def main():
    print "[*] Testing project and git flow"

if __name__ == "__main__":
    main()


text:
class AddFullTextIndexToBalanceTransfers < ActiveRecord::Migration
  def change
    add_column :balance_transfers, :full_text_index, :tsvector
  end
end


text:
window.fbAsyncInit = function() {
    FB.init({
        appId      : '1109487575831651',
        xfbml      : true,
        version    : 'v2.6'
    });
};

(function(d, s, id){
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) {return;}
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
    });
}

function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
        // Logged into your app and Facebook.
        testAPI();
    } else if (response.status === 'not_authorized') {
        // The person is logged into Facebook, but not your app.
        document.getElementById('status').innerHTML = 'Please log ' +
            'into this app.';
    } else {
        // The person is not logged into Facebook, so we're not sure if
        // they are logged into this app or not.
        document.getElementById('status').innerHTML = 'Please log ' +
            'into Facebook.';
    }
}

function testAPI() {
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
        console.log('Successful login for: ' + response.name);
        document.getElementById('status').innerHTML =
            'Thanks for logging in, ' + response.name + '!';
    });
}

function checkLoginState() {
    FB.getLoginStatus(function(response) {
        statusChangeCallback(response);
        console.log(response);
    });
}


text:
package com.russo_oppido_marzucco.sweng.smartgreenhouse;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Array;
import java.util.UUID;
import android.os.Handler;

public class Dati extends AppCompatActivity {

    int temperaturaVar,umiditaVar,luceVar,altezzaVar,umiditaTerraVar;

    TextView umiditaAria;
    TextView luceAria;
    TextView temperaturaAria;
    TextView umiditaTerreno;
    TextView altezza;

    public static String EXTRA_ADDRESS = "device_address";
    public static String IS_BT_CONNECT="device_connected";
    public String address = null;
    private ProgressDialog progress;
    BluetoothAdapter myBluetooth = null;
    public static BluetoothSocket btSocket = null;

    public static boolean isBtConnected = false;

    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dati);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final Context context=Dati.this;

        Intent newint = getIntent();
        address = newint.getStringExtra(DeviceList.EXTRA_ADDRESS);
        btSocket=ManualControl.btSocket;
        isBtConnected=ManualControl.isBtConnected;

        new ConnectBT().execute();
        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.syncFab);

        temperaturaAria= (TextView)findViewById(R.id.LetturaTemperatura);
        umiditaAria= (TextView)findViewById(R.id.LetturaUmidita);
        luceAria= (TextView)findViewById(R.id.LetturaLuce);
        altezza= (TextView)findViewById(R.id.altezza);
        umiditaTerreno= (TextView)findViewById(R.id.LetturaUmiditaTerra);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                receivedData();
               /*AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                alertDialog.setTitle("Avviso");
                alertDialog.setMessage("Lettura dati completata!");
                alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                alertDialog.show();*/

            }
        });

    }

    private void receivedData()
    {

        char[] buffer = new char[1024];

        if (btSocket!=null)
        {
            String found="";
            String t1="";
            String t2="";
            String t3="";
            String t4="";
            String t5="";
            int j=0;
            int i;
                try {
                    BufferedReader in = new BufferedReader(new InputStreamReader(btSocket.getInputStream()));
                    in.read(buffer);

                    String string =new String(buffer);

                    try{
                        String[] valori= string.split("\n");
                        int length=  Array.getLength(valori);

                        for(i=0;i<length-1;i++){
                           if( valori[i].startsWith("*")){
                               found=valori[i];
                               j=i;
                           }
                        }

                        i=found.indexOf(" ");
                        t1=found.substring(1,i+1);
                        found=found.substring(i+1,found.length());
                        i=found.indexOf(" ");
                        t2=found.substring(0,i+1);
                        found=found.substring(i+1,found.length());
                        i=found.indexOf(" ");
                        t3=found.substring(0,i+1);
                        found=found.substring(i+1,found.length());
                        i=found.indexOf(" ");
                        t4=found.substring(0,i+1);
                        found=found.substring(i+1,found.length());
                        i=found.indexOf(" ");
                        t5=found.substring(0,i+1);

                        temperaturaAria.setText(t1);
                        umiditaAria.setText(t2);
                        luceAria.setText(t3);
                        altezza.setText(t4);
                        umiditaTerreno.setText(t5);

                        String[] temp=t1.split(" ");
                        temperaturaVar=Integer.parseInt(temp[0]);
                        temp=t2.split(" ");
                        umiditaVar= Integer.parseInt(temp[0]);
                        temp=t3.split(" ");
                        luceVar= Integer.parseInt(temp[0]);
                        temp=t4.split(" ");
                        altezzaVar= Integer.parseInt(temp[0]);
                        temp=t5.split(" ");
                        umiditaTerraVar= Integer.parseInt(temp[0]);
                        Toast.makeText(getApplicationContext(),"Dati aggiornati!",Toast.LENGTH_SHORT).show();

                    }catch (Exception e){
                        Toast.makeText(getApplicationContext(),"Errore sincronizzazione! Riprovare.",Toast.LENGTH_SHORT).show();

                    }

                    setAlertColor(temperaturaVar,umiditaVar,luceVar,altezzaVar,umiditaTerraVar);

                } catch (IOException e) {
                    msg("Errore!");
                }

        }
    }

    public void setAlertColor(int i1, int i2, int i3, int i4, int i5){
        if(i1>22 || i1 <18){
            temperaturaAria.setBackgroundColor(getResources().getColor(R.color.alert));

        }else {
            temperaturaAria.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        }

        if(i2>75 || i2<45){
            umiditaAria.setBackgroundColor(getResources().getColor(R.color.alert));
        }else {
            umiditaAria.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        }

        if(i3<40){
            luceAria.setBackgroundColor(getResources().getColor(R.color.alert));
        }else {
            luceAria.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        }

        if(i4>20){
            altezza.setBackgroundColor(getResources().getColor(R.color.green));
        }else {
            altezza.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        }

        if(i5<35 || i5>60){
            umiditaTerreno.setBackgroundColor(getResources().getColor(R.color.alert));
        }else {
            umiditaTerreno.setBackgroundColor(getResources().getColor(R.color.colorAccent));
        }

    }

    private void msg(String s)
    {
        Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
    }

    private class ConnectBT extends AsyncTask<Void, Void, Void>
    {
        private boolean ConnectSuccess = true;

        @Override
        protected void onPreExecute() {

            {
                progress = ProgressDialog.show(Dati.this, "Connessione...", "Attendere prego!!!");
            }
        }

        @Override
        protected Void doInBackground(Void... devices)
        {
            try
            {
                if ((btSocket == null || !isBtConnected))
                {
                    myBluetooth = BluetoothAdapter.getDefaultAdapter();
                    BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
                    btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                    btSocket.connect();

                }
            }
            catch (IOException e)
            {
                ConnectSuccess = false;
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void result)
        {
            super.onPostExecute(result);

            if (!ConnectSuccess)
            {
                msg("Connessione fallita! Prova di nuovo.");
                finish();
            }
            else
            {
                msg("Connesso.");
                isBtConnected = true;
            }
            progress.dismiss();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        switch (id){
            case R.id.manualControl: {
                Intent setting = new Intent(Dati.this, ManualControl.class);
                setting.putExtra(EXTRA_ADDRESS, address);
                setting.putExtra(IS_BT_CONNECT,isBtConnected);
                startActivity(setting);

                break;
            }

        }

        return super.onOptionsItemSelected(item);
    }

}


text:
package com.google.zxing.oned;

import java.util.Hashtable;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.ResultPoint;
import com.google.zxing.common.BitArray;

/**
 *
Decodes Codabar barcodes.

 *
 * @author Bas Vijfwinkel
 */
public final class CodaBarReader extends OneDReader {

  private static final String ALPHABET_STRING = "0123456789-$:/.+ABCDTN";
  private static final char[] ALPHABET = ALPHABET_STRING.toCharArray();

  /**
   * These represent the encodings of characters, as patterns of wide and narrow bars. The 7 least-significant bits of
   * each int correspond to the pattern of wide and narrow, with 1s representing "wide" and 0s representing narrow. NOTE
   * : c is equal to the  * pattern NOTE : d is equal to the e pattern
   */
  private static final int[] CHARACTER_ENCODINGS = {
      0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, // 0-9
      0x00c, 0x018, 0x025, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E, // -$:/.+ABCD
      0x01A, 0x029 //TN
  };

  // minimal number of characters that should be present (inclusing start and stop characters)
  // this check has been added to reduce the number of false positive on other formats
  // until the cause for this behaviour has been determined
  // under normal circumstances this should be set to 3
  private static final int minCharacterLength = 6;

  // multiple start/end patterns
  // official start and end patterns
  private static final char[] STARTEND_ENCODING = {'E', '*', 'A', 'B', 'C', 'D', 'T', 'N'};
  // some codabar generator allow the codabar string to be closed by every character
  //private static final char[] STARTEND_ENCODING = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '$', ':', '/', '.', '+', 'A', 'B', 'C', 'D', 'T', 'N'};

  // some industries use a checksum standard but this is not part of the original codabar standard
  // for more information see : http://www.mecsw.com/specs/codabar.html

  public Result decodeRow(int rowNumber, BitArray row, Hashtable hints) throws NotFoundException {
    int[] start = findAsteriskPattern(row);
    start[1] = 0; // BAS: settings this to 0 improves the recognition rate somehow?
    int nextStart = start[1];
    int end = row.getSize();

    // Read off white space
    while (nextStart < end && !row.get(nextStart)) {
      nextStart++;
    }

    StringBuffer result = new StringBuffer();
    //int[] counters = new int[7];
    int[] counters;
    int lastStart;

    do {
      counters = new int[]{0, 0, 0, 0, 0, 0, 0}; // reset counters
      recordPattern(row, nextStart, counters);

      char decodedChar = toNarrowWidePattern(counters);
      if (decodedChar == '!') {
        throw NotFoundException.getNotFoundInstance();
      }
      result.append(decodedChar);
      lastStart = nextStart;
      for (int i = 0; i < counters.length; i++) {
        nextStart += counters[i];
      }

      // Read off white space
      while (nextStart < end && !row.get(nextStart)) {
        nextStart++;
      }
    } while (nextStart < end); // no fixed end pattern so keep on reading while data is available

    // Look for whitespace after pattern:
    int lastPatternSize = 0;
    for (int i = 0; i < counters.length; i++) {
      lastPatternSize += counters[i];
    }

    int whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;
    // If 50% of last pattern size, following last pattern, is not whitespace, fail
    // (but if it's whitespace to the very end of the image, that's OK)
    if ((nextStart) != end && (whiteSpaceAfterEnd / 2 < lastPatternSize)) {
      throw NotFoundException.getNotFoundInstance();
    }

	// valid result?
	if (result.length() < 2)
	{
		throw NotFoundException.getNotFoundInstance();
	}

	char startchar = result.charAt(0);
	if (!arrayContains(STARTEND_ENCODING, startchar))
	{
		//invalid start character
		throw NotFoundException.getNotFoundInstance();
	}

	// find stop character
    for (int k = 1;k < result.length() ;k++)
	{
      if (result.charAt(k) == startchar)
	  {
        // found stop character -> discard rest of the string
		if ((k+1) != result.length())
		{
			result.delete(k+1,result.length()-1);
			k = result.length();// break out of loop
		}
	  }
    }

    // remove stop/start characters character and check if a string longer than 5 characters is contained
    if (result.length() > minCharacterLength)
	{
		result.deleteCharAt(result.length()-1);
		result.deleteCharAt(0);
	}
	else
	{
		// Almost surely a false positive ( start + stop + at least 1 character)
		throw NotFoundException.getNotFoundInstance();
	}

    float left = (float) (start[1] + start[0]) / 2.0f;
    float right = (float) (nextStart + lastStart) / 2.0f;
    return new Result(
        result.toString(),
        null,
        new ResultPoint[]{
            new ResultPoint(left, (float) rowNumber),
            new ResultPoint(right, (float) rowNumber)},
        BarcodeFormat.CODABAR);
  }

  private static int[] findAsteriskPattern(BitArray row) throws NotFoundException {
    int width = row.getSize();
    int rowOffset = 0;
    while (rowOffset < width) {
      if (row.get(rowOffset)) {
        break;
      }
      rowOffset++;
    }

    int counterPosition = 0;
    int[] counters = new int[7];
    int patternStart = rowOffset;
    boolean isWhite = false;
    int patternLength = counters.length;

    for (int i = rowOffset; i < width; i++) {
      boolean pixel = row.get(i);
      if (pixel ^ isWhite) {
        counters[counterPosition]++;
      } else {
        if (counterPosition == patternLength - 1) {
          try {
            if (arrayContains(STARTEND_ENCODING, toNarrowWidePattern(counters))) {
              // Look for whitespace before start pattern, >= 50% of width of start pattern
              if (row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {
                return new int[]{patternStart, i};
              }
            }
          } catch (IllegalArgumentException re) {
            // no match, continue
          }
          patternStart += counters[0] + counters[1];
          for (int y = 2; y < patternLength; y++) {
            counters[y - 2] = counters[y];
          }
          counters[patternLength - 2] = 0;
          counters[patternLength - 1] = 0;
          counterPosition--;
        } else {
          counterPosition++;
        }
        counters[counterPosition] = 1;
        isWhite ^= true; // isWhite = !isWhite;
      }
    }
    throw NotFoundException.getNotFoundInstance();
  }

  private static boolean arrayContains(char[] array, char key) {
    if (array != null) {
      for (int i = 0; i < array.length; i++) {
        if (array[i] == key) {
          return true;
        }
      }
    }
    return false;
  }

  private static char toNarrowWidePattern(int[] counters) {
    // BAS : I have changed the following part because some codabar images would fail with the original routine
    //        I took from the Code39Reader.java file
    // ----------- change start
    int numCounters = counters.length;
    int maxNarrowCounter = 0;

    int minCounter = Integer.MAX_VALUE;
    for (int i = 0; i < numCounters; i++) {
      if (counters[i] < minCounter) {
        minCounter = counters[i];
      }
      if (counters[i] > maxNarrowCounter) {
        maxNarrowCounter = counters[i];
      }
    }
    // ---------- change end

    do {
      int wideCounters = 0;
      int pattern = 0;
      for (int i = 0; i < numCounters; i++) {
        if (counters[i] > maxNarrowCounter) {
          pattern |= 1 << (numCounters - 1 - i);
          wideCounters++;
        }
      }

      if ((wideCounters == 2) || (wideCounters == 3)) {
        for (int i = 0; i < CHARACTER_ENCODINGS.length; i++) {
          if (CHARACTER_ENCODINGS[i] == pattern) {
            return ALPHABET[i];
          }
        }
      }
      maxNarrowCounter--;
    } while (maxNarrowCounter > minCounter);
    return '!';
  }

}


text:
package com.github.ambry.account;

import java.util.Set;

import static com.github.ambry.account.Container.*;

/**
 * A builder class for {@link Container}. Since {@link Container} is immutable, modifying a {@link Container} needs to
 * build a new {@link Container} object with updated fields through this builder. A {@link Container} can be built
 * in two ways: 1) from an existing {@link Container} object; and 2) by supplying required fields of a {@link Container}.
 * This class is not thread safe.
 */
public class ContainerBuilder {
  // necessary
  private short id;
  private String name;
  private ContainerStatus status;
  private String description;
  private short parentAccountId;

  // optional
  private boolean encrypted = ENCRYPTED_DEFAULT_VALUE;
  private boolean previouslyEncrypted = PREVIOUSLY_ENCRYPTED_DEFAULT_VALUE;
  private boolean cacheable = CACHEABLE_DEFAULT_VALUE;
  private boolean mediaScanDisabled = MEDIA_SCAN_DISABLED_DEFAULT_VALUE;
  private String replicationPolicy = null;
  private boolean ttlRequired = TTL_REQUIRED_DEFAULT_VALUE;
  private boolean securePathRequired = SECURE_PATH_REQUIRED_DEFAULT_VALUE;
  private Set<String> contentTypeWhitelistForFilenamesOnDownload =
      CONTENT_TYPE_WHITELIST_FOR_FILENAMES_ON_DOWNLOAD_DEFAULT_VALUE;
  private boolean backupEnabled = BACKUP_ENABLED_DEFAULT_VALUE;

  /**
   * Constructor. This will allow building a new {@link Container} from an existing {@link Container}. The builder will
   * include all the information of the existing {@link Container}. This constructor should be used when modifying an
   * existing container.
   * @param origin The {@link Container} to build from.
   */
  public ContainerBuilder(Container origin) {
    if (origin == null) {
      throw new IllegalArgumentException("origin cannot be null.");
    }
    id = origin.getId();
    name = origin.getName();
    status = origin.getStatus();
    description = origin.getDescription();
    encrypted = origin.isEncrypted();
    previouslyEncrypted = origin.wasPreviouslyEncrypted();
    cacheable = origin.isCacheable();
    mediaScanDisabled = origin.isMediaScanDisabled();
    replicationPolicy = origin.getReplicationPolicy();
    ttlRequired = origin.isTtlRequired();
    parentAccountId = origin.getParentAccountId();
    securePathRequired = origin.isSecurePathRequired();
    contentTypeWhitelistForFilenamesOnDownload = origin.getContentTypeWhitelistForFilenamesOnDownload();
    backupEnabled = origin.isBackupEnabled();
  }

  /**
   * Constructor for a {@link ContainerBuilder} taking individual arguments.
   * @param id The id of the {@link Container} to build.
   * @param name The name of the {@link Container}.
   * @param status The status of the {@link Container}.
   * @param description The description of the {@link Container}.
   * @param parentAccountId The id of the parent {@link Account} of the {@link Container} to build.
   */
  public ContainerBuilder(short id, String name, ContainerStatus status, String description, short parentAccountId) {
    this.id = id;
    this.name = name;
    this.status = status;
    this.description = description;
    this.parentAccountId = parentAccountId;
  }

  /**
   * Sets the ID of the {@link Container} to build.
   * @param id The ID to set.
   * @return This builder.
   */
  public ContainerBuilder setId(short id) {
    this.id = id;
    return this;
  }

  /**
   * Sets the name of the {@link Container} to build.
   * @param name The name to set.
   * @return This builder.
   */
  public ContainerBuilder setName(String name) {
    this.name = name;
    return this;
  }

  /**
   * Sets the status of the {@link Container} to build.
   * @param status The status to set.
   * @return This builder.
   */
  public ContainerBuilder setStatus(ContainerStatus status) {
    this.status = status;
    return this;
  }

  /**
   * Sets the description of the {@link Container} to build.
   * @param description The description to set.
   * @return This builder.
   */
  public ContainerBuilder setDescription(String description) {
    this.description = description;
    return this;
  }

  /**
   * Sets the ID of the parent {@link Account} of the {@link Container} to build.
   * @param parentAccountId The parent {@link Account} ID to set.
   * @return This builder.
   */
  public ContainerBuilder setParentAccountId(short parentAccountId) {
    this.parentAccountId = parentAccountId;
    return this;
  }

  /**
   * Sets the encryption setting of the {@link Container} to build.
   * @param encrypted The encryption setting to set.
   * @return This builder.
   */
  public ContainerBuilder setEncrypted(boolean encrypted) {
    this.encrypted = encrypted;
    return this;
  }

  /**
   * Sets the previously encrypted setting of the {@link Container} to build.
   * @param previouslyEncrypted The previouslyEncrypted setting to set.
   * @return This builder.
   */
  public ContainerBuilder setPreviouslyEncrypted(boolean previouslyEncrypted) {
    this.previouslyEncrypted = previouslyEncrypted;
    return this;
  }

  /**
   * Sets the caching setting of the {@link Container} to build
   * @param cacheable The cache setting to set.
   * @return This builder.
   */
  public ContainerBuilder setCacheable(boolean cacheable) {
    this.cacheable = cacheable;
    return this;
  }

  /**
   * Sets the backup setting of the {@link Container} to build
   * @param backupEnabled The backup setting to set.
   * @return This builder.
   */
  public ContainerBuilder setBackupEnabled(boolean backupEnabled) {
    this.backupEnabled = backupEnabled;
    return this;
  }

  /**
   * Sets the media scan disabled setting of the {@link Container} to build
   * @param mediaScanDisabled The media scan disabled setting to set.
   * @return This builder.
   */
  public ContainerBuilder setMediaScanDisabled(boolean mediaScanDisabled) {
    this.mediaScanDisabled = mediaScanDisabled;
    return this;
  }

  /**
   * Sets the ttl required setting of the {@link Container}.
   * @param ttlRequired The ttlRequired setting to set.
   * @return This builder.
   */
  public ContainerBuilder setTtlRequired(boolean ttlRequired) {
    this.ttlRequired = ttlRequired;
    return this;
  }

  /**
   * Sets the secure path validation required setting of the {@link Container}.
   * @param securePathRequired The securePathRequired setting to set.
   * @return This builder.
   */
  public ContainerBuilder setSecurePathRequired(boolean securePathRequired) {
    this.securePathRequired = securePathRequired;
    return this;
  }

  /**
   * Sets the replication policy desired by the {@link Container}.
   * @param replicationPolicy the replication policy desired by the container
   * @return This builder.
   */
  public ContainerBuilder setReplicationPolicy(String replicationPolicy) {
    this.replicationPolicy = replicationPolicy;
    return this;
  }

  /**
   * Sets the whitelist for the content types for which filenames can be sent on download
   * @param contentTypeWhitelistForFilenamesOnDownload the whitelist for the content types for which filenames can be
   *                                                   sent on download
   * @return This builder.
   */
  public ContainerBuilder setContentTypeWhitelistForFilenamesOnDownload(
      Set<String> contentTypeWhitelistForFilenamesOnDownload) {
    this.contentTypeWhitelistForFilenamesOnDownload = contentTypeWhitelistForFilenamesOnDownload;
    return this;
  }

  /**
   * Builds a {@link Container} object. {@code id}, {@code name}, {@code status}, {@code isPrivate}, and
   * {@code parentAccountId} are required before build.
   * @return A {@link Container} object.
   * @throws IllegalStateException If any required fields is not set.
   */
  public Container build() {
    return new Container(id, name, status, description, encrypted, previouslyEncrypted || encrypted, cacheable,
        mediaScanDisabled, replicationPolicy, ttlRequired, securePathRequired,
        contentTypeWhitelistForFilenamesOnDownload, backupEnabled, parentAccountId);
  }
}


text:
package org.apache.camel.component.huaweicloud.obs;

import java.io.File;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import com.obs.services.model.StorageClassEnum;
import org.apache.camel.BindToRegistry;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.huaweicloud.common.models.ServiceKeys;
import org.apache.camel.component.huaweicloud.obs.constants.OBSProperties;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit5.CamelTestSupport;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class PutObjectTest extends CamelTestSupport {

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

    TestConfiguration testConfiguration = new TestConfiguration();

    ObjectMapper mapper = new ObjectMapper();

    @BindToRegistry("obsClient")
    ObsClient mockClient = Mockito.mock(ObsClient.class);

    @BindToRegistry("serviceKeys")
    ServiceKeys serviceKeys = new ServiceKeys(
            testConfiguration.getProperty("accessKey"),
            testConfiguration.getProperty("secretKey"));

    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:put_object")
                        .setBody(constant(new File("src/test/resources/files/test_file.txt")))
                        .setProperty(OBSProperties.BUCKET_NAME, constant("reji-abc"))
                        .setProperty(OBSProperties.BUCKET_LOCATION, constant("cn-north-1"))
                        .to("hwcloud-obs:putObject?" +
                            "serviceKeys=#serviceKeys" +
                            "&region=" + testConfiguration.getProperty("region") +
                            "&ignoreSslVerification=true" +
                            "&obsClient=#obsClient")
                        .log("Put object successful")
                        .to("log:LOG?showAll=true")
                        .to("mock:put_object_result");
            }
        };
    }

    @Test
    public void putObjectFileTest() throws Exception {

        PutObjectResult putObjectResult = new PutObjectResult(
                "reji-abc", "test_file.txt",
                "eb733a00c0c9d336e65691a37ab54293", "version-xxx",
                StorageClassEnum.STANDARD, "https://reji-abc.obs.cn-north-1.myhuaweicloud.com/test_file.txt");

        Mockito.when(mockClient.putObject(Mockito.any(String.class),
                Mockito.any(String.class), Mockito.any(File.class)))
                .thenReturn(putObjectResult);

        MockEndpoint mock = getMockEndpoint("mock:put_object_result");
        mock.expectedMinimumMessageCount(1);
        template.sendBody("direct:put_object", "sample file content");
        Exchange responseExchange = mock.getExchanges().get(0);

        mock.assertIsSatisfied();

        assertEquals("{\"bucketName\":\"reji-abc\",\"objectKey\":\"test_file.txt\"," +
                     "\"etag\":\"eb733a00c0c9d336e65691a37ab54293\",\"versionId\":\"version-xxx\"," +
                     "\"storageClass\":\"STANDARD\"," +
                     "\"objectUrl\":\"https://reji-abc.obs.cn-north-1.myhuaweicloud.com/test_file.txt\"," +
                     "\"statusCode\":0}",
                responseExchange.getIn().getBody());

    }
}


text:
package org.apache.spark.utils

import org.apache.spark.SPARK_VERSION

object SparkVersionUtils {

  /**
   * Utility method to return the Spark Versions as float type
   * and only return major version.
   * SPARK_VERSION will be of format x.y.z e.g 2.4.7, 3.0.1,
   * and return 2.4, 3.0
   */
  def getSparkVersionAsNumeric(): Float = {
    val tmpArray = SPARK_VERSION.split("\\.")
    // convert to float
    if (tmpArray.length >= 2) {
      (tmpArray(0) + "." + tmpArray(1)).toFloat
    } else {
      (tmpArray(0) + ".0").toFloat
    }
  }

  /**
   * This API ignores the sub-version and compares with only major version.
   * Version passed should be of format x.y  e.g 2.2 ,2.3.
   */
  def isEqualToSparkVersion(targetVersion: String): Boolean = {
    getSparkVersionAsNumeric == targetVersion.toFloat
  }

  /**
   * This API ignores the sub-version and compares with only major version.
   * Version passed should be of format x.y  e.g 2.2 ,2.3.
   */
  def isGreaterThanSparkVersion(targetVersion: String, isEqualTo: Boolean = false): Boolean = {
    // compare the versions
    if (isEqualTo) {
      getSparkVersionAsNumeric >= targetVersion.toFloat
    } else {
      getSparkVersionAsNumeric > targetVersion.toFloat
    }
  }

  /**
   * This API ignores the sub-version and compares with only major version.
   * Version passed should be of format x.y  e.g 2.2 ,2.3.
   */
  def isLessThanSparkVersion(targetVersion: String, isEqualTo: Boolean = false): Boolean = {
    // compare the versions
    if (isEqualTo) {
      getSparkVersionAsNumeric <= targetVersion.toFloat
    } else {
      getSparkVersionAsNumeric < targetVersion.toFloat
    }
  }
}


text:
package com.lyft.cityguide.bll;

import com.lyft.cityguide.services.ServiceErrors;

import rx.Subscriber;

/**
 * BLLJob
 * <p>
 */
abstract class BLLJob {
    <T> void handleError(Throwable e, Subscriber<T> subscriber) {
        if (e instanceof ServiceErrors.NoConnection) {
            subscriber.onError(new BLLErrors.NoConnection());
        } else if (e instanceof ServiceErrors.ServerError) {
            subscriber.onError(new BLLErrors.ServiceError());
        } else {
            subscriber.onError(e);
        }
    }
}


text:
"""Russian roulette style game for the command line"""

import math
import random

CHAMBER_COUNT = 6

bullet_chamber = 0
current_chamber = 0
player_turn = False

def setup_game():
	"""Sets a game up"""

	global bullet_chamber
	global current_chamber
	global player_turn

	bullet_chamber = math.ceil(random.random()*CHAMBER_COUNT)
	current_chamber = 1

	print "Gun prepared..."
	# determine who's first
	if random.random() >= 0.5:
		player_turn = True
		print "Player goes first"
	else:
		player_turn = False
		print "Computer goes first"

def pull_trigger():
	"""Trigger pulling function -> bool"""

	global current_chamber

	discharged = (current_chamber == bullet_chamber)
	if not discharged:
		print "*Click*\n"
	else:
		print "*BANG!*\n"

	current_chamber += 1
	return discharged

def game_loop():
	"""Function containing the game's loop"""

	global player_turn

	while True:
		if player_turn:
			raw_input("Your turn...")
		else:
			print "Computer's turn..."

		if pull_trigger():
			break

		player_turn = not(player_turn)

	if player_turn:
		print "Computer wins"
	else:
		print "Player wins"

# Program loop
while True:
	if bullet_chamber > 0:		# don't display this on first run
		if raw_input("Play again? (y/n)").lower() == "n":
			break	# terminate

	setup_game()
	game_loop()

# EOF


text:
#ifndef _MAGICKCORE_DRAW_PRIVATE_H
#define _MAGICKCORE_DRAW_PRIVATE_H

#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif

#include "MagickCore/cache.h"
#include "MagickCore/image.h"
#include "MagickCore/memory_.h"

static inline MagickBooleanType GetFillColor(const DrawInfo *draw_info,
  const ssize_t x,const ssize_t y,PixelInfo *fill,ExceptionInfo *exception)
{
  if (draw_info->fill_pattern == (Image *) NULL)
    {
      *fill=draw_info->fill;
      return(MagickTrue);
    }
  {
    Image
      *pattern;

    MagickBooleanType
      status;

    pattern=draw_info->fill_pattern;
    status=GetOneVirtualPixelInfo(pattern,TileVirtualPixelMethod,x+
      pattern->tile_offset.x,y+pattern->tile_offset.y,fill,exception);
    return(status);
  }
}

static inline MagickBooleanType GetStrokeColor(const DrawInfo *draw_info,
  const ssize_t x,const ssize_t y,PixelInfo *stroke,ExceptionInfo *exception)
{
  if (draw_info->stroke_pattern == (Image *) NULL)
    {
      *stroke=draw_info->stroke;
      return(MagickTrue);
    }
  {
    Image
      *pattern;

    MagickBooleanType
      status;

    pattern=draw_info->stroke_pattern;
    status=GetOneVirtualPixelInfo(pattern,TileVirtualPixelMethod,x+
      pattern->tile_offset.x,y+pattern->tile_offset.y,stroke,exception);
    return(status);
  }
}

#if defined(__cplusplus) || defined(c_plusplus)
}
#endif

#endif


text:
from flask import request
from nanobox_libcloud import app
from nanobox_libcloud.adapters import get_adapter
from nanobox_libcloud.utils import output

# SSH Key endpoints for the Nanobox Provider Adapter API
@app.route('/<adapter_id>/keys', methods=['POST'])
def key_create(adapter_id):
    """Creates a key using a certain adapter."""
    adapter = get_adapter(adapter_id)

    if not adapter:
        return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501)

    if not adapter.do_verify(request.headers):
        return output.failure("Credential verification failed. Please check your credentials and try again.", 401)

    result = adapter.do_key_create(request.headers, request.json)

    if 'error' in result:
        return output.failure(result['error'], result['status'])

    return output.success(result['data'], result['status'])

@app.route('/<adapter_id>/keys/<key_id>', methods=['GET'])
def key_query(adapter_id, key_id):
    """Queries data about a key using a certain adapter."""
    adapter = get_adapter(adapter_id)

    if not adapter:
        return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501)

    if not adapter.do_verify(request.headers):
        return output.failure("Credential verification failed. Please check your credentials and try again.", 401)

    result = adapter.do_key_query(request.headers, key_id)

    if 'error' in result:
        return output.failure(result['error'], result['status'])

    return output.success(result['data'], result['status'])

@app.route('/<adapter_id>/keys/<key_id>', methods=['DELETE'])
def key_delete(adapter_id, key_id):
    """Deletes a key using a certain adapter."""
    adapter = get_adapter(adapter_id)

    if not adapter:
        return output.failure("That adapter doesn't (yet) exist. Please check the adapter name and try again.", 501)

    if not adapter.do_verify(request.headers):
        return output.failure("Credential verification failed. Please check your credentials and try again.", 401)

    result = adapter.do_key_delete(request.headers, key_id)

    if isinstance(result, dict) and 'error' in result:
        return output.failure(result['error'], result['status'])

    return ""


text:
<?php

$EXERCISES =
Array(
"hello" => Array (
"qtext" => "Write a program that uses a print statement to say 'hello world'
as shown in 'Desired Output'.",
"desired" => "hello world",
"code" => '# the code below almost works
prinq "hello world"',
"checks" => Array(
"print" => "You must use a print statement within the loop."
)),

"loop" => Array (
"qtext" => "Write a program that uses a for loop and the built-in function
range to write out three numbers as shown in 'Desired Output'.",
"desired" => "0
1
2",
"code" => 'print range(3)',
"checks" => Array(
"for" => "You must produce the numbers using a for loop.",
"print" => "You must use a print statement within the loop.",
"range" => "You should use the range function to generate the list of numbers on the for statement.",
":" => "Your for statement should end with a colon (:) and the following line should be indented"
)),

"2.2" => Array (
"qtext" => "2.2 Write a program that uses raw_input
to prompt a user for their name and then
welcomes them.  Note that raw_input will pop up a dialog box.
Enter Sarah in the pop-up box when you are prompted so your
output will match the desired output.",
"desired" => "Hello Sarah",
"code" => '# The code below almost works

name = raw_input("Enter your name")
print "Howdy"',
"checks" => Array(
"raw_input" => "You must prompt for the user's name using the raw_input() function.",
"!Sarah" => "You must actually prompt for the user's name",
"print" => "You must use the print statement to print the line of output."
)),

"2.3" => Array(
"qtext" => "2.3 Write a program to prompt the user for
hours and rate per hour using raw_input
to compute gross pay.  Use 35 hours and a rate of 2.75 per hour to test the
program (the pay should be 96.25).  You should use raw_input to
read a string and float() to convert the string to a number.
Do not worry about error checking or bad user data.",
"desired" => "96.25",
"desired2" => "Pay: 96.25",
"code" => '# This first line is provided for you

hrs = raw_input("Enter Hours:")',
"checks" => Array(
"raw_input" => "You must prompt the pay and rate using the raw_input() function.",
"print" => "You must use the print statement to print the output.",
"float" => "You should use the built-in float() function to convert from a string to a float.",
"*" => "To multiply the pay and rate after you read them use the '*' operator.",
"!35" => "You should not include the input data in your source code. You must read the values for the rate and pay using raw_input().",
"!2.75" => "You should not include the input data in your source code. You must read the values for the rate and pay using raw_input().",
"!96.25" => "You must actually calculate the pay.")),

"3.1" => Array(
"qtext" => "3.1 Write a program to prompt the user for hours and rate per hour using raw_input
to compute gross pay.  Pay the hourly rate for the hours up to 40 and
1.5 times the hourly rate for all hours
worked above 40 hours.  Use 45 hours and a rate of 10.50 per hour to test the
program (the pay should be 498.75).  You should use raw_input to
read a string and float() to convert the string to a number.
Do not worry about error checking the user input - assume the user types numbers properly.
",
"desired" => "498.75",
"desired2" => "Pay: 498.75",
"code" => 'hrs = raw_input("Enter Hours:")
h = float(hrs)',
"checks" => Array(
"raw_input" => "You must prompt the pay and rate using the raw_input() function.",
"print" => "You must use the print statement to print the output.",
"if" => "You should use an if statement to decide to to the overtime computation or not.",
"float" => "You should use the built-in float() function to convert from a string to a float.",
"!45" => "You must read the data using raw_input() and then convert it. The number '45' should not appear in your program.",
"!10.5" => "You must read the data using raw_input() and then convert it.",
"!498" => "You must actually calculate the pay.")),

"3.3" => Array(
"qtext" => "3.3 Write a program to prompt for a score between 0.0 and 1.0.
If the score is out of range, print an error. If the score is between 0.0 and 1.0,
print a grade using the following table:

Score    Grade

>= 0.9     A

>= 0.8     B

>= 0.7     C

>= 0.6     D

< 0.6      F

If the user enters a value out of range, print a suitable error message and exit.
For the test, enter a score of 0.85.
",
"desired" => "B",
"code" => 'score = raw_input("Enter Score: ")',
"checks" => Array(
"raw_input" => "You must prompt for the score using the raw_input() function.",
"float" => "You should use the built-in float() function to convert from a string to a float.",
"print" => "You must use the print statement to print the output.",
"if" => "You should use an if statement to check the value of the score.",
"elif" => "You should use an elif statement to check the value of the score.")
),

"4.6" => Array(
"qtext" => "4.6 Write a program to prompt the user for hours and rate per hour using raw_input
to compute gross pay.  Award time-and-a-half for the hourly rate for all hours
worked above 40 hours.
Put the logic to do the computation of time-and-a-half in a function called computepay()
and use the function to do the computation.  The function should return a value.
Use 45 hours and a rate of 10.50 per hour to test the
program (the pay should be 498.75).
You should use raw_input to
read a string and float() to convert the string to a number.
Do not worry about error checking the user input unless you want to -
you can assume the user types numbers properly.  Do not name your variable
sum or use the sum() function.
",
"desired" => "498.75",
"code" => 'def computepay(h,r):
    return 42.37

hrs = raw_input("Enter Hours:")
p = computepay(10,20)
print "Pay",p',
"checks" => Array(
"raw_input" => "You must prompt the pay and rate using the raw_input() function.",
"print" => "You must use the print statement to print the output.",
"if" => "You should use an if statement to decide to to the overtime computation or not.",
"float" => "You should use the built-in float() function to convert from a string to a float.",
"def" => "You must use a function called computepay to do the computation.",
"!sum(" => "Do not use a variable named sum or a function named sum()",
"return" => "You must use a return statement to pass the computed pay back to the main code.",
"computepay" => "You must use a function called computepay to do the computation.",
"!475" => "You must actually calculate the pay.")
),

"5.2" => Array(
"qtext" => "5.2 Write a program that repeatedly prompts a user for integer numbers
until the user enters 'done'.  Once 'done' is entered, print out the largest and smallest
of the numbers.  If the user enters anything other than a valid number catch it
with a try/except and put out an appropriate message and ignore the number.
Enter the numbers from the book for problem 5.1 and Match the desired output as shown.
",
"desired" => "Invalid input
Maximum is 7
Minimum is 4",
"code" => 'largest = None
smallest = None
while True:
    num = raw_input("Enter a number: ")
    if num == "done" : break
    print num

print "Maximum", largest',
"checks" => Array(
"raw_input" => "You must prompt for the numbers using the raw_input() function.",
"print" => "You must use the print statement to print the output.",
"while" => "You should use a while statement to read the numbers.",
"int" => "You should use the int() function to convert from a string to an integer.",
"!=4" => "You should actually compute the maximum and minimum.",
"!= 4" => "You should actually compute the maximum and minimum.",
"!=7" => "You should actually compute the maximum and minimum.",
"!= 7" => "You should actually compute the maximum and minimum.",
"try" => "You should handle bad numbers using a try/except structure.",
"except" => "You should handle bad numbers using a try/except structure.")
),

"6.5" => Array(
"qtext" => "6.5 Write code using find() and string slicing (see section 6.10) to extract
the number at the end of the line below.   Convert the extracted value to a floating point
number and print it out.",
"desired" => "0.8475",
"code" => 'text = "X-DSPAM-Confidence:    0.8475";',
"checks" => Array(
"find" => "You should use the find function to get the position of the colon in the string.",
":" => "You should use string slicing [n:m] to extract data from the string.",
"float" => "You should use the float() function to convert from a string to an integer.",
'!"0.8475"' =>  "You must actually pull the data from the string.")
),

"fopen" => Array(
"qtext" => 'This Python program opens the file
"mbox-short.txt" and counts the number of lines in the file.',
"desired" => "1910 Lines",
"code" => 'fh = open("mbox-short.txt", "r")

count = 0
for line in fh:
   count = count + 1

print count,"Lines"
'
),

"7.1" => Array(
"qtext" => "7.1 Write a program that prompts for a file name, then opens that file
and reads through the file, and print the contents of the file in upper case.  Use
the file words.txt to produce the output below.".
'

You can download the sample data at

http://www.pythonlearn.com/code/words.txt',
"desired" => "WRITING PROGRAMS OR PROGRAMMING IS A VERY CREATIVE
AND REWARDING ACTIVITY  YOU CAN WRITE PROGRAMS FOR
MANY REASONS RANGING FROM MAKING YOUR LIVING TO SOLVING
A DIFFICULT DATA ANALYSIS PROBLEM TO HAVING FUN TO HELPING
SOMEONE ELSE SOLVE A PROBLEM  THIS BOOK ASSUMES THAT
{\EM EVERYONE} NEEDS TO KNOW HOW TO PROGRAM AND THAT ONCE
YOU KNOW HOW TO PROGRAM, YOU WILL FIGURE OUT WHAT YOU WANT
TO DO WITH YOUR NEWFOUND SKILLS

WE ARE SURROUNDED IN OUR DAILY LIVES WITH COMPUTERS RANGING
FROM LAPTOPS TO CELL PHONES  WE CAN THINK OF THESE COMPUTERS
AS OUR PERSONAL ASSISTANTS WHO CAN TAKE CARE OF MANY THINGS
ON OUR BEHALF  THE HARDWARE IN OUR CURRENT-DAY COMPUTERS
IS ESSENTIALLY BUILT TO CONTINUOUSLY AS US THE QUESTION
WHAT WOULD YOU LIKE ME TO DO NEXT

OUR COMPUTERS ARE FAST AND HAVE VASTS AMOUNTS OF MEMORY AND
COULD BE VERY HELPFUL TO US IF WE ONLY KNEW THE LANGUAGE TO
SPEAK TO EXPLAIN TO THE COMPUTER WHAT WE WOULD LIKE IT TO
DO NEXT IF WE KNEW THIS LANGUAGE WE COULD TELL THE
COMPUTER TO DO TASKS ON OUR BEHALF THAT WERE REPTITIVE
INTERESTINGLY, THE KINDS OF THINGS COMPUTERS CAN DO BEST
ARE OFTEN THE KINDS OF THINGS THAT WE HUMANS FIND BORING
AND MIND-NUMBING",
"code" => '# Use words.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
',
"xcode" => '# Use words.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
text = fh.read().strip()
print text.upper()
',
"checks" => Array(
"raw_input" => "You must prompt for the file name using the raw_input() function.",
"open" => "You need to use open() to open the file.",
"print" => "You must use the print statement to print the lines.",
"strip" => "You should use strip() or rstrip() to avoid double newlines.  You may need to scroll down to see a mis-match of the output.",
"upper" => "You should use the upper() function to convert the lines to upper case.")
),

"7.2" => Array(
"qtext" => '7.2 Write a program that prompts for a file name, then opens that file
and reads through the file, looking for lines of the form:

X-DSPAM-Confidence:    0.8475

Count these lines and extract the floating point values from each
of the lines and compute the average of those values and produce an output
as shown below.  Do not use the sum() function or a variable named sum in your solution.

You can download the sample data at

http://www.pythonlearn.com/code/mbox-short.txt when you are testing
below enter mbox-short.txt as the file name.',
"desired" => "Average spam confidence: 0.750718518519",
"code" => '# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    print line
print "Done"
',
"xcode" => '# Use the file name mbox-short.txt as the file name
fname = raw_input("Enter file name: ")
fh = open(fname)
tot = 0.0
count = 0
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    words = line.split()
    tot = tot + float(words[1])
    count = count + 1
print "Average spam confidence:", tot/count
',
"checks" => Array(
"raw_input" => "You must prompt for the file name using the raw_input() function.",
"open" => "You need to use open() to open the file.",
"!sum" => "You should not use the sum() function and avoid using sum as a variable.",
"float" => "You should use the float() function to convert from a string to an integer.",
'!18518' =>  "You must actually pull the data from the strings and convert it.",
"/" => "Average is usually a total / count.")
),

"8.4" => Array(
"qtext" => '8.4 Open the file romeo.txt and read it line by
line.  For each line, split the line into a list of words using the split()
method.   The program should build a list of words.  For each word on each line
check to see if the word is already in the list and if not append it to the list.
When the program completes, sort and print the resulting words in alphabetical order.

You can download the sample data at

http://www.pythonlearn.com/code/romeo.txt',
"desired" => "['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'the', 'through', 'what', 'window', 'with', 'yonder']",
"code" => 'fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
print line.rstrip()
',
"xcode" => 'fname = raw_input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
    words = line.split()
    for word in words:
        if word in lst: continue
        lst.append(word)
lst.sort()
print lst
',
"checks" => Array(
"split" => "You should use split() to break each line into words.",
"append" => "You should use append() to add the word to the list if it is not there.",
"open" => "You need to use open() to open the file.",
"sort" => "You need to use sort() to sort the list before you print it out.",
"!'yonder'" => "You should not put the output data in strings",
"for" => "You need two for loops. One for the lines and one for the words on each line.")
),

"8.5" => Array(
"qtext" => "8.5 Open the file mbox-short.txt and read it line by
line.  When you find a line that starts with 'From ' like the following line:

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008

You will parse the From line using split() and print out the second word in the line
(i.e. the entire address of the person who sent the message).  Then print out
a count at the end.

Hint: make sure not to include the lines that start with 'From:'.".
'

You can download the sample data at

http://www.pythonlearn.com/code/mbox-short.txt',
"desired" => "stephen.marquard@uct.ac.za
louis@media.berkeley.edu
zqian@umich.edu
rjlowe@iupui.edu
zqian@umich.edu
rjlowe@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
gsilver@umich.edu
gsilver@umich.edu
zqian@umich.edu
gsilver@umich.edu
wagnermr@iupui.edu
zqian@umich.edu
antranig@caret.cam.ac.uk
gopal.ramasammycook@gmail.com
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
david.horwitz@uct.ac.za
stephen.marquard@uct.ac.za
louis@media.berkeley.edu
louis@media.berkeley.edu
ray@media.berkeley.edu
cwen@iupui.edu
cwen@iupui.edu
cwen@iupui.edu
There were 27 lines in the file with From as the first word",
"code" => 'fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"

fh = open(fname)
count = 0

print "There were", count, "lines in the file with From as the first word"
',
"xcode" => 'fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"

fh = open(fname)
count = 0
for line in fh:
    wds = line.split()
    if len(wds) < 2 : continue
    if wds[0] != "From" : continue
    print wds[1]
    count = count + 1
print "There were", count, "lines in the file with From as the first word"
',
"checks" => Array(
"for" => "You need a for loop to read the lines in the file.",
"split" => "You should use split() to break each line into words.",
"if" => "You need to use one or more if statements to skip the lines that do not start with 'From '.",
"open" => "You need to use open() to open the file.")
),

"9.4" => Array(
"qtext" => "9.4 Write a program to read through the mbox-short.txt and figure
out who has the sent  the greatest number of mail messages.  The program looks
for 'From ' lines and takes the second
word of those lines as the person who sent the mail.  The program creates a Python
dictionary that maps the sender's mail address to a count of the number of times
they appear in the file.  After the dictionary is produced, the program reads through
the dictionary using a maximum loop to find the most prolific committer.",
"desired" => "cwen@iupui.edu 5",
"code" => 'name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
',
"xcode" => 'name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
    wds = line.split()
    if len(wds) < 2 : continue
    if wds[0] != "From" : continue
    email = wds[1]
    counts[email] = counts.get(email,0) + 1

bigcount = None
bigname = None
for name,count in counts.items():
    if bigname is None or count > bigcount:
        bigname = name
        bigcount = count

print bigname, bigcount
',
"checks" => Array(
"for" => "You need a for loop to read the lines in the file.",
"split" => "You should use split() to break each line into words.",
"if" => "You need to use one or more if statements to skip the lines that do not start with 'From '.",
"open" => "You need to use open() to open the file.")
),

"10.2" => Array(
"qtext" => "10.2 Write a program to read through the mbox-short.txt and figure
out the distribution by hour of the day for each of the messages.  You can pull the hour
out from the 'From ' line by finding the time and then splitting the string a second time
using a colon.

From stephen.marquard@uct.ac.za Sat Jan  5 09:14:16 2008

Once you have accumulated the counts for each hour, print out the counts, sorted by hour
as shown below.",
"desired" => "04 3
06 1
07 1
09 2
10 3
11 6
14 1
15 2
16 4
17 2
18 1
19 1",
"code" => 'name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
',
"xcode" => 'name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
    wds = line.split()
    if len(wds) < 5 : continue
    if wds[0] != "From" : continue
    when = wds[5]
    tics = when.split(":")
    if len(tics) != 3 : continue
    hour = tics[0]
    counts[hour] = counts.get(hour,0) + 1

lst = counts.items()
lst.sort()

for key, val in lst :
    print key, val
',
"checks" => Array(
"for" => "You need a for loop to read the lines in the file.",
"sort" => "You need to use list sort() method to sort the list of times.")
),

"11.1" => Array (
"qtext" => '11.1 Sadly, the autograder does not support the regular expression library.
So please write a program that computes the
Answer to the Ultimate Question of Life, the Universe, and Everything
[more detail].
Sample output is below.',
"desired" => "42",
"code" => '',
"checks" => Array(
"print" => "By now you should know that a print statement would be helpful here.",
"*" => "I think that multiplication is involved..."
)),

"11.9" => Array(
"qtext" => "11.9 Write a program to prompt the user for a regular expression
and read through the mbox-short.txt and count the number of lines that match
the regular expression using re.search().",
"desired" => "04 3
19 1",
"code" => 'import re

string = raw_input("Enter a regular expression:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open("mbox-short.txt")
count = 0
for line in handle:
    if re.search(string) : count = count + 1
print "mbox-short.txt had ", count, "lines that matched", string

',
"xcode" => 'name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
counts = dict()
for line in handle:
    wds = line.split()
    if len(wds) < 5 : continue
    if wds[0] != "From" : continue
    when = wds[5]
    tics = when.split(":")
    if len(tics) != 3 : continue
    hour = tics[0]
    counts[hour] = counts.get(hour,0) + 1

lst = counts.items()
lst.sort()

for key, val in lst :
    print key, val
',
"checks" => Array(
"for" => "You need a for loop to read the lines in the file.",
"sort" => "You need to use list sort() method to sort the list of times.")
)

);


text:
"""Utility functions specifically for NMT."""
from __future__ import print_function

from REDACTED.tensorflow_models.mlperf.models.rough.nmt.utils import misc_utils as utils

__all__ = ["get_translation"]

def get_translation(nmt_outputs, tgt_eos, subword_option):
  """Given batch decoding outputs, select a sentence and turn to text."""
  if tgt_eos: tgt_eos = tgt_eos.encode("utf-8")
  # Select a sentence
  output = nmt_outputs.tolist()

  # If there is an eos symbol in outputs, cut them at that point.
  if tgt_eos and tgt_eos in output:
    output = output[:output.index(tgt_eos)]

  if subword_option == "bpe":  # BPE
    translation = utils.format_bpe_text(output)
  elif subword_option == "spm":  # SPM
    translation = utils.format_spm_text(output)
  else:
    translation = utils.format_text(output)

  return translation