text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import logging
import os

import numpy as np
import torch
import torch.nn as nn

import pickle
from collections import defaultdict
from tqdm import tqdm

from lego.model.pruner import BranchPruner, RelationPruner
from lego.data_process.dataloader import ProgramDataloader
from lego.common.utils import set_logger, parse_time, set_global_seed, construct_graph, eval_tuple, load_lse_checkpoint, load_pruner_checkpoint, set_train_mode

from smore.common.config import parse_args
from smore.cpp_sampler import sampler_clib
from lego.model import get_lse_model
from lego.env.runner import ProgramEnv

def parse_additional_args(parser):
    parser.add_argument('--do_search', action='store_true', default=False)
    parser.add_argument('--pruner_save_path', default="", type=str)
    parser.add_argument('--question_path', type=str, default=None)

    parser.add_argument('--search_time_stamp', default=None, type=str)
    parser.add_argument('--max_eps_len_list', default=None, type=str, help="")
    parser.add_argument('--start_idx', default=0, type=int, help="random seed")
    parser.add_argument('--end_idx', default=-1, type=int, help="random seed")

    parser.add_argument('--dataset_name', default=None, type=str)
    parser.add_argument('--branch_threshold', default=0.1, type=float, help="margin in the loss")
    parser.add_argument('--relation_threshold', default=50, type=int, help="margin in the loss")
    parser.add_argument('--beam_size', default=1, type=int, help="margin in the loss")
    parser.add_argument('--mask_mode', default="rs", type=str)
    return parser

def set_save_path(args):
    cur_time = parse_time()
    if args.search_time_stamp is None:
        args.search_time_stamp = cur_time
    args.save_path = os.path.join(args.pruner_save_path, "candidates/%s" % args.search_time_stamp)
    if not os.path.exists(args.save_path):
        os.makedirs(args.save_path)

    with open(os.path.join(args.save_path, "config.txt"), 'a+') as f:
        f.write("----------------------------------------------\n")
        f.write("%s\n"%cur_time)
        f.write("max_eps_len_list\n")
        f.write(str(args.max_eps_len_list)+"\n")
        f.write("----------------------------------------------\n")

def all_available_action(powersets, nrelation, x_scores, relation_threshold, mask_scores_class, relation_pruner, geo, mask_mode='none'):
    sampled_scores, sampled_relations, branches_picked_list = [], [], []
    for i in range(len(mask_scores_class[0])):
        if not mask_scores_class[0][i]:
            continue
        sampled_score = torch.LongTensor(np.array([i]))
        branches_picked = powersets[0][sampled_score[0].numpy()]
        if len(branches_picked) == 1:
            if mask_mode == 'rs':
                if geo == 'rotate':
                    rel_logits = relation_pruner(x_scores[branches_picked[0]].unsqueeze(0))
                elif geo == 'box':
                    center, offset = torch.chunk(x_scores[branches_picked[0]], 2, -1)
                    rel_logits = relation_pruner(center.unsqueeze(0))
                _, indices = torch.topk(rel_logits, relation_threshold)
                indices = indices.detach().cpu().numpy().T
            else:
                assert mask_mode == 'none'
                indices = np.random.choice(nrelation, relation_threshold, replace=False).reshape([relation_threshold, 1])

            sampled_scores.extend([sampled_score]*len(indices))
            sampled_relations.extend(indices)
            branches_picked_list.extend([branches_picked]*len(indices))
        else:
            sampled_relation = None

            sampled_scores.append(sampled_score)
            sampled_relations.append(sampled_relation)
            branches_picked_list.append(branches_picked)

    return sampled_scores, sampled_relations, branches_picked_list

def search_beam(args, relation_pruner, test_env, min_idx, max_idx, save_path='./'):
    all_logs = []

    print("number of queries", test_env.n_query)
    if max_idx == -1:
        max_idx = test_env.n_query
    for i in range(test_env.n_query):
        obs, done, ep_reward = test_env.reset(), False, 0
        if i < min_idx:
            continue
        if i >= max_idx:
            break
        if len(obs[0]) == 4:
            continue
        print ('-'*50, '(%d)'%i, test_env.queries[0], '-'*50)
        print ('-'*50, '(%d)'%i, test_env.questions[0], '-'*50)

        if args.dataset_name == 'webqsp':
            if len(obs[0]) == 3:
                continue
            threshold = args.relation_threshold
        elif args.dataset_name == 'cwq':
            if len(obs[0]) == 3 and args.mask_mode == 'none':
                threshold = 20
            else:
                threshold = args.relation_threshold

        assert obs[0] != None
        steps = 0
        same = True
        obs_list = [obs]
        # base_lls = [0]
        final_ll, final_reward, final_logs, final_structures = [], [], [], []
        while True:
            prev_obs_list = []
            all_sampled_scores, all_sampled_relations, all_branches_picked = [], [], []
            new_obs_list = []
            for obs in obs_list:
                x_scores, x_relations, berts, edge_indices, softmax_edge_indices, \
                    n_program, max_y_score_len, powersets, value_edge_indices, mask_scores_class, tmp_structure, steps_so_far = obs

                sampled_scores, sampled_relations, branches_picked_list = all_available_action(powersets, test_env.latent_space_executor.nrelation,
                                                        x_scores, threshold,
                                                        mask_scores_class, relation_pruner, args.geo, mask_mode=args.mask_mode)

                prev_obs_list.extend([obs]*len(sampled_scores))
                all_sampled_scores.extend(sampled_scores)
                all_sampled_relations.extend(sampled_relations)
                all_branches_picked.extend(branches_picked_list)

            for idx in tqdm(range(len(prev_obs_list))):
                x_scores, x_relations, berts, edge_indices, softmax_edge_indices, \
                    n_program, max_y_score_len, powersets, value_edge_indices, mask_scores_class, tmp_structure, steps_so_far = prev_obs_list[idx]
                test_env.set_state(*prev_obs_list[idx])

                new_obs, reward, done, info = test_env.step(all_sampled_scores[idx], all_sampled_relations[idx], all_branches_picked[idx])
                if done:
                    if test_env.delayed_evaluation:
                        continue
                    final_reward.append(reward)
                    final_logs.append(info)
                    final_structures.append(test_env.tmp_structure)
                else:
                    new_obs_list.append(new_obs)

            obs_list = new_obs_list
            steps += 1
            if len(obs_list) == 0:
                break
        if test_env.delayed_evaluation:
            final_reward, final_logs, final_structures = test_env.batch_evaluation()
        pickle.dump({'reward': final_reward, 'logs': final_logs, 'structures': final_structures}, open(os.path.join(save_path, "%d.pkl"%i), 'wb'))

def main(parser):
    parser = parse_additional_args(parser)
    args = parser.parse_args(None)
    set_global_seed(args.seed)
    assert args.do_train or args.do_valid or args.do_test or args.do_search
    set_train_mode(args)
    set_save_path(args)
    print ("Logging to", args.save_path)
    writer = set_logger(args)
    del writer

    latent_space_executor = get_lse_model(args)
    logging.info("Latent space executor created")
    load_lse_checkpoint(args, latent_space_executor)
    logging.info("Latent space executor loaded")

    relation_pruner = RelationPruner(latent_space_executor.entity_dim, args.nrelation)
    if args.geo == 'box':
        branch_pruner = BranchPruner(latent_space_executor.entity_dim * 2)
    elif args.geo == 'rotate':
        branch_pruner = BranchPruner(latent_space_executor.entity_dim)
    logging.info("Pruner created")
    load_pruner_checkpoint(args, relation_pruner, branch_pruner)
    logging.info("Pruner loaded")
    if args.cuda:
        latent_space_executor = latent_space_executor.cuda()
        relation_pruner = relation_pruner.cuda()
        branch_pruner = branch_pruner.cuda()

    kg = sampler_clib.create_kg(args.nentity, args.nrelation, args.kg_dtype)
    kg.load_triplets(os.path.join(args.data_path, "train_indexified.txt"), True)
    ent_in, ent_out, _ = construct_graph(args.data_path, ["train_indexified.txt"])
    logging.info("KG constructed")

    if args.dataset_name == 'webqsp':
        all_berts = pickle.load(open(os.path.join(args.question_path, "q_berts.pkl"), 'rb'))
        questions_to_search = pickle.load(open(os.path.join(args.question_path, "all_train_vanilla_datasets_with_query_structure.pkl"), 'rb'))
        with open(os.path.join(args.question_path, 'all_test_%s_fn_answers.pkl'%args.dataset_name), 'rb') as f:
            question_answers = pickle.load(f)
        for i in tqdm(range(len(questions_to_search)), disable=not args.print_on_screen):
            question = questions_to_search[i][0][-1]
            for j in range(len(questions_to_search[i])):
                assert (question in question_answers)
                questions_to_search[i][j][0] = all_berts[question]
                questions_to_search[i][j].append(np.ones(args.nrelation)) #! place holder
    else:
        raise NotImplemented

    test_train_iterator = ProgramDataloader(questions_to_search, args.nentity, args.nrelation, 1, latent_space_executor, shuffle=False, reduce='max')

    args.force = True
    args.reward_metrics = 'mrr'
    test_traversed_fn_answers = None
    args.min_eps_len = 2
    args.filter_3p = False
    args.keep_original_intersection_order = True
    args.delayed_evaluation = True
    args.min_eps_len_list = None

    env = ProgramEnv(test_train_iterator, latent_space_executor, question_answers, ent_out, args.force, args.dataset_name, reward_metrics=args.reward_metrics, traversed_answer=test_traversed_fn_answers, min_eps_len=args.min_eps_len, filter_3p=args.filter_3p, answer_type='query' if args.dataset_name=='metaqa' else 'question', keep_original_intersection_order=args.keep_original_intersection_order, intersection_selector=branch_pruner, intersection_threshold=args.branch_threshold, max_eps_len_list=None if args.max_eps_len_list is None else eval_tuple(args.max_eps_len_list), delayed_evaluation=args.delayed_evaluation, min_eps_len_list=None if args.min_eps_len_list is None else eval_tuple(args.min_eps_len_list))

    search_beam(args, relation_pruner, env, min_idx=args.start_idx, max_idx=args.end_idx, save_path=args.save_path)

if __name__ == '__main__':
    main(parse_args())


text:
using Stormpath.Owin.Abstractions.Configuration;
using Stormpath.Owin.Abstractions.ViewModel;

namespace Stormpath.Owin.Middleware.ViewModelBuilder
{
    public sealed class VerifyEmailFormViewModelBuilder
    {
        private readonly IntegrationConfiguration _configuration;

        public VerifyEmailFormViewModelBuilder(
            IntegrationConfiguration configuration)
        {
            _configuration = configuration;
        }

