text:
require 'test_helper'

class MonerisTest < Test::Unit::TestCase
  include CommStub

  def setup
    Base.mode = :test

    @gateway = MonerisGateway.new(
      :login => 'store3',
      :password => 'yesguy'
    )

    @amount = 100
    @credit_card = credit_card('4242424242424242')
    @options = { :order_id => '1', :customer => '1', :billing_address => address}
  end

  def test_default_options
    assert_equal 7, @gateway.options[:crypt_type]
    assert_equal 'store3', @gateway.options[:login]
    assert_equal 'yesguy', @gateway.options[:password]
  end

  def test_successful_purchase
    @gateway.expects(:ssl_post).returns(successful_purchase_response)

    assert response = @gateway.purchase(100, @credit_card, @options)
    assert_success response
    assert_equal '58-0_3;1026.1', response.authorization
  end

  def test_successful_first_purchase_with_credential_on_file
    gateway = MonerisGateway.new(
      :login => 'store3',
      :password => 'yesguy'
    )
    gateway.expects(:ssl_post).returns(successful_first_cof_purchase_response)
    assert response = gateway.purchase(
      @amount,
      @credit_card,
      @options.merge(
        issuer_id: '',
        payment_indicator: 'C',
        payment_information: '0'
      )
    )
    assert_success response
    assert_equal 'Approved', response.message
    assert_false response.authorization.blank?
    assert_not_empty response.params['issuer_id']
  end

  def test_successful_subsequent_purchase_with_credential_on_file
    gateway = MonerisGateway.new(
      :login => 'store3',
      :password => 'yesguy'
    )
    gateway.expects(:ssl_post).returns(successful_first_cof_authorize_response)
    assert response = gateway.authorize(
      @amount,
      @credit_card,
      @options.merge(
        issuer_id: '',
        payment_indicator: 'C',
        payment_information: '0'
      )
    )
    assert_success response
    assert_equal 'Approved', response.message
    assert_false response.authorization.blank?

    gateway.expects(:ssl_post).returns(successful_subsequent_cof_purchase_response)

    assert response2 = gateway.purchase(
      @amount,
      @credit_card,
      @options.merge(
        order_id: response.authorization,
        issuer_id: response.params['issuer_id'],
        payment_indicator: 'U',
        payment_information: '2'
      )
    )
    assert_success response2
    assert_equal 'Approved', response2.message
    assert_false response2.authorization.blank?
  end

  def test_successful_purchase_with_network_tokenization
    @gateway.expects(:ssl_post).returns(successful_purchase_network_tokenization)
    @credit_card = network_tokenization_credit_card('4242424242424242',
      payment_cryptogram: 'BwABB4JRdgAAAAAAiFF2AAAAAAA=',
      verification_value: nil
    )
    assert response = @gateway.purchase(100, @credit_card, @options)
    assert_success response
    assert_equal '101965-0_10;0bbb277b543a17b6781243889a689573', response.authorization
  end

  def test_failed_purchase
    @gateway.expects(:ssl_post).returns(failed_purchase_response)

    assert response = @gateway.authorize(100, @credit_card, @options)
    assert_failure response
  end

  def test_deprecated_credit
    @gateway.expects(:ssl_post).with(anything, regexp_matches(/txn_number>123<\//), anything).returns('')
    @gateway.expects(:parse).returns({})
    assert_deprecation_warning(Gateway::CREDIT_DEPRECATION_MESSAGE) do
      @gateway.credit(@amount, '123;456', @options)
    end
  end

  def test_refund
    @gateway.expects(:ssl_post).with(anything, regexp_matches(/txn_number>123<\//), anything).returns('')
    @gateway.expects(:parse).returns({})
    @gateway.refund(@amount, '123;456', @options)
  end

  def test_amount_style
    assert_equal '10.34', @gateway.send(:amount, 1034)

    assert_raise(ArgumentError) do
      @gateway.send(:amount, '10.34')
    end
  end

  def test_preauth_is_valid_xml
    params = {
      :order_id => 'order1',
      :amount => '1.01',
      :pan => '4242424242424242',
      :expdate => '0303',
      :crypt_type => 7,
    }

    assert data = @gateway.send(:post_data, 'preauth', params)
    assert REXML::Document.new(data)
    assert_equal xml_capture_fixture.size, data.size
  end

  def test_purchase_is_valid_xml
    params = {
      :order_id => 'order1',
      :amount => '1.01',
      :pan => '4242424242424242',
      :expdate => '0303',
      :crypt_type => 7,
    }

    assert data = @gateway.send(:post_data, 'purchase', params)
    assert REXML::Document.new(data)
    assert_equal xml_purchase_fixture.size, data.size
  end

  def test_capture_is_valid_xml
    params = {
      :order_id => 'order1',
      :amount => '1.01',
      :pan => '4242424242424242',
      :expdate => '0303',
      :crypt_type => 7,
    }

    assert data = @gateway.send(:post_data, 'preauth', params)
    assert REXML::Document.new(data)
    assert_equal xml_capture_fixture.size, data.size
  end

  def test_successful_verify
    response = stub_comms do
      @gateway.verify(@credit_card, @options)
    end.respond_with(successful_authorize_response, failed_void_response)
    assert_success response
    assert_equal 'Approved', response.message
  end

  def test_supported_countries
    assert_equal ['CA'], MonerisGateway.supported_countries
  end

  def test_supported_card_types
    assert_equal [:visa, :master, :american_express, :diners_club, :discover], MonerisGateway.supported_cardtypes
  end

  def test_should_raise_error_if_transaction_param_empty_on_credit_request
    [nil, '', '1234'].each do |invalid_transaction_param|
      assert_raise(ArgumentError) { @gateway.void(invalid_transaction_param) }
    end
  end

  def test_successful_store
    @gateway.expects(:ssl_post).returns(successful_store_response)
    assert response = @gateway.store(@credit_card)
    assert_success response
    assert_equal 'Successfully registered cc details', response.message
    assert response.params['data_key'].present?
    @data_key = response.params['data_key']
  end

  def test_successful_unstore
    @gateway.expects(:ssl_post).returns(successful_unstore_response)
    test_successful_store
    assert response = @gateway.unstore(@data_key)
    assert_success response
    assert_equal 'Successfully deleted cc details', response.message
    assert response.params['data_key'].present?
  end

  def test_update
    @gateway.expects(:ssl_post).returns(successful_update_response)
    test_successful_store
    assert response = @gateway.update(@data_key, @credit_card)
    assert_success response
    assert_equal 'Successfully updated cc details', response.message
    assert response.params['data_key'].present?
  end

  def test_successful_purchase_with_vault
    @gateway.expects(:ssl_post).returns(successful_purchase_response)
    test_successful_store
    assert response = @gateway.purchase(100, @data_key, {:order_id => generate_unique_id, :customer => generate_unique_id})
    assert_success response
    assert_equal 'Approved', response.message
    assert response.authorization.present?
  end

  def test_successful_authorize_with_network_tokenization
    @gateway.expects(:ssl_post).returns(successful_authorization_network_tokenization)
    @credit_card = network_tokenization_credit_card('4242424242424242',
      payment_cryptogram: 'BwABB4JRdgAAAAAAiFF2AAAAAAA=',
      verification_value: nil
    )
    assert response = @gateway.authorize(100, @credit_card, @options)
    assert_success response
    assert_equal '109232-0_10;d88d9f5f3472898832c54d6b5572757e', response.authorization
  end

  def test_successful_authorization_with_vault
    @gateway.expects(:ssl_post).returns(successful_purchase_response)
    test_successful_store
    assert response = @gateway.authorize(100, @data_key, {:order_id => generate_unique_id, :customer => generate_unique_id})
    assert_success response
    assert_equal 'Approved', response.message
    assert response.authorization.present?
  end

  def test_failed_authorization_with_vault
    @gateway.expects(:ssl_post).returns(failed_purchase_response)
    test_successful_store
    assert response = @gateway.authorize(100, @data_key, @options)
    assert_failure response
  end

  def test_cvv_enabled_and_provided
    gateway = MonerisGateway.new(login: 'store1', password: 'yesguy', cvv_enabled: true)

    @credit_card.verification_value = '452'
    stub_comms(gateway) do
      gateway.purchase(@amount, @credit_card, @options)
    end.check_request do |endpoint, data, headers|
      assert_match(%r{cvd_indicator>1<}, data)
      assert_match(%r{cvd_value>452<}, data)
    end.respond_with(successful_purchase_response)
  end

  def test_cvv_enabled_but_not_provided
    gateway = MonerisGateway.new(login: 'store1', password: 'yesguy', cvv_enabled: true)

    @credit_card.verification_value = ''
    stub_comms(gateway) do
      gateway.purchase(@amount, @credit_card, @options)
    end.check_request do |endpoint, data, headers|
      assert_match(%r{cvd_indicator>0<}, data)
      assert_no_match(%r{cvd_value>}, data)
    end.respond_with(successful_purchase_response)
  end

  def test_cvv_disabled_and_provided
    @credit_card.verification_value = '452'
    stub_comms do
      @gateway.purchase(@amount, @credit_card, @options)
    end.check_request do |endpoint, data, headers|
      assert_no_match(%r{cvd_value>}, data)
      assert_no_match(%r{cvd_indicator>}, data)
    end.respond_with(successful_purchase_response)
  end

  def test_cvv_disabled_but_not_provided
    @credit_card.verification_value = ''
    stub_comms do
      @gateway.purchase(@amount, @credit_card, @options)
    end.check_request do |endpoint, data, headers|
      assert_no_match(%r{cvd_value>}, data)
      assert_no_match(%r{cvd_indicator>}, data)
    end.respond_with(successful_purchase_response)
  end

  def test_avs_enabled_and_provided
    gateway = MonerisGateway.new(login: 'store1', password: 'yesguy', avs_enabled: true)

    billing_address = address(address1: '1234 Anystreet', address2: '')
    stub_comms(gateway) do
      gateway.purchase(@amount, @credit_card, billing_address: billing_address, order_id: '1')
    end.check_request do |endpoint, data, headers|
      assert_match(%r{avs_street_number>1234<}, data)
      assert_match(%r{avs_street_name>Anystreet<}, data)
      assert_match(%r{avs_zipcode>#{billing_address[:zip]}<}, data)
    end.respond_with(successful_purchase_response_with_avs_result)
  end

  def test_avs_enabled_but_not_provided
    gateway = MonerisGateway.new(login: 'store1', password: 'yesguy', avs_enabled: true)

    stub_comms(gateway) do
      gateway.purchase(@amount, @credit_card, @options.tap { |x| x.delete(:billing_address) })
    end.check_request do |endpoint, data, headers|
      assert_no_match(%r{avs_street_number>}, data)
      assert_no_match(%r{avs_street_name>}, data)
      assert_no_match(%r{avs_zipcode>}, data)
    end.respond_with(successful_purchase_response)
  end

  def test_avs_disabled_and_provided
    billing_address = address(address1: '1234 Anystreet', address2: '')
    stub_comms do
      @gateway.purchase(@amount, @credit_card, billing_address: billing_address, order_id: '1')
    end.check_request do |endpoint, data, headers|
      assert_no_match(%r{avs_street_number>}, data)
      assert_no_match(%r{avs_street_name>}, data)
      assert_no_match(%r{avs_zipcode>}, data)
    end.respond_with(successful_purchase_response_with_avs_result)
  end

  def test_avs_disabled_and_not_provided
    stub_comms do
      @gateway.purchase(@amount, @credit_card, @options.tap { |x| x.delete(:billing_address) })
    end.check_request do |endpoint, data, headers|
      assert_no_match(%r{avs_street_number>}, data)
      assert_no_match(%r{avs_street_name>}, data)
      assert_no_match(%r{avs_zipcode>}, data)
    end.respond_with(successful_purchase_response)
  end

  def test_avs_result_valid_with_address
    @gateway.expects(:ssl_post).returns(successful_purchase_response_with_avs_result)
    assert response = @gateway.purchase(100, @credit_card, @options)
    assert_equal(response.avs_result, {
      'code' => 'A',
      'message' => 'Street address matches, but postal code does not match.',
      'street_match' => 'Y',
      'postal_match' => 'N'
    })
  end

  def test_customer_can_be_specified
    stub_comms do
      @gateway.purchase(@amount, @credit_card, order_id: '3', customer: 'Joe Jones')
    end.check_request do |endpoint, data, headers|
      assert_match(%r{cust_id>Joe Jones}, data)
    end.respond_with(successful_purchase_response)
  end

  def test_customer_not_specified_card_name_used
    stub_comms do
      @gateway.purchase(@amount, @credit_card, order_id: '3')
    end.check_request do |endpoint, data, headers|
      assert_match(%r{cust_id>Longbob Longsen}, data)
    end.respond_with(successful_purchase_response)
  end

  def test_add_swipe_data_with_creditcard
    @credit_card.track_data = 'Track Data'

    stub_comms do
      @gateway.purchase(@amount, @credit_card, @options)
    end.check_request do |endpoint, data, headers|
      assert_match '<pos_code>00</pos_code>', data
      assert_match '<track2>Track Data</track2>', data
    end.respond_with(successful_purchase_response)
  end

  def test_scrub
    assert_equal @gateway.scrub(pre_scrub), post_scrub
  end

  def test_supports_scrubbing?
    assert @gateway.supports_scrubbing?
  end

  private

  def successful_purchase_response
    <<-RESPONSE
<?xml version="1.0"?>
<response>
  <receipt>
    <ReceiptId>1026.1</ReceiptId>
    <ReferenceNum>661221050010170010</ReferenceNum>
    <ResponseCode>027</ResponseCode>
    <ISO>01</ISO>
    <AuthCode>013511</AuthCode>
    <TransTime>18:41:13</TransTime>
    <TransDate>2008-01-05</TransDate>
    <TransType>00</TransType>
    <Complete>true</Complete>
    <Message>APPROVED * =</Message>
    <TransAmount>1.00</TransAmount>
    <CardType>V</CardType>
    <TransID>58-0_3</TransID>
    <TimedOut>false</TimedOut>
  </receipt>
</response>

    RESPONSE
  end

  def successful_first_cof_purchase_response
    <<-RESPONSE
<?xml version=\"1.0\" standalone=\"yes\"?>
<?xml version="1.0" standalone="yes"?>
<response>
 <receipt>
   <ReceiptId>a33ba7edd448b91ef8d2f85fea614b8d</ReceiptId>
   <ReferenceNum>660114080015099160</ReferenceNum>
   <ResponseCode>027</ResponseCode>
   <ISO>01</ISO>
   <AuthCode>822665</AuthCode>
   <TransTime>07:43:28</TransTime>
   <TransDate>2018-11-11</TransDate>
   <TransType>00</TransType>
   <Complete>true</Complete>
   <Message>APPROVED           *                    =</Message>
   <TransAmount>1.00</TransAmount>
   <CardType>V</CardType>
   <TransID>799655-0_11</TransID>
   <TimedOut>false</TimedOut>
   <BankTotals>null</BankTotals>
   <Ticket>null</Ticket>
   <IssuerId>355689484440192</IssuerId>
   <IsVisaDebit>false</IsVisaDebit>
 </receipt>
</response>
    RESPONSE
  end

  def successful_first_cof_authorize_response
    <<-RESPONSE
<?xml version=\"1.0\" standalone=\"yes\"?>
<response>
  <receipt>
    <ReceiptId>8dbc28468af2007779bbede7ec1bab6c</ReceiptId>
    <ReferenceNum>660109300018229130</ReferenceNum>
    <ResponseCode>027</ResponseCode>
    <ISO>01</ISO>
    <AuthCode>718280</AuthCode>
    <TransTime>07:50:53</TransTime>
    <TransDate>2018-11-11</TransDate>
    <TransType>01</TransType>
    <Complete>true</Complete>
    <Message>APPROVED           *                    =</Message>
    <TransAmount>1.00</TransAmount>
    <CardType>V</CardType>
    <TransID>830724-0_11</TransID>
    <TimedOut>false</TimedOut>
    <BankTotals>null</BankTotals>
    <Ticket>null</Ticket>
    <MessageId>1A8315282537312</MessageId>
    <IssuerId>550923784451193</IssuerId>
    <IsVisaDebit>false</IsVisaDebit>
  </receipt>
</response>
    RESPONSE
  end

  def successful_subsequent_cof_purchase_response
    <<-RESPONSE
<?xml version="1.0" standalone="yes"?>
<response>
  <receipt>
    <ReceiptId>830724-0_11;8dbc28468af2007779bbede7ec1bab6c</ReceiptId>
    <ReferenceNum>660109490014038930</ReferenceNum>
    <ResponseCode>027</ResponseCode>
    <ISO>01</ISO>
    <AuthCode>111234</AuthCode>
    <TransTime>07:50:54</TransTime>
    <TransDate>2018-11-11</TransDate>
    <TransType>00</TransType>
    <Complete>true</Complete>
    <Message>APPROVED           *                    =</Message>
    <TransAmount>1.00</TransAmount>
    <CardType>V</CardType>
    <TransID>455422-0_11</TransID>
    <TimedOut>false</TimedOut>
    <BankTotals>null</BankTotals>
    <Ticket>null</Ticket>
    <IssuerId>762097792112819</IssuerId>
    <IsVisaDebit>false</IsVisaDebit>
  </receipt>
</response>
    RESPONSE
  end

  def successful_purchase_network_tokenization
    <<-RESPONSE
<?xml version="1.0"?>
<response>
   <receipt>
      <ReceiptId>0bbb277b543a17b6781243889a689573</ReceiptId>
      <ReferenceNum>660110910011133780</ReferenceNum>
      <ResponseCode>027</ResponseCode>
      <ISO>01</ISO>
      <AuthCode>368269</AuthCode>
      <TransTime>22:54:10</TransTime>
      <TransDate>2015-07-05</TransDate>
      <TransType>00</TransType>
      <Complete>true</Complete>
      <Message>APPROVED           *                    =</Message>
      <TransAmount>1.00</TransAmount>
      <CardType>V</CardType>
      <TransID>101965-0_10</TransID>
      <TimedOut>false</TimedOut>
      <BankTotals>null</BankTotals>
      <Ticket>null</Ticket>
      <CorporateCard>false</CorporateCard>
      <IsVisaDebit>false</IsVisaDebit>
   </receipt>
</response>

    RESPONSE
  end

  def successful_authorize_response
    <<-RESPONSE
    <?xml version="1.0"?>
    <response>
      <receipt>
        <ReceiptId>47986100c3ad69c37ca945f5c54abf1c</ReceiptId>
        <ReferenceNum>660144080010396720</ReferenceNum>
        <ResponseCode>027</ResponseCode>
        <ISO>01</ISO>
        <AuthCode>149406</AuthCode>
        <TransTime>09:59:15</TransTime>
        <TransDate>2016-03-10</TransDate>
        <TransType>01</TransType>
        <Complete>true</Complete>
        <Message>APPROVED           *                    =</Message>
        <TransAmount>1.00</TransAmount>
        <CardType>V</CardType>
        <TransID>51340-0_10</TransID>
        <TimedOut>false</TimedOut>
        <BankTotals>null</BankTotals>
        <Ticket>null</Ticket>
        <CorporateCard>false</CorporateCard>
        <MessageId>1A6070359555668</MessageId>
        <IsVisaDebit>false</IsVisaDebit>
      </receipt>
    </response>
    RESPONSE
  end

  def successful_authorization_network_tokenization
    <<-RESPONSE
<?xml version="1.0"?>
<response>
   <receipt>
      <ReceiptId>d88d9f5f3472898832c54d6b5572757e</ReceiptId>
      <ReferenceNum>660110910011139740</ReferenceNum>
      <ResponseCode>027</ResponseCode>
      <ISO>01</ISO>
      <AuthCode>873534</AuthCode>
      <TransTime>09:31:41</TransTime>
      <TransDate>2015-07-09</TransDate>
      <TransType>01</TransType>
      <Complete>true</Complete>
      <Message>APPROVED           *                    =</Message>
      <TransAmount>1.00</TransAmount>
      <CardType>V</CardType>
      <TransID>109232-0_10</TransID>
      <TimedOut>false</TimedOut>
      <BankTotals>null</BankTotals>
      <Ticket>null</Ticket>
      <CorporateCard>false</CorporateCard>
      <IsVisaDebit>false</IsVisaDebit>
   </receipt>
</response>

    RESPONSE
  end

  def successful_purchase_response_with_avs_result
    <<-RESPONSE
<?xml version="1.0"?>
<response>
  <receipt>
    <ReceiptId>9c7189ec64b58f541335be1ca6294d09</ReceiptId>
    <ReferenceNum>660110910011136190</ReferenceNum>
    <ResponseCode>027</ResponseCode>
    <ISO>01</ISO>
    <AuthCode>115497</AuthCode>
    <TransTime>15:20:51</TransTime>
    <TransDate>2014-06-18</TransDate>
    <TransType>00</TransType>
    <Complete>true</Complete><Message>APPROVED * =</Message>
    <TransAmount>10.10</TransAmount>
    <CardType>V</CardType>
    <TransID>491573-0_9</TransID>
    <TimedOut>false</TimedOut>
    <BankTotals>null</BankTotals>
    <Ticket>null</Ticket>
    <CorporateCard>false</CorporateCard>
    <AvsResultCode>A</AvsResultCode>
    <ITDResponse>null</ITDResponse>
    <IsVisaDebit>false</IsVisaDebit>
  </receipt>
</response>

    RESPONSE
  end

  def failed_purchase_response
    <<-RESPONSE
<?xml version="1.0"?>
<response>
  <receipt>
    <ReceiptId>1026.1</ReceiptId>
    <ReferenceNum>661221050010170010</ReferenceNum>
    <ResponseCode>481</ResponseCode>
    <ISO>01</ISO>
    <AuthCode>013511</AuthCode>
    <TransTime>18:41:13</TransTime>
    <TransDate>2008-01-05</TransDate>
    <TransType>00</TransType>
    <Complete>true</Complete>
    <Message>DECLINED * =</Message>
    <TransAmount>1.00</TransAmount>
    <CardType>V</CardType>
    <TransID>97-2-0</TransID>
    <TimedOut>false</TimedOut>
  </receipt>
</response>

    RESPONSE
  end

  def successful_store_response
    <<-RESPONSE
<?xml version="1.0"?>
<response>
  <receipt>
    <DataKey>1234567890</DataKey>
    <ResponseCode>027</ResponseCode>
    <Complete>true</Complete>
    <Message>Successfully registered cc details * =</Message>
  </receipt>
</response>
    RESPONSE
  end

  def successful_unstore_response
    <<-RESPONSE
<?xml version="1.0"?>
<response>
  <receipt>
    <DataKey>1234567890</DataKey>
    <ResponseCode>027</ResponseCode>
    <Complete>true</Complete>
    <Message>Successfully deleted cc details * =</Message>
  </receipt>
</response>
    RESPONSE
  end

  def successful_update_response
    <<-RESPONSE
<?xml version="1.0"?>
<response>
  <receipt>
    <DataKey>1234567890</DataKey>
    <ResponseCode>027</ResponseCode>
    <Complete>true</Complete>
    <Message>Successfully updated cc details * =</Message>
  </receipt>
</response>
    RESPONSE
  end

  def failed_void_response
    <<-RESPONSE
      <?xml version="1.0"?>
      <response>
        <receipt>
          <ReceiptId>null</ReceiptId>
          <ReferenceNum>null</ReferenceNum>
          <ResponseCode>null</ResponseCode>
          <ISO>null</ISO>
          <AuthCode>null</AuthCode>
          <TransTime>null</TransTime>
          <TransDate>null</TransDate>
          <TransType>null</TransType>
          <Complete>false</Complete>
          <Message>No Pre-auth corresponds to the store Id and order Id and transaction Id entered</Message>
          <TransAmount>null</TransAmount>
          <CardType>null</CardType>
          <TransID>null</TransID>
          <TimedOut>false</TimedOut>
          <BankTotals>null</BankTotals>
          <Ticket>null</Ticket>
          <IsVisaDebit>false</IsVisaDebit>
        </receipt>
      </response>
    RESPONSE
  end

  def xml_purchase_fixture
    '<request><store_id>store1</store_id><api_token>yesguy</api_token><purchase><amount>1.01</amount><pan>4242424242424242</pan><expdate>0303</expdate><crypt_type>7</crypt_type><order_id>order1</order_id></purchase></request>'
  end

  def xml_capture_fixture
    '<request><store_id>store1</store_id><api_token>yesguy</api_token><preauth><amount>1.01</amount><pan>4242424242424242</pan><expdate>0303</expdate><crypt_type>7</crypt_type><order_id>order1</order_id></preauth></request>'
  end

  def pre_scrub
    <<-pre_scrub
      opening connection to esqa.moneris.com:443...
      opened
      starting SSL for esqa.moneris.com:443...
      SSL established
      <- "POST /gateway2/servlet/MpgRequest HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nConnection: close\r\nHost: esqa.moneris.com\r\nContent-Length: 176\r\n\r\n"
      <- "<request><store_id>store1</store_id><api_token>yesguy</api_token><res_add_cc><pan>4242424242424242</pan><expdate>1705</expdate><crypt_type>7</crypt_type></res_add_cc></request>"
      -> "HTTP/1.1 200 OK\r\n"
      -> "Date: Mon, 16 May 2016 02:35:23 GMT\r\n"
      -> "Connection: close\r\n"
      -> "Content-Type: text/html\r\n"
      -> "Set-Cookie: TS011902c9=01649737b1334cfbe6b21538231fb4ad142215050461293f17e2dc76d7821e71c2f25055ea; Path=/\r\n"
      -> "Transfer-Encoding: chunked\r\n"
      -> "\r\n"
      -> "391\r\n"
      reading 913 bytes...
      -> "<?xml version=\"1.0\"?><response><receipt><DataKey>LAmXQeZwdtzUtz1QI1vF6etR2</DataKey><ReceiptId>null</ReceiptId><ReferenceNum>null</ReferenceNum><ResponseCode>001</ResponseCode><ISO>null</ISO><AuthCode>null</AuthCode><Message>Successfully registered CC details.</Message><TransTime>22:35:23</TransTime><TransDate>2016-05-15</TransDate><TransType>null</TransType><Complete>true</Complete><TransAmount>null</TransAmount><CardType>null</CardType><TransID>null</TransID><TimedOut>false</TimedOut><CorporateCard>null</CorporateCard><RecurSuccess>null</RecurSuccess><AvsResultCode>null</AvsResultCode><CvdResultCode>null</CvdResultCode><ResSuccess>true</ResSuccess><PaymentType>cc</PaymentType><IsVisaDebit>null</IsVisaDebit><ResolveData><cust_id></cust_id><phone></phone><email></email><note></note><crypt_type>7</crypt_type><masked_pan>4242***4242</masked_pan><expdate>1705</expdate></ResolveData></receipt></response>"
      read 913 bytes
      reading 2 bytes...
      -> "\r\n"
      read 2 bytes
      -> "0\r\n"
      -> "\r\n"
      Conn close
    pre_scrub
  end

  def post_scrub
    <<-post_scrub
      opening connection to esqa.moneris.com:443...
      opened
      starting SSL for esqa.moneris.com:443...
      SSL established
      <- "POST /gateway2/servlet/MpgRequest HTTP/1.1\r\nContent-Type: application/x-www-form-urlencoded\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nConnection: close\r\nHost: esqa.moneris.com\r\nContent-Length: 176\r\n\r\n"
      <- "<request><store_id>[FILTERED]</store_id><api_token>[FILTERED]</api_token><res_add_cc><pan>[FILTERED]</pan><expdate>1705</expdate><crypt_type>7</crypt_type></res_add_cc></request>"
      -> "HTTP/1.1 200 OK\r\n"
      -> "Date: Mon, 16 May 2016 02:35:23 GMT\r\n"
      -> "Connection: close\r\n"
      -> "Content-Type: text/html\r\n"
      -> "Set-Cookie: TS011902c9=01649737b1334cfbe6b21538231fb4ad142215050461293f17e2dc76d7821e71c2f25055ea; Path=/\r\n"
      -> "Transfer-Encoding: chunked\r\n"
      -> "\r\n"
      -> "391\r\n"
      reading 913 bytes...
      -> "<?xml version=\"1.0\"?><response><receipt><DataKey>LAmXQeZwdtzUtz1QI1vF6etR2</DataKey><ReceiptId>null</ReceiptId><ReferenceNum>null</ReferenceNum><ResponseCode>001</ResponseCode><ISO>null</ISO><AuthCode>null</AuthCode><Message>Successfully registered CC details.</Message><TransTime>22:35:23</TransTime><TransDate>2016-05-15</TransDate><TransType>null</TransType><Complete>true</Complete><TransAmount>null</TransAmount><CardType>null</CardType><TransID>null</TransID><TimedOut>false</TimedOut><CorporateCard>null</CorporateCard><RecurSuccess>null</RecurSuccess><AvsResultCode>null</AvsResultCode><CvdResultCode>null</CvdResultCode><ResSuccess>true</ResSuccess><PaymentType>cc</PaymentType><IsVisaDebit>null</IsVisaDebit><ResolveData><cust_id></cust_id><phone></phone><email></email><note></note><crypt_type>7</crypt_type><masked_pan>4242***4242</masked_pan><expdate>1705</expdate></ResolveData></receipt></response>"
      read 913 bytes
      reading 2 bytes...
      -> "\r\n"
      read 2 bytes
      -> "0\r\n"
      -> "\r\n"
      Conn close
    post_scrub
  end
end


text:
<!DOCTYPE html>

    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />

    <title>{{ page.title }}</title>
    <meta name="description" content="">

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

所有文章

后端

移动

前端

系统

数据存储

        {% for post in site.posts %}
          {{ post.title }}{{ post.date | date: "%b %Y" }}
        {% endfor %}

        {{ content }}

          Table of Contents

    <button id="js-fullscreen"></button>

redpajama_set_name: RedPajamaGithub


text:
namespace DeckEditor.Database.Characteristics
{
	enum Legality
	{
		Banned,
		Legal,
		Restricted
	}
}


text:
import unittest

from hello_world import hello

# Tests adapted from `problem-specifications//canonical-data.json`

class HelloWorldTest(unittest.TestCase):
    def test_say_hi(self):
        self.assertEqual(hello(), "Hello, World!")

if __name__ == "__main__":
    unittest.main()


text:
package com.zblog.web.backend.controller;

import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zblog.biz.CategoryManager;
import com.zblog.core.dal.entity.Category;
import com.zblog.core.plugin.MapContainer;
import com.zblog.core.util.CollectionUtils;
import com.zblog.core.util.IdGenerator;
import com.zblog.service.CategoryService;
import com.zblog.web.backend.form.validator.CategoryFormValidator;

@Controller("adminCategoryController")
@RequestMapping("/backend/categorys")
@RequiresRoles(value = { "admin", "editor" }, logical = Logical.OR)
public class CategoryController{
  @Autowired
  private CategoryService categoryService;
  @Autowired
  private CategoryManager categoryManager;

  @RequestMapping(method = RequestMethod.GET)
  public String index(){
    return "backend/post/category";
  }

  @ResponseBody
  @RequestMapping(value = "/index", method = RequestMethod.GET)
  public Object data(){
    List<MapContainer> list = categoryManager.listAsTree();
    for(MapContainer temp : list){
      temp.put("text", temp.remove("name"));
      List<MapContainer> nodes = temp.get("nodes");
      if(CollectionUtils.isEmpty(nodes))
        continue;

      for(MapContainer child : nodes){
        child.put("text", child.remove("name"));
        child.put("icon", "glyphicon glyphicon-star");
      }
    }

    return list;
  }

  @ResponseBody
  @RequestMapping(method = RequestMethod.POST)
  public Object insert(Category category, String parent){
    MapContainer form = CategoryFormValidator.validateInsert(category);
    if(!form.isEmpty()){
      return form.put("success", false);
    }

    category.setId(IdGenerator.uuid19());
    category.setCreateTime(new Date());
    category.setLastUpdate(category.getCreateTime());
    return new MapContainer("success", categoryService.insertChildren(category, parent));
  }

  @ResponseBody
  @RequestMapping(value = "/{categoryName}", method = RequestMethod.DELETE)
  public Object remove(@PathVariable String categoryName){
    categoryManager.remove(categoryName);
    return new MapContainer("success", true);
  }

}


text:
<?php

namespace Ekyna\Bundle\AdminBundle\Acl;

use Ekyna\Bundle\UserBundle\Model\GroupInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Security\Acl\Domain\ObjectIdentity;
use Symfony\Component\Security\Acl\Domain\RoleSecurityIdentity;
use Symfony\Component\Security\Acl\Model\ObjectIdentityInterface;

/**
 * Interface AclOperatorInterface
 * @package Ekyna\Bundle\AdminBundle\Acl
 * @author Étienne Dauvergne <contact@ekyna.com>
 */
interface AclOperatorInterface
{
    /**
     * Loads all the registered objects identity Acls.
     */
    public function loadAcls();

    /**
     * Find acl.
     *
     * @param ObjectIdentityInterface $oid
     * @param array $sids
     *
     * @see \Symfony\Component\Security\Acl\Model\AclProviderInterface::findAcl
     */
    public function findAcl(ObjectIdentityInterface $oid, array $sids = []);

    /**
     * Returns the mask relative to ObjectIdentity and RoleSecurityIdentity
     *
     * @param ObjectIdentity $oid
     * @param RoleSecurityIdentity $rid
     *
     * @return number
     */
    public function getClassMask(ObjectIdentity $oid, RoleSecurityIdentity $rid);

    /**
     * Sets the mask for given ObjectIdentity and RoleSecurityIdentity
     *
     * @param ObjectIdentity $oid
     * @param RoleSecurityIdentity $rid
     * @param int $mask
     */
    public function setClassMask(ObjectIdentity $oid, RoleSecurityIdentity $rid, $mask = 0);

    /**
     * Returns permission map
     *
     * @return \Symfony\Component\Security\Acl\Permission\PermissionMapInterface
     */
    public function getPermissionMap();

    /**
     * Returns permissions list
     *
     * @return array
     */
    public function getPermissions();

    /**
     * Returns permission masks
     *
     * @param string $permission
     *
     * @return array
     */
    public function getPermissionMasks($permission);

    /**
     * Builds the group permissions form.
     *
     * @param \Symfony\Component\Form\FormBuilderInterface $builder
     */
    public function buildGroupForm(FormBuilderInterface $builder);

    /**
     * Generates the group permissions form datas.
     *
     * @param \Ekyna\Bundle\UserBundle\Model\GroupInterface $group
     */
    public function generateGroupFormDatas(GroupInterface $group);

    /**
     * Generates the group permissions view datas.
     *
     * @param \Ekyna\Bundle\UserBundle\Model\GroupInterface $group
     */
    public function generateGroupViewDatas(GroupInterface $group);

    /**
     * Updates the group permissions from the given datas.
     *
     * @param \Ekyna\Bundle\UserBundle\Model\GroupInterface $group
     * @param array                                         $datas
     */
    public function updateGroup(GroupInterface $group, array $datas);

    /**
     * Returns whether the current user is granted for the given permission on the given resource.
     *
     * @param mixed  $resource
     * @param string $permission
     *
     * @throws \InvalidArgumentException
     *
     * @return boolean
     */
    public function isAccessGranted($resource, $permission);
}


text:
<!doctype html>

    <meta charset="utf-8">
    <title>jQuery UI Datepicker - Dates in other months</title>
    <link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">

    <link rel="stylesheet" href="../demos.css">

Date: <input type="text" id="datepicker">

The datepicker can show dates that come from other than the main month
        being displayed. These other dates can also be made selectable.


text:
package com.acunu.analytics.alerts;

import java.util.Iterator;
import java.util.Map;

import com.acunu.analytics.conf.ConfigProperties;

/**
 * Interface for the configuration settings of the Alert Monitor and Alert sinks.
 * @author tmoreton
 *
 */
public interface AlertMonitorConfig extends ConfigProperties {

	public abstract Iterator<Map.Entry<String, ConfigProperties>> enumerateAlertSinkConfigs();

	public abstract ConfigProperties getSslDetails();

	public abstract ConfigProperties getReporting();

	public Map<String,String> getHttpHeaders();

}


text:
package de.businesscode.bcdui.logging;

import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import de.businesscode.bcdui.toolbox.config.BareConfiguration;
import de.businesscode.sqlengine.SQLEngine;
import de.businesscode.util.SingletonHolder;

/**
 * logs {@link de.businesscode.bcdui.logging.LogoutSqlLogger.LogRecord} into database, binding set used is bcd_log_session,
 * this class is not intended to be customized or extended in projects. The existence of
 * the binding-set enables this logger automatically.
 *
 */
final public class LogoutSqlLogger extends ASqlLogger<LogoutSqlLogger.LogRecord> {
  private static final int DEFAULT_QUEUE_SIZE =       100;
  private static final long DEFAULT_QUEUE_SLEEP_MS =  10*1000;  //10seconds
  private static final String PARAM_QUEUE_SIZE =      "bcdui/loggers/db/login/queueSize";
  private static final String PARAM_QUEUE_SLEEP_MS =  "bcdui/loggers/db/login/queueSleepMs";
  private static Logger logger = LogManager.getLogger(LogoutSqlLogger.class);
  /**
   * the result to log into database
   *
   */
  public static final class LogRecord extends LogEventBase {
    final String sessionId;
    final Date stamp = new Date();

    public LogRecord(String sessionId) {
      super();
      this.sessionId = sessionId;
    }

    @Override
    public String toString() {
      return String.format("[LOGOUT SESSION:'%s']", sessionId);
    }

    @Override
    public String getFormattedMessage() {
      return toString();
    }
  }

  private final static String TPL_UPDATE_STMT =
      "#set($b = $bindings.bcd_log_login)" +
          " UPDATE $b.plainTableName SET $b.sessionExpiredTime- = ? where $b.sessionId- = ?";

  protected LogoutSqlLogger() {
    super("bcd_log_login",
        BareConfiguration.getInstance().getConfigurationParameter(PARAM_QUEUE_SIZE, DEFAULT_QUEUE_SIZE),
        BareConfiguration.getInstance().getConfigurationParameter(PARAM_QUEUE_SLEEP_MS, DEFAULT_QUEUE_SLEEP_MS));
  }

  private static SingletonHolder<LogoutSqlLogger> holder = new SingletonHolder<LogoutSqlLogger>() {
    @Override
    protected LogoutSqlLogger createInstance() {
      return new LogoutSqlLogger();
    }
  };

  public static LogoutSqlLogger getInstance() {
    return holder.get();
  }

  @Override
  protected String getSqlTemplate() {
    return new SQLEngine().transform(TPL_UPDATE_STMT);
  }

  @Override
  protected int[] executeStatement(Object[][] params) throws SQLException {
    int[] updates = super.executeStatement(params);
    // check and report when no updates done
    for(int i=0; i<updates.length; i++){
      if(updates[i] == 0) {
        // This happens if a restricted page is accessed without a valid login and the user does not login before the temporary session expires.
        // In that case there is no log entry to update. So this is not considered a warning or error
        logger.trace("Failed to update session expiry in bcd_log_login for session: " + params[i][1]);
      }
    }
    return updates;
  }

  /**
   * processes given collection of type to dimensional object array to be consumed by batch SQL
   * @param records
   * @return
   */
  @Override
  protected Object[][] convertData(Collection<LogRecord> records) {
    Object[][] data = new Object[records.size()][];

    int cnt=0;
    for(LogRecord record: records){
      data[cnt++] = new Object[]{
        new Timestamp(record.stamp.getTime()),
        record.sessionId
      };
    }

    return data;
  }
}


text:
package org.springframework.security.web.server.context;

import org.springframework.security.core.context.ReactiveSecurityContextHolder;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;
import reactor.util.context.Context;

/**
 * Uses a {@link ServerSecurityContextRepository} to provide the {@link SecurityContext} to initialize the
 * {@link ReactiveSecurityContextHolder}.
 *
 * @author Rob Winch
 * @since 5.0
 */
public class ReactorContextWebFilter implements WebFilter {
	private final ServerSecurityContextRepository repository;

	public ReactorContextWebFilter(ServerSecurityContextRepository repository) {
		Assert.notNull(repository, "repository cannot be null");
		this.repository = repository;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
		return chain.filter(exchange)
			.subscriberContext(c -> c.hasKey(SecurityContext.class) ? c :
				withSecurityContext(c, exchange)
			);
	}

	private Context withSecurityContext(Context mainContext, ServerWebExchange exchange) {
		return mainContext.putAll(this.repository.load(exchange)
			.as(ReactiveSecurityContextHolder::withSecurityContext));
	}
}


text:
/* Menu script by Marinko Gazdek
   Syntax: ShowMenu(event,parent,text,id,class)
   WHERE:
	- event: the event of the click (to prevent bubbling)
	- parent: the element that needs to be clicked in order to show the menu (used to generate width and position)
	- text: content of the menu
	- id: id of the menu for CSS purposes (OPTIONAL)
	- class: class of the menu for CSS purposes (OPTIONAL)
*/

var menudisplayed = 0;
function ShowMenu(event,parent,text,id,classa) {
	if(typeof id === "undefined") {
        id = "";
        content = null;
    }
	if(typeof classa === "undefined") {
		classa = "";
        content = null;
    }
	event.stopPropagation();
	if(menudisplayed == 0) {
		var rect = parent.getBoundingClientRect();
		var width = parent.offsetWidth;
		var height = parent.offsetHeight;
		var iDiv = document.createElement('div');
		iDiv.className = 'menu_jsgenerated '+classa;
		iDiv.id = id;
		document.getElementsByTagName('body')[0].appendChild(iDiv);
		$(".menu_jsgenerated").css("width",width);
		$(".menu_jsgenerated").html(text);
		$(".menu_jsgenerated").css("position","absolute");
		$(".menu_jsgenerated").css("top",rect.top+height);
		$(".menu_jsgenerated").css("left",rect.left);
		$(".menu_jsgenerated").css("box-sizing","border-box");
		$(".menu_jsgenerated").css("-webkit-box-sizing","border-box");
		$(".menu_jsgenerated").css("-moz-box-sizing","border-box");
		$(".menu_jsgenerated").click(function(e) {
			e.stopPropagation();
		});
		menudisplayed = 1;
	}
	else {
		menudisplayed = 0;
		$(".menu_jsgenerated").remove();
	}
}
$(document).ready(function() {
	$("body").css("width","100%");
	$("body").css("height","100%");
	$("html").css("width","100%");
	$("html").css("height","100%");
	$("body").click(function() {
		if(menudisplayed == 1) {
			menudisplayed = 0;
			$(".menu_jsgenerated").remove();
		}
	});
	$( window ).resize(function() {
		if(menudisplayed == 1) {
			menudisplayed = 0;
			$(".menu_jsgenerated").remove();
		}
	});
});


text:
package com.swfarm.biz.product.job;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.swfarm.biz.oa.bo.Image;
import com.swfarm.biz.oa.bo.ImageDirectory;
import com.swfarm.biz.product.dto.SearchImagesCriteria;
import com.swfarm.biz.product.srv.ProductManagementService;
import com.swfarm.biz.product.srv.ProductService;
import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.SpringUtils;

public class SyncImagePathTask extends QuartzJobBean {

	private Logger logger = Logger.getLogger(SyncImagePathTask.class);

	private ProductService productService;

	private ProductManagementService productManagementService;

	public void syncImagePath() {
		File isfile = new File("/root/temp/");
		if (!isfile.exists()) {
			isfile.mkdirs();
		}
		FTPClient ftp = new FTPClient();
		try {
			int reply;
			ftp.connect("192.168.1.249", 21);
			ftp.login("java", "java");
			reply = ftp.getReplyCode();
			ftp.setFileType(FTP.BINARY_FILE_TYPE);
			ftp.enterLocalPassiveMode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftp.disconnect();
			}
			ftp.changeWorkingDirectory("/list/");
			FTPFile[] fileList = ftp.listFiles();

			for (FTPFile file : fileList) {
				File localFile = new File("/root/temp/" + file.getName());
				OutputStream is = new FileOutputStream(localFile);
				ftp.retrieveFile(file.getName(), is);
				is.close();
				ftp.deleteFile(file.getName());
			}

	        File file = new File("/root/temp/");
	        File[] tempList = file.listFiles();
			for (File strFile : tempList) {
				String encoding = "GBK";
				if (strFile.isFile() && strFile.exists()) {
					InputStreamReader read = new InputStreamReader(new FileInputStream(strFile), encoding);
					BufferedReader bufferedReader = new BufferedReader(read);
					String lineTxt = null;
					while ((lineTxt = bufferedReader.readLine()) != null) {
						if (!lineTxt.equals("")) {
							String[] str = lineTxt.split("main");
							if (str.length > 1) {
							    logger.warn("------------------------------------------->path:" + strFile.getPath());
								String ftpPath = "ftp://192.168.1.249" + str[1];
								String httpPath = "http://192.168.1.249" + str[1];
								logger.warn("-------------------->ftpPath:" + ftpPath);
								SearchImagesCriteria imageCriteria = new SearchImagesCriteria();
								imageCriteria.setLocation(ftpPath);
								Image image = this.productService.findImages(imageCriteria);
								if (image != null) {
								    image.setCreateDate(new Date());
		                            this.productService.saveImage(image);
		                            logger.warn("-------------------->updateImagePath:" + httpPath);
								} else {
									String folderName = "";
									if (ftpPath.split("amazonimage").length == 2) {
										folderName = "amazonimage";
									} else if(ftpPath.split("originalimage").length == 2){
										folderName = "originalimage";
									} else {
									    folderName = "publicimage";
									}
									String[] strnum = ftpPath.split("/");
									ImageDirectory imageDirectory = this.productService
											.findImageDirectoryByName(strnum[3]);
									image = new Image();
									image.setLocation(ftpPath);
									image.setAccessUrl(httpPath);
									image.setName(strnum[strnum.length - 1]);
									image.setDescription(strnum[strnum.length - 1]);
									image.setArticleNumber(strnum[strnum.length - 2]);
									image.setImageDirectoryId(imageDirectory.getId());
									image.setFolderName(folderName);
									image.setCreateDate(new Date());
									this.productService.saveImage(image);
									logger.warn("-------------------->saveImagePath:" + httpPath);
									String[] strArticleNumber = image.getName().split("\\.");
									this.productManagementService.refreshAccecitySkuImages(strArticleNumber[0]);
								}
							}
						}
					}
					read.close();
					deleteFile(strFile);
				} else {
					logger.warn("-------------------->找不到指定的文件");
				}
			}
			ftp.logout();
		} catch (Exception e) {
			logger.warn(e.getMessage(), e);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (Exception ioe) {
					logger.warn(ioe.getMessage(), ioe);
				}
			}
		}
	}

	@Override
	protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
		productService = (ProductService) SpringUtils.getBean("productService");
		productManagementService = (ProductManagementService) SpringUtils.getBean("productManagementService");
		if (Env.SYNCHRONIZING_IMAGEPATH == false) {
			try {
				Env.SYNCHRONIZING_IMAGEPATH = true;
				this.syncImagePath();
			} catch (Exception e) {
				logger.warn(e.getMessage(), e);
			} finally {
				Env.SYNCHRONIZING_IMAGEPATH = false;
			}
		} else {
			logger.warn("previous synchronize image path job is still running");
		}
	}

	public void deleteFile(File strFile) {
        if (strFile.isFile() && strFile.exists()) {
            strFile.delete();
        }
    }

}


text:
<?php

$app->group("/corporation", function() use ($app) {
    $controller = new \Thessia\Controller\CorporationController($app);
    $app->get("/[{corporationID:[0-9]+}/]", $controller("index"));
});


text:
<?php

namespace PHPExiftool\Driver\Tag\Microsoft;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class IsAttachment extends AbstractTag
{

    protected $Id = '{F23F425C-71A1-4FA8-922F-678EA4A60408} 100';

    protected $Name = 'IsAttachment';

    protected $FullName = 'Microsoft::Xtra';

    protected $GroupName = 'Microsoft';

    protected $g0 = 'QuickTime';

    protected $g1 = 'Microsoft';

    protected $g2 = 'Video';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Is Attachment';

}


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Imports Roslyn.Test.Utilities

Public Class TestOptions
    Public Shared ReadOnly Script As New VisualBasicParseOptions(kind:=SourceCodeKind.Script)
    ' https://github.com/dotnet/roslyn/issues/29819 remove explicit language version when VB 16 is latest
    Public Shared ReadOnly Regular As New VisualBasicParseOptions(kind:=SourceCodeKind.Regular, languageVersion:=LanguageVersion.VisualBasic16)
    Public Shared ReadOnly Regular15_5 As VisualBasicParseOptions = Regular.WithLanguageVersion(LanguageVersion.VisualBasic15_5)
    Public Shared ReadOnly RegularWithLegacyStrongName As VisualBasicParseOptions = Regular.WithFeature("UseLegacyStrongNameProvider")

    Public Shared ReadOnly ReleaseDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular)
    Public Shared ReadOnly ReleaseExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular)

    Public Shared ReadOnly ReleaseDebugDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Release).
        WithDebugPlusMode(True).WithParseOptions(Regular)

    Public Shared ReadOnly ReleaseDebugExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Release).
        WithDebugPlusMode(True).WithParseOptions(Regular)

    Public Shared ReadOnly DebugDll As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular)
    Public Shared ReadOnly DebugExe As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.ConsoleApplication, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular)

    Public Shared ReadOnly ReleaseModule As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.NetModule, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular)
    Public Shared ReadOnly ReleaseWinMD As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata, optimizationLevel:=OptimizationLevel.Release).WithParseOptions(Regular)
    Public Shared ReadOnly DebugWinMD As VisualBasicCompilationOptions = New VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata, optimizationLevel:=OptimizationLevel.Debug).WithParseOptions(Regular)

    Public Shared ReadOnly SigningReleaseDll As VisualBasicCompilationOptions = ReleaseDll.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider)
    Public Shared ReadOnly SigningReleaseExe As VisualBasicCompilationOptions = ReleaseExe.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider)
    Public Shared ReadOnly SigningDebugDll As VisualBasicCompilationOptions = DebugDll.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider)
    Public Shared ReadOnly SigningDebugExe As VisualBasicCompilationOptions = DebugExe.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider)
    Public Shared ReadOnly SigningReleaseModule As VisualBasicCompilationOptions = ReleaseModule.WithStrongNameProvider(SigningTestHelpers.DefaultDesktopStrongNameProvider)
