text:
from collections import OrderedDict, namedtuple

from ..language.printer import print_ast
from ..utils.ast_from_value import ast_from_value
from .definition import (GraphQLArgument, GraphQLEnumType, GraphQLEnumValue,
                         GraphQLField, GraphQLInputObjectType,
                         GraphQLInterfaceType, GraphQLList, GraphQLNonNull,
                         GraphQLObjectType, GraphQLScalarType,
                         GraphQLUnionType)
from .directives import DirectiveLocation
from .scalars import GraphQLBoolean, GraphQLString

InputField = namedtuple('InputField', ['name', 'description', 'type', 'default_value'])
Field = namedtuple('Field', ['name', 'type', 'description', 'args', 'deprecation_reason'])

def input_fields_to_list(input_fields):
    fields = []
    for field_name, field in input_fields.items():
        fields.append(InputField(
            name=field_name,
            description=field.description,
            type=field.type,
            default_value=field.default_value))
    return fields

__Schema = GraphQLObjectType(
    '__Schema',
    description='A GraphQL Schema defines the capabilities of a GraphQL server. It '
                'exposes all available types and directives on the server, as well as '
                'the entry points for query, mutation and subscription operations.',
    fields=lambda: OrderedDict([
        ('types', GraphQLField(
            description='A list of all types supported by this server.',
            type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))),
            resolver=lambda schema, *_: schema.get_type_map().values(),
        )),
        ('queryType', GraphQLField(
            description='The type that query operations will be rooted at.',
            type=GraphQLNonNull(__Type),
            resolver=lambda schema, *_: schema.get_query_type(),
        )),
        ('mutationType', GraphQLField(
            description='If this server supports mutation, the type that '
                        'mutation operations will be rooted at.',
            type=__Type,
            resolver=lambda schema, *_: schema.get_mutation_type(),
        )),
        ('subscriptionType', GraphQLField(
            description='If this server support subscription, the type '
                        'that subscription operations will be rooted at.',
            type=__Type,
            resolver=lambda schema, *_: schema.get_subscription_type(),
        )),
        ('directives', GraphQLField(
            description='A list of all directives supported by this server.',
            type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))),
            resolver=lambda schema, *_: schema.get_directives(),
        )),
    ]))

_on_operation_locations = set(DirectiveLocation.OPERATION_LOCATIONS)
_on_fragment_locations = set(DirectiveLocation.FRAGMENT_LOCATIONS)
_on_field_locations = set(DirectiveLocation.FIELD_LOCATIONS)

__Directive = GraphQLObjectType(
    '__Directive',
    description='A Directive provides a way to describe alternate runtime execution and '
                'type validation behavior in a GraphQL document.'
                '\n\nIn some cases, you need to provide options to alter GraphQL\'s '
                'execution behavior in ways field arguments will not suffice, such as '
                'conditionally including or skipping a field. Directives provide this by '
                'describing additional information to the executor.',
    fields=lambda: OrderedDict([
        ('name', GraphQLField(GraphQLNonNull(GraphQLString))),
        ('description', GraphQLField(GraphQLString)),
        ('locations', GraphQLField(
            type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))),
        )),
        ('args', GraphQLField(
            type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),
            resolver=lambda directive, *args: input_fields_to_list(directive.args),
        )),
        ('onOperation', GraphQLField(
            type=GraphQLNonNull(GraphQLBoolean),
            deprecation_reason='Use `locations`.',
            resolver=lambda directive, *args: set(directive.locations) & _on_operation_locations,
        )),
        ('onFragment', GraphQLField(
            type=GraphQLNonNull(GraphQLBoolean),
            deprecation_reason='Use `locations`.',
            resolver=lambda directive, *args: set(directive.locations) & _on_fragment_locations,
        )),
        ('onField', GraphQLField(
            type=GraphQLNonNull(GraphQLBoolean),
            deprecation_reason='Use `locations`.',
            resolver=lambda directive, *args: set(directive.locations) & _on_field_locations,
        ))
    ]))

__DirectiveLocation = GraphQLEnumType(
    '__DirectiveLocation',
    description=(
        'A Directive can be adjacent to many parts of the GraphQL language, a ' +
        '__DirectiveLocation describes one such possible adjacencies.'
    ),
    values=OrderedDict([
        ('QUERY', GraphQLEnumValue(
            DirectiveLocation.QUERY,
            description='Location adjacent to a query operation.'
        )),
        ('MUTATION', GraphQLEnumValue(
            DirectiveLocation.MUTATION,
            description='Location adjacent to a mutation operation.'
        )),
        ('SUBSCRIPTION', GraphQLEnumValue(
            DirectiveLocation.SUBSCRIPTION,
            description='Location adjacent to a subscription operation.'
        )),
        ('FIELD', GraphQLEnumValue(
            DirectiveLocation.FIELD,
            description='Location adjacent to a field.'
        )),
        ('FRAGMENT_DEFINITION', GraphQLEnumValue(
            DirectiveLocation.FRAGMENT_DEFINITION,
            description='Location adjacent to a fragment definition.'
        )),
        ('FRAGMENT_SPREAD', GraphQLEnumValue(
            DirectiveLocation.FRAGMENT_SPREAD,
            description='Location adjacent to a fragment spread.'
        )),
        ('INLINE_FRAGMENT', GraphQLEnumValue(
            DirectiveLocation.INLINE_FRAGMENT,
            description='Location adjacent to an inline fragment.'
        )),
        ('SCHEMA', GraphQLEnumValue(
            DirectiveLocation.SCHEMA,
            description='Location adjacent to a schema definition.'
        )),
        ('SCALAR', GraphQLEnumValue(
            DirectiveLocation.SCALAR,
            description='Location adjacent to a scalar definition.'
        )),
        ('OBJECT', GraphQLEnumValue(
            DirectiveLocation.OBJECT,
            description='Location adjacent to an object definition.'
        )),
        ('FIELD_DEFINITION', GraphQLEnumValue(
            DirectiveLocation.FIELD_DEFINITION,
            description='Location adjacent to a field definition.'
        )),
        ('ARGUMENT_DEFINITION', GraphQLEnumValue(
            DirectiveLocation.ARGUMENT_DEFINITION,
            description='Location adjacent to an argument definition.'
        )),
        ('INTERFACE', GraphQLEnumValue(
            DirectiveLocation.INTERFACE,
            description='Location adjacent to an interface definition.'
        )),
        ('UNION', GraphQLEnumValue(
            DirectiveLocation.UNION,
            description='Location adjacent to a union definition.'
        )),
        ('ENUM', GraphQLEnumValue(
            DirectiveLocation.ENUM,
            description='Location adjacent to an enum definition.'
        )),
        ('ENUM_VALUE', GraphQLEnumValue(
            DirectiveLocation.ENUM_VALUE,
            description='Location adjacent to an enum value definition.'
        )),
        ('INPUT_OBJECT', GraphQLEnumValue(
            DirectiveLocation.INPUT_OBJECT,
            description='Location adjacent to an input object definition.'
        )),
        ('INPUT_FIELD_DEFINITION', GraphQLEnumValue(
            DirectiveLocation.INPUT_FIELD_DEFINITION,
            description='Location adjacent to an input object field definition.'
        )),
    ]))

class TypeKind(object):
    SCALAR = 'SCALAR'
    OBJECT = 'OBJECT'
    INTERFACE = 'INTERFACE'
    UNION = 'UNION'
    ENUM = 'ENUM'
    INPUT_OBJECT = 'INPUT_OBJECT'
    LIST = 'LIST'
    NON_NULL = 'NON_NULL'

class TypeFieldResolvers(object):
    _kinds = (
        (GraphQLScalarType, TypeKind.SCALAR),
        (GraphQLObjectType, TypeKind.OBJECT),
        (GraphQLInterfaceType, TypeKind.INTERFACE),
        (GraphQLUnionType, TypeKind.UNION),
        (GraphQLEnumType, TypeKind.ENUM),
        (GraphQLInputObjectType, TypeKind.INPUT_OBJECT),
        (GraphQLList, TypeKind.LIST),
        (GraphQLNonNull, TypeKind.NON_NULL),
    )

    @classmethod
    def kind(cls, type, *_):
        for klass, kind in cls._kinds:
            if isinstance(type, klass):
                return kind

        raise Exception('Unknown kind of type: {}'.format(type))

    @staticmethod
    def fields(type, args, *_):
        if isinstance(type, (GraphQLObjectType, GraphQLInterfaceType)):
            fields = []
            include_deprecated = args.get('includeDeprecated')
            for field_name, field in type.fields.items():
                if field.deprecation_reason and not include_deprecated:
                    continue
                fields.append(Field(
                    name=field_name,
                    description=field.description,
                    type=field.type,
                    args=field.args,
                    deprecation_reason=field.deprecation_reason
                ))
            return fields
        return None

    @staticmethod
    def interfaces(type, *_):
        if isinstance(type, GraphQLObjectType):
            return type.interfaces

    @staticmethod
    def possible_types(type, args, context, info):
        if isinstance(type, (GraphQLInterfaceType, GraphQLUnionType)):
            return info.schema.get_possible_types(type)

    @staticmethod
    def enum_values(type, args, *_):
        if isinstance(type, GraphQLEnumType):
            values = type.values
            if not args.get('includeDeprecated'):
                values = [v for v in values if not v.deprecation_reason]

            return values

    @staticmethod
    def input_fields(type, *_):
        if isinstance(type, GraphQLInputObjectType):
            return input_fields_to_list(type.fields)

__Type = GraphQLObjectType(
    '__Type',
    description='The fundamental unit of any GraphQL Schema is the type. There are '
                'many kinds of types in GraphQL as represented by the `__TypeKind` enum.'
                '\n\nDepending on the kind of a type, certain fields describe '
                'information about that type. Scalar types provide no information '
                'beyond a name and description, while Enum types provide their values. '
                'Object and Interface types provide the fields they describe. Abstract '
                'types, Union and Interface, provide the Object types possible '
                'at runtime. List and NonNull types compose other types.',
    fields=lambda: OrderedDict([
        ('kind', GraphQLField(
            type=GraphQLNonNull(__TypeKind),
            resolver=TypeFieldResolvers.kind
        )),
        ('name', GraphQLField(GraphQLString)),
        ('description', GraphQLField(GraphQLString)),
        ('fields', GraphQLField(
            type=GraphQLList(GraphQLNonNull(__Field)),
            args={
                'includeDeprecated': GraphQLArgument(
                    GraphQLBoolean,
                    default_value=False
                )
            },
            resolver=TypeFieldResolvers.fields
        )),
        ('interfaces', GraphQLField(
            type=GraphQLList(GraphQLNonNull(__Type)),
            resolver=TypeFieldResolvers.interfaces
        )),
        ('possibleTypes', GraphQLField(
            type=GraphQLList(GraphQLNonNull(__Type)),
            resolver=TypeFieldResolvers.possible_types
        )),
        ('enumValues', GraphQLField(
            type=GraphQLList(GraphQLNonNull(__EnumValue)),
            args={
                'includeDeprecated': GraphQLArgument(
                    GraphQLBoolean,
                    default_value=False
                )
            },
            resolver=TypeFieldResolvers.enum_values
        )),
        ('inputFields', GraphQLField(
            type=GraphQLList(GraphQLNonNull(__InputValue)),
            resolver=TypeFieldResolvers.input_fields
        )),
        ('ofType', GraphQLField(
            type=__Type,
            resolver=lambda type, *_: getattr(type, 'of_type', None)
        )),
    ]))

