text:
package eu.gruchala.typelevel.full

object E_AuxPattern {

  trait Foo[A] {
    type B
    def value: B
  }

  object Foo {

    //Heart of Aux pattern
    type Aux[A0, B0] = Foo[A0] { type B = B0 }

    implicit def fooIntToString = new Foo[Int] {
      override type B = String
      override def value: B = "message"
    }

    implicit def fooStringToBoolean = new Foo[String] {
      override type B = Boolean
      override def value: B = true
    }
  }

  def fooSimple[A](a: A)(implicit f: Foo[A]): f.B = f.value
  val simpleString: String = fooSimple(2)
  val simpleBoolean: Boolean = fooSimple("")

  //the problem
  // does not compile, illegal dependent method type: parameter appears in the type of another parameter in the same section or an earlier one
//  def foo[A](a: A)(implicit f: Foo[A], opt: Option[f.B]): f.B = opt.getOrElse(f.value)

  //f is in fact a predicate. We want compiler to prove that within scope exists evidence that A0 can be converted to B0
  //If we inform compiler about type B0, we will know type of B - and vice versa! If we have defined type B, we know type B0!
  def foo[A, R](a: A)(implicit f: Foo.Aux[A, R], opt: Option[R]): R = opt.getOrElse(f.value)

  implicit val optString: Option[String] = Some("asd")
  val a: String = foo(2)

  implicit val optBoolean: Option[Boolean] = Some(false)
  val b: Boolean = foo("")

  //real world scenario using shapeless
  import shapeless._
  import shapeless.ops.hlist.Length
  //Generic will extract generic representation of T and return its type in R, which can be passed to Length
  def length[T, R <: HList](t: T)(implicit g: Generic.Aux[T, R], l: Length[R]): l.Out = l()
  case class HClass(i: Int, s: String, b: Boolean)
  val hClass = HClass(1, "", b = false)
  Nat.toInt(length(hClass)) // 3

}


text:
jQuery(document).ready(function($) {
	$('.motocalendar_title').click(function(event) {
		event.preventDefault();
		$('.motocalendar_title').removeClass('motocalendar_title-active');
		$(this).addClass('motocalendar_title-active');

		var target = ($(this).data('tab'));

		$('.motocalendar__tab').hide();
		$("."+ target).show();
	});

	$('.motocalendar__list_nav_btn').click(function(event) {
		event.preventDefault();
		$('.motocalendar__list_nav_btn').removeClass('motocalendar__list_nav-active');
		$(this).addClass('motocalendar__list_nav-active');

		var target = ($(this).data('tab'));

		$('.motocalendar__list_tab').hide();
		$("."+ target).show();
	});
});

redpajama_set_name: RedPajamaGithub


text:
import logging
import os
import requests
import six.moves.configparser

# This file contains the oauth token for a github user, their username, and optionally, a repository
# name and owner. All in the format:
# github_repo
# github_repo_owner
# github_username
# github_token
CONFIG_FILE = '~/.github-auth.conf'

global config
config = six.moves.configparser.ConfigParser()  # Sets up the configParser to read the .conf file
config.read([os.path.expanduser(CONFIG_FILE)])  # Reads the config file

def auth():
    # Creates and authorises a requests session
    session = requests.session()
    session.auth = (get_username(), get_oauth_token())

    return session

def get_oauth_token():
    _get_data('token')

def get_username():
    _get_data('username')

def get_repo():
    _get_data('repo')

def get_repo_owner():
    _get_data('repo_owner')

def _get_data(key):
    try:
        return config.get('github', 'github_%s' % (key))
    except Exception:
        logging.exception('GitHub %s not supplied in ~/.github-auth.conf.' % (key))


text:
class PlayerComponent < EntitySystem::Component
  provides :shields, :is_turning_left, :is_turning_right, :is_firing
end


text:
function render(data) {
  var template = '';

  var districts = _.keys(data)

  districts.forEach(function (districtId) {
    const district = data[districtId]

    template += "
";
    template += `<h1 id=${districtId}>${district['name']}</h1>`;

    $.each(district['indicators'], function(index, indicator) {
      template += buildTemplateIndicator(indicator);
    });

    template += "
";
  })

  $('#dashboard').html(template);

  $('[data-toggle="tooltip"]').tooltip();

  $(".description-modal").click(function(){
    $('#myModalLabel').html($(this).data('modalTitle'));
    $('#myModalText').html($(this).data('modalDescription'));
    $("#myModal").modal();
  });

  $('.easypiechart-teal').easyPieChart({
    scaleColor: false,
    barColor: '#1ebfae'
  });

  $('.easypiechart-red').easyPieChart({
    scaleColor: false,
    barColor: '#f9243f'
  });
}

$(function () {
    $.get('frontend.json', function (frontendData) {
      let fetchData = Promise.all(
          frontendData
          .map((indicator) => `data/indicators/${indicator.data}`)
          .map(dataUrl=>($.get(dataUrl)))
      )

      fetchData.then(function (indicatorData) {
        var indicatorHash = indicatorData.reduce(function (hash, indicator) {
          hash[indicator.id] = indicator
          return hash
        }, {})

        var districtsData = indicatorData.reduce(function (districtsHash, indicator) {
          const indicatorId = indicator.id

          indicator.districts.forEach(function (district) {
            let districtData = districtsHash[district.id]

            if (districtData === undefined) {
              districtsHash[district.id] = {
                name: district.name,
                indicators: []
              }
              districtData =  districtsHash[district.id]
            }

            let indicatorData = _.cloneDeep(indicator)
            delete indicatorData.districts
            indicatorData.value = district.value
            indicatorData.isOk = district.isOk

            districtData.indicators.push(indicatorData)
          })

          return districtsHash
        }, {})
        console.log(indicatorHash, districtsData)

        render(districtsData)
      })
    });
});

function buildTemplateIndicator(indicator){
  // One more color: orange
  var name = indicator['name']
  var color = indicator['value'] <= indicator['average'] ? 'teal' : 'red'
  var unit = indicator['unit'] !== undefined ? indicator['unit'] : ''
  var tooltip = indicator['tooltip'] !== undefined ? indicator['tooltip'] : ''
  var icon = ''
  if(indicator['icon']){
    icon = ''
  }

  var achievement = ''
  // var achievement = ''

  return `

                ${icon}

${name}

${indicator['value']}

                  ${achievement}

${unit}

`
}


