Generate a credit card number
547985
def generate(options = {})
      rule   = find_rule(options) || return
      number = generate_from_rule(rule)

      {
        number:  number,
        type:    rule[:type],
        country: rule[:country]
      }
    end
735214
def id_generator(size=15, random_state=None):
    """"""
    chars = list(string.ascii_uppercase + string.digits)
    return ''.join(random_state.choice(chars, size, replace=True))
807589
private function insertData($amount, CreditCard $creditcard, $type, $options = array())
    {
        $month = $this->cc_format($creditcard->month, 'two_digits');
        $year = $this->cc_format($creditcard->year, 'two_digits');

        $this->xml .= <<<XML
 <OrderFormDoc>
 <Mode DataType="String">{$this->payment_mode}</Mode>
 <Consumer>
 <PaymentMech>
 <Type DataType="String">{$this->payment_mech_type}</Type>
 <CreditCard>
 <Number DataType="String">{$creditcard->number}</Number>
 <Expires DataType="ExpirationDate">{$month}/{$year}</Expires>
 <Cvv2Val DataType="String">{$creditcard->verification_value}</Cvv2Val>
 <Cvv2Indicator DataType="String">1</Cvv2Indicator>
 </CreditCard>
 </PaymentMech>
 </Consumer>
XML;
        $this->addTransactionElement($amount, $type, $options);
        $this->addBillingAddress($options);
        $this->addShippingAddress($options);
    }
443962
public function validate($ccNumber, $ccValid, $amount = 1.0, $text = null)
    {
        $service = $this->getService();

        $validMonth     = substr($ccValid, 0, 2);
        $validYear      = substr($ccValid, 3, 4);
        $ccData         = new Model\CreditCardData($ccNumber, $validMonth, $validYear);
        $validateAction = new Request\Action\Validate($service, $ccData, $amount, $text);

        return $validateAction->validate();
    }
1311496
function confirmation() {
    if (isset($_POST['authorizenet_cc_number'])) {
      $confirmation = array('title' => $this->title . ': ' . $this->cc_card_type,
                            'fields' => array(array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_OWNER,
                                                    'field' => $_POST['authorizenet_cc_owner']),
                                              array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_NUMBER,
                                                    'field' => substr($this->cc_card_number, 0, 4) . str_repeat('X', (strlen($this->cc_card_number) - 8)) . substr($this->cc_card_number, -4)),
                                              array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_EXPIRES,
                                                    'field' => strftime('%B, %Y', mktime(0,0,0,$_POST['authorizenet_cc_expires_month'], 1, '20' . $_POST['authorizenet_cc_expires_year'])))));
    } else {
      $confirmation = array(); //array('title' => $this->title);
    }
    return $confirmation;
  }
534335
private function validateNumber(): bool
    {
        $value = $this->value;
        $length = \strlen($value);
        $sum = 0;
        $weight = 2;

        if ($length < 2) {
            $this->setError(self::VALIDATOR_ERROR_CREDIT_CARD_NUMBER_NOT_VALID);
            return false;
        }

        for ($i = $length - 2; $i >= 0; $i--) {
            $digit = $weight * $value[$i];
            $sum += \floor($digit / 10) + $digit % 10;
            $weight = $weight % 2 + 1;
        }

        if ((10 - $sum % 10) % 10 != $value[$length - 1]) {
            $this->setError(self::VALIDATOR_ERROR_CREDIT_CARD_NUMBER_NOT_VALID);
            return false;
        }
        return true;
    }
437565
def generate(num, prompt_default=True):
    """"""
    p = Problem(num)

    problem_text = p.text

    msg = "Generate file for problem %i?" % num
    click.confirm(msg, default=prompt_default, abort=True)

    # Allow skipped problem files to be recreated
    if p.glob:
        filename = str(p.file)
        msg = '"{}" already exists. Overwrite?'.format(filename)
        click.confirm(click.style(msg, fg='red'), abort=True)
    else:
        # Try to keep prefix consistent with existing files
        previous_file = Problem(num - 1).file
        prefix = previous_file.prefix if previous_file else ''
        filename = p.filename(prefix=prefix)

    header = 'Project Euler Problem %i' % num
    divider = '=' * len(header)
    text = '\n'.join([header, divider, '', problem_text])
    content = '\n'.join(['"""', text, '"""'])

    with open(filename, 'w') as f:
        f.write(content + '\n\n\n')

    click.secho('Successfully created "{}".'.format(filename), fg='green')

    # Copy over problem resources if required
    if p.resources:
        p.copy_resources()