        public VerifyEmailFormViewModel Build()
        {
            var baseViewModelBuilder = new VerifyEmailViewModelBuilder(_configuration.Web);
            var result = new VerifyEmailFormViewModel(baseViewModelBuilder.Build());

            // Add a state (CSRF) token
            result.StateToken = new StateTokenBuilder(_configuration.Application.Id, _configuration.OktaEnvironment.ClientSecret).ToString();

            return result;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
@interface UITableView (FDTemplateLayoutCell)

/// Access to internal template layout cell for given reuse identifier.
/// Generally, you don't need to know these template layout cells.
///
/// @param identifier Reuse identifier for cell which must be registered.
///
- (__kindof UITableViewCell *)fd_templateCellForReuseIdentifier:(NSString *)identifier;

/// Returns height of cell of type specifed by a reuse identifier and configured
/// by the configuration block.
///
/// The cell would be layed out on a fixed-width, vertically expanding basis with
/// respect to its dynamic content, using auto layout. Thus, it is imperative that
/// the cell was set up to be self-satisfied, i.e. its content always determines
/// its height given the width is equal to the tableview's.
///
/// @param identifier A string identifier for retrieving and maintaining template
///        cells with system's "-dequeueReusableCellWithIdentifier:" call.
/// @param configuration An optional block for configuring and providing content
///        to the template cell. The configuration should be minimal for scrolling
///        performance yet sufficient for calculating cell's height.
///
- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier configuration:(void (^)(id cell))configuration;

/// This method does what "-fd_heightForCellWithIdentifier:configuration" does, and
/// calculated height will be cached by its index path, returns a cached height
/// when needed. Therefore lots of extra height calculations could be saved.
///
/// No need to worry about invalidating cached heights when data source changes, it
/// will be done automatically when you call "-reloadData" or any method that triggers
/// UITableView's reloading.
///
/// @param indexPath where this cell's height cache belongs.
///
- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByIndexPath:(NSIndexPath *)indexPath configuration:(void (^)(id cell))configuration;

/// This method caches height by your model entity's identifier.
/// If your model's changed, call "-invalidateHeightForKey:(id <NSCopying>)key" to
/// invalidate cache and re-calculate, it's much cheaper and effective than "cacheByIndexPath".
///
/// @param key model entity's identifier whose data configures a cell.
///
- (CGFloat)fd_heightForCellWithIdentifier:(NSString *)identifier cacheByKey:(id<NSCopying>)key configuration:(void (^)(id cell))configuration;

@end

@interface UITableView (FDTemplateLayoutHeaderFooterView)

/// Returns header or footer view's height that registered in table view with reuse identifier.
///
/// Use it after calling "-[UITableView registerNib/Class:forHeaderFooterViewReuseIdentifier]",
/// same with "-fd_heightForCellWithIdentifier:configuration:", it will call "-sizeThatFits:" for
/// subclass of UITableViewHeaderFooterView which is not using Auto Layout.
///
- (CGFloat)fd_heightForHeaderFooterViewWithIdentifier:(NSString *)identifier configuration:(void (^)(id headerFooterView))configuration;

@end

@interface UITableViewCell (FDTemplateLayoutCell)

/// Indicate this is a template layout cell for calculation only.
/// You may need this when there are non-UI side effects when configure a cell.
/// Like:
///   - (void)configureCell:(FooCell *)cell atIndexPath:(NSIndexPath *)indexPath {
///       cell.entity = [self entityAtIndexPath:indexPath];
///       if (!cell.fd_isTemplateLayoutCell) {
///           [self notifySomething]; // non-UI side effects
///       }
///   }
///
@property (nonatomic, assign) BOOL fd_isTemplateLayoutCell;

/// Enable to enforce this template layout cell to use "frame layout" rather than "auto layout",
/// and will ask cell's height by calling "-sizeThatFits:", so you must override this method.
/// Use this property only when you want to manually control this template layout cell's height
/// calculation mode, default to NO.
///
@property (nonatomic, assign) BOOL fd_enforceFrameLayout;

@end


text:
ActiveRecord::Schema.define(version: 20160128191420) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "agencies", force: :cascade do |t|
    t.string "name"
    t.string "phone"
    t.string "fax"
    t.string "email"
    t.string "address"
    t.string "city"
    t.string "state"
    t.string "zip"
  end

  create_table "budgets", force: :cascade do |t|
    t.float    "earned_income1"
    t.float    "unearned_income1"
    t.float    "earned_income2"
    t.float    "unearned_income2"
    t.float    "other_household_income"
    t.float    "child_support"
    t.float    "food_stamps"
    t.float    "security_deposit_refund"
    t.float    "rent"
    t.float    "utilities"
    t.float    "phone"
    t.float    "food"
    t.float    "health_insurance"
    t.float    "medical"
    t.float    "auto_loan"
    t.float    "auto_insurance"
    t.float    "auto_expenses"
    t.float    "public_transportation"
    t.float    "child_care"
    t.float    "clothing"
    t.float    "toiletries"
    t.float    "household"
    t.float    "television"
    t.float    "internet"
    t.float    "installment_payments"
    t.string   "installment_payment_description"
    t.float    "miscellaneous_expenses"
    t.string   "miscellaneous_expenses_description"
    t.datetime "created_at",                         null: false
    t.datetime "updated_at",                         null: false
  end

  create_table "comments", force: :cascade do |t|
    t.integer  "user_id"
    t.integer  "grant_id"
    t.text     "body"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "coverage_types", force: :cascade do |t|
    t.string "description"
  end

  create_table "coverage_types_grants", force: :cascade do |t|
    t.integer "coverage_type_id"
    t.integer "grant_id"
  end

  add_index "coverage_types_grants", ["coverage_type_id"], name: "index_coverage_types_grants_on_coverage_type_id", using: :btree
  add_index "coverage_types_grants", ["grant_id"], name: "index_coverage_types_grants_on_grant_id", using: :btree

  create_table "data_import_history_logs", force: :cascade do |t|
    t.integer  "ehf_records_processed"
    t.integer  "ehf_records_imported"
    t.text     "errors"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "grant_statuses", force: :cascade do |t|
    t.string "description"
  end

  create_table "grants", force: :cascade do |t|
    t.date     "application_date"
    t.string   "details"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "ehf_number"
    t.float    "total_rent"
    t.float    "adjusted_rent"
    t.boolean  "subsidized"
    t.integer  "subsidy_type_id"
    t.integer  "months_owed"
    t.float    "rent_owed"
    t.float    "security_deposit_owed"
    t.string   "utility_type_owed"
    t.float    "utility_owed"
    t.float    "grant_amount"
    t.datetime "funding_date"
    t.integer  "residence_id"
    t.integer  "previous_residence_id"
    t.integer  "grant_status_id"
    t.integer  "user_id"
    t.integer  "last_month_budget_id"
    t.integer  "current_month_budget_id"
    t.integer  "next_month_budget_id"
    t.string   "step"
  end

  create_table "grants_reason_types", force: :cascade do |t|
    t.integer "grant_id"
    t.integer "reason_type_id"
  end

  add_index "grants_reason_types", ["grant_id"], name: "index_grants_reason_types_on_grant_id", using: :btree
  add_index "grants_reason_types", ["reason_type_id"], name: "index_grants_reason_types_on_reason_type_id", using: :btree

  create_table "income_types", force: :cascade do |t|
    t.string "description"
  end

  create_table "incomes", force: :cascade do |t|
    t.integer  "person_id"
    t.boolean  "current"
    t.date     "start_date"
    t.date     "end_date"
    t.string   "employer"
    t.string   "occupation"
    t.float    "monthly_income"
    t.string   "reason_for_leaving"
    t.boolean  "disabled"
    t.boolean  "full_time"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "income_type_id"
  end

  create_table "other_payments", force: :cascade do |t|
    t.integer "grant_id"
    t.float   "amount"
    t.date    "date_paid"
    t.string  "description"
  end

  create_table "payees", force: :cascade do |t|
    t.integer "grant_id"
    t.string  "name"
    t.string  "attention"
    t.string  "street_address"
    t.string  "unit_number"
    t.string  "city"
    t.string  "state"
    t.string  "zip"
    t.string  "email"
    t.string  "phone"
    t.float   "check_amount"
    t.date    "check_date"
    t.string  "check_number"
  end

  create_table "people", force: :cascade do |t|
    t.integer  "grant_id"
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.string   "phone"
    t.date     "birth_date"
    t.boolean  "veteran"
    t.boolean  "student"
    t.boolean  "full_time_student"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "cell"
  end

  create_table "reason_types", force: :cascade do |t|
    t.string   "description"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "residence_types", force: :cascade do |t|
    t.string "description"
  end

  create_table "residences", force: :cascade do |t|
    t.string  "address"
    t.string  "unit_number"
    t.string  "city"
    t.string  "state"
    t.string  "zip"
    t.integer "residence_type_id"
    t.date    "move_in_date"
    t.date    "move_out_date"
    t.string  "reason_left"
    t.boolean "transitional_housing"
    t.float   "rent"
    t.float   "deposit"
    t.float   "amount_returned"
  end

  create_table "subsidy_types", force: :cascade do |t|
    t.string "description"
  end

  create_table "uploads", force: :cascade do |t|
    t.integer  "user_id",           null: false
    t.string   "user_type",         null: false
    t.string   "description"
    t.string   "category"
    t.string   "file_fingerprint",  null: false
    t.string   "file_file_name",    null: false
    t.string   "file_content_type", null: false
    t.integer  "file_file_size",    null: false
    t.datetime "file_updated_at",   null: false
    t.datetime "created_at",        null: false
    t.datetime "updated_at",        null: false
  end

  add_index "uploads", ["user_type", "user_id"], name: "index_uploads_on_user_type_and_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string   "email",                  default: "",            null: false
    t.string   "encrypted_password",     default: "",            null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,             null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.inet     "current_sign_in_ip"
    t.inet     "last_sign_in_ip"
    t.datetime "created_at",                                     null: false
    t.datetime "updated_at",                                     null: false
    t.string   "role",                   default: "case_worker", null: false
    t.string   "first_name"
    t.string   "last_name"
    t.integer  "agency_id"
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.integer  "failed_attempts",        default: 0,             null: false
    t.string   "unlock_token"
    t.datetime "locked_at"
  end

  add_index "users", ["agency_id"], name: "index_users_on_agency_id", using: :btree
  add_index "users", ["confirmation_token"], name: "index_users_on_confirmation_token", unique: true, using: :btree
  add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree
  add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree
  add_index "users", ["unlock_token"], name: "index_users_on_unlock_token", unique: true, using: :btree

  add_foreign_key "coverage_types_grants", "coverage_types"
  add_foreign_key "coverage_types_grants", "grants", on_delete: :cascade
  add_foreign_key "grants", "budgets", column: "current_month_budget_id"
  add_foreign_key "grants", "budgets", column: "last_month_budget_id"
  add_foreign_key "grants", "budgets", column: "next_month_budget_id"
  add_foreign_key "grants", "grant_statuses"
  add_foreign_key "grants", "residences"
  add_foreign_key "grants", "residences", column: "previous_residence_id"
  add_foreign_key "grants_reason_types", "grants", on_delete: :cascade
  add_foreign_key "grants_reason_types", "reason_types"
  add_foreign_key "incomes", "income_types"
  add_foreign_key "incomes", "people", on_delete: :cascade
  add_foreign_key "other_payments", "grants", on_delete: :cascade
  add_foreign_key "people", "grants", on_delete: :cascade
  add_foreign_key "residences", "residence_types"
  add_foreign_key "users", "agencies"
end


text:
{-# LANGUAGE OverloadedStrings #-}

import qualified Aws
import qualified Aws.S3 as S3
import Data.Conduit
import Data.Conduit.Binary
import Data.IORef
import Data.Monoid

import BkrAwsConfig

{-
-- Credentials
import Aws.Credentials
import Aws.Aws
import qualified Data.ByteString.Char8 as B

-- Configuration
import           Aws.Http
import           Aws.S3.Info
import           Aws.Ses.Info
import           Aws.Signature
import           Aws.SimpleDb.Info
import           Aws.Sqs.Info
-}
-- A small function to save the object's data into a file.
saveObject :: Aws.HTTPResponseConsumer ()
saveObject status headers source = source $$ sinkFile "tst.txt"

listObject :: Aws.HTTPResponseConsumer ()
listObject status headers source = do
           obj <- source $$ Data.Conduit.Binary.lines
           print $ show obj

main :: IO ()
main = do
  -- Set up AWS credentials and the default configuration.
  --cfg <- baseConfiguration'
  --let cfg = baseConfiguration''
  let cfg = getS3Config

  -- Create an IORef to store the response Metadata (so it is also available in case of an error).
  metadataRef <- newIORef mempty

  -- Create a request object with S3.getObject and run the request with simpleAwsRef.
  --Aws.simpleAwsRef cfg metadataRef $ S3.getObject "haskell-aws" "cloud-remote.pdf" saveObject
  --Aws.simpleAwsRef cfg metadataRef $ S3.getObject "ms-bkr" "_DSC2283.NEF" saveObject
  bucket <- Aws.simpleAwsRef cfg metadataRef $ S3.getBucket "ms-bkr"
  print $ show bucket

  -- Print the response metadata.
  print =<< readIORef metadataRef

{-
getCredentials :: Credentials
getCredentials = Credentials (B.pack "AKIAJNREVFV4JQNNNQRQ") (B.pack "dqQmkG7q4TwJemnEoqVeSppTuOcMp6RoBRZCpibp")

baseConfiguration' :: IO Configuration
baseConfiguration' = do
  --let cr = getCredentials
  let cr = Credentials (B.pack "AKIAJNREVFV4JQNNNQRQ") (B.pack "dqQmkG7q4TwJemnEoqVeSppTuOcMp6RoBRZCpibp")
  return Configuration {
                      timeInfo = Timestamp
                    , credentials = cr
                    , sdbInfo = sdbHttpsPost sdbUsEast
                    , sdbInfoUri = sdbHttpsGet sdbUsEast
                    , s3Info = s3 HTTP s3EndpointUsClassic False
                    , s3InfoUri = s3 HTTP s3EndpointUsClassic True
                    , sqsInfo = sqs HTTP sqsEndpointUsClassic False
                    , sqsInfoUri = sqs HTTP sqsEndpointUsClassic True
                    , sesInfo = sesHttpsPost sesUsEast
                    , sesInfoUri = sesHttpsGet sesUsEast
                    , logger = defaultLog Warning
                    }

baseConfiguration'' :: Configuration
baseConfiguration'' = do
  --let cr = getCredentials
  let cr = Credentials (B.pack "AKIAJNREVFV4JQNNNQRQ") (B.pack "dqQmkG7q4TwJemnEoqVeSppTuOcMp6RoBRZCpibp")
  Configuration { timeInfo = Timestamp
                , credentials = cr
                , sdbInfo = sdbHttpsPost sdbUsEast
                , sdbInfoUri = sdbHttpsGet sdbUsEast
                , s3Info = s3 HTTP s3EndpointUsClassic False
                , s3InfoUri = s3 HTTP s3EndpointUsClassic True
                , sqsInfo = sqs HTTP sqsEndpointUsClassic False
                , sqsInfoUri = sqs HTTP sqsEndpointUsClassic True
                , sesInfo = sesHttpsPost sesUsEast
                , sesInfoUri = sesHttpsGet sesUsEast
                , logger = defaultLog Warning
                }
-}


text:
import { Mongo } from 'meteor/mongo';

export const Classes = new Mongo.Collection('classes');


text:
<?php
/****
index.php - Controller_Index
-----------
author: Mike Elsmore<mike@elsmore.me>
****/

class Controller_Index extends Controller_Base {

	// Index Action
	public function IndexAction()
	{

		//

	}

}


text:
@interface WorkstationSetupXMLParser : NSObject <NSXMLParserDelegate> {
    NSMutableString *curElem;
    NSMutableString *startingElem;
    NSMutableString *imageName;
    NSMutableString *pointDesc;
    NSMutableDictionary *descDictionary;
    NSMutableString *title;
    NSMutableDictionary *workstationSetupDictionary;
}

@property (nonatomic, retain) NSMutableString *curElem;
@property (nonatomic, retain) NSMutableString *startingElem;
@property (nonatomic, retain) NSMutableString *imageName;
@property (nonatomic, retain) NSMutableString *pointDesc;
@property (nonatomic, retain) NSMutableDictionary *descDictionary;
@property (nonatomic, retain) NSMutableString *title;
@property (nonatomic, retain) NSMutableDictionary *workstationSetupDictionary;

- (WorkstationSetupXMLParser*) initXMLParser;
- (NSMutableDictionary *) getDictionary;

@end


text:
<?php

namespace Traitor\GetSet;

/**
 * A field that is expanded by a virtual getter and setter.
 *
 * @author moe
 */
interface Field
{
    /**
     * The field's name
     * @param String $name
     */
    function setName($name);

    /**
     * @return String
     */
    function getName();

    /**
     * The field's current value.
     */
    function getValue();

    /**
     * @param mixed $value The value to set
     * @throws Exception Generic run time exception if something is wrong and
     * therefore the value cannot be set. Usually this will be the case
     * if something is not configured/initialized properly.
     * @throws \InvalidArgumentException If $value is not valid for this field.
     */
    function setValue($value);
}


text:
package com.envyleague.cricket.domain;

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.validator.constraints.Email;

import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Entity
@Table(name = "EL_USER")
public class User implements Serializable {
    @NotNull
    @Size(min = 0, max = 50)
    @Id
    @Column(length = 50)
    private String login;

    @JsonIgnore
    @Size(min = 0, max = 100)
    @Column(length = 100)
    private String password;

    @Size(min = 0, max = 50)
    @Column(name = "name", length = 50)
    private String name;

    @Email
    @Size(min = 0, max = 100)
    @Column(length = 100)
    private String email;

    private boolean activated = false;

    @Size(min = 2, max = 5)
    @Column(name = "lang_key", length = 5)
    private String langKey;

    @Size(min = 0, max = 20)
    @Column(name = "ACTIVATION_KEY", length = 20)
    private String activationKey;

    @Column(name="FACEBOOK_USER_ID", length = 500)
    private String facebookUserId;

    @Column(name="FACEBOOK_AUTH_TOKEN", length = 500)
    private String facebookAuthToken;

    @Enumerated(EnumType.STRING)
    private Status status = Status.PENDING;

    @OneToMany(mappedBy = "userLeagueKey.user", cascade = CascadeType.ALL)
    private Set<UserLeague> userLeagues = new HashSet<>();

    @ElementCollection(targetClass = Authority.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "EL_USER_AUTHORITY", joinColumns = @JoinColumn(name = "login"))
    @Column(name = "name", nullable = false)
    @Enumerated(EnumType.STRING)
    private Set<Authority> authorities = new HashSet<>();

    @JsonIgnore
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "user")
    private Set<PersistentToken> persistentTokens = new HashSet<>();

    public String getLogin() {
        return login;
    }

    public void setLogin(String login) {
        this.login = login;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isActivated() {
        return activated;
    }

    public void setActivated(boolean activated) {
        this.activated = activated;
    }

    public String getActivationKey() {
        return activationKey;
    }

    public void setActivationKey(String activationKey) {
        this.activationKey = activationKey;
    }

    public String getLangKey() {
        return langKey;
    }

    public void setLangKey(String langKey) {
        this.langKey = langKey;
    }

    public String getFacebookUserId() {
        return facebookUserId;
    }

    public void setFacebookUserId(String facebookUserId) {
        this.facebookUserId = facebookUserId;
    }

    public String getFacebookAuthToken() {
        return facebookAuthToken;
    }

    public void setFacebookAuthToken(String facebookAuthToken) {
        this.facebookAuthToken = facebookAuthToken;
    }

    public Set<Authority> getAuthorities() {
        return authorities;
    }

    public void setAuthorities(Set<Authority> authorities) {
        this.authorities = authorities;
    }

    public Set<PersistentToken> getPersistentTokens() {
        return persistentTokens;
    }

    public void setPersistentTokens(Set<PersistentToken> persistentTokens) {
        this.persistentTokens = persistentTokens;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    public Set<UserLeague> getUserLeagues() {
        return userLeagues;
    }

    public void setUserLeagues(Set<UserLeague> userLeagues) {
        this.userLeagues = userLeagues;
    }

    @JsonIgnore
    public List<League> getLeagues() {
        return userLeagues.stream().map(UserLeague::getLeague).collect(Collectors.toList());
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        User user = (User) o;

        if (!login.equals(user.login)) {
            return false;
        }

        return true;
    }

    @Override
    public int hashCode() {
        return login.hashCode();
    }

    @Override
    public String toString() {
        return "User{" +
                "login='" + login + '\'' +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", activated=" + activated +
                ", langKey='" + langKey + '\'' +
                ", facebookUserId='" + facebookUserId + '\'' +
                ", userLeagues=" + userLeagues +
                ", authorities=" + authorities +
                '}';
    }

}


text:
package org.apache.sshd.common.cipher;

import org.apache.sshd.common.Cipher;
import org.apache.sshd.common.NamedFactory;

/**
 * ARCFOUR256 cipher
 *
 * @author Apache MINA SSHD Project
 */
public class ARCFOUR256 extends BaseCipher {

    /**
     * Named factory for AES128CTR Cipher
     */
    public static class Factory implements NamedFactory<Cipher> {
        public String getName() {
            return "arcfour256";
        }
        public Cipher create() {
            return new ARCFOUR256();
        }
    }

    public ARCFOUR256() {
        super(8, 32, "ARCFOUR", "RC4");
    }

    @Override
    public void init(Mode mode, byte[] key, byte[] iv) throws Exception {
        super.init(mode, key, iv);
        try {
            byte[] foo = new byte[1];
            for (int i = 0; i < 1536; i++) {
                cipher.update(foo, 0, 1, foo, 0);
            }
        } catch (Exception e) {
            cipher = null;
            throw e;
        }
    }
}


text:
/* i2c-core.c - a device driver for the iic-bus interface		     */
/* ------------------------------------------------------------------------- */
/*   Copyright (C) 1995-99 Simon G. Vogl

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.		     */
/* ------------------------------------------------------------------------- */

/* With some changes from Kyösti Mälkki <kmalkki@cc.hut.fi>.
   All SMBus-related things are written by Frodo Looijaard <frodol@dds.nl>
   SMBus 2.0 support by Mark Studebaker <mdsxyz123@yahoo.com>                */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/i2c.h>
#include <linux/init.h>
#include <linux/idr.h>
#include <linux/seq_file.h>
#include <asm/uaccess.h>

static LIST_HEAD(adapters);
static LIST_HEAD(drivers);
static DECLARE_MUTEX(core_lists);
static DEFINE_IDR(i2c_adapter_idr);

static int i2c_device_match(struct device *dev, struct device_driver *drv)
{
	return 1;
}

static int i2c_bus_suspend(struct device * dev, pm_message_t state)
{
	int rc = 0;

	if (dev->driver && dev->driver->suspend)
		rc = dev->driver->suspend(dev,state,0);
	return rc;
}

static int i2c_bus_resume(struct device * dev)
{
	int rc = 0;

	if (dev->driver && dev->driver->resume)
		rc = dev->driver->resume(dev,0);
	return rc;
}

struct bus_type i2c_bus_type = {
	.name =	"i2c",
	.match = i2c_device_match,
	.suspend = i2c_bus_suspend,
	.resume = i2c_bus_resume,
};

static int i2c_device_probe(struct device *dev)
{
	return -ENODEV;
}

static int i2c_device_remove(struct device *dev)
{
	return 0;
}

void i2c_adapter_dev_release(struct device *dev)
{
	struct i2c_adapter *adap = dev_to_i2c_adapter(dev);
	complete(&adap->dev_released);
}

struct device_driver i2c_adapter_driver = {
	.name =	"i2c_adapter",
	.bus = &i2c_bus_type,
	.probe = i2c_device_probe,
	.remove = i2c_device_remove,
};

static void i2c_adapter_class_dev_release(struct class_device *dev)
{
	struct i2c_adapter *adap = class_dev_to_i2c_adapter(dev);
	complete(&adap->class_dev_released);
}

struct class i2c_adapter_class = {
	.name =	"i2c-adapter",
	.release =&i2c_adapter_class_dev_release,
};

static ssize_t show_adapter_name(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct i2c_adapter *adap = dev_to_i2c_adapter(dev);
	return sprintf(buf, "%s\n", adap->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_adapter_name, NULL);

static void i2c_client_release(struct device *dev)
{
	struct i2c_client *client = to_i2c_client(dev);
	complete(&client->released);
}

static ssize_t show_client_name(struct device *dev, struct device_attribute *attr, char *buf)
{
	struct i2c_client *client = to_i2c_client(dev);
	return sprintf(buf, "%s\n", client->name);
}

/*
 * We can't use the DEVICE_ATTR() macro here as we want the same filename for a
 * different type of a device.  So beware if the DEVICE_ATTR() macro ever
 * changes, this definition will also have to change.
 */
static struct device_attribute dev_attr_client_name = {
	.attr = {.name = "name", .mode = S_IRUGO, .owner = THIS_MODULE },
	.show   =  &show_client_name,
};

/* ---------------------------------------------------
 * registering functions
 * ---------------------------------------------------
 */

/* -----
 * i2c_add_adapter is called from within the algorithm layer,
 * when a new hw adapter registers. A new device is register to be
 * available for clients.
 */
int i2c_add_adapter(struct i2c_adapter *adap)
{
	int id, res = 0;
	struct list_head   *item;
	struct i2c_driver  *driver;

	down(&core_lists);

	if (idr_pre_get(&i2c_adapter_idr, GFP_KERNEL) == 0) {
		res = -ENOMEM;
		goto out_unlock;
	}

	res = idr_get_new(&i2c_adapter_idr, adap, &id);
	if (res < 0) {
		if (res == -EAGAIN)
			res = -ENOMEM;
		goto out_unlock;
	}

	adap->nr =  id & MAX_ID_MASK;
	init_MUTEX(&adap->bus_lock);
	init_MUTEX(&adap->clist_lock);
	list_add_tail(&adap->list,&adapters);
	INIT_LIST_HEAD(&adap->clients);

	/* Add the adapter to the driver core.
	 * If the parent pointer is not set up,
	 * we add this adapter to the host bus.
	 */
	if (adap->dev.parent == NULL)
		adap->dev.parent = &platform_bus;
	sprintf(adap->dev.bus_id, "i2c-%d", adap->nr);
	adap->dev.driver = &i2c_adapter_driver;
	adap->dev.release = &i2c_adapter_dev_release;
	device_register(&adap->dev);
	device_create_file(&adap->dev, &dev_attr_name);

	/* Add this adapter to the i2c_adapter class */
	memset(&adap->class_dev, 0x00, sizeof(struct class_device));
	adap->class_dev.dev = &adap->dev;
	adap->class_dev.class = &i2c_adapter_class;
	strlcpy(adap->class_dev.class_id, adap->dev.bus_id, BUS_ID_SIZE);
	class_device_register(&adap->class_dev);

	dev_dbg(&adap->dev, "adapter [%s] registered\n", adap->name);

	/* inform drivers of new adapters */
	list_for_each(item,&drivers) {
		driver = list_entry(item, struct i2c_driver, list);
		if (driver->flags & I2C_DF_NOTIFY)
		/* We ignore the return code; if it fails, too bad */
		driver->attach_adapter(adap);
	}

out_unlock:
	up(&core_lists);
	return res;
}

int i2c_del_adapter(struct i2c_adapter *adap)
{
	struct list_head  *item, *_n;
	struct i2c_adapter *adap_from_list;
	struct i2c_driver *driver;
	struct i2c_client *client;
	int res = 0;

	down(&core_lists);

	/* First make sure that this adapter was ever added */
	list_for_each_entry(adap_from_list, &adapters, list) {
		if (adap_from_list == adap)
			break;
	}
	if (adap_from_list != adap) {
		pr_debug("i2c-core: attempting to delete unregistered "
			 "adapter [%s]\n", adap->name);
		res = -EINVAL;
		goto out_unlock;
	}

	list_for_each(item,&drivers) {
		driver = list_entry(item, struct i2c_driver, list);
		if (driver->detach_adapter)
			if ((res = driver->detach_adapter(adap))) {
				dev_err(&adap->dev, "detach_adapter failed "
					"for driver [%s]\n", driver->name);
				goto out_unlock;
			}
	}

	/* detach any active clients. This must be done first, because
	 * it can fail; in which case we give up. */
	list_for_each_safe(item, _n, &adap->clients) {
		client = list_entry(item, struct i2c_client, list);

		/* detaching devices is unconditional of the set notify
		 * flag, as _all_ clients that reside on the adapter
		 * must be deleted, as this would cause invalid states.
		 */
		if ((res=client->driver->detach_client(client))) {
			dev_err(&adap->dev, "detach_client failed for client "
				"[%s] at address 0x%02x\n", client->name,
				client->addr);
			goto out_unlock;
		}
	}

	/* clean up the sysfs representation */
	init_completion(&adap->dev_released);
	init_completion(&adap->class_dev_released);
	class_device_unregister(&adap->class_dev);
	device_remove_file(&adap->dev, &dev_attr_name);
	device_unregister(&adap->dev);
	list_del(&adap->list);

	/* wait for sysfs to drop all references */
	wait_for_completion(&adap->dev_released);
	wait_for_completion(&adap->class_dev_released);

	/* free dynamically allocated bus id */
	idr_remove(&i2c_adapter_idr, adap->nr);

	dev_dbg(&adap->dev, "adapter [%s] unregistered\n", adap->name);

 out_unlock:
	up(&core_lists);
	return res;
}

/* -----
 * What follows is the "upwards" interface: commands for talking to clients,
 * which implement the functions to access the physical information of the
 * chips.
 */

int i2c_add_driver(struct i2c_driver *driver)
{
	struct list_head   *item;
	struct i2c_adapter *adapter;
	int res = 0;

	down(&core_lists);

	/* add the driver to the list of i2c drivers in the driver core */
	driver->driver.name = driver->name;
	driver->driver.bus = &i2c_bus_type;
	driver->driver.probe = i2c_device_probe;
	driver->driver.remove = i2c_device_remove;

	res = driver_register(&driver->driver);
	if (res)
		goto out_unlock;

	list_add_tail(&driver->list,&drivers);
	pr_debug("i2c-core: driver [%s] registered\n", driver->name);

	/* now look for instances of driver on our adapters */
	if (driver->flags & I2C_DF_NOTIFY) {
		list_for_each(item,&adapters) {
			adapter = list_entry(item, struct i2c_adapter, list);
			driver->attach_adapter(adapter);
		}
	}

 out_unlock:
	up(&core_lists);
	return res;
}

int i2c_del_driver(struct i2c_driver *driver)
{
	struct list_head   *item1, *item2, *_n;
	struct i2c_client  *client;
	struct i2c_adapter *adap;

	int res = 0;

	down(&core_lists);

	/* Have a look at each adapter, if clients of this driver are still
	 * attached. If so, detach them to be able to kill the driver
	 * afterwards.
	 *
	 * Removing clients does not depend on the notify flag, else
	 * invalid operation might (will!) result, when using stale client
	 * pointers.
	 */
	list_for_each(item1,&adapters) {
		adap = list_entry(item1, struct i2c_adapter, list);
		if (driver->detach_adapter) {
			if ((res = driver->detach_adapter(adap))) {
				dev_err(&adap->dev, "detach_adapter failed "
					"for driver [%s]\n", driver->name);
				goto out_unlock;
			}
		} else {
			list_for_each_safe(item2, _n, &adap->clients) {
				client = list_entry(item2, struct i2c_client, list);
				if (client->driver != driver)
					continue;
				dev_dbg(&adap->dev, "detaching client [%s] "
					"at 0x%02x\n", client->name,
					client->addr);
				if ((res = driver->detach_client(client))) {
					dev_err(&adap->dev, "detach_client "
						"failed for client [%s] at "
						"0x%02x\n", client->name,
						client->addr);
					goto out_unlock;
				}
			}
		}
	}

	driver_unregister(&driver->driver);
	list_del(&driver->list);
	pr_debug("i2c-core: driver [%s] unregistered\n", driver->name);

 out_unlock:
	up(&core_lists);
	return 0;
}

static int __i2c_check_addr(struct i2c_adapter *adapter, unsigned int addr)
{
	struct list_head   *item;
	struct i2c_client  *client;

	list_for_each(item,&adapter->clients) {
		client = list_entry(item, struct i2c_client, list);
		if (client->addr == addr)
			return -EBUSY;
	}
	return 0;
}

int i2c_check_addr(struct i2c_adapter *adapter, int addr)
{
	int rval;

	down(&adapter->clist_lock);
	rval = __i2c_check_addr(adapter, addr);
	up(&adapter->clist_lock);

	return rval;
}

int i2c_attach_client(struct i2c_client *client)
{
	struct i2c_adapter *adapter = client->adapter;

	down(&adapter->clist_lock);
	if (__i2c_check_addr(client->adapter, client->addr)) {
		up(&adapter->clist_lock);
		return -EBUSY;
	}
	list_add_tail(&client->list,&adapter->clients);
	up(&adapter->clist_lock);

	if (adapter->client_register)  {
		if (adapter->client_register(client))  {
			dev_dbg(&adapter->dev, "client_register "
				"failed for client [%s] at 0x%02x\n",
				client->name, client->addr);
		}
	}

	if (client->flags & I2C_CLIENT_ALLOW_USE)
		client->usage_count = 0;

	client->dev.parent = &client->adapter->dev;
	client->dev.driver = &client->driver->driver;
	client->dev.bus = &i2c_bus_type;
	client->dev.release = &i2c_client_release;

	snprintf(&client->dev.bus_id[0], sizeof(client->dev.bus_id),
		"%d-%04x", i2c_adapter_id(adapter), client->addr);
	dev_dbg(&adapter->dev, "client [%s] registered with bus id %s\n",
		client->name, client->dev.bus_id);
	device_register(&client->dev);
	device_create_file(&client->dev, &dev_attr_client_name);

	return 0;
}

int i2c_detach_client(struct i2c_client *client)
{
	struct i2c_adapter *adapter = client->adapter;
	int res = 0;

	if ((client->flags & I2C_CLIENT_ALLOW_USE)
	 && (client->usage_count > 0)) {
		dev_warn(&client->dev, "Client [%s] still busy, "
			 "can't detach\n", client->name);
		return -EBUSY;
	}

	if (adapter->client_unregister)  {
		res = adapter->client_unregister(client);
		if (res) {
			dev_err(&client->dev,
				"client_unregister [%s] failed, "
				"client not detached\n", client->name);
			goto out;
		}
	}

	down(&adapter->clist_lock);
	list_del(&client->list);
	init_completion(&client->released);
	device_remove_file(&client->dev, &dev_attr_client_name);
	device_unregister(&client->dev);
	up(&adapter->clist_lock);
	wait_for_completion(&client->released);

 out:
	return res;
}

static int i2c_inc_use_client(struct i2c_client *client)
{

	if (!try_module_get(client->driver->owner))
		return -ENODEV;
	if (!try_module_get(client->adapter->owner)) {
		module_put(client->driver->owner);
		return -ENODEV;
	}

	return 0;
}

static void i2c_dec_use_client(struct i2c_client *client)
{
	module_put(client->driver->owner);
	module_put(client->adapter->owner);
}

int i2c_use_client(struct i2c_client *client)
{
	int ret;

	ret = i2c_inc_use_client(client);
	if (ret)
		return ret;

	if (client->flags & I2C_CLIENT_ALLOW_USE) {
		if (client->flags & I2C_CLIENT_ALLOW_MULTIPLE_USE)
			client->usage_count++;
		else if (client->usage_count > 0)
			goto busy;
		else
			client->usage_count++;
	}

	return 0;
 busy:
	i2c_dec_use_client(client);
	return -EBUSY;
}

int i2c_release_client(struct i2c_client *client)
{
	if(client->flags & I2C_CLIENT_ALLOW_USE) {
		if(client->usage_count>0)
			client->usage_count--;
		else {
			pr_debug("i2c-core: %s used one too many times\n",
				__FUNCTION__);
			return -EPERM;
		}
	}

	i2c_dec_use_client(client);

	return 0;
}

void i2c_clients_command(struct i2c_adapter *adap, unsigned int cmd, void *arg)
{
	struct list_head  *item;
	struct i2c_client *client;

	down(&adap->clist_lock);
	list_for_each(item,&adap->clients) {
		client = list_entry(item, struct i2c_client, list);
		if (!try_module_get(client->driver->owner))
			continue;
		if (NULL != client->driver->command) {
			up(&adap->clist_lock);
			client->driver->command(client,cmd,arg);
			down(&adap->clist_lock);
		}
		module_put(client->driver->owner);
       }
       up(&adap->clist_lock);
}

static int __init i2c_init(void)
{
	int retval;

	retval = bus_register(&i2c_bus_type);
	if (retval)
		return retval;
	retval = driver_register(&i2c_adapter_driver);
	if (retval)
		return retval;
	return class_register(&i2c_adapter_class);
}

static void __exit i2c_exit(void)
{
	class_unregister(&i2c_adapter_class);
	driver_unregister(&i2c_adapter_driver);
	bus_unregister(&i2c_bus_type);
}

subsys_initcall(i2c_init);
module_exit(i2c_exit);

/* ----------------------------------------------------
 * the functional interface to the i2c busses.
 * ----------------------------------------------------
 */

int i2c_transfer(struct i2c_adapter * adap, struct i2c_msg *msgs, int num)
{
	int ret;

	if (adap->algo->master_xfer) {
#ifdef DEBUG
		for (ret = 0; ret < num; ret++) {
			dev_dbg(&adap->dev, "master_xfer[%d] %c, addr=0x%02x, "
				"len=%d\n", ret, msgs[ret].flags & I2C_M_RD ?
				'R' : 'W', msgs[ret].addr, msgs[ret].len);
		}
#endif

		down(&adap->bus_lock);
		ret = adap->algo->master_xfer(adap,msgs,num);
		up(&adap->bus_lock);

		return ret;
	} else {
		dev_dbg(&adap->dev, "I2C level transfers not supported\n");
		return -ENOSYS;
	}
}

int i2c_master_send(struct i2c_client *client,const char *buf ,int count)
{
	int ret;
	struct i2c_adapter *adap=client->adapter;
	struct i2c_msg msg;

	msg.addr = client->addr;
	msg.flags = client->flags & I2C_M_TEN;
	msg.len = count;
	msg.buf = (char *)buf;

	ret = i2c_transfer(adap, &msg, 1);

	/* If everything went ok (i.e. 1 msg transmitted), return #bytes
	   transmitted, else error code. */
	return (ret == 1) ? count : ret;
}

int i2c_master_recv(struct i2c_client *client, char *buf ,int count)
{
	struct i2c_adapter *adap=client->adapter;
	struct i2c_msg msg;
	int ret;

	msg.addr = client->addr;
	msg.flags = client->flags & I2C_M_TEN;
	msg.flags |= I2C_M_RD;
	msg.len = count;
	msg.buf = buf;

	ret = i2c_transfer(adap, &msg, 1);

	/* If everything went ok (i.e. 1 msg transmitted), return #bytes
	   transmitted, else error code. */
	return (ret == 1) ? count : ret;
}

int i2c_control(struct i2c_client *client,
	unsigned int cmd, unsigned long arg)
{
	int ret = 0;
	struct i2c_adapter *adap = client->adapter;

	dev_dbg(&client->adapter->dev, "i2c ioctl, cmd: 0x%x, arg: %#lx\n", cmd, arg);
	switch (cmd) {
		case I2C_RETRIES:
			adap->retries = arg;
			break;
		case I2C_TIMEOUT:
			adap->timeout = arg;
			break;
		default:
			if (adap->algo->algo_control!=NULL)
				ret = adap->algo->algo_control(adap,cmd,arg);
	}
	return ret;
}

/* ----------------------------------------------------
 * the i2c address scanning function
 * Will not work for 10-bit addresses!
 * ----------------------------------------------------
 */
static int i2c_probe_address(struct i2c_adapter *adapter, int addr, int kind,
			     int (*found_proc) (struct i2c_adapter *, int, int))
{
	int err;

	/* Make sure the address is valid */
	if (addr < 0x03 || addr > 0x77) {
		dev_warn(&adapter->dev, "Invalid probe address 0x%02x\n",
			 addr);
		return -EINVAL;
	}

	/* Skip if already in use */
	if (i2c_check_addr(adapter, addr))
		return 0;

	/* Make sure there is something at this address, unless forced */
	if (kind < 0) {
		if (i2c_smbus_xfer(adapter, addr, 0, 0, 0,
				   I2C_SMBUS_QUICK, NULL) < 0)
			return 0;

		/* prevent 24RF08 corruption */
		if ((addr & ~0x0f) == 0x50)
			i2c_smbus_xfer(adapter, addr, 0, 0, 0,
				       I2C_SMBUS_QUICK, NULL);
	}

	/* Finally call the custom detection function */
	err = found_proc(adapter, addr, kind);

	/* -ENODEV can be returned if there is a chip at the given address
	   but it isn't supported by this chip driver. We catch it here as
	   this isn't an error. */
	return (err == -ENODEV) ? 0 : err;
}

int i2c_probe(struct i2c_adapter *adapter,
	      struct i2c_client_address_data *address_data,
	      int (*found_proc) (struct i2c_adapter *, int, int))
{
	int i, err;
	int adap_id = i2c_adapter_id(adapter);

	/* Forget it if we can't probe using SMBUS_QUICK */
	if (! i2c_check_functionality(adapter,I2C_FUNC_SMBUS_QUICK))
		return -1;

	/* Force entries are done first, and are not affected by ignore
	   entries */
	if (address_data->forces) {
		unsigned short **forces = address_data->forces;
		int kind;

		for (kind = 0; forces[kind]; kind++) {
			for (i = 0; forces[kind][i] != I2C_CLIENT_END;
			     i += 2) {
				if (forces[kind][i] == adap_id
				 || forces[kind][i] == ANY_I2C_BUS) {
					dev_dbg(&adapter->dev, "found force "
						"parameter for adapter %d, "
						"addr 0x%02x, kind %d\n",
						adap_id, forces[kind][i + 1],
						kind);
					err = i2c_probe_address(adapter,
						forces[kind][i + 1],
						kind, found_proc);
					if (err)
						return err;
				}
			}
		}
	}

	/* Probe entries are done second, and are not affected by ignore
	   entries either */
	for (i = 0; address_data->probe[i] != I2C_CLIENT_END; i += 2) {
		if (address_data->probe[i] == adap_id
		 || address_data->probe[i] == ANY_I2C_BUS) {
			dev_dbg(&adapter->dev, "found probe parameter for "
				"adapter %d, addr 0x%02x\n", adap_id,
				address_data->probe[i + 1]);
			err = i2c_probe_address(adapter,
						address_data->probe[i + 1],
						-1, found_proc);
			if (err)
				return err;
		}
	}

	/* Normal entries are done last, unless shadowed by an ignore entry */
	for (i = 0; address_data->normal_i2c[i] != I2C_CLIENT_END; i += 1) {
		int j, ignore;

		ignore = 0;
		for (j = 0; address_data->ignore[j] != I2C_CLIENT_END;
		     j += 2) {
			if ((address_data->ignore[j] == adap_id ||
			     address_data->ignore[j] == ANY_I2C_BUS)
			 && address_data->ignore[j + 1]
			    == address_data->normal_i2c[i]) {
				dev_dbg(&adapter->dev, "found ignore "
					"parameter for adapter %d, "
					"addr 0x%02x\n", adap_id,
					address_data->ignore[j + 1]);
			}
			ignore = 1;
			break;
		}
		if (ignore)
			continue;

		dev_dbg(&adapter->dev, "found normal entry for adapter %d, "
			"addr 0x%02x\n", adap_id,
			address_data->normal_i2c[i]);
		err = i2c_probe_address(adapter, address_data->normal_i2c[i],
					-1, found_proc);
		if (err)
			return err;
	}

	return 0;
}

struct i2c_adapter* i2c_get_adapter(int id)
{
	struct i2c_adapter *adapter;

	down(&core_lists);
	adapter = (struct i2c_adapter *)idr_find(&i2c_adapter_idr, id);
	if (adapter && !try_module_get(adapter->owner))
		adapter = NULL;

	up(&core_lists);
	return adapter;
}

void i2c_put_adapter(struct i2c_adapter *adap)
{
	module_put(adap->owner);
}

/* The SMBus parts */

#define POLY    (0x1070U << 3)
static u8
crc8(u16 data)
{
	int i;

	for(i = 0; i < 8; i++) {
		if (data & 0x8000)
			data = data ^ POLY;
		data = data << 1;
	}
	return (u8)(data >> 8);
}

/* CRC over count bytes in the first array plus the bytes in the rest
   array if it is non-null. rest[0] is the (length of rest) - 1
   and is included. */
static u8 i2c_smbus_partial_pec(u8 crc, int count, u8 *first, u8 *rest)
{
	int i;

	for(i = 0; i < count; i++)
		crc = crc8((crc ^ first[i]) << 8);
	if(rest != NULL)
		for(i = 0; i <= rest[0]; i++)
			crc = crc8((crc ^ rest[i]) << 8);
	return crc;
}

static u8 i2c_smbus_pec(int count, u8 *first, u8 *rest)
{
	return i2c_smbus_partial_pec(0, count, first, rest);
}

/* Returns new "size" (transaction type)
   Note that we convert byte to byte_data and byte_data to word_data
   rather than invent new xxx_PEC transactions. */
static int i2c_smbus_add_pec(u16 addr, u8 command, int size,
			     union i2c_smbus_data *data)
{
	u8 buf[3];

	buf[0] = addr << 1;
	buf[1] = command;
	switch(size) {
		case I2C_SMBUS_BYTE:
			data->byte = i2c_smbus_pec(2, buf, NULL);
			size = I2C_SMBUS_BYTE_DATA;
			break;
		case I2C_SMBUS_BYTE_DATA:
			buf[2] = data->byte;
			data->word = buf[2] ||
			            (i2c_smbus_pec(3, buf, NULL) << 8);
			size = I2C_SMBUS_WORD_DATA;
			break;
		case I2C_SMBUS_WORD_DATA:
			/* unsupported */
			break;
		case I2C_SMBUS_BLOCK_DATA:
			data->block[data->block[0] + 1] =
			             i2c_smbus_pec(2, buf, data->block);
			size = I2C_SMBUS_BLOCK_DATA_PEC;
			break;
	}
	return size;
}

static int i2c_smbus_check_pec(u16 addr, u8 command, int size, u8 partial,
			       union i2c_smbus_data *data)
{
	u8 buf[3], rpec, cpec;

	buf[1] = command;
	switch(size) {
		case I2C_SMBUS_BYTE_DATA:
			buf[0] = (addr << 1) | 1;
			cpec = i2c_smbus_pec(2, buf, NULL);
			rpec = data->byte;
			break;
		case I2C_SMBUS_WORD_DATA:
			buf[0] = (addr << 1) | 1;
			buf[2] = data->word & 0xff;
			cpec = i2c_smbus_pec(3, buf, NULL);
			rpec = data->word >> 8;
			break;
		case I2C_SMBUS_WORD_DATA_PEC:
			/* unsupported */
			cpec = rpec = 0;
			break;
		case I2C_SMBUS_PROC_CALL_PEC:
			/* unsupported */
			cpec = rpec = 0;
			break;
		case I2C_SMBUS_BLOCK_DATA_PEC:
			buf[0] = (addr << 1);
			buf[2] = (addr << 1) | 1;
			cpec = i2c_smbus_pec(3, buf, data->block);
			rpec = data->block[data->block[0] + 1];
			break;
		case I2C_SMBUS_BLOCK_PROC_CALL_PEC:
			buf[0] = (addr << 1) | 1;
			rpec = i2c_smbus_partial_pec(partial, 1,
			                             buf, data->block);
			cpec = data->block[data->block[0] + 1];
			break;
		default:
			cpec = rpec = 0;
			break;
	}
	if (rpec != cpec) {
		pr_debug("i2c-core: Bad PEC 0x%02x vs. 0x%02x\n",
			rpec, cpec);
		return -1;
	}
	return 0;
}

s32 i2c_smbus_write_quick(struct i2c_client *client, u8 value)
{
	return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
 	                      value,0,I2C_SMBUS_QUICK,NULL);
}

s32 i2c_smbus_read_byte(struct i2c_client *client)
{
	union i2c_smbus_data data;
	if (i2c_smbus_xfer(client->adapter,client->addr,client->flags,
	                   I2C_SMBUS_READ,0,I2C_SMBUS_BYTE, &data))
		return -1;
	else
		return 0x0FF & data.byte;
}

s32 i2c_smbus_write_byte(struct i2c_client *client, u8 value)
{
	union i2c_smbus_data data;	/* only for PEC */
	return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
	                      I2C_SMBUS_WRITE,value, I2C_SMBUS_BYTE,&data);
}

s32 i2c_smbus_read_byte_data(struct i2c_client *client, u8 command)
{
	union i2c_smbus_data data;
	if (i2c_smbus_xfer(client->adapter,client->addr,client->flags,
	                   I2C_SMBUS_READ,command, I2C_SMBUS_BYTE_DATA,&data))
		return -1;
	else
		return 0x0FF & data.byte;
}

s32 i2c_smbus_write_byte_data(struct i2c_client *client, u8 command, u8 value)
{
	union i2c_smbus_data data;
	data.byte = value;
	return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
	                      I2C_SMBUS_WRITE,command,
	                      I2C_SMBUS_BYTE_DATA,&data);
}

s32 i2c_smbus_read_word_data(struct i2c_client *client, u8 command)
{
	union i2c_smbus_data data;
	if (i2c_smbus_xfer(client->adapter,client->addr,client->flags,
	                   I2C_SMBUS_READ,command, I2C_SMBUS_WORD_DATA, &data))
		return -1;
	else
		return 0x0FFFF & data.word;
}

s32 i2c_smbus_write_word_data(struct i2c_client *client, u8 command, u16 value)
{
	union i2c_smbus_data data;
	data.word = value;
	return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
	                      I2C_SMBUS_WRITE,command,
	                      I2C_SMBUS_WORD_DATA,&data);
}

s32 i2c_smbus_write_block_data(struct i2c_client *client, u8 command,
			       u8 length, u8 *values)
{
	union i2c_smbus_data data;
	int i;
	if (length > I2C_SMBUS_BLOCK_MAX)
		length = I2C_SMBUS_BLOCK_MAX;
	for (i = 1; i <= length; i++)
		data.block[i] = values[i-1];
	data.block[0] = length;
	return i2c_smbus_xfer(client->adapter,client->addr,client->flags,
			      I2C_SMBUS_WRITE,command,
			      I2C_SMBUS_BLOCK_DATA,&data);
}

/* Returns the number of read bytes */
s32 i2c_smbus_read_i2c_block_data(struct i2c_client *client, u8 command, u8 *values)
{
	union i2c_smbus_data data;
	int i;
	if (i2c_smbus_xfer(client->adapter,client->addr,client->flags,
	                      I2C_SMBUS_READ,command,
	                      I2C_SMBUS_I2C_BLOCK_DATA,&data))
		return -1;
	else {
		for (i = 1; i <= data.block[0]; i++)
			values[i-1] = data.block[i];
		return data.block[0];
	}
}

/* Simulate a SMBus command using the i2c protocol
   No checking of parameters is done!  */
static s32 i2c_smbus_xfer_emulated(struct i2c_adapter * adapter, u16 addr,
                                   unsigned short flags,
                                   char read_write, u8 command, int size,
                                   union i2c_smbus_data * data)
{
	/* So we need to generate a series of msgs. In the case of writing, we
	  need to use only one message; when reading, we need two. We initialize
	  most things with sane defaults, to keep the code below somewhat
	  simpler. */
	unsigned char msgbuf0[34];
	unsigned char msgbuf1[34];
	int num = read_write == I2C_SMBUS_READ?2:1;
	struct i2c_msg msg[2] = { { addr, flags, 1, msgbuf0 },
	                          { addr, flags | I2C_M_RD, 0, msgbuf1 }
	                        };
	int i;