End Class

Friend Module TestOptionExtensions
    <Extension()>
    Public Function WithStrictFeature(options As VisualBasicParseOptions) As VisualBasicParseOptions
        Return WithFeature(options, "Strict")
    End Function

    <Extension()>
    Public Function WithFeature(options As VisualBasicParseOptions, feature As String, Optional value As String = "True") As VisualBasicParseOptions
        Return options.WithFeatures(options.Features.Concat(New KeyValuePair(Of String, String)() {New KeyValuePair(Of String, String)(feature, value)}))
    End Function

    <Extension()>
    Friend Function WithExperimental(options As VisualBasicParseOptions, ParamArray features As Feature()) As VisualBasicParseOptions
        If features.Length = 0 Then
            Throw New InvalidOperationException("Need at least one feature to enable")
        End If
        Dim list As New List(Of KeyValuePair(Of String, String))
        For Each feature In features
            Dim flagName = feature.GetFeatureFlag()
            If flagName Is Nothing Then
                Throw New InvalidOperationException($"{feature} is not an experimental feature")
            End If
            list.Add(New KeyValuePair(Of String, String)(flagName, "True"))
        Next
        Return options.WithFeatures(options.Features.Concat(list))
    End Function
End Module


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.codepath.apps.restclienttemplate.ComposeActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/tbnew_tweet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="0dp"
        android:background="#FFF"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_editor_absoluteY="-2dp" />

    <EditText
        android:id="@+id/et_newtweet"
        android:layout_width="match_parent"
        android:layout_height="255dp"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tbnew_tweet"
        android:textColorHint="#AAB8C2"
        android:gravity="top|left"></EditText>

    <Button
        android:id="@+id/bt_tweet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_below="@+id/et_newtweet"
        android:background="@color/logo_blue"
        android:onClick="postTweet"
        android:text="Tweet"
        android:textAllCaps="false"
        android:textColor="#FFF"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/tvTextCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/bt_tweet"
        android:layout_alignBottom="@+id/bt_tweet"
        android:layout_marginEnd="16dp"
        android:layout_toStartOf="@+id/bt_tweet"
        android:text="140"
        android:textSize="18sp"
        tools:text="140" />