text:
Sponsored by rollbar: [rollbar.com/pythonbytes](http://rollbar.com/pythonbytes)

**Brian #1: Two part series on interactive terminal applications**

**Part 1:** [**4 terminal applications with great command-line UIs**](https://opensource.com/article/17/5/4-terminal-apps)

- For Comparison: both ok but could be better
  - MySQL REPL
  - Python REPL
- [bpython](https://bpython-interpreter.org/) adds autocompletion and other goodies
  - also check out [ptpython](https://pypi.python.org/pypi/ptpython) as a REPL replacement
- [mycli](http://mycli.net/) adds context aware completion to MySQL
[mycli](http://mycli.net/) - [pgcli](https://www.pgcli.com/) for postgress that adds fuzzy search
- [fish](https://fishshell.com/) : like bash, but has better search history

**Part 2:** [**4 Python libraries for building great cli's**](https://opensource.com/article/17/5/4-practical-python-libraries)

- [prompt_toolkit](https://python-prompt-toolkit.readthedocs.io/en/latest/) - for building a REPL like interface
  - includes command history, auto-suggestion, auto-completion
- [click](http://click.pocoo.org/5/)
  - includes pager and ability to launch an editor
- [fuzzyfinder](https://pypi.python.org/pypi/fuzzyfinder) - make suggestions
  - article shows how to combine that with prompt_toolkit
- [pygments](http://pygments.org/) - syntax highlighting

**Michael #2:** [**How have you automated your life with python?**](https://www.reddit.com/r/Python/comments/69ba93/how_have_you_automated_your_life_with_python_if/)

- There is something magical about writing code that interacts with the physical world.
- I have a script which runs every 5 minutes between 17:00 and 17:30 which scrapes the train times website and sends me desktop notifications saying whether or not my trains home are delayed / cancelled.
- I recently wrote a quick python script that tells me when my girlfriend comes home: It sniffs the network for DHCP traffic, when her phone joins the wifi network outside it uses the say command to let me know.
- Wrote a script to check if nearby ice cream shops are stocking my favourite (rare) flavour by scanning their menu page for keywords.
- A script to check the drive time too/from work using a route with tolls or without tolls.. to try and save some money when the times aren't too different. Using google maps API and a flask site.
- I have a script that generates weekly status update emails based off my git commit messages and pull requests. It also creates timesheets in Harvest based on the projects I'm assigned.
- I have thrown together some python that automatically controls my reverse-cycle AC system so that it makes optimal use of my solar panels on my roof.

**Brian #3**: [**Building a Simple Birthday App with Flask-SQLAlchemy**](http://pybit.es/flask-sqlalchemy-bday-app.html)

- Nice simple application with a clear need.
  - Keep track of upcoming birthdays
  - Avoid Faceboook
  - Build a simple Flask app
  - Try SQLAlchemy

**Sponsored by Rollbar**, try them at [rollbar.com/pythonbytes](http://rollbar.com/pythonbytes) and don't forget to visit their booth at PyCon!

**Michael #4:** [**Spelling with Elemental Symbols**](https://www.amin.space/blog/2017/5/elemental_speller/)

- How does it work?
  - Input: "Amputations"
  - Output: "AmPuTaTiONS", "AmPUTaTiONS"
- Generating Character Groupings:
  - 'AmPuTaTiONS' `(2,2,2,2,1,1,1)`
  - 'AmPUTaTiONS' `(2,1,1,2,2,1,1,1)`
  - How many are there in general for a given word? `fib(n + 1)`!
- Addressing Performance Issues: A few attempts don't add much but
- Memoization: The technique of saving a function's output and returning it if the function is called again with the same inputs. A memoized function only needs to generate output once for a given input. This can be very helpful with expensive functions that are called many times with the same few inputs, but only works for pure functions. → 30% faster
- Algorithms: Switch to directed graphs and recursion, changes O(2^n) to O(n) and time from 16min to 10 sec.
- Learned a great deal along the way. This project introduced:
  - Combinatorics
  - Performance profiling
  - Time complexity
  - Memoization
  - Recursion
  - Graphs and trees

**Brian #5:** **IDE's for beginners**

- [Recent discussion on Reddit about Thonny](https://www.reddit.com/r/Python/comments/6ahnsb/thonny_python_ide_for_beginners/)
- I have mixed feelings about encouraging beginner IDE's.
  - Mostly negative feelings.
  - And yet there is IDLE, there is Thonny, ...
- Are these useful? Anti-useful?
- Isn't learning a decent editor part of learning to program?

**Michael #6:** [**PDF Plumber**](https://twitter.com/dtizzlenizzle/status/861024781273112576)

- Plumb a PDF for detailed information about each char, rectangle, line, et cetera — and easily extract text and tables.
- Visual debugging with `.to_image()`
- Extracting tables
  - pdfplumber's approach to table detection borrows heavily from Anssi Nurminen's master's thesis, and is inspired by Tabula. It works like this:
  - For any given PDF page, find the lines that are (a) explicitly defined and/or (b) implied by the alignment of words on the page.
  - Merge overlapping, or nearly-overlapping, lines.
  - Find the intersections of all those lines.
  - Find the most granular set of rectangles (i.e., cells) that use these intersections as their vertices.
  - Group contiguous cells into tables.
  - Check out the demonstrations section.


text:
'use strict';

exports.port = process.env.PORT || 3000;
exports.mongodb = {
  uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://fjcarb:aardvark@ds017231.mlab.com:17231/carbajaleventsapp'
};
exports.companyName = 'Acme, Inc.';
exports.projectName = 'comevents';
exports.systemEmail = 'fjcarb@gmail.com';
exports.cryptoKey = 'k3yb0ardc4t';
exports.loginAttempts = {
  forIp: 50,
  forIpAndUser: 7,
  logExpiration: '20m'
};
exports.requireAccountVerification = false;
exports.smtp = {
  from: {
    name: process.env.SMTP_FROM_NAME || exports.projectName +' comevents',
    address: process.env.SMTP_FROM_ADDRESS || 'fjcarb@gmail.com'
  },
  credentials: {
    user: process.env.SMTP_USERNAME || 'fjcarb@gmail.com',
    password: process.env.SMTP_PASSWORD || 'jwai fpie oubw epdx',
    host: process.env.SMTP_HOST || 'smtp.gmail.com',
    tls: true
  }
};
exports.oauth = {
  twitter: {
    key: process.env.TWITTER_OAUTH_KEY || '',
    secret: process.env.TWITTER_OAUTH_SECRET || ''
  },
  facebook: {
    key: process.env.FACEBOOK_OAUTH_KEY || '',
    secret: process.env.FACEBOOK_OAUTH_SECRET || ''
  },
  github: {
    key: process.env.GITHUB_OAUTH_KEY || '',
    secret: process.env.GITHUB_OAUTH_SECRET || ''
  },
  google: {
    key: process.env.GOOGLE_OAUTH_KEY || '',
    secret: process.env.GOOGLE_OAUTH_SECRET || ''
  },
  tumblr: {
    key: process.env.TUMBLR_OAUTH_KEY || '',
    secret: process.env.TUMBLR_OAUTH_SECRET || ''
  }
};


text:
// #######################################################
//
// # Copyright (C) 2010, Dave Taylor and Arnold Zokas
//
// # This source code is subject to terms and conditions of the New BSD License.
// # A copy of the license can be found in the license.txt file at the root of this distribution.
// # If you cannot locate the New BSD License, please send an email to dave@the-taylors.org or arnold.zokas@coderoom.net.
// # By using this source code in any fashion, you are agreeing to be bound by the terms of the New BSD License.
// # You must not remove this notice, or any other, from this software.
//
// #######################################################
using System.Collections.Generic;

namespace Rivet.Console
{
	public interface IParameterParser
	{
		RivetParameters Parse(IEnumerable<string> parameters);
	}
}


text:
/* jshint node: true */
'use strict';

var mergeTrees = require( 'broccoli-merge-trees' ),
    pickFiles  = require( 'broccoli-static-compiler' );

module.exports = {
    name: 'sl-ember-components',

    included: function( app ) {
        this._super.included( app );

        if ( app.env === 'development' ) {
            app.import( 'bower_components/sl-bootstrap/dist/css/sl-bootstrap-theme.css.map' );
        }

        app.import({
            development : 'bower_components/sl-bootstrap/dist/js/sl-bootstrap.js',
            production  : 'bower_components/sl-bootstrap/dist/js/sl-bootstrap.min.js'
        });

        app.import( 'bower_components/bootstrap-datepicker/js/bootstrap-datepicker.js' );

        app.import( 'bower_components/fontawesome/css/font-awesome.min.css' );

        app.import({
            development : 'bower_components/highcharts/highcharts.src.js',
            production  : 'bower_components/highcharts/highcharts.js'
        });

        app.import({
            development : 'bower_components/moment/min/moment-with-locales.js',
            production  : 'bower_components/moment/min/moment-with-locales.min.js'
        });

        app.import({
            development : 'bower_components/moment-timezone/builds/moment-timezone-with-data.js',
            production  : 'bower_components/moment-timezone/builds/moment-timezone-with-data.min.js'
        });

        app.import({
            development : 'bower_components/select2/select2.js',
            production  : 'bower_components/select2/select2.min.js'
        });

        app.import({
            development : 'bower_components/typeahead.js/dist/typeahead.bundle.js',
            production  : 'bower_components/typeahead.js/dist/typeahead.bundle.min.js'
        });
    },

    postprocessTree: function( type, tree ) {
        return mergeTrees([ tree,
            pickFiles( 'bower_components/sl-bootstrap/fonts', {
                srcDir  : '/',
                files   : [ 'benton-sans-*' ],
                destDir : '/fonts'
            }),

            pickFiles( 'bower_components/fontawesome/fonts', {
                srcDir  : '/',
                files   : [ 'fontawesome-webfont.woff' ],
                destDir : '/fonts'
            })
        ],
        {
            overwrite: true
        });
    }
};


text:
module Javelin.Lib.ByteCode.DescSign
  ( parseFieldDescriptor
  , parseMethodDescriptor
  , parseMethodSignature
  , parseFieldSignature
  , parseClassSignature
  , FieldType(..)
  , BaseType(..)
  , FieldDescriptor(..)
  ) where

import Data.Word ()

import Text.ParserCombinators.Parsec.Char
import Text.ParserCombinators.Parsec.Combinator
import Text.ParserCombinators.Parsec.Error (ParseError)
import Text.ParserCombinators.Parsec.Prim

type QualifiedName = [String]

type UnqualifiedName = String

data FieldType
  = BaseType
      { unBaseType :: BaseType
      }
  | ObjectType
      { unObjectType :: QualifiedName
      }
  | ArrayType
      { unArrayType :: FieldType
      }
  deriving (Show, Eq)

data BaseType
  = ByteT
  | CharT
  | DoubleT
  | FloatT
  | IntT
  | LongT
  | ShortT
  | BooleanT
  deriving (Show, Eq, Ord)

-- FieldDescriptor
newtype FieldDescriptor =
  FieldDescriptor
    { unFieldType :: FieldType
    }
  deriving (Show, Eq)

-- MethodDescriptor
data MethodDescriptor =
  MethodDescriptor
    { parameterDescrs :: [FieldType]
    , returnDescr :: ReturnDescriptor
    }
  deriving (Show, Eq)

data ReturnDescriptor
  = FieldTypeDescriptor
      { returnTypeDescriptor :: FieldType
      }
  | VoidDescriptor
  deriving (Show, Eq)

-- JavaTypeSignature
data JavaTypeSignature
  = FromReferenceTypeSignature
      { fieldTypeSignature :: ReferenceTypeSignature
      }
  | FromBaseTypeSignature
      { baseTypeSignature :: BaseType
      }
  deriving (Show, Eq)

-- ReferenceTypeSignature
data ReferenceTypeSignature
  = FromClassTypeSignature
      { fieldClassType :: ClassTypeSignature
      }
  | ArrayTypeSignature
      { signatures :: [JavaTypeSignature]
      }
  | FromTypeVariableSignature
      { signature :: TypeVariableSignature
      }
  deriving (Show, Eq)

-- ClassTypeSignature
data ClassTypeSignature =
  ClassTypeSignature
    { packageSpecifier :: QualifiedName
    , simpleSignature :: SimpleClassTypeSignature
    , suffix :: [SimpleClassTypeSignature]
    }
  deriving (Show, Eq)

data SimpleClassTypeSignature =
  SimpleClassTypeSignature
    { sctId :: String
    , typeArguments :: [TypeArgument]
    }
  deriving (Show, Eq)

data TypeArgument
  = TypeArgumentWithIndicator
      { indicator :: WildcardIndicator
      , typeArgumentSignature :: ReferenceTypeSignature
      }
  | TypeArgument
      { typeArgumentSignature :: ReferenceTypeSignature
      }
  | Asterisk
  deriving (Show, Eq)

data WildcardIndicator
  = Plus
  | Minus
  deriving (Show, Eq)

data TypeVariableSignature =
  TypeVariableSignature
    { tvId :: UnqualifiedName
    }
  deriving (Show, Eq)

-- ClassSignature
data ClassSignature =
  ClassSignature
    { classTypeParameters :: [FormalTypeParameter]
    , superclassSignature :: ClassTypeSignature
    , superinterfaceSignature :: [ClassTypeSignature]
    }
  deriving (Show, Eq)

data FormalTypeParameter =
  FormalTypeParameter
    { ftId :: UnqualifiedName
    , classBound :: ReferenceTypeSignature
    , interfaceBound :: [ReferenceTypeSignature]
    }
  deriving (Show, Eq)

--MethodSignature
data MethodSignature =
  MethodSignature
    { methodTypeParameters :: [FormalTypeParameter]
    , typeSignatures :: [JavaTypeSignature]
    , methodReturnType :: ReturnType
    , throwsTypeSignature :: [ThrowsSignature]
    }
  deriving (Show, Eq)

data ReturnType
  = ReturnTypeSignature
      { returnTypeSignature :: JavaTypeSignature
      }
  | VoidTypeSignature
  deriving (Show, Eq)

data ThrowsSignature =
  ThrowsSignature
    { throwsClassType :: ClassTypeSignature
    , typeVariable :: TypeVariableSignature
    }
  deriving (Show, Eq)

-- FieldSignature
newtype FieldSignature =
  FieldSignature
    { referenceType :: ReferenceTypeSignature
    }

parseFieldDescriptor :: String -> Either ParseError FieldDescriptor
parseFieldDescriptor = parse fieldDescriptorP ""

parseMethodDescriptor :: String -> Either ParseError MethodDescriptor
parseMethodDescriptor = parse methodDescriptorP ""

parseMethodSignature :: String -> Either ParseError MethodSignature
parseMethodSignature = parse methodSignatureP ""

parseClassSignature :: String -> Either ParseError ClassSignature
parseClassSignature = parse classSignatureP ""

parseFieldSignature :: String -> Either ParseError ReferenceTypeSignature
parseFieldSignature = parse fieldSignatureP ""

-- Fundamentals
type StringParser a = CharParser () a

nameSymbol = noneOf ".;[/"

unqualifiedNameP :: StringParser UnqualifiedName
unqualifiedNameP = many nameSymbol

qualifiedNameP :: StringParser QualifiedName
qualifiedNameP = sepBy unqualifiedNameP (char '/')

fieldTypeP =
  BaseType <$> baseTypeP <|>
  ObjectType <$> (char 'L' *> qualifiedNameP <* char ';') <|>
  ArrayType <$> (char '[' *> fieldTypeP) <?> "FieldType"

baseTypeP :: StringParser BaseType
baseTypeP =
  ByteT <$ char 'B' <|> CharT <$ char 'C' <|> DoubleT <$ char 'D' <|>
  FloatT <$ char 'F' <|>
  IntT <$ char 'I' <|>
  LongT <$ char 'J' <|>
  ShortT <$ char 'S' <|>
  BooleanT <$ char 'Z' <?> "BaseType"

-- FieldDescriptor
fieldDescriptorP = FieldDescriptor <$> fieldTypeP

-- MethodDescriptor
methodDescriptorP =
  MethodDescriptor <$> (char '(' *> many fieldTypeP) <*>
  (char ')' *> returnDescriptorP)

returnDescriptorP =
  FieldTypeDescriptor <$> fieldTypeP <|>
  VoidDescriptor <$ voidDescriptorP <?> "ReturnDescriptor"

voidDescriptorP = char 'v'

-- JavaTypeSignature
identifierP = many $ noneOf ".;[/<>:"

javaTypeSignatureP =
  FromReferenceTypeSignature <$> referenceTypeSignatureP <|>
  FromBaseTypeSignature <$> baseTypeP <?> "TypeSignature"

-- ReferenceTypeSignature
referenceTypeSignatureP =
  FromClassTypeSignature <$> classTypeSignatureP <|>
  ArrayTypeSignature <$> (char '[' *> many javaTypeSignatureP) <|>
  FromTypeVariableSignature <$>
  typeVariableSignatureP <?> "Field Type Signature"

-- ClassTypeSignature
classTypeSignatureP =
  (char 'L') *>
  (ClassTypeSignature <$> packageSpecifierP <*> simpleClassTypeSignatureP <*>
   many (char '.' *> simpleClassTypeSignatureP)) <*
  (char ';')

packageP = identifierP <* char '/'

packageSpecifierP = manyTill packageP (try (notFollowedBy packageP))

simpleClassTypeSignatureP =
  SimpleClassTypeSignature <$> identifierP <*> (typeArgumentsP <|> return [])

typeArgumentsP = char '<' *> many1 typeArgumentP <* char '>'

typeArgumentP =
  TypeArgumentWithIndicator <$> wildCardIndicatorP <*> referenceTypeSignatureP <|>
  TypeArgument <$> referenceTypeSignatureP <|>
  Asterisk <$ char '*' <?> "TypeArgument"

wildCardIndicatorP =
  Plus <$ char '+' <|> Minus <$ char '-' <?> "wildcard indicator"

typeVariableSignatureP =
  TypeVariableSignature <$> (char 'T' *> identifierP <* char ';')

-- ClassSignature
classSignatureP :: StringParser ClassSignature
classSignatureP =
  ClassSignature <$> typeParametersP <*> classTypeSignatureP <*>
  many classTypeSignatureP

typeParametersP =
  char '<' *> many1 formalTypeParameterP <* char '>' <|> return []

formalTypeParameterP =
  FormalTypeParameter <$> identifierP <*> classBoundP <*> many interfaceBoundP

classBoundP = char ':' *> referenceTypeSignatureP

interfaceBoundP = char ':' *> referenceTypeSignatureP

-- MethodSignature
methodSignatureP :: StringParser MethodSignature
methodSignatureP =
  MethodSignature <$> typeParametersP <*>
  (char '(' *> many javaTypeSignatureP <* char ')') <*>
  resultP <*>
  many throwsSignatureP

resultP =
  ReturnTypeSignature <$> javaTypeSignatureP <|>
  VoidTypeSignature <$ voidDescriptorP <?> "ReturnType"

throwsSignatureP =
  ThrowsSignature <$> (char '^' *> classTypeSignatureP) <*>
  (char '^' *> typeVariableSignatureP)

-- FieldSignature
fieldSignatureP = referenceTypeSignatureP


text:
'use strict';

/**
 * @ngdoc function
 * @name gitStuffApp.controller:SearchcontrollerCtrl
 * @description
 * # SearchcontrollerCtrl
 * Controller of the gitStuffApp
 */
angular.module('gitStuffApp')
  .controller('SearchcontrollerCtrl', function ($scope, $location) {
      $scope.notifyMain = function() {
      $scope.$broadcast('search', $scope.username);
      $scope.username = null;
    }
  });


text:
#ifndef __FSL_DEVICE_REGISTERS_H__
#define __FSL_DEVICE_REGISTERS_H__

/*
 * Include the cpu specific register header files.
 *
 * The CPU macro should be declared in the project or makefile.
 */
#if (defined(CPU_MIMXRT1064CVL5A) || defined(CPU_MIMXRT1064DVL6A))

#define MIMXRT1064_SERIES

/* CMSIS-style register definitions */
#include "MIMXRT1064.h"
/* CPU specific feature definitions */
#include "MIMXRT1064_features.h"

#else
    #error "No valid CPU defined!"
#endif

#endif /* __FSL_DEVICE_REGISTERS_H__ */

/*******************************************************************************
 * EOF
 ******************************************************************************/


text:
package org.prevayler.implementation;

import java.util.Date;

public class NondeterministicErrorTransaction extends Appendix {

  private static final long serialVersionUID = 1L;

  private static int _timeToDetonation = 0;

  public static synchronized void armBomb(int timeToDetonation) {
    _timeToDetonation = timeToDetonation;
  }

  private static synchronized void triggerBomb() {
    if (_timeToDetonation > 0 && --_timeToDetonation == 0) {
      throw new Error("BOOM!");
    }
  }

  public NondeterministicErrorTransaction(String toAdd) {
    super(toAdd);
  }

  public void executeOn(AppendingSystem prevalentSystem, Date executionTime) {
    triggerBomb();
    super.executeOn(prevalentSystem, executionTime);
  }

}


text:
/*
 * File:   DDSBoardMain.c
 * Author: Andrew T
 *
 * Created on March 6, 2015, 1:51 AM
 */
#include "mcc_generated_files/mcc.h"
#include <stdio.h>
#include <stdlib.h>
#include "mcc_generated_files/timer2.h"
#include <stdbool.h>
// Arrays to recorded the button and LED state.
int LED_array[8];
bool butnarray[8];

/* Sets a certain LED to the appropriate state given as a argument and then records the state of that LED that it is in.
 Arguments:
   lednum= the led you specified that will change its state.
   State= the state of that LED is in. State=1(LED On),2 (LED Off),3 (LED is blinking)

 After this function changes the LED's state in then records that state it just changed to. */

void SetLEDOut(int lednum, int state) {
    switch (lednum) {
        case 0:
            if (state == 1) {
                Off_Led(0); //Turns off LED from blinking in the tmr2 file.
                LED0_SetHigh();
                LED_array[0] = 1;
            } else if (state == 0) {
                Off_Led(0); //Turns off LED from blinking in the tmr2 file.
                LED0_SetLow();
                LED_array[0] = 0;
            }
            else if (state == 2) {

                LED0_SetLow(); //Start the LED at a 0 to turn it off and then begin blinking.
                setLED(0); //Turns on LED to blink in the tmr2 file.
                LED_array[0] = 2;

            }
            break;

        case 1:
            if (state == 1) {
                Off_Led(1); //Turns off LED from blinking in the tmr2 file.
                LED1_SetHigh();
                LED_array[1] = 1;
            } else if (state == 0) {
                Off_Led(1); //Turns off LED from blinking in the tmr2 file.
                LED1_SetLow();
                LED_array[1] = 0;
            } else if (state == 2) {

                LED1_SetLow(); //Start the LED at a 0 to turn it off and then begin blinking.
                setLED(1); //Turns on LED to blink in the tmr2 file.
                LED_array[1] = 2;

            }
            break;
        case 2:
            if (state == 1) {
                Off_Led(2); //Turns off LED from blinking in the tmr2 file.
                LED2_SetHigh();
                LED_array[2] = 1;
            } else if (state == 0) {
                Off_Led(2); //Turns off LED from blinking in the tmr2 file.
                LED2_SetLow();
                LED_array[2] = 0;
            } else if (state == 2) {

                LED2_SetLow(); //Start the LED at a 0 to turn it off and then begin blinking.
                setLED(2); //Turns on LED to blink in the tmr2 file.

                LED_array[2] = 2;

            }

            break;

        case 3:
            if (state == 1) {
                Off_Led(3); //Turns off LED from blinking in the tmr2 file.
                LED3_SetHigh();
                LED_array[3] = 1;
            } else if (state == 0) {
                Off_Led(3); //Turns off LED from blinking in the tmr2 file.
                LED3_SetLow();
                LED_array[3] = 0;
            }
            else if (state == 2) {
                LED3_SetLow(); //Start the LED at a 0 to turn it off and then begin blinking.
                setLED(3); //Turns on LED to blink in the tmr2 file.
                LED_array[3] = 2;

            }

            break;
        case 4:
            if (state == 1) {
                Off_Led(4); //Turns off LED from blinking in the tmr2 file.
                LED4_SetHigh();
                LED_array[4] = 1;
            } else if (state == 0) {
                Off_Led(4); //Turns off LED from blinking in the tmr2 file.
                LED4_SetLow();
                LED_array[4] = 0;
            }
            else if (state == 2) {
                LED4_SetLow(); //Start the LED at a 0 to turn it off and then begin blinking.
                setLED(4); //Turns on LED to blink in the tmr2 file.
                LED_array[4] = 2;
            }

            break;
        case 5:
            if (state == 1) {
                Off_Led(5); //Turns off LED from blinking in the tmr2 file.
                LED5_SetHigh();
                LED_array[5] = 1;
            } else if (state == 0) {
                Off_Led(5); //Turns off LED from blinking in the tmr2 file.
                LED5_SetLow();
                LED_array[5] = 0;
            }
            else if (state == 2) {
                LED5_SetLow(); //Start the LED at a 0 to turn it off and then begin blinking.
                setLED(5); //Turns on LED to blink in the tmr2 file.
                LED_array[5] = 2;

            }

            break;
    }
}
//Function to change the blink rate of the blinking LED's
void Change_Blink(int time){
    Change_Blink_Rate(time);
}

// Gets the LED state of the desired led number the state can currently be on(1) off(0) or blinking(2))
  int GetLEDState(int lednum)
  {
      return LED_array[lednum];
  }

void ReadButtonState(int btnnum) {
    switch (btnnum) {
        case 0:
            butnarray[btnnum] = Button1_GetValue();
            break;
        case 1:
            butnarray[btnnum] = Button2_GetValue();
            break;
        case 2:
            butnarray[btnnum] = Button3_GetValue();
            break;
        case 3:
            butnarray[btnnum] = Button4_GetValue();
            break;
        case 4:
            butnarray[btnnum] = Button5_GetValue();
            break;
        case 5:
            butnarray[btnnum] = Button6_GetValue();
            break;
        case 6:
            butnarray[btnnum] = Button7_GetValue();
            break;
        case 7:
            butnarray[btnnum] = Button8_GetValue();
            break;

    }
}

bool GetButtonState(int btnnum) {
    return butnarray[btnnum - 1];
}


text:
package com.vsahin.moneycim.View.AddAndEditSpending;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.android.gms.common.api.CommonStatusCodes;
import com.google.android.material.snackbar.Snackbar;
import com.vsahin.moneycim.Model.Entity.RawSpending;
import com.vsahin.moneycim.Model.Entity.SpendingGroup;
import com.vsahin.moneycim.R;
import com.vsahin.moneycim.View.Base.BaseFragment;
import com.vsahin.moneycim.View.OCR_Scan_Receipt.OcrCaptureActivity;
import com.vsahin.moneycim.ViewModelFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import dagger.android.support.AndroidSupportInjection;

public class AddAndEditSpendingFragment extends BaseFragment {

    private static final int RC_OCR_CAPTURE = 3;

    @BindView(R.id.root_view)
    ConstraintLayout rootView;

    @BindView(R.id.group_spinner)
    Spinner groupSpinner;

    @BindView(R.id.save_button)
    ImageButton saveButton;

    @BindView(R.id.quantity_edittext)
    EditText quantityEditText;

    @BindView(R.id.description_edittext)
    EditText descriptionEditText;

    @BindView(R.id.title_textView)
    TextView titleTextView;

    @BindView(R.id.camera_button)
    ImageButton cameraButton;

    @BindView(R.id.delete_button)
    ImageButton deleteButton;

    private AddAndEditSpendingViewModel viewModel;

    private RawSpending spending;
    private ArrayList<SpendingGroup> spendingGroupList;
    private AlertDialog deleteConfirmDialog;

    public static AddAndEditSpendingFragment newInstance(RawSpending spending) {

        Bundle args = new Bundle();
        args.putSerializable("spending", spending);
        AddAndEditSpendingFragment fragment = new AddAndEditSpendingFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_add_and_edit_spending, container, false);
        unbinder = ButterKnife.bind(this, view);

        spending = (RawSpending) getArguments().getSerializable("spending");

        if (spending == null) {
            spending = new RawSpending();
        }

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = ViewModelProviders.of(this, viewModelFactory).get(AddAndEditSpendingViewModel.class);
        subscribeSpendingGroups();
    }

    private void subscribeSpendingGroups() {
        viewModel.spendingGroups.observe(this, spendingGroups -> {
            spendingGroupList = (ArrayList<SpendingGroup>) spendingGroups;
            fillSpinner(groupSpinner, spendingGroupList);
            if(spending.getId() != 0){
                setTakenSpendingDataToFormElements();
                deleteButton.setVisibility(View.VISIBLE);
            }
        });
    }

    @OnClick(R.id.save_button)
    public void save(){
        int groupId = groupSpinner.getSelectedItemPosition();
        String quantityString = quantityEditText.getText().toString();
        String description = descriptionEditText.getText().toString();
        Date date;
        if(spending.getDate() == null) {
            date = new Date(System.currentTimeMillis());
        } else {
            date = spending.getDate();
        }

        if(groupId == 0){
            showSnackBar("Please Select Group");
            return;
        }

        if(quantityString.equals("")) {
            showSnackBar("Please write correct quantity");
            return;
        }

        fillSpending(groupId, Double.valueOf(quantityString), description, date );
        addSpending(spending);
        showSnackBar("Successfully Saved");
        getActivity().onBackPressed();
    }

    private void addSpending(RawSpending s){
        viewModel.addSpending(s);
    }

    private void showSnackBar(String text){
        Snackbar.make(rootView, text, Snackbar.LENGTH_SHORT)
                .setAction("OK", v -> { })
                .show();
    }

    private String trimQuantity(String text){
        int lastIndexOfLine = text.lastIndexOf("\n");
        if (lastIndexOfLine != -1) {
            text = text.substring(text.lastIndexOf("\n"));
        }
        text = text.replace(" ", "");
        text = text.replace(",", ".");
        text = text.replaceAll("[^\\d.]", "");

        return text;
    }

    @OnClick(R.id.delete_button)
    public void deleteSpending(){
        askForDelete();
    }

    private void askForDelete()
    {
        if(deleteConfirmDialog == null){
            Resources stringResources  = getResources();
            String title = stringResources.getString(R.string.delete);
            String message = stringResources.getString(R.string.delete_message);
            String cancel = stringResources.getString(R.string.cancel);

            DialogInterface.OnClickListener dialogClickListener = (dialog, which) -> {
                switch (which){
                    case DialogInterface.BUTTON_POSITIVE:
                        viewModel.deleteSpending(spending.id);
                        dialog.dismiss();
                        getActivity().onBackPressed();
                        break;
                    case DialogInterface.BUTTON_NEGATIVE:
                        dialog.dismiss();
                        break;
                }
            };

            deleteConfirmDialog = new AlertDialog.Builder(getActivity())
                .setTitle(title)
                .setMessage(message)
                .setIcon(R.drawable.icon_delete)
                .setPositiveButton(title, dialogClickListener)
                .setNegativeButton(cancel, dialogClickListener)
                .create();
        }

        deleteConfirmDialog.show();
    }

    @OnClick(R.id.camera_button)
    public void openOcrCaptureActivity(){
        Intent intent = new Intent(getActivity(), OcrCaptureActivity.class);
        startActivityForResult(intent, RC_OCR_CAPTURE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == RC_OCR_CAPTURE) {
            if (resultCode == CommonStatusCodes.SUCCESS) {
                if (data != null) {
                    String text = data.getStringExtra(OcrCaptureActivity.TextBlockObject);
                    text = trimQuantity(text);
                    quantityEditText.setText(text);
                }
            } else {
                showSnackBar("Error");
            }
        }
    }

    private void fillSpending(int groupId, double quantity, String description, Date date){
        spending.setGroupId(groupId);
        spending.setQuantity(quantity);
        spending.setDescription(description);
        spending.setDate(date);
    }

    private void fillSpinner(Spinner groupSpinner, List<SpendingGroup> spendingGroups){
        List<String> stringGroups = new ArrayList<>();
        stringGroups.add("Please Select Group");
        for (SpendingGroup group: spendingGroups) {
            stringGroups.add(group.getGroupName());
        }
        ArrayAdapter adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, stringGroups);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        groupSpinner.setAdapter(adapter);
    }

    private void setTakenSpendingDataToFormElements(){
        titleTextView.setText(R.string.edit_a_spending);
        quantityEditText.setText(String.valueOf(spending.getQuantity()));
        descriptionEditText.setText(spending.getDescription());
        groupSpinner.setSelection(spending.getGroupId());

    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Log.JavaUtilLoggingStrategy (groovy 2.1.7 API)</title>
<meta name="date" content="2013-09-05">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../../groovy.ico" type="image/x-icon" rel="shortcut icon">
<link href="../../../groovy.ico" type="image/x-icon" rel="icon">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

      Overview

      Package
    Class

      Deprecated
      Index
      Help

Groovy 2.1.7

  FRAMES
 NO FRAMES

  All Classes

SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

groovy.util.logging

[Java] Class Log.JavaUtilLoggingStrategy

java.lang.Object
  org.codehaus.groovy.transform.LogASTTransformation.AbstractLoggingStrategy
      groovy.util.logging.Log.JavaUtilLoggingStrategy

public static class Log.JavaUtilLoggingStrategy
extends AbstractLoggingStrategy

 This class contains the logic of how to weave a Java Util Logging logger into the host class.

    Constructor Summary

            protected Log.JavaUtilLoggingStrategy(GroovyClassLoader loader)

    Method Summary

            FieldNode

            addLoggerFieldToClass(ClassNode classNode, String logFieldName)

            boolean

            isLoggingMethod(String methodName)

            Expression

            wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression)

    Constructor Detail

        Log.JavaUtilLoggingStrategy

protected Log.JavaUtilLoggingStrategy(GroovyClassLoader loader)

    Method Detail

        addLoggerFieldToClass

public FieldNode addLoggerFieldToClass(ClassNode classNode, String logFieldName)

        isLoggingMethod

public boolean isLoggingMethod(String methodName)

        wrapLoggingMethodCall

public Expression wrapLoggingMethodCall(Expression logVariable, String methodName, Expression originalExpression)

Copyright &copy; 2003-2013 The Codehaus. All rights reserved.


text:
<?php

/**
 * Description of Merchant_Billing_Braintree
 *
 * @package Aktive Merchant
 * @author  Ibrahim Tunali <ibrahimtunali@gmail.com>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
$default_bt_path = dirname(__FILE__).'/braintree/lib/Braintree.php';
if (!class_exists('Braintree') && !file_exists($default_bt_path)) {
	throw new Exception('Braintree API not found');
} else {
	require_once($default_bt_path);
}

class Merchant_Billing_Braintree extends Merchant_Billing_Gateway implements Merchant_Billing_Gateway_Store, Merchant_Billing_Gateway_Credit, Merchant_Billing_Gateway_Charge
{
	public static $default_currency = 'USD';
	public static $supported_countries = array('US');
	public static $supported_cardtypes = array('visa', 'master', 'american_express', 'discover', 'jcb', 'dinners_club');
	public static $homepage_url = 'http://www.braintreepaymentsolutions.com';
	public static $display_name = 'Braintree';

	private $options = array();

	public function __construct($options)
	{
		parent::__construct($options);

		$this->required_options('merchant_id, public_key, private_key', $options);
		$this->options = $options;
		Braintree_Configuration::environment($this->is_test()?'sandbox':'production');
		Braintree_Configuration::merchantId($options['merchant_id']);
		Braintree_Configuration::publicKey($options['public_key']);
		Braintree_Configuration::privateKey($options['private_key']);

	}

	private function commit($action, $options)
	{
		try {

			switch ($action) {
				case 'sale':
					$result = Braintree_Transaction::sale($options);
					break;
				case 'store':
					$result = Braintree_Customer::create($options);
					break;
				case 'unstore':
					$result = Braintree_Customer::delete($options);
					break;
				case 'add_address':
					$result = Braintree_Address::create($options);
					break;
				case 'update_address':
					$merchant_customer_id = $options['_merchant_customer_id'];
					$address_id = $options['_address_id'];
					unset($options['_merchant_customer_id'],$options['_address_id']);
					$result = Braintree_Address::update($merchant_customer_id, $address_id, $options);
					break;
				case 'update':
					$merchant_customer_id = $options['_merchant_customer_id'];
					unset($options['_merchant_customer_id']);
					$result = Braintree_Customer::update($merchant_customer_id, $options);
					break;
				case 'transaction_find':
					$result = Braintree_Transaction::find($options);
					break;
				case 'settle':
					$result = Braintree_Transaction::submitForSettlement($options['transaction_id'],$options['amount']);
					break;
				case 'refund':
					$result = Braintree_Transaction::refund($options['transaction_id'],$options['amount']);
					break;
				case 'customer_find':
					$result = Braintree_Customer::find($options);
					break;
				case 'void':
					$result = Braintree_Transaction::void($options);
					break;
				case 'credit':
					if(isset($options['token'])){
						$result = Braintree_Transaction::credit($options['token'],array('amount'=>$options['amount']));
					} else {
						$result = Braintree_Transaction::credit($options);
					}
					break;
			}
		} catch (Braintree_Exception_NotFound $e) {
				throw new Merchant_Billing_Exception($e->getMessage()?$e->getMessage():'Item Not Found');
		}
		$result = $this->_parse_result($result);

		$response_options = array();
		$response_options['test'] = $this->is_test();
		isset($result['transaction_id']) && $response_options['authorization'] = $result['transaction_id'];
		isset($result['fraud_review']) && $response_options['fraud_review'] = $result['fraud_review'];
		isset($result['avs_result']) && $response_options['avs_result'] = $result['avs_result'];
		isset($result['cvv_result']) && $response_options['cvv_result'] = $result['cvv_result'];

		return new Merchant_Billing_Response(
			isset($result['success'])?$result['success']:true,
			isset($result['message'])?$result['message']:'',
			$result,
			$response_options
		);
	}

	public function store_address($options)
	{
		$this->required_options('merchant_customer_id,first_name,last_name,city,address,zip,country,state', $options);
		$data['customerId'] = $options['merchant_customer_id'];
		!empty($options['first_name']) && $data['firstName'] = $options['first_name'];
		!empty($options['last_name']) && $data['lastName'] = $options['last_name'];
		!empty($options['company']) && $data['company'] = $options['company'];
		!empty($options['city']) && $data['locality'] = $options['city'];
		!empty($options['address']) && $data['streetAddress'] = $options['address'];
		!empty($options['address_ext']) && $data['extendedAddress'] = $options['address_ext'];
		!empty($options['state']) && $data['region'] = $options['state'];
		!empty($options['zip']) && $data['postalCode'] = $options['zip'];
		!empty($options['country']) && $data['countryCodeAlpha3'] = Merchant_Country::find($options['country'])->code('alpha3')->__toString();
		return $this->commit('add_address',$data);
	}

	public function update_address($options)
	{
		$this->required_options('merchant_customer_id,id,first_name,last_name,city,address,zip,country,state', $options);
		$data['_merchant_customer_id'] = $options['merchant_customer_id'];
		$data['_address_id'] = $options['id'];
		!empty($options['first_name']) && $data['firstName'] = $options['first_name'];
		!empty($options['last_name']) && $data['lastName'] = $options['last_name'];
		!empty($options['company']) && $data['company'] = $options['company'];
		!empty($options['city']) && $data['locality'] = $options['city'];
		!empty($options['address']) && $data['streetAddress'] = $options['address'];
		!empty($options['address_ext']) && $data['extendedAddress'] = $options['address_ext'];
		!empty($options['state']) && $data['region'] = $options['state'];
		!empty($options['zip']) && $data['postalCode'] = $options['zip'];
		!empty($options['country']) && $data['countryCodeAlpha3'] = Merchant_Country::find($options['country'])->code('alpha3')->__toString();
		return $this->commit('update_address',$data);
	}

	private function _parse_result($result)
	{
		$return = array();
		$class_name = str_replace('\\','_',get_class($result));
		switch ($class_name) {
			case 'Braintree_Result_Error':
				$return['sended_params'] = $result->params;
				$return['errors'] = $result->errors->deepAll();
				$return['message'] = $result->message;
				if(isset($result->verification)){
					$return['fraud_review'] = $result->verification->processorResponseCode==2000?true:false;
					$return['avs_result'] = array(
						'code'=>$result->verification->avsErrorResponseCode,
						'street_match'=>$result->verification->avsStreetAddressResponseCode,
						'postal_match'=>$result->verification->avsPostalCodeResponseCode
					);
					$return['cvv_result'] = $result->verification->cvvResponseCode;
				}

			case 'Braintree_Result_Successful':
				//'authorization' => $response['transaction_id'],
				$return['success'] = $result->success;
				if(isset($result->customer)){
					$return = array_merge($return,$this->_parse_result($result->customer));
				}
				if(isset($result->address)){
					$return = array_merge($return,$this->_parse_result($result->address));
				}
				if(isset($result->transaction)){
					$return = array_merge($return,$this->_parse_result($result->transaction));
				}
				break;
			case 'Braintree_Customer':
				$return['created'] = $result->createdAt;
				$return['updated'] = $result->updatedAt;
				$return['customfields'] = $result->customFields;
				foreach ($result->creditCards as $cc) {
					$return['creditcards'][] = $this->_parse_result($cc);
				}
				foreach ($result->addresses as $addr) {
					$return['addresses'][] = $this->_parse_result($addr);
				}
				foreach ($result->paypalAccounts as $paypal_account) {
					$return['paypalaccounts'][] = $this->_parse_result($paypal_account);
				}
			case 'Braintree_Transaction_CustomerDetails':
				$return['merchant_customer_id'] = $result->id;
				$return['first_name'] = $result->firstName;
				$return['last_name'] = $result->lastName;
				$return['company'] = $result->company;
				$return['email'] = $result->email;
				$return['phone'] = $result->phone;
				$return['fax'] = $result->fax;
				$return['website'] = $result->website;
				break;
			case 'Braintree_CreditCard':
				$return['created'] = $result->createdAt;
				$return['updated'] = $result->updatedAt;
				$return['default'] = $result->default;
				$return['expired'] = $result->expired;
				$return['subscriptions'] = $result->subscriptions;
				$return['merchant_customer_id'] = $result->customerId;
				$return['billing_address'] = $this->_parse_result($result->billingAddress);
			case 'Braintree_Transaction_CreditCardDetails':
				$return['bin'] = $result->bin;
				$return['month'] = $result->expirationMonth;
				$return['year'] = $result->expirationYear;
				$return['last4'] = $result->last4;
				$return['holdername'] = $result->cardholderName;
				$return['customer_location'] = $result->customerLocation;
				$return['token'] = $result->token;
				$return['expire_date'] = $result->expirationDate;
				$return['masked'] = $result->maskedNumber;
				$return['type'] = $result->cardType;
				break;
			case 'Braintree_Address':
				$return['merchant_customer_id'] = $result->customerId;
				$return['create'] = $result->createdAt;
				$return['update'] = $result->updatedAt;
			case 'Braintree_Transaction_AddressDetails':
				$return['id'] = $result->id;
				$return['first_name'] = $result->firstName;
				$return['last_name'] = $result->lastName;
				$return['company'] = $result->company;
				$return['address'] = $result->streetAddress;
				$return['address_ext'] = $result->extendedAddress;
				$return['city'] = $result->locality;
				$return['state'] = $result->region;
				$return['zip'] = $result->postalCode;
				$return['country'] = !empty($result->countryCodeAlpha3)?Merchant_Country::find($result->countryCodeAlpha3)->code('alpha3')->__toString():NULL;
				break;
			case 'Braintree_Transaction':
				$return['transaction_id'] = $result->id;
				$return['status'] = $result->status;
				$return['type'] = $result->type;
				$return['currency_code'] = $result->currencyIsoCode;
				$return['amount'] = $result->amount;
				$return['merchant_account_id'] = $result->merchantAccountId;
				$return['order_id'] = $result->orderId;
				$return['created'] = $result->createdAt;
				$return['updated'] = $result->updatedAt;
				$return['customer'] = array(
					'id' => $result->customer['firstName'],
					'first_name' => $result->customer['firstName'],
					'last_name' => $result->customer['lastName'],
					'company' => $result->customer['company'],
					'email' => $result->customer['email'],
					'phone' => $result->customer['phone'],
					'fax' => $result->customer['fax'],
					'website' => $result->customer['website'],
				);
				$return['billing'] = array(
					'id' => $result->billing['id'],
					'first_name' => $result->billing['firstName'],
					'last_name' => $result->billing['lastName'],
					'company' => $result->billing['company'],
					'address' => $result->billing['streetAddress'],
					'address_ext' => $result->billing['extendedAddress'],
					'city' => $result->billing['locality'],
					'state' => $result->billing['region'],
					'zip' => $result->billing['postalCode'],
					'country' => $result->billing['countryCodeAlpha3'],
				);
				$return['shipping'] = array(
					'id' => $result->billing['id'],
					'first_name' => $result->billing['firstName'],
					'last_name' => $result->billing['lastName'],
					'company' => $result->billing['company'],
					'address' => $result->billing['streetAddress'],
					'address_ext' => $result->billing['extendedAddress'],
					'city' => $result->billing['locality'],
					'state' => $result->billing['region'],
					'zip' => $result->billing['postalCode'],
					'country' => $result->billing['countryCodeAlpha3'],
				);
				$return['refund_id'] = $result->refundId;
				$return['refund_ids'] = $result->refundIds;
				$return['refunded_transaction_id'] = $result->refundedTransactionId;
				$return['fraud_review'] = $result->processorResponseCode==2000?true:false;
				$return['avs_result'] = array(
					'code'=>$result->avsErrorResponseCode,
					'street_match'=>$result->avsStreetAddressResponseCode,
					'postal_match'=>$result->avsPostalCodeResponseCode
				);
				$return['cvv_result'] = $result->cvvResponseCode;

				$return['settlement_batch_id'] = $result->settlementBatchId;
				$return['custom_fields'] = $result->customFields;
				$return['processor_authorization_code'] = $result->processorAuthorizationCode;
				$return['processor_response_code'] = $result->processorResponseCode;
				$return['processor_response_text'] = $result->processorResponseText;
				$return['purchase_order_number'] = $result->purchaseOrderNumber;
				$return['tax_amount'] = $result->taxAmount;
				$return['tax'] = $result->taxExempt;
				$return['creditcard'] = array(
					'token' => $result->creditCard['token'],
					'bin' => $result->creditCard['bin'],
					'last4' => $result->creditCard['last4'],
					'type' => $result->creditCard['cardType'],
					'month' => $result->creditCard['expirationMonth'],
					'year' => $result->creditCard['expirationYear'],
					'location' => $result->creditCard['customerLocation'],
					'holdername' => $result->creditCard['cardholderName'],
				);
				foreach ($result->statusHistory as $status) {
					$return['status_history'][] = $this->_parse_result($status);
				}

				$return['plan_id'] = $result->planId;
				$return['subscription_id'] = $result->subscriptionId;
				$return['subscription'] = array(
					'period_end' => $result->subscription['billingPeriodEndDate'],
					'period_start' => $result->subscription['billingPeriodStartDate'],
				);
				$return['descriptor'] = $this->_parse_result($result->descriptor);
				$return['creditcard_details'] = $this->_parse_result($result->creditCardDetails);
				$return['billing_details'] = $this->_parse_result($result->billingDetails);
				$return['shipping_details'] = $this->_parse_result($result->shippingDetails);
				$return['subscription_details'] = $this->_parse_result($result->subscriptionDetails);
				$return['addons'] = $result->addOns;
				$return['discounts'] = $result->discounts;
				isset($result->paypalDetails) && $return['paypal_details'] = $this->_parse_result($result->paypalDetails);
				break;
			case 'Braintree_Transaction_StatusDetails':
				$return['timestamp'] = $result->timestamp;
				$return['status'] = $result->status;
				$return['amount'] = $result->amount;
				$return['user'] = $result->user;
				$return['transaction_source'] = $result->transactionSource;
				break;
			case 'Braintree_Descriptor':
				$return['name'] = $result->name;
				$return['phone'] = $result->phone;
				break;
			case 'Braintree_Transaction_PayPalDetails':
				$return['token'] = $result->token;
				$return['payer_email'] = $result->payerEmail;
				$return['payment_id'] = $result->paymentId;
				$return['authorization_id'] = $result->authorizationId;
				$return['image_url'] = $result->imageUrl;
				$return['debug_id'] = $result->debugId;
				$return['payee_email'] = $result->payeeEmail;
				break;
			case 'Braintree_PayPalAccount':
				$return['token'] = $result->token;
				$return['email'] = $result->email;
				$return['default'] = $result->default;
				$return['image_url'] = $result->imageUrl;
				break;
		}
		return $return;
	}

	private function _data_build($options)
	{
		$data = array();
		!empty($options['first_name']) && $data['firstName'] = $options['first_name'];
		!empty($options['last_name']) && $data['lastName'] = $options['last_name'];
		!empty($options['company']) && $data['company'] = $options['company'];
		!empty($options['merchant_customer_id']) && $data['id'] = $options['merchant_customer_id'];
		!empty($options['email']) && $data['email'] = $options['email'];
		!empty($options['phone']) && $data['phone'] = $options['phone'];
		!empty($options['fax']) && $data['fax'] = $options['fax'];
		!empty($options['website']) && $data['website'] = $options['website'];
		isset($options['device_data']) && $data['deviceData'] = $options['device_data'];

		if($options['_creditcard'] instanceof Merchant_Billing_CreditCard) {
			$creditcard = $options['_creditcard'];
			$data['creditCard'] = array(
				'expirationDate' => date('m/y',$creditcard->expire_date()->expiration()),
				'cardholderName' => $creditcard->name(),
				'cvv' => $creditcard->verification_value,
			);
			// invalid card number means do not update
			!empty($creditcard->number) && $data['creditCard']['number'] = $creditcard->number;
			if(isset($options['billing_address_id'])) {
				$data['creditCard']['billingAddressId'] = $options['billing_address_id'];
			}
			if(isset($options['options'])) {
				isset($options['options']['verify_card']) && $data['creditCard']['options']['verifyCard'] = $options['options']['verify_card'];
				!empty($options['options']['update_token']) && $data['creditCard']['options']['updateExistingToken'] = $options['options']['update_token'];
			}
		}
		if(!empty($options['payment_nonce'])){
			$data['creditCard'] = array(
				'paymentMethodNonce' => $options['payment_nonce'],
			);
			if(isset($options['billing_address_id'])) {
				$data['creditCard']['billingAddressId'] = $options['billing_address_id'];
			}
			if(isset($options['options'])) {
				$data['creditCard']['options'] = array();
				isset($options['options']['verify_card']) && $data['creditCard']['options']['verifyCard'] = $options['options']['verify_card'];
				!empty($options['options']['update_token']) && $data['creditCard']['options']['updateExistingToken'] = $options['options']['update_token'];
			}
		}
		return $data;
	}
	// To void a transaction, the status must be authorized or submitted for settlement.
	public function void($authorization, $options = array())
	{
		return $this->commit('void',$authorization);
	}

	public function credit($money=NULL, $identification, $options = array())
	{
		if(is_numeric($money))
		{
			$money = $this->amount($money);
		}
		return $this->commit('refund',array('transaction_id'=>$identification,'amount'=>$money));
	}

	public function capture($money=NULL, $authorization, $options = array())
	{
		if(is_numeric($money))
		{
			$money = $this->amount($money);
		}
		return $this->commit('settle',array('transaction_id'=>$authorization,'amount'=>$money));

	}
	private function _transaction($money, Merchant_Billing_CreditCard $creditcard = NULL, $options = array())
	{
		$amount = $this->amount($money);
		$data = $this->_transaction_data_build(array_merge(array('_creditcard'=>$creditcard,'amount'=>$amount),$options));
		return $this->commit('sale',$data);
	}
	public function purchase($money, Merchant_Billing_CreditCard $creditcard = NULL, $options = array())
	{
		$options['settle'] = true;
		return $this->_transaction($money, $creditcard, $options);
	}

	public function authorize($money, Merchant_Billing_CreditCard $creditcard = NULL, $options = array())
	{
		$options['settle'] = false;
		return $this->_transaction($money, $creditcard, $options);
	}

	private function _transaction_data_build($options)
	{
		$this->required_options('amount', $options);
		$data = array(
			'amount'=>$options['amount'],
		);
		!empty($options['order_id']) && $data['orderId'] = $options['order_id'];
		!empty($options['merchant_account_id']) && $data['merchantAccountId'] = $options['merchant_account_id'];
		!empty($options['recurring']) && $data['recurring'] = $options['recurring'];

		$data['creditCard'] = array();
		if($options['_creditcard'] instanceof Merchant_Billing_CreditCard) {
			$data['creditCard']['number'] = $options['_creditcard']->number;
			$data['creditCard']['expirationDate'] = date('m/y',$options['_creditcard']->expire_date()->expiration());
			$options['_creditcard']->name()!='' && $data['creditCard']['cardholderName'] = $options['_creditcard']->name();
			!empty($options['_creditcard']->verification_value) && $data['creditCard']['cvv'] = $options['_creditcard']->verification_value;
			// store this card on vault
			!empty($options['token']) && $data['creditCard']['token'] = $options['token'];
		}elseif(!empty($options['payment_nonce'])){
			$data['paymentMethodNonce'] = $options['payment_nonce'];
		}else{
			// use recorded vault record for card details
			$this->required_options('token', $options);
			$data['paymentMethodToken'] = $options['token'];
		}

		// use vault saved customer record
		if(!empty($options['merchant_customer_id'])) {
			$data['customerId'] = $options['merchant_customer_id'];
		}else{
			$data['customer'] = array();
			// for vault store
			!empty($options['customer_id']) && $data['customer']['id'] = $options['customer_id'];
			!empty($options['first_name']) && $data['customer']['firstName'] = $options['first_name'];
			!empty($options['last_name']) && $data['customer']['lastName'] = $options['last_name'];
			!empty($options['company']) && $data['customer']['company'] = $options['company'];
			!empty($options['email']) && $data['customer']['email'] = $options['email'];
			!empty($options['phone']) && $data['customer']['phone'] = $options['phone'];
			!empty($options['fax']) && $data['customer']['fax'] = $options['fax'];
			!empty($options['website']) && $data['customer']['website'] = $options['website'];
		}

		$data['billing'] = array();
		if(!empty($options['billing_address'])) {
			$billing_address = explode('|',wordwrap($options['billing_address'],255,'|'));
			$data['billing']['streetAddress'] = array_shift($billing_address);
			$data['billing']['extendedAddress'] = array_shift($billing_address);
		}
		!empty($options['billing_first_name']) && $data['billing']['firstName'] = $options['billing_first_name'];
		!empty($options['billing_last_name']) && $data['billing']['lastName'] = $options['billing_last_name'];
		!empty($options['billing_company']) && $data['billing']['company'] = $options['billing_company'];
		!empty($options['billing_city']) && $data['billing']['locality'] = $options['billing_city'];
		!empty($options['billing_state']) && $data['billing']['region'] = $options['billing_state'];
		!empty($options['billing_zip']) && $data['billing']['postalCode'] = $options['billing_zip'];
		!empty($options['billing_country']) && $data['billing']['countryCodeAlpha3'] = Merchant_Country::find($options['billing_country'])->code('alpha3')->__toString();

		$data['shipping'] = array();
		if(!empty($options['shipping_address'])) {
			$shipping_address = explode('|',wordwrap($options['shipping_address'],255,'|'));
			$data['shipping']['streetAddress'] = array_shift($shipping_address);
			$data['shipping']['extendedAddress'] = array_shift($shipping_address);
		}
		!empty($options['shipping_first_name']) && $data['shipping']['firstName'] = $options['shipping_first_name'];
		!empty($options['shipping_last_name']) && $data['shipping']['lastName'] = $options['shipping_last_name'];
		!empty($options['shipping_company']) && $data['shipping']['company'] = $options['shipping_company'];
		!empty($options['shipping_city']) && $data['shipping']['locality'] = $options['shipping_city'];
		!empty($options['shipping_state']) && $data['shipping']['region'] = $options['shipping_state'];
		!empty($options['shipping_zip']) && $data['shipping']['postalCode'] = $options['shipping_zip'];
		!empty($options['shipping_country']) && $data['shipping']['countryCodeAlpha3'] = Merchant_Country::find($options['shipping_country'])->code('alpha3')->__toString();

		!empty($options['invoice_number']) && $data['purchaseOrderNumber'] = $options['invoice_number'];
		// only This amount is not automatically added to the total amount of this transaction
		// you have to manually add the tax amount to the transaction's amount
		!empty($options['tax_amount']) && $data['taxAmount'] = $options['tax_amount'];
		$data['options'] = array();
		isset($options['settle']) && $data['options']['submitForSettlement'] = $options['settle'];
		isset($options['store_in_vault_on_success']) && $data['options']['storeInVaultOnSuccess'] = $options['store_in_vault_on_success'];
		isset($options['add_billing_address_to_payment_method']) && $data['options']['addBillingAddressToPaymentMethod'] = $options['add_billing_address_to_payment_method'];
		isset($options['tax']) && $data['taxExempt'] = $options['tax'];
		isset($options['device_data']) && $data['deviceData'] = $options['device_data'];
		if(isset($options['custom_fields']) && is_array($options['custom_fields'])) {
			$data['customFields'] = $options['custom_fields'];
		}

		$descriptor = array();
		!empty($options['descriptor_name']) && $descriptor['name'] = $options['descriptor_name'];
		!empty($options['descriptor_phone']) && $descriptor['phone'] = $options['descriptor_phone'];
		if(count($descriptor)>0) {
			$data['descriptor'] = $descriptor;
		}
		return $data;
	}

	public function update($customer_vault_id, Merchant_Billing_CreditCard $creditcard = NULL, $options)
	{
		$data = $this->_data_build(array_merge(array('_creditcard'=>$creditcard),$options));
		return $this->commit('update',array_merge(array('_merchant_customer_id'=>$customer_vault_id),$data));
	}

	public function store(Merchant_Billing_CreditCard $creditcard = NULL, $options)
	{
		$data = $this->_data_build(array_merge(array('_creditcard'=>$creditcard),$options));
		return $this->commit('store',$data);
	}

	public function unstore(Merchant_Billing_CreditCard $creditcard = NULL, $customer_vault_id = NULL)
	{
		if(is_null($customer_vault_id)) {
			throw new Merchant_Billing_Exception("Customer vault id is required!");
		}
		return $this->commit('unstore',$customer_vault_id);
	}

	// disabled credit to creditcard transactions by default
	public function credit_to_creditcard($money, $identification = NULL, $options = array())
	{
		if(is_null($identification)) {
			return $this->commit('credit',array('token'=>$identification,'amount'=>$money));
		}else{
			$this->required_options('card_number,card_month,card_year', $options);
			return $this->commit('credit',array(
				'amount' => $money,
				'creditCard' => array(
					'number' => $options['card_number'],
					'expirationDate' => $options['card_month'].'/'.$options['card_year'],
				)
			));
		}
	}

	public function get_customer_profile($options)
	{
		$this->required_options('customer_profile_id', $options);
		return $this->commit('customer_find',$options['customer_profile_id']);
	}

	public function get_transaction($transaction_id)
	{
		return $this->commit('transaction_find',$transaction_id);
	}

	public function amount($money)
	{
		if (!is_numeric($money) || $money < 0) {
			throw new Merchant_Billing_Exception('money amount must be a positive Integer in cents.');
		}

		return number_format($money, 2, '.', '');
	}

	public function generate_unique_id($options = NULL)
	{
		$opts = array();
		isset($options['merchant_account_id']) && $opts['merchantAccountId'] = $options['merchant_account_id'];
		isset($options['customer_id']) && $opts['customerId'] = $options['customer_id'];
		return Braintree_ClientToken::generate($opts);
	}
}


text:
<?php

namespace Magento\Catalog\Block\Product\View\Options\Type;

/**
 * Detail options text type block
 *
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class Date extends \Magento\Catalog\Block\Product\View\Options\AbstractOptions
{
    /**
     * Fill date and time options with leading zeros or not
     *
     * @var boolean
     */
    protected $_fillLeadingZeros = true;

    /**
     * Catalog product option type date
     *
     * @var \Magento\Catalog\Model\Product\Option\Type\Date
     */
    protected $_catalogProductOptionTypeDate;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Framework\Pricing\Helper\Data $pricingHelper
     * @param \Magento\Catalog\Helper\Data $catalogData
     * @param \Magento\Catalog\Model\Product\Option\Type\Date $catalogProductOptionTypeDate
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Framework\Pricing\Helper\Data $pricingHelper,
        \Magento\Catalog\Helper\Data $catalogData,
        \Magento\Catalog\Model\Product\Option\Type\Date $catalogProductOptionTypeDate,
        array $data = []
    ) {
        $this->_catalogProductOptionTypeDate = $catalogProductOptionTypeDate;
        parent::__construct($context, $pricingHelper, $catalogData, $data);
    }

    /**
     * Use JS calendar settings
     *
     * @return boolean
     */
    public function useCalendar()
    {
        return $this->_catalogProductOptionTypeDate->useCalendar();
    }

    /**
     * Date input
     *
     * @return string Formatted Html
     */
    public function getDateHtml()
    {
        if ($this->useCalendar()) {
            return $this->getCalendarDateHtml();
        } else {
            return $this->getDropDownsDateHtml();
        }
    }

    /**
     * JS Calendar html
     *
     * @return string Formatted Html
     */
    public function getCalendarDateHtml()
    {
        $option = $this->getOption();
        $value = $this->getProduct()->getPreconfiguredValues()->getData('options/' . $option->getId() . '/date');

        $yearStart = $this->_catalogProductOptionTypeDate->getYearStart();
        $yearEnd = $this->_catalogProductOptionTypeDate->getYearEnd();

        $calendar = $this->getLayout()->createBlock(
            'Magento\Framework\View\Element\Html\Date'
        )->setId(
            'options_' . $this->getOption()->getId() . '_date'
        )->setName(
            'options[' . $this->getOption()->getId() . '][date]'
        )->setClass(
            'product-custom-option datetime-picker input-text'
        )->setImage(
            $this->getViewFileUrl('Magento_Theme::calendar.png')
        )->setDateFormat(
            $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT)
        )->setValue(
            $value
        )->setYearsRange(
            $yearStart . ':' . $yearEnd
        );

        return $calendar->getHtml();
    }

    /**
     * Date (dd/mm/yyyy) html drop-downs
     *
     * @return string Formatted Html
     */
    public function getDropDownsDateHtml()
    {
        $fieldsSeparator = ' ';
        $fieldsOrder = $this->_catalogProductOptionTypeDate->getConfigData('date_fields_order');
        $fieldsOrder = str_replace(',', $fieldsSeparator, $fieldsOrder);

        $monthsHtml = $this->_getSelectFromToHtml('month', 1, 12);
        $daysHtml = $this->_getSelectFromToHtml('day', 1, 31);

        $yearStart = $this->_catalogProductOptionTypeDate->getYearStart();
        $yearEnd = $this->_catalogProductOptionTypeDate->getYearEnd();
        $yearsHtml = $this->_getSelectFromToHtml('year', $yearStart, $yearEnd);

        $translations = ['d' => $daysHtml, 'm' => $monthsHtml, 'y' => $yearsHtml];
        return strtr($fieldsOrder, $translations);
    }

    /**
     * Time (hh:mm am/pm) html drop-downs
     *
     * @return string Formatted Html
     */
    public function getTimeHtml()
    {
        if ($this->_catalogProductOptionTypeDate->is24hTimeFormat()) {
            $hourStart = 0;
            $hourEnd = 23;
            $dayPartHtml = '';
        } else {
            $hourStart = 1;
            $hourEnd = 12;
            $dayPartHtml = $this->_getHtmlSelect(
                'day_part'
            )->setOptions(
                ['am' => __('AM'), 'pm' => __('PM')]
            )->getHtml();
        }
        $hoursHtml = $this->_getSelectFromToHtml('hour', $hourStart, $hourEnd);
        $minutesHtml = $this->_getSelectFromToHtml('minute', 0, 59);

        return $hoursHtml . ' <b>:</b> ' . $minutesHtml . ' ' . $dayPartHtml;
    }

    /**
     * Return drop-down html with range of values
     *
     * @param string $name Id/name of html select element
     * @param int $from  Start position
     * @param int $to    End position
     * @param int|null $value Value selected
     * @return string Formatted Html
     */
    protected function _getSelectFromToHtml($name, $from, $to, $value = null)
    {
        $options = [['value' => '', 'label' => '-']];
        for ($i = $from; $i <= $to; $i++) {
            $options[] = ['value' => $i, 'label' => $this->_getValueWithLeadingZeros($i)];
        }
        return $this->_getHtmlSelect($name, $value)->setOptions($options)->getHtml();
    }

    /**
     * HTML select element
     *
     * @param string $name Id/name of html select element
     * @param int|null $value
     * @return mixed
     */
    protected function _getHtmlSelect($name, $value = null)
    {
        $option = $this->getOption();

        $this->setSkipJsReloadPrice(1);

        // $require = $this->getOption()->getIsRequire() ? ' required-entry' : '';
        $require = '';
        $select = $this->getLayout()->createBlock(
            'Magento\Framework\View\Element\Html\Select'
        )->setId(
            'options_' . $this->getOption()->getId() . '_' . $name
        )->setClass(
            'product-custom-option admin__control-select datetime-picker' . $require
        )->setExtraParams()->setName(
            'options[' . $option->getId() . '][' . $name . ']'
        );

        $extraParams = 'style="width:auto"';
        if (!$this->getSkipJsReloadPrice()) {
            $extraParams .= ' onchange="opConfig.reloadPrice()"';
        }
        $extraParams .= ' data-role="calendar-dropdown" data-calendar-role="' . $name . '"';
        $extraParams .= ' data-selector="' . $select->getName() . '"';
        if ($this->getOption()->getIsRequire()) {
            $extraParams .= ' data-validate=\'{"datetime-validation": true}\'';
        }

        $select->setExtraParams($extraParams);
        if ($value === null) {
            $value = $this->getProduct()->getPreconfiguredValues()->getData(
                'options/' . $option->getId() . '/' . $name
            );
        }
        if ($value !== null) {
            $select->setValue($value);
        }

        return $select;
    }

    /**
     * Add Leading Zeros to number less than 10
     *
     * @param int $value
     * @return string|int
     */
    protected function _getValueWithLeadingZeros($value)
    {
        if (!$this->_fillLeadingZeros) {
            return $value;
        }
        return $value < 10 ? '0' . $value : $value;
    }
}


text:
use {
    System, Planner,
    Application,
    World, EntityBuilder,
    ApplicationConfig,
};
use std::fmt;

/// Application builder, to simplify registering components and adding systems.
///
pub struct ApplicationBuilder<E> {
    /// Becomes true when components have been registered.
    lock: bool,
    /// Specs process planner.
    pub planner: Planner<()>,
    pub cfg: ApplicationConfig<E>,
}

impl <E>fmt::Debug for ApplicationBuilder<E> {
    //stub for now. wtf specs for not implementing debug.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
       write!(f, "<EvilBuilder>")
   }
}

impl <E>ApplicationBuilder<E>
where E: Sized + Send + Clone + 'static {

    /// Create a new `ApplicationBuilder` object.
    ///
    pub fn new(config: ApplicationConfig<E>) -> ApplicationBuilder<E> {

        ApplicationBuilder {
            lock: false,
            planner: Planner::new(World::new(),config.num_threads-1),
            cfg: config
        }
    }

    /// Runs the closure giving a specs World.
    ///
    pub fn register<F>(mut self, func: F) -> ApplicationBuilder<E>
    where F: FnOnce(&mut World) -> () {
        func(self.planner.mut_world());
        self. lock = true;
        self
    }

    /// Add a System to execution planner.
    ///
    /// A system is just a object that implements the System trait from specs.
    ///
    pub fn with_system<S>(mut self, sys: S, name: &str, priority: i32) -> ApplicationBuilder<E>
    where S: System<()> + 'static {
        info!(self.cfg.logger, "Added {} to planner.",name);
        {
            self.planner.add_system::<S>(sys,name,priority);
        }
        self
    }

    /// Add an entity to the world before application start.
    ///
    pub fn with_entity<F>(mut self, func: F) -> ApplicationBuilder<E>
    where F: FnOnce(EntityBuilder) -> EntityBuilder {
        if self.lock {
            func(self.planner.mut_world().create_now()).build();
        } else {
            error!(self.cfg.logger, "Attempted to add entity before any components were registered!");
            panic!();
        }
        self
    }

    /// Complete build process and generate the Application.
    pub fn done(self) -> Application<E> {
        let a: Application<E> = From::from(self);
        a
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use { EventContext, ApplicationConfig, RunArg, Component, State, System, VecStorage };

    struct TestSystem;

    impl System<()> for TestSystem {
        fn run(&mut self, _: RunArg, _: ()) {}
    }
    #[derive(Clone)]
    struct TestContext;
    impl EventContext for TestContext {
        type Event = &'static str;
        fn next_event(&mut self) -> Option<&'static str> {
            Some("string")
        }

        fn send_event(&mut self, _: &'static str) {}
    }

    unsafe impl Send for TestContext {}

    struct STATE;
    struct COMP{
        data: u8
    }
    impl Component for COMP {
        type Storage = VecStorage<COMP>;
    }

    impl State for STATE {
        type Event = &'static str;
        fn name(&self) -> Option<&str> {
            Some("my_test_state")
        }
    }
    #[test]
    fn creation() {
        let mut c = ApplicationConfig::new(Box::new(TestContext));
        c.add_initial_state(Box::new(STATE));
        let _ = ApplicationBuilder::new(c).done();
    }

    #[test]
    fn register() {
        let mut c = ApplicationConfig::new(Box::new(TestContext));
        c.add_initial_state(Box::new(STATE));
        let _ = ApplicationBuilder::new(c)
                    .register(|w|{
                        w.register::<COMP>();
                    })
                    .done();
    }

    #[test]
    fn add_entity() {
        let my_object = COMP { data: 123 };
        let mut c = ApplicationConfig::new(Box::new(TestContext));
        c.add_initial_state(Box::new(STATE));
        let _ = ApplicationBuilder::new(c)
                                .register(|w|{
                                    w.register::<COMP>();
                                })
                                .with_entity(|w|{
                                    w.with(my_object)
                                }).done();
    }
    #[test]
    fn add_system() {
        let sys = TestSystem;
        let mut c = ApplicationConfig::new(Box::new(TestContext));
        c.add_initial_state(Box::new(STATE));
        let _ = ApplicationBuilder::new(c)
                                .with_system(sys,"test_system",0)
                                .register(|w|{
                                    w.register::<COMP>();
                                }).done();

    }
}


text:
<?php
class Example{

private static $table="users";

public static function login($params=null){
	$user=Database::get(App::DB('main'),'UserName,Password',self::$table,"WHERE UserName = ?",array($params['UserName']));
	if(Password::equals($params['Password'],$user['Password'][0])){Session::write("User",$user['UserName'][0]);return true;}
	else{return false;}

	}

public static function add_user($params=null){
	//Method 1
	//$add_user=Database::insert(App::DB('main'),self::$table,$params);

	//Method 2 ---> The $params was not passed which can be deleted on your code if using method 2.
	$params =array ("UserName"=>$_POST['UserName'],"Password"=>Password::set($_POST['Password']),"Email"=>$_POST['Email'],
						  "Code"=>App::randcode(),"Photo"=>$_FILES['Photo']['name'],"CreatedOn"=>App::createdon());
	$add_user=Database::insert(App::DB('main'),self::$table,$params);

	//Do not comment the below lines.
	return $add_user;
	}

public static function resetpwd(){

	$resetpwd=Database::get(App::DB('main'),"UserName, Code",self::$table,"WHERE Email = ?",array($_POST['Email']));
	return $resetpwd;

	}

public  static function setnewpwd(){

	$setnewpwd=Database::update(App::DB('main'),self::$table,'Password',Password::set($_POST['Password']), array('Code','=',$_POST['Code']));
	$setnewpwd=Database::update(App::DB('main'),self::$table,'Code',App::randcode(), array('Code','=',$_POST['Code']));
	return $setnewpwd;

	}

	}


text:
package com.intellij.java.codeInsight.daemon.quickFix;

import com.intellij.codeInsight.daemon.quickFix.LightQuickFixTestCase;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.SkipSlowTestLocally;

@SkipSlowTestLocally
public class CreateMethodFromUsagePerformanceTest extends LightQuickFixTestCase {

  public void testWithHugeNumberOfParameters() {
    PlatformTestUtil.startPerformanceTest("5000 args for a new method", 400_000, () -> {
      String text = "class Foo {{ f<caret>oo(" + StringUtil.repeat("\"a\", ", 5000) + " \"a\");}}";
      configureFromFileText("Foo.java", text);
      doAction("Create method 'foo'");
    })
      .assertTiming();
  }

  @Override
  protected String getBasePath() {
    return "/codeInsight/daemonCodeAnalyzer/quickFix/createMethodFromUsage";
  }

}


text:
using UnityEngine;
using UnityEditor;
using System;
using System.IO;

[InitializeOnLoad]
public class AndroidManifestManager
{
    static AndroidManifestManager()
    {
#if UNITY_ANDROID
        if (PlayerSettings.bundleIdentifier != "com.playfab.sampleproj") {
            CustomizeManifest ();
        }
#endif
    }

    public static void CustomizeManifest()
    {
        string appId = PlayerSettings.applicationIdentifier;

        if (String.IsNullOrEmpty(appId) || appId == "com.Company.ProductName")
        {
            EditorUtility.DisplayDialog("Android Manifest Reminder", "Your project does not currently have a bundle identifier set. If you wish to publish on Android, you must manually edit your Android manifest at Assets/Plugins/Android/AndroindManifest.xml and replace all occurances of {APP_BUNDLE_ID} with your bundle identifier", "OK");
            return;
        }

        TextAsset manifestAsset = (TextAsset)AssetDatabase.LoadMainAssetAtPath("Assets/Plugins/Android/AndroindManifest.xml");
        if (manifestAsset == null)
        {
            // No manifest to fix up
            return;
        }

        String manifestStr = manifestAsset.text;
        String fixedManifest = manifestStr.Replace("{APP_BUNDLE_ID}", appId);
        if (fixedManifest == manifestStr)
        {
            // no changes made
            return;
        }

        AssetDatabase.RenameAsset("Assets/Plugins/Android/AndroindManifest.xml", "Assets/Plugins/Android/AndroindManifest.xml.back");

        String path = Application.dataPath + "/Plugins/Android/AndroindManifest.xml";
        File.WriteAllText(path, fixedManifest);

        AssetDatabase.MoveAssetToTrash("Assets/PlayFabSDK/Editor/AndroidManifestManager.cs");

        AssetDatabase.Refresh();
    }
}


text:
package org.hl7.fhir.dstu3.model.codesystems;

// Generated on Tue, Dec 6, 2016 09:42-0500 for FHIR v1.8.0

import org.hl7.fhir.exceptions.FHIRException;

public enum V3GenderStatus {

        /**
         * Reproductively intact
         */
        I,
        /**
         * Reproductively neutered
         */
        N,
        /**
         * added to help the parsers
         */
        NULL;
        public static V3GenderStatus fromCode(String codeString) throws FHIRException {
            if (codeString == null || "".equals(codeString))
                return null;
        if ("I".equals(codeString))
          return I;
        if ("N".equals(codeString))
          return N;
        throw new FHIRException("Unknown V3GenderStatus code '"+codeString+"'");
        }
        public String toCode() {
          switch (this) {
            case I: return "I";
            case N: return "N";
            default: return "?";
          }
        }
        public String getSystem() {
          return "http://hl7.org/fhir/v3/GenderStatus";
        }
        public String getDefinition() {
          switch (this) {
            case I: return "Reproductively intact";
            case N: return "Reproductively neutered";
            default: return "?";
          }
        }
        public String getDisplay() {
          switch (this) {
            case I: return "Intact";
            case N: return "Neutered";
            default: return "?";
          }
    }

}


text:
namespace Envoy {
namespace Upstream {

ClusterManagerPtr ValidationClusterManagerFactory::clusterManagerFromProto(
    const envoy::config::bootstrap::v2::Bootstrap& bootstrap) {
  return std::make_unique<ValidationClusterManager>(
      bootstrap, *this, stats_, tls_, runtime_, random_, local_info_, log_manager_,
      main_thread_dispatcher_, admin_, api_, http_context_, time_system_);
}

CdsApiPtr
ValidationClusterManagerFactory::createCds(const envoy::api::v2::core::ConfigSource& cds_config,
                                           ClusterManager& cm) {
  // Create the CdsApiImpl...
  ProdClusterManagerFactory::createCds(cds_config, cm);
  // ... and then throw it away, so that we don't actually connect to it.
  return nullptr;
}

ValidationClusterManager::ValidationClusterManager(
    const envoy::config::bootstrap::v2::Bootstrap& bootstrap, ClusterManagerFactory& factory,
    Stats::Store& stats, ThreadLocal::Instance& tls, Runtime::Loader& runtime,
    Runtime::RandomGenerator& random, const LocalInfo::LocalInfo& local_info,
    AccessLog::AccessLogManager& log_manager, Event::Dispatcher& main_thread_dispatcher,
    Server::Admin& admin, Api::Api& api, Http::Context& http_context,
    Event::TimeSystem& time_system)
    : ClusterManagerImpl(bootstrap, factory, stats, tls, runtime, random, local_info, log_manager,
                         main_thread_dispatcher, admin, api, http_context),
      async_client_(api, time_system) {}

Http::ConnectionPool::Instance*
ValidationClusterManager::httpConnPoolForCluster(const std::string&, ResourcePriority,
                                                 Http::Protocol, LoadBalancerContext*) {
  return nullptr;
}

Host::CreateConnectionData
ValidationClusterManager::tcpConnForCluster(const std::string&, LoadBalancerContext*,
                                            Network::TransportSocketOptionsSharedPtr) {
  return Host::CreateConnectionData{nullptr, nullptr};
}

Http::AsyncClient& ValidationClusterManager::httpAsyncClientForCluster(const std::string&) {
  return async_client_;
}

} // namespace Upstream
} // namespace Envoy


text:
package org.apache.druid.common.config;

import com.google.common.base.Throwables;
import org.apache.druid.java.util.common.ISE;
import org.apache.logging.log4j.core.LifeCycle;
import org.apache.logging.log4j.core.util.Cancellable;
import org.apache.logging.log4j.core.util.ShutdownCallbackRegistry;

import javax.annotation.concurrent.GuardedBy;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class Log4jShutdown implements ShutdownCallbackRegistry, LifeCycle
{
  private static final long SHUTDOWN_WAIT_TIMEOUT_MILLIS = TimeUnit.MINUTES.toMillis(1);

  private final SynchronizedStateHolder state = new SynchronizedStateHolder(State.INITIALIZED);
  private final Queue<Runnable> shutdownCallbacks = new ConcurrentLinkedQueue<>();

  @Override
  public Cancellable addShutdownCallback(final Runnable callback)
  {
    if (callback == null) {
      throw new NullPointerException("callback");
    }
    if (!isStarted()) {
      throw new IllegalStateException("Not started");
    }
    final Cancellable cancellable = new Cancellable()
    {
      private volatile boolean cancelled = false;
      private final AtomicBoolean ran = new AtomicBoolean(false);

      @Override
      public void cancel()
      {
        cancelled = true;
      }

      @Override
      public void run()
      {
        if (!cancelled) {
          if (ran.compareAndSet(false, true)) {
            callback.run();
          }
        }
      }
    };
    shutdownCallbacks.add(cancellable);
    if (!isStarted()) {
      // We are shutting down in the middle of registering... Make sure the callback fires
      callback.run();
      throw new IllegalStateException("Shutting down while adding shutdown hook. Callback fired just in case");
    }
    return cancellable;
  }

  @Override
  public State getState()
  {
    return state.get();
  }

  @Override
  public void initialize()
  {
    // NOOP, state is always at least INITIALIZED
  }

  @Override
  public void start()
  {
    if (!state.compareAndSet(State.INITIALIZED, State.STARTED)) { // Skip STARTING
      throw new ISE("Expected state [%s] found [%s]", State.INITIALIZED, state.get());
    }
  }

  @Override
  public void stop()
  {
    if (!state.compareAndSet(State.STARTED, State.STOPPING)) {
      State current = state.waitForTransition(State.STOPPING, State.STOPPED, SHUTDOWN_WAIT_TIMEOUT_MILLIS);
      if (current != State.STOPPED) {
        throw new ISE("Expected state [%s] found [%s]", State.STARTED, current);
      }
      return;
    }
    try {
      runCallbacks();
    }
    finally {
      state.compareAndSet(State.STOPPING, State.STOPPED);
    }
  }

  private void runCallbacks()
  {
    RuntimeException e = null;
    for (Runnable callback = shutdownCallbacks.poll(); callback != null; callback = shutdownCallbacks.poll()) {
      try {
        callback.run();
      }
      catch (RuntimeException ex) {
        if (e == null) {
          e = new RuntimeException("Error running callback");
        }
        e.addSuppressed(ex);
      }
    }
    if (e != null) {
      throw e;
    }
  }

  @Override
  public boolean isStarted()
  {
    return State.STARTED.equals(getState());
  }

  @Override
  public boolean isStopped()
  {
    return State.STOPPED.equals(getState());
  }

  private static class SynchronizedStateHolder
  {
    @GuardedBy("this")
    private State current;

    private SynchronizedStateHolder(State initial)
    {
      current = initial;
    }

    private synchronized boolean compareAndSet(State expected, State transition)
    {
      if (current == expected) {
        return transition(transition);
      }
      return false;
    }

    /**
     * if current state is `expected`, wait it to be changed into `transition` state for `timeout` msec.
     * if it's not, return current state immediately.
     *
     * @return current state
     */
    private synchronized State waitForTransition(State expected, State transition, long timeout)
    {
      if (current == expected) {
        long remaining = timeout;
        try {
          long prev = System.currentTimeMillis();
          while (current != transition && remaining > 0) {
            wait(remaining);
            long now = System.currentTimeMillis();
            remaining -= now - prev;
            prev = now;
          }
        }
        catch (InterruptedException e) {
          throw Throwables.propagate(e);
        }
      }
      return current;
    }

    private synchronized boolean transition(State transition)
    {
      current = transition;
      notifyAll();
      return true;
    }

    private synchronized State get()
    {
      return current;
    }
  }
}


text:
package datastore

import (
	"context"

	"cloud.google.com/go/datastore"
	"github.com/ohsu-comp-bio/funnel/events"
	"github.com/ohsu-comp-bio/funnel/tes"
)

// WriteEvent writes a task event to the database.
func (d *Datastore) WriteEvent(ctx context.Context, e *events.Event) error {

	switch e.Type {

	case events.Type_TASK_CREATED:
		putKeys, putData := marshalTask(e.GetTask())
		_, err := d.client.PutMulti(ctx, putKeys, putData)
		return err

	case events.Type_EXECUTOR_STDOUT:
		_, err := d.client.Put(ctx, stdoutKey(e.Id, e.Attempt, e.Index), marshalEvent(e))
		return err

	case events.Type_EXECUTOR_STDERR:
		_, err := d.client.Put(ctx, stderrKey(e.Id, e.Attempt, e.Index), marshalEvent(e))
		return err

	case events.Type_SYSTEM_LOG:
		_, err := d.client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
			props := datastore.PropertyList{}
			err := tx.Get(sysLogsKey(e.Id, e.Attempt), &props)
			if err != nil && err != datastore.ErrNoSuchEntity {
				return err
			}

			p := &part{}
			err = datastore.LoadStruct(p, props)
			if err != nil {
				return err
			}

			_, err = tx.Put(sysLogsKey(e.Id, e.Attempt), &part{
				Type:       sysLogsPart,
				Attempt:    int(e.Attempt),
				Index:      int(e.Index),
				SystemLogs: append(p.SystemLogs, e.SysLogString()),
			})
			return err
		})
		return err

	default:
		_, err := d.client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
			props := datastore.PropertyList{}
			err := tx.Get(taskKey(e.Id), &props)
			if err == datastore.ErrNoSuchEntity {
				return tes.ErrNotFound
			}
			if err != nil {
				return err
			}

			task := &tes.Task{}
			if err := unmarshalTask(task, props); err != nil {
				return err
			}

			if e.Type == events.Type_TASK_STATE {
				from := task.State
				to := e.GetState()
				if err := tes.ValidateTransition(from, to); err != nil {
					return err
				}
			}

			tb := events.TaskBuilder{Task: task}
			err = tb.WriteEvent(context.Background(), e)
			if err != nil {
				return err
			}

			putKeys, putData := marshalTask(task)
			_, err = tx.PutMulti(putKeys, putData)
			return err
		})
		return err
	}
}


text:
/*!
 * \file
 * \brief Class module::Encoder_BCH_inter.
 */
#ifndef ENCODER_BCH_INTER_HPP_
#define ENCODER_BCH_INTER_HPP_

#include <vector>

#include "Tools/Code/BCH/BCH_polynomial_generator.hpp"
#include "Module/Encoder/BCH/Encoder_BCH.hpp"

namespace aff3ct
{
namespace module
{
template <typename B = int>
class Encoder_BCH_inter : public Encoder_BCH<B>
{
protected:
	std::vector<B> U_K_reordered;
	std::vector<B> par_reordered;

	std::vector<mipp::Reg<B>> regs_par;

public:
	Encoder_BCH_inter(const int& K, const int& N, const tools::BCH_polynomial_generator<B>& GF);

	virtual ~Encoder_BCH_inter() = default;

	virtual Encoder_BCH_inter<B>* clone() const;

protected:
	virtual void  _encode(const B *U_K, B *X_N, const size_t frame_id);
	virtual void __encode(const B *U_K, B *bb);
};
}
}

#endif // ENCODER_BCH_INTER_HPP_