text:
'use strict';
module.exports = {
  up: (queryInterface, Sequelize) => {
    return queryInterface.createTable('DiscordInteractions', {
      id: {
        primaryKey: true,
        type: Sequelize.INTEGER,
        autoIncrement: true,
        allowNull: false,
      },
      command: {
        type: Sequelize.STRING,
      },
      alias: {
        type: Sequelize.STRING,
      },
      properties: {
        type: Sequelize.JSONB,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      UserId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'DiscordUsers',
          key: 'id',
        },
        onUpdate: 'no action',
        onDelete: 'no action',
      },
      ChannelId: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'DiscordChannels',
          key: 'id',
        },
        onUpdate: 'no action',
        onDelete: 'no action',
      },
      GuildId: {
        type: Sequelize.INTEGER,
        allowNull: true,
        references: {
          model: 'DiscordGuilds',
          key: 'id',
        },
        onUpdate: 'no action',
        onDelete: 'no action',
      },
    });
  },
  down: (queryInterface, Sequelize) => {
    return queryInterface.dropTable('DiscordInteractions');
  },
};


text:
let buf;

function patch(el, fn, data) {
  buf = '';
  fn(data);
  el.innerHTML = buf;
}

const EMPTY_ARRAY = [];

const escapeHtml = (function() {
  const cache = {};
  const textNode = document.createTextNode('');
  const div = document.createElement('div');
  div.appendChild(textNode);

  function escape(str) {
    textNode.data = str;
    return div.innerHTML;
  }

  return function(str) {
    return cache[str] || (cache[str] = escape(str));
  }
})();

function applyAttr(name, value) {
  if (value !== undefined) {
    buf += ' ' + name + '="' + value + '"';
  }
}

function applyAttrEscaped(name, value) {
  if (typeof value === 'string') {
    applyAttr(name, escapeHtml(value));
  } else {
    applyAttr(name, value);
  }
}

function elementOpen(tagName, key, statics) {
  let arr;
  let i;

  buf += '<' + tagName;

  arr = statics || EMPTY_ARRAY;
  for (i = 0; i < arr.length; i += 2) {
    applyAttrEscaped(arr[i], arr[i + 1]);
  }

  arr = arguments;
  for (i = 3; i < arr.length; i += 2) {
    applyAttrEscaped(arr[i], arr[i + 1]);
  }

  buf += '>';
}

function elementClose(tagName) {
  buf += '</' + tagName + '>';
}

function elementVoid (tagName, key, statics) {
  elementOpen.apply(null, arguments);
  elementClose.apply(null, arguments);
}

function text(value) {
  let formatted = value;
  for (let i = 1; i < arguments.length; i += 1) {
    let formatter = arguments[i];
    formatted = formatter(formatted);
  }

  buf += escapeHtml(formatted);
}

export const CreationInnerHtml = {
  patch,
  elementOpen,
  elementClose,
  elementVoid,
  text,
};

redpajama_set_name: RedPajamaGithub


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

// Include test fixture.
GEN_INCLUDE(['../testing/chromevox_next_e2e_test_base.js']);

/**
 * Test fixture for SmartStickyMode.
 */
ChromeVoxSmartStickyModeTest = class extends ChromeVoxNextE2ETest {
  /** @override */
  async setUpDeferred() {
    await super.setUpDeferred();
    await importModule(
        'ChromeVoxBackground', '/chromevox/background/classic_background.js');
    await importModule(
        'ChromeVoxState', '/chromevox/background/chromevox_state.js');
    await importModule('CursorRange', '/common/cursors/range.js');
    await importModule(
        'SmartStickyMode', '/chromevox/background/smart_sticky_mode.js');
    this.ssm_ = new SmartStickyMode();
    // Deregister from actual range changes.
    ChromeVoxState.removeObserver(this.ssm_);
    assertFalse(this.ssm_.didTurnOffStickyMode_);
  }

  assertDidTurnOffForNode(node) {
    this.ssm_.onCurrentRangeChanged(CursorRange.fromNode(node));
    assertTrue(this.ssm_.didTurnOffStickyMode_);
  }

  assertDidNotTurnOffForNode(node) {
    this.ssm_.onCurrentRangeChanged(CursorRange.fromNode(node));
    assertFalse(this.ssm_.didTurnOffStickyMode_);
  }

  get relationsDoc() {
    return `

start

      <input aria-controls="controls-target" type="text"></input>
      <textarea aria-activedescendant="active-descendant-target"></textarea>

hello

end

end

    `;
  }
};

AX_TEST_F(
    'ChromeVoxSmartStickyModeTest', 'PossibleRangeTypes', async function() {
      const root = await this.runWithLoadedTree(this.relationsDoc);
      const [p, input, textarea, contenteditable, ul1, ul2] = root.children;

      // First, turn on sticky mode and try changing range to various parts of
      // the document.
      ChromeVoxBackground.setPref(
          'sticky', true /* value */, true /* announce */);
      this.assertDidTurnOffForNode(input);
      this.assertDidTurnOffForNode(textarea);
      this.assertDidNotTurnOffForNode(p);
      this.assertDidTurnOffForNode(contenteditable);
      this.assertDidTurnOffForNode(ul1);
      this.assertDidNotTurnOffForNode(p);
      this.assertDidTurnOffForNode(ul2);
      this.assertDidTurnOffForNode(ul1.firstChild);
      this.assertDidNotTurnOffForNode(ul1.parent);
      this.assertDidNotTurnOffForNode(ul2.parent);
      this.assertDidNotTurnOffForNode(p);
      this.assertDidTurnOffForNode(ul2.firstChild);
      this.assertDidNotTurnOffForNode(p);
      this.assertDidNotTurnOffForNode(contenteditable.parent);
      this.assertDidTurnOffForNode(contenteditable.find({role: 'heading'}));
      this.assertDidTurnOffForNode(
          contenteditable.find({role: 'inlineTextBox'}));
    });

AX_TEST_F(
    'ChromeVoxSmartStickyModeTest', 'UserPressesStickyModeCommand',
    async function() {
      const root = await this.runWithLoadedTree(this.relationsDoc);
      const [p, input, textarea, contenteditable, ul1, ul2] = root.children;
      ChromeVoxBackground.setPref(
          'sticky', true /* value */, true /* announce */);

      // Mix in calls to turn on / off sticky mode while moving the range
      // around.
      this.assertDidTurnOffForNode(input);
      this.ssm_.onStickyModeCommand(CursorRange.fromNode(input));
      this.assertDidNotTurnOffForNode(input);
      this.ssm_.onStickyModeCommand(CursorRange.fromNode(input));
      this.assertDidNotTurnOffForNode(input);
      this.assertDidNotTurnOffForNode(input.firstChild);
      this.assertDidNotTurnOffForNode(p);

      // Make sure sticky mode is on again. This call doesn't impact our
      // instance of SmartStickyMode.
      ChromeVoxBackground.setPref(
          'sticky', true /* value */, true /* announce */);

      // Mix in more sticky mode user commands and move to related nodes.
      this.assertDidTurnOffForNode(contenteditable);
      this.assertDidTurnOffForNode(ul2);
      this.ssm_.onStickyModeCommand(CursorRange.fromNode(ul2));
      this.assertDidNotTurnOffForNode(ul2);
      this.assertDidNotTurnOffForNode(ul2.firstChild);
      this.assertDidNotTurnOffForNode(contenteditable);
      this.ssm_.onStickyModeCommand(CursorRange.fromNode(input));
      this.assertDidNotTurnOffForNode(ul2);
      this.assertDidNotTurnOffForNode(ul2.firstChild);
      this.assertDidNotTurnOffForNode(contenteditable);

      // Finally, verify sticky mode isn't impacted on non-editables.
      this.assertDidNotTurnOffForNode(p);
      this.ssm_.onStickyModeCommand(CursorRange.fromNode(p));
      this.assertDidNotTurnOffForNode(p);
      this.ssm_.onStickyModeCommand(CursorRange.fromNode(p));
      this.assertDidNotTurnOffForNode(p);
    });