</RelativeLayout>


text:
package com.arquitetaweb.comanda.controller;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.Fragment;

import com.arquitetaweb.comanda.R;
import com.arquitetaweb.comanda.dados.GetGenericApi;
import com.arquitetaweb.comanda.interfaces.AsyncTaskListener;
import com.arquitetaweb.comanda.model.ConsumoModel;
import com.google.gson.reflect.TypeToken;

public class ConsumoController {

	private ProgressDialog progressDialog;
	private Context context;
	private Fragment fragment;
	private String URL_API = "Mesa/";
	private String URL_API_FECHAR = "Conta/";
	private long MESA_ID = 0;

	public ConsumoController(Fragment fragment, ProgressDialog progressDialog,
			Long mesaId) {
		this.progressDialog = progressDialog;
		this.context = fragment.getActivity();
		this.fragment = fragment;
		this.MESA_ID = mesaId;
	}

	public void sincronizar() {
		new SincronizarDados(fragment).execute();
	}

	public void fecharConta() {
		new FecharConta(fragment).execute();
	}

	private class SincronizarDados extends
			AsyncTask<Void, Void, List<ConsumoModel>> {

		private AsyncTaskListener callback;

		public SincronizarDados(Fragment fragment) {
			this.callback = (AsyncTaskListener) fragment;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.setCancelable(false);
			progressDialog.setMessage(context.getString(R.string.carregandoConsumo));
			progressDialog.show();
		}

		@Override
		protected List<ConsumoModel> doInBackground(Void... produtos) {
			return SincronizarConsumo();
		}

		@Override
		protected void onPostExecute(List<ConsumoModel> result) {
			super.onPostExecute(result);
			callback.onTaskComplete(result);
			progressDialog.dismiss();
		}

		private List<ConsumoModel> SincronizarConsumo() {
			GetGenericApi<ConsumoModel> api = new GetGenericApi<ConsumoModel>(
					context);
			List<ConsumoModel> mesaList = api.LoadListApiFromUrl(URL_API
					+ MESA_ID, new TypeToken<ArrayList<ConsumoModel>>() {
			}.getType());
			return mesaList;
		}
	}