	msgbuf0[0] = command;
	switch(size) {
	case I2C_SMBUS_QUICK:
		msg[0].len = 0;
		/* Special case: The read/write field is used as data */
		msg[0].flags = flags | (read_write==I2C_SMBUS_READ)?I2C_M_RD:0;
		num = 1;
		break;
	case I2C_SMBUS_BYTE:
		if (read_write == I2C_SMBUS_READ) {
			/* Special case: only a read! */
			msg[0].flags = I2C_M_RD | flags;
			num = 1;
		}
		break;
	case I2C_SMBUS_BYTE_DATA:
		if (read_write == I2C_SMBUS_READ)
			msg[1].len = 1;
		else {
			msg[0].len = 2;
			msgbuf0[1] = data->byte;
		}
		break;
	case I2C_SMBUS_WORD_DATA:
		if (read_write == I2C_SMBUS_READ)
			msg[1].len = 2;
		else {
			msg[0].len=3;
			msgbuf0[1] = data->word & 0xff;
			msgbuf0[2] = (data->word >> 8) & 0xff;
		}
		break;
	case I2C_SMBUS_PROC_CALL:
		num = 2; /* Special case */
		read_write = I2C_SMBUS_READ;
		msg[0].len = 3;
		msg[1].len = 2;
		msgbuf0[1] = data->word & 0xff;
		msgbuf0[2] = (data->word >> 8) & 0xff;
		break;
	case I2C_SMBUS_BLOCK_DATA:
	case I2C_SMBUS_BLOCK_DATA_PEC:
		if (read_write == I2C_SMBUS_READ) {
			dev_err(&adapter->dev, "Block read not supported "
			       "under I2C emulation!\n");
			return -1;
		} else {
			msg[0].len = data->block[0] + 2;
			if (msg[0].len > I2C_SMBUS_BLOCK_MAX + 2) {
				dev_err(&adapter->dev, "smbus_access called with "
				       "invalid block write size (%d)\n",
				       data->block[0]);
				return -1;
			}
			if(size == I2C_SMBUS_BLOCK_DATA_PEC)
				(msg[0].len)++;
			for (i = 1; i <= msg[0].len; i++)
				msgbuf0[i] = data->block[i-1];
		}
		break;
	case I2C_SMBUS_BLOCK_PROC_CALL:
	case I2C_SMBUS_BLOCK_PROC_CALL_PEC:
		dev_dbg(&adapter->dev, "Block process call not supported "
		       "under I2C emulation!\n");
		return -1;
	case I2C_SMBUS_I2C_BLOCK_DATA:
		if (read_write == I2C_SMBUS_READ) {
			msg[1].len = I2C_SMBUS_I2C_BLOCK_MAX;
		} else {
			msg[0].len = data->block[0] + 1;
			if (msg[0].len > I2C_SMBUS_I2C_BLOCK_MAX + 1) {
				dev_err(&adapter->dev, "i2c_smbus_xfer_emulated called with "
				       "invalid block write size (%d)\n",
				       data->block[0]);
				return -1;
			}
			for (i = 1; i <= data->block[0]; i++)
				msgbuf0[i] = data->block[i];
		}
		break;
	default:
		dev_err(&adapter->dev, "smbus_access called with invalid size (%d)\n",
		       size);
		return -1;
	}