AX_TEST_F(
    'ChromeVoxSmartStickyModeTest', 'SmartStickyModeJumpCommands',
    async function() {
      const mockFeedback = this.createMockFeedback();
      const root = await this.runWithLoadedTree(`

start

        <input type="text"></input>
        <button>end</button>
      `);
      mockFeedback.call(doCmd('toggleStickyMode'))
          .expectSpeech('Sticky mode enabled')
          .call(doCmd('nextFormField'))
          .expectSpeech('Edit text')
          .call(() => assertTrue(ChromeVox.isStickyModeOn()))
          .call(doCmd('nextFormField'))
          .expectSpeech('Button')
          .call(doCmd('previousFormField'))
          .expectSpeech('Edit text')
          .call(() => assertTrue(ChromeVox.isStickyModeOn()))
          .call(doCmd('previousObject'))
          .expectSpeech('start')
          .call(doCmd('nextEditText'))
          .expectSpeech('Edit text')
          .call(() => assertTrue(ChromeVox.isStickyModeOn()))
          .call(doCmd('nextObject'))
          .expectSpeech('Button')
          .call(doCmd('previousEditText'))
          .expectSpeech('Edit text')
          .call(() => assertTrue(ChromeVox.isStickyModeOn()))
          .call(doCmd('nextObject'))
          .expectSpeech('Button')
          .call(doCmd('previousObject'))
          .expectSpeech('Sticky mode disabled')
          .expectSpeech('Edit text')
          .call(() => assertFalse(ChromeVox.isStickyModeOn()));
      await mockFeedback.replay();
    });

AX_TEST_F(
    'ChromeVoxSmartStickyModeTest', 'SmartStickyModeEarcons', async function() {
      const mockFeedback = this.createMockFeedback();
      const root = await this.runWithLoadedTree(`

start

    <input type="text"></input>
    <button>end</button>
  `);
      mockFeedback.call(doCmd('toggleStickyMode'))
          .expectSpeech('Sticky mode enabled')
          .call(doCmd('nextObject'))
          .expectEarcon(Earcon.SMART_STICKY_MODE_OFF)
          .expectSpeech('Sticky mode disabled')
          .expectSpeech('Edit text')
          .call(() => assertFalse(ChromeVox.isStickyModeOn()))
          .call(doCmd('nextObject'))
          .expectEarcon(Earcon.SMART_STICKY_MODE_ON)
          .expectSpeech('Sticky mode enabled')
          .expectSpeech('Button')
          .call(() => assertTrue(ChromeVox.isStickyModeOn()));
      await mockFeedback.replay();
    });

AX_TEST_F('ChromeVoxSmartStickyModeTest', 'ContinuousRead', async function() {
  const mockFeedback = this.createMockFeedback();
  const site = `

start

    <input type="text"></input>
    <button>end</button>
  `;
  const root = await this.runWithLoadedTree(site);
  // Fake the read from here/continuous read state.
  ChromeVoxState.instance.isReadingContinuously = true;
  mockFeedback.call(doCmd('toggleStickyMode'))
      .expectSpeech('Sticky mode enabled')
      .call(doCmd('nextObject'))
      .expectNextSpeechUtteranceIsNot('Sticky mode disabled')
      .expectSpeech('Edit text')
      .call(() => assertTrue(ChromeVox.isStickyModeOn()))
      .call(doCmd('nextObject'))
      .expectNextSpeechUtteranceIsNot('Sticky mode enabled')
      .expectSpeech('Button')
      .call(() => assertTrue(ChromeVox.isStickyModeOn()));
  await mockFeedback.replay();
});


text:
#import "AppDelegate.h"

#import "RCTRootView.h"
#import <QMapKit/QMapKit.h>

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

  // Set the QMapKit apiKey
  [QMapServices sharedServices].apiKey = @"ZPZBZ-3V2HD-ENU4M-PYUZO-GEQVE-KPB2S";

  NSURL *jsCodeLocation;

  /**
   * Loading JavaScript code - uncomment the one you want.
   *
   * OPTION 1
   * Load from development server. Start the server from the repository root:
   *
   * $ npm start
   *
   * To run on device, change `localhost` to the IP address of your computer
   * (you can get this by typing `ifconfig` into the terminal and selecting the
   * `inet` value under `en0:`) and make sure your computer and iOS device are
   * on the same Wi-Fi network.
   */

  jsCodeLocation = [NSURL URLWithString:@"http://192.168.31.243:8081/index.ios.bundle?platform=ios&dev=true"];

  /**
   * OPTION 2
   * Load from pre-bundled file on disk. To re-generate the static bundle
   * from the root of your project directory, run
   *
   * $ react-native bundle --minify
   *
   * see http://facebook.github.io/react-native/docs/runningondevice.html
   */

//   jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"demo"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [[UIViewController alloc] init];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  return YES;
}

@end


text:
import datetime
import operator

from typing import List, Optional, Sequence

from ....typing import SexLiteral
from .. import Provider as SsnProvider

def checksum(digits: Sequence[int], scale: List[int]) -> int:
    """
    Calculate checksum of Norwegian personal identity code.

    Checksum is calculated with "Module 11" method using a scale.
    The digits of the personal code are multiplied by the corresponding
    number in the scale and summed;
    if remainder of module 11 of the sum is less than 10, checksum is the
    remainder.
    If remainder is 0, the checksum is 0.

    https://no.wikipedia.org/wiki/F%C3%B8dselsnummer
    """
    chk_nbr = 11 - (sum(map(operator.mul, digits, scale)) % 11)
    if chk_nbr == 11:
        return 0
    return chk_nbr

class Provider(SsnProvider):
    scale1 = (3, 7, 6, 1, 8, 9, 4, 5, 2)
    scale2 = (5, 4, 3, 2, 7, 6, 5, 4, 3, 2)

    def ssn(self, dob: Optional[str] = None, gender: Optional[SexLiteral] = None) -> str:
        """
        Returns 11 character Norwegian personal identity code (Fødselsnummer).

        A Norwegian personal identity code consists of 11 digits, without any
        whitespace or other delimiters. The form is DDMMYYIIICC, where III is
        a serial number separating persons born oh the same date with different
        intervals depending on the year they are born. CC is two checksums.
        https://en.wikipedia.org/wiki/National_identification_number#Norway

        :param dob: date of birth as a "YYYYMMDD" string
        :type dob: str
        :param gender: gender of the person - "F" for female, M for male.
        :type gender: str
        :return: Fødselsnummer in str format (11 digs)
        :rtype: str
        """

        if dob:
            birthday = datetime.datetime.strptime(dob, "%Y%m%d")
        else:
            age = datetime.timedelta(days=self.generator.random.randrange(18 * 365, 90 * 365))
            birthday = datetime.datetime.now() - age
        if not gender:
            gender = self.generator.random.choice(("F", "M"))
        elif gender not in ("F", "M"):
            raise ValueError("Gender must be one of F or M.")

        while True:
            if 1900 <= birthday.year <= 1999:
                suffix = str(self.generator.random.randrange(0, 49))
            elif 1854 <= birthday.year <= 1899:
                suffix = str(self.generator.random.randrange(50, 74))
            elif 2000 <= birthday.year <= 2039:
                suffix = str(self.generator.random.randrange(50, 99))
            elif 1940 <= birthday.year <= 1999:
                suffix = str(self.generator.random.randrange(90, 99))
            if gender == "F":
                gender_num = self.generator.random.choice((0, 2, 4, 6, 8))
            elif gender == "M":
                gender_num = self.generator.random.choice((1, 3, 5, 7, 9))
            pnr = birthday.strftime("%d%m%y") + suffix.zfill(2) + str(gender_num)
            pnr_nums = [int(ch) for ch in pnr]
            k1 = checksum(Provider.scale1, pnr_nums)
            k2 = checksum(Provider.scale2, pnr_nums + [k1])
            # Checksums with a value of 10 is rejected.
            # https://no.wikipedia.org/wiki/F%C3%B8dselsnummer
            if k1 == 10 or k2 == 10:
                continue
            pnr += f"{k1}{k2}"
            return pnr