	private class FecharConta extends AsyncTask<Void, Void, Boolean> {
		private AsyncTaskListener callback;

		public FecharConta(Fragment fragment) {
			this.callback = (AsyncTaskListener) fragment;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog.setCancelable(false);
			progressDialog.setMessage(context.getString(R.string.fechandoConta));
			progressDialog.show();
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			return fecharConta();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			callback.onClosedComplete(result);
			progressDialog.dismiss();
		}

		private Boolean fecharConta() {
			GetGenericApi<ConsumoModel> api = new GetGenericApi<ConsumoModel>(
					context);
			return api.LoadListApiFromUrl_(URL_API + URL_API_FECHAR + MESA_ID);
		}
	}

}


text:
      <form class="form-inline">

          <input type="number" class="form-control form-control-narrow" id="start" ng-model="controls.start" ng-i18next="[placeholder]Action.StartPlaceholder">

          <input type="number" class="form-control form-control-narrow" id="end" ng-model="controls.end" ng-i18next="[placeholder]Action.EndPlaceholder">

          <input type="text" class="form-control" id="make" ng-model="controls.make" typeahead="make for make in actions.makes.filter($viewValue)" typeahead-template-url="makeTypeaheadTemplate.html" typeahead-loading="loadingMakeResults" typeahead-no-results="noMakeResults" ng-i18next="[placeholder]Action.MakePlaceholder">

        <button class="btn btn-default" ng-i18next="[title]Search" ng-click="actions.search()"></button>
      </form>

      <pagination boundary-links="true" total-items="page.total" items-per-page="page.options.limit" max-size="10" ng-model="page.current" ng-change="actions.page()" class="pagination-sm" previous-text="‹" next-text="›" first-text="«" last-text="»"></pagination>

            {{recall.Year}}
            {{recall.Make}}
            {{recall.Model}}
            {{recall.Component}}

      <pagination boundary-links="true" total-items="page.total" items-per-page="page.options.limit" max-size="10" ng-model="page.current" ng-change="actions.page()" class="pagination-sm" previous-text="‹" next-text="›" first-text="«" last-text="»"></pagination>