	if (i2c_transfer(adapter, msg, num) < 0)
		return -1;

	if (read_write == I2C_SMBUS_READ)
		switch(size) {
			case I2C_SMBUS_BYTE:
				data->byte = msgbuf0[0];
				break;
			case I2C_SMBUS_BYTE_DATA:
				data->byte = msgbuf1[0];
				break;
			case I2C_SMBUS_WORD_DATA:
			case I2C_SMBUS_PROC_CALL:
				data->word = msgbuf1[0] | (msgbuf1[1] << 8);
				break;
			case I2C_SMBUS_I2C_BLOCK_DATA:
				/* fixed at 32 for now */
				data->block[0] = I2C_SMBUS_I2C_BLOCK_MAX;
				for (i = 0; i < I2C_SMBUS_I2C_BLOCK_MAX; i++)
					data->block[i+1] = msgbuf1[i];
				break;
		}
	return 0;
}

s32 i2c_smbus_xfer(struct i2c_adapter * adapter, u16 addr, unsigned short flags,
                   char read_write, u8 command, int size,
                   union i2c_smbus_data * data)
{
	s32 res;
	int swpec = 0;
	u8 partial = 0;

	flags &= I2C_M_TEN | I2C_CLIENT_PEC;
	if((flags & I2C_CLIENT_PEC) &&
	   !(i2c_check_functionality(adapter, I2C_FUNC_SMBUS_HWPEC_CALC))) {
		swpec = 1;
		if(read_write == I2C_SMBUS_READ &&
		   size == I2C_SMBUS_BLOCK_DATA)
			size = I2C_SMBUS_BLOCK_DATA_PEC;
		else if(size == I2C_SMBUS_PROC_CALL)
			size = I2C_SMBUS_PROC_CALL_PEC;
		else if(size == I2C_SMBUS_BLOCK_PROC_CALL) {
			i2c_smbus_add_pec(addr, command,
		                          I2C_SMBUS_BLOCK_DATA, data);
			partial = data->block[data->block[0] + 1];
			size = I2C_SMBUS_BLOCK_PROC_CALL_PEC;
		} else if(read_write == I2C_SMBUS_WRITE &&
		          size != I2C_SMBUS_QUICK &&
		          size != I2C_SMBUS_I2C_BLOCK_DATA)
			size = i2c_smbus_add_pec(addr, command, size, data);
	}