text:
<?php
/**
 * The contents of this file was generated using the WSDLs as provided by eBay.
 *
 * DO NOT EDIT THIS FILE!
 */

namespace DTS\eBaySDK\ResolutionCaseManagement\Types;

/**
 *
 * @property boolean $buyerPreference
 */
class BaseActivityOptionType extends \DTS\eBaySDK\Types\BaseType
{
    /**
     * @var array Properties belonging to objects of this class.
     */
    private static $propertyTypes = [
        'buyerPreference' => [
            'type' => 'boolean',
            'repeatable' => false,
            'attribute' => false,
            'elementName' => 'buyerPreference'
        ]
    ];

    /**
     * @param array $values Optional properties and values to assign to the object.
     */
    public function __construct(array $values = [])
    {
        list($parentValues, $childValues) = self::getParentValues(self::$propertyTypes, $values);

        parent::__construct($parentValues);

        if (!array_key_exists(__CLASS__, self::$properties)) {
            self::$properties[__CLASS__] = array_merge(self::$properties[get_parent_class()], self::$propertyTypes);
        }

        if (!array_key_exists(__CLASS__, self::$xmlNamespaces)) {
            self::$xmlNamespaces[__CLASS__] = 'xmlns="http://www.ebay.com/marketplace/resolution/v1/services"';
        }

        $this->setValues(__CLASS__, $childValues);
    }
}


text:
import { Matrix } from '../../../../core';

declare module '../../../../core' {
    interface Matrix {
        threshold(thresh: number, maxval: number, type: number): Matrix;
    }
}


text:
<?php

namespace App\Models\Payment;

use Illuminate\Database\Eloquent\Model;

class Invoice extends Model
{
    protected $guarded = ['id'];

    protected $table = 'invoices';

    public function user(){
        return $this->belongsTo('App\Models\User\User');
    }

    public function payments(){
        return $this->hasMany('App\Models\Payment\Payment');
    }
}


text:
package de.codecrafters.tableview.toolkit;

import de.codecrafters.tableview.R;
import de.codecrafters.tableview.SortState;
import de.codecrafters.tableview.providers.SortStateViewProvider;

/**
 * A factory providing different implementations of the {@link SortStateViewProvider}.
 *
 * @author ISchwarz
 */
public class SortStateViewProviders {

    /**
     * Gives a {@link SortStateViewProvider} that will provide dark (transparent black) arrows.
     *
     * @return The described {@link SortStateViewProvider}.
     */
    public static SortStateViewProvider darkArrows() {
        return new DarkSortStateViewProvider();
    }

    /**
     * Gives a {@link SortStateViewProvider} that will provide bright (transparent white) arrows.
     *
     * @return The described {@link SortStateViewProvider}.
     */
    public static SortStateViewProvider brightArrows() {
        return new BrightSortStateViewProvider();
    }

    private static class DarkSortStateViewProvider implements SortStateViewProvider {

        private static final int NO_IMAGE_RES = -1;

        @Override
        public int getSortStateViewResource(SortState state) {
            switch (state) {
                case SORTABLE:
                    return R.mipmap.ic_dark_sortable;
                case SORTED_ASC:
                    return R.mipmap.ic_dark_sorted_asc;
                case SORTED_DESC:
                    return R.mipmap.ic_dark_sorted_desc;
                default:
                    return NO_IMAGE_RES;
            }
        }
    }

    private static class BrightSortStateViewProvider implements SortStateViewProvider {

        private static final int NO_IMAGE_RES = -1;

        @Override
        public int getSortStateViewResource(SortState state) {
            switch (state) {
                case SORTABLE:
                    return R.mipmap.ic_light_sortable;
                case SORTED_ASC:
                    return R.mipmap.ic_light_sorted_asc;
                case SORTED_DESC:
                    return R.mipmap.ic_light_sorted_desc;
                default:
                    return NO_IMAGE_RES;
            }
        }
    }

}


text:
Team Norfolk Flood, DE HackData Hackathon 2016

##Target User and Problem Statement
Our app seeks to aid city personnel responsible for planning and marketing area-wide for dealing with the effects of sea level rise by informing citizens of estimated economic impacts, published by RTI International, on several sea-level rise scenarios and providing data on citizens reactions to those estimates.