text:
export const queryGetAllIndicatorTypes = `query getAllIndicatorTypes($first: Int, $offset: Int, $orderBy: [IndicatorTypesOrderBy!]){
    allIndicatorTypes(first: $first, offset: $offset, orderBy: $orderBy) {
        nodes {
            id
            name
        }
        totalCount
    }
}`;

export const queryGetIndicatorType = `query getIndicatorType($id: Int!) {
    indicatorTypeById(id: $id) {
        id
        name
        createdDate
        updatedDate
        userByCreatedById { email }
        userByUpdatedById { email }
    }
}`;

export const mutationCreateIndicatorType = `mutation createIndicatorType($indicatorType: IndicatorTypeInput!) {
    createIndicatorType(input: {indicatorType: $indicatorType}) {
        indicatorType {
            id
        }
    }
}`;

export const mutationUpdateIndicatorType = `mutation updateIndicatorType($id: Int!, $indicatorTypePatch: IndicatorTypePatch!) {
    updateIndicatorTypeById(input: {id: $id, indicatorTypePatch: $indicatorTypePatch }) {
        indicatorType {
            id
            updatedDate
            userByUpdatedById { email }
        }
    }
}`;

export const mutationDeleteIndicatorType = `mutation deleteIndicatorType($id: Int!) {
    deleteIndicatorTypeById(input: {id: $id}) {
        indicatorType {
            id
        }
    }
}`;