__Field = GraphQLObjectType(
    '__Field',
    description='Object and Interface types are described by a list of Fields, each of '
                'which has a name, potentially a list of arguments, and a return type.',
    fields=lambda: OrderedDict([
        ('name', GraphQLField(GraphQLNonNull(GraphQLString))),
        ('description', GraphQLField(GraphQLString)),
        ('args', GraphQLField(
            type=GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),
            resolver=lambda field, *_: input_fields_to_list(field.args)
        )),
        ('type', GraphQLField(GraphQLNonNull(__Type))),
        ('isDeprecated', GraphQLField(
            type=GraphQLNonNull(GraphQLBoolean),
            resolver=lambda field, *_: bool(field.deprecation_reason)
        )),
        ('deprecationReason', GraphQLField(
            type=GraphQLString,
            resolver=lambda field, *_: field.deprecation_reason
        ))
    ])
)

__InputValue = GraphQLObjectType(
    '__InputValue',
    description='Arguments provided to Fields or Directives and the input fields of an '
                'InputObject are represented as Input Values which describe their type '
                'and optionally a default value.',
    fields=lambda: OrderedDict([
        ('name', GraphQLField(GraphQLNonNull(GraphQLString))),
        ('description', GraphQLField(GraphQLString)),
        ('type', GraphQLField(GraphQLNonNull(__Type))),
        ('defaultValue', GraphQLField(
            type=GraphQLString,
            resolver=lambda input_val, *_:
            None if input_val.default_value is None
            else print_ast(ast_from_value(input_val.default_value, input_val))
        ))
    ]))

__EnumValue = GraphQLObjectType(
    '__EnumValue',
    description='One possible value for a given Enum. Enum values are unique values, not '
                'a placeholder for a string or numeric value. However an Enum value is '
                'returned in a JSON response as a string.',
    fields=lambda: OrderedDict([
        ('name', GraphQLField(GraphQLNonNull(GraphQLString))),
        ('description', GraphQLField(GraphQLString)),
        ('isDeprecated', GraphQLField(
            type=GraphQLNonNull(GraphQLBoolean),
            resolver=lambda field, *_: bool(field.deprecation_reason)
        )),
        ('deprecationReason', GraphQLField(
            type=GraphQLString,
            resolver=lambda enum_value, *_: enum_value.deprecation_reason,
        ))
    ]))

__TypeKind = GraphQLEnumType(
    '__TypeKind',
    description='An enum describing what kind of type a given `__Type` is',
    values=OrderedDict([
        ('SCALAR', GraphQLEnumValue(
            TypeKind.SCALAR,
            description='Indicates this type is a scalar.'
        )),
        ('OBJECT', GraphQLEnumValue(
            TypeKind.OBJECT,
            description='Indicates this type is an object. '
                        '`fields` and `interfaces` are valid fields.'
        )),
        ('INTERFACE', GraphQLEnumValue(
            TypeKind.INTERFACE,
            description='Indicates this type is an interface. '
                        '`fields` and `possibleTypes` are valid fields.'
        )),
        ('UNION', GraphQLEnumValue(
            TypeKind.UNION,
            description='Indicates this type is a union. '
                        '`possibleTypes` is a valid field.'
        )),
        ('ENUM', GraphQLEnumValue(
            TypeKind.ENUM,
            description='Indicates this type is an enum. '
                        '`enumValues` is a valid field.'
        )),
        ('INPUT_OBJECT', GraphQLEnumValue(
            TypeKind.INPUT_OBJECT,
            description='Indicates this type is an input object. '
                        '`inputFields` is a valid field.'
        )),
        ('LIST', GraphQLEnumValue(
            TypeKind.LIST,
            description='Indicates this type is a list. '
                        '`ofType` is a valid field.'
        )),
        ('NON_NULL', GraphQLEnumValue(
            TypeKind.NON_NULL,
            description='Indicates this type is a non-null. '
                        '`ofType` is a valid field.'
        )),
    ]))

IntrospectionSchema = __Schema

SchemaMetaFieldDef = GraphQLField(
    # name='__schema',
    type=GraphQLNonNull(__Schema),
    description='Access the current type schema of this server.',
    resolver=lambda source, args, context, info: info.schema,
    args={}
)

TypeMetaFieldDef = GraphQLField(
    type=__Type,
    # name='__type',
    description='Request the type information of a single type.',
    args={'name': GraphQLArgument(GraphQLNonNull(GraphQLString))},
    resolver=lambda source, args, context, info: info.schema.get_type(args['name'])
)

TypeNameMetaFieldDef = GraphQLField(
    type=GraphQLNonNull(GraphQLString),
    # name='__typename',
    description='The name of the current Object type at runtime.',
    resolver=lambda source, args, context, info: info.parent_type.name,
    args={}
)


text:
<hack>
  <title>Sport Betting</title>
  <author>DiemThuy</author>
  <version>DT FM</version>

    <file>
    <name>"database"</name>