##Data Sources
Economic Impact data from ["Final Report Hampton Roads SLR" Table 4-1]( https://norfolkflood.slack.com/files/timdunbar/F39P95T1T/final_report_hampton_roads_slr_.pdf)

[Costs of doing nothing: Economic consequences of not adapting to sea level rise in the Hampton Roads region [Prepared for the Virginia Coastal Policy Center/College of William & Mary Law School]] (https://www.rti.org/publication/costs-doing-nothing-economic-consequences-not-adapting-sea-level-rise-hampton-roads)


text:
using Antlr4.Runtime;
using Antlr4.Runtime.Sharpen;

namespace Antlr4.Runtime
{
    ///
    /// This class extends
    /// <see cref="ParserRuleContext"/>
    /// by allowing the value of
    /// <see cref="RuleIndex()"/>
    /// to be explicitly set for the context.
    ///

    /// <see cref="ParserRuleContext"/>
    /// does not include field storage for the rule index
    /// since the context classes created by the code generator override the
    /// <see cref="RuleIndex()"/>
    /// method to return the correct value for that context.
    /// Since the parser interpreter does not use the context classes generated for a
    /// parser, this class (with slightly more memory overhead per node) is used to
    /// provide equivalent functionality.

    ///
    public class InterpreterRuleContext : ParserRuleContext
    {
        ///
        /// This is the backing field for
        /// <see cref="RuleIndex()"/>
        /// .
        ///
        private readonly int ruleIndex;

        ///
        /// Constructs a new
        /// <see cref="InterpreterRuleContext"/>
        /// with the specified
        /// parent, invoking state, and rule index.
        ///
        /// <param name="parent">The parent context.</param>
        /// <param name="invokingStateNumber">The invoking state number.</param>
        /// <param name="ruleIndex">The rule index for the current context.</param>
        public InterpreterRuleContext(ParserRuleContext parent, int invokingStateNumber, int ruleIndex)
            : base(parent, invokingStateNumber)
        {
            this.ruleIndex = ruleIndex;
        }

        public override int RuleIndex
        {
            get
            {
                return ruleIndex;
            }
        }
    }
}


text:
package com.cloudbees.genapp.glassfish3;

import com.cloudbees.genapp.XmlUtils;
import com.cloudbees.genapp.metadata.Metadata;
import com.cloudbees.genapp.metadata.resource.Database;
import com.cloudbees.genapp.metadata.resource.Email;
import com.cloudbees.genapp.metadata.resource.Resource;
import com.cloudbees.genapp.metadata.resource.SessionStore;
import com.mysql.jdbc.NonRegisteringDriver;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.XPathExpressionException;
import java.io.File;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;

public class DomainXmlBuilder {

    private final Logger logger = Logger.getLogger(getClass().getName());
    private Document xmlDocument;
    private Metadata metadata;
    private List<String> databaseProperties = Arrays.asList("AllowLoadLocalInfile",
            "AllowMultiQueries",
            "AllowNanAndInf",
            "AllowUrlInLocalInfile",
            "AlwaysSendSetIsolation",
            "AutoClosePStmtStreams",
            "AutoDeserialize",
            "AutoGenerateTestcaseScript",
            "AutoReconnectForPools",
            "AutoSlowLog",
            "BlobsAreStrings",
            "BlobSendChunkSize",
            "CacheCallableStatements",
            "CacheCallableStmts",
            "CachePreparedStatements",
            "CachePrepStmts",
            "CacheResultSetMetadata",
            "CacheServerConfiguration",
            "CallableStatementCacheSize",
            "CallableStmtCacheSize",
            "CapitalizeTypeNames",
            "ClientCertificateKeyStoreType",
            "ClientInfoProvider",
            "ClobberStreamingResults",
            "CompensateOnDuplicateKeyUpdateCounts",
            "ConnectTimeout",
            "ContinueBatchOnError",
            "CreateDatabaseIfNotExist",
            "DefaultAuthenticationPlugin",
            "DefaultFetchSize",
            "DisconnectOnExpiredPasswords",
            "DontTrackOpenResources",
            "DumpMetadataOnColumnNotFound",
            "DumpQueriesOnException",
            "DynamicCalendars",
            "ElideSetAutoCommits",
            "EmptyStringsConvertToZero",
            "EmulateLocators",
            "EmulateUnsupportedPstmts",
            "EnablePacketDebug",
            "EnableQueryTimeouts",
            "ExplainSlowQueries",
            "FailOverReadOnly",
            "FunctionsNeverReturnBlobs",
            "GatherPerfMetrics",
            "GatherPerformanceMetrics",
            "GenerateSimpleParameterMetadata",
            "HoldResultsOpenOverStatementClose",
            "IgnoreNonTxTables",
            "IncludeInnodbStatusInDeadlockExceptions",
            "IncludeThreadDumpInDeadlockExceptions",
            "IncludeThreadNamesAsStatementComment",
            "InitialTimeout",
            "InteractiveClient",
            "IsInteractiveClient",
            "JdbcCompliantTruncation",
            "JdbcCompliantTruncationForReads",
            "LoadBalanceAutoCommitStatementThreshold",
            "LoadBalanceBlacklistTimeout",
            "LoadBalanceEnableJMX",
            "LoadBalanceExceptionChecker",
            "LoadBalancePingTimeout",
            "LoadBalanceStrategy",
            "LoadBalanceValidateConnectionOnSwapServer",
            "LocatorFetchBufferSize",
            "Logger",
            "LoggerClassName",
            "LoginTimeout",
            "LogSlowQueries",
            "LogXaCommands",
            "MaintainTimeStats",
            "MaxAllowedPacket",
            "MaxQuerySizeToLog",
            "MaxReconnects",
            "MaxRows",
            "MetadataCacheSize",
            "NetTimeoutForStreamingResults",
            "NoAccessToProcedureBodies",
            "NoDatetimeStringSync",
            "NoTimezoneConversionForTimeType",
            "NullCatalogMeansCurrent",
            "NullNamePatternMatchesAll",
            "OverrideSupportsIntegrityEnhancementFacility",
            "PacketDebugBufferSize",
            "PadCharsWithSpace",
            "Paranoid",
            "ParseInfoCacheFactory",
            "Pedantic",
            "PinGlobalTxToPhysicalConnection",
            "PopulateInsertRowWithDefaultValues",
            "PreparedStatementCacheSize",
            "PreparedStatementCacheSqlLimit",
            "PrepStmtCacheSize",
            "PrepStmtCacheSqlLimit",
            "ProcessEscapeCodesForPrepStmts",
            "ProfilerEventHandler",
            "ProfileSQL",
            "ProfileSql",
            "QueriesBeforeRetryMaster",
            "QueryTimeoutKillsConnection",
            "ReconnectAtTxEnd",
            "RelaxAutoCommit",
            "ReportMetricsIntervalMillis",
            "RequireSSL",
            "ResultSetSizeThreshold",
            "RetainStatementAfterResultSetClose",
            "RetriesAllDown",
            "RewriteBatchedStatements",
            "RollbackOnPooledClose",
            "RoundRobinLoadBalance",
            "RunningCTS13",
            "SecondsBeforeRetryMaster",
            "SelfDestructOnPingMaxOperations",
            "SelfDestructOnPingSecondsLifetime",
            "ServerConfigCacheFactory",
            "SlowQueryThresholdMillis",
            "SlowQueryThresholdNanos",
            "SocketFactory",
            "SocketFactoryClassName",
            "SocketTimeout",
            "StrictFloatingPoint",
            "StrictUpdates",
            "TcpKeepAlive",
            "TcpNoDelay",
            "TcpRcvBuf",
            "TcpSndBuf",
            "TcpTrafficClass",
            "TinyInt1isBit",
            "TraceProtocol",
            "TransformedBitIsBoolean",
            "TreatUtilDateAsTimestamp",
            "TrustCertificateKeyStoreType",
            "UltraDevHack",
            "UseAffectedRows",
            "UseBlobToStoreUTF8OutsideBMP",
            "UseColumnNamesInFindColumn",
            "UseCompression",
            "UseCursorFetch",
            "UseDirectRowUnpack",
            "UseDynamicCharsetInfo",
            "UseFastDateParsing",
            "UseFastIntParsing",
            "UseGmtMillisForDatetimes",
            "UseHostsInPrivileges",
            "UseInformationSchema",
            "UseJDBCCompliantTimezoneShift",
            "UseJvmCharsetConverters",
            "UseLegacyDatetimeCode",
            "UseLocalSessionState",
            "UseLocalTransactionState",
            "UseNanosForElapsedTime",
            "UseOldAliasMetadataBehavior",
            "UseOldUTF8Behavior",
            "UseOnlyServerErrorMessages",
            "UseReadAheadInput",
            "UseServerPreparedStmts",
            "UseServerPrepStmts",
            "UseSqlStateCodes",
            "UseSSL",
            "UseSSPSCompatibleTimezoneShift",
            "UseStreamLengthsInPrepStmts",
            "UseTimezone",
            "UseUltraDevWorkAround",
            "UseUnbufferedInput",
            "UseUnicode",
            "UseUsageAdvisor",
            "VerifyServerCertificate",
            "YearIsDateType",
            "ZeroDateTimeBehavior");

    public DomainXmlBuilder(Metadata metadata) {
        this.metadata = metadata;
    }

    public DomainXmlBuilder create(Metadata metadata) {
        return new DomainXmlBuilder(metadata);
    }

    private DomainXmlBuilder addResources(Metadata metadata) {
        for (Resource resource : metadata.getResources().values()) {
            if (resource instanceof Database) {
                addDatabase((Database) resource);
            } else if (resource instanceof Email) {
                addEmail((Email) resource);
            } else if (resource instanceof SessionStore) {
                addSessionStore((SessionStore) resource);
            }

        }
        return this;
    }

    private DomainXmlBuilder addDatabase(Database database) {
        logger.info("Insert DataSource " + database.getName());
        // <jdbc-connection-pool>
        Element connectionPool = xmlDocument.createElement("jdbc-connection-pool");
        connectionPool.setAttribute("driver-classname", database.getJavaDriver());
        connectionPool.setAttribute("connection-validation-method", database.getProperty("connection-validation-method", "auto-commit"));
        connectionPool.setAttribute("is-connection-validation-required", database.getProperty("is-connection-validation-required", "true"));
        connectionPool.setAttribute("validation-table-name", database.getProperty("validation-table-name", ""));

        connectionPool.setAttribute("datasource-classname", database.getDataSourceClassName());
        connectionPool.setAttribute("max-pool-size", database.getProperty("max-pool-size", "20"));
        connectionPool.setAttribute("wrap-jdbc-objects", "false");
        connectionPool.setAttribute("res-type", "javax.sql.DataSource");
        connectionPool.setAttribute("steady-pool-size", database.getProperty("steady-pool-size", "1"));
        String connectionPoolName = database.getName() + "ConnectionPool";
        connectionPool.setAttribute("name", connectionPoolName);

        String jdbcUrl = "jdbc:" + database.getUrl();
        addProperty("URL", jdbcUrl, connectionPool);
        addProperty("Url", jdbcUrl, connectionPool);
        Properties properties;
        try {
            properties = new NonRegisteringDriver().parseURL(jdbcUrl, null);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        addProperty("ServerName", properties.getProperty(NonRegisteringDriver.HOST_PROPERTY_KEY), connectionPool);
        addProperty("Port", properties.getProperty(NonRegisteringDriver.PORT_PROPERTY_KEY), connectionPool);
        addProperty("DatabaseName", properties.getProperty(NonRegisteringDriver.DBNAME_PROPERTY_KEY), connectionPool);
        addProperty("User", database.getUsername(), connectionPool);
        addProperty("Password", database.getPassword(), connectionPool);

        Map<String, String> optionalParameters = database.filterProperties(databaseProperties);
        for (Map.Entry<String, String> entry : optionalParameters.entrySet()) {
            connectionPool.setAttribute(entry.getKey(), entry.getValue());
        }
        Element glassfishResourcesElement = XmlUtils.getUniqueElement(xmlDocument, "/domain/resources");

        glassfishResourcesElement.appendChild(connectionPool);

        // <jdbc-resource>
        Element jdbcResource = xmlDocument.createElement("jdbc-resource");
        jdbcResource.setAttribute("pool-name", connectionPoolName);
        String jndiName = "jdbc/" + database.getName();
        jdbcResource.setAttribute("jndi-name", jndiName);
        glassfishResourcesElement.appendChild(jdbcResource);

        // <resource-ref ref="..." />
        Element glassfishServerElement = XmlUtils.getUniqueElement(xmlDocument, "/domain/servers/server");

        Element resourceRefElement = xmlDocument.createElement("resource-ref");
        resourceRefElement.setAttribute("ref", jndiName);
        glassfishServerElement.appendChild(resourceRefElement);

        return this;
    }

    protected void addProperty(String name, String value, Element parent) {
        Element property = parent.getOwnerDocument().createElement("property");
        property.setAttribute("name", name);
        property.setAttribute("value", value);
        parent.appendChild(property);
    }

    private void addAuthenticationRealm(Metadata metadata) throws XPathExpressionException {

        String jdbcRealmBinding = metadata.getRuntimeParameter("glassfish3", "auth-realm.database", null);
        if (jdbcRealmBinding == null) {
            return;
        }

        // Verify that the database binding exists
        Resource resource = metadata.getResource(jdbcRealmBinding);
        if (resource == null || !(resource instanceof Database)) {
            throw new RuntimeException("Database binding '" + jdbcRealmBinding + "' declared for RuntimeParameter " +
                    "glassfish3" + "#" + "auth-realm.database" + " does not exist! Existing Resources " + metadata.getResources().keySet());
        }

        String realmName = "authentication-realm";
        String groupsTable = "cb_groups";
        String usersTable = "cb_users";
        String usernameColumn = "username";
        String passwordColumn = "password";
        String groupNameColumn = "groupname";
        String encodingAlgorithm = "SHA-256";
        String encoding = "Base64";

        logger.info("Insert JdbcRealm '" + realmName + "' associated to database '" + jdbcRealmBinding + "'");

        Element authRealm = xmlDocument.createElement("auth-realm");
        authRealm.setAttribute("name", realmName);
        authRealm.setAttribute("classname", "com.sun.enterprise.security.auth.realm.jdbc.JDBCRealm");
        // jaas-context:jdbcRealm must match an enentry in login.conf
        addProperty("jaas-context", "jdbcRealm", authRealm);
        addProperty("password-column", passwordColumn, authRealm);
        addProperty("datasource-jndi", "jdbc/" + jdbcRealmBinding, authRealm);
        addProperty("group-table", groupsTable, authRealm);
        addProperty("user-table", usersTable, authRealm);
        addProperty("group-name-column", groupNameColumn, authRealm);
        addProperty("digestrealm-password-enc-algorithm", encodingAlgorithm, authRealm);
        addProperty("digest-algorithm", encodingAlgorithm, authRealm);
        addProperty("encoding", encoding, authRealm);
        addProperty("user-name-column", usernameColumn, authRealm);

        Element securityService = XmlUtils.getUniqueElement(xmlDocument, "domain/configs/config[@name='server-config']/security-service");
        securityService.appendChild(authRealm);

    }

    private DomainXmlBuilder addEmail(Email email) {
        logger.warning("email is not yet supported, ignore it");
        return this;
    }

    private DomainXmlBuilder addSessionStore(SessionStore store) {
        logger.warning("session store is not yet supported, ignore it");
        return this;
    }

    private DomainXmlBuilder fromExistingDocument(Document domainDocument) throws XPathExpressionException {
        xmlDocument = domainDocument;
        return this;
    }

    private DomainXmlBuilder fromExistingDocument(File file) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.parse(file);
        fromExistingDocument(document);
        return this;
    }

    public void writeConfiguration(String configurationRelativePath) throws Exception {

        Map<String, String> env = System.getenv();
        String configurationPath = env.get("app_dir") + configurationRelativePath;

        // Locate configuration file
        File configurationFile = new File(configurationPath);
        if (!configurationFile.exists())
            throw new Exception("Missing context config file: " + configurationFile.getAbsolutePath());

        Document contextXml = this.create(metadata).fromExistingDocument(configurationFile).buildContextDocument();

        // Write the content into XML file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "no");

        transformer.transform(new DOMSource(contextXml), new StreamResult(configurationFile));
    }

    private Document buildContextDocument() throws ParserConfigurationException, XPathExpressionException {
        if (xmlDocument == null) {
            throw new IllegalStateException();
        }

        addResources(metadata);
        addAuthenticationRealm(metadata);
        return xmlDocument;
    }

}


text:
package com.navercorp.pinpoint.bootstrap.plugin.request;

import com.navercorp.pinpoint.bootstrap.context.Header;
import com.navercorp.pinpoint.bootstrap.context.TraceContext;
import com.navercorp.pinpoint.bootstrap.context.TraceId;
import com.navercorp.pinpoint.bootstrap.logging.PLogger;
import com.navercorp.pinpoint.bootstrap.logging.PLoggerFactory;
import com.navercorp.pinpoint.bootstrap.sampler.SamplingFlagUtils;
import com.navercorp.pinpoint.common.util.StringUtils;

import java.util.Objects;

/**
 * @author jaehong.kim
 */
public class DefaultRequestTraceWriter<T> implements RequestTraceWriter<T> {

    private static final String NOT_SET = null;

    private final PLogger logger = PLoggerFactory.getLogger(this.getClass());
    private final boolean isDebug = logger.isDebugEnabled();
    private final ClientHeaderAdaptor<T> clientHeaderAdaptor;
    private final String applicationName;
    private final short serverTypeCode;
    private final String applicationNamespace;

    public DefaultRequestTraceWriter(ClientHeaderAdaptor<T> clientHeaderAdaptor, TraceContext traceContext) {
        this(clientHeaderAdaptor, traceContext.getApplicationName(), traceContext.getServerTypeCode(), traceContext.getProfilerConfig().getApplicationNamespace());
    }

    public DefaultRequestTraceWriter(ClientHeaderAdaptor<T> clientHeaderAdaptor, String applicationName, short serverTypeCode, String applicationNamespace) {
        this.clientHeaderAdaptor = Objects.requireNonNull(clientHeaderAdaptor, "clientHeaderAdaptor");

        this.applicationName = Objects.requireNonNull(applicationName, "applicationName");
        this.serverTypeCode = serverTypeCode;
        this.applicationNamespace = StringUtils.defaultIfEmpty(applicationNamespace, NOT_SET);
    }

    @Override
    public void write(T header) {
        if (isDebug) {
            logger.debug("Set request header that is not to be sampled.");
        }
        clientHeaderAdaptor.setHeader(header, Header.HTTP_SAMPLED.toString(), SamplingFlagUtils.SAMPLING_RATE_FALSE);
    }

    // Set transaction information in the request.
    @Override
    public void write(T header, final TraceId traceId, final String host) {
        Objects.requireNonNull(traceId, "traceId");

        if (isDebug) {
            logger.debug("Set request header. traceId={}, applicationName={}, serverTypeCode={}, applicationNamespace={}", traceId, applicationName, serverTypeCode, applicationNamespace);
        }
        clientHeaderAdaptor.setHeader(header, Header.HTTP_TRACE_ID.toString(), traceId.getTransactionId());
        clientHeaderAdaptor.setHeader(header, Header.HTTP_SPAN_ID.toString(), String.valueOf(traceId.getSpanId()));
        clientHeaderAdaptor.setHeader(header, Header.HTTP_PARENT_SPAN_ID.toString(), String.valueOf(traceId.getParentSpanId()));
        clientHeaderAdaptor.setHeader(header, Header.HTTP_FLAGS.toString(), String.valueOf(traceId.getFlags()));
        clientHeaderAdaptor.setHeader(header, Header.HTTP_PARENT_APPLICATION_NAME.toString(), applicationName);
        clientHeaderAdaptor.setHeader(header, Header.HTTP_PARENT_APPLICATION_TYPE.toString(), Short.toString(serverTypeCode));

        if (applicationNamespace != NOT_SET) {
            clientHeaderAdaptor.setHeader(header, Header.HTTP_PARENT_APPLICATION_NAMESPACE.toString(), applicationNamespace);
        }

        if (host != null) {
            clientHeaderAdaptor.setHeader(header, Header.HTTP_HOST.toString(), host);
        }
    }
}


text:
package org.fcrepo.storage.policy;

import static org.fcrepo.storage.policy.FedoraStoragePolicy.POLICY_RESOURCE;
import static org.junit.Assert.assertEquals;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.tika.io.IOUtils;
import org.fcrepo.kernel.services.policy.StoragePolicy;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

import static javax.ws.rs.core.MediaType.APPLICATION_FORM_URLENCODED;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

// Runs integration test for restful interface for storage policies
public class FedoraStoragePolicyIT extends AbstractResourceIT {

    private static final String MIME_KEY = "mix:mimeType";
    private static final String MIME = "image/tiff";
    private static final String STORE = "cloud-store";

    private Set<String> policyKeys;

    @Before
    public void setUp() {
        policyKeys = new HashSet<>();
    }

    @After
    public void tearDown() {
        for (String policyKey : policyKeys) {
            deletePolicy(policyKey);
        }
    }

    @Test
    public void testPolicyCreateByPost() throws Exception {
        final HttpPost objMethod = HttpPostObjMethod(POLICY_RESOURCE);
        StringEntity input = new StringEntity(MIME_KEY + " " + MIME + " " + STORE,
                                              "UTF-8");
        input.setContentType(APPLICATION_FORM_URLENCODED);
        objMethod.setEntity(input);
        final HttpResponse response = client.execute(objMethod);

        String body = IOUtils.toString(response.getEntity().getContent());
        assertEquals(body, 201, response.getStatusLine().getStatusCode());

        policyKeys.add(MIME_KEY);

        Header[] headers = response.getHeaders("Location");
        assertNotNull(headers);
        assertEquals(1, headers.length);
        assertEquals(objMethod.getURI()
                             .toString()
                             .replace(POLICY_RESOURCE, MIME_KEY),
                     headers[0].getValue());
    }

    @Test
    public void testGetStoragePolicy() throws Exception {
        // Test no policy
        final HttpGet getMethod0 = HttpGetObjMethod(MIME_KEY);
        final HttpResponse response0 = client.execute(getMethod0);
        assertNotNull(response0);
        assertEquals(IOUtils.toString(response0.getEntity().getContent()),
                     404,
                     response0.getStatusLine().getStatusCode());

        // Add a policy
        testPolicyCreateByPost();

        // Test Get Storage Policy
        final HttpGet getMethod1 = HttpGetObjMethod(MIME_KEY);
        final HttpResponse response1 = client.execute(getMethod1);
        assertNotNull(response1);

        String body = IOUtils.toString(response1.getEntity().getContent());
        assertEquals(body, 200, response1.getStatusLine().getStatusCode());
        assertEquals(MIME + ":" + STORE, body);
    }

    @Test
    public void testGetStoragePolicies() throws Exception {
        // Add a policy
        testPolicyCreateByPost();

        // Test Get Storage Policy
        final HttpGet getMethod1 = HttpGetObjMethod(POLICY_RESOURCE);
        final HttpResponse response1 = client.execute(getMethod1);
        assertNotNull(response1);

        String body = IOUtils.toString(response1.getEntity().getContent());
        assertEquals(body, 200, response1.getStatusLine().getStatusCode());

        StoragePolicy policy = new MimeTypeStoragePolicy(MIME, STORE);
        assertEquals("policies=[" + policy.toString() + "]", body);
    }

    @Test
    public void testInvalidPoliciesCreateByPost() throws Exception {
        final HttpPost objMethod = HttpPostObjMethod(POLICY_RESOURCE);
        StringEntity input = new StringEntity("mix:newType " + MIME + " " + STORE,
                                              "UTF-8");
        input.setContentType(APPLICATION_FORM_URLENCODED);
        objMethod.setEntity(input);
        final HttpResponse response = client.execute(objMethod);
        assertEquals(response.getStatusLine().getStatusCode(), 500);
    }

    @Test
    public void testPolicyDelete() throws Exception {
        testPolicyCreateByPost();

        final HttpResponse response = deletePolicy(MIME_KEY);
        assertEquals(204, response.getStatusLine().getStatusCode());

        final HttpGet objGetMethod = HttpGetObjMethod(POLICY_RESOURCE);
        final HttpResponse getResponse = client.execute(objGetMethod);
        assertEquals("No Policies Found",
                     IOUtils.toString(getResponse.getEntity().getContent())
        );
    }

    private HttpResponse deletePolicy(String policyKey) {
        final HttpDelete objMethod = HttpDeleteObjMethod(policyKey);
        try {
            return client.execute(objMethod);

        } catch (IOException e) {
            fail(e.getMessage());
            return null; // never
        }
    }

}


text:
<?php

/////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Payhub;

/////////////////////////////////////////////////////////////////////////////////////////////////////

class Payhub
{
    /////////////////////////////////////////////////////////////////////////////////////////////////////

    public static $DATETIME_ZONE;

    /////////////////////////////////////////////////////////////////////////////////////////////////////

    public $standard_request;

    /////////////////////////////////////////////////////////////////////////////////////////////////////

    private $_oauth_token;

    ///////////////////////////////////////////////////////////////////////////////////////////////////

    public function __construct($config) {
        $this->url = get_and_require($config, 'url');
        $this->url = rtrim($this->url, '/\\').'/';

        $mode = get_and_require($config, 'mode');
        if ($mode === 'live') {
            $this->_oauth_token = get_and_require($config, 'oauth_token');

            $this->standard_request = array(
                'merchant' => array(
                    'organization_id' => get_and_require($config, 'orgid'),
                    'terminal_id' => get_and_require($config, 'tid'),
                ),
            );
        } else if ($mode === 'demo') {
            $this->_oauth_token = '039d423b-3d4d-4abc-a37f-9de10a07e9ee';

            $this->standard_request = array(
                'merchant' => array(
                    'organization_id' => '10057',
                    'terminal_id' => '101',
                ),
            );
        } else {
            throw new CustomException('Invalid Payhub mode: ', $mode);
        }
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////

    public function sale($data, $options = null) {
        $options['add_response_header'] = true;

        $response = $this->_postResponse('sale', $this->_prepare_data($data), $options);

        $response = array(
            'transaction_id' => get_or_null($response, 'saleResponse', 'saleId'),
            'transaction_date_time' => $this->toLocaltime(get_or_null($response, 'createdAt')),
            'approval_code' => get_or_null($response, 'saleResponse', 'approvalCode'),
            'card_id' => get_or_null($response, 'card_data', 'id'),
            'batch_id' => get_or_null($response, 'saleResponse', 'batchId'),
            'customer_id' => get_or_null($response, 'customer', 'id'),
        );

        return $response;
    }

    public function void($transaction_id, $options = null) {
        require_value($transaction_id, 'Transaction ID');

        $options['add_response_header'] = true;

        $response = $this->_postResponse('void', array(
            'transaction_id' => $transaction_id
        ), $options);

        $response = array(
            'transaction_id' => get_or_null($response, 'lastVoidResponse', 'voidTransactionId'),
            'parent_transaction_id' => $transaction_id,
            'transaction_date_time' => $this->toLocaltime(get_and_require($response, 'createdAt')),
            'card_token_no' => get_or_null($response, 'lastVoidResponse', 'token'),
        );

        return $response;
    }

    public function refund($transaction_id, $options = null) {
        require_value($transaction_id, 'Transaction ID');

        $options['add_response_header'] = true;

        $response = $this->_postResponse('refund', array(
            'transaction_id' => $transaction_id,
            'record_format' => 'CREDIT_CARD',
        ), $options);

        $response = array(
            'transaction_id' => get_or_null($response, 'lastRefundResponse', 'refundTransactionId'),
            'parent_transaction_id' => $transaction_id,
            'transaction_date_time' => $this->toLocaltime(get_and_require($response, 'createdAt')),
            'card_token_no' => get_or_null($response, 'lastRefundResponse', 'token'),
        );

        return $response;
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////

    public function info($url_hint, $options = null) {
        return $this->_getResponse($url_hint, null, $options);
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////

    private function _prepare_data(& $data) {
        return $data;
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////

    public function toLocaltime($date_time) {
        if (!$date_time) {
            return $date_time;
        }
        $store_timezone = \Mage::app()->getStore()->getConfig('general/locale/timezone');
        if ($store_timezone !== self::$DATETIME_ZONE->getName()) { // converting timezone A to timezone A might add an offset in minutes
            $date_time = new \DateTime($date_time, new \DateTimeZone('UTC'));

            $gmt_offset = timezone_offset_get(self::$DATETIME_ZONE, $date_time);

            $date_time = $date_time->modify(strval(abs($gmt_offset)) . 'sec');

            $date_time = \Mage::getModel('core/date')->date(null, $date_time->format('Y-m-d H:i:s'));
        }

        return $date_time;
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////

    private function _postResponse($action, $request, $options = null) {
        require_value($action, 'API action');

        $url = $this->url.'api/v2/'.$action;

        $request = array_merge($request, $this->standard_request);

        $response = null;
        $ex = null;

        Log::network("|payhub||REQUEST||$action| ", $request);

        $add_response_header = isset($options['add_response_header']) && $options['add_response_header'];

        try {
            $standard_options = array(
                'curlopt' => array(
                    CURLOPT_SSL_VERIFYPEER => 0,
                ),
                'headers' => array(
                    'Authorization' => 'Bearer'.$this->_oauth_token,
                ),
            );
            if ($add_response_header) {
                $standard_options['curlopt'][CURLOPT_HEADER] = 1;
            }
            $options = array_merge($standard_options, is_null($options) ? array() : $options);

            if (get_or_null($options, 'post_form')) {
                $response = CURL::post($url, $request, array_merge($standard_options, is_null($options) ? array() : $options));
            } else {
                $response = CURL::post_json($url, $request, array_merge($standard_options, is_null($options) ? array() : $options));
            }
        } catch(\Exception $ex) {
            Log::ex($ex, "|payhub||$action|");

            $response = null;
        }

        Log::network("|payhub||RESPONSE||$action| ", $response);

        if (is_null($response)) {
            if ($ex && $add_response_header) {
                $pos = strpos($ex->getMessage(), "\r\n\r\n");
                $pos = $pos !== false ? $pos : strpos($ex->getMessage(), "\n\n");
                $message = trim(substr($ex->getMessage(), $pos));
            } else if ($ex) {
                $message = $ex->getMessage();
            } else {
                $message = 'unknown error';
            }
            $match = preg_match('/reason:([^,$]*)[$,].*/', $message, $matches);
            if ($match === 1) {
                $message = $matches[1];
            }
            throw new CustomException('API request to payhub returned with errors: ', $message);
        }

        $location = trim(preg_replace('/.*Location:\s*([^\n]*).*/ms', '$1', $response));

        if ($location) {
            $response = $this->_getResponse($location, null, $options);
        }

        return $response;
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////

    private function _getResponse($url_hint, $request = null, $options = null) {
        if (stripos($url_hint, 'http') === 0) {
            $url = $url_hint;
        } else {
            $url = $this->url.'api/v2/'.$url_hint;
        }

        $response = null;
        $ex = null;

        Log::network("|payhub||REQUEST||$url_hint| ", $request);

        try {
            $response = CURL::get($url, $request, array_merge(array(
                'curlopt' => array(
                    CURLOPT_SSL_VERIFYPEER => 0,
                    CURLOPT_HEADER => 0,
                ),
                'headers' => array(
                    'Authorization' => 'Bearer'.$this->_oauth_token,
                ),
            ), is_null($options) ? array() : $options));
        } catch(\Exception $ex) {
            Log::ex($ex, "|payhub||$url_hint|");

            $response = null;
        }

        if ($response && strpos($response, 'HTTP/') == 0) {
            $pos = strpos($response, "\r\n\r\n");
            $pos = $pos !== false ? $pos : strpos($response, "\n\n");
            $response = trim(substr($response, $pos));
            $response = json_decode($response, true);
        }

        Log::network("|payhub||RESPONSE||$url_hint| ", $response);

        if (is_null($response)) {
            throw new CustomException('API request to payhub returned with errors: ', $ex ? $ex->getMessage() : 'unknown error');
        }

        return $response;
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////////

}

/////////////////////////////////////////////////////////////////////////////////////////////////////

Payhub::$DATETIME_ZONE = new \DateTimeZone('America/Los_Angeles');

///////////////////////////////////////////////////////////////////////////////////////////////////


text:
<!--
  ~ Copyright (c) 2016 Adventech <info@adventech.io>
  ~
  ~ Permission is hereby granted, free of charge, to any person obtaining a copy
  ~ of this software and associated documentation files (the "Software"), to deal
  ~ in the Software without restriction, including without limitation the rights
  ~ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  ~ copies of the Software, and to permit persons to whom the Software is
  ~ furnished to do so, subject to the following conditions:
  ~
  ~ The above copyright notice and this permission notice shall be included in
  ~ all copies or substantial portions of the Software.
  ~
  ~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  ~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  ~ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  ~ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  ~ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  ~ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  ~ THE SOFTWARE.
  -->

<resources>
    <string name="ss_app_name">Sabbatschule</string>
    <string name="ss_share">Weiterempfehlen</string>
    <string name="ss_login_button_google">Über Google anmelden</string>
    <string name="ss_login_button_facebook">Über Facebook anmelden</string>
    <string name="ss_login_button_anonymous">Ohne Anmeldung weiter</string>
    <string name="ss_menu_anonymous_name">Anonym</string>
    <string name="ss_menu_sign_out">Ausloggen</string>
    <string name="ss_menu_read_now">Jetzt lesen</string>
    <string name="ss_menu_share_app">App teilen</string>
    <string name="ss_menu_share_app_text">Ich benutze die Sabbatschule App</string>
    <string name="ss_my_highlights">Meine Hervorhebungen</string>
    <string name="ss_my_notes">Meine Notizen</string>
    <string name="ss_settings">Einstellungen</string>
    <string name="ss_about">Impressum</string>
    <string name="ss_login_failed">Anmeldung fehlgeschlagen. Bitte versuche es erneut</string>
    <string name="ss_login_anonymously_dialog_positive">Ja</string>
    <string name="ss_login_anonymously_dialog_negative">Nein</string>
    <string name="ss_login_anonymously_dialog_title">Anonym anmelden?</string>
    <string name="ss_login_anonymously_dialog_description">Mit der anonymen Anmeldung werden Sie nicht in der Lage sein Ihre Daten, wie zum Beispiel Kommentare und Hervorhebungen, auf verschiedenen Geräten zu synchronisieren oder nach einer Deinstallation zu verwenden. Sind Sie sicher, dass Sie fortfahren möchten?</string>
    <string name="ss_quarterlies_filter_languages_prompt_title">In anderen Sprachen lesen</string>
    <string name="ss_quarterlies_filter_languages_prompt_description">Tippen Sie auf das Filtersymbol, um alle verfügbaren Sprachen anzuzeigen</string>
    <string name="ss_quarterlies_filter_languages">Sprachenfilter</string>
    <string name="ss_quarterlies_downloading">Lade die Liste der Lektionen runter...</string>
    <string name="ss_quarterlies_error">Ein unbekannter Fehler ist aufgetreten. Bitte versuche es erneut</string>
    <string name="ss_quarterlies_empty">Zur Zeit wurden keine Lektionen gefunden</string>
    <string name="ss_quarterly_item_read_text">Öffnen</string>
    <string name="ss_lessons_downloading">Lektion wird geöffnet…</string>
    <string name="ss_lessons_error">Fehler beim Öffnen der Lektion. Bitte versuche es erneut</string>
    <string name="ss_lessons_empty">Es wurden keine Lektionen gefunden</string>
    <string name="ss_lessons_read">Lesen</string>
    <string name="ss_reading_empty">Die Lektion ist zur Zeit leer</string>
    <string name="ss_reading_offline">Du bist offline. Reconnect, um diese Lektion zu lesen</string>
    <string name="ss_reading_offline_retry">Wiederholen</string>
    <string name="ss_reading_downloading">Laden von Lektion für offline</string>
    <string name="ss_reading_error">Fehler beim Öffnen der Lektion. Bitte versuche es erneut</string>
    <string name="ss_reading_suggest_edit">Fehler oder Vorschlag übermitteln</string>
    <string name="ss_reading_suggest_edit_hint">Bitte beschreiben Sie den Fehler oder Ihren Vorschlag</string>
    <string name="ss_reading_suggest_edit_done">Vielen Dank! Ihr Vorschlag wird überprüft</string>
    <string name="ss_reading_comment">Kommentar</string>
    <string name="ss_reading_enter_comment">Geben Sie Ihren Kommentar ein</string>
    <string name="ss_reading_copied">Auswahl wurde kopiert</string>
    <string name="ss_reading_share_to">Auswahl teilen über:</string>
    <string name="ss_bible">Bibel</string>

    <!-- TODO: remove when done -->
    <string name="ss_coming_soon_header">Demnächst</string>
    <string name="ss_coming_soon_subheader">Zur Zeit arbeiten wir an dieser Funktion. Haben Sie Geduld, bald wird diese verfügbar sein</string>
    <string name="ss_about_app_version">version 3.0</string>
    <string name="ss_about_made">Entwickelt mit ❤ von Adventech</string>
    <string name="ss_settings_display_options">Darstellungsoptionen</string>
    <string name="ss_settings_color_theme">Farbschema</string>
    <string name="ss_settings_color_theme_light">Hell</string>
    <string name="ss_settings_color_theme_sepia">Sepia</string>
    <string name="ss_settings_color_theme_dark">Dunkel</string>
    <string name="ss_settings_typeface">Schriftart</string>
    <string name="ss_settings_font_size">Schriftgröße</string>
    <string name="ss_settings_font_size_tiny">Sehr klein</string>
    <string name="ss_settings_font_size_small">Klein</string>
    <string name="ss_settings_font_size_medium">Mittel</string>
    <string name="ss_settings_font_size_large">Groß</string>
    <string name="ss_settings_font_size_huge">Sehr groß</string>

    <string name="ss_settings_reminder">Tägliche Benachrichtigung</string>
    <string name="ss_settings_reminder_summary">Selektieren um täglich über die Sabbatschullektion benachrichtigt zu werden</string>
    <string name="ss_settings_reminder_time">Zeitpunkt der Benachrichtigung</string>
    <string name="ss_settings_reminder_text">Zeit, die Sabbatschule zu studieren</string>

    <!-- RATE APP -->
    <string name="rate_dialog_title">Sabbatschule-App bewerten</string>
    <string name="rate_dialog_message">Wenn Sie Sabbatschule-App mögen, wären Sie bereit einen Moment Zeit zu nehmen um die App zu bewerten? Danke für Ihre Unterstützung!</string>
    <string name="rate_dialog_ok">Bewerten</string>
    <string name="rate_dialog_cancel">Später</string>
    <string name="rate_dialog_no">Nein</string>

    <string name="ss_settings_website">Webseite</string>
</resources>


text:
<?php
session_start();
if (!isset($_SESSION["manager"])) {
    header("location: admin_login.php");
    exit();
}
// Be sure to check that this manager SESSION value is in fact in the database
$managerID = preg_replace('#[^0-9]#i', '', $_SESSION["id"]); // filter everything but numbers and letters
$manager = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["manager"]); // filter everything but numbers and letters
$password = preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["password"]); // filter everything but numbers and letters
// Run mySQL query to be sure that this person is an admin and that their password session var equals the database information

include "../storescripts/connect_to_mysql.php";
    $sql_get_admin = "SELECT * FROM admin WHERE id=? AND username=? AND password=? LIMIT 1";
	$sql_query = $DBH->prepare($sql_get_admin); //saves againt injections
	$sql_query->execute(array($managerID,$manager,$password));
    // ------- MAKE SURE PERSON EXISTS IN DATABASE ---------
    $user = $sql_query->fetchColumn(); // returns the desired row
if (!$user  ) { // evaluate the count
	 echo "Your login session data is not on record in the database.";
     exit();
}
?>
<!doctype html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Ali's Game Store | Welcome</title>
    <link rel="stylesheet" href="../css/foundation.css" />

	<link rel="stylesheet" href="../style/style.css" type="text/css" media="screen" />

  <?php include_once("../template_header.php");?>

Manager page

		 Welcome manager! Here you can manage items and import/export the products table from mysql as XML

	<form  action="inventory_list.php" >
	<fieldset>
	<legend>Manage Inventory</legend>
		<input  class="button"  type="submit" value="Manage">
	</fieldset>
	</form>
	<form  action="exportXML.php" >
	<fieldset>
	<legend>Export products table as xml file</legend>
		<input  class="button"  type="submit" value="Export">
	</fieldset>
	</form>
	<form name="import_form" action="importXML.php" method="POST"  enctype="multipart/form-data">
	<fieldset>
	<legend>Import a products via xml file</legend>
		<input type="file" class="button postfix"  value="upload"  name="file">
		<input  class="button"  type="submit" value="Upload">
	</fieldset>
	</form>

  <?php include_once("../template_footer.php");?>


text:
/*
 * @author max
 */
package org.jetbrains.generate.tostring.template;

import com.intellij.openapi.components.*;
import com.intellij.openapi.util.Comparing;

import java.util.*;

@State(
  name = "ToStringTemplates",
  storages = {
    @Storage(
      file = StoragePathMacros.APP_CONFIG + "/toStringTemplates.xml"
    )}
)
public class TemplatesManager implements PersistentStateComponent<TemplatesState> {
    public static TemplatesManager getInstance() {
        return ServiceManager.getService(TemplatesManager.class);
    }

    private TemplatesState myState = new TemplatesState();

    public TemplatesManager() {
        for (TemplateResource o : TemplateResourceLocator.getDefaultTemplates()) {
            addTemplate(o);
        }
    }

    public TemplatesState getState() {
        return myState;
    }

    public void loadState(TemplatesState state) {
        myState = state;
    }

    public void addTemplate(TemplateResource template) {
        myState.templates.add(template);
    }

    public void removeTemplate(TemplateResource template) {
        final Iterator<TemplateResource> it = myState.templates.iterator();
        while (it.hasNext()) {
            TemplateResource resource = it.next();
            if (Comparing.equal(resource.getFileName(), template.getFileName())) {
                it.remove();
            }
        }
    }

  public Collection<TemplateResource> getAllTemplates() {
    TemplateResource[] defaultTemplates = TemplateResourceLocator.getDefaultTemplates();
    HashSet<String> names = new HashSet<String>();
    for (TemplateResource defaultTemplate : defaultTemplates) {
      names.add(defaultTemplate.getFileName());
    }
    Collection<TemplateResource> templates = new LinkedHashSet<TemplateResource>(Arrays.asList(defaultTemplates));
    for (TemplateResource template : myState.templates) {
      if (!names.contains(template.getFileName())) {
        templates.add(template);
      }
    }
    return templates;
  }

  public TemplateResource getDefaultTemplate() {
        for (TemplateResource template : getAllTemplates()) {
            if (Comparing.equal(template.getFileName(), myState.defaultTempalteName)) {
                return template;
            }
        }

        return getAllTemplates().iterator().next();
    }

    public void setDefaultTemplate(TemplateResource res) {
        myState.defaultTempalteName = res.getFileName();
    }

    public void setTemplates(List<TemplateResource> items) {
        myState.templates.clear();
        for (TemplateResource item : items) {
            if (!item.isDefault()) {
                myState.templates.add(item);
            }
        }
    }
}