export const mutationSearchIndicatorType = `mutation searchIndicatorType($searchKeyword: String, $sortAttribute: String, $sortOrder: String) {
    searchIndicatorType(input: {searchKeyword: $searchKeyword, sortAttribute: $sortAttribute, sortOrder: $sortOrder}) {
        indicatorTypes {
            id
            name
        }
    }
}`;

// Response labels must be formatted according to Treeselect requirements
export const queryGetIndicatorTypes = `query getAllIndicatorTypes {
    allIndicatorTypes(orderBy: NAME_ASC) {
        nodes {
            id
            label:name
        }
    }
}`;


text:
package org.jnbis.internal.record.reader;

import org.jnbis.api.model.record.TransactionInformation;
import org.jnbis.api.model.record.TransactionInformation.InfoDesignation;
import org.jnbis.api.model.record.TransactionInformation.TransactionContent;
import org.jnbis.internal.NistHelper;
import org.jnbis.internal.NistHelper.Field;
import org.jnbis.internal.NistHelper.Token;

/**
 * @author ericdsoto
 */
public class TransactionInfoReader extends RecordReader {

    @Override
    public TransactionInformation read(NistHelper.Token token) {
        TransactionInformation transaction = new TransactionInformation();

        while (token.buffer.hasRemaining()) {
            Field field = nextField(token);

            String value = field.asString();

            switch (field.fieldNumber) {
            case 1:
                transaction.setLogicalRecordLength(Integer.parseInt(value));
                break;
            case 2:
                transaction.setVersion(value);
                break;
            case 3: {
                TransactionContent content = new TransactionContent();
                Token subToken = new Token(field.value);
                Field subField = nextInformationItem(subToken);
                content.setFirstRecordCategoryCode(subField.asInteger());

                subField = nextInformationItem(subToken);
                content.setContentRecordCount(subField.asInteger());

                while (true) {
                    subField = nextInformationItem(subToken);
                    if (subField == null) {
                        break;
                    }
                    int recordType = subField.asInteger();

                    subField = nextInformationItem(subToken);
                    int idc = subField.asInteger();

                    content.getIdcs().add(new InfoDesignation(recordType, idc));
                }
                transaction.setTransactionContent(content);
                break;
            }
            case 4:
                transaction.setTypeOfTransaction(value);
                break;
            case 5:
                transaction.setDate(parseDate(value));
                break;
            case 6:
                transaction.setPriority(value);
                break;
            case 7:
                transaction.setDestinationAgencyId(value);
                break;
            case 8:
                transaction.setOriginatingAgencyId(value);
                break;
            case 9:
                transaction.setControlNumber(value);
                break;
            case 10:
                transaction.setControlReferenceNumber(value);
                break;
            case 11:
                transaction.setNativeScanningResolution(value);
                break;
            case 12:
                transaction.setNominalTransmittingResolution(value);
                break;
            case 13:
                transaction.setDomainName(value);
                break;
            case 14:
                transaction.setGreenwichMeanTime(value);
                break;
            case 15: {
                TransactionContent content = new TransactionContent();
                Token subToken = new Token(field.value);
                Field subField = nextInformationItem(subToken);
                content.setFirstRecordCategoryCode(subField.asInteger());

                token.setCharSet(value);
                transaction.setDirectoryOfCharsets(value);
                break;
            }
            }
        }

        return transaction;
    }
}