178110
public function execute()
    {

        //$cardInternational = $this->getRequest()->getParam('card_international');

        try {
            $creditCard = new CreditCardMethod(
                $this->_objectManager->create('Magento\Directory\Api\CountryInformationAcquirerInterface'),
                $this->_objectManager->create('Magento\Framework\App\Config\ScopeConfigInterface'),
                $this->_objectManager->create('Magento\Framework\Module\ModuleList'),
                $this->loadOrder(),
                $this->_objectManager->create('UOL\PagSeguro\Helper\Library'),
                $data = [
                    'sender_document' => $this->helperData()->formatDocument($this->getRequest()->getParam('sender_document')),
                    'sender_hash' => $this->getRequest()->getParam('sender_hash'),
                    'order_id' => $this->lastRealOrderId(),
                    'installment' => [
                        'quantity' => $this->getRequest()->getParam('installment_quantity'),
                        'amount'   => $this->getRequest()->getParam('installment_amount')
                    ],
                    'token' => $this->getRequest()->getParam('card_token'),
                    'holder' => [
                        'name'       => $this->getRequest()->getParam('holder_name'),
                        'birth_date' => $this->getRequest()->getParam('holder_birthdate'),

                    ]
                ]
            );
            return $this->placeOrder($creditCard);

        } catch (\Exception $exception) {
            $this->changeOrderHistory('pagseguro_cancelada');
            $this->clearSession();
            return $this->whenError($exception->getMessage());
        }
    }
1238571
function DoDirectPayment($cc, $cvv2 = '', $exp, $fname = null, $lname = null, $cc_type, $options = array(), $nvp = array() ) {
    $values = $options;
    $values['ACCT'] = $cc;
    if ($cvv2 != '') $values['CVV2'] = $cvv2;
    $values['FIRSTNAME'] = $fname;
    $values['LASTNAME'] = $lname;
    if (isset($values['NAME'])) unset ($values['NAME']);

    if ($this->_mode == 'payflow') {
      $values['EXPDATE'] = $exp;
      $values['TENDER'] = 'C';
      $values['TRXTYPE'] = $this->_trxtype;
      $values['VERBOSITY'] = 'MEDIUM';
      $values['NOTIFYURL'] = zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true);
    } elseif ($this->_mode == 'nvp') {
      $values = array_merge($values, $nvp);
      if (isset($values['ECI'])) {
        $values['ECI3DS'] = $values['ECI'];
        unset($values['ECI']);
      }
      $values['CREDITCARDTYPE'] = ($cc_type == 'American Express') ? 'Amex' : $cc_type;
      $values['NOTIFYURL'] = urlencode(zen_href_link('ipn_main_handler.php', '', 'SSL',false,false,true));
      if (!isset($values['PAYMENTACTION'])) $values['PAYMENTACTION'] = ($this->_trxtype == 'S' ? 'Sale' : 'Authorization');

      if (isset($values['COUNTRY'])) unset ($values['COUNTRY']);
      if (isset($values['COMMENT1'])) unset ($values['COMMENT1']);
      if (isset($values['COMMENT2'])) unset ($values['COMMENT2']);
      if (isset($values['CUSTREF'])) unset ($values['CUSTREF']);
    }
    $this->values = $values;
    $this->notify('NOTIFY_PAYPAL_DODIRECTPAYMENT');
    ksort($this->values);
    return $this->_request($this->values, 'DoDirectPayment');
  }