	if (adapter->algo->smbus_xfer) {
		down(&adapter->bus_lock);
		res = adapter->algo->smbus_xfer(adapter,addr,flags,read_write,
		                                command,size,data);
		up(&adapter->bus_lock);
	} else
		res = i2c_smbus_xfer_emulated(adapter,addr,flags,read_write,
	                                      command,size,data);

	if(res >= 0 && swpec &&
	   size != I2C_SMBUS_QUICK && size != I2C_SMBUS_I2C_BLOCK_DATA &&
	   (read_write == I2C_SMBUS_READ || size == I2C_SMBUS_PROC_CALL_PEC ||
	    size == I2C_SMBUS_BLOCK_PROC_CALL_PEC)) {
		if(i2c_smbus_check_pec(addr, command, size, partial, data))
			return -1;
	}
	return res;
}

/* Next four are needed by i2c-isa */
EXPORT_SYMBOL_GPL(i2c_adapter_dev_release);
EXPORT_SYMBOL_GPL(i2c_adapter_driver);
EXPORT_SYMBOL_GPL(i2c_adapter_class);
EXPORT_SYMBOL_GPL(i2c_bus_type);

EXPORT_SYMBOL(i2c_add_adapter);
EXPORT_SYMBOL(i2c_del_adapter);
EXPORT_SYMBOL(i2c_add_driver);
EXPORT_SYMBOL(i2c_del_driver);
EXPORT_SYMBOL(i2c_attach_client);
EXPORT_SYMBOL(i2c_detach_client);
EXPORT_SYMBOL(i2c_use_client);
EXPORT_SYMBOL(i2c_release_client);
EXPORT_SYMBOL(i2c_clients_command);
EXPORT_SYMBOL(i2c_check_addr);

EXPORT_SYMBOL(i2c_master_send);
EXPORT_SYMBOL(i2c_master_recv);
EXPORT_SYMBOL(i2c_control);
EXPORT_SYMBOL(i2c_transfer);
EXPORT_SYMBOL(i2c_get_adapter);
EXPORT_SYMBOL(i2c_put_adapter);
EXPORT_SYMBOL(i2c_probe);

EXPORT_SYMBOL(i2c_smbus_xfer);
EXPORT_SYMBOL(i2c_smbus_write_quick);
EXPORT_SYMBOL(i2c_smbus_read_byte);
EXPORT_SYMBOL(i2c_smbus_write_byte);
EXPORT_SYMBOL(i2c_smbus_read_byte_data);
EXPORT_SYMBOL(i2c_smbus_write_byte_data);
EXPORT_SYMBOL(i2c_smbus_read_word_data);
EXPORT_SYMBOL(i2c_smbus_write_word_data);
EXPORT_SYMBOL(i2c_smbus_write_block_data);
EXPORT_SYMBOL(i2c_smbus_read_i2c_block_data);

MODULE_AUTHOR("Simon G. Vogl <simon@tk.uni-linz.ac.at>");
MODULE_DESCRIPTION("I2C-Bus main module");
MODULE_LICENSE("GPL");


text:
package Module::Pluggable::Object;

use strict;
use File::Find ();
use File::Basename;
use File::Spec::Functions qw(splitdir catdir curdir catfile abs2rel);
use Carp qw(croak carp);
use Devel::InnerPackage;
use Data::Dumper;
use vars qw($VERSION);

$VERSION = '3.6';

sub new {
    my $class = shift;
    my %opts  = @_;

    return bless \%opts, $class;

}

### Eugggh, this code smells
### This is what happens when you keep adding patches
### *sigh*

sub plugins {
        my $self = shift;

        # override 'require'
        $self->{'require'} = 1 if $self->{'inner'};

        my $filename   = $self->{'filename'};
        my $pkg        = $self->{'package'};

        # automatically turn a scalar search path or namespace into a arrayref
        for (qw(search_path search_dirs)) {
            $self->{$_} = [ $self->{$_} ] if exists $self->{$_} && !ref($self->{$_});
        }

        # default search path is '<Module>::<Name>::Plugin'
        $self->{'search_path'} = ["${pkg}::Plugin"] unless $self->{'search_path'};

        #my %opts = %$self;

        # check to see if we're running under test
        my @SEARCHDIR = exists $INC{"blib.pm"} && defined $filename && $filename =~ m!(^|/)blib/! ? grep {/blib/} @INC : @INC;

        # add any search_dir params
        unshift @SEARCHDIR, @{$self->{'search_dirs'}} if defined $self->{'search_dirs'};

        my @plugins = $self->search_directories(@SEARCHDIR);

        # push @plugins, map { print STDERR "$_\n"; $_->require } list_packages($_) for (@{$self->{'search_path'}});

        # return blank unless we've found anything
        return () unless @plugins;

        # exceptions
        my %only;
        my %except;
        my $only;
        my $except;

        if (defined $self->{'only'}) {
            if (ref($self->{'only'}) eq 'ARRAY') {
                %only   = map { $_ => 1 } @{$self->{'only'}};
            } elsif (ref($self->{'only'}) eq 'Regexp') {
                $only = $self->{'only'}
            } elsif (ref($self->{'only'}) eq '') {
                $only{$self->{'only'}} = 1;
            }
        }

        if (defined $self->{'except'}) {
            if (ref($self->{'except'}) eq 'ARRAY') {
                %except   = map { $_ => 1 } @{$self->{'except'}};
            } elsif (ref($self->{'except'}) eq 'Regexp') {
                $except = $self->{'except'}
            } elsif (ref($self->{'except'}) eq '') {
                $except{$self->{'except'}} = 1;
            }
        }

        # remove duplicates
        # probably not necessary but hey ho
        my %plugins;
        for(@plugins) {
            next if (keys %only   && !$only{$_}     );
            next unless (!defined $only || m!$only! );

            next if (keys %except &&  $except{$_}   );
            next if (defined $except &&  m!$except! );
            $plugins{$_} = 1;
        }

        # are we instantiating or requring?
        if (defined $self->{'instantiate'}) {
            my $method = $self->{'instantiate'};
            return map { ($_->can($method)) ? $_->$method(@_) : () } keys %plugins;
        } else {
            # no? just return the names
            return keys %plugins;
        }

}

sub search_directories {
    my $self      = shift;
    my @SEARCHDIR = @_;

    my @plugins;
    # go through our @INC
    foreach my $dir (@SEARCHDIR) {
        push @plugins, $self->search_paths($dir);
    }

    return @plugins;
}

sub search_paths {
    my $self = shift;
    my $dir  = shift;
    my @plugins;

    my $file_regex = $self->{'file_regex'} || qr/\.pm$/;

    # and each directory in our search path
    foreach my $searchpath (@{$self->{'search_path'}}) {
        # create the search directory in a cross platform goodness way
        my $sp = catdir($dir, (split /::/, $searchpath));

        # if it doesn't exist or it's not a dir then skip it
        next unless ( -e $sp && -d _ ); # Use the cached stat the second time

        my @files = $self->find_files($sp);

        # foreach one we've found
        foreach my $file (@files) {
            # untaint the file; accept .pm only
            next unless ($file) = ($file =~ /(.*$file_regex)$/);
            # parse the file to get the name
            my ($name, $directory, $suffix) = fileparse($file, $file_regex);

            next if (!$self->{include_editor_junk} && $self->_is_editor_junk($name));

            $directory = abs2rel($directory, $sp);

            # If we have a mixed-case package name, assume case has been preserved
            # correctly.  Otherwise, root through the file to locate the case-preserved
            # version of the package name.
            my @pkg_dirs = ();
            if ( $name eq lc($name) || $name eq uc($name) ) {
                my $pkg_file = catfile($sp, $directory, "$name$suffix");
                open PKGFILE, "<$pkg_file" or die "search_paths: Can't open $pkg_file: $!";
                my $in_pod = 0;
                while ( my $line = <PKGFILE> ) {
                    $in_pod = 1 if $line =~ m/^=\w/;
                    $in_pod = 0 if $line =~ /^=cut/;
                    next if ($in_pod || $line =~ /^=cut/);  # skip pod text
                    next if $line =~ /^\s*#/;               # and comments
                    if ( $line =~ m/^\s*package\s+(.*::)?($name)\s*;/i ) {
                        @pkg_dirs = split /::/, $1;
                        $name = $2;
                        last;
                    }
                }
                close PKGFILE;
            }

            # then create the class name in a cross platform way
            $directory =~ s/^[a-z]://i if($^O =~ /MSWin32|dos/);       # remove volume
            my @dirs = ();
            if ($directory) {
                ($directory) = ($directory =~ /(.*)/);
                @dirs = grep(length($_), splitdir($directory))
                    unless $directory eq curdir();
                for my $d (reverse @dirs) {
                    my $pkg_dir = pop @pkg_dirs;
                    last unless defined $pkg_dir;
                    $d =~ s/\Q$pkg_dir\E/$pkg_dir/i;  # Correct case
                }
            } else {
                $directory = "";
            }
            my $plugin = join '::', $searchpath, @dirs, $name;

            next unless $plugin =~ m!(?:[a-z\d]+)[a-z\d]!i;

            my $err = $self->handle_finding_plugin($plugin);
            carp "Couldn't require $plugin : $err" if $err;

            push @plugins, $plugin;
        }

        # now add stuff that may have been in package
        # NOTE we should probably use all the stuff we've been given already
        # but then we can't unload it :(
        push @plugins, $self->handle_innerpackages($searchpath) unless (exists $self->{inner} && !$self->{inner});
    } # foreach $searchpath

    return @plugins;
}

sub _is_editor_junk {
    my $self = shift;
    my $name = shift;

    # Emacs (and other Unix-y editors) leave temp files ending in a
    # tilde as a backup.
    return 1 if $name =~ /~$/;
    # Emacs makes these files while a buffer is edited but not yet
    # saved.
    return 1 if $name =~ /^\.#/;
    # Vim can leave these files behind if it crashes.
    return 1 if $name =~ /\.sw[po]$/;

    return 0;
}

sub handle_finding_plugin {
    my $self   = shift;
    my $plugin = shift;

    return unless (defined $self->{'instantiate'} || $self->{'require'});
    $self->_require($plugin);
}

sub find_files {
    my $self         = shift;
    my $search_path  = shift;
    my $file_regex   = $self->{'file_regex'} || qr/\.pm$/;

    # find all the .pm files in it
    # this isn't perfect and won't find multiple plugins per file
    #my $cwd = Cwd::getcwd;
    my @files = ();
    { # for the benefit of perl 5.6.1's Find, localize topic
        local $_;
        File::Find::find( { no_chdir => 1,
                           wanted => sub {
                             # Inlined from File::Find::Rule C< name => '*.pm' >
                             return unless $File::Find::name =~ /$file_regex/;
                             (my $path = $File::Find::name) =~ s#^\\./##;
                             push @files, $path;
                           }
                      }, $search_path );
    }
    #chdir $cwd;
    return @files;

}

sub handle_innerpackages {
    my $self = shift;
    my $path = shift;
    my @plugins;

    foreach my $plugin (Devel::InnerPackage::list_packages($path)) {
        my $err = $self->handle_finding_plugin($plugin);
        #next if $err;
        #next unless $INC{$plugin};
        push @plugins, $plugin;
    }
    return @plugins;

}

sub _require {
    my $self = shift;
    my $pack = shift;
    local $@;
    eval "CORE::require $pack";
    return $@;
}

1;

=pod

=head1 NAME

Module::Pluggable::Object - automatically give your module the ability to have plugins

=head1 SYNOPSIS

Simple use Module::Pluggable -