text:
using System;
using System.Runtime.Serialization;
using CommonLib.Attributes;
using Core.Core;
using Core.Handlers.KeyBoard;
using LogWrapper;
using Newtonsoft.Json;

namespace Core.ConfigEntity.ActionObjects
{
    /// <summary>
    /// Событие клавиатуры
    /// </summary>
    [DataContract]
    [LocDescription("KeyboardAct", typeof(Resources.CoreText))]
    public class KeyboardAct : BaseActionObject
    {
        /// <summary>
        /// Тип действия для внутренней фабрики
        /// </summary>
        [IgnoreDataMember]
        public new static ActionType ActionType => ActionType.KeyBoardAction;

        /// <summary>
        /// Клавиша, нажатие которой надо эмулировать
        /// </summary>
        [DataMember]
        [LocDescription("KeyBoardAct_Key", typeof(Resources.CoreText))]
        public KeyName Key { get; set; }

        /// <summary>
        /// Клавиша, нажатие которой надо эмулировать
        /// </summary>
        [DataMember]
        [LocDescription("KeyboardAct_KeyAction", typeof(Resources.CoreText))]
        public KeyAction KeyAction { get; set; }

        [JsonConstructor]
        public KeyboardAct(KeyName key, KeyAction action)
        {
            Log.WriteLine($"{GetType().Name}.ctor->(key:{key};)");
            Key = key;
            KeyAction = action;
        }
        public KeyboardAct(){}
    }
}


text:
package model

import (
	"regexp"
	"time"
)