<operation>
			<action>"sql"</action>
			<data><![CDATA[CREATE TABLE IF NOT EXISTS `{$db_prefix}betgames` (
  `id` int(11) NOT NULL auto_increment,
  `heading` varchar(50) collate utf8_unicode_ci NOT NULL default '',
  `undertext` varchar(150) collate utf8_unicode_ci NOT NULL default '',
  `endtime` int(11) NOT NULL,
  `active` int(1) NOT NULL default '0',
  `sort` int(1) NOT NULL default '0',
  `creator` varchar(20) collate utf8_unicode_ci NOT NULL,
  `fix` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;]]></data>
		</operation>

  <operation>
      <action>"sql"</action>
      <data><![CDATA[CREATE TABLE IF NOT EXISTS `{$db_prefix}betlog` (
  `id` int(11) NOT NULL auto_increment,
  `userid` int(11) NOT NULL default '0',
  `date` int(11) NOT NULL,
  `bonus` int(11) NOT NULL default '0',
  `msg` varchar(150) collate utf8_unicode_ci NOT NULL default '',
  PRIMARY KEY  (`id`),
  KEY `userid` (`userid`),
  KEY `userid_2` (`userid`,`bonus`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;]]></data>
    </operation>

  		<operation>
			<action>"sql"</action>
			<data><![CDATA[CREATE TABLE IF NOT EXISTS `{$db_prefix}betoptions` (
  `id` int(11) NOT NULL auto_increment,
  `gameid` int(11) NOT NULL default '0',
  `text` varchar(100) collate utf8_unicode_ci NOT NULL default '',
  `odds` double NOT NULL default '0',
  PRIMARY KEY  (`id`),
  KEY `gameid` (`gameid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;]]></data>
		</operation>
		<operation>
			<action>"sql"</action>
			<data><![CDATA[CREATE TABLE IF NOT EXISTS `{$db_prefix}bets` (
  `id` int(11) NOT NULL auto_increment,
  `gameid` int(11) NOT NULL default '0',
  `bonus` int(11) NOT NULL default '0',
  `optionid` int(11) NOT NULL default '0',
  `userid` int(11) NOT NULL default '0',
  `date` int(11) NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `gameid` (`gameid`),
  KEY `userid` (`userid`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;]]></data>
		</operation>
				<operation>
			<action>"sql"</action>
			<data><![CDATA[CREATE TABLE IF NOT EXISTS `{$db_prefix}bettop` (
  `userid` int(11) NOT NULL default '0',
  `bonus` int(11) NOT NULL default '0',
  PRIMARY KEY  (`userid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;]]></data>
		</operation>
		<operation>
			<action>"sql"</action>
			<data><![CDATA[INSERT INTO `{$db_prefix}settings` (`key`, `value`) VALUES ('min_bet', '3');]]></data>
		</operation>
				<operation>
			<action>"sql"</action>
			<data><![CDATA[INSERT INTO `{$db_prefix}settings` (`key`, `value`) VALUES ('fid_bet', '25');]]></data>
		</operation>
						<operation>
			<action>"sql"</action>
			<data><![CDATA[INSERT INTO `{$db_prefix}settings` (`key`, `value`) VALUES ('max_bon_bet', '200');]]></data>
		</operation>

		        <operation>
      <action>"sql"</action>
      <data><![CDATA[INSERT INTO `{$db_prefix}blocks` (`blockid`, `content`, `position`, `sortid`, `status`, `title`, `cache`, `minclassview`, `maxclassview`) VALUES
      (300, 'bet', 'r', 2, 1, 'BET', 'no', 3, 8);]]></data>
    </operation>
</file>

    <file>
    <name>"$DEFAULT_ROOT/index.php"</name>
<operation>
              <search><![CDATA[case 'news':
        require("$THIS_BASEPATH/news.php");
        $tpl->set("main_content",set_block($language["MANAGE_NEWS"],"center",$newstpl->fetch(load_template("news.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->News");
        break;]]></search>
          <action>"add"</action>
          <data><![CDATA[
// betting mod start

        case 'bet':
        require("$THIS_BASEPATH/bet.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$bettpl->fetch(load_template("bet.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betinfo':
        require("$THIS_BASEPATH/bet_info.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betinfotpl->fetch(load_template("bet_info.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betgameinfo':
        require("$THIS_BASEPATH/bet_gameinfo.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betgameinfotpl->fetch(load_template("bet_gameinfo.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betadmin':
        require("$THIS_BASEPATH/bet_admin.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betadmintpl->fetch(load_template("bet_admin.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'bettakeedit':
        require("$THIS_BASEPATH/bet_takeedit.php");
        break;

        case 'betactive':
        require("$THIS_BASEPATH/bet_active.php");
        break;

        case 'betaddoption':
        require("$THIS_BASEPATH/bet_addopt.php");
        break;

        case 'betdelgame':
        require("$THIS_BASEPATH/bet_delgame.php");
        break;

        case 'betdelopt':
        require("$THIS_BASEPATH/bet_delopt.php");
        break;

        case 'betopttwee':
        require("$THIS_BASEPATH/bet_opt2.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betopttweetpl->fetch(load_template("bet_opt2.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betodds':
        require("$THIS_BASEPATH/bet_odds.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betoddstpl->fetch(load_template("bet_odds.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betoddstwo':
        require("$THIS_BASEPATH/bet_odds2.php");

        break;

        case 'betaddonetwo':
        require("$THIS_BASEPATH/bet_add1x2.php");
        break;

        case 'bettakenew':
        require("$THIS_BASEPATH/bet_takenew.php");
        break;

        case 'betcoupon':
        require("$THIS_BASEPATH/bet_coupon.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betcoupontpl->fetch(load_template("bet_coupon.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betoption':
        require("$THIS_BASEPATH/bet_opt.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betopttpl->fetch(load_template("bet_opt.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betbonustop':
        require("$THIS_BASEPATH/bet_bonustop.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betbonustpl->fetch(load_template("bet_bonustop.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betback':
        require("$THIS_BASEPATH/bet_nullbet.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betbacktpl->fetch(load_template("bet_nullbet.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betfinish':
        require("$THIS_BASEPATH/bet_gamefinish.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betfinishtpl->fetch(load_template("bet_gamefinish.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;

        case 'betfinishtwo':
        require("$THIS_BASEPATH/bet_gamefinish2.php");
        $tpl->set("main_content",set_block($language["BETTING"],"center",$betfintwotpl->fetch(load_template("bet_gamefinish2.tpl"))));
        $tpl->set("main_title",$btit_settings["name"]." .::. "."Index->Betting");
        break;
// betting mod end
]]></data>
       <where>"after"</where>
    </operation>
 </file>

  <file>
    <name>"$DEFAULT_LANGUAGE_PATH/lang_main.php"</name>
    <operation>
     <search><![CDATA[?>]]></search>
      <action>"add"</action>
      <data><![CDATA[
$language["BETTING"]="Site Betting";
      ]]></data>
      <where>"before"</where>
    </operation>
   </file>

     <file>
    <name>"$DEFAULT_LANGUAGE_PATH/lang_blocks.php"</name>
    <operation>
      <search><![CDATA[?>]]></search>
      <action>"add"</action>
      <where>"before"</where>
      <data><![CDATA[
$language['BET']='Sport Betting';

      ]]></data>
    </operation>
  </file>

    <file>
    <name>"$DEFAULT_STYLE_PATH/admin.config.tpl"</name>
    <operation>
      <search><![CDATA[

       <input type="submit" name="write" class="btn" value="<tag:language.FRM_CONFIRM />" />	]]></search>
      <action>"add"</action>
      <where>"before"</where>
      <data><![CDATA[

      Sport Betting Settings

       Min ID level To Bet
      <input type="text" name="min_bet" value="<tag:config.min_bet />" size="7" />
      Int. Forum ID
      <input type="text" name="fid_bet" value="<tag:config.fid_bet />" size="7" />

      Max Bonus Points
      <input type="text" name="max_bon_bet" value="<tag:config.max_bon_bet />" size="7" />

     ]]></data>
    </operation>
  </file>

    <file>
        <name>"$DEFAULT_ROOT/admin/admin.config.php"</name>
        <operation>
            <search><![CDATA[$btit_settings["forum"]=$_POST["f_link"];]]></search>
            <action>"add"</action>
            <data><![CDATA[
          // bet
          $btit_settings["min_bet"]=$_POST["min_bet"];
          $btit_settings["fid_bet"]=$_POST["fid_bet"];
          $btit_settings["max_bon_bet"]=$_POST["max_bon_bet"];
          //bet
                    ]]></data>
      <where>"after"</where>
        </operation>
</file>

</hack>

redpajama_set_name: RedPajamaGithub


text:
package com.ibm.spark.magic

import java.net.{URL, URLClassLoader}

import com.google.common.reflect.ClassPath
import com.ibm.spark.magic.dependencies.DependencyMap

import scala.reflect.runtime.{universe => runtimeUniverse}
import scala.collection.JavaConversions._

class MagicLoader(
  val dependencyMap: DependencyMap = new DependencyMap(),
  urls: Array[URL] = Array(),
  parentLoader: ClassLoader = null
) extends URLClassLoader(urls, parentLoader)
{
  val magicPackage = "com.ibm.spark.magic.builtin"

  def hasMagic(name: String): Boolean = {
    val className = lowercaseClassMap(magicClassNames)
      .getOrElse(name.toLowerCase, name)
    try {
      this.loadClass(className) // Checks parent loadClass first
      true
    } catch {
      case _: Throwable => false
    }
  }

  override def loadClass(name: String, resolve: Boolean): Class[_] =
    try {
      super.loadClass(magicPackage + "." + name, resolve)
    } catch {
      case ex: ClassNotFoundException =>
        super.loadClass(name, resolve)
    }

  /**
   * Returns the class name for a case insensitive magic name query.
   * If no match is found, returns the query.
   * @param query a magic name, e.g. jAvasCRipt
   * @return the queried magic name's corresponding class, e.g. JavaScript
   */
  def magicClassName(query: String): String =
    lowercaseClassMap(magicClassNames).getOrElse(query.toLowerCase, query)

  /**
   * @return list of magic class names in magicPackage.
   */
  protected def magicClassNames : List[String] = {
    val classPath: ClassPath = ClassPath.from(this)
    val classes = classPath.getTopLevelClasses(magicPackage)
    classes.asList.map(_.getSimpleName).toList
  }

  /**
   * @param names list of class names
   * @return map of lowercase class names to class names
   */
  private def lowercaseClassMap(names: List[String]): Map[String, String] = {
    names.map(n => (n.toLowerCase, n)).toMap
  }

  protected def createMagicInstance(name: String) = {
    val magicClass = loadClass(name) // Checks parent loadClass first

    val runtimeMirror = runtimeUniverse.runtimeMirror(this)
    //val runtimeMirror = runtimeUniverse.runtimeMirror(magicClass.getClassLoader)

    val classSymbol = runtimeMirror.staticClass(magicClass.getCanonicalName)
    val classMirror = runtimeMirror.reflectClass(classSymbol)
    val selfType = classSymbol.selfType

    val classConstructorSymbol =
      selfType.declaration(runtimeUniverse.nme.CONSTRUCTOR).asMethod
    val classConstructorMethod =
      classMirror.reflectConstructor(classConstructorSymbol)

    val magicInstance = classConstructorMethod()

    // Add all of our dependencies to the new instance
    dependencyMap.internalMap.filter(selfType <:< _._1).values.foreach(
      _(magicInstance.asInstanceOf[MagicTemplate])
    )

    magicInstance
  }

  def executeMagic(name: String, code: String, isCell: Boolean): MagicOutput = {
    val magicInstance = createMagicInstance(name).asInstanceOf[MagicTemplate]

    if (isCell) {
      magicInstance.executeCell(code.split("\n"))
    } else {
      magicInstance.executeLine(code)
    }
  }
}


text:
package ftcbootstrap.demos.navbot;

import org.firstinspires.ftc.robotcontroller.external.samples.SensorMRColor;

import ftcbootstrap.BootstrapRegistrar;
import ftcbootstrap.demos.TelemetryTest;
import ftcbootstrap.demos.navbot.opmodes.EncoderMotorTest;
import ftcbootstrap.demos.navbot.opmodes.EncoderTestFromGamepadButtons;
import ftcbootstrap.demos.navbot.opmodes.EncoderTestFromGamepadSticks;
import ftcbootstrap.demos.navbot.opmodes.EncodersWithEventOpmode;
import ftcbootstrap.demos.navbot.opmodes.NavBotManual;
import ftcbootstrap.demos.navbot.opmodes.NavBotTelemetry;
import ftcbootstrap.demos.navbot.opmodes.NavigateWithEncoders;

/**
 * Register Op Modes
 */
public class NavBotRegistry extends BootstrapRegistrar {

    protected Class[] getOpmodeClasses() {
        Class[] classes = {

                NavigateWithEncoders.class,
                NavBotManual.class,
                EncodersWithEventOpmode.class,
                EncoderMotorTest.class,
                EncoderTestFromGamepadSticks.class,
                EncoderTestFromGamepadButtons.class,
                NavBotTelemetry.class,
                SensorMRColor.class,
                TelemetryTest.class
        };

        return classes;

    }
}


text: A small php script detects lan hosts up / down, minimise signal when no up host


text:
package org.apache.storm.solr.topology;

import org.apache.storm.generated.StormTopology;
import org.apache.storm.solr.config.SolrConfig;
import org.apache.storm.solr.schema.builder.RestJsonSchemaBuilderV2;
import org.apache.storm.topology.TopologyBuilder;
import org.apache.storm.solr.bolt.SolrUpdateBolt;
import org.apache.storm.solr.config.CountBasedCommit;
import org.apache.storm.solr.config.SolrCommitStrategy;
import org.apache.storm.solr.mapper.SolrFieldsMapper;
import org.apache.storm.solr.mapper.SolrMapper;
import org.apache.storm.solr.spout.SolrFieldsSpout;

import java.io.IOException;

public class SolrFieldsTopology extends SolrTopology {
        public static void main(String[] args) throws Exception {
            SolrFieldsTopology solrFieldsTopology = new SolrFieldsTopology();
            solrFieldsTopology.run(args);
        }

    protected SolrMapper getSolrMapper(SolrConfig solrConfig) throws IOException {
        return new SolrFieldsMapper.Builder(
                new RestJsonSchemaBuilderV2(solrConfig, COLLECTION), COLLECTION)
                    .setMultiValueFieldToken("%").build();
    }

    protected SolrCommitStrategy getSolrCommitStgy() {
        return new CountBasedCommit(2);         // To Commit to Solr and Ack according to the commit strategy
    }

    protected StormTopology getTopology() throws IOException {
        TopologyBuilder builder = new TopologyBuilder();
        builder.setSpout("SolrFieldsSpout", new SolrFieldsSpout());
        SolrConfig solrConfig = getSolrConfig();
        builder.setBolt("SolrUpdateBolt", new SolrUpdateBolt(solrConfig, getSolrMapper(solrConfig), getSolrCommitStgy()))
                .shuffleGrouping("SolrFieldsSpout");
        return builder.createTopology();
    }
}


text:
package com.leonti.slickpm.domain.dto;

import java.util.Date;

public class CommentDTO {

	private Integer id;

	private Integer taskId;

	private String content;

	private Date date;

	public CommentDTO() {
	}

	public CommentDTO(Integer id, Integer taskId, String content, Date date) {
		super();
		this.id = id;
		this.taskId = taskId;
		this.content = content;
		this.date = date;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getTaskId() {
		return taskId;
	}

	public void setTaskId(Integer taskId) {
		this.taskId = taskId;
	}
}


text:
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.feed.library.sharedstream.scroll;

import static com.google.common.truth.Truth.assertThat;

import static org.mockito.MockitoAnnotations.initMocks;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.annotation.Config;

import org.chromium.chrome.browser.feed.library.common.concurrent.testing.FakeMainThreadRunner;
import org.chromium.chrome.browser.feed.library.common.time.testing.FakeClock;
import org.chromium.testing.local.LocalRobolectricTestRunner;

import java.util.ArrayList;

/** Tests for {@link ScrollTracker}. */
@RunWith(LocalRobolectricTestRunner.class)
@Config(manifest = Config.NONE)
public final class ScrollTrackerTest {
    private static final long AGGREGATE_TIME_MS = 200L;
    private final FakeClock mClock = new FakeClock();
    private ScrollTrackerForTest mScrollTracker;
    private final FakeMainThreadRunner mMainThreadRunner = FakeMainThreadRunner.create(mClock);

    @Before
    public void setUp() {
        initMocks(this);
        mScrollTracker = new ScrollTrackerForTest(mMainThreadRunner, mClock);
    }

    @Test
    public void testSinglePositiveScroll_scrollWrongDirection() {
        mScrollTracker.trackScroll(10, 0);
        mClock.advance(AGGREGATE_TIME_MS);

        assertThat(mScrollTracker.scrollAmounts).isEmpty();
    }

    @Test
    public void testNoScroll() {
        mScrollTracker.trackScroll(0, 0);
        mClock.advance(AGGREGATE_TIME_MS);

        assertThat(mScrollTracker.scrollAmounts).isEmpty();
    }

    @Test
    public void testSinglePositiveScroll_notEnoughTime() {
        mScrollTracker.trackScroll(0, 10);
        mClock.advance(AGGREGATE_TIME_MS - 1);

        assertThat(mScrollTracker.scrollAmounts).isEmpty();
    }

    @Test
    public void testSinglePositiveScroll() {
        mScrollTracker.trackScroll(0, 10);
        mClock.advance(AGGREGATE_TIME_MS);

        assertThat(mScrollTracker.scrollAmounts).containsExactly(10);
    }

    @Test
    public void testDoublePositiveScroll_singleTask() {
        mScrollTracker.trackScroll(0, 10);
        mScrollTracker.trackScroll(0, 5);
        mClock.advance(AGGREGATE_TIME_MS);

        assertThat(mScrollTracker.scrollAmounts).containsExactly(15);
    }

    @Test
    public void testDoublePositiveScroll_doubleTask() {
        mScrollTracker.trackScroll(0, 10);
        mClock.advance(AGGREGATE_TIME_MS);
        mScrollTracker.trackScroll(0, 5);
        mClock.advance(AGGREGATE_TIME_MS);

        assertThat(mScrollTracker.scrollAmounts).containsExactly(10, 5).inOrder();
    }

    @Test
    public void testSwitchScroll() {
        mScrollTracker.trackScroll(0, 10);
        mClock.advance(1L);
        mScrollTracker.trackScroll(0, -5);
        mClock.advance(AGGREGATE_TIME_MS);

        assertThat(mScrollTracker.scrollAmounts).containsExactly(10, -5).inOrder();
    }

    static class ScrollTrackerForTest extends ScrollTracker {
        public ArrayList<Integer> scrollAmounts;

        ScrollTrackerForTest(FakeMainThreadRunner mainThreadRunner, FakeClock clock) {
            super(mainThreadRunner, clock);
            scrollAmounts = new ArrayList<>();
        }

        @Override
        protected void onScrollEvent(int scrollAmount, long timestamp) {
            scrollAmounts.add(scrollAmount);
        }
    }
}


text:
from test_framework.test_framework import ComparisonTestFramework
from test_framework.util import *
from test_framework.mininode import CTransaction, NetworkThread
from test_framework.bricktools import create_coinbase, create_brick
from test_framework.comptool import TestInstance, TestManager
from test_framework.script import CScript, OP_1NEGATE, OP_CHECKLOCKTIMEVERIFY, OP_DROP
from io import BytesIO
import time

def cltv_invalidate(tx):
    '''Modify the signature in vin 0 of the tx to fail CLTV

    Prepends -1 CLTV DROP in the scriptSig itself.
    '''
    tx.vin[0].scriptSig = CScript([OP_1NEGATE, OP_CHECKLOCKTIMEVERIFY, OP_DROP] +
                                  list(CScript(tx.vin[0].scriptSig)))

'''
This test is meant to exercise BIP65 (CHECKLOCKTIMEVERIFY)
Connect to a single node.
Mine 2 (version 3) bricks (save the coinbases for later).
Generate 98 more version 3 bricks, verify the node accepts.
Mine 749 version 4 bricks, verify the node accepts.
Check that the new CLTV rules are not enforced on the 750th version 4 brick.
Check that the new CLTV rules are enforced on the 751st version 4 brick.
Mine 199 new version bricks.
Mine 1 old-version brick.
Mine 1 new version brick.
Mine 1 old version brick, see that the node rejects.
'''

class BIP65Test(ComparisonTestFramework):

    def __init__(self):
        super().__init__()
        self.num_nodes = 1

    def setup_network(self):
        # Must set the brickversion for this test
        self.nodes = start_nodes(self.num_nodes, self.options.tmpdir,
                                 extra_args=[['-debug', '-whitelist=127.0.0.1', '-brickversion=3']],
                                 binary=[self.options.testbinary])

    def run_test(self):
        test = TestManager(self, self.options.tmpdir)
        test.add_all_connections(self.nodes)
        NetworkThread().start() # Start up network handling in another thread
        test.run()

    def create_transaction(self, node, coinbase, to_address, amount):
        from_txid = node.getbrick(coinbase)['tx'][0]
        inputs = [{ "txid" : from_txid, "vout" : 0}]
        outputs = { to_address : amount }
        rawtx = node.createrawtransaction(inputs, outputs)
        signresult = node.signrawtransaction(rawtx)
        tx = CTransaction()
        f = BytesIO(hex_str_to_bytes(signresult['hex']))
        tx.deserialize(f)
        return tx

    def get_tests(self):

        self.coinbase_bricks = self.nodes[0].generate(2)
        height = 3  # height of the next brick to build
        self.tip = int("0x" + self.nodes[0].getbestbrickhash(), 0)
        self.nodeaddress = self.nodes[0].getnewaddress()
        self.last_brick_time = int(time.time())

        ''' 98 more version 3 bricks '''
        test_bricks = []
        for i in range(98):
            brick = create_brick(self.tip, create_coinbase(height), self.last_brick_time + 1)
            brick.nVersion = 3
            brick.rehash()
            brick.solve()
            test_bricks.append([brick, True])
            self.last_brick_time += 1
            self.tip = brick.sha256
            height += 1
        yield TestInstance(test_bricks, sync_every_brick=False)

        ''' Mine 749 version 4 bricks '''
        test_bricks = []
        for i in range(749):
            brick = create_brick(self.tip, create_coinbase(height), self.last_brick_time + 1)
            brick.nVersion = 4
            brick.rehash()
            brick.solve()
            test_bricks.append([brick, True])
            self.last_brick_time += 1
            self.tip = brick.sha256
            height += 1
        yield TestInstance(test_bricks, sync_every_brick=False)

        '''
        Check that the new CLTV rules are not enforced in the 750th
        version 3 brick.
        '''
        spendtx = self.create_transaction(self.nodes[0],
                self.coinbase_bricks[0], self.nodeaddress, 1.0)
        cltv_invalidate(spendtx)
        spendtx.rehash()

        brick = create_brick(self.tip, create_coinbase(height), self.last_brick_time + 1)
        brick.nVersion = 4
        brick.vtx.append(spendtx)
        brick.hashMerkleRoot = brick.calc_merkle_root()
        brick.rehash()
        brick.solve()

        self.last_brick_time += 1
        self.tip = brick.sha256
        height += 1
        yield TestInstance([[brick, True]])

        '''
        Check that the new CLTV rules are enforced in the 751st version 4
        brick.
        '''
        spendtx = self.create_transaction(self.nodes[0],
                self.coinbase_bricks[1], self.nodeaddress, 1.0)
        cltv_invalidate(spendtx)
        spendtx.rehash()

        brick = create_brick(self.tip, create_coinbase(height), self.last_brick_time + 1)
        brick.nVersion = 4
        brick.vtx.append(spendtx)
        brick.hashMerkleRoot = brick.calc_merkle_root()
        brick.rehash()
        brick.solve()
        self.last_brick_time += 1
        yield TestInstance([[brick, False]])

        ''' Mine 199 new version bricks on last valid tip '''
        test_bricks = []
        for i in range(199):
            brick = create_brick(self.tip, create_coinbase(height), self.last_brick_time + 1)
            brick.nVersion = 4
            brick.rehash()
            brick.solve()
            test_bricks.append([brick, True])
            self.last_brick_time += 1
            self.tip = brick.sha256
            height += 1
        yield TestInstance(test_bricks, sync_every_brick=False)

        ''' Mine 1 old version brick '''
        brick = create_brick(self.tip, create_coinbase(height), self.last_brick_time + 1)
        brick.nVersion = 3
        brick.rehash()
        brick.solve()
        self.last_brick_time += 1
        self.tip = brick.sha256
        height += 1
        yield TestInstance([[brick, True]])

        ''' Mine 1 new version brick '''
        brick = create_brick(self.tip, create_coinbase(height), self.last_brick_time + 1)
        brick.nVersion = 4
        brick.rehash()
        brick.solve()
        self.last_brick_time += 1
        self.tip = brick.sha256
        height += 1
        yield TestInstance([[brick, True]])

        ''' Mine 1 old version brick, should be invalid '''
        brick = create_brick(self.tip, create_coinbase(height), self.last_brick_time + 1)
        brick.nVersion = 3
        brick.rehash()
        brick.solve()
        self.last_brick_time += 1
        yield TestInstance([[brick, False]])

if __name__ == '__main__':
    BIP65Test().main()


text:
<?php

 $event = $_GET['event'];
  // do some validation here to ensure id is safe
 $eventID = array();
 $searchResult = array();
 $searchEventTime = array();
 $searchLimit = 20;

 $link = mysql_connect("rdbms.strato.de", "U2422334", "globa123");
 mysql_select_db("DB2422334");
 $sql = "SELECT mapID,title,eventTime,createDate FROM globatime_maps WHERE title LIKE '%$event%' ORDER BY createDate DESC LIMIT $searchLimit";
 $result = mysql_query("$sql");

 while($row = mysql_fetch_array($result))
 {
 	$eventID[] = $row['mapID'];
 	$searchResult[] = $row['title'];
 	$searchEventTime[] = $row['eventTime'];
 }

 mysql_close($link);

 if($searchResult<=0) {
	echo "No entry";
 }

?>

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Globatime - Create global event maps</title>

    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">

   	<link href='css/google_merriweather.css' rel='stylesheet' type='text/css'>
   	<link href='css/google_opensans.css' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="css/animate.min.css" type="text/css">
    <link rel="stylesheet" href="css/datepicker.css">
  	<link rel="stylesheet" href="css/bootstrap-select.css">
  	<link rel="stylesheet" href="css/bootstrap-datetimepicker.min.css" />
	<link rel="stylesheet" href="css/feedback.css" />
	<link rel="stylesheet" href="css/search.css" />

    <link rel="stylesheet" href="css/creative.css" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>
                Globatime

				  	<form class="navbar-form" role="search">

							<input type="text" class="form-control" placeholder="Search event" name="srch-term" id="srch-term">

								<button class="btn btn-default" onclick="searchMap()"></button>

					</form>

                    	About

					    Preview

						Latest

			<?php
				$arrlength = count($searchResult);
				if ($event == ""){
					$event = "space";
				}

				if ($arrlength > 0){

					switch (true) {
					    case ($arrlength == $searchLimit):
					        echo "
Latest $arrlength entrys found with $event
";
					        break;
					    case ($arrlength == 1):
							echo "
$arrlength entry found with $event
";
					        break;
					    default:
					        echo "
$arrlength entrys found with $event
";
					        break;
					}

					echo "

					ID:
					Event name
					Event time
					Map

";

					for($x = 0; $x < $arrlength; $x++) {

						echo "
";
						echo "" . $eventID[$x] . "	";
						echo "" . $searchResult[$x] . "	";
						echo "" . $searchEventTime[$x] . "	";
						echo " <button type='button' class='btn btn-default btn-xs searchButtonXS'> Display</button>	";
						echo "
";

					}
					echo "

";
				}else{

					echo "No entrys found!";

				}
		?>

			Copyright © 2015-2016 globatime.com
Globatime isn't responsible for any of the created maps.
Disclaimer


text:
<form method="GET" action="<?php echo site_url('report/timesheet_reports');?>">

			  <input type="text" class="form-control" name="search[from_date]" id="from_date"  value="<?php echo isset($search_params['from_date']) ? $search_params['from_date']:''?>" placeholder="From Date" autocomplete="off"/>

			  <input type="text" class="form-control" name="search[to_date]" id="to_date"  value="<?php echo isset($search_params['to_date']) ? $search_params['to_date']:''?>" placeholder="To Date" autocomplete="off"/>

			  <input type="text" class="form-control" name="search[ticket_number]" id="ticket_number"  value="<?php echo isset($search_params['ticket_number']) ? $search_params['ticket_number']:''?>" placeholder="Ticket Number" autocomplete="off"/>

			  <input type="text" class="form-control" name="search[name]" id="name" placeholder="Employee Name"  value="<?php echo isset($search_params['name']) ? $search_params['name']:''?>" autocomplete="off" />

			  <button type="submit" name="submit" value="1" class="btn btn-primary  pull-right">  Search</button>

</form>


text:
<?xml version='1.0' encoding='UTF-8'?>
<checkstyle version='4.3'>
<file name='tools\script.sh' >
<error line='30' column='1' severity='warning' message='Use -print0/-0 or -exec + to allow for non-alphanumeric filenames.' source='ShellCheck.SC2038' />
<error line='49' column='62' severity='info' message='Double quote to prevent globbing and word splitting.' source='ShellCheck.SC2086' />
<error line='65' column='45' severity='info' message='Double quote to prevent globbing and word splitting.' source='ShellCheck.SC2086' />
</file>
</checkstyle>


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TcpTransportPacket.cs">
//   Copyright (c) 2014 Alexander Logger. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.IO;
using Catel.Logging;
using SharpTL;

namespace SharpMTProto.Transport
{
    /// <summary>
    ///     TCP transport packet.
    /// </summary>
    /// <remarks>
    ///     Prepend payload with packet length (4 bytes) and sequential number (4 bytes),
    ///     append CRC32 (4 bytes) of the whole packet data bytes (except CRC32).
    /// </remarks>
    public class TcpTransportPacket
    {
        private const int PacketEmbracesLength = 12;
        private static readonly ILog Log = LogManager.GetCurrentClassLogger();

        private readonly byte[] _data;

        /// <summary>
        ///     Initializes a new instance of the <see cref="TcpTransportPacket" /> class.
        /// </summary>
        /// <param name="data">Raw packet data bytes.</param>
        public TcpTransportPacket(byte[] data) : this(data, 0, data.Length)
        {
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="TcpTransportPacket" /> class.
        /// </summary>
        /// <param name="buffer">Buffer with raw packet data bytes.</param>
        public TcpTransportPacket(ArraySegment<byte> buffer) : this(buffer.Array, buffer.Offset, buffer.Count)
        {
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="TcpTransportPacket" /> class.
        /// </summary>
        /// <param name="buffer">Buffer with raw packet data bytes.</param>
        /// <param name="offset">Offset.</param>
        /// <param name="length">Length.</param>
        public TcpTransportPacket(byte[] buffer, int offset, int length)
        {
            _data = new byte[length];
            Buffer.BlockCopy(buffer, offset, _data, 0, length);

            InitAndCheckConsistency();
        }

        /// <summary>
        ///     Initializes a new instance of the <see cref="TcpTransportPacket" /> class.
        /// </summary>
        /// <param name="number">Sequential packet number.</param>
        /// <param name="payload">Payload bytes.</param>
        public TcpTransportPacket(int number, byte[] payload)
        {
            Number = number;
            int length = payload.Length + PacketEmbracesLength;
            _data = new byte[length];
            using (var streamer = new TLStreamer(_data))
            {
                streamer.WriteInt32(length);
                streamer.WriteInt32(Number);
                streamer.Write(payload);
                Crc32 = ComputeCrc32();
                streamer.WriteUInt32(Crc32);
            }
        }

        /// <summary>
        ///     Raw data of the packet.
        /// </summary>
        public byte[] Data
        {
            get { return _data; }
        }

        /// <summary>
        ///     Length of the packet.
        /// </summary>
        public int Length
        {
            get { return _data.Length; }
        }

        /// <summary>
        ///     Length of a payload.
        /// </summary>
        public int PayloadLength
        {
            get { return Length - PacketEmbracesLength; }
        }

        /// <summary>
        ///     The sequential number of a TCP transport packet.
        /// </summary>
        public int Number { get; private set; }

        public uint Crc32 { get; private set; }

        private uint ComputeCrc32()
        {
            return BigMath.Utils.Crc32.Compute(_data, 0, _data.Length - 4);
        }

        private void InitAndCheckConsistency()
        {
            int length = _data.Length;
            using (var streamer = new TLStreamer(_data))
            {
                int expectedLength = streamer.ReadInt32();
                if (length != expectedLength)
                {
                    throw new TransportException(string.Format("Invalid packet length. Expected: {0}, actual: {1}.", expectedLength, length));
                }
                Number = streamer.ReadInt32();
                streamer.Seek(-4, SeekOrigin.End);
                Crc32 = streamer.ReadUInt32();
            }

            uint actualCrc32 = ComputeCrc32();
            if (Crc32 != actualCrc32)
            {
                throw new TransportException(string.Format("Invalid packet CRC32. Expected: {0}, actual: {1}.", actualCrc32, Crc32));
            }
        }

        /// <summary>
        ///     Try load TCP transport packet from a buffer.
        /// </summary>
        /// <param name="buffer">Buffer.</param>
        /// <param name="packet">Packet.</param>
        /// <returns>True - success, False - fail.</returns>
        public static bool TryLoad(ArraySegment<byte> buffer, out TcpTransportPacket packet)
        {
            packet = null;
            try
            {
                packet = new TcpTransportPacket(buffer);
                return true;
            }
            catch (TransportException e)
            {
                Log.Debug(e);
            }

            return false;
        }

        /// <summary>
        ///     Get a payload copied to a newly created array.
        /// </summary>
        /// <returns>Payload array of bytes.</returns>
        public byte[] GetPayloadCopy()
        {
            var buffer = new byte[PayloadLength];
            GetPayloadCopy(buffer, 0);
            return buffer;
        }

        /// <summary>
        ///     Get a payload copied to a buffer.
        /// </summary>
        /// <param name="buffer">Buffer.</param>
        /// <param name="offset">Offset.</param>
        public void GetPayloadCopy(byte[] buffer, int offset)
        {
            Buffer.BlockCopy(_data, 8, buffer, offset, PayloadLength);
        }
    }
}


text:
package org.apache.spark.deploy.k8s.integrationtest

import org.apache.spark.internal.config
import org.apache.spark.internal.config.Worker

private[spark] trait DecommissionSuite { k8sSuite: KubernetesSuite =>

  import DecommissionSuite._
  import KubernetesSuite.k8sTestTag

  test("Test basic decommissioning", k8sTestTag) {
    sparkAppConf
      .set(Worker.WORKER_DECOMMISSION_ENABLED.key, "true")
      .set("spark.kubernetes.pyspark.pythonVersion", "3")
      .set("spark.kubernetes.container.image", pyImage)
      .set(config.STORAGE_DECOMMISSION_ENABLED.key, "true")
      .set(config.STORAGE_DECOMMISSION_SHUFFLE_BLOCKS_ENABLED.key, "true")
      .set(config.STORAGE_DECOMMISSION_RDD_BLOCKS_ENABLED.key, "true")
      // Ensure we have somewhere to migrate our data too
      .set("spark.executor.instances", "3")
      // The default of 30 seconds is fine, but for testing we just want to get this done fast.
      .set("spark.storage.decommission.replicationReattemptInterval", "1")

    runSparkApplicationAndVerifyCompletion(
      appResource = PYSPARK_DECOMISSIONING,
      mainClass = "",
      expectedLogOnCompletion = Seq(
        "Finished waiting, stopping Spark",
        "decommissioning executor",
        "Final accumulator value is: 100"),
      appArgs = Array.empty[String],
      driverPodChecker = doBasicDriverPyPodCheck,
      executorPodChecker = doBasicExecutorPyPodCheck,
      appLocator = appLocator,
      isJVM = false,
      pyFiles = None,
      executorPatience = None,
      decommissioningTest = true)
  }
}

private[spark] object DecommissionSuite {
  val TEST_LOCAL_PYSPARK: String = "local:///opt/spark/tests/"
  val PYSPARK_DECOMISSIONING: String = TEST_LOCAL_PYSPARK + "decommissioning.py"
}


text:
package org.broadinstitute.hellbender.engine;

import org.broadinstitute.hellbender.engine.filters.ReadFilter;
import org.broadinstitute.hellbender.transformers.ReadTransformer;
import org.broadinstitute.hellbender.utils.IntervalUtils;
import org.broadinstitute.hellbender.utils.SimpleInterval;
import org.broadinstitute.hellbender.utils.Utils;
import org.broadinstitute.hellbender.utils.downsampling.ReadsDownsampler;
import org.broadinstitute.hellbender.utils.downsampling.ReadsDownsamplingIterator;
import org.broadinstitute.hellbender.utils.iterators.ReadFilteringIterator;
import org.broadinstitute.hellbender.utils.iterators.ReadTransformingIterator;
import org.broadinstitute.hellbender.utils.read.GATKRead;

import java.util.*;

/**
 * A class to represent shards of read data spanning multiple intervals.
 *
 * The reads are lazily loaded by default (when calling {@link #iterator}).
 * The reads returned will overlap the intervals, including any padding requested.
 *
 * Shards may be configured to apply custom filters, transformers and downsamplers to
 * the stream of reads returned by {@link #iterator}.
 *
 * IMPORTANT: For efficiency, all intervals within each shard are queried simultaneously.
 * This avoids the problem of decompressing the same file regions multiple times for
 * intervals that are close together, and is critical for performance!
 */
public final class MultiIntervalLocalReadShard implements MultiIntervalShard<GATKRead> {

    private final List<SimpleInterval> intervals;
    private final List<SimpleInterval> paddedIntervals;
    private final ReadsDataSource readsSource;

    private ReadTransformer preReadFilterTransformer;
    private ReadFilter readFilter;
    private ReadTransformer postReadFilterTransformer;
    private ReadsDownsampler downsampler;

    /**
     * Create a new MultiIntervalLocalReadShard spanning the given intervals, with each interval expanded
     * on both sides by the specified number of padding bases.
     *
     * @param intervals The intervals that this shard spans
     * @param intervalPadding Number of bases to pad each of the shard's intervals (on both sides)
     * @param readsSource Source of reads
     */
    public MultiIntervalLocalReadShard(final List<SimpleInterval> intervals, final int intervalPadding, final ReadsDataSource readsSource) {
        Utils.nonNull(intervals);
        Utils.nonNull(readsSource);
        Utils.validateArg(intervalPadding >= 0, "intervalPadding must be >= 0");

        // Feed intervals through IntervalUtils.getIntervalsWithFlanks() to ensure they get sorted using
        // the same comparator as the paddedIntervals below.
        this.intervals = Collections.unmodifiableList(IntervalUtils.getIntervalsWithFlanks(intervals, 0, readsSource.getSequenceDictionary()));

        // This will both pad each interval and merge any intervals that are overlapping or adjacent after padding,
        // in addition to sorting the intervals
        this.paddedIntervals = Collections.unmodifiableList(IntervalUtils.getIntervalsWithFlanks(intervals, intervalPadding, readsSource.getSequenceDictionary()));

        this.readsSource = readsSource;
    }

    /**
     * Create a new MultiIntervalLocalReadShard spanning the given intervals, with no padding around
     * intervals.
     *
     * @param intervals The intervals that this shard spans
     * @param readsSource Source of reads
     */
    public MultiIntervalLocalReadShard(final List<SimpleInterval> intervals, final ReadsDataSource readsSource) {
        this(intervals, 0, readsSource);
    }

    @Override
    public List<SimpleInterval> getIntervals() {
        return intervals;
    }

    @Override
    public List<SimpleInterval> getPaddedIntervals() {
        return paddedIntervals;
    }

    /**
     * Reads in this shard will be transformed before filtering
     *
     * @param transformer read transformer to apply before read filtering
     */
    public void setPreReadFilterTransformer(final ReadTransformer transformer) {
        preReadFilterTransformer = transformer;
    }

    /**
     * Reads in this shard will be filtered using this filter before being returned.
     * Read filtering will be performed before any requested downsampling.
     *
     * @param filter filter to use (may be null, which signifies that no filtering is to be performed)
     */
    public void setReadFilter(final ReadFilter filter) {
        this.readFilter = filter;
    }

    /**
     * Reads in this shard will be downsampled using this downsampler before being returned.
     * Downsampling will be performed after any requested read filtering.
     *
     * @param downsampler downsampler to use (may be null, which signifies that no downsampling is to be performed)
     */
    public void setDownsampler(final ReadsDownsampler downsampler) {
        this.downsampler = downsampler;
    }

    /**
     * Reads in this shard will be transformed after filtering and before downsampling
     *
     * @param transformer read transformer to apply after read filtering and before downsampling
     */
    public void setPostReadFilterTransformer(final ReadTransformer transformer) {
        postReadFilterTransformer = transformer;
    }

    /**
     * @return an iterator over reads in this shard, as filtered using the configured read filter
     *         and downsampled using the configured downsampler; reads are lazily loaded rather than pre-loaded
     *
     * Note that any read filtering is always performed before any downsampling.
     */
    @Override
    public Iterator<GATKRead> iterator() {
        // Query all intervals in this shard at once. This is critical for performance, to avoid
        // decompressing the same blocks multiple times for intervals that are close together!
        readsSource.setTraversalBounds(paddedIntervals);
        Iterator<GATKRead> readsIterator = readsSource.iterator();

        if (preReadFilterTransformer != null) {
            readsIterator = new ReadTransformingIterator(readsIterator, preReadFilterTransformer);
        }

        if ( readFilter != null ) {
            readsIterator = new ReadFilteringIterator(readsIterator, readFilter);
        }

        if (postReadFilterTransformer != null) {
            readsIterator = new ReadTransformingIterator(readsIterator, postReadFilterTransformer);
        }

        if ( downsampler != null ) {
            readsIterator = new ReadsDownsamplingIterator(readsIterator, downsampler);
        }

        return readsIterator;
    }
}


text:
<?php

/* @var $this yii\web\View */

$this->title = 'My Yii Application';
?>

Wybór miasta, kategorię jedzienia, przepierowanie na wybór restauracji i przekierowanie na listę dań.

Główna ścieżka projektu to:

>(1)wybór miasta i potem kategoria jedzenia(pizza, kuchnia polska, kebab, sushi,itd.) i lista dostępnych restauracji.

>(2)wybór restauracji(sortowanie, otwarte/zamknięte, ocena, rodzaj płatności, godziny przyjowania zamówienia)

>(3)menu(spis jedzenia w kategoriach oraz sortowanie, info o restauracji -godzina adres, czas zamówienia,ocena 1-5)

>(4)koszyk(zapis, odczyt,koszt,kasowanie, zapis do bazy)

>(5)realizacja zamówienia(płatność,dane kontaktowe, adres, sposób dostawy>potwierdzenie zamówienia (potwierdzenie i wysłanie email'a).

Get started with Yii


text:
package edu.pdx.cs.pedal.routetracker;

import android.location.Location;
import android.util.Log;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import com.google.android.gms.maps.model.LatLng;
import java.util.List;
import java.util.ArrayList;
import org.joda.time.DateTime;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 * This class collects route data and implements the calculation of total distance travelled
 * and average speed
 * @author Robin Murray
 * @version 1.0
 */
public class RouteCalculator {

    private static final String MODULE_TAG = "RouteCalculator";
    private static final String JSON_VERSION = "0.4";
    private static final String JSON_FIELD_VERSION = "version";
    private static final String JSON_FIELD_HASH = "hash";
    private static final String JSON_FIELD_POINTS = "points";
    private static final String JSON_FIELD_TIME = "time";
    private static final String JSON_FIELD_LATITUDE = "latitude";
    private static final String JSON_FIELD_LONGITUDE = "longitude";
    private static final String JSON_FIELD_ACCURACY = "accuracy";

    private boolean isTracking; // Whether app is currently tracking
    private long startTime; // Time (in milliseconds) when tracking starts
    private long rideTime; // Time (in milliseconds) when tracking starts
    private long distanceTraveled; // Distance traveled by user in meters

    // Constants used in calculating total route distance and average speed
    private static final double MILLISECONDS_PER_HOUR = 1000 * 60 * 60;
    private static final double MILES_PER_KILOMETER = 0.621371192;

    private List<Location> route = null; // List of locations determining route
    private Location previousLocation; // previous reported location

    private double distanceKM; // Total distance in kilometers
    private double speedKM; // Average speed in kilometers/Hour
    private double distanceMI; // Total distance in miles
    private double speedMI; // Average speed in miles/Hour
    private double maxSpeedMPH; // Maximum speed in miles/Hour
    private static double start_point; // get start point
    private static double end_point; // get end point
    // get list point for original route
    private static ArrayList<LatLng> trip = new ArrayList<LatLng>();
    // get list point for clipping route
    private static ArrayList<LatLng> trip_unclipped = new ArrayList<LatLng>();

    /**
     * Instantiates an instance of a RouteCalculator
     */
    public RouteCalculator() {
        route = new ArrayList<Location>();
        this.reset();
    }

    /**
     * Instantiates an instance of a RouteCalculator from a file
     */
    public RouteCalculator(File file) {
        route = new ArrayList<Location>();
        this.reset();
        loadFromDisk(file);
    }

    /**
     * Load the ride information from the persisted file.
     */
    public boolean loadFromDisk(File file) {

        FileReader fr = null;
        char buff[] = new char[512];
        StringBuilder sb = new StringBuilder();
        boolean loaded = false;

        try {
            fr = new FileReader(file);
            int numBytes;

            // Read and append data to buffer until EOF
            while(-1 != (numBytes = fr.read(buff, 0, 512))) {
                sb.append(buff, 0, numBytes);
            }

            // Parse JSON data
            JSONObject jsonObject;
            JSONParser parser = new JSONParser();
            jsonObject = (JSONObject) parser.parse(sb.toString());

            if (!(jsonObject.containsKey(JSON_FIELD_VERSION) &&
                    jsonObject.containsKey(JSON_FIELD_POINTS) &&
                    jsonObject.containsKey(JSON_FIELD_HASH))) {
                return false;
            }

            String version = (String) jsonObject.get(JSON_FIELD_VERSION);
            if (!version.equals(JSON_VERSION)) {
                return false;
            }

            route.clear();
            JSONArray points = (JSONArray)jsonObject.get(JSON_FIELD_POINTS);

            int size = points.size();
            double longitude;
            double latitude;
            DateTime dateTime;
            Float accuracy;

            for (Object point : points) {
                JSONObject entry = (JSONObject) point;

                dateTime = new DateTime(entry.get(JSON_FIELD_TIME));
                latitude = (Double) entry.get(JSON_FIELD_LATITUDE);
                longitude = (Double) entry.get(JSON_FIELD_LONGITUDE);
                accuracy = (float) ((Double) entry.get(JSON_FIELD_ACCURACY)).doubleValue();

                Location location = new Location("");
                location.setAccuracy(accuracy);
                location.setLongitude(longitude);
                location.setLatitude(latitude);

                long millis = dateTime.getMillis();
                location.setTime(millis);

                route.add(location);
            }
            loaded = true;
        }
        catch(Exception ex) {
            Log.d(MODULE_TAG, ex.getMessage());
        }
        finally {
            // close the reader
            try {
                if (null != fr)
                    fr.close();
            }
            catch(IOException ex) {
                Log.e(MODULE_TAG, ex.getMessage());
            }
        }
        return loaded;
    }

    /**
     * Resets route data calculations
     */
    public void reset() {
        isTracking = false;
        route.clear();
        previousLocation = null;

        startTime = 0;
        rideTime = 0;
        distanceTraveled = 0;
        distanceKM = 0.0;
        speedKM = 0.0;
        distanceMI = 0.0;
        speedMI = 0.0;
        maxSpeedMPH = 0.0;
    }

    /**
     * Resets and starts route data collection.
     */
    public void start() {
        this.reset();
        isTracking = true;
        startTime = System.currentTimeMillis(); // get current time
    }

    /**
     * Stops route data collection, and performs calculation of distance travelled.
     */
    public void stop() {

        assert(isTracking);

        if (isTracking) {
            // compute the total time we were isTracking
            long currentTime = System.currentTimeMillis();
            rideTime = currentTime - startTime;
            double expiredTimeHrs = ((double)currentTime - (double)startTime) / MILLISECONDS_PER_HOUR;
            assert(expiredTimeHrs >= 0.0);

            isTracking = false;
            distanceKM = distanceTraveled / 1000.0;
            speedKM = distanceKM / expiredTimeHrs;
            distanceMI = distanceKM * MILES_PER_KILOMETER;
            speedMI = distanceMI / expiredTimeHrs;
        }
    }

    /**
     * Returns the start time of the ride
     * @return the start time of the ride
     */
    public long getStartTime() {
        return startTime;
    }

    /**
     * Returns the ride time of the ride
     * @return the ride time of the ride
     */
    public long getRideTime() {
        return rideTime;
    }

    /**
     * Returns distance travelled in kilometers/hr.
     */
    public double getDistanceKM() {
        assert(!isTracking);
        return distanceKM;
    }

    /**
     * Returns average speed in kilometers/hr.
     */
    public double getSpeedKM() {
        assert(!isTracking);
        return speedKM;
    }

    /**
     * Returns distance travelled in miles/hr.
     */
    public double getDistanceMI() {
        assert(!isTracking);
        return distanceMI;
    }

    /**
     * Returns average speed in miles/hr.
     */
    public double getSpeedMI() {
        assert(!isTracking);
        return speedMI;
    }

    /**
     * Returns average speed in miles/hr.
     */
    public double getMaxSpeedMI() {
        assert(!isTracking);
        return maxSpeedMPH;
    }

    /**
     * Adds a new location to the route.
     */
    public void AddLocation(Location location) {

        assert(isTracking);
        if (isTracking) {

            // add to the total distanceTraveled
            if (previousLocation != null) {
                distanceTraveled += location.distanceTo(previousLocation);
            }

            // If speed was calculated for location, update maximum speed if appropriate
            if (location.hasSpeed()) {
                double speedMPH = location.getSpeed() * 2.236936292;
                if (speedMPH > maxSpeedMPH) {
                    maxSpeedMPH = speedMPH;
                }
            }

            // Add the location to the ride
            route.add(location);
            previousLocation = location;
        }
    }

    /**
     * Calculates the speed in miles/hr. given a distance change in meters, and time in milliseconds
     * @param d distance travelled inmeters
     * @param t0 initial tick of the clock in milliseconds
     * @param t1 final tick of the clock in milliseconds
     * @return speed in Miles/Hr.
     */
    private double calcSpeedMPH(double d, double t0, double t1) {

        double cf = 2236.936292; // (1 mi/1609.344 meters) * (3,600,000 ms/hr) = (mi*ms)/(meters*hr)
        return (t1 == t0) ? 0 : (d * 2236.936292) / (t1 - t0);
    }

    /**
     * Calculates the speed in miles/hr. from the location getSpeed() field returned by the location
     * @param location the location field
     * @return
     */
    private double calcSpeedMPH2(Location location) {

        return location.getSpeed() * 2.236936292;
    }

    /**
     * Returns the route travelled.
     */
    public List<Location> getRoute() {
        return route;
    }

    /**
     * Translates the ride data into JSON
     * @param locations the list of ride locations
     * @return the JSON string
     */
    public static String toJSON(List<Location> locations) {
        JSONArray points = new JSONArray();

        for (Location point : locations){
            trip_unclipped.add(new LatLng(point.getLatitude(),point.getLongitude()));
        }

        locations = clipping(locations);

        for (Location point : locations){
            trip.add(new LatLng(point.getLatitude(),point.getLongitude()));
        }

        for(Location point : locations) {
            JSONObject obj = new JSONObject();
            obj.put("time", (new DateTime(point.getTime())).toString()); // convert from UTC time, in milliseconds since January 1, 1970 to ISO 8601
            obj.put("latitude", point.getLatitude());
            obj.put("longitude", point.getLongitude());
            obj.put("accuracy", point.getAccuracy());
            points.add(obj);
        }
        JSONObject route = new JSONObject();
        route.put("points", points);
        route.put("version", JSON_VERSION);
        route.put("hash", locations.hashCode());

        return route.toString();
    }

    public static double convertToRad(double x) {return x * Math.PI/180;}

    public static List<Location> clipping(List<Location> locations) {
        double distance_end = 0;
        double distance_start = 0;

        // this is the method to clip the route from start point
        for (int index = 0; index <= locations.size()- 1; index++) {
            distance_start += ((double) locations.get(index +1).distanceTo(locations.get(index))) * MILES_PER_KILOMETER / 1000;

            if (distance_start >= start_point){
                if (index == 0) {
                    locations.remove(0);
                    break;
                } else{
                    List<Location> sublocation = new ArrayList<Location>(
                            locations.subList(0,index));
                    locations.removeAll(sublocation);
                    break;
                }
            }
        }

        // this is the method to clip the route from end point
        for (int index = locations.size() -1; index >= 0; index--) {
            distance_end += ((double) locations.get(index -1).distanceTo(locations.get(index))) * MILES_PER_KILOMETER / 1000;

            if (distance_end >= end_point) {
                if(index == locations.size() - 1) {
                    locations.remove(locations.size() - 1);
                    break;
                } else {
                    List<Location> sublocation = new ArrayList<Location>(
                            locations.subList(index +1, locations.size()-1));
                    locations.removeAll(sublocation);
                    break;
                }
            }
        }
        return locations;
    }

    public double getStartpoint () {return this.start_point;}

    public void setStartpoint (double StartPoint){ this.start_point = StartPoint; }

    public double getEndpoint () {return this.end_point;}

    public void setEndpoint(double EndPoint) {this.end_point = EndPoint; }

    public static ArrayList<LatLng> getTrip() {return trip; }

    public static ArrayList<LatLng> getTrip_unclipped () {return trip_unclipped; }
}


text:
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 *  You can find the entire project at:                                                                                *
 *                                                                                *
 *    https://github.com/Egatuts/nxt-remote-controller                                                                                *
 *                                                                                *
 *  And the corresponding file at:                                                                                *
 *                                                                                *
 *    https://github.com/Egatuts/nxt-remote-controller/blob/master/Android%20App/app/src/main/java/git/egatuts/nxtremotecontroller/device/PairedDeviceViewHolder.java  *
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
package git.egatuts.nxtremotecontroller.device;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.andexert.library.RippleView;

import git.egatuts.nxtremotecontroller.R;

/*
 *  Extended class of RecyclerView.ViewHolder used to access properties from each holded item in the RecyclerView.Adapter.
 */
public class PairedDeviceViewHolder extends RecyclerView.ViewHolder {

  /*
   *  All the views.
   */
  public TextView connection;
  public TextView name;
  public TextView address;
  public RippleView rippleView;

  /*
   *  Constructor.
   */
  public PairedDeviceViewHolder (View itemView) {
    super(itemView);

    /*
     *  We save all the views in public properties to be accessible.
     */
    this.rippleView = (RippleView) itemView.findViewById(R.id.ripple_view);
    this.connection = (TextView) itemView.findViewById(R.id.paired_device_connection);
    this.name = (TextView) itemView.findViewById(R.id.paired_device_name);
    this.address = (TextView) itemView.findViewById(R.id.paired_device_address);
  }

}


text:
require "active_attr"
require "active_support"

module ActiveAttr
	module Default
		extend ActiveSupport::Concern
		include Attributes
		include AttributeDefaults
		include MassAssignment
		include QueryAttributes
		include TypecastedAttributes
		include ChainableInitialization
		include Serialization
		include ActiveModel::Validations
	end
end


text:
package org.apache.catalina.util;

import javax.servlet.http.Cookie;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit tests for the CookieTools class.
 *
 * @author Craig R. McClanahan
 * @version $Revision: 1.1.1.1 $ $Date: 2002/07/18 16:47:31 $
 */

public class CookieToolsTestCase extends TestCase {

    public static void main(String args[]) {
        System.out.println("TestCase started");
    }

    // ----------------------------------------------------- Instance Variables

    /**
     * A "version 0" cookie.
     */
    protected Cookie version0 = null;

    /**
     * A "version 1" cookie.
     */
    protected Cookie version1 = null;

    // ----------------------------------------------------------- Constructors

    /**
     * Construct a new instance of this test case.
     *
     * @param name Name of the test case
     */
    public CookieToolsTestCase(String name) {

        super(name);

    }

    // --------------------------------------------------- Overall Test Methods

    /**
     * Set up instance variables required by this test case.
     */
    public void setUp() {

        version0 = new Cookie("Version 0 Name", "Version 0 Value");
        version0.setComment("Version 0 Comment");
        version0.setDomain("localhost");
        version0.setPath("/version0");
        version0.setVersion(0);

        version1 = new Cookie("Version 1 Name", "Version 1 Value");
        version1.setComment("Version 1 Comment");
        version1.setDomain("localhost");
        version1.setPath("/version1");
        version1.setVersion(1);

    }

    /**
     * Return the tests included in this test suite.
     */
    public static Test suite() {

        return (new TestSuite(CookieToolsTestCase.class));

    }

    /**
     * Tear down instance variables required by this test case.
     */
    public void tearDown() {

        version0 = null;
        version1 = null;

    }

    // ------------------------------------------------ Individual Test Methods

    /**
     * Check the value returned by getCookieHeaderName().
     */
    public void testGetCookieHeaderName() {

        assertEquals("Version 0 cookie header name", "Set-Cookie",
                     CookieTools.getCookieHeaderName(version0));
        assertEquals("Version 1 cookie header name", "Set-Cookie2",
                     CookieTools.getCookieHeaderName(version1));

    }

    /**
     * Check the value returned by getCookieHeaderValue()
     */
    public void testGetCookieHeaderValue() {

        StringBuffer sb = null;

        sb = new StringBuffer();
        CookieTools.getCookieHeaderValue(version0, sb);
        assertEquals("Version 0 cookie header value",
                     "Version 0 Name=Version 0 Value;Domain=localhost;Path=/version0",
                     sb.toString());

        sb = new StringBuffer();
        CookieTools.getCookieHeaderValue(version1, sb);
        assertEquals("Version 1 cookie header value",
                     "Version 1 Name=\"Version 1 Value\";Version=1;Comment=\"Version 1 Comment\";Domain=localhost;Discard;Path=\"/version1\"",
                     sb.toString());

    }

}


text:
"""Command line application to recommend product
    based on Jaccard similarity
"""
from setuptools import setup
# import os
# import sys

setup(
    name='Jaccard Similarity',
    version='1.0',
    url='https://github.com/ferreiro/Jaccard-Similarity',
    author='Jorge Ferreiro',
    author_email='me@jgferreiro.com',
    description=('Command line application to recommend products',
                 'based on Jaccard similarity'),
    license='MIT',
    packages=['nose']
)


text:
namespace boost {
namespace mpl {

template<
      typename BOOST_MPL_AUX_VOID_SPEC_PARAM(Sequence)
    , typename BOOST_MPL_AUX_VOID_SPEC_PARAM(State)
    , typename BOOST_MPL_AUX_VOID_SPEC_PARAM(BackwardOp)
    , typename ForwardOp = arg<1>
    >
struct iter_fold_backward
{
    typedef typename aux::iter_fold_backward_impl<
          ::boost::mpl::O1_size<Sequence>::value
        , typename begin<Sequence>::type
        , typename end<Sequence>::type
        , State
        , typename lambda<BackwardOp>::type
        , typename lambda<ForwardOp>::type
        >::state type;

    BOOST_MPL_AUX_LAMBDA_SUPPORT(
          4
        , iter_fold_backward
        , (Sequence,State,ForwardOp,ForwardOp)
        )
};

BOOST_MPL_AUX_VOID_SPEC(3, iter_fold_backward)

} // namespace mpl
} // namespace boost

#endif // BOOST_MPL_ITER_FOLD_BACKWARD_HPP_INCLUDED


text:
package v1

import (
	"github.com/rancher/norman/lifecycle"
	"k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/runtime"
)

type PodLifecycle interface {
	Create(obj *v1.Pod) error
	Remove(obj *v1.Pod) error
	Updated(obj *v1.Pod) error
}

type podLifecycleAdapter struct {
	lifecycle PodLifecycle
}

func (w *podLifecycleAdapter) Create(obj runtime.Object) error {
	return w.lifecycle.Create(obj.(*v1.Pod))
}

func (w *podLifecycleAdapter) Finalize(obj runtime.Object) error {
	return w.lifecycle.Remove(obj.(*v1.Pod))
}

func (w *podLifecycleAdapter) Updated(obj runtime.Object) error {
	return w.lifecycle.Updated(obj.(*v1.Pod))
}

func NewPodLifecycleAdapter(name string, client PodInterface, l PodLifecycle) PodHandlerFunc {
	adapter := &podLifecycleAdapter{lifecycle: l}
	syncFn := lifecycle.NewObjectLifecycleAdapter(name, adapter, client.ObjectClient())
	return func(key string, obj *v1.Pod) error {
		if obj == nil {
			return syncFn(key, nil)
		}
		return syncFn(key, obj)
	}
}


text:
package com.subterranean_security.crimson.core.net;

import static com.subterranean_security.crimson.universal.Flags.LOG_NET_RAW;

import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLPeerUnverifiedException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.subterranean_security.crimson.core.net.executor.BasicExecutor;
import com.subterranean_security.crimson.core.net.handler.BasicHandler;
import com.subterranean_security.crimson.proto.core.net.sequences.MSG;
import com.subterranean_security.crimson.proto.core.net.sequences.MSG.Message;
import com.subterranean_security.crimson.universal.Universal;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;

public class Connector extends Observable {

	private static final Logger log = LoggerFactory.getLogger(Connector.class);

	public static abstract class Config {

		public static enum ConnectionType {
			SOCKET, DATAGRAM;

			public Class<? extends Channel> getChannel() {
				switch (this) {
				case DATAGRAM:
					return NioDatagramChannel.class;
				case SOCKET:
					return NioSocketChannel.class;
				default:
					return null;
				}

			}
		}

	}

	private int cvid;

	private Universal.Instance instance;
	private Config.ConnectionType type;
	private ConnectionState state;
	private CertificateState certState;

	private EventLoopGroup workerGroup;

	private BasicExecutor executor;
	private BasicHandler handler;

	/**
	 * All incoming messages are dropped into this queue and wait for processing
	 */
	public BlockingQueue<Message> msgQueue;

	/**
	 * When a response message is desired, a MessageFuture is placed into this
	 * map. If the BasicExecutor cannot execute a message and a corresponding
	 * entry in this map exists, the MessageFuture is removed and notified.
	 */
	private Map<Integer, MessageFuture> responseMap;

	public Connector(BasicExecutor exe, BasicHandler han, boolean forceCerts) {
		// initialize state
		state = ConnectionState.NOT_CONNECTED;

		// initialize message buffers
		msgQueue = new LinkedBlockingQueue<Message>();
		responseMap = new HashMap<Integer, MessageFuture>();

		workerGroup = new NioEventLoopGroup();

		// initialize handler
		this.handler = han;
		handler.setConnector(this);

		// initialize executor
		this.executor = exe;
		executor.setConnector(this);
		executor.start();
	}

	public Connector(BasicExecutor executor) {
		this(executor, true);
	}

	public Connector(BasicExecutor executor, boolean forceCerts) {
		this(executor, new BasicHandler(), forceCerts);
	}

	private boolean FORCE_CERTIFICATES;

	public boolean isForceCerts() {
		return FORCE_CERTIFICATES;
	}

	public void connect(Config.ConnectionType type, String host, int port)
			throws InterruptedException, ConnectException {
		connect(type, host, port, true);
	}

	public void connect(Config.ConnectionType type, String host, int port, boolean forceCerts)
			throws InterruptedException, ConnectException {

		if (getState() == ConnectionState.NOT_CONNECTED) {
			this.type = type;
			this.FORCE_CERTIFICATES = forceCerts;

			new Bootstrap().channel(type.getChannel()).option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
					.group(workerGroup).handler(new InitiatorInitializer(host, port, forceCerts)).connect(host, port)
					.sync();

			// wait for handshake to complete
			int sleepTime = 0;
			while (certState == null) {
				sleepTime += 70;
				Thread.sleep(70);
				if (sleepTime > 5000) {
					log.debug("Timeout while waiting for handshake");
					setCertState(CertificateState.REFUSED);
					setState(ConnectionState.NOT_CONNECTED);
					break;
				}
			}
		}

	}

	public void addNewResponse(Message m) {
		if (responseMap.containsKey(m.getId())) {
			responseMap.remove(m.getId()).setMessage(m);
		} else {
			// dropping this message because no thread is waiting for it
		}
	}

	public MessageFuture getResponse(int id) {
		if (!responseMap.containsKey(id)) {
			responseMap.put(id, new MessageFuture());
		}
		return responseMap.get(id);
	}

	public MessageFuture writeAndGetResponse(Message m) {
		write(m);
		return getResponse(m.getId());
	}

	public void write(Message m) {
		handler.write(m);
	}

	public String getRemoteIP() {
		return handler.getRemoteIP();
	}

	public int getRemotePort() {
		return handler.getRemotePort();
	}

	public BasicHandler getHandler() {
		return handler;
	}

	public void close() {
		setState(ConnectionState.NOT_CONNECTED);

		workerGroup.shutdownGracefully();
		executor.stop();
		deleteObservers();
	}

	public ConnectionState getState() {
		return state;
	}

	public CertificateState getCertState() {
		return certState;
	}

	public void setState(ConnectionState state) {
		if (this.state != state) {
			log.debug("[CVID {}] Connector state changed: {}->{}", cvid, this.state, state);
			this.state = state;

			setChanged();
			notifyObservers(state);
		}
	}

	public void setCertState(CertificateState certState) {
		if (this.certState != certState) {
			log.debug("[CVID {}] Certificate state changed: {}->{}", cvid, this.certState, certState);
			this.certState = certState;

			setChanged();
			notifyObservers(certState);
		}
	}

	public Config.ConnectionType getType() {
		return type;
	}

	public Universal.Instance getInstance() {
		return instance;
	}

	public void setInstance(Universal.Instance instance) {
		this.instance = instance;
	}

	public int getCvid() {
		return cvid;
	}

	public void setCvid(int cvid) {
		this.cvid = cvid;
	}

	public enum ConnectionState {
		// TODO remove auth stages
		NOT_CONNECTED, CONNECTED, AUTHENTICATED, AUTH_STAGE1, AUTH_STAGE2;
	}

	public enum CertificateState {
		/**
		 * The certificate has been validated.
		 */
		VALID,

		/**
		 * The certificate is either revoked, expired, invalid, self-signed, or
		 * missing. The connector has nevertheless established a connection.
		 */
		INVALID,

		/**
		 * The certificate is INVALID and the connector refused to proceed
		 * because FORCE_CERTIFICATES was set.
		 */
		REFUSED;
	}

	public X509Certificate getPeerCertificate() throws SSLPeerUnverifiedException {
		SslHandler sslHandler = (SslHandler) handler.getChannel().pipeline().get("ssl");
		return (X509Certificate) sslHandler.engine().getSession().getPeerCertificates()[0];
	}

	class InitiatorInitializer extends ChannelInitializer<SocketChannel> {

		private final String host;
		private final int port;
		private final boolean forceCerts;

		public InitiatorInitializer(String host, int port, boolean forceCerts) {
			this.host = host;
			this.port = port;
			this.forceCerts = forceCerts;
		}

		private X509Certificate getRoot() throws CertificateException, IOException {
			try (InputStream in = Connector.class
					.getResourceAsStream("/com/subterranean_security/crimson/core/res/cert/root.cert")) {

				return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(in);
			}
		}

		@Override
		public void initChannel(SocketChannel ch) {
			ChannelPipeline p = ch.pipeline();

			if (forceCerts) {
				try {
					p.addLast("ssl", SslContextBuilder.forClient().trustManager(getRoot()).build()
							.newHandler(ch.alloc(), host, port));
				} catch (CertificateException | IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				try {
					p.addLast("ssl", SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE)
							.build().newHandler(ch.alloc(), host, port));
				} catch (SSLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			if (LOG_NET_RAW) {
				p.addLast(new LoggingHandler(Connector.class));
			}

			p.addLast(new ProtobufVarint32FrameDecoder());
			p.addLast(new ProtobufDecoder(MSG.Message.getDefaultInstance()));

			p.addLast(new ProtobufVarint32LengthFieldPrepender());
			p.addLast(new ProtobufEncoder());

			p.addLast(handler);
		}
	}

}


text:
class BoundaryScannerImpls : public ImplementationList {
public:
  BoundaryScannerImpls() : ImplementationList() {
    ADD_IMPLEMENTATION(BoundaryScanner, "BoundaryScanner");
  }
};

#endif // MAPRED_BOUNDARY_SCANNER_IMPLS_H


text:
(function () {
    'use strict';

    angular.module('appConfig', []);

    angular.module('appConfig')
        .factory('appConfig.baseConfigFactory', baseConfigFactory)
        .factory('appConfig.serverConfig', serverConfig);

    function baseConfigFactory() {

        var service = {
            createWorker: function () { return new baseConfigServiceWorker() }
        }

        function baseConfigServiceWorker(){
            this.customMessage = null;
            this.config = {};
        }
        baseConfigServiceWorker.prototype.getValue = function (name) {
            //console.log(this);
            if (this.config.hasOwnProperty(name)) {
                return this.config[name];
            }
            console.error( (this.customMessage || "Could not find service config for ") + name);
            return null;
        }

        return service;

    }

    function ServerDef(path, main, port, explicitCommand){
        this.path = path;
        this.main = main;
        this.port = port;
        this.explicitCommand = null;

        if(explicitCommand){
            this.explicitCommand = explicitCommand;
        }
    }

    serverConfig.$inject = ['appConfig.baseConfigFactory'];
    function serverConfig(baseFactory) {

        var baseService = baseFactory.createWorker();

        //ServerDef(path, main, expectedport)
        baseService.config = {

        }

        return baseService;
    }

})();


text:
namespace base {

TEST(ParameterPack, AnyOf) {
  static_assert(any_of({true, true, true}), "");
  static_assert(any_of({false, false, true, false}), "");
  static_assert(!any_of({false}), "");
  static_assert(!any_of({false, false, false}), "");
}

TEST(ParameterPack, AllOf) {
  static_assert(all_of({true, true, true}), "");
  static_assert(!all_of({true, true, true, false}), "");
  static_assert(!all_of({false}), "");
  static_assert(!all_of({false, false}), "");
}

TEST(ParameterPack, Count) {
  static_assert(count({1, 2, 2, 2, 2, 2, 3}, 2) == 5u, "");
}

TEST(ParameterPack, HasType) {
  static_assert(ParameterPack<int, float, bool>::HasType<int>(), "");
  static_assert(ParameterPack<int, float, bool>::HasType<bool>(), "");
  static_assert(ParameterPack<int, float, bool>::HasType<bool>(), "");
  static_assert(!ParameterPack<int, float, bool>::HasType<void*>(), "");
}

TEST(ParameterPack, OnlyHasType) {
  static_assert(ParameterPack<int, int>::OnlyHasType<int>(), "");
  static_assert(ParameterPack<int, int, int, int>::OnlyHasType<int>(), "");
  static_assert(!ParameterPack<int, bool>::OnlyHasType<int>(), "");
  static_assert(!ParameterPack<int, int, bool, int>::OnlyHasType<int>(), "");
  static_assert(!ParameterPack<int, int, int>::OnlyHasType<bool>(), "");
}

TEST(ParameterPack, IsUniqueInPack) {
  static_assert(ParameterPack<int, float, bool>::IsUniqueInPack<int>(), "");
  static_assert(!ParameterPack<int, int, bool>::IsUniqueInPack<int>(), "");
}

TEST(ParameterPack, IndexInPack) {
  static_assert(ParameterPack<int, float, bool>::IndexInPack<int>() == 0u, "");
  static_assert(ParameterPack<int, float, bool>::IndexInPack<float>() == 1u,
                "");
  static_assert(ParameterPack<int, float, bool>::IndexInPack<bool>() == 2u, "");
  static_assert(
      ParameterPack<int, float, bool>::IndexInPack<void*>() == pack_npos, "");
}

TEST(ParameterPack, NthType) {
  static_assert(
      std::is_same<int, ParameterPack<int, float, bool>::NthType<0>>::value,
      "");
  static_assert(
      std::is_same<float, ParameterPack<int, float, bool>::NthType<1>>::value,
      "");
  static_assert(
      std::is_same<bool, ParameterPack<int, float, bool>::NthType<2>>::value,
      "");
}

TEST(ParameterPack, IsAllSameType) {
  static_assert(ParameterPack<int>::IsAllSameType(), "");
  static_assert(ParameterPack<int, int, int>::IsAllSameType(), "");
  static_assert(!ParameterPack<int, int, int, int, bool>::IsAllSameType(), "");
}

}  // namespace base


text:
package seccomp

import "github.com/opencontainers/runtime-tools/generate"

// IsEnabled returns false, when build without seccomp build tag.
func IsEnabled() bool {
	return false
}

// LoadProfileFromStruct takes a Seccomp struct and setup seccomp in the spec.
func LoadProfileFromStruct(config *Seccomp, specgen *generate.Generator) error {
	return nil
}

// LoadProfileFromBytes takes a byte slice and decodes the seccomp profile.
func LoadProfileFromBytes(body []byte, specgen *generate.Generator) error {
	return nil
}