    package MyClass;
    use Module::Pluggable::Object;

    my $finder = Module::Pluggable::Object->new(%opts);
    print "My plugins are: ".join(", ", $finder->plugins)."\n";

=head1 DESCRIPTION

Provides a simple but, hopefully, extensible way of having 'plugins' for
your module. Obviously this isn't going to be the be all and end all of
solutions but it works for me.

Essentially all it does is export a method into your namespace that
looks through a search path for .pm files and turn those into class names.

Optionally it instantiates those classes for you.

This object is wrapped by C<Module::Pluggable>. If you want to do something
odd or add non-general special features you're probably best to wrap this
and produce your own subclass.

=head1 OPTIONS

See the C<Module::Pluggable> docs.

=head1 AUTHOR

Simon Wistow <simon@thegestalt.org>

=head1 COPYING

Copyright, 2006 Simon Wistow

Distributed under the same terms as Perl itself.

=head1 BUGS

None known.

=head1 SEE ALSO

L<Module::Pluggable>

=cut


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/CountBook2.iml" filepath="$PROJECT_DIR$/CountBook2.iml" />
      <module fileurl="file://$PROJECT_DIR$/CountBook2_close.iml" filepath="$PROJECT_DIR$/CountBook2_close.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
    </modules>
  </component>
</project>


text:
from msrest.serialization import Model

class ImageOSDisk(Model):
    """Describes an Operating System disk.

    :param os_type: The Operating System type. Possible values include:
     'Windows', 'Linux'
    :type os_type: str or :class:`OperatingSystemTypes
     <azure.mgmt.compute.models.OperatingSystemTypes>`
    :param os_state: The OS State. Possible values include: 'Generalized',
     'Specialized'
    :type os_state: str or :class:`OperatingSystemStateTypes
     <azure.mgmt.compute.models.OperatingSystemStateTypes>`
    :param snapshot: The snapshot.
    :type snapshot: :class:`SubResource
     <azure.mgmt.compute.models.SubResource>`
    :param managed_disk: The managedDisk.
    :type managed_disk: :class:`SubResource
     <azure.mgmt.compute.models.SubResource>`
    :param blob_uri: The Virtual Hard Disk.
    :type blob_uri: str
    :param caching: The caching type. Possible values include: 'None',
     'ReadOnly', 'ReadWrite'
    :type caching: str or :class:`CachingTypes
     <azure.mgmt.compute.models.CachingTypes>`
    :param disk_size_gb: The initial managed disk size in GB for blank data
     disks, and the new desired size for existing OS and Data disks.
    :type disk_size_gb: int
    """