type CompliancePost struct {

	// From Team
	TeamName        string
	TeamDisplayName string

	// From Channel
	ChannelName        string
	ChannelDisplayName string

	// From User
	UserUsername string
	UserEmail    string
	UserNickname string

	// From Post
	PostId         string
	PostCreateAt   int64
	PostUpdateAt   int64
	PostDeleteAt   int64
	PostRootId     string
	PostParentId   string
	PostOriginalId string
	PostMessage    string
	PostType       string
	PostProps      string
	PostHashtags   string
	PostFileIds    string
}

func CompliancePostHeader() []string {
	return []string{
		"TeamName",
		"TeamDisplayName",

		"ChannelName",
		"ChannelDisplayName",

		"UserUsername",
		"UserEmail",
		"UserNickname",

		"PostId",
		"PostCreateAt",
		"PostUpdateAt",
		"PostDeleteAt",
		"PostRootId",
		"PostParentId",
		"PostOriginalId",
		"PostMessage",
		"PostType",
		"PostProps",
		"PostHashtags",
		"PostFileIds",
	}
}

func cleanComplianceStrings(in string) string {
	if matched, _ := regexp.MatchString("^\\s*(=|\\+|\\-)", in); matched {
		return "'" + in

	} else {
		return in
	}
}

func (me *CompliancePost) Row() []string {

	postDeleteAt := ""
	if me.PostDeleteAt > 0 {
		postDeleteAt = time.Unix(0, me.PostDeleteAt*int64(1000*1000)).Format(time.RFC3339)
	}

	postUpdateAt := ""
	if me.PostUpdateAt != me.PostCreateAt {
		postUpdateAt = time.Unix(0, me.PostUpdateAt*int64(1000*1000)).Format(time.RFC3339)
	}

	return []string{
		cleanComplianceStrings(me.TeamName),
		cleanComplianceStrings(me.TeamDisplayName),

		cleanComplianceStrings(me.ChannelName),
		cleanComplianceStrings(me.ChannelDisplayName),

		cleanComplianceStrings(me.UserUsername),
		cleanComplianceStrings(me.UserEmail),
		cleanComplianceStrings(me.UserNickname),

		me.PostId,
		time.Unix(0, me.PostCreateAt*int64(1000*1000)).Format(time.RFC3339),
		postUpdateAt,
		postDeleteAt,

		me.PostRootId,
		me.PostParentId,
		me.PostOriginalId,
		cleanComplianceStrings(me.PostMessage),
		me.PostType,
		me.PostProps,
		me.PostHashtags,
		me.PostFileIds,
	}
}


text:
    <form name="newTaskForm" ng-submit="startDownload()" novalidate>

                    Links

                    Options

                        <button type="button" class="btn btn-sm btn-default dropdown-toggle" data-toggle="dropdown">

                        </button>

Open Torrent File

Open Metalink File

                        <button type="submit" class="btn btn-sm"
                                ng-class="{'btn-default': !isNewTaskValid(), 'btn-success': isNewTaskValid()}"
                                ng-disabled="!isNewTaskValid()" translate>Download Now
                        </button>
                        <button type="button" class="btn btn-sm dropdown-toggle"
                                ng-class="{'btn-default': !isNewTaskValid(), 'btn-success': isNewTaskValid()}"
                                ng-disabled="!isNewTaskValid()" data-toggle="dropdown">

                        </button>

Download Later

Export Command API

Download Links:

                                    <textarea name="urls" class="form-control" rows="10" autofocus="autofocus" ng-auto-focus ng-valid-urls
                                              ng-model="context.urls" ng-required="true" ng-keydown="urlTextboxKeyDown($event)"
                                              ng-placeholder="'Support multiple URLs, one URL per line.' | translate"></textarea>

File Name:

                                <input class="form-control" ng-value="context.uploadFile ? context.uploadFile.fileName : ''" readonly="readonly"/>

                    <input id="file-holder" type="file" style="display: none"/>

                                    Filters:

                                        <input id="optionFilterGlobal" type="checkbox" ng-model="context.optionFilter['global']"/>
                                        Global

                                        <input id="optionFilterHttp" type="checkbox" ng-model="context.optionFilter['http']"/>
                                        Http

                                        <input id="optionFilterBittorrent" type="checkbox" ng-model="context.optionFilter['bittorrent']"/>
                                        BitTorrent

                        <ng-setting ng-repeat="option in context.availableOptions" ng-if="context.optionFilter[option.category]"
                                    option="option" lazy-save-timeout="0" default-value="context.globalOptions[option.key]"
                                    on-change-value="setOption(key, value, optionStatus)"></ng-setting>

        <ng-export-command-api-dialog options="context.exportCommandApiOptions"></ng-export-command-api-dialog>
    </form>


text:
/***********************************************************************************
 * @file    video_update.h
 * @author  kzhong1991<kzhong1991@gmail.com>
 * @date    2013-03-29
 * @brief   Update the the video in main window
 ***********************************************************************************/
#ifndef VIDEO_UPDATE_H
#define VIDEO_UPDATE_H

#include <QtCore/QThread>
#include <QtGui/QImage>
#include <QtCore/QTimer>
#include <QtCore/QTime>
#include <QtCore/QObject>
#include <QtGui/QApplication>
#include <QtCore/QSemaphore>
#include <opencv2/opencv.hpp>
#include "..//video/video.h"
#include "..//video/video_frame.h"
#include "..//entry/mainWindow.h"

class videoUpdate : public QThread
{
	Q_OBJECT
public:
	videoUpdate(MainWindow * wd, Video* video, QObject* parent = 0);

	/* Convert the IplImage to QImage */
	QImage IplImageToQImage(const IplImage* iplImage);

	/* start / stop the thread */
	void go();
	void stop();

private:
	Video			*_video;
	MainWindow		*_wd;
	bool			_stop;

	QTimer			*_videoTimer;

	IplImage		*_img;

	QSemaphore		*_sem;

	bool			_videoOk;

protected:
	void run();

signals:

	/* notify video that video_update thread had stoped */
	void videoUpdateStoped();

public slots:

	/* start / stop video update thread, receive signal from video */
	void startVideoUpdate();
	void stopVideoUpdate();
};

#endif // VIDEO_UPDATE_H


text:
<?php

namespace NekoToNeko\MainBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Entity\User as BaseUser;

/**
 * User
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="NekoToNeko\MainBundle\Entity\UserRepository")
 */
class User extends BaseUser
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var string
     *
     * @ORM\Column(name="iphone_token", type="string", length=255, nullable=true)
     */
    private $iphone_token;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set iphone_token
     *
     * @param string $iphoneToken
     * @return User
     */
    public function setIphoneToken($iphoneToken)
    {
        $this->iphone_token = $iphoneToken;

        return $this;
    }

    /**
     * Get iphone_token
     *
     * @return string
     */
    public function getIphoneToken()
    {
        return $this->iphone_token;
    }
}


text:
/**
 * Created by Julian/Wolke on 07.11.2016.
 *
 */
let Manager = require('../../structures/manager');
const winston = require('winston');
let fs = require('fs');
Promise.promisifyAll(fs);
let path = require('path');
let util = require('util');
let i18next = require('i18next');
let Backend = require('i18next-node-fs-backend');
class LangManager extends Manager {
    constructor() {
        super();
        this.setMaxListeners(1);
        this.commands = {};
        this.i18next = i18next;
        this.t = null;
        this.list = null;
    }

    async init() {
        return this.load();
    }

    async load() {
        let that = this;
        let backendOptions = {
            loadPath: '../rem_translate/{{lng}}/{{ns}}.json',
            addPath: '../rem_translate/{{lng}}/{{ns}}.missing.json',
            jsonIndent: 2
        };
        let dirs = await this.getDirs('rem_translate/');
        this.list = dirs;
        return new Promise(function (resolve, reject) {
            i18next.use(Backend).init({
                backend: backendOptions,
                lng: 'en',
                fallbacklngs: false,
                preload: dirs,
                load: 'all'
            }, (err, t) => {
                if (err) {
                    winston.error('Error at i18n' + err);
                    reject(err);
                } else {
                    that.t = t;
                    resolve(t);
                }
            });
        });
    }

    async getDirs(rootDir) {
        let langPath = path.join(__dirname, `../../../${rootDir}`);
        // console.log(langPath);
        let files = await fs.readdirAsync(langPath);
        // if (err) {
        //     winston.error(err);
        //     return cb(err);
        // }
        let dirs = [];
        for (let index = 0; index < files.length; ++index) {
            let file = files[index];
            if (!file.startsWith('.')) {
                let filePath = langPath + '/' + file;
                let stat = await fs.statAsync(filePath);
                if (stat.isDirectory()) {
                    dirs.push(file);
                }
            }
        }
        return dirs;
    }

    getT() {
        return this.t;
    }

    getList() {
        return this.list;
    }

    reload() {
        this.i18next.reloadResources();
        this.i18next.on('loaded', () => {
            console.log('reloaded!');
        });
        this.i18next.on('failedLoading', () => {
            console.log('failed reload!');
        })

    }
}
module.exports = {class: LangManager, deps: [], async: true, shortcode: 'lm'};