<commit_before>/* @flow */
/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

// The GraphQL query recommended for a full schema introspection.
export { introspectionQuery } from './introspectionQuery';

// Build a GraphQLSchema from an introspection result.
export { buildClientSchema } from './buildClientSchema';

// Build a GraphQLSchema from a parsed GraphQL Schema language AST.
export { buildASTSchema } from './buildASTSchema';

// Print a GraphQLSchema to GraphQL Schema language.
export { printSchema, printIntrospectionSchema } from './schemaPrinter';

// Create a GraphQLType from a GraphQL language AST.
export { typeFromAST } from './typeFromAST';

// Create a JavaScript value from a GraphQL language AST.
export { valueFromAST } from './valueFromAST';

// Create a GraphQL language AST from a JavaScript value.
export { astFromValue } from './astFromValue';

// A helper to use within recursive-descent visitors which need to be aware of
// the GraphQL type system.
export { TypeInfo } from './TypeInfo';

// Determine if JavaScript values adhere to a GraphQL type.
export { isValidJSValue } from './isValidJSValue';

// Determine if AST values adhere to a GraphQL type.
export { isValidLiteralValue } from './isValidLiteralValue';
<commit_msg>properly export getOperationAST utility<commit_after>/* @flow */
/**
 *  Copyright (c) 2015, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 */

// The GraphQL query recommended for a full schema introspection.
export { introspectionQuery } from './introspectionQuery';

// Gets the target Operation from a Document
export { getOperationAST } from './getOperationAST';

// Build a GraphQLSchema from an introspection result.
export { buildClientSchema } from './buildClientSchema';

// Build a GraphQLSchema from a parsed GraphQL Schema language AST.
export { buildASTSchema } from './buildASTSchema';

// Print a GraphQLSchema to GraphQL Schema language.
export { printSchema, printIntrospectionSchema } from './schemaPrinter';

// Create a GraphQLType from a GraphQL language AST.
export { typeFromAST } from './typeFromAST';

// Create a JavaScript value from a GraphQL language AST.
export { valueFromAST } from './valueFromAST';

// Create a GraphQL language AST from a JavaScript value.
export { astFromValue } from './astFromValue';

// A helper to use within recursive-descent visitors which need to be aware of
// the GraphQL type system.
export { TypeInfo } from './TypeInfo';

// Determine if JavaScript values adhere to a GraphQL type.
export { isValidJSValue } from './isValidJSValue';

// Determine if AST values adhere to a GraphQL type.
export { isValidLiteralValue } from './isValidLiteralValue';
<|endoftext|>


<commit_before>export const defaultState = {
  contracts: {
    token: {},
    crowdsale: {addr:[], abiConstructor:[]},
    pricingStrategy: {addr:[], abiConstructor:[]},
    multisig: {},
    nullFinalizeAgent: {addr:[], abiConstructor:[]},
    finalizeAgent: {addr:[], abiConstructor:[]},
    tokenTransferProxy: {}
  },
  token: {
    name: '',
    ticker: '',
    supply: 0,
    decimals: '',
    reservedTokens: [],
    reservedTokensElements: [],
    reservedTokensInput: {dim: "tokens"}
  },
  crowdsale: [{
    startTime: '',
    endTime: '',
    walletAddress: '',
    supply: '',
    whitelist: [],
    whitelistElements: [],
    whitelistInput: {}
  }],
  pricingStrategy: [{rate: ''}],
  blockTimeGeneration: 17,
  compilerVersion: "0.4.11",
  optimized: true,
  contractName: "MintedTokenCappedCrowdsaleExt",
  contractType: "white-list-with-cap",
  contractTypes: {
    standard: "standard",
    capped: "capped",
    whitelistwithcap: "white-list-with-cap"
  }
}

export const defaultTiers = [{
  startTime: '',
  endTime: '',
  walletAddress: '',
  supply: '',
  whitelist: [],
  whitelistElements: [],
  whitelistInput: {}
}]

export const CONTRACT_TYPES = {
  standard: "standard",
  capped: "capped",
  whitelistwithcap: "white-list-with-cap"
}

export const TRUNC_TO_DECIMALS = {
  DECIMALS18: -18
}

export const GAS_PRICE = {
  SLOW: {
    ID: 'slow',
    PRICE: 5000000000,
    DESCRIPTION: 'Slow and Cheap'
  },
  NORMAL: {
    ID: 'normal',
    PRICE: 10000000000,
    DESCRIPTION: 'Normal'
  },
  FAST: {
    ID: 'fast',
    PRICE: 15000000000,
    DESCRIPTION: 'Fast and Expensive'
  },
  INSTANT: {
    ID: 'instant',
    PRICE: 45000000000,
    DESCRIPTION: 'Instantaneous and Expensive'
  },
  CUSTOM: {
    ID: 'custom',
    PRICE: 0,
    DESCRIPTION: 'Custom'
  },
  API: {
    URL: 'https://gasprice.poa.network'
  }
}
export const UNKNOWN = "Unknown"
export const CHAINS = {
  UNKNOWN: 'Unknown',
  MAINNET: 'Mainnet',
  MORDEN: 'Morden',
  ROPSTEN: 'Ropsten',
  RINKEBY: 'Rinkeby',
  KOVAN: 'Kovan',
  ORACLES: 'Oracles dev test'
}

export const NAVIGATION_STEPS = {
  CROWDSALE_CONTRACT: 'Crowdsale Contract',
  TOKEN_SETUP: 'Token Setup',
  CROWDSALE_SETUP: 'Crowdsale Setup',
  PUBLISH: 'Publish',
  CROWDSALE_PAGE: 'Crowdsale Page'
}

export const VALIDATION_MESSAGES = {
  TIER: 'Please enter a valid tier name between 1-30 characters',
  NAME: 'Please enter a valid name between 1-30 characters',
  TICKER: 'Please enter a valid Ticker that is less than three characters',
  SUPPLY: 'Please enter a valid number greater than 0',
  DECIMALS: 'Please enter a number greater than or equal to zero',
  WALLET_ADDRESS: 'Please enter a valid address',
  START_TIME: 'Please enter a valid date later than now',
  END_TIME: 'Please enter a valid date later than start time',
  MULTIPLE_TIERS_START_TIME: 'Please enter a valid date not less than the end time of the previous tier',
  EDITED_END_TIME: 'Please enter a valid date later than start time and previous than start time of next tier',
  EDITED_START_TIME: 'Please enter a valid date later than now, less than end time and later than the end time of the previous tier',
  RATE: 'Please enter a valid number greater than 0'
}

export const TEXT_FIELDS = {
  NAME: 'Name',
  TICKER: 'Ticker',
  SUPPLY: 'Supply',
  DECIMALS: 'Decimals',
  RATE: 'Rate',
  WALLET_ADDRESS: 'Wallet Address',
  START_TIME: 'Start Time',
  END_TIME: 'End Time',
  CROWDSALE_SETUP_NAME: 'Crowdsale setup name',
  ADDRESS: 'Address',
  MIN: 'Min',
  MAX: 'Max',
  MINCAP: 'Investor min cap',
  DIMENSION: 'Dimension',
  VALUE: 'Value',
  MAX_CAP: 'Max cap',
  ALLOWMODIFYING: 'Allow modifying',
  DISABLEWHITELISTING: 'Disable whitelisting',
  GAS_PRICE: 'Gas Price'
}

export const VALIDATION_TYPES = {
  VALID: "VALIDATED",
  EMPTY: 'EMPTY',
  INVALID: 'INVALID'
}
const { VALID, EMPTY } = VALIDATION_TYPES

export const intitialStepTwoValidations = {
  validations: {
    name: EMPTY,
    decimals: EMPTY,
    ticker: EMPTY
  }
}

export const initialStepTwoValues = {
  token: {
    name: '',
    supply: 0,
    ticker: '',
    decimals: '',
    reservedTokens: [],
    reservedTokensElements: [],
    reservedTokensInput: {dim: "tokens"}
  }
}

export const intitialStepThreeValidations = {
  validations: [{
    tier: VALID,
    startTime: VALID,
    endTime: VALID,
    walletAddress: EMPTY,
    supply: VALID,
    rate: EMPTY
  }]
}

export const initialStepThreeValues = {
  crowdsale: [{
    tier: '',
    startTime: '',
    endTime: '',
    walletAddress: '',
    supply: ''
  }]
}

export const FILE_CONTENTS = {
  common: [
    { field: 'name', value: 'Token name: ', parent: 'tokenStore' },
    { field: 'ticker', value: 'Token ticker: ', parent: 'tokenStore' },
    { field: 'decimals', value: 'Token decimals: ', parent: 'tokenStore' },
    { field: 'walletAddress', value: 'Multisig wallet address: ', parent: 'tierStore' },
    { value: '*****************************', parent: 'none', fileValue: '' },
    { field: 'rate', value: 'Crowdsale rate: ', parent: 'tierStore' },
    { field: 'startTime', value: 'Crowdsale start time: ', parent: 'tierStore' },
    { field: 'endTime', value: 'Crowdsale end time: ', parent: 'tierStore' },
    { value: 'Compiler Version: ', parent: 'none', fileValue: '0.4.11' },
    { value: 'Is optimization enabled?: ', parent: 'none', fileValue: 'true' },
    { value: '*****************************', parent: 'none', fileValue: '' }
  ],
  files: {
    order: [
      'safeMathLib',
      'token',
      'pricingStrategy',
      'crowdsale',
      'nullFinalizeAgent',
      'finalizeAgent'
    ],
    safeMathLib: {
      name: 'SafeMathLibExt',
      txt: [
        { value: 'SafeMathLib library name: ', parent: 'none', fileValue: 'SafeMathLibExt' },
        { field: 'addr', value: 'SafeMathLib library address: ', parent: 'contracts', child: 'safeMathLib' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        { field: 'abi', value: '****SafeMathLib contract ABI:**** \n\n', parent: 'contracts', child: 'safeMathLib' }
      ],
      sol: {
        field: 'src',
        value: '****SafeMathLib contract source:**** \n\n',
        parent: 'contracts',
        child: 'safeMathLib'
      }

    },
    token: {
      name: 'CrowdsaleTokenExt',
      txt: [
        { value: 'Token contract name: ', parent: 'none', fileValue: 'CrowdsaleTokenExt' },
        { field: 'addr', value: 'Token contract address: ', parent: 'contracts', child: 'token' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        { field: 'abi', value: '****Token contract ABI:**** \n\n', parent: 'contracts', child: 'token' },
        {
          field: 'abiConstructor',
          value: '****Token contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'token'
        }
      ],
      sol: { field: 'src', value: '****Token contract source:**** \n\n', parent: 'contracts', child: 'token' }

    },
    pricingStrategy: {
      name: 'FlatPricingExt',
      txt: [
        { value: 'Pricing strategy contract name: ', parent: 'none', fileValue: 'FlatPricingExt' },
        { field: 'addr', value: 'Pricing strategy contract address', parent: 'contracts', child: 'pricingStrategy' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        {
          field: 'abi',
          value: '****Pricing strategy contract ABI:**** \n\n',
          parent: 'contracts',
          child: 'pricingStrategy'
        },
        {
          field: 'abiConstructor',
          value: '****Pricing strategy contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'pricingStrategy'
        }
      ],
      sol: {
        field: 'src',
        value: '****Pricing strategy contract source:**** \n\n',
        parent: 'contracts',
        child: 'pricingStrategy'
      }

    },
    crowdsale: {
      name: 'MintedTokenCappedCrowdsaleExt',
      txt: [
        { value: 'Crowdsale contract name: ', parent: 'none', fileValue: 'MintedTokenCappedCrowdsaleExt' },
        { field: 'addr', value: 'Crowdsale contract address', parent: 'contracts', child: 'crowdsale' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        { field: 'abi', value: '****Crowdsale contract ABI:**** \n\n', parent: 'contracts', child: 'crowdsale' },
        {
          field: 'abiConstructor',
          value: '****Crowdsale contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'crowdsale'
        }
      ],
      sol: { field: 'src', value: '****Crowdsale contract source:**** \n\n', parent: 'contracts', child: 'crowdsale' }

    },
    nullFinalizeAgent: {
      name: 'NullFinalizeAgentExt',
      txt: [
        { value: 'Null finalize agent contract name: ', parent: 'none', fileValue: 'NullFinalizeAgentExt' },
        {
          field: 'addr',
          value: 'Null finalize agent contract address',
          parent: 'contracts',
          child: 'finalizeAgent'
        },
        { value: '*****************************', parent: 'none', fileValue: '' },
        {
          field: 'abi',
          value: '****Null Finalize agent contract ABI:**** \n\n',
          parent: 'contracts',
          child: 'nullFinalizeAgent'
        },
        {
          field: 'abiConstructor',
          value: '****Null Finalize agent contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'finalizeAgent'
        }
      ],
      sol: {
        field: 'src',
        value: '****Null Finalize agent contract source:**** \n\n',
        parent: 'contracts',
        child: 'nullFinalizeAgent'
      }

    },
    finalizeAgent: {
      name: 'ReservedTokensFinalizeAgent',
      txt: [
        { value: 'Finalize agent contract name: ', parent: 'none', fileValue: 'ReservedTokensFinalizeAgent' },
        { field: 'addr', value: 'Finalize agent contract address', parent: 'contracts', child: 'finalizeAgent' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        {
          field: 'abi',
          value: '****Finalize agent contract ABI:**** \n\n',
          parent: 'contracts',
          child: 'finalizeAgent'
        },
        {
          field: 'abiConstructor',
          value: '****Finalize agent contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'finalizeAgent'
        }
      ],
      sol: {
        field: 'src',
        value: '****Finalize agent contract source:**** \n\n',
        parent: 'contracts',
        child: 'finalizeAgent'
      }

    }
  }
}

export const DOWNLOAD_NAME = 'icowizard'
export const DOWNLOAD_TYPE = {
  text: 'text/plain',
  blob: 'blob'
}

export const INVESTMENT_OPTIONS = {
  METAMASK: 'metamask',
  QR: 'qr'
}
export const TOAST = {
  TYPE: {
    ERROR: 'error',
    INFO: 'info',
    SUCCESS: 'warning'
  },
  MESSAGE: {
    TRANSACTION_FAILED: 'Transaction has failed, please retry',
    CONTRACT_DOWNLOAD_FAILED: 'Contract Download failed',
    CONTRACT_DOWNLOAD_SUCCESS: 'A file with contracts and metadata downloaded on your computer',
    FINALIZE_FAIL: 'Was not able to finalize Crowdsale. Please be sure that Crowdsale has ended already'
  },
  DEFAULT_OPTIONS: {
    position: 'top right',
    offset: '80px 14',
    time: 10000
  }
}
<commit_msg>Rename Slow to Safe<commit_after>export const defaultState = {
  contracts: {
    token: {},
    crowdsale: {addr:[], abiConstructor:[]},
    pricingStrategy: {addr:[], abiConstructor:[]},
    multisig: {},
    nullFinalizeAgent: {addr:[], abiConstructor:[]},
    finalizeAgent: {addr:[], abiConstructor:[]},
    tokenTransferProxy: {}
  },
  token: {
    name: '',
    ticker: '',
    supply: 0,
    decimals: '',
    reservedTokens: [],
    reservedTokensElements: [],
    reservedTokensInput: {dim: "tokens"}
  },
  crowdsale: [{
    startTime: '',
    endTime: '',
    walletAddress: '',
    supply: '',
    whitelist: [],
    whitelistElements: [],
    whitelistInput: {}
  }],
  pricingStrategy: [{rate: ''}],
  blockTimeGeneration: 17,
  compilerVersion: "0.4.11",
  optimized: true,
  contractName: "MintedTokenCappedCrowdsaleExt",
  contractType: "white-list-with-cap",
  contractTypes: {
    standard: "standard",
    capped: "capped",
    whitelistwithcap: "white-list-with-cap"
  }
}

export const defaultTiers = [{
  startTime: '',
  endTime: '',
  walletAddress: '',
  supply: '',
  whitelist: [],
  whitelistElements: [],
  whitelistInput: {}
}]

export const CONTRACT_TYPES = {
  standard: "standard",
  capped: "capped",
  whitelistwithcap: "white-list-with-cap"
}

export const TRUNC_TO_DECIMALS = {
  DECIMALS18: -18
}

export const GAS_PRICE = {
  SLOW: {
    ID: 'slow',
    PRICE: 5000000000,
    DESCRIPTION: 'Safe and Cheap'
  },
  NORMAL: {
    ID: 'normal',
    PRICE: 10000000000,
    DESCRIPTION: 'Normal'
  },
  FAST: {
    ID: 'fast',
    PRICE: 15000000000,
    DESCRIPTION: 'Fast and Expensive'
  },
  INSTANT: {
    ID: 'instant',
    PRICE: 45000000000,
    DESCRIPTION: 'Instantaneous and Expensive'
  },
  CUSTOM: {
    ID: 'custom',
    PRICE: 0,
    DESCRIPTION: 'Custom'
  },
  API: {
    URL: 'https://gasprice.poa.network'
  }
}
export const UNKNOWN = "Unknown"
export const CHAINS = {
  UNKNOWN: 'Unknown',
  MAINNET: 'Mainnet',
  MORDEN: 'Morden',
  ROPSTEN: 'Ropsten',
  RINKEBY: 'Rinkeby',
  KOVAN: 'Kovan',
  ORACLES: 'Oracles dev test'
}

export const NAVIGATION_STEPS = {
  CROWDSALE_CONTRACT: 'Crowdsale Contract',
  TOKEN_SETUP: 'Token Setup',
  CROWDSALE_SETUP: 'Crowdsale Setup',
  PUBLISH: 'Publish',
  CROWDSALE_PAGE: 'Crowdsale Page'
}

export const VALIDATION_MESSAGES = {
  TIER: 'Please enter a valid tier name between 1-30 characters',
  NAME: 'Please enter a valid name between 1-30 characters',
  TICKER: 'Please enter a valid Ticker that is less than three characters',
  SUPPLY: 'Please enter a valid number greater than 0',
  DECIMALS: 'Please enter a number greater than or equal to zero',
  WALLET_ADDRESS: 'Please enter a valid address',
  START_TIME: 'Please enter a valid date later than now',
  END_TIME: 'Please enter a valid date later than start time',
  MULTIPLE_TIERS_START_TIME: 'Please enter a valid date not less than the end time of the previous tier',
  EDITED_END_TIME: 'Please enter a valid date later than start time and previous than start time of next tier',
  EDITED_START_TIME: 'Please enter a valid date later than now, less than end time and later than the end time of the previous tier',
  RATE: 'Please enter a valid number greater than 0'
}

export const TEXT_FIELDS = {
  NAME: 'Name',
  TICKER: 'Ticker',
  SUPPLY: 'Supply',
  DECIMALS: 'Decimals',
  RATE: 'Rate',
  WALLET_ADDRESS: 'Wallet Address',
  START_TIME: 'Start Time',
  END_TIME: 'End Time',
  CROWDSALE_SETUP_NAME: 'Crowdsale setup name',
  ADDRESS: 'Address',
  MIN: 'Min',
  MAX: 'Max',
  MINCAP: 'Investor min cap',
  DIMENSION: 'Dimension',
  VALUE: 'Value',
  MAX_CAP: 'Max cap',
  ALLOWMODIFYING: 'Allow modifying',
  DISABLEWHITELISTING: 'Disable whitelisting',
  GAS_PRICE: 'Gas Price'
}

export const VALIDATION_TYPES = {
  VALID: "VALIDATED",
  EMPTY: 'EMPTY',
  INVALID: 'INVALID'
}
const { VALID, EMPTY } = VALIDATION_TYPES

export const intitialStepTwoValidations = {
  validations: {
    name: EMPTY,
    decimals: EMPTY,
    ticker: EMPTY
  }
}

export const initialStepTwoValues = {
  token: {
    name: '',
    supply: 0,
    ticker: '',
    decimals: '',
    reservedTokens: [],
    reservedTokensElements: [],
    reservedTokensInput: {dim: "tokens"}
  }
}

export const intitialStepThreeValidations = {
  validations: [{
    tier: VALID,
    startTime: VALID,
    endTime: VALID,
    walletAddress: EMPTY,
    supply: VALID,
    rate: EMPTY
  }]
}

export const initialStepThreeValues = {
  crowdsale: [{
    tier: '',
    startTime: '',
    endTime: '',
    walletAddress: '',
    supply: ''
  }]
}

export const FILE_CONTENTS = {
  common: [
    { field: 'name', value: 'Token name: ', parent: 'tokenStore' },
    { field: 'ticker', value: 'Token ticker: ', parent: 'tokenStore' },
    { field: 'decimals', value: 'Token decimals: ', parent: 'tokenStore' },
    { field: 'walletAddress', value: 'Multisig wallet address: ', parent: 'tierStore' },
    { value: '*****************************', parent: 'none', fileValue: '' },
    { field: 'rate', value: 'Crowdsale rate: ', parent: 'tierStore' },
    { field: 'startTime', value: 'Crowdsale start time: ', parent: 'tierStore' },
    { field: 'endTime', value: 'Crowdsale end time: ', parent: 'tierStore' },
    { value: 'Compiler Version: ', parent: 'none', fileValue: '0.4.11' },
    { value: 'Is optimization enabled?: ', parent: 'none', fileValue: 'true' },
    { value: '*****************************', parent: 'none', fileValue: '' }
  ],
  files: {
    order: [
      'safeMathLib',
      'token',
      'pricingStrategy',
      'crowdsale',
      'nullFinalizeAgent',
      'finalizeAgent'
    ],
    safeMathLib: {
      name: 'SafeMathLibExt',
      txt: [
        { value: 'SafeMathLib library name: ', parent: 'none', fileValue: 'SafeMathLibExt' },
        { field: 'addr', value: 'SafeMathLib library address: ', parent: 'contracts', child: 'safeMathLib' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        { field: 'abi', value: '****SafeMathLib contract ABI:**** \n\n', parent: 'contracts', child: 'safeMathLib' }
      ],
      sol: {
        field: 'src',
        value: '****SafeMathLib contract source:**** \n\n',
        parent: 'contracts',
        child: 'safeMathLib'
      }

    },
    token: {
      name: 'CrowdsaleTokenExt',
      txt: [
        { value: 'Token contract name: ', parent: 'none', fileValue: 'CrowdsaleTokenExt' },
        { field: 'addr', value: 'Token contract address: ', parent: 'contracts', child: 'token' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        { field: 'abi', value: '****Token contract ABI:**** \n\n', parent: 'contracts', child: 'token' },
        {
          field: 'abiConstructor',
          value: '****Token contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'token'
        }
      ],
      sol: { field: 'src', value: '****Token contract source:**** \n\n', parent: 'contracts', child: 'token' }

    },
    pricingStrategy: {
      name: 'FlatPricingExt',
      txt: [
        { value: 'Pricing strategy contract name: ', parent: 'none', fileValue: 'FlatPricingExt' },
        { field: 'addr', value: 'Pricing strategy contract address', parent: 'contracts', child: 'pricingStrategy' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        {
          field: 'abi',
          value: '****Pricing strategy contract ABI:**** \n\n',
          parent: 'contracts',
          child: 'pricingStrategy'
        },
        {
          field: 'abiConstructor',
          value: '****Pricing strategy contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'pricingStrategy'
        }
      ],
      sol: {
        field: 'src',
        value: '****Pricing strategy contract source:**** \n\n',
        parent: 'contracts',
        child: 'pricingStrategy'
      }

    },
    crowdsale: {
      name: 'MintedTokenCappedCrowdsaleExt',
      txt: [
        { value: 'Crowdsale contract name: ', parent: 'none', fileValue: 'MintedTokenCappedCrowdsaleExt' },
        { field: 'addr', value: 'Crowdsale contract address', parent: 'contracts', child: 'crowdsale' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        { field: 'abi', value: '****Crowdsale contract ABI:**** \n\n', parent: 'contracts', child: 'crowdsale' },
        {
          field: 'abiConstructor',
          value: '****Crowdsale contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'crowdsale'
        }
      ],
      sol: { field: 'src', value: '****Crowdsale contract source:**** \n\n', parent: 'contracts', child: 'crowdsale' }

    },
    nullFinalizeAgent: {
      name: 'NullFinalizeAgentExt',
      txt: [
        { value: 'Null finalize agent contract name: ', parent: 'none', fileValue: 'NullFinalizeAgentExt' },
        {
          field: 'addr',
          value: 'Null finalize agent contract address',
          parent: 'contracts',
          child: 'finalizeAgent'
        },
        { value: '*****************************', parent: 'none', fileValue: '' },
        {
          field: 'abi',
          value: '****Null Finalize agent contract ABI:**** \n\n',
          parent: 'contracts',
          child: 'nullFinalizeAgent'
        },
        {
          field: 'abiConstructor',
          value: '****Null Finalize agent contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'finalizeAgent'
        }
      ],
      sol: {
        field: 'src',
        value: '****Null Finalize agent contract source:**** \n\n',
        parent: 'contracts',
        child: 'nullFinalizeAgent'
      }

    },
    finalizeAgent: {
      name: 'ReservedTokensFinalizeAgent',
      txt: [
        { value: 'Finalize agent contract name: ', parent: 'none', fileValue: 'ReservedTokensFinalizeAgent' },
        { field: 'addr', value: 'Finalize agent contract address', parent: 'contracts', child: 'finalizeAgent' },
        { value: '*****************************', parent: 'none', fileValue: '' },
        {
          field: 'abi',
          value: '****Finalize agent contract ABI:**** \n\n',
          parent: 'contracts',
          child: 'finalizeAgent'
        },
        {
          field: 'abiConstructor',
          value: '****Finalize agent contract ABI encoded constructor arguments',
          parent: 'contracts',
          child: 'finalizeAgent'
        }
      ],
      sol: {
        field: 'src',
        value: '****Finalize agent contract source:**** \n\n',
        parent: 'contracts',
        child: 'finalizeAgent'
      }

    }
  }
}

export const DOWNLOAD_NAME = 'icowizard'
export const DOWNLOAD_TYPE = {
  text: 'text/plain',
  blob: 'blob'
}

export const INVESTMENT_OPTIONS = {
  METAMASK: 'metamask',
  QR: 'qr'
}
export const TOAST = {
  TYPE: {
    ERROR: 'error',
    INFO: 'info',
    SUCCESS: 'warning'
  },
  MESSAGE: {
    TRANSACTION_FAILED: 'Transaction has failed, please retry',
    CONTRACT_DOWNLOAD_FAILED: 'Contract Download failed',
    CONTRACT_DOWNLOAD_SUCCESS: 'A file with contracts and metadata downloaded on your computer',
    FINALIZE_FAIL: 'Was not able to finalize Crowdsale. Please be sure that Crowdsale has ended already'
  },
  DEFAULT_OPTIONS: {
    position: 'top right',
    offset: '80px 14',
    time: 10000
  }
}
<|endoftext|>


<commit_before>const request = require('request-promise');
const Discord = require('discord.js');
module.exports = {};
exports = module.exports;
exports.rank = function(message)
{
	var id = message.mentions.users.first() || message.author;
	id = id.id;
	request("http://revive-bot-discord.revive.systems/v0/discord/userinfo/" + id).then(body =>{
		body = JSON.parse(body).catch(message.reply);
		if(body.error)
		{message.reply("The requested user hasnt linked his discord account with thier revive account");return;}
		for(var i=0;i<body.soldiers.length;i++)
		{
			var soldier = body.soldiers[i];
			var game = soldier.game=="stella"?require('./bf2142'):require('./bf2');
			var ranklink = soldier.game=='stella'?'http://files.2142-stats.com/2142/ranks/':'https://battlelog.co/img/ranks/rank_'
			game.getrank(soldier.pid).then(rank => {
			var embed = new Discord.RichEmbed()
			.setTitle(soldier.nickname)
			.setThumbnail((soldier.game=='stella'?ranklink+rank+'.jpg':ranklink+rank+'.png'))
			.addField("Game: ",(soldier.game== "stella" ? "Battlefield 2142" : "Battlefield 2"))
			.addField("Online: ",(soldier.online == 1 ? "yes" : "no"))
			.addField("Last Active: ",soldier.last_active)
			.setURL((soldier.game == "stella" ? "http://bl2142.co/bfhq.php?pid=" : "http://battlelog.co/bfhq.php?pid=")+soldier.pid)
			.setFooter(soldier.time_created)
			.setColor(soldier.game == "stella" ? "#0000FF" : "#ff0000");
			message.channel.sendEmbed(embed);
			});
		}
	});
}
<commit_msg>fix try catch<commit_after>const request = require('request-promise');
const Discord = require('discord.js');
module.exports = {};
exports = module.exports;
exports.rank = function(message)
{
	var id = message.mentions.users.first() || message.author;
	id = id.id;
	request("http://revive-bot-discord.revive.systems/v0/discord/userinfo/" + id).then(body =>{
		try{body = JSON.parse(body)}catch(e){console.log("error: "+body);}
		if(body.error)
		{message.reply("The requested user hasnt linked his discord account with thier revive account");return;}
		for(var i=0;i<body.soldiers.length;i++)
		{
			var soldier = body.soldiers[i];
			var game = soldier.game=="stella"?require('./bf2142'):require('./bf2');
			var ranklink = soldier.game=='stella'?'http://files.2142-stats.com/2142/ranks/':'https://battlelog.co/img/ranks/rank_'
			game.getrank(soldier.pid).then(rank => {
			var embed = new Discord.RichEmbed()
			.setTitle(soldier.nickname)
			.setThumbnail((soldier.game=='stella'?ranklink+rank+'.jpg':ranklink+rank+'.png'))
			.addField("Game: ",(soldier.game== "stella" ? "Battlefield 2142" : "Battlefield 2"))
			.addField("Online: ",(soldier.online == 1 ? "yes" : "no"))
			.addField("Last Active: ",soldier.last_active)
			.setURL((soldier.game == "stella" ? "http://bl2142.co/bfhq.php?pid=" : "http://battlelog.co/bfhq.php?pid=")+soldier.pid)
			.setFooter(soldier.time_created)
			.setColor(soldier.game == "stella" ? "#0000FF" : "#ff0000");
			message.channel.sendEmbed(embed);
			});
		}
	});
}
<|endoftext|>


<commit_before>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Finds a given variable by searching through the data and attrs
//------------------------------------------------------------------------------
d3plus.variable.value = function(vars,id,variable,id_var,agg) {

  if (!id_var) {
    if (variable && typeof variable == "object") {
      if (variable[vars.id.key]) {
        var id_var = vars.id.key
      }
      else {
        var id_var = Object.keys(variable)[0]
      }
      variable = variable[id_var]
    }
    else {
      var id_var = vars.id.key
    }
  }

  if (variable && typeof variable == "function") {
    return variable(id)
  }

  function filter_array(arr) {
    return arr.filter(function(d){
      return d[id_var] == id
    })[0]
  }

  var value_array = []
  function check_children(obj) {
    if (obj.children) {
      obj.children.forEach(function(c){
        check_children(c)
      })
    }
    else if (obj[variable]) {
      value_array.push(obj[variable])
    }
  }

  if (typeof id == "object" && typeof id[variable] != "undefined") {
    return id[variable]
  }
  else if (typeof id == "object" && id.children) {

    if (!agg) {
      var agg = "sum"
      if (typeof vars.aggs.value == "string") {
        agg = vars.aggs.value
      }
      else if (vars.aggs.value[variable]) {
        agg = vars.aggs.value[variable]
      }
    }
    check_children(id)
    if (value_array.length) {
      if (typeof agg == "string") {
        return d3[agg](value_array)
      }
      else if (typeof agg == "function") {
        return agg(value_array)
      }
    }

    var dat = id
    id = dat[id_var]

  }
  else {

    if (typeof id == "object") {
      var dat = id
      id = id[id_var]
    }

    if (vars.data.app instanceof Array) {
      var dat = filter_array(vars.data.app)
    }
    if (!dat) {
      var dat = filter_array(vars.data.value)
    }

    if (dat && typeof dat[variable] != "undefined") return dat[variable]
  }

  if (vars.attrs.value instanceof Array) {
    var attr = filter_array(vars.attrs.value)
  }
  else if (vars.attrs.value[id_var]) {
    if (vars.attrs.value[id_var] instanceof Array) {
      var attr = filter_array(vars.attrs.value[id_var])
    }
    else {
      var attr = vars.attrs.value[id_var][id]
    }
  }
  else {
    var attr = vars.attrs.value[id]
  }

  if (attr && typeof attr[variable] != "undefined") return attr[variable]

  return null

}

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Finds an object's color and returns random if it cannot be found
//------------------------------------------------------------------------------
d3plus.variable.color = function(vars,id,level) {

  function get_random(c) {
    if (typeof c == "object") {
      c = c[vars.id.key]
    }
    return d3plus.color.random(c)
  }

  function validate_color(c) {
    if (typeof c == "string" && c.indexOf("#") == 0 && [4,7].indexOf(c.length) >= 0) return true
    else return false
  }

  if (!vars.color.key) {
    return get_random(id);
  }
  else {

    var color = d3plus.variable.value(vars,id,vars.color.key,level)

    if (!color) {
      if (typeof vars.color.scale == "function") {
        return vars.style.color.missing
      }
      return get_random(id)
    }
    else if (!vars.color.scale) {
      var true_color = validate_color(color)
      return true_color ? color : get_random(color)
    }
    else {
      return vars.color.scale(color)
    }

  }
}

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Get array of available text values
//------------------------------------------------------------------------------
d3plus.variable.text = function(vars,obj,depth) {

  if (typeof depth != "number") var depth = vars.depth.value

  if (vars.text.array && typeof vars.text.array == "object") {
    if (vars.text.array[vars.id.nesting[depth]]) {
      var text_keys = vars.text.array[vars.id.nesting[depth]]
    }
    else {
      var text_keys = vars.text.array[Object.keys(vars.text.array)[0]]
    }
  }
  else {
    var text_keys = []
    if (vars.text.key) text_keys.push(vars.text.key)
    text_keys.push(vars.id.nesting[depth])
  }
  if (typeof text_keys == "string") {
    text_keys = [text_keys]
  }

  var names = []
  text_keys.forEach(function(t){
    var name = d3plus.variable.value(vars,obj,t,vars.id.nesting[depth])
    if (name) names.push(vars.format(name))
  })

  return names

}
<commit_msg>removed unnecessary filter of entire dataset (wtf was that!?)<commit_after>//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Finds a given variable by searching through the data and attrs
//------------------------------------------------------------------------------
d3plus.variable.value = function(vars,id,variable,id_var,agg) {

  if (!id_var) {
    if (variable && typeof variable == "object") {
      if (variable[vars.id.key]) {
        var id_var = vars.id.key
      }
      else {
        var id_var = Object.keys(variable)[0]
      }
      variable = variable[id_var]
    }
    else {
      var id_var = vars.id.key
    }
  }

  if (variable && typeof variable == "function") {
    return variable(id)
  }

  function filter_array(arr) {
    return arr.filter(function(d){
      return d[id_var] == id
    })[0]
  }

  var value_array = []
  function check_children(obj) {
    if (obj.children) {
      obj.children.forEach(function(c){
        check_children(c)
      })
    }
    else if (obj[variable]) {
      value_array.push(obj[variable])
    }
  }

  if (typeof id == "object" && typeof id[variable] != "undefined") {
    return id[variable]
  }
  else if (typeof id == "object" && id.children) {

    if (!agg) {
      var agg = "sum"
      if (typeof vars.aggs.value == "string") {
        agg = vars.aggs.value
      }
      else if (vars.aggs.value[variable]) {
        agg = vars.aggs.value[variable]
      }
    }
    check_children(id)
    if (value_array.length) {
      if (typeof agg == "string") {
        return d3[agg](value_array)
      }
      else if (typeof agg == "function") {
        return agg(value_array)
      }
    }

    var dat = id
    id = dat[id_var]

  }
  else {

    if (typeof id == "object") {
      var dat = id
      id = id[id_var]
    }

    if (vars.data.app instanceof Array) {
      var dat = filter_array(vars.data.app)
    }

    if (dat && typeof dat[variable] != "undefined") return dat[variable]
  }

  if (vars.attrs.value instanceof Array) {
    var attr = filter_array(vars.attrs.value)
  }
  else if (vars.attrs.value[id_var]) {
    if (vars.attrs.value[id_var] instanceof Array) {
      var attr = filter_array(vars.attrs.value[id_var])
    }
    else {
      var attr = vars.attrs.value[id_var][id]
    }
  }
  else {
    var attr = vars.attrs.value[id]
  }

  if (attr && typeof attr[variable] != "undefined") return attr[variable]

  return null

}

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Finds an object's color and returns random if it cannot be found
//------------------------------------------------------------------------------
d3plus.variable.color = function(vars,id,level) {

  function get_random(c) {
    if (typeof c == "object") {
      c = c[vars.id.key]
    }
    return d3plus.color.random(c)
  }

  function validate_color(c) {
    if (typeof c == "string" && c.indexOf("#") == 0 && [4,7].indexOf(c.length) >= 0) return true
    else return false
  }

  if (!vars.color.key) {
    return get_random(id);
  }
  else {

    var color = d3plus.variable.value(vars,id,vars.color.key,level)

    if (!color) {
      if (typeof vars.color.scale == "function") {
        return vars.style.color.missing
      }
      return get_random(id)
    }
    else if (!vars.color.scale) {
      var true_color = validate_color(color)
      return true_color ? color : get_random(color)
    }
    else {
      return vars.color.scale(color)
    }

  }
}

//^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// Get array of available text values
//------------------------------------------------------------------------------
d3plus.variable.text = function(vars,obj,depth) {

  if (typeof depth != "number") var depth = vars.depth.value

  if (vars.text.array && typeof vars.text.array == "object") {
    if (vars.text.array[vars.id.nesting[depth]]) {
      var text_keys = vars.text.array[vars.id.nesting[depth]]
    }
    else {
      var text_keys = vars.text.array[Object.keys(vars.text.array)[0]]
    }
  }
  else {
    var text_keys = []
    if (vars.text.key) text_keys.push(vars.text.key)
    text_keys.push(vars.id.nesting[depth])
  }
  if (typeof text_keys == "string") {
    text_keys = [text_keys]
  }

  var names = []
  text_keys.forEach(function(t){
    var name = d3plus.variable.value(vars,obj,t,vars.id.nesting[depth])
    if (name) names.push(vars.format(name))
  })

  return names

}
<|endoftext|>


<commit_before>const HANDLERS_PROPERTY = '__v-click-outside'
const HAS_WINDOWS = typeof window !== 'undefined'
const HAS_NAVIGATOR = typeof navigator !== 'undefined'
const IS_TOUCH =
  HAS_WINDOWS &&
  ('ontouchstart' in window ||
    (HAS_NAVIGATOR && navigator.msMaxTouchPoints > 0))
const EVENTS = IS_TOUCH ? ['touchstart'] : ['click']

function processDirectiveArguments(bindingValue) {
  const isFunction = typeof bindingValue === 'function'
  if (!isFunction && typeof bindingValue !== 'object') {
    throw new Error(
      'v-click-outside: Binding value must be a function or an object',
    )
  }

  return {
    handler: isFunction ? bindingValue : bindingValue.handler,
    middleware: bindingValue.middleware || ((item) => item),
    events: bindingValue.events || EVENTS,
    isActive: !(bindingValue.isActive === false),
    detectIframe: !(bindingValue.detectIframe === false),
    capture: !!bindingValue.capture,
  }
}

function execHandler({ event, handler, middleware }) {
  if (middleware(event)) {
    handler(event)
  }
}

function onFauxIframeClick({ el, event, handler, middleware }) {
  // Note: on firefox clicking on iframe triggers blur, but only on
  //       next event loop it becomes document.activeElement
  // https://stackoverflow.com/q/2381336#comment61192398_23231136
  setTimeout(() => {
    const { activeElement } = document
    if (
      activeElement &&
      activeElement.tagName === 'IFRAME' &&
      !el.contains(activeElement)
    ) {
      execHandler({ event, handler, middleware })
    }
  }, 0)
}

function onEvent({ el, event, handler, middleware }) {
  // Note: composedPath is not supported on IE and Edge, more information here:
  //       https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath
  //       In the meanwhile, we are using el.contains for those browsers, not
  //       the ideal solution, but using IE or EDGE is not ideal either.
  const path = (event.composedPath && event.composedPath()) || event.path
  const isClickOutside = path
    ? path.indexOf(el) < 0
    : !el.contains(event.target)

  if (!isClickOutside) {
    return
  }

  execHandler({ event, handler, middleware })
}

function bind(el, { value }) {
  const {
    events,
    handler,
    middleware,
    isActive,
    detectIframe,
    capture,
  } = processDirectiveArguments(value)
  if (!isActive) {
    return
  }

  el[HANDLERS_PROPERTY] = events.map((eventName) => ({
    event: eventName,
    srcTarget: document.documentElement,
    handler: (event) => onEvent({ el, event, handler, middleware }),
    capture,
  }))

  if (detectIframe) {
    const detectIframeEvent = {
      event: 'blur',
      srcTarget: window,
      handler: (event) => onFauxIframeClick({ el, event, handler, middleware }),
      capture,
    }

    el[HANDLERS_PROPERTY] = [...el[HANDLERS_PROPERTY], detectIframeEvent]
  }

  el[HANDLERS_PROPERTY].forEach(({ event, srcTarget, handler }) =>
    setTimeout(() => {
      // Note: More info about this implementation can be found here:
      //       https://github.com/ndelvalle/v-click-outside/issues/137
      if (!el[HANDLERS_PROPERTY]) {
        return
      }
      srcTarget.addEventListener(event, handler, capture)
    }, 0),
  )
}

function unbind(el) {
  const handlers = el[HANDLERS_PROPERTY] || []
  handlers.forEach(({ event, srcTarget, handler, capture }) =>
    srcTarget.removeEventListener(event, handler, capture),
  )
  delete el[HANDLERS_PROPERTY]
}

function update(el, { value, oldValue }) {
  if (JSON.stringify(value) === JSON.stringify(oldValue)) {
    return
  }
  unbind(el)
  bind(el, { value })
}

const directive = {
  bind,
  update,
  unbind,
}

export default HAS_WINDOWS ? directive : {}
<commit_msg>fix: make directive vue3 compatible<commit_after>import { directiveHooks } from './utils'

const HANDLERS_PROPERTY = '__v-click-outside'
const HAS_WINDOWS = typeof window !== 'undefined'
const HAS_NAVIGATOR = typeof navigator !== 'undefined'
const IS_TOUCH =
  HAS_WINDOWS &&
  ('ontouchstart' in window ||
    (HAS_NAVIGATOR && navigator.msMaxTouchPoints > 0))
const EVENTS = IS_TOUCH ? ['touchstart'] : ['click']

function processDirectiveArguments(bindingValue) {
  const isFunction = typeof bindingValue === 'function'
  if (!isFunction && typeof bindingValue !== 'object') {
    throw new Error(
      'v-click-outside: Binding value must be a function or an object',
    )
  }

  return {
    handler: isFunction ? bindingValue : bindingValue.handler,
    middleware: bindingValue.middleware || ((item) => item),
    events: bindingValue.events || EVENTS,
    isActive: !(bindingValue.isActive === false),
    detectIframe: !(bindingValue.detectIframe === false),
    capture: !!bindingValue.capture,
  }
}

function execHandler({ event, handler, middleware }) {
  if (middleware(event)) {
    handler(event)
  }
}

function onFauxIframeClick({ el, event, handler, middleware }) {
  // Note: on firefox clicking on iframe triggers blur, but only on
  //       next event loop it becomes document.activeElement
  // https://stackoverflow.com/q/2381336#comment61192398_23231136
  setTimeout(() => {
    const { activeElement } = document
    if (
      activeElement &&
      activeElement.tagName === 'IFRAME' &&
      !el.contains(activeElement)
    ) {
      execHandler({ event, handler, middleware })
    }
  }, 0)
}

function onEvent({ el, event, handler, middleware }) {
  // Note: composedPath is not supported on IE and Edge, more information here:
  //       https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath
  //       In the meanwhile, we are using el.contains for those browsers, not
  //       the ideal solution, but using IE or EDGE is not ideal either.
  const path = (event.composedPath && event.composedPath()) || event.path
  const isClickOutside = path
    ? path.indexOf(el) < 0
    : !el.contains(event.target)

  if (!isClickOutside) {
    return
  }

  execHandler({ event, handler, middleware })
}

function bind(el, { value }) {
  const {
    events,
    handler,
    middleware,
    isActive,
    detectIframe,
    capture,
  } = processDirectiveArguments(value)
  if (!isActive) {
    return
  }

  el[HANDLERS_PROPERTY] = events.map((eventName) => ({
    event: eventName,
    srcTarget: document.documentElement,
    handler: (event) => onEvent({ el, event, handler, middleware }),
    capture,
  }))

  if (detectIframe) {
    const detectIframeEvent = {
      event: 'blur',
      srcTarget: window,
      handler: (event) => onFauxIframeClick({ el, event, handler, middleware }),
      capture,
    }

    el[HANDLERS_PROPERTY] = [...el[HANDLERS_PROPERTY], detectIframeEvent]
  }

  el[HANDLERS_PROPERTY].forEach(({ event, srcTarget, handler }) =>
    setTimeout(() => {
      // Note: More info about this implementation can be found here:
      //       https://github.com/ndelvalle/v-click-outside/issues/137
      if (!el[HANDLERS_PROPERTY]) {
        return
      }
      srcTarget.addEventListener(event, handler, capture)
    }, 0),
  )
}

function unbind(el) {
  const handlers = el[HANDLERS_PROPERTY] || []
  handlers.forEach(({ event, srcTarget, handler, capture }) =>
    srcTarget.removeEventListener(event, handler, capture),
  )
  delete el[HANDLERS_PROPERTY]
}

function update(el, { value, oldValue }) {
  if (JSON.stringify(value) === JSON.stringify(oldValue)) {
    return
  }
  unbind(el)
  bind(el, { value })
}

const directive = {
  [directiveHooks.beforeMount]: bind,
  [directiveHooks.updated]: update,
  [directiveHooks.unmounted]: unbind,
}

export default HAS_WINDOWS ? directive : {}
<|endoftext|>


<commit_before>function attack(aChara) {
	let tDamagedCharas=new Array()//ダメージを受けたキャラ
	let tLogTag="";
	//カードの確認
	var tCard=mCard[aChara.x+aChara.y*8];

	//デッキの確認
	var tSkill;
	if(tCard[1]=="joker"){
		tSkill=aChara.deck[13];
	}
	else if(tCard[1]=="suka"){
		tSkill=aChara.deck[14];
	}
	else{
		tSkill=aChara.deck[tCard[0]];
	}

	//技取り出し
	tSkill=mSkillList[tSkill];

	if(aChara.MP<tSkill.MAGIC){
		//delay計算
		var tDelay = Math.floor(100000/aChara.SPD);//初期値
		// tDelay+=Math.floor(tSkill.DELAY/aChara.SPD)//追加delay

		aChara.addDelay(tDelay);
		// mDelayList=sortDelay(mDelayList);
		mDelayList = initDelay(mTrueTeam,mFalseTeam);//mDelayListのdelay値が変わってなかったため
		displayDelay();
		// return;
	}
	else{
	aChara.MP -= tSkill.MAGIC;

	//補助効果適用(B)
	Support_B_M(tSkill.SUPPORT_Be_Myself,aChara);

	//攻撃
	let tRange=getAttackRange(tSkill.RANGE);
	if(aChara.team=="T"||tSkill.F_ATTACK==true){
		for(var i=0;i<mFalseTeam.length;i++){
			for(var j=0;j<tRange.length;j++){
				if(mFalseTeam[i].x==tRange[j][0]&&mFalseTeam[i].y==tRange[j][1]){
					//サポート効果敵　前
					Support_B_E(tSkill.SUPPORT_Be_Enemy,mFalseTeam[i]);
					//ダメージ計算
					var tDamage = calcDamage(aChara.ATK,mFalseTeam[i].DEF,tSkill.POWER);

					if(tCard[1]==aChara.TYPE){
						tDamage = Math.floor(tDamage*1.5);
					}

					mFalseTeam[i].HP-=tDamage;
					damageLog(mFalseTeam[i],tDamage);
					tDamagedCharas.push(mFalseTeam[i]);
					if(mFalseTeam[i].HP<=0){
						mFalseTeam[i].HP=0;
						winner("T");
					}
					if(mFalseTeam[i].HP>mFalseTeam[i].originalHP){//威力がマイナスだと回復する
						mFalseTeam[i].HP = mFalseTeam[i].originalHP;
					}

					//サポート効果敵　後
					Support_A_E(tSkill.SUPPORT_Af_Enemy,mFalseTeam[i]);
					displayStatus();
				}
			}
		}
	}
	if(aChara.team=="F"||tSkill.F_ATTACK==true){
		for(var i=0;i<mTrueTeam.length;i++){
			for(var j=0;j<tRange.length;j++){
				if(mTrueTeam[i].x==tRange[j][0]&&mTrueTeam[i].y==tRange[j][1]){
					//サポート効果敵　前
					Support_B_E(tSkill.SUPPORT_Be_Enemy,mTrueTeam[i]);
					//ダメージ計算
					var tDamage = calcDamage(aChara.ATK,mTrueTeam[i].DEF,tSkill.POWER);

					if(tCard[1]==aChara.TYPE){
						tDamage = Math.floor(tDamage*1.5);
					}

					mTrueTeam[i].HP-=tDamage;
					damageLog(mTrueTeam[i],tDamage);
					tDamagedCharas.push(mTrueTeam[i]);
					if(mTrueTeam[i].HP<=0){
						mTrueTeam[i].HP=0;
						winner("F");
					}
					if(mTrueTeam[i].HP>mTrueTeam[i].originalHP){//威力がマイナスだと回復する
						mTrueTeam[i].HP = mTrueTeam[i].originalHP;
					}
					//サポート効果敵　後
					Support_A_E(tSkill.SUPPORT_Af_Enemy,mFalseTeam[i]);
					displayStatus();
				}
			}
		}
	}

	//補助効果適用(A)
	Support_A_M(tSkill.SUPPORT_Af_Myself,aChara);
	Support_O(tSkill.SUPPORT_Otherwise,aChara);

	//delay計算
	var tDelay = Math.floor(100000/aChara.SPD);//初期値
	tDelay+=Math.floor(tSkill.DELAY/aChara.SPD)//追加delay

	aChara.addDelay(tDelay);
	// mDelayList=sortDelay(mDelayList);
	mDelayList = initDelay(mTrueTeam,mFalseTeam);//mDelayListのdelay値が変わってなかったため
	displayDelay();
}
	return new Promise((res,rej)=>{
		attackAnimate(aChara,tDamagedCharas,tSkill.ANIMATION,()=>{res();});
	})
}

function calcDamage(aATK,aDEF,aPOWER){
	var tDamage = Math.floor((aATK+30)*5/(aDEF+30)*aPOWER)

	return tDamage
}
<commit_msg>インデント<commit_after>function attack(aChara) {
	let tDamagedCharas=new Array()//ダメージを受けたキャラ
	let tLogTag="";
	//カードの確認
	var tCard=mCard[aChara.x+aChara.y*8];

	//デッキの確認
	var tSkill;
	if(tCard[1]=="joker"){
		tSkill=aChara.deck[13];
	}
	else if(tCard[1]=="suka"){
		tSkill=aChara.deck[14];
	}
	else{
		tSkill=aChara.deck[tCard[0]];
	}

	//技取り出し
	tSkill=mSkillList[tSkill];

	if(aChara.MP<tSkill.MAGIC){
		//delay計算
		var tDelay = Math.floor(100000/aChara.SPD);//初期値
		// tDelay+=Math.floor(tSkill.DELAY/aChara.SPD)//追加delay

		aChara.addDelay(tDelay);
		// mDelayList=sortDelay(mDelayList);
		mDelayList = initDelay(mTrueTeam,mFalseTeam);//mDelayListのdelay値が変わってなかったため
		displayDelay();
		// return;
	}
	else{

		aChara.MP -= tSkill.MAGIC;

		//補助効果適用(B)
		Support_B_M(tSkill.SUPPORT_Be_Myself,aChara);

		//攻撃
		let tRange=getAttackRange(tSkill.RANGE);
		if(aChara.team=="T"||tSkill.F_ATTACK==true){
			for(var i=0;i<mFalseTeam.length;i++){
				for(var j=0;j<tRange.length;j++){
					if(mFalseTeam[i].x==tRange[j][0]&&mFalseTeam[i].y==tRange[j][1]){
						//サポート効果敵　前
						Support_B_E(tSkill.SUPPORT_Be_Enemy,mFalseTeam[i]);
						//ダメージ計算
						var tDamage = calcDamage(aChara.ATK,mFalseTeam[i].DEF,tSkill.POWER);

						if(tCard[1]==aChara.TYPE){
							tDamage = Math.floor(tDamage*1.5);
						}

						mFalseTeam[i].HP-=tDamage;
						damageLog(mFalseTeam[i],tDamage);
						tDamagedCharas.push(mFalseTeam[i]);
						if(mFalseTeam[i].HP<=0){
							mFalseTeam[i].HP=0;
							winner("T");
						}
						if(mFalseTeam[i].HP>mFalseTeam[i].originalHP){//威力がマイナスだと回復する
							mFalseTeam[i].HP = mFalseTeam[i].originalHP;
						}

						//サポート効果敵　後
						Support_A_E(tSkill.SUPPORT_Af_Enemy,mFalseTeam[i]);
						displayStatus();
					}
				}
			}
		}
		if(aChara.team=="F"||tSkill.F_ATTACK==true){
			for(var i=0;i<mTrueTeam.length;i++){
				for(var j=0;j<tRange.length;j++){
					if(mTrueTeam[i].x==tRange[j][0]&&mTrueTeam[i].y==tRange[j][1]){
						//サポート効果敵　前
						Support_B_E(tSkill.SUPPORT_Be_Enemy,mTrueTeam[i]);
						//ダメージ計算
						var tDamage = calcDamage(aChara.ATK,mTrueTeam[i].DEF,tSkill.POWER);

						if(tCard[1]==aChara.TYPE){
							tDamage = Math.floor(tDamage*1.5);
						}

						mTrueTeam[i].HP-=tDamage;
						damageLog(mTrueTeam[i],tDamage);
						tDamagedCharas.push(mTrueTeam[i]);
						if(mTrueTeam[i].HP<=0){
							mTrueTeam[i].HP=0;
							winner("F");
						}
						if(mTrueTeam[i].HP>mTrueTeam[i].originalHP){//威力がマイナスだと回復する
							mTrueTeam[i].HP = mTrueTeam[i].originalHP;
						}
						//サポート効果敵　後
						Support_A_E(tSkill.SUPPORT_Af_Enemy,mFalseTeam[i]);
						displayStatus();
					}
				}
			}
		}

		//補助効果適用(A)
		Support_A_M(tSkill.SUPPORT_Af_Myself,aChara);
		Support_O(tSkill.SUPPORT_Otherwise,aChara);

		//delay計算
		var tDelay = Math.floor(100000/aChara.SPD);//初期値
		tDelay+=Math.floor(tSkill.DELAY/aChara.SPD)//追加delay

		aChara.addDelay(tDelay);
		// mDelayList=sortDelay(mDelayList);
		mDelayList = initDelay(mTrueTeam,mFalseTeam);//mDelayListのdelay値が変わってなかったため
		displayDelay();
	}
	return new Promise((res,rej)=>{
		attackAnimate(aChara,tDamagedCharas,tSkill.ANIMATION,()=>{res();});
	})
}

function calcDamage(aATK,aDEF,aPOWER){
	var tDamage = Math.floor((aATK+30)*5/(aDEF+30)*aPOWER)

	return tDamage
}
<|endoftext|>


<commit_before>/**
 * Collapsible - jQuery Plugin
 *
 * This plugin enables the management of
 * collapsibles on the page with cookie support.
 *
 * Copyright (c) 2010 John Snyder (snyderplace.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {
	$.fn.collapsible = function(cmd, arg) {
		if (typeof cmd == 'string') {
			return $.fn.collapsible.dispatcher[cmd](this, arg);
		}

		return $.fn.collapsible.dispatcher['_create'](this, cmd);
	};

	$.fn.collapsible.dispatcher = {
		_create : function(obj, arg) {
			createCollapsable(obj, arg);
		},
		toggle: function(obj) {
			toggle(obj, loadOpts(obj));
			return obj;
		},
		collapsed: function(obj) {
			return collapsed(obj, loadOpts(obj));
		},
	};

	function createCollapsable(obj, options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.collapsible.defaults, options);
		// store any opened default values to set cookie later
		var opened = new Array();

		// iterate and reformat each matched element
		obj.each(function() {
			var $this = $(this);
			saveOpts($this, opts);

			//lets bind it to mouseenter
			if (opts.bind == 'mouseenter') {
				$this.bind('mouseenter', function(e) {
					e.preventDefault(); //stop links from firing
					toggle($this, opts); //toggle open/close
				});
			}

			//lets bind it to mouseover
			if (opts.bind == 'mouseover') {
				$this.bind('mouseover',function(e) {
					e.preventDefault(); //stop links from firing
					toggle($this, opts); //toggle open/close
				});
			}

			//lets bind it to click
			if (opts.bind == 'click') {
				$this.bind('click', function(e) {
					e.preventDefault(); //stop links from firing
					toggle($this, opts); //toggle open/close
				});
			}

			//lets bind it to dblclick
			if (opts.bind == 'dblclick') {
				$this.bind('dblclick', function(e) {
					e.preventDefault(); //stop links from firing
					toggle($this, opts); //toggle open/close
				});
			}

			//lets initialize the collapsibles
			//get the id for this element
			id = $this.attr('id');
			//do we use cookies
			if (!useCookies(opts)) { //no just open the defaults
				//is this collapsible in the default open array?
				dOpenIndex = inDefaultOpen(id, opts);
				if (dOpenIndex === false) { //no, close it
					$this.addClass(opts.cssClose); //append the close class
					$this.next().hide();
				} else { //yes open it
					$this.addClass(opts.cssOpen); //append the open class
					$this.next().show();
					opened.push(id);
				}
			} else { //we can use cookies, let do so
				//has a cookie been set, this overrides default open
				if (issetCookie(opts)) {
					cookieIndex = inCookie(id, opts);
					if (cookieIndex === false) {
						$this.addClass(opts.cssClose);//append the close class
						$this.next().hide();
					} else {
						$this.addClass(opts.cssOpen);//append the open class
						$this.next().show();
						opened.push(id);
					}
				} else { //a cookie hasn't been set open defaults, add them to opened array
					dOpenIndex = inDefaultOpen(id, opts);
					if (dOpenIndex === false) {
						$this.addClass(opts.cssClose);//append the close class
						$this.next().hide();
					} else {
						$this.addClass(opts.cssOpen);//append the open class
						$this.next().show();
						opened.push(id);
					}
				}
			}
		});
		//now that the loop is done, lets set the cookie
		if (opened.length > 0 && useCookies(opts)) {
			setCookie(opened.toString(), opts);
		} else {
			setCookie('', opts);
		}
		return obj;
	};
	// Load opts from object
	function loadOpts($this) {
		return $this.data('collapsible-opts');
	}
	// Save opts into object
	function saveOpts($this, opts) {
		return $this.data('collapsible-opts', opts);
	}
	//Returns true if object is opened
	function collapsed($this, opts)
	{
		return $this.hasClass(opts.cssClose);
	}
	//Toggle a collapsible on an event
	function toggle($this, opts)
	{
		// open a closed item
		if (collapsed($this, opts)) {
			$this.removeClass(opts.cssClose).addClass(opts.cssOpen);
			$this.next().slideDown(opts.speed);
			//do cookies if plugin available
			if (useCookies(opts)) {
				// split the cookieOpen string by ","
				id = $this.attr('id');
				appendCookie(id, opts);
			}
			//return false; //skipped this element
		} else {
			//give the proper class to the heading
			$this.addClass(opts.cssClose).removeClass(opts.cssOpen);
			//still here, close an open item
			$this.next().slideUp(opts.speed); //no animation as its a page load initalization
			//return false; //just incase its a link, lets not let it fire off
			//do cookies if plugin available
			if (useCookies(opts)) {
				// split the cookieOpen string by ","
				id = $this.attr('id');
				unsetCookieId(id, opts);
			}
		}
		return false;
	}
	//do we use cookies
	function useCookies(opts)
	{
		//return false if cookie plugin not present or if a cookie name is not provided
		if (!$.cookie || opts.cookieName == '') {
			return false;
		}
		//we can use cookies
		return true;
	}
	//append a collapsible to the cookie
	function appendCookie(value, opts)
	{
		//check if cookie plugin available and cookiename is set
		if (!useCookies(opts)) {
			return false;
		}
		//does a cookie already exist
		if (!issetCookie(opts)) {
			//no lets set one
			setCookie(value, opts);
			return true;
		}
		//cookie already exists, is this collapsible already set?
		if (inCookie(value, opts)) { //yes, quit here
			return true;
		}
		//still here, we have a cookie and need to append our collapsible
		//get the cookie
		cookie = $.cookie(opts.cookieName);
		//unescape it
		cookie = unescape(cookie);
		//turn it into an array
		cookieArray = cookie.split(',');
		//add it to list
		cookieArray.push(value);
		//save it
		setCookie(cookieArray.toString(), opts);
		return true;
	}
	//unset a collapsible from the cookie
	function unsetCookieId(value, opts)
	{
		//check if cookie plugin available and cookiename is set
		if (!useCookies(opts)) {
			return false;
		}
		//if its not there we don't need to remove from it
		if (!issetCookie(opts)) { //quit here, don't have a cookie
			return true;
		}
		//we have a cookie, is this collapsible in it
		cookieIndex = inCookie(value, opts);
		if (cookieIndex === false) { //not in the cookie quit here
			return true;
		}
		//still here get the cookie
		cookie = $.cookie(opts.cookieName);
		//unescape it
		cookie = unescape(cookie);
		//turn it into an array
		cookieArray = cookie.split(',');
		//lets pop it out of the array
		cookieArray.splice(cookieIndex, 1);
		setCookie(cookieArray.toString(), opts);
	}
	//set a cookie
	function setCookie(value, opts)
	{
		//can use the cookie plugin
		if (!useCookies(opts)) { //no, quit here
			return false;
		}
		//cookie plugin is available, lets set the cookie
		$.cookie(opts.cookieName, value, opts.cookieOptions);
	}
	//check if a collapsible is in the cookie
	function inCookie(value, opts)
	{
		//can use the cookie plugin
		if (!useCookies(opts)) {
			return false;
		}
		//if its not there we don't need to remove from it
		if (!issetCookie(opts)) { //quit here, don't have a cookie
			return false;
		}
		//unescape it
		cookie = unescape($.cookie(opts.cookieName));
		//turn it into an array
		cookieArray = cookie.split(',');
		//get the index of the collapsible if in the cookie array
		cookieIndex = $.inArray(value, cookieArray);
		//is this value in the cookie arrray
		if (cookieIndex == -1) { //no, quit here
			return false;
		}
		//yes, return the index
		return cookieIndex;
	}
	//check if a cookie is set
	function issetCookie(opts)
	{
		//can we use the cookie plugin
		if (!useCookies(opts)) { //no, quit here
			return false;
		}
		//is the cookie set
		if ($.cookie(opts.cookieName) == null) { //no, quit here
			return false;
		}
		//the cookie is set and we can use the cookie plugin
		return true;
	}
	//check if a collapsible is in the list of collapsibles to be opened by default
	function inDefaultOpen(id, opts)
	{
		//get the array of open collapsibles
		defaultOpen = getDefaultOpen(opts);
		//is it in the default open array
		index = $.inArray(id, defaultOpen);
		if (index == -1) { //nope, quit here
			return false;
		}
		//it is a default open item, return its index
		return index;
	}
	//get the default open collapsibles and return array
	function getDefaultOpen(opts)
	{
		//initialize an empty array
		defaultOpen = new Array();
		//if there is a list, lets split it into an array
		if (opts.defaultOpen != '') {
			defaultOpen = opts.defaultOpen.split(',');
		}
		//return the default open array
		return defaultOpen;
	}

	// settings
	$.fn.collapsible.defaults = {
		cssClose: 'collapse-close', //class you want to assign to a closed collapsible header
		cssOpen: 'collapse-open', //class you want to assign an opened collapsible header
		cookieName: 'collapsible', //name of the cookie you want to set for this collapsible
		cookieOptions: { //cookie options, see cookie plugin for details
			path: '/',
			expires: 7,
			domain: '',
			secure: ''
		},
		defaultOpen: '', //comma seperated list of header ids that you want opened by default
		speed: 300, //speed of the slide effect
		bind: 'click' //event to bind to, supports click, dblclick, mouseover and mouseenter
	};
})(jQuery);<commit_msg>Implemented 'open' and 'close' commands<commit_after>/**
 * Collapsible - jQuery Plugin
 *
 * This plugin enables the management of
 * collapsibles on the page with cookie support.
 *
 * Copyright (c) 2010 John Snyder (snyderplace.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
(function($) {
	$.fn.collapsible = function(cmd, arg) {
		if (typeof cmd == 'string') {
			return $.fn.collapsible.dispatcher[cmd](this, arg);
		}

		return $.fn.collapsible.dispatcher['_create'](this, cmd);
	};

	$.fn.collapsible.dispatcher = {
		_create : function(obj, arg) {
			createCollapsable(obj, arg);
		},
		toggle: function(obj) {
			toggle(obj, loadOpts(obj));
			return obj;
		},
		open: function(obj) {
			open(obj, loadOpts(obj));
			return obj;
		},
		close: function(obj) {
			close(obj, loadOpts(obj));
			return obj;
		},
		collapsed: function(obj) {
			return collapsed(obj, loadOpts(obj));
		},
	};

	function createCollapsable(obj, options) {
		// build main options before element iteration
		var opts = $.extend({}, $.fn.collapsible.defaults, options);
		// store any opened default values to set cookie later
		var opened = new Array();

		// iterate and reformat each matched element
		obj.each(function() {
			var $this = $(this);
			saveOpts($this, opts);

			//lets bind it to mouseenter
			if (opts.bind == 'mouseenter') {
				$this.bind('mouseenter', function(e) {
					e.preventDefault(); //stop links from firing
					toggle($this, opts); //toggle open/close
				});
			}

			//lets bind it to mouseover
			if (opts.bind == 'mouseover') {
				$this.bind('mouseover',function(e) {
					e.preventDefault(); //stop links from firing
					toggle($this, opts); //toggle open/close
				});
			}

			//lets bind it to click
			if (opts.bind == 'click') {
				$this.bind('click', function(e) {
					e.preventDefault(); //stop links from firing
					toggle($this, opts); //toggle open/close
				});
			}

			//lets bind it to dblclick
			if (opts.bind == 'dblclick') {
				$this.bind('dblclick', function(e) {
					e.preventDefault(); //stop links from firing
					toggle($this, opts); //toggle open/close
				});
			}

			//lets initialize the collapsibles
			//get the id for this element
			id = $this.attr('id');
			//do we use cookies
			if (!useCookies(opts)) { //no just open the defaults
				//is this collapsible in the default open array?
				dOpenIndex = inDefaultOpen(id, opts);
				if (dOpenIndex === false) { //no, close it
					$this.addClass(opts.cssClose); //append the close class
					$this.next().hide();
				} else { //yes open it
					$this.addClass(opts.cssOpen); //append the open class
					$this.next().show();
					opened.push(id);
				}
			} else { //we can use cookies, let do so
				//has a cookie been set, this overrides default open
				if (issetCookie(opts)) {
					cookieIndex = inCookie(id, opts);
					if (cookieIndex === false) {
						$this.addClass(opts.cssClose);//append the close class
						$this.next().hide();
					} else {
						$this.addClass(opts.cssOpen);//append the open class
						$this.next().show();
						opened.push(id);
					}
				} else { //a cookie hasn't been set open defaults, add them to opened array
					dOpenIndex = inDefaultOpen(id, opts);
					if (dOpenIndex === false) {
						$this.addClass(opts.cssClose);//append the close class
						$this.next().hide();
					} else {
						$this.addClass(opts.cssOpen);//append the open class
						$this.next().show();
						opened.push(id);
					}
				}
			}
		});
		//now that the loop is done, lets set the cookie
		if (opened.length > 0 && useCookies(opts)) {
			setCookie(opened.toString(), opts);
		} else {
			setCookie('', opts);
		}
		return obj;
	};
	// Load opts from object
	function loadOpts($this) {
		return $this.data('collapsible-opts');
	}
	// Save opts into object
	function saveOpts($this, opts) {
		return $this.data('collapsible-opts', opts);
	}
	//Returns true if object is opened
	function collapsed($this, opts)
	{
		return $this.hasClass(opts.cssClose);
	}
	// Hides a collapsible
	function close($this, opts) {
		//give the proper class to the heading
		$this.addClass(opts.cssClose).removeClass(opts.cssOpen);
		//still here, close an open item
		$this.next().slideUp(opts.speed); //no animation as its a page load initalization
		//return false; //just incase its a link, lets not let it fire off
		//do cookies if plugin available
		if (useCookies(opts)) {
			// split the cookieOpen string by ","
			id = $this.attr('id');
			unsetCookieId(id, opts);
		}
	}
	// Opens a collapsible
	function open($this, opts) {
		$this.removeClass(opts.cssClose).addClass(opts.cssOpen);
		$this.next().slideDown(opts.speed);
		//do cookies if plugin available
		if (useCookies(opts)) {
			// split the cookieOpen string by ","
			id = $this.attr('id');
			appendCookie(id, opts);
		}
	}
	//Toggle a collapsible on an event
	function toggle($this, opts)
	{
		// open a closed item
		if (collapsed($this, opts)) {
			open($this, opts);
		} else {
			close($this, opts);
		}
		return false;
	}
	//do we use cookies
	function useCookies(opts)
	{
		//return false if cookie plugin not present or if a cookie name is not provided
		if (!$.cookie || opts.cookieName == '') {
			return false;
		}
		//we can use cookies
		return true;
	}
	//append a collapsible to the cookie
	function appendCookie(value, opts)
	{
		//check if cookie plugin available and cookiename is set
		if (!useCookies(opts)) {
			return false;
		}
		//does a cookie already exist
		if (!issetCookie(opts)) {
			//no lets set one
			setCookie(value, opts);
			return true;
		}
		//cookie already exists, is this collapsible already set?
		if (inCookie(value, opts)) { //yes, quit here
			return true;
		}
		//still here, we have a cookie and need to append our collapsible
		//get the cookie
		cookie = $.cookie(opts.cookieName);
		//unescape it
		cookie = unescape(cookie);
		//turn it into an array
		cookieArray = cookie.split(',');
		//add it to list
		cookieArray.push(value);
		//save it
		setCookie(cookieArray.toString(), opts);
		return true;
	}
	//unset a collapsible from the cookie
	function unsetCookieId(value, opts)
	{
		//check if cookie plugin available and cookiename is set
		if (!useCookies(opts)) {
			return false;
		}
		//if its not there we don't need to remove from it
		if (!issetCookie(opts)) { //quit here, don't have a cookie
			return true;
		}
		//we have a cookie, is this collapsible in it
		cookieIndex = inCookie(value, opts);
		if (cookieIndex === false) { //not in the cookie quit here
			return true;
		}
		//still here get the cookie
		cookie = $.cookie(opts.cookieName);
		//unescape it
		cookie = unescape(cookie);
		//turn it into an array
		cookieArray = cookie.split(',');
		//lets pop it out of the array
		cookieArray.splice(cookieIndex, 1);
		setCookie(cookieArray.toString(), opts);
	}
	//set a cookie
	function setCookie(value, opts)
	{
		//can use the cookie plugin
		if (!useCookies(opts)) { //no, quit here
			return false;
		}
		//cookie plugin is available, lets set the cookie
		$.cookie(opts.cookieName, value, opts.cookieOptions);
	}
	//check if a collapsible is in the cookie
	function inCookie(value, opts)
	{
		//can use the cookie plugin
		if (!useCookies(opts)) {
			return false;
		}
		//if its not there we don't need to remove from it
		if (!issetCookie(opts)) { //quit here, don't have a cookie
			return false;
		}
		//unescape it
		cookie = unescape($.cookie(opts.cookieName));
		//turn it into an array
		cookieArray = cookie.split(',');
		//get the index of the collapsible if in the cookie array
		cookieIndex = $.inArray(value, cookieArray);
		//is this value in the cookie arrray
		if (cookieIndex == -1) { //no, quit here
			return false;
		}
		//yes, return the index
		return cookieIndex;
	}
	//check if a cookie is set
	function issetCookie(opts)
	{
		//can we use the cookie plugin
		if (!useCookies(opts)) { //no, quit here
			return false;
		}
		//is the cookie set
		if ($.cookie(opts.cookieName) == null) { //no, quit here
			return false;
		}
		//the cookie is set and we can use the cookie plugin
		return true;
	}
	//check if a collapsible is in the list of collapsibles to be opened by default
	function inDefaultOpen(id, opts)
	{
		//get the array of open collapsibles
		defaultOpen = getDefaultOpen(opts);
		//is it in the default open array
		index = $.inArray(id, defaultOpen);
		if (index == -1) { //nope, quit here
			return false;
		}
		//it is a default open item, return its index
		return index;
	}
	//get the default open collapsibles and return array
	function getDefaultOpen(opts)
	{
		//initialize an empty array
		defaultOpen = new Array();
		//if there is a list, lets split it into an array
		if (opts.defaultOpen != '') {
			defaultOpen = opts.defaultOpen.split(',');
		}
		//return the default open array
		return defaultOpen;
	}

	// settings
	$.fn.collapsible.defaults = {
		cssClose: 'collapse-close', //class you want to assign to a closed collapsible header
		cssOpen: 'collapse-open', //class you want to assign an opened collapsible header
		cookieName: 'collapsible', //name of the cookie you want to set for this collapsible
		cookieOptions: { //cookie options, see cookie plugin for details
			path: '/',
			expires: 7,
			domain: '',
			secure: ''
		},
		defaultOpen: '', //comma seperated list of header ids that you want opened by default
		speed: 300, //speed of the slide effect
		bind: 'click' //event to bind to, supports click, dblclick, mouseover and mouseenter
	};
})(jQuery);<|endoftext|>


<commit_before>/* global describe, expect, it */
'use strict';

(function (self)
{
    function createOutput()
    {
        function appendLengths(char)
        {
            compatibilities.forEach(
                function (compatibility)
                {
                    var content;
                    try
                    {
                        content = JScrewIt.encode(char, false, compatibility).length;
                    }
                    catch (e)
                    {
                        content = 'ERROR';
                    }
                    result += padLeft(content, 8);
                }
            );
        }

        var result = '   ';
        compatibilities.forEach(
            function (compatibility)
            {
                result += padBoth(compatibility, 8);
            }
        );
        result = result.replace(/ +$/, '');
        result += '\n   ' + new Array(compatibilities.length + 1).join(' -------');
        result += '\nNL ';
        appendLengths('\n');
        var MIN = 32, MAX = 127;
        for (var code = MIN; code < MAX; ++code)
        {
            var char = String.fromCharCode(code);
            result += '\n`' + char + '`';
            appendLengths(char);
        }
        result += '\n`©`';
        appendLengths('©');
        result += '\n`♥`';
        appendLengths('♥');
        return result;
    }

    function createOutputNodeJs()
    {
        try
        {
            global.atob =
                function (value)
                {
                    return new Buffer(value + '', 'base64').toString('binary');
                };
            global.btoa =
                function (value)
                {
                    return new Buffer(value + '', 'binary').toString('base64');
                };
            global.self = self;
            return createOutput();
        }
        finally
        {
            delete global.atob;
            delete global.btoa;
            delete global.self;
        }
    }

    function init(env)
    {
        JScrewIt = (env || self).JScrewIt;
        compatibilities = ['DEFAULT'];
        if (!isIE())
        {
            compatibilities.push('NO_IE');
        }
        compatibilities.push('NO_NODE');
    }

    function isIE()
    {
        var navigator = self.navigator;
        var result = navigator && /\b(MSIE|Trident)\b/.test(navigator.userAgent);
        return result;
    }

    function isNodeJs()
    {
        return typeof module !== 'undefined' && !!module.exports;
    }

    function padBoth(str, length)
    {
        str += '';
        var result = padLeft(padRight(str, length + str.length >> 1), length);
        return result;
    }

    function padLeft(str, length)
    {
        str += '';
        var result = new Array(length - str.length + 1).join(' ') + str;
        return result;
    }

    function padRight(str, length)
    {
        str += '';
        var result = str + new Array(length - str.length + 1).join(' ');
        return result;
    }

    function run()
    {
        describe(
            'JScrewIt',
            function()
            {
                compatibilities.forEach(
                    function (compatibility)
                    {
                        if (compatibility !== 'NO_NODE' || !isNodeJs())
                        {
                            describe(
                                'encodes with ' + compatibility + ' compatibility',
                                function ()
                                {
                                    var code;
                                    for (code = 0; code < 128; ++code)
                                    {
                                        test(code, compatibility);
                                    }
                                    for (; code < 0x00010000; code <<= 1)
                                    {
                                        test(code + 33, compatibility);
                                    }
                                }
                            );
                        }
                    }
                );
            }
        );
    }

    function test(code, compatibility)
    {
        var char = String.fromCharCode(code);
        var desc = char === '\x7f' ? '"\\u007f"' : JSON.stringify(char);
        it(
            desc,
            function ()
            {
                var encoding = JScrewIt.encode(char, false, compatibility);
                expect(eval(encoding)).toBe(char);
                expect(encoding).toMatch(/^[!+()[\]]*$/);
                if (compatibility !== 'DEFAULT')
                {
                    expect(encoding.length).not.toBeGreaterThan(JScrewIt.encode(char).length);
                }
            }
        );
    }

    var compatibilities;
    var JScrewIt;

    self.TestSuite =
    {
        createOutput: isNodeJs() ? createOutputNodeJs : createOutput,
        init: init,
        run: run
    };

})(typeof(exports) === 'undefined' ? window : exports);
<commit_msg>Code cleanup in test suite<commit_after>/* global describe, expect, it, navigator */
'use strict';

(function (self)
{
    function createOutput()
    {
        function appendLengths(char)
        {
            compatibilities.forEach(
                function (compatibility)
                {
                    var content;
                    try
                    {
                        content = JScrewIt.encode(char, false, compatibility).length;
                    }
                    catch (e)
                    {
                        content = 'ERROR';
                    }
                    result += padLeft(content, 8);
                }
            );
        }

        var result = '   ';
        var compatibilities = ['DEFAULT'];
        if (!isIE)
        {
            compatibilities.push('NO_IE');
        }
        compatibilities.push('NO_NODE');
        compatibilities.forEach(
            function (compatibility)
            {
                result += padBoth(compatibility, 8);
            }
        );
        result = result.replace(/ +$/, '');
        result += '\n   ' + new Array(compatibilities.length + 1).join(' -------');
        result += '\nNL ';
        appendLengths('\n');
        var MIN = 32, MAX = 127;
        for (var code = MIN; code < MAX; ++code)
        {
            var char = String.fromCharCode(code);
            result += '\n`' + char + '`';
            appendLengths(char);
        }
        result += '\n`©`';
        appendLengths('©');
        result += '\n`♥`';
        appendLengths('♥');
        return result;
    }

    function createOutputNodeJs()
    {
        try
        {
            global.atob =
                function (value)
                {
                    return new Buffer(value + '', 'base64').toString('binary');
                };
            global.btoa =
                function (value)
                {
                    return new Buffer(value + '', 'binary').toString('base64');
                };
            global.self = self;
            return createOutput();
        }
        finally
        {
            delete global.atob;
            delete global.btoa;
            delete global.self;
        }
    }

    function describeTest(compatibility)
    {
        describe(
            'encodes with ' + compatibility + ' compatibility',
            function ()
            {
                var code;
                for (code = 0; code < 128; ++code)
                {
                    test(code, compatibility);
                }
                for (; code < 0x00010000; code <<= 1)
                {
                    test(code + 33, compatibility);
                }
            }
        );
    }

    function init(env)
    {
        JScrewIt = (env || self).JScrewIt;
    }

    function padBoth(str, length)
    {
        str += '';
        var result = padLeft(padRight(str, length + str.length >> 1), length);
        return result;
    }

    function padLeft(str, length)
    {
        str += '';
        var result = new Array(length - str.length + 1).join(' ') + str;
        return result;
    }

    function padRight(str, length)
    {
        str += '';
        var result = str + new Array(length - str.length + 1).join(' ');
        return result;
    }

    function run()
    {
        describe(
            'JScrewIt',
            function()
            {
                describeTest('DEFAULT');
                if (!isIE)
                {
                    describeTest('NO_IE');
                }
                if (!isNodeJs)
                {
                    describeTest('NO_NODE');
                }
            }
        );
    }

    function test(code, compatibility)
    {
        var char = String.fromCharCode(code);
        var desc = char === '\x7f' ? '"\\u007f"' : JSON.stringify(char);
        it(
            desc,
            function ()
            {
                var encoding = JScrewIt.encode(char, false, compatibility);
                expect(eval(encoding)).toBe(char);
                expect(encoding).toMatch(/^[!+()[\]]*$/);
                if (compatibility !== 'DEFAULT')
                {
                    expect(encoding.length).not.toBeGreaterThan(JScrewIt.encode(char).length);
                }
            }
        );
    }

    var isIE = typeof navigator !== 'undefined' && /\b(MSIE|Trident)\b/.test(navigator.userAgent);
    var isNodeJs = typeof module !== 'undefined' && !!module.exports;
    var JScrewIt;

    self.TestSuite =
    {
        createOutput: isNodeJs ? createOutputNodeJs : createOutput,
        init: init,
        run: run
    };

})(typeof(exports) === 'undefined' ? window : exports);
<|endoftext|>


<commit_before>import entries from 'lodash/object/pairs';
import isArray from 'lodash/lang/isArray';
import isObject from 'lodash/lang/isObject';

import fetch from './fetch';
import urlBuilder from '../util/url/builder';
import rename from '../util/function/rename';

const defaultMethod = 'GET';

const preFetchActions = [];

/**
 * Utility function, to build a query string from an object
 *
 * @param {object} obj the object to serialize in a query string
 * @param {string} [prefix=''] the name of the object in the query string
 * @returns {string} the built query string
 */
const buildQueryString = (obj, prefix = '') => {
    let queryString = '';
    if (isObject(obj)) {
        queryString = entries(obj).reduce((acc, [key, value]) => {
            return acc + (acc && acc !== '' && !acc.endsWith('&') ? '&' : '') + buildQueryString(value, prefix !== '' ? prefix + '.' + key : key);
        }, '');
    } else if (prefix && prefix !== '') {
        queryString = prefix + '=' + encodeURIComponent(obj);
    }
    return queryString;
};

/**
 * Utility method that ensure that data passed in the url is properly encoded
 *
 * @param {any} urlData the data to pass in the url
 * @returns {any} the data properly encoded
 */
const urlDataObjectBuilder = (urlData) => {
    let escapedUrlData = {};
    let propData = {};
    for (let prop in urlData) {
        propData = urlData[prop];

        if (isArray(propData)) {
            escapedUrlData[prop] = propData.map(urlDataObjectBuilder);
        } else if (isObject(propData)) {
            escapedUrlData[prop] = urlDataObjectBuilder(propData);
        } else {
            escapedUrlData[prop] = encodeURIComponent(propData);
        }
    }

    return escapedUrlData;
};

/**
 * Register a function to transform data before giving it to. It can be to add headers, etc.
 * The function must take one argument, an object {urlData, data, options} and return an object of the same format.
 * All registered functions are called sequentially on data.
 *
 * @param {function} action a function to transform an object to another object of the same format
 */
const registerPreFetchTransform = (action) => {
    if (!action || typeof (action) !== 'function') {
        throw new Error('A transform action must be a function');
    }
    preFetchActions.push(action);
};

/**
 * Private function, to simplify call to fetch.
 *
 * @param {function} urlFunc the result of the call to urlBuilder.
 * @param {object} urlData data to provide in the url
 * @param {object} bodyData data to provide in the body of the request
 * @param {object} options options for fetch
 * @returns {any} the result of the fetch call
 */
const fetchCall = (urlFunc, urlData, bodyData, options) => (
    fetch(
        urlFunc({
            urlData: urlDataObjectBuilder(urlData || {}),
            data: bodyData
        }), options
    )
);
/* eslint-disable valid-jsdoc */
/**
 * Build api driver method, from url, method and function name.
 *
 * @param {object} { url, method = defaultMethod } object containing url and method
 * @param {string} funcName name to give to the function
 * @returns {function} the built function
 */
const buildApiDriverMethod = ({ url, method = defaultMethod }, funcName) => {
    /* eslint-disable require-jsdoc */
    const toRename = (urlData, data, optionsArg) => {
        const options = optionsArg || {};
        const transformed = preFetchActions.reduce((data, func) => (func(data)), { urlData, data, options });
        return fetchCall(
            urlBuilder(url + (options.queryObj ? '?' + buildQueryString(options.queryObj) : ''), method),
            transformed.urlData,
            transformed.data,
            transformed.options
        );
    }
    rename(toRename, funcName);
    return toRename;
};
/* eslint-enable */

/**
 * Function, to build API driver, so easy call can be made in service.
 *
 * @param {object} urls an object containing for each key an url and a method, like { getById : { url: 'api/test/action/', method: 'GET' } }
 * @returns {object} an object, with properties named as the config given, like a DAO or DAL (myDriver.loadMyObject({id:myId}), or myDriver.saveMyObject(null, toSave)).
 */
const apiDriverBuilder = (urls) => {
    if (!urls || typeof urls !== 'object') {
        throw new Error('The config given to api driver must be an object, like { getById : { url: \'api/test/action/\', method: \'GET\' } }, instead got :' + urls);
    }
    return entries(urls)
        .map(([prop, url]) => {
            if (!url || !url.url || typeof url.url !== 'string') {
                throw new Error(`${prop} does not contain an url for property url, instead got : ` + url);
            }
            return [prop, url];
        })
        .reduce((apiDriver, [prop, url]) => {
            apiDriver[prop] = buildApiDriverMethod(url, prop);
            return apiDriver;
        }, {});
}

export default apiDriverBuilder;
export { registerPreFetchTransform };<commit_msg>Add post-fetch transformation utility<commit_after>import entries from 'lodash/object/pairs';
import isArray from 'lodash/lang/isArray';
import isObject from 'lodash/lang/isObject';

import fetch from './fetch';
import urlBuilder from '../util/url/builder';
import rename from '../util/function/rename';

const defaultMethod = 'GET';

const preFetchActions = [];
const postFetchActions = [];

/**
 * Utility function, to build a query string from an object
 *
 * @param {object} obj the object to serialize in a query string
 * @param {string} [prefix=''] the name of the object in the query string
 * @returns {string} the built query string
 */
const buildQueryString = (obj, prefix = '') => {
    let queryString = '';
    if (isObject(obj)) {
        queryString = entries(obj).reduce((acc, [key, value]) => {
            return acc + (acc && acc !== '' && !acc.endsWith('&') ? '&' : '') + buildQueryString(value, prefix !== '' ? prefix + '.' + key : key);
        }, '');
    } else if (prefix && prefix !== '') {
        queryString = prefix + '=' + encodeURIComponent(obj);
    }
    return queryString;
};

/**
 * Utility method that ensure that data passed in the url is properly encoded
 *
 * @param {any} urlData the data to pass in the url
 * @returns {any} the data properly encoded
 */
const urlDataObjectBuilder = (urlData) => {
    let escapedUrlData = {};
    let propData = {};
    for (let prop in urlData) {
        propData = urlData[prop];

        if (isArray(propData)) {
            escapedUrlData[prop] = propData.map(urlDataObjectBuilder);
        } else if (isObject(propData)) {
            escapedUrlData[prop] = urlDataObjectBuilder(propData);
        } else {
            escapedUrlData[prop] = encodeURIComponent(propData);
        }
    }

    return escapedUrlData;
};

/**
 * Register a function to transform data before giving it to. It can be to add headers, etc.
 * The function must take one argument, an object {urlData, data, options} and return an object of the same format.
 * All registered functions are called sequentially on data.
 *
 * @param {function} action a function to transform an object to another object of the same format
 */
const registerPreFetchTransform = (action) => {
    if (!action || typeof (action) !== 'function') {
        throw new Error('A transform action must be a function');
    }
    preFetchActions.push(action);
};

/**
 * Register a function to transform data after the fetch return.
 * The function must take one argument, an object {data, options} and return an object of the same format.
 * All registered functions are called sequentially on data.
 *
 * @param {function} action a function to transform an object to another object of the same format
 */
const registerPostFetchTransform = (action) => {
    if (!action || typeof (action) !== 'function') {
        throw new Error('A transform action must be a function');
    }
    postFetchActions.push(action);
};

/**
 * Private function, to simplify call to fetch.
 *
 * @param {function} urlFunc the result of the call to urlBuilder.
 * @param {object} urlData data to provide in the url
 * @param {object} bodyData data to provide in the body of the request
 * @param {object} options options for fetch
 * @returns {any} the result of the fetch call
 */
const fetchCall = (urlFunc, urlData, bodyData, options) => (
    fetch(
        urlFunc({
            urlData: urlDataObjectBuilder(urlData || {}),
            data: bodyData
        }), options
    )
);
/* eslint-disable valid-jsdoc */
/**
 * Build api driver method, from url, method and function name.
 *
 * @param {object} { url, method = defaultMethod } object containing url and method
 * @param {string} funcName name to give to the function
 * @returns {function} the built function
 */
const buildApiDriverMethod = ({ url, method = defaultMethod }, funcName) => {
    /* eslint-disable require-jsdoc */
    const toRename = (urlData, data, optionsArg) => {
        const options = optionsArg || {};
        const transformed = preFetchActions.reduce((data, func) => (func(data)), { urlData, data, options });
        return fetchCall(
            urlBuilder(url + (options.queryObj ? '?' + buildQueryString(options.queryObj) : ''), method),
            transformed.urlData,
            transformed.data,
            transformed.options
        ).then((dataResult) => {
            return postFetchActions.reduce((data, func) => {
                return func(data, options);
            }, dataResult)
        });
    }
    rename(toRename, funcName);
    return toRename;
};
/* eslint-enable */

/**
 * Function, to build API driver, so easy call can be made in service.
 *
 * @param {object} urls an object containing for each key an url and a method, like { getById : { url: 'api/test/action/', method: 'GET' } }
 * @returns {object} an object, with properties named as the config given, like a DAO or DAL (myDriver.loadMyObject({id:myId}), or myDriver.saveMyObject(null, toSave)).
 */
const apiDriverBuilder = (urls) => {
    if (!urls || typeof urls !== 'object') {
        throw new Error('The config given to api driver must be an object, like { getById : { url: \'api/test/action/\', method: \'GET\' } }, instead got :' + urls);
    }
    return entries(urls)
        .map(([prop, url]) => {
            if (!url || !url.url || typeof url.url !== 'string') {
                throw new Error(`${prop} does not contain an url for property url, instead got : ` + url);
            }
            return [prop, url];
        })
        .reduce((apiDriver, [prop, url]) => {
            apiDriver[prop] = buildApiDriverMethod(url, prop);
            return apiDriver;
        }, {});
}

export default apiDriverBuilder;
export { registerPreFetchTransform, registerPostFetchTransform };<|endoftext|>


<commit_before>$(function(){

	$.get('/header.html', '', function(data){
		$('#header').html(data);
	}, 'html');

	$.get('/footer.html', '', function(data){
		$('#footer').html(data);
	}, 'html');

	( function() {
		if (window.CHITIKA === undefined) {
		  window.CHITIKA = { 'units' : [] };
		};
		var unit = {
		  'publisher' : "luiges90",
		  'width' : 550,
		  'height' : 90,
		  'type' : "mpu",
		  'sid' : "Left",
		  'color_site_link' : "FFCC00",
		  'color_title' : "FFCC00",
		  'color_border' : "252525",
		  'color_text' : "B6B6B6",
		  'color_bg' : "252525"
		};
		var placement_id = window.CHITIKA.units.length;
		window.CHITIKA.units.push(unit);

		$('#ad-unit').html('

');

		var s = document.createElement('script');
		s.type = 'text/javascript';
		s.src = 'http://scripts.chitika.net/getads.js';
		try {
		  document.getElementsByTagName('head')[0].appendChild(s);
		} catch(e) {
		  $('#ad-unit').html(s.outerHTML);
		}
	})();

	(function(){
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		$.getScript(gaJsHost + 'google-analytics.com/ga.js', function(script, status, jqxhr){
			try {
				var pageTracker = _gat._getTracker("UA-44491635-1");
				pageTracker._trackPageview();
			} catch (e) {
				eval(script);
				var pageTracker = _gat._getTracker("UA-44491635-1");
				pageTracker._trackPageview();
			}
		});
	})();
});

<commit_msg>disqus script<commit_after>$(function(){

	$.get('/header.html', '', function(data){
		$('#header').html(data);
	}, 'html');

	$.get('/footer.html', '', function(data){
		$('#footer').html(data);
	}, 'html');

	( function() {
		if (window.CHITIKA === undefined) {
		  window.CHITIKA = { 'units' : [] };
		};
		var unit = {
		  'publisher' : "luiges90",
		  'width' : 550,
		  'height' : 90,
		  'type' : "mpu",
		  'sid' : "Left",
		  'color_site_link' : "FFCC00",
		  'color_title' : "FFCC00",
		  'color_border' : "252525",
		  'color_text' : "B6B6B6",
		  'color_bg' : "252525"
		};
		var placement_id = window.CHITIKA.units.length;
		window.CHITIKA.units.push(unit);

		$('#ad-unit').html('

');

		var s = document.createElement('script');
		s.type = 'text/javascript';
		s.src = 'http://scripts.chitika.net/getads.js';
		try {
		  document.getElementsByTagName('head')[0].appendChild(s);
		} catch(e) {
		  $('#ad-unit').html(s.outerHTML);
		}
	})();

	(function(){
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
		$.getScript(gaJsHost + 'google-analytics.com/ga.js', function(script, status, jqxhr){
			try {
				var pageTracker = _gat._getTracker("UA-44491635-1");
				pageTracker._trackPageview();
			} catch (e) {
				eval(script);
				var pageTracker = _gat._getTracker("UA-44491635-1");
				pageTracker._trackPageview();
			}
		});
	})();

	(function(){
		/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
		var disqus_shortname = 'luiges90'; // required: replace example with your forum shortname
		var disqus_identifier = $('h1').text().replace(/\W/gi, '-') || 'id';
		var disqus_title = $('h1').text() || '';

		/* * * DON'T EDIT BELOW THIS LINE * * */
		(function() {
			var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
			dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
			(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
		})();
	})();
});

<|endoftext|>


<commit_before>var pitGenChance = 5; // a variable from 0 - 9 that controls chance of a pit being generated
var prevGeneratedPit = false;

function createGround() {

	if ( Math.random() < ( pitGenChance / 10 ) && !prevGeneratedPit ) {
		prevGeneratedPit = true;
		return ;
	}

	prevGeneratedPit = false;

  groundGroup = game.add.group();

  groundGroup.enableBody = true;

  game.physics.arcade.enableBody(groundGroup);

  var groundInstance = groundGroup.create( game.world.width, game.world.height - platformHeight, 'ground');

  groundInstance.body.velocity.x = -150;

  groundInstance.body.immovable = true;

}

function createInitalGround() {

	groundGroup = game.add.group();
  groundGroup.enableBody = true;
  game.physics.arcade.enableBody(groundGroup);

  initialGroundGroup = game.add.group();

  initialGroundGroup.enableBody = true;

  game.physics.arcade.enableBody(initialGroundGroup);

  var initialGroundInstance = initialGroundGroup.create(0, game.world.height - platformHeight, 'initialGround' );

  initialGroundInstance.width = game.world.width;

  initialGroundInstance.body.velocity.x = -150;

  initialGroundInstance.body.immovable = true;

}

function destroyOldGround() {

  //get rid of old ground once it goes offscreen
}<commit_msg>REFIX ground collisions<commit_after>var pitGenChance = 5; // a variable from 0 - 9 that controls chance of a pit being generated
var prevGeneratedPit = false;

function createGround() {

	if ( Math.random() < ( pitGenChance / 10 ) && !prevGeneratedPit ) {
		prevGeneratedPit = true;
		return ;
	}

	prevGeneratedPit = false;

  var groundInstance = groundGroup.create( game.world.width, game.world.height - platformHeight, 'ground');

  groundInstance.body.velocity.x = -150;

  groundInstance.body.immovable = true;

}

function createInitalGround() {

	groundGroup = game.add.group();
  groundGroup.enableBody = true;
  game.physics.arcade.enableBody(groundGroup);

  initialGroundGroup = game.add.group();

  initialGroundGroup.enableBody = true;

  game.physics.arcade.enableBody(initialGroundGroup);

  var initialGroundInstance = initialGroundGroup.create(0, game.world.height - platformHeight, 'initialGround' );

  initialGroundInstance.width = game.world.width;

  initialGroundInstance.body.velocity.x = -150;

  initialGroundInstance.body.immovable = true;

}

function destroyOldGround() {

  //get rid of old ground once it goes offscreen
}<|endoftext|>