    _validation = {
        'os_type': {'required': True},
        'os_state': {'required': True},
    }

    _attribute_map = {
        'os_type': {'key': 'osType', 'type': 'OperatingSystemTypes'},
        'os_state': {'key': 'osState', 'type': 'OperatingSystemStateTypes'},
        'snapshot': {'key': 'snapshot', 'type': 'SubResource'},
        'managed_disk': {'key': 'managedDisk', 'type': 'SubResource'},
        'blob_uri': {'key': 'blobUri', 'type': 'str'},
        'caching': {'key': 'caching', 'type': 'CachingTypes'},
        'disk_size_gb': {'key': 'diskSizeGB', 'type': 'int'},
    }

    def __init__(self, os_type, os_state, snapshot=None, managed_disk=None, blob_uri=None, caching=None, disk_size_gb=None):
        self.os_type = os_type
        self.os_state = os_state
        self.snapshot = snapshot
        self.managed_disk = managed_disk
        self.blob_uri = blob_uri
        self.caching = caching
        self.disk_size_gb = disk_size_gb


text:
require 'aws/s3'

module MongoDbUtils

  module Tools

    class ToolsException < RuntimeError
      attr :cmd, :output
      def initialize(cmd, output, message)
        super(message)
        @cmd = cmd
        @output = output
      end

    end

    class BaseCmd

      def initialize(cmd_name, host_and_port, db, username = '', password = '')
        @unsafe_options = build_base_options(host_and_port, db, username, password)
        @options_without_credentials = build_base_options(host_and_port, db, username.empty? ? '':'****', password.empty? ? '':'****')
        @cmd_name = cmd_name
      end

      def run
        puts "[#{self.class}] run: #{cmd}"
        output = `#{executable_cmd} 2>&1`
        raise ToolsException.new("#{cmd}", output, "Error in #{@cmd_name}:: #{output}, cmd: #{cmd}") unless $?.to_i == 0
      end

      def cmd
        "#{@cmd_name} #{options_string(@options_without_credentials)}"
      end

      def executable_cmd
        "#{@cmd_name} #{options_string(@unsafe_options)}"
      end

      private

      def add_option(option)
        @unsafe_options << option
        @options_without_credentials << option
      end

      def o(key,value)
        Option.new(key,value)
      end

      # options common to all commands
      def build_base_options(host_and_port,db,username='',password='')
        options = []
        options << o('-h', host_and_port)
        options << o('-db', db)
        options << o('-u', username)
        options << o('-p', password)
        options
      end

      # given an array of options build a string of those options unless the option is empty
      def options_string(opts)
        opt_strings = opts.reject{ |o| o.empty? }.map { |o| o.to_s }
        opt_strings.join(' ').strip
      end
    end

    class Dump < BaseCmd
      def initialize(host_and_port,db,output,username = '', password = '')
        super('mongodump', host_and_port, db, username, password)
        add_option(o('-o', output))
      end
    end

    class Restore < BaseCmd
      def initialize(host_and_port,db,source_folder,username = '', password = '')
        super('mongorestore', host_and_port, db, username, password)
        add_option('--drop')
        @source_folder = source_folder
      end

      def cmd
        "#{super} #{@source_folder}"
      end

      def executable_cmd
        "#{super} #{@source_folder}"
      end
    end

    class Import < BaseCmd
      def initialize(host_and_port, db, collection, file, username = '', password = '', opts = {})
        super('mongoimport', host_and_port, db, username, password)
        add_option(o('-c', collection))
        add_option(o('--file', file))
        add_option('--jsonArray') if opts[:json_array]
        add_option('--drop') if opts[:drop]
      end
    end

    class Export < BaseCmd

      def initialize(host_and_port, db, collection, query, output, username = '', password = '', opts = {})
        super('mongoexport', host_and_port, db, username, password)
        add_option(o('-c', collection))
        add_option(o('-o', output))
        add_option(o('--query', "'#{query}'"))
        add_option('--jsonArray') if opts[:json_array]
      end
    end

    class Option
      attr_accessor :key, :value

      def initialize(key,value = nil)
        @key = key
        @value = value
      end

      def empty?
        (@value.nil? || @value.empty?)
      end

      def to_s
        if empty?
          nil
        else
          "#{@key} #{@value}"
        end
      end

      private
      def value_empty?
        @value.nil? || @value.empty?
      end
    end
  end
end


text:
package victor.training.java8.jprime.predicates;

import static java.util.stream.Collectors.toSet;

import java.time.LocalDate;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;

public class OrderService {

	public void notifyCustomersOfIncompleteOrders(List<Order> orders) {
		LocalDate warningDate = LocalDate.now().plusDays(3);

		Set<Customer> customersToNotify = orders.stream()
				.filter(OrderPredicates.hasDeliveryDateBeforeWarning(warningDate))
				.filter(this::hasOrderLinesNotInStock)
				.map(Order::getCustomer).collect(toSet());

		for (Customer customer : customersToNotify) {
			sendEmail(customer);
		}
	}

	public static class OrderPredicates {
		public static Predicate<Order> hasDeliveryDateBeforeWarning(LocalDate warningDate) {
			return order -> order.getDeliveryDueDate().isBefore(warningDate);
		}
	}

	private boolean hasOrderLinesNotInStock(Order order) {
		return order.getOrderLines().stream().anyMatch(OrderLine::isNotInStock);
	}

	private void sendEmail(Customer customer) {
		// TODO Auto-generated method stub

	}

}


text:
package com.google.android.gms.games.leaderboard;

import com.google.android.gms.common.data.DataHolder;
import com.google.android.gms.internal.ee;
import com.google.android.gms.internal.ee.a;
import com.google.android.gms.internal.eg;
import com.google.android.gms.internal.ge;
import java.util.HashMap;

@Deprecated
public final class SubmitScoreResult
{
  private static final String[] wh = { "leaderboardId", "playerId", "timeSpan", "hasResult", "rawScore", "formattedScore", "newBest", "scoreTag" };
  private int mC;
  private String tC;
  private String vD;
  private HashMap<Integer, Result> wi;

  public SubmitScoreResult(int paramInt, String paramString1, String paramString2)
  {
    this(paramInt, paramString1, paramString2, new HashMap());
  }

  public SubmitScoreResult(int paramInt, String paramString1, String paramString2, HashMap<Integer, Result> paramHashMap)
  {
    this.mC = paramInt;
    this.vD = paramString1;
    this.tC = paramString2;
    this.wi = paramHashMap;
  }

  public SubmitScoreResult(DataHolder paramDataHolder)
  {
    this.mC = paramDataHolder.getStatusCode();
    this.wi = new HashMap();
    int i = paramDataHolder.getCount();
    boolean bool;
    if (i == 3)
      bool = true;
    else
      bool = false;
    eg.r(bool);
    for (int j = 0; j < i; j++)
    {
      int k = paramDataHolder.C(j);
      if (j == 0)
      {
        this.vD = paramDataHolder.getString("leaderboardId", j, k);
        this.tC = paramDataHolder.getString("playerId", j, k);
      }
      if (paramDataHolder.getBoolean("hasResult", j, k))
        a(new Result(paramDataHolder.getLong("rawScore", j, k), paramDataHolder.getString("formattedScore", j, k), paramDataHolder.getString("scoreTag", j, k), paramDataHolder.getBoolean("newBest", j, k)), paramDataHolder.getInteger("timeSpan", j, k));
    }
  }

  private void a(Result paramResult, int paramInt)
  {
    this.wi.put(Integer.valueOf(paramInt), paramResult);
  }

  public final String getLeaderboardId()
  {
    return this.vD;
  }

  public final String getPlayerId()
  {
    return this.tC;
  }

  public final Result getScoreResult(int paramInt)
  {
    return (Result)this.wi.get(Integer.valueOf(paramInt));
  }

  public final int getStatusCode()
  {
    return this.mC;
  }

  public final String toString()
  {
    ee.a locala = ee.e(this).a("PlayerId", this.tC).a("StatusCode", Integer.valueOf(this.mC));
    for (int i = 0; i < 3; i++)
    {
      Result localResult = (Result)this.wi.get(Integer.valueOf(i));
      locala.a("TimesSpan", ge.aG(i));
      String str;
      if (localResult == null)
        str = "null";
      else
        str = localResult.toString();
      locala.a("Result", str);
    }
    return locala.toString();
  }

  public static final class Result
  {
    public final String formattedScore;
    public final boolean newBest;
    public final long rawScore;
    public final String scoreTag;

    public Result(long paramLong, String paramString1, String paramString2, boolean paramBoolean)
    {
      this.rawScore = paramLong;
      this.formattedScore = paramString1;
      this.scoreTag = paramString2;
      this.newBest = paramBoolean;
    }

    public final String toString()
    {
      return ee.e(this).a("RawScore", Long.valueOf(this.rawScore)).a("FormattedScore", this.formattedScore).a("ScoreTag", this.scoreTag).a("NewBest", Boolean.valueOf(this.newBest)).toString();
    }
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.google.android.gms.games.leaderboard.SubmitScoreResult
 * JD-Core Version:    0.6.2
 */


text:
include ../rules.inc

EXES = ring_blocking

all: $(EXES)

test: $(EXES)