348318
private static String toPrettyString(long creditCardNumber) {
	String plain = Long.toString(creditCardNumber);
	// int i = findMatchingRange(creditCardNumber);
	int length = plain.length();

	switch (length) {
	case 12:
	    // 12 pattern 3-3-3-3
	    return plain.substring(0, 3) + ' ' + plain.substring(3, 6) + ' ' + plain.substring(6, 9) + ' ' + plain.substring(9, 12);

	case 13:
	    // 13 pattern 4-3-3-3
	    return plain.substring(0, 4) + ' ' + plain.substring(4, 7) + ' ' + plain.substring(7, 10) + ' ' + plain.substring(10, 13);

	case 14:
	    // 14 pattern 2-4-4-4
	    return plain.substring(0, 2) + ' ' + plain.substring(2, 6) + ' ' + plain.substring(6, 10) + ' ' + plain.substring(10, 14);

	case 15:
	    // 15 pattern 3-4-4-4
	    return plain.substring(0, 3) + ' ' + plain.substring(3, 7) + ' ' + plain.substring(7, 11) + ' ' + plain.substring(11, 15);

	case 16:
	    // 16 pattern 4-4-4-4
	    return plain.substring(0, 4) + ' ' + plain.substring(4, 8) + ' ' + plain.substring(8, 12) + ' ' + plain.substring(12, 16);

	case 17:
	    // 17 pattern 1-4-4-4-4
	    return plain.substring(0, 1) + ' ' + plain.substring(1, 5) + ' ' + plain.substring(5, 9) + ' ' + plain.substring(9, 13) + ' ' + plain.substring(13, 17);

	default:
	    // 0..11, 18+ digits long
	    // plain
	    return plain;
	} // end switch
    }
963111
public function boot()
    {
        \Validator::extend('ccn', function($attribute, $value, $parameters, $validator) {
            return CreditCard::validCreditCard($value)['valid'];
        });

        \Validator::extend('ccd', function($attribute, $value, $parameters, $validator) {
            try {
                $value = explode('/', $value);
                return CreditCard::validDate(strlen($value[1]) == 2 ? (2000+$value[1]) : $value[1], $value[0]);
            } catch(\Exception $e) {
                return false;
            }
        });

        \Validator::extend('cvc', function($attribute, $value, $parameters, $validator) {
            return ctype_digit($value) && (strlen($value) == 3 || strlen($value) == 4);
        });
    }
1279905
function generateData() {
  var totalTransactions = 20;
  var totalAmount = 0;
  var transactions = [];

  // Generate transactions
  for (var i = 0; i < totalTransactions; i++) {
    // Transactions
    var transaction = faker.helpers.createTransaction();
    transaction.date = getDate();
    totalAmount += parseFloat(transaction.amount);

    // Other transactions
    transaction.other = [];
    for (var j = 0; j < totalTransactions; j++) {
      other = faker.helpers.createTransaction();
      other.date = getDate();
      transaction.other.push(other);
    }

    transactions.push(transaction);
  }

  dataView.transactions = transactions.sort(compare);
  dataView.selectedTransaction = transactions[0];
  dataView.totalAmount = toCurrency(totalAmount);
}
1225139
def generate(length):
    """"""
    if not isinstance(length, int) or length < 2:
        raise TypeError('length must be a positive integer greater than 1.')

    # first digit cannot be 0
    digits = [random.randint(1, 9)]

    for i in range(length-2):
        digits.append(random.randint(0, 9))
    digits.append(get_check_digit(''.join(map(str, digits))))

    return ''.join(map(str, digits))
935412
function selection() {
    global $order;

    for ($i=1; $i<13; $i++) {
      $expires_month[] = array('id' => sprintf('%02d', $i), 'text' => strftime('%B - (%m)',mktime(0,0,0,$i,1,2000)));
    }

    $today = getdate();
    for ($i=$today['year']; $i < $today['year']+10; $i++) {
      $expires_year[] = array('id' => strftime('%y',mktime(0,0,0,1,1,$i)), 'text' => strftime('%Y',mktime(0,0,0,1,1,$i)));
    }

    $onFocus = ' onfocus="methodSelect(\'pmt-' . $this->code . '\')"';

    if ($this->gateway_mode == 'offsite') {
      $selection = array('id' => $this->code,
                         'module' => $this->title);
    } else {
      $selection = array('id' => $this->code,
                         'module' => $this->title,
                         'fields' => array(array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_OWNER,
                                                 'field' => zen_draw_input_field('authorizenet_cc_owner', $order->billing['firstname'] . ' ' . $order->billing['lastname'], 'id="'.$this->code.'-cc-owner"' . $onFocus . ' autocomplete="off"'),
                                               'tag' => $this->code.'-cc-owner'),
                                         array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_NUMBER,
                                               'field' => zen_draw_input_field('authorizenet_cc_number', '', 'id="'.$this->code.'-cc-number"' . $onFocus . ' autocomplete="off"'),
                                               'tag' => $this->code.'-cc-number'),
                                         array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CREDIT_CARD_EXPIRES,
                                               'field' => zen_draw_pull_down_menu('authorizenet_cc_expires_month', $expires_month, strftime('%m'), 'id="'.$this->code.'-cc-expires-month"' . $onFocus) . '&nbsp;' . zen_draw_pull_down_menu('authorizenet_cc_expires_year', $expires_year, '', 'id="'.$this->code.'-cc-expires-year"' . $onFocus),
                                               'tag' => $this->code.'-cc-expires-month')));
      if (MODULE_PAYMENT_AUTHORIZENET_USE_CVV == 'True') {
        $selection['fields'][] = array('title' => MODULE_PAYMENT_AUTHORIZENET_TEXT_CVV,
                                       'field' => zen_draw_input_field('authorizenet_cc_cvv', '', 'size="4" maxlength="4"' . ' id="'.$this->code.'-cc-cvv"' . $onFocus . ' autocomplete="off"') . ' ' . '<a href="javascript:popupWindow(\'' . zen_href_link(FILENAME_POPUP_CVV_HELP) . '\')">' . MODULE_PAYMENT_AUTHORIZENET_TEXT_POPUP_CVV_LINK . '</a>',
                                       'tag' => $this->code.'-cc-cvv');
      }
    }
    return $selection;
  }
121043
function isCreditCard(val) {
  const digits = val.replace(/\D/g, '');
  const types = creditCardType(digits);
  if (!isArray(types) || isEmpty(types)) return false;
  let match = false;
  for (let t = 0; t < types.length; t++) {
    if (match) break;
    const type = types[t];
    // can match any one of the lengths
    if (!isArray(type.lengths) || isEmpty(type.lengths)) continue;
    for (let l = 0; l < type.lengths.length; l++) {
      const len = type.lengths[l];
      if (isFinite(len) && len === digits.length) {
        match = true;
        break;
      }
    }
  }

  return match;
}
201416
public static String creditCardNumber(JDefaultCreditCardType type) {
        String ccNumber = null;
        switch (type) {
            case VISA: {
                StringBuffer tempCC = new StringBuffer("4");
                tempCC.append(JDefaultNumber.randomNumberString(14));
                ccNumber = tempCC.append(+generateCheckDigit(tempCC.toString())).toString();
                break;
            }
            case MASTERCARD: {
                StringBuffer tempCC = new StringBuffer("5");
                tempCC.append(JDefaultNumber.randomIntBetweenTwoNumbers(1, 5));
                tempCC.append(JDefaultNumber.randomNumberString(13));
                ccNumber = tempCC.append(+generateCheckDigit(tempCC.toString())).toString();
                break;
            }
            case AMEX: {
                StringBuffer tempCC = new StringBuffer("3");
                tempCC.append(JDefaultNumber.randomIntBetweenTwoNumbers(4, 7));
                tempCC.append(JDefaultNumber.randomNumberString(12));
                ccNumber = tempCC.append(+generateCheckDigit(tempCC.toString())).toString();
                break;
            }
            case DISCOVER: {
                StringBuffer tempCC = new StringBuffer("6011");
                tempCC.append(JDefaultNumber.randomNumberString(11));
                ccNumber = tempCC.append(+generateCheckDigit(tempCC.toString())).toString();
                break;
            }
        }
        return ccNumber;
    }
388621
def payment_methods(self):
		
		for source in self.sources.iterator():
			yield source

		for card in self.legacy_cards.iterator():
			yield card