text:
package org.apache.james.mime4j.mboxiterator;

import org.junit.Assert;
import org.junit.Test;

import java.io.*;

/**
 * Tests for {@link MboxIterator}.
 */
public class MboxIteratorTest {

    public static final String MBOX_PATH = "src/test/resources/test-1/mbox.rlug";
    private final int DEFAULT_MESSAGE_SIZE = 10 * 1024;
    // number of chars oin our largest test message
    private static final int CHARS_IN_MAX_MSG = 3500;
    private static final int MORE_THAN_FILE_SIZE = 13291;

    /**
     * Test of iterator method, of class MboxIterator.
     */
    @Test
    public void testIterator() throws FileNotFoundException, IOException {
        iterateWithMaxMessage(DEFAULT_MESSAGE_SIZE);
    }

    /**
     * Test of iterator method, of class MboxIterator.
     */
    @Test
    public void testIteratorLoop() throws FileNotFoundException, IOException {
        for (int i = CHARS_IN_MAX_MSG; i < MORE_THAN_FILE_SIZE; i++) {
            iterateWithMaxMessage(i);
        }
    }

    private void iterateWithMaxMessage(int maxMessageSize) throws IOException {
        int count = 0;
        for (CharBufferWrapper msg : MboxIterator.fromFile(MBOX_PATH).maxMessageSize(maxMessageSize).build()) {
            String message = fileToString(new File(MBOX_PATH + "-" + count));
            //MboxIterator.printCharBuffer(msg);
            Assert.assertEquals("String sizes match for file " + count, message.length(), msg.toString().length());
            Assert.assertEquals("Missmatch with file " + count, message, msg.toString());
            count++;
        }
    }

    private static String fileToString(File file) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(file));
        StringBuilder sb = new StringBuilder();
        int ch;
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        reader.close();
        return sb.toString();
    }

}

redpajama_set_name: RedPajamaGithub


text:
from ics_demo.dao.interfaces import base
from ics_demo.dao.orm.demo import Carrot, Rabbit, Corps

from ics_demo.helpers import uuidgen

def get_all():
    return base.class_get_all_to_dict(Corps)

def get_one(uuid):
    return base.class_get_one_by_uuid_to_dict(Corps, uuid)

def get_obj(uuid):
    return base.class_get_one_by_uuid_to_obj(Corps, uuid)

def get_obj_by_ID(ID):
    return base.class_get_one_by_ID_to_obj(Corps, ID)

def get_keys():
    return base.class_get_keys(Corps)


text:
1. Copy contents of WeatherComJSONMeasures.inc
2. Add `[!Update]` to the end of `@EntireSiteSuperParent`'s `FinishAction`
3. Remove all forecast measures after `today`
4. Convert Latitude, Longitude, Language, Units, and UpdateRate variables to camelCase
5. Change TimeFormat variable to `[&Measure[#timeFormat]TimeFormat]`
6. Comment out `@CurrentObservationDate` measure (unused)
7. Copy API key, common substitute, and URL variables from WeatherComJSONVariables.inc, paste at top of WeatherComJSONMeasures.inc
8. Add `; Edited by raiguard for ModernGadgets - see Conversion.md` below last edited date at top

## WeatherComJSONMoon

1. Copy contents of WeatherComJSONMoon.inc
2. Remove all but the first day
3. Change TimeFormat variable to `[&Measure[#timeFormat]TimeFormat]`
4. Add a `,"":"-----"` to `Substitute` in `@MoonDay1PhaseName`
5. Add `; Edited by raiguard for ModernGadgets - see Conversion.md` below last edited date at top

## WeatherComJSONAlerts

1. Copy contents of WeatherComJSONAlerts.inc
2. Remove all but the first alert
3. Add `; Edited by raiguard for ModernGadgets - see Conversion.md` below last edited date at top


text:
import { getBidRequest } from '../utils.js';
var CONSTANTS = require('../constants.json');
var utils = require('../utils.js');
var bidfactory = require('../bidfactory.js');
var bidmanager = require('../bidmanager.js');

var SekindoAdapter;
SekindoAdapter = function SekindoAdapter() {

  function _callBids(params) {
    var bids = params.bids;
    var bidsCount = bids.length;

    var pubUrl = null;
    if (parent !== window)
      pubUrl = document.referrer;
    else
      pubUrl = window.location.href;

    for (var i = 0; i < bidsCount; i++) {
      var bidReqeust = bids[i];
      var callbackId = bidReqeust.bidId;
      _requestBids(bidReqeust, callbackId, pubUrl);
      //store a reference to the bidRequest from the callback id
      //bidmanager.pbCallbackMap[callbackId] = bidReqeust;
    }
  }

  $$PREBID_GLOBAL$$.sekindoCB = function(callbackId, response) {
    var bidObj = getBidRequest(callbackId);
    if (typeof (response) !== 'undefined' && typeof (response.cpm) !== 'undefined') {
      var bid = [];
      if (bidObj) {
        var bidCode = bidObj.bidder;
        var placementCode = bidObj.placementCode;

        if (response.cpm !== undefined && response.cpm > 0) {

          bid = bidfactory.createBid(CONSTANTS.STATUS.GOOD);
          bid.adId = response.adId;
          bid.callback_uid = callbackId;
          bid.bidderCode = bidCode;
          bid.creative_id = response.adId;
          bid.cpm = parseFloat(response.cpm);
          bid.ad = response.ad;
          bid.width = response.width;
          bid.height = response.height;

          bidmanager.addBidResponse(placementCode, bid);
        }

        else {
          bid = bidfactory.createBid(CONSTANTS.STATUS.NO_BID);
          bid.callback_uid = callbackId;
          bid.bidderCode = bidCode;
          bidmanager.addBidResponse(placementCode, bid);
        }
      }
    }

    else {
      if (bidObj) {
        utils.logMessage('No prebid response for placement '+bidObj.placementCode);
      }

      else {
        utils.logMessage('sekindo callback general error');
      }
    }
  };

  function _requestBids(bid, callbackId, pubUrl) {
    //determine tag params
    var spaceId = utils.getBidIdParamater('spaceId', bid.params);
    var bidfloor = utils.getBidIdParamater('bidfloor', bid.params);
    var protocol = ('https:' === document.location.protocol ? 's' : '');
    var scriptSrc = 'https://live.sekindo.com/live/liveView.php?';

    scriptSrc = utils.tryAppendQueryString(scriptSrc, 's', spaceId);
    scriptSrc = utils.tryAppendQueryString(scriptSrc, 'pubUrl', pubUrl);
    scriptSrc = utils.tryAppendQueryString(scriptSrc, 'hbcb', callbackId);
    scriptSrc = utils.tryAppendQueryString(scriptSrc, 'dcpmflr', bidfloor);
    scriptSrc = utils.tryAppendQueryString(scriptSrc, 'hbto', $$PREBID_GLOBAL$$.bidderTimeout);
    scriptSrc = utils.tryAppendQueryString(scriptSrc, 'protocol', protocol);

    var html = '<scr'+'ipt type="text/javascript" src="'+scriptSrc+'"></scr'+'ipt>';

    var iframe = utils.createInvisibleIframe();
    iframe.id = 'skIfr_'+callbackId;

    var elToAppend = document.getElementsByTagName('head')[0];
    //insert the iframe into document
    elToAppend.insertBefore(iframe, elToAppend.firstChild);

    var iframeDoc = utils.getIframeDocument(iframe);
    iframeDoc.open();
    iframeDoc.write(html);
    iframeDoc.close();
  }

  return {
    callBids: _callBids
  };
};

module.exports = SekindoAdapter;


text:
<?xml version="1.0" encoding="utf-8"?>

  <title>
    System Properties
  </title>

    <title> Explanation of System properties used in Qpid </title>

    <para>
      This page documents the various System Properties that are
      currently used in the Qpid Java code base.
    </para>

      <title> Client Properties </title>

      <variablelist>
	<varlistentry>
	  <term>STRICT_AMQP</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Type</term>
		<listitem><para>Boolean</para></listitem>
	      </varlistentry>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>FALSE</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para> This forces the client to only send AMQP compliant
	    frames. This will disable a number of JMS features.</para>

          <itemizedlist>
	  <title> Features disabled by STRICT_AMQP</title>
            <listitem><para>Queue Browser
            </para></listitem>
            <listitem><para>Message Selectors
            </para></listitem>
            <listitem><para>Durable Subscriptions
            </para></listitem>
            <listitem><para>Session Recover may result in duplicate message delivery
            </para></listitem>
            <listitem><para>Destination validation, so no InvalidDestinationException
            will be thrown
            </para></listitem>
          </itemizedlist>
	  <para>
            This is associated with property <xref linkend="SystemProperties-STRICTAMQPFATAL"/>
          </para>
	  </listitem>
	</varlistentry>

	<varlistentry id="SystemProperties-STRICTAMQPFATAL">
	  <term>STRICT_AMQP_FATAL</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Type</term>
		<listitem><para>Boolean</para></listitem>
	      </varlistentry>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>FALSE</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>
	      This will cause any attempt to utilise an enhanced feature to
	      throw and UnsupportedOperationException. When set to false then
	      the exception will not occur but the feature will be disabled.
	    </para>
	    <para>
	      e.g.
	      The Queue Browser will always show no messages.
	      Any message selector will be removed.
	    </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>IMMEDIATE_PREFETCH</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Type</term>
		<listitem><para>Boolean</para></listitem>
	      </varlistentry>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>FALSE</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>
	      The default with AMQP is to start prefetching messages. However,
	      with certain 3rd party Java tools, such as Mule this can cause a
	      problem. Mule will create a consumer but never consume from it so
	      any any prefetched messages will be stuck until that session is
	      closed. This property is used to re-instate the default AMQP
	      behaviour. The default Qpid behaviour is to prevent prefetch
	      occurring, by starting the connection Flow Controlled, until a
	      request for a message is made on the consumer either via a
            receive() or setting a message listener.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>qpid.sync_op_timeout</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Type</term>
		<listitem><para>long</para></listitem>
	      </varlistentry>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>60000</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>The length of time (in milliseconds) to wait for a synchronous operation to complete.
                  For compatibility with older	clients, the synonym amqj.default_syncwrite_timeout is supported.</para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>amq.dynamicsaslregistrar.properties</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Type</term>
		<listitem><para>String</para></listitem>
	      </varlistentry>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>org/apache/qpid/client/security/DynamicSaslRegistrar.properties</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>The name of the SASL configuration properties file.
	    </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>amqj.heartbeat.timeoutFactor</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Type</term>
		<listitem><para>float</para></listitem>
	      </varlistentry>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>2.0</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>
            The factor used to get the timeout from the delay between
            heartbeats
            </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>amqj.tcp_nodelay</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Type</term>
		<listitem><para>Boolean</para></listitem>
	      </varlistentry>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>TRUE</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para> Disable Nagle's algorithm on the TCP connection.
	    </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>amqj.protocol.logging.level</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Type</term>
		<listitem><para>Boolean</para></listitem>
	      </varlistentry>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>null</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>If set this will turn on protocol logging on the
	    client. </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>jboss.host</term>
	  <listitem>
	    <para>
            Used by the JBossConnectionFactoryInitialiser to specify the host
            to connect to perform JNDI lookups.
            </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>jboss.port</term>
	  <listitem>
	    <para>
            Used by the JBossConnectionFactoryInitialiser to specify the port
            to connect to perform JNDI lookups.
            </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>amqj.MaximumStateWait</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>30000</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>
	      Used to set the maximum time the State Manager should wait before
	      timing out a frame wait.
            </para>
	  </listitem>
	</varlistentry>
      </variablelist>

      <title>
	Management Properties
      </title>

      <variablelist>
	<varlistentry>
	  <term>security</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>null</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>
	      String representing the Security level to be used to on
	      the connection to the broker. The null default results
	      in no security or PLAIN. When used with jmxconnector
	      'javax.management.remote.jmxmp.JMXMPConnector' a
	      security value of 'CRAM-MD5' will result in all
	      communication to the broker being encrypted.
            </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>jmxconnector</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>null</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>
	      String representing the JMXConnector class used to
	      perform the connection to the broker. The null default
	      results in the standard JMX connector. Utilising
	      'javax.management.remote.jmxmp.JMXMPConnector' and
	      security 'CRAM-MD5' will result in all communication to
	      the broker being encrypted.
            </para>
	  </listitem>
	</varlistentry>

	<varlistentry>
	  <term>timeout</term>
	  <listitem>
	    <variablelist>
	      <varlistentry>
		<term>Default</term>
		<listitem><para>5000</para></listitem>
	      </varlistentry>
	    </variablelist>
	    <para>
	      Long value representing the milli seconds before
	      connection to the broker should timeout.
            </para>
	  </listitem>
	</varlistentry>

      </variablelist>

      <title> Properties used in Examples </title>

      <variablelist>
	<varlistentry>
	  <term>archivepath</term>
	  <listitem>
	    <para>
	      Used in <filename>FileMessageDispatcher</filename>. This
	      properties specifies the directory to move payload
	      file(s) to archive location as no error</para>
	  </listitem>
	</varlistentry>
      </variablelist>


text:
/* The file is part of Snowman decompiler. */
/* See doc/licenses.asciidoc for the licensing information. */

/* * SmartDec decompiler - SmartDec is a native code to C/C++ decompiler
 * Copyright (C) 2015 Alexander Chernov, Katerina Troshina, Yegor Derevenets,
 * Alexander Fokin, Sergey Levin, Leonid Tsvetkov
 *
 * This file is part of SmartDec decompiler.
 *
 * SmartDec decompiler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * SmartDec decompiler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SmartDec decompiler.  If not, see <http://www.gnu.org/licenses/>.
 */

#pragma once

#include <nc/config.h>

namespace nc {
namespace core {
namespace ir {

class Jump;
class JumpTarget;
class Term;

namespace dflow {

class Dataflow;

/**
 * \param[in] term      Valid pointer to a term.
 * \param[in] dataflow  Dataflow information.
 *
 * \return Valid pointer to the term being the first copy of the given one.
 */
const ir::Term *getFirstCopy(const Term *term, const Dataflow &dataflow);

/**
 * \param[in] jump      Valid pointer to a jump.
 * \param[in] dataflow  Dataflow information.
 *
 * \return True iff the jump has a jump target being a return address.
 */
bool isReturn(const Jump *jump, const Dataflow &dataflow);

/**
 * \param[in] target    Jump target.
 * \param[in] dataflow  Dataflow information.
 *
 * \return True iff the jump target is a return address.
 */
bool isReturnAddress(const JumpTarget &target, const Dataflow &dataflow);

/**
 * \param[in] term      Valid pointer to a term.
 * \param[in] dataflow  Dataflow information.
 *
 * \return True iff the term contains a return address.
 */
bool isReturnAddress(const Term *term, const Dataflow &dataflow);

} // namespace dflow
} // namespace ir
} // namespace core
} // namespace nc

/* vim:set et sts=4 sw=4: */


text:
require 'rails_helper'

module Ecm::References
  describe ReferencesController do
    it 'routes to #index' do
      get('/en/references').should route_to('ecm/references/references#index', locale: 'en')
    end # it

    it 'routes to #show' do
      get('/en/references/example-reference').should route_to(
        'ecm/references/references#show',
        locale: 'en',
        id: 'example-reference'
      )
    end # it
  end # describe ReferencesController
end # module Ecm::References


text:
package com.herohuang.doctor.service;

public interface CanalService {
	void startBinlog() throws Exception;
}


text:
import re

regex = re.compile(r'^()$', re.MULTILINE)

with open('psiturk/default_configs/local_config_defaults.txt', 'r') as f:
    lines = f.readlines()

new_lines = []
line_num = 0
for line in lines:
    if line_num == 2:
        line = (
            f'# Example config file. Uncomment lines (remove the `;`)\n'
            f'# in order to override defaults.\n'
        )
    if len(line) > 1 and line[0] not in ['#', '[', ';']:  # every line will have at least an \n char
        line = f';{line}'
    new_lines.append(line)
    line_num += 1

with open('psiturk/example/config.txt.sample', 'w') as f:
    f.writelines(new_lines)


text:
package org.mifos.framework.util.helpers;

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

import org.mifos.accounts.business.AccountBO;
import org.mifos.accounts.business.AccountFeesEntity;
import org.mifos.accounts.business.AccountStateEntity;
import org.mifos.accounts.exceptions.AccountException;
import org.mifos.accounts.fees.business.AmountFeeBO;
import org.mifos.accounts.fund.business.FundBO;
import org.mifos.accounts.fund.persistence.FundDao;
import org.mifos.accounts.loan.business.LoanBO;
import org.mifos.accounts.loan.persistance.LoanDao;
import org.mifos.accounts.penalties.business.PenaltyBO;
import org.mifos.accounts.penalties.persistence.PenaltyDao;
import org.mifos.accounts.productdefinition.business.LoanOfferingBO;
import org.mifos.accounts.productdefinition.business.PrdOfferingBO;
import org.mifos.accounts.productdefinition.business.ProductTypeEntity;
import org.mifos.accounts.productdefinition.business.SavingsOfferingBO;
import org.mifos.accounts.productdefinition.persistence.LoanProductDao;
import org.mifos.accounts.productdefinition.persistence.SavingsProductDao;
import org.mifos.accounts.savings.business.SavingsBO;
import org.mifos.accounts.savings.persistence.GenericDao;
import org.mifos.accounts.savings.persistence.SavingsDao;
import org.mifos.accounts.util.helpers.AccountState;
import org.mifos.accounts.util.helpers.PaymentData;
import org.mifos.application.holiday.business.Holiday;
import org.mifos.application.holiday.business.HolidayBO;
import org.mifos.application.holiday.business.service.HolidayService;
import org.mifos.application.holiday.persistence.HolidayDao;
import org.mifos.application.master.business.FundCodeEntity;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.servicefacade.ApplicationContextProvider;
import org.mifos.application.servicefacade.LoanAccountServiceFacade;
import org.mifos.clientportfolio.newloan.applicationservice.CreateLoanAccount;
import org.mifos.clientportfolio.newloan.applicationservice.LoanAccountCashFlow;
import org.mifos.core.MifosRuntimeException;
import org.mifos.customers.api.CustomerLevel;
import org.mifos.customers.business.CustomerBO;
import org.mifos.customers.business.CustomerLevelEntity;
import org.mifos.customers.business.CustomerStatusEntity;
import org.mifos.customers.business.service.CustomerService;
import org.mifos.customers.center.business.CenterBO;
import org.mifos.customers.checklist.business.AccountCheckListBO;
import org.mifos.customers.checklist.business.CustomerCheckListBO;
import org.mifos.customers.client.business.ClientBO;
import org.mifos.customers.exceptions.CustomerException;
import org.mifos.customers.group.business.GroupBO;
import org.mifos.customers.office.business.OfficeBO;
import org.mifos.customers.office.persistence.OfficeDao;
import org.mifos.customers.office.persistence.OfficePersistence;
import org.mifos.customers.persistence.CustomerDao;
import org.mifos.customers.persistence.CustomerPersistence;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.personnel.persistence.PersonnelDao;
import org.mifos.customers.personnel.util.helpers.PersonnelConstants;
import org.mifos.customers.util.helpers.CustomerStatus;
import org.mifos.domain.builders.OfficeBuilder;
import org.mifos.domain.builders.SavingsProductBuilder;
import org.mifos.dto.domain.HolidayDetails;
import org.mifos.dto.screen.LoanCreationResultDto;
import org.mifos.framework.TestUtils;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.platform.questionnaire.service.QuestionGroupDetail;
import org.mifos.security.util.UserContext;

/**
 *
 */
public class IntegrationTestObjectMother {

    private static final String INTEGRATION_TEST_DATA_MISSING_MESSAGE = "This should exist within database for integration tests but does not.";

    // user
    private static final Short DEFAULT_INTEGRATION_TEST_USER = PersonnelConstants.TEST_USER;
    private static PersonnelBO testUser = null;
    private static PersonnelBO systemUser = null;

    // office
    public static final Short SAMPLE_BRANCH_OFFICE = 3;
    private static OfficeBO sampleBranchOffice = null;

    // serviceFacades
    private static final LoanAccountServiceFacade loanAccountServiceFacade = ApplicationContextProvider.getBean(LoanAccountServiceFacade.class);

    // DAO's for fetching existing data within database
    private static final OfficePersistence officePersistence = new OfficePersistence();
    private static final OfficeDao officeDao = ApplicationContextProvider.getBean(OfficeDao.class);
    private static final HolidayDao holidayDao = ApplicationContextProvider.getBean(HolidayDao.class);
    private static final PenaltyDao penaltyDao = ApplicationContextProvider.getBean(PenaltyDao.class);
    private static final FundDao fundDao = ApplicationContextProvider.getBean(FundDao.class);
    private static final SavingsDao savingsDao = ApplicationContextProvider.getBean(SavingsDao.class);
    private static final LoanProductDao loanProductDao = ApplicationContextProvider.getBean(LoanProductDao.class);
    private static final SavingsProductDao savingsProductDao = ApplicationContextProvider.getBean(SavingsProductDao.class);
    private static final CustomerDao customerDao = ApplicationContextProvider.getBean(CustomerDao.class);
    private static final LoanDao loanDao = ApplicationContextProvider.getBean(LoanDao.class);
    private static final PersonnelDao personnelDao = ApplicationContextProvider.getBean(PersonnelDao.class);
    private static final CustomerPersistence customerPersistence = new CustomerPersistence();

    private static final CustomerService customerService = ApplicationContextProvider.getBean(CustomerService.class);
    private static final HolidayService holidayService = ApplicationContextProvider.getBean(HolidayService.class);
    private static final GenericDao genericDao = ApplicationContextProvider.getBean(GenericDao.class);

    public static OfficeBO sampleBranchOffice() {
        if (sampleBranchOffice == null) {
            try {
                sampleBranchOffice = officePersistence.getOffice(SAMPLE_BRANCH_OFFICE);
                StaticHibernateUtil.flushAndClearSession();
            } catch (PersistenceException e) {
                throw new IllegalStateException("Office with id [" + SAMPLE_BRANCH_OFFICE + "]. "
                        + INTEGRATION_TEST_DATA_MISSING_MESSAGE);
            }
        }
        return sampleBranchOffice;
    }

    public static PersonnelBO testUser() {
        if (testUser == null) {
            try {
                testUser = personnelDao.findPersonnelById(DEFAULT_INTEGRATION_TEST_USER);
            } catch (Exception e) {
                throw new IllegalStateException("PersonnelBO with id [" + DEFAULT_INTEGRATION_TEST_USER + "]. "
                        + INTEGRATION_TEST_DATA_MISSING_MESSAGE);
            }
        }

        return testUser;
    }

    public static PersonnelBO systemUser() {
        if (systemUser == null) {
            try {
                systemUser = personnelDao.findPersonnelById(PersonnelConstants.SYSTEM_USER);
            } catch (Exception e) {
                throw new IllegalStateException("PersonnelBO with id [" + PersonnelConstants.SYSTEM_USER + "]. "
                        + INTEGRATION_TEST_DATA_MISSING_MESSAGE);
            }
        }

        return systemUser;
    }

    public static MeetingBO getMeeting(Integer meetingId) throws PersistenceException {
        return customerPersistence.getPersistentObject(MeetingBO.class, meetingId);
    }

    public static void saveMeeting(final MeetingBO meeting) {
        try {
            customerPersistence.createOrUpdate(meeting);
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveCustomer(final CustomerBO center) {
        try {
//            StaticHibernateUtil.startTransaction();
            customerPersistence.saveCustomer(center);
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //    public static void cleanCustomerHierarchyWithMultipleClientsMeetingsAndFees(final ClientBO activeClient,
//            final ClientBO inActiveClient, final GroupBO group, final CustomerBO center, final MeetingBO weeklyMeeting) {
//        try {
//            TestObjectFactory.cleanUp(activeClient);
//            TestObjectFactory.cleanUp(inActiveClient);
//            group = null;
//            center = null;
//            TestObjectFactory.cleanUp(weeklyMeeting);
//        } finally {
//            StaticHibernateUtil.flushSession();
//        }
//    }

    public static void cleanCustomerHierarchyWithMeeting(final ClientBO client, final GroupBO group,
            final CustomerBO center, final MeetingBO weeklyMeeting) {
        try {
//            client = null;
//            group = null;
//            center = null;
//            TestObjectFactory.cleanUp(weeklyMeeting);
        } finally {
            StaticHibernateUtil.flushSession();
        }
    }

    public static void saveSavingsProductAndAssociatedSavingsAccounts(final SavingsOfferingBO savingsProduct,
            final SavingsBO... relatedSavingsAccounts) {
        try {
            customerPersistence.createOrUpdate(savingsProduct);
            for (SavingsBO savingAccount : relatedSavingsAccounts) {
                customerPersistence.createOrUpdate(savingAccount);
            }
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void cleanSavingsProductAndAssociatedSavingsAccounts(final SavingsBO... savingsAccount) {

        try {
//            for (SavingsBO savingsBO : savingsAccount) {
//                savingsBO = null;
//            }
        } finally {
            StaticHibernateUtil.flushSession();
        }
    }

    public static void saveLoanProducts(final LoanOfferingBO... loanProducts) {
        try {
            for (LoanOfferingBO loanProduct : loanProducts) {
                customerPersistence.createOrUpdate(loanProduct);
            }
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveSavingsProducts(final SavingsOfferingBO... savingsProducts) {
        try {
            for (SavingsOfferingBO savingsProduct : savingsProducts) {
                savingsProductDao.save(savingsProduct);
            }
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void createSavingsProduct(SavingsProductBuilder savingsProductBuilder) {
        SavingsOfferingBO savingsProduct = savingsProductBuilder.buildForIntegrationTests();
        try {
            StaticHibernateUtil.startTransaction();
            savingsProductDao.save(savingsProduct);
            StaticHibernateUtil.commitTransaction();
        } catch (Exception e) {
            StaticHibernateUtil.rollbackTransaction();
            throw new RuntimeException(e);
        } finally {
            StaticHibernateUtil.closeSession();
        }
    }

    public static void createCenter(CenterBO center, MeetingBO meeting) {
        UserContext userContext = TestUtils.makeUser();
        center.setUserContext(userContext);

        List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>();

        customerService.createCenter(center, meeting, accountFees);
        StaticHibernateUtil.flushAndClearSession();
    }

    public static void createCenter(CenterBO center, MeetingBO meeting, AmountFeeBO fee) {

        UserContext userContext = TestUtils.makeUser();
        center.setUserContext(userContext);

        AccountFeesEntity accountFee = new AccountFeesEntity(null, fee, fee.getFeeAmount().getAmountDoubleValue());

        List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>();
        accountFees.add(accountFee);

            customerService.createCenter(center, meeting, accountFees);
    }

    public static void createCenter(CenterBO center, MeetingBO meeting, AmountFeeBO...fees) {

        UserContext userContext = TestUtils.makeUser();
        center.setUserContext(userContext);

        List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>();
        for (AmountFeeBO fee : fees) {
            AccountFeesEntity accountFee = new AccountFeesEntity(null, fee, fee.getFeeAmount().getAmountDoubleValue());
            accountFees.add(accountFee);
        }

        customerService.createCenter(center, meeting, accountFees);
    }

    public static void createGroup(GroupBO group, MeetingBO meeting) {

        UserContext userContext = TestUtils.makeUser();
        group.setUserContext(userContext);

        List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>();

        try {
            customerService.createGroup(group, meeting, accountFees);
        } catch (CustomerException e) {
            throw new RuntimeException(e);
        }
    }

    public static void createGroup(GroupBO group, MeetingBO meeting, AmountFeeBO fee) throws CustomerException {

        UserContext userContext = TestUtils.makeUser();
        group.setUserContext(userContext);

        AccountFeesEntity accountFee = new AccountFeesEntity(null, fee, fee.getFeeAmount().getAmountDoubleValue());

        List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>();
        accountFees.add(accountFee);

        customerService.createGroup(group, meeting, accountFees);
    }

    public static void createClient(ClientBO client, MeetingBO meeting) throws CustomerException {
        UserContext userContext = TestUtils.makeUser();
        client.setUserContext(userContext);

        List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>();
        List<SavingsOfferingBO> selectedOfferings = new ArrayList<SavingsOfferingBO>();

        customerService.createClient(client, meeting, accountFees, selectedOfferings);
    }

    public static void createClient(ClientBO client, MeetingBO meeting, SavingsOfferingBO savingsProduct) throws CustomerException {
        UserContext userContext = TestUtils.makeUser();
        client.setUserContext(userContext);

        List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>();
        List<SavingsOfferingBO> selectedOfferings = new ArrayList<SavingsOfferingBO>();
        selectedOfferings.add(savingsProduct);

        customerService.createClient(client, meeting, accountFees, selectedOfferings);
    }

    public static void createClient(ClientBO client, MeetingBO meeting, AmountFeeBO fee) throws CustomerException {

        UserContext userContext = TestUtils.makeUser();
        client.setUserContext(userContext);

        AccountFeesEntity accountFee = new AccountFeesEntity(null, fee, fee.getFeeAmount().getAmountDoubleValue());

        List<AccountFeesEntity> accountFees = new ArrayList<AccountFeesEntity>();
        accountFees.add(accountFee);

        List<SavingsOfferingBO> selectedOfferings = new ArrayList<SavingsOfferingBO>();

        customerService.createClient(client, meeting, accountFees, selectedOfferings);
    }

    public static void saveFee(AmountFeeBO fee) {
        try {
//            StaticHibernateUtil.startTransaction();
            customerPersistence.createOrUpdate(fee);
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void createProduct(PrdOfferingBO product) {
        try {
//            StaticHibernateUtil.startTransaction();
            customerPersistence.createOrUpdate(product);
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveLoanAccount(LoanBO loanAccount) {
        try {
            loanAccount.save();
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void saveSavingsAccount(SavingsBO savingsAccount) {
        try {
            savingsAccount.save();
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void update(CustomerBO customer) {
        try {
            new CustomerPersistence().createOrUpdate(customer);
            StaticHibernateUtil.flushSession();
          } catch (Exception e) {
              throw new RuntimeException(e);
          }
    }

    /**
     * remove and use {@link IntegrationTestObjectMother#createHoliday(HolidayDetails, List)}
     */
    @Deprecated
    public static void saveHoliday (Holiday holiday) {
        try {
//            StaticHibernateUtil.startTransaction();
            genericDao.createOrUpdate(holiday);
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new MifosRuntimeException(e);
        }
    }

    public static void createPersonnel(PersonnelBO personnel) {
        try {
            StaticHibernateUtil.startTransaction();
            personnelDao.save(personnel);
            StaticHibernateUtil.commitTransaction();
        } catch (Exception e) {
            StaticHibernateUtil.rollbackTransaction();
            throw new MifosRuntimeException(e);
        }
    }

    public static void createHoliday(HolidayDetails holidayDetails, List<Short> officeIds) {
        holidayService.create(holidayDetails, officeIds);
    }

    public static OfficeBO findOfficeById(Short officeId) {
        return officeDao.findOfficeById(officeId);
    }

    public static HolidayBO findHolidayById(Integer id) {
        return holidayDao.findHolidayById(id);
    }

    public static void createOffice(OfficeBO office) {
        try {
//            StaticHibernateUtil.startTransaction();
            customerPersistence.createOrUpdate(office);
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void createOffice(OfficeBuilder officeBuilder) {
        try {
//            StaticHibernateUtil.startTransaction();
            customerPersistence.createOrUpdate(officeBuilder.build());
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static PenaltyBO createPenalty(PenaltyBO penalty) throws Exception {
        try {
            penaltyDao.save(penalty);
            StaticHibernateUtil.flushSession();
            return penalty;
        } catch (Exception e) {
            throw new MifosRuntimeException(e.getMessage(), e);
        }
    }

    public static FundBO createFund(FundBO fund) throws Exception {
        try {
            fundDao.save(fund);
            StaticHibernateUtil.flushSession();
            return fund;
        } catch (Exception e) {
            throw new MifosRuntimeException(e.getMessage(), e);
        }
    }

    public static void createFundCode(FundCodeEntity fundCode) {
        try {
            customerPersistence.createOrUpdate(fundCode);
            StaticHibernateUtil.flushSession();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static FundBO findFundByName(final String fundName) {
        return fundDao.findByName(fundName);
    }

    public static SavingsBO findSavingsAccountById(Long savingsId) {
        return savingsDao.findById(savingsId);
    }

    public static CustomerBO findCustomerById(Integer customerId) {
        return customerDao.findCustomerById(customerId);
    }

    public static LoanBO findLoanBySystemId(String globalAccountNum) {
        return loanDao.findByGlobalAccountNum(globalAccountNum);
    }

    public static PersonnelBO findPersonnelById(Short personnelId) {
        return personnelDao.findPersonnelById(personnelId);
    }

    public static void applyAccountPayment(AccountBO loan, PaymentData paymentData) {

        try {
            StaticHibernateUtil.startTransaction();
            loan.applyPayment(paymentData);
            StaticHibernateUtil.commitTransaction();
        } catch (AccountException e) {
            StaticHibernateUtil.rollbackTransaction();
            throw new RuntimeException(e);
        } finally {
            StaticHibernateUtil.closeSession();
        }

    }

    public static CustomerCheckListBO createCustomerChecklist(Short customerLevel, Short customerStatus, Short checklistStatus, List<String> details) {

        try {
            StaticHibernateUtil.startTransaction();
            CustomerLevelEntity customerLevelEntity = new CustomerLevelEntity(CustomerLevel.getLevel(customerLevel));
            CustomerStatusEntity customerStatusEntity = new CustomerStatusEntity(CustomerStatus.fromInt(customerStatus));
            CustomerCheckListBO customerChecklist = new CustomerCheckListBO(customerLevelEntity, customerStatusEntity,
                    "productchecklist", checklistStatus, details, Short.valueOf("1"), PersonnelConstants.SYSTEM_USER);

            customerDao.save(customerChecklist);
            StaticHibernateUtil.commitTransaction();
            return customerChecklist;
        } catch (Exception e) {
            StaticHibernateUtil.rollbackTransaction();
            throw new RuntimeException(e);
        } finally {
            StaticHibernateUtil.closeSession();
        }
    }

    public static AccountCheckListBO createAccountChecklist(Short prdTypeId, AccountState accountState,
            Short checklistStatus, List<String> details) {
        try {
            StaticHibernateUtil.startTransaction();
            ProductTypeEntity productTypeEntity = (ProductTypeEntity) StaticHibernateUtil.getSessionTL().get(
                    ProductTypeEntity.class, prdTypeId);
            AccountStateEntity accountStateEntity = new AccountStateEntity(accountState);
            AccountCheckListBO accountChecklist = new AccountCheckListBO(productTypeEntity, accountStateEntity,
                    "productchecklist", checklistStatus, details, Short.valueOf("1"), PersonnelConstants.SYSTEM_USER);

            customerDao.save(accountChecklist);
            StaticHibernateUtil.commitTransaction();
            return accountChecklist;
        } catch (Exception e) {
            StaticHibernateUtil.rollbackTransaction();
            throw new RuntimeException(e);
        } finally {
            StaticHibernateUtil.closeSession();
        }

    }

    public static LoanOfferingBO findLoanProductBySystemId(String globalPrdOfferingNum) {

        return loanProductDao.findBySystemId(globalPrdOfferingNum);
    }

    public static LoanBO createClientLoan(CreateLoanAccount createLoanAccount) {

        List<QuestionGroupDetail> questionGroups = new ArrayList<QuestionGroupDetail>();
        LoanAccountCashFlow loanAccountCashFlow = null;

        LoanCreationResultDto result = loanAccountServiceFacade.createLoan(createLoanAccount, questionGroups, loanAccountCashFlow);
        return loanDao.findByGlobalAccountNum(result.getGlobalAccountNum());
    }
}


text:
package org.kuali.kfs.module.cg.service;

import org.kuali.kfs.module.cg.businessobject.Agency;

/**
 * Services for Agency
 */
public interface AgencyService {

    /**
     * Finds a Agency by agency number.
     *
     * @param agencyNumber the primary key of the Agency to get
     * @return the corresponding Agency, or null if none
     */
    public Agency getByPrimaryId(String agencyNumber);
}


text:
template <typename T>
class QuickSort : public IndexedSort<T>
{
private:
	int getPivot(Indexed<T> &data, int start_bound, int end_bound)
	{
		//assume best pivot is the starting index
		int pivot_index = start_bound;
		int mid_point = ((end_bound - start_bound) / 2) + start_bound;
		T start_value = data.getElementAt(start_bound);
		T mid_value = data.getElementAt(mid_point);
		T end_value = data.getElementAt(end_bound);

		//is the middle the best pivot?
		if (mid_value > start_value && mid_value < end_value)
		{
			pivot_index = mid_point;
		}
		else if (mid_value < start_value && mid_value > end_value)
		{
			pivot_index = mid_point;
		}

		//is end the best pivot?
		if (end_value > start_value && end_value < mid_value)
		{
			pivot_index = end_bound;
		}
		else if (end_value < start_value && end_value > mid_value)
		{
			pivot_index = end_bound;
		}
		return pivot_index;
	}
	void swap(Indexed<T> &data, int from, int to)
	{
		T temp = data.getElementAt(from);
		data.setElementAt(data.getElementAt(to), from);
		data.setElementAt(temp, to);
	}
	int findSmallerThan(Indexed<T> &data, T to_compare, int start_bound, int end_bound)
	{
		for (int i = end_bound; i >= start_bound; i--)
		{
			if (data.getElementAt(i) < to_compare)
			{
				return i;
			}
		}
		return start_bound - 1;

	}
	int findGreaterThan(Indexed<T> &data, T to_compare, int start_bound, int end_bound)
	{
		for (int i = start_bound; i <= end_bound; i++)
		{
			if (data.getElementAt(i) > to_compare)
			{
				return i;
			}
		}
		return end_bound + 1;
	}

	void sortHelper(Indexed<T> &data, int start_bound, int end_bound)
	{
        //base case not reached?
        if (end_bound - start_bound > 30)
        {
            //find the pivot
            int pivot = getPivot(data, start_bound, end_bound);
            T& pivot_value = data.getElementAt(pivot);

            //swap pivot with last element in array
            swap(data, pivot, end_bound);

            //set up i and j
            int i = start_bound;
            int j = end_bound - 1;

            //go until I and J cross
            while (i < j)
            {
                i = findGreaterThan(data, pivot_value, i, j);
                j = findSmallerThan(data, pivot_value, i, j);

                //are we not at the end?  If not, swap
                if (i < j)
                {
                    swap(data, i, j);
                }
            }

            //after loop, I must equal J.  Put pivot back.
            swap(data, i, end_bound);

            //recursive call
            if (start_bound < i - 1)
            {
                sortHelper(data, start_bound, i - 1);
            }
            if(end_bound > i + 1)
            {
                sortHelper(data, i + 1, end_bound);
            }
        }
        else
        {
            insertionSort(data, start_bound, end_bound);
        }
	}

	void insertionSort(Indexed<T> &data, int start_bound, int end_bound)
	{
        //we're starting at 1 becaues an array of size 1 (element 0) is
        //by definition sorted
        for (int i = start_bound + 1; i < end_bound; i++)
        {
            for (int j = i; j > 0; j--)
            {
                //out of order, swap
                if (data.getElementAt(j) < data.getElementAt(j - 1))
                {
                    T temp = data.getElementAt(j);
                    data.getElementAt(j) = data.getElementAt(j - 1);
                    data.getElementAt(j - 1) = temp;
                }
                else
                {
                    //no more comparisons to be made on this J loop
                    break;
                }
            }
        }
	}

public:
	virtual Indexed<T>& sort(Indexed<T>& data)
	{
		sortHelper(data, 0, data.getSize() - 1);
		return data;
	}

};

#endif


text:
import os
import io
import sys
import time
import platform
import typing as T
from contextlib import contextmanager
from pathlib import Path

if T.TYPE_CHECKING:
    from ._typing import StringProtocol

"""This is (mostly) a standalone module used to write logging
information about Meson runs. Some output goes to screen,
some to logging dir and some goes to both."""

def _windows_ansi() -> bool:
    # windll only exists on windows, so mypy will get mad
    from ctypes import windll, byref  # type: ignore
    from ctypes.wintypes import DWORD

    kernel = windll.kernel32
    stdout = kernel.GetStdHandle(-11)
    mode = DWORD()
    if not kernel.GetConsoleMode(stdout, byref(mode)):
        return False
    # ENABLE_VIRTUAL_TERMINAL_PROCESSING == 0x4
    # If the call to enable VT processing fails (returns 0), we fallback to
    # original behavior
    return bool(kernel.SetConsoleMode(stdout, mode.value | 0x4) or os.environ.get('ANSICON'))

def colorize_console() -> bool:
    _colorize_console = getattr(sys.stdout, 'colorize_console', None)  # type: bool
    if _colorize_console is not None:
        return _colorize_console

    try:
        if platform.system().lower() == 'windows':
            _colorize_console = os.isatty(sys.stdout.fileno()) and _windows_ansi()
        else:
            _colorize_console = os.isatty(sys.stdout.fileno()) and os.environ.get('TERM', 'dumb') != 'dumb'
    except Exception:
        _colorize_console = False

    sys.stdout.colorize_console = _colorize_console  # type: ignore[attr-defined]
    return _colorize_console

def setup_console() -> None:
    # on Windows, a subprocess might call SetConsoleMode() on the console
    # connected to stdout and turn off ANSI escape processing. Call this after
    # running a subprocess to ensure we turn it on again.
    if platform.system().lower() == 'windows':
        try:
            delattr(sys.stdout, 'colorize_console')
        except AttributeError:
            pass

log_dir = None               # type: T.Optional[str]
log_file = None              # type: T.Optional[T.TextIO]
log_fname = 'meson-log.txt'  # type: str
log_depth = []               # type: T.List[str]
log_timestamp_start = None   # type: T.Optional[float]
log_fatal_warnings = False   # type: bool
log_disable_stdout = False   # type: bool
log_errors_only = False      # type: bool
_in_ci = 'CI' in os.environ  # type: bool
_logged_once = set()         # type: T.Set[T.Tuple[str, ...]]
log_warnings_counter = 0     # type: int

def disable() -> None:
    global log_disable_stdout
    log_disable_stdout = True

def enable() -> None:
    global log_disable_stdout
    log_disable_stdout = False

def set_quiet() -> None:
    global log_errors_only
    log_errors_only = True

def set_verbose() -> None:
    global log_errors_only
    log_errors_only = False

def initialize(logdir: str, fatal_warnings: bool = False) -> None:
    global log_dir, log_file, log_fatal_warnings
    log_dir = logdir
    log_file = open(os.path.join(logdir, log_fname), 'w', encoding='utf-8')
    log_fatal_warnings = fatal_warnings

def set_timestamp_start(start: float) -> None:
    global log_timestamp_start
    log_timestamp_start = start

def shutdown() -> T.Optional[str]:
    global log_file
    if log_file is not None:
        path = log_file.name
        exception_around_goer = log_file
        log_file = None
        exception_around_goer.close()
        return path
    return None

class AnsiDecorator:
    plain_code = "\033[0m"

    def __init__(self, text: str, code: str, quoted: bool = False):
        self.text = text
        self.code = code
        self.quoted = quoted

    def get_text(self, with_codes: bool) -> str:
        text = self.text
        if with_codes and self.code:
            text = self.code + self.text + AnsiDecorator.plain_code
        if self.quoted:
            text = f'"{text}"'
        return text

    def __len__(self) -> int:
        return len(self.text)

    def __str__(self) -> str:
        return self.get_text(colorize_console())

TV_Loggable = T.Union[str, AnsiDecorator, 'StringProtocol']
TV_LoggableList = T.List[TV_Loggable]

class AnsiText:
    def __init__(self, *args: TV_LoggableList):
        self.args = args

    def __len__(self) -> int:
        return sum(len(x) for x in self.args)

    def __str__(self) -> str:
        return ''.join(str(x) for x in self.args)

def bold(text: str, quoted: bool = False) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[1m", quoted=quoted)

def plain(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "")

def red(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[1;31m")

def green(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[1;32m")

def yellow(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[1;33m")

def blue(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[1;34m")

def cyan(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[1;36m")

def normal_red(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[31m")

def normal_green(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[32m")

def normal_yellow(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[33m")

def normal_blue(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[34m")

def normal_cyan(text: str) -> AnsiDecorator:
    return AnsiDecorator(text, "\033[36m")

# This really should be AnsiDecorator or anything that implements
# __str__(), but that requires protocols from typing_extensions
def process_markup(args: T.Sequence[TV_Loggable], keep: bool) -> T.List[str]:
    arr = []  # type: T.List[str]
    if log_timestamp_start is not None:
        arr = ['[{:.3f}]'.format(time.monotonic() - log_timestamp_start)]
    for arg in args:
        if arg is None:
            continue
        if isinstance(arg, str):
            arr.append(arg)
        elif isinstance(arg, AnsiDecorator):
            arr.append(arg.get_text(keep))
        else:
            arr.append(str(arg))
    return arr

def force_print(*args: str, nested: str, **kwargs: T.Any) -> None:
    if log_disable_stdout:
        return
    iostr = io.StringIO()
    kwargs['file'] = iostr
    print(*args, **kwargs)

    raw = iostr.getvalue()
    if log_depth:
        prepend = log_depth[-1] + '| ' if nested else ''
        lines = []
        for l in raw.split('\n'):
            l = l.strip()
            lines.append(prepend + l if l else '')
        raw = '\n'.join(lines)

    # _Something_ is going to get printed.
    try:
        print(raw, end='')
    except UnicodeEncodeError:
        cleaned = raw.encode('ascii', 'replace').decode('ascii')
        print(cleaned, end='')

# We really want a heterogeneous dict for this, but that's in typing_extensions
def debug(*args: TV_Loggable, **kwargs: T.Any) -> None:
    arr = process_markup(args, False)
    if log_file is not None:
        print(*arr, file=log_file, **kwargs)
        log_file.flush()

def _debug_log_cmd(cmd: str, args: T.List[str]) -> None:
    if not _in_ci:
        return
    args = [f'"{x}"' for x in args]  # Quote all args, just in case
    debug('!meson_ci!/{} {}'.format(cmd, ' '.join(args)))

def cmd_ci_include(file: str) -> None:
    _debug_log_cmd('ci_include', [file])

def log(*args: TV_Loggable, is_error: bool = False,
        once: bool = False, **kwargs: T.Any) -> None:
    if once:
        return log_once(*args, is_error=is_error, **kwargs)
    return _log(*args, is_error=is_error, **kwargs)

def _log(*args: TV_Loggable, is_error: bool = False,
        **kwargs: T.Any) -> None:
    nested = kwargs.pop('nested', True)
    arr = process_markup(args, False)
    if log_file is not None:
        print(*arr, file=log_file, **kwargs)
        log_file.flush()
    if colorize_console():
        arr = process_markup(args, True)
    if not log_errors_only or is_error:
        force_print(*arr, nested=nested, **kwargs)

def log_once(*args: TV_Loggable, is_error: bool = False,
             **kwargs: T.Any) -> None:
    """Log variant that only prints a given message one time per meson invocation.

    This considers ansi decorated values by the values they wrap without
    regard for the AnsiDecorator itself.
    """
    def to_str(x: TV_Loggable) -> str:
        if isinstance(x, str):
            return x
        if isinstance(x, AnsiDecorator):
            return x.text
        return str(x)
    t = tuple(to_str(a) for a in args)
    if t in _logged_once:
        return
    _logged_once.add(t)
    _log(*args, is_error=is_error, **kwargs)

# This isn't strictly correct. What we really want here is something like:
# class StringProtocol(typing_extensions.Protocol):
#
#      def __str__(self) -> str: ...
#
# This would more accurately embody what this function can handle, but we
# don't have that yet, so instead we'll do some casting to work around it
def get_error_location_string(fname: str, lineno: str) -> str:
    return f'{fname}:{lineno}:'

def _log_error(severity: str, *rargs: TV_Loggable,
               once: bool = False, fatal: bool = True, **kwargs: T.Any) -> None:
    from .mesonlib import MesonException, relpath

    # The typing requirements here are non-obvious. Lists are invariant,
    # therefore T.List[A] and T.List[T.Union[A, B]] are not able to be joined
    if severity == 'notice':
        label = [bold('NOTICE:')]  # type: TV_LoggableList
    elif severity == 'warning':
        label = [yellow('WARNING:')]
    elif severity == 'error':
        label = [red('ERROR:')]
    elif severity == 'deprecation':
        label = [red('DEPRECATION:')]
    else:
        raise MesonException('Invalid severity ' + severity)
    # rargs is a tuple, not a list
    args = label + list(rargs)

    location = kwargs.pop('location', None)
    if location is not None:
        location_file = relpath(location.filename, os.getcwd())
        location_str = get_error_location_string(location_file, location.lineno)
        # Unions are frankly awful, and we have to T.cast here to get mypy
        # to understand that the list concatenation is safe
        location_list = T.cast(TV_LoggableList, [location_str])
        args = location_list + args

    log(*args, once=once, **kwargs)

    global log_warnings_counter
    log_warnings_counter += 1

    if log_fatal_warnings and fatal:
        raise MesonException("Fatal warnings enabled, aborting")

def error(*args: TV_Loggable, **kwargs: T.Any) -> None:
    return _log_error('error', *args, **kwargs, is_error=True)

def warning(*args: TV_Loggable, **kwargs: T.Any) -> None:
    return _log_error('warning', *args, **kwargs, is_error=True)

def deprecation(*args: TV_Loggable, **kwargs: T.Any) -> None:
    return _log_error('deprecation', *args, **kwargs, is_error=True)

def notice(*args: TV_Loggable, **kwargs: T.Any) -> None:
    return _log_error('notice', *args, **kwargs, is_error=False)

def get_relative_path(target: Path, current: Path) -> Path:
    """Get the path to target from current"""
    # Go up "current" until we find a common ancestor to target
    acc = ['.']
    for part in [current, *current.parents]:
        try:
            path = target.relative_to(part)
            return Path(*acc, path)
        except ValueError:
            pass
        acc += ['..']

    # we failed, should not get here
    return target

def exception(e: Exception, prefix: T.Optional[AnsiDecorator] = None) -> None:
    if prefix is None:
        prefix = red('ERROR:')
    log()
    args = []  # type: T.List[T.Union[AnsiDecorator, str]]
    if all(getattr(e, a, None) is not None for a in ['file', 'lineno', 'colno']):
        # Mypy doesn't follow hasattr, and it's pretty easy to visually inspect
        # that this is correct, so we'll just ignore it.
        path = get_relative_path(Path(e.file), Path(os.getcwd()))  # type: ignore
        args.append(f'{path}:{e.lineno}:{e.colno}:')  # type: ignore
    if prefix:
        args.append(prefix)
    args.append(str(e))
    log(*args)

# Format a list for logging purposes as a string. It separates
# all but the last item with commas, and the last with 'and'.
def format_list(input_list: T.List[str]) -> str:
    l = len(input_list)
    if l > 2:
        return ' and '.join([', '.join(input_list[:-1]), input_list[-1]])
    elif l == 2:
        return ' and '.join(input_list)
    elif l == 1:
        return input_list[0]
    else:
        return ''

@contextmanager
def nested(name: str = '') -> T.Generator[None, None, None]:
    global log_depth
    log_depth.append(name)
    try:
        yield
    finally:
        log_depth.pop()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using Northwind.Data;
using Northwind.Web.Models;
using System.Web.Http;
using System.Net.Http;
using System.Net;

namespace Northwind.Web.Api
{
    /// <summary>
    /// This is the controller that gets called when the customers page is loaded
    /// </summary>
    public class CustomersController : BaseApiController
    {
        /// <summary>
        /// Get all the customers
        /// </summary>
        /// <returns></returns>
        [Queryable]
        public IQueryable<CustomerListModel> Get()
        {
            return this.DataContext.Customers
                                   .Select(c => new CustomerListModel
                                   {
                                       Id = c.Id,
                                       Name = c.Name,
                                       ContactName = c.Contact.Name,
                                       ContactTitle = c.Contact.Title,
                                   });
        }

        /// <summary>
        /// Get an individual customer
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public CustomerDetailModel Get(string id)
        {
            return this.DataContext.Customers
                                   .Select(c => new CustomerDetailModel
                                    {
                                        Id = c.Id,
                                        Name = c.Name,
                                        ContactName = c.Contact.Name,
                                        ContactTitle = c.Contact.Title,
                                        Address = c.Address,
                                        City = c.City,
                                        Region = c.Region,
                                        PostalCode = c.PostalCode,
                                        Country = c.Country,
                                        Phone = c.Phone,
                                        Fax = c.Fax,
                                    })
                                   .SingleOrDefault(c => c.Id == id);
        }

        /// <summary>
        /// Create a new customer
        /// </summary>
        /// <param name="model"></param>
        public HttpResponseMessage Post(CustomerDetailModel model)
        {
            var customer = this.DataContext.Customers.Add(new Customer
            {
                Id = model.Id,
                Name = model.Name,
                Contact = new Contact
                {
                    Name = model.ContactName,
                    Title = model.ContactTitle,
                },
                Address = model.Address,
                City = model.City,
                Region = model.Region,
                PostalCode = model.PostalCode,
                Country = model.Country,
                Phone = model.Phone,
                Fax = model.Fax,
            });
            this.DataContext.SaveChanges();

            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, customer);
            response.Headers.Location = new Uri(Url.Link("Api", new { controller = "Customers", id = customer.Id }));
            return response;
        }

        /// <summary>
        /// Create a new customer
        /// </summary>
        /// <param name="model"></param>
        public HttpResponseMessage Put(CustomerDetailModel model)
        {
            var customer = this.DataContext.Customers.Find(model.Id);

            if (customer == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            customer.Name = model.Name;
            customer.Contact = new Contact
            {
                Name = model.ContactName,
                Title = model.ContactTitle,
            };
            customer.Address = model.Address;
            customer.City = model.City;
            customer.Region = model.Region;
            customer.PostalCode = model.PostalCode;
            customer.Country = model.Country;
            customer.Phone = model.Phone;
            customer.Fax = model.Fax;
            this.DataContext.SaveChanges();

            return Request.CreateResponse(HttpStatusCode.OK, model);
        }

        /// <summary>
        /// Delete a customer
        /// </summary>
        /// <param name="id"></param>
        public HttpResponseMessage Delete(string id)
        {
            var customer = this.DataContext.Customers.Find(id);

            if (customer == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            this.DataContext.Customers.Remove(customer);
            this.DataContext.SaveChanges();

            return Request.CreateResponse(HttpStatusCode.OK);
        }
    }
}


text:
use strict;
use integer;

use NaturalDocs::ClassHierarchy::Class;
use NaturalDocs::ClassHierarchy::File;

package NaturalDocs::ClassHierarchy;

use Encode qw(encode_utf8 decode_utf8);

###############################################################################
# Group: Variables

#
#   handle: CLASS_HIERARCHY_FILEHANDLE
#   The file handle used with <ClassHierarchy.nd>.
#

#
#   hash: classes
#
#   A hash of all the classes.  The keys are the class <SymbolStrings> and the values are <NaturalDocs::ClassHierarchy::Classes>.
#
my %classes;

#
#   hash: files
#
#   A hash of the hierarchy information referenced by file.  The keys are the <FileNames>, and the values are
#   <NaturalDocs::ClassHierarchy::File>s.
#
my %files;

#
#   hash: parentReferences
#
#   A hash of all the parent reference strings and what they resolve to.  The keys are the <ReferenceStrings> and the values are
#   the class <SymbolStrings> that they resolve to.
#
my %parentReferences;

#
#   object: watchedFile
#
#   A <NaturalDocs::ClassHierarchy::File> object of the file being watched for changes.  This is compared to the version in <files>
#   to see if anything was changed since the last parse.
#
my $watchedFile;

#
#   string: watchedFileName
#
#   The <FileName> of the watched file, if any.  If there is no watched file, this will be undef.
#
my $watchedFileName;

#
#   bool: dontRebuildFiles
#
#   A bool to set if you don't want changes in the hierarchy to cause files to be rebuilt.
#
my $dontRebuildFiles;

###############################################################################
# Group: Files

#
#   File: ClassHierarchy.nd
#
#   Stores the class hierarchy on disk.
#
#   Format:
#
#       > [BINARY_FORMAT]
#       > [VersionInt: app version]
#
#       The standard <BINARY_FORMAT> and <VersionInt> header.
#
#       > [SymbolString: class or undef to end]
#
#       Next we begin a class segment with its <SymbolString>.  These continue until the end of the file.  Only defined classes are
#       included.
#
#       > [UInt32: number of files]
#       > [UString16: file] [UString16: file] ...
#
#       Next there is the number of files that define that class.  It's a UInt32, which seems like overkill, but I could imagine every
#       file in a huge C++ project being under the same namespace, and thus contributing its own definition.  It's theoretically
#       possible.
#
#       Following the number is that many file names.  You must remember the index of each file, as they will be important later.
#       Indexes start at one because zero has a special meaning.
#
#       > [UInt8: number of parents]
#       > ( [ReferenceString (no type): parent]
#       >   [UInt32: file index] [UInt32: file index] ... [UInt32: 0] ) ...
#
#       Next there is the number of parents defined for this class.  For each one, we define a parent segment, which consists of
#       its <ReferenceString>, and then a zero-terminated string of indexes of the files that define that parent as part of that class.
#       The indexes start at one, and are into the list of files we saw previously.
#
#       Note that we do store class segments for classes without parents, but not for undefined classes.
#
#       This concludes a class segment.  These segments continue until an undef <SymbolString>.
#
#   See Also:
#
#       <File Format Conventions>
#
#   Revisions:
#
#		1.52:
#
#			- Changed AString16s to UString16s.
#
#       1.22:
#
#           - Classes and parents switched from AString16s to <SymbolStrings> and <ReferenceStrings>.
#           - A ending undef <SymbolString> was added to the end.  Previously it stopped when the file ran out.
#
#       1.2:
#
#           - This file was introduced in 1.2.
#

###############################################################################
# Group: File Functions

#
#   Function: Load
#
#   Loads the class hierarchy from disk.
#
sub Load
    {
    my ($self) = @_;

    $dontRebuildFiles = 1;

    my $fileIsOkay;
    my $fileName = NaturalDocs::Project->DataFile('ClassHierarchy.nd');

    if (!NaturalDocs::Settings->RebuildData() && open(CLASS_HIERARCHY_FILEHANDLE, '<' . $fileName))
        {
        # See if it's binary.
        binmode(CLASS_HIERARCHY_FILEHANDLE);

        my $firstChar;
        read(CLASS_HIERARCHY_FILEHANDLE, $firstChar, 1);

        if ($firstChar != ::BINARY_FORMAT())
            {
            close(CLASS_HIERARCHY_FILEHANDLE);
            }
        else
            {
            my $version = NaturalDocs::Version->FromBinaryFile(\*CLASS_HIERARCHY_FILEHANDLE);

            # Last file format change was 1.52

            if (NaturalDocs::Version->CheckFileFormat( $version, NaturalDocs::Version->FromString('1.52') ))
                {  $fileIsOkay = 1;  }
            else
                {  close(CLASS_HIERARCHY_FILEHANDLE);  };
            };
        };

    if (!$fileIsOkay)
        {
        NaturalDocs::Project->ReparseEverything();
        }
    else
        {
        my $raw;

        for (;;)
            {
            # [SymbolString: class or undef to end]

            my $class = NaturalDocs::SymbolString->FromBinaryFile(\*CLASS_HIERARCHY_FILEHANDLE);

            if (!defined $class)
                {  last;  };

            # [UInt32: number of files]

            read(CLASS_HIERARCHY_FILEHANDLE, $raw, 4);
            my $numberOfFiles = unpack('N', $raw);

            my @files;

            while ($numberOfFiles)
                {
                # [UString16: file]

                read(CLASS_HIERARCHY_FILEHANDLE, $raw, 2);
                my $fileLength = unpack('n', $raw);

                my $file;
                read(CLASS_HIERARCHY_FILEHANDLE, $file, $fileLength);
                $file = decode_utf8($file);

                push @files, $file;
                $self->AddClass($file, $class, NaturalDocs::Languages->LanguageOf($file)->Name());

                $numberOfFiles--;
                };

            # [UInt8: number of parents]

            read(CLASS_HIERARCHY_FILEHANDLE, $raw, 1);
            my $numberOfParents = unpack('C', $raw);

            while ($numberOfParents)
                {
                # [ReferenceString (no type): parent]

                my $parent = NaturalDocs::ReferenceString->FromBinaryFile(\*CLASS_HIERARCHY_FILEHANDLE,
                                                                                ::BINARYREF_NOTYPE(),
                                                                                ::REFERENCE_CH_PARENT());

                for (;;)
                    {
                    # [UInt32: file index or 0]

                    read(CLASS_HIERARCHY_FILEHANDLE, $raw, 4);
                    my $fileIndex = unpack('N', $raw);

                    if ($fileIndex == 0)
                        {  last;  }

                    $self->AddParentReference( $files[$fileIndex - 1], $class, $parent );
                    };

                $numberOfParents--;
                };
            };

        close(CLASS_HIERARCHY_FILEHANDLE);
        };

    $dontRebuildFiles = undef;
    };

#
#   Function: Save
#
#   Saves the class hierarchy to disk.
#
sub Save
    {
    my ($self) = @_;

    open (CLASS_HIERARCHY_FILEHANDLE, '>' . NaturalDocs::Project->DataFile('ClassHierarchy.nd'))
        or die "Couldn't save " . NaturalDocs::Project->DataFile('ClassHierarchy.nd') . ".\n";

    binmode(CLASS_HIERARCHY_FILEHANDLE);

    print CLASS_HIERARCHY_FILEHANDLE '' . ::BINARY_FORMAT();
    NaturalDocs::Version->ToBinaryFile(\*CLASS_HIERARCHY_FILEHANDLE, NaturalDocs::Settings->AppVersion());

    while (my ($class, $classObject) = each %classes)
        {
        if ($classObject->IsDefined())
            {
            # [SymbolString: class or undef to end]

            NaturalDocs::SymbolString->ToBinaryFile(\*CLASS_HIERARCHY_FILEHANDLE, $class);

            # [UInt32: number of files]

            my @definitions = $classObject->Definitions();
            my %definitionIndexes;

            print CLASS_HIERARCHY_FILEHANDLE pack('N', scalar @definitions);

            for (my $i = 0; $i < scalar @definitions; $i++)
                {
                # [UString16: file]
                my $uDefinition = encode_utf8($definitions[$i]);
                print CLASS_HIERARCHY_FILEHANDLE pack('na*', length($uDefinition), $uDefinition);
                $definitionIndexes{$definitions[$i]} = $i + 1;
                };

            # [UInt8: number of parents]

            my @parents = $classObject->ParentReferences();
            print CLASS_HIERARCHY_FILEHANDLE pack('C', scalar @parents);

            foreach my $parent (@parents)
                {
                # [ReferenceString (no type): parent]

                NaturalDocs::ReferenceString->ToBinaryFile(\*CLASS_HIERARCHY_FILEHANDLE, $parent, ::BINARYREF_NOTYPE());

                # [UInt32: file index]

                my @parentDefinitions = $classObject->ParentReferenceDefinitions($parent);

                foreach my $parentDefinition (@parentDefinitions)
                    {
                    print CLASS_HIERARCHY_FILEHANDLE pack('N', $definitionIndexes{$parentDefinition});
                    };

                # [UInt32: 0]
                print CLASS_HIERARCHY_FILEHANDLE pack('N', 0);
                };
            };
        };

    # [SymbolString: class or undef to end]

    NaturalDocs::SymbolString->ToBinaryFile(\*CLASS_HIERARCHY_FILEHANDLE, undef);

    close(CLASS_HIERARCHY_FILEHANDLE);
    };

#
#   Function: Purge
#
#   Purges the hierarchy of files that no longer have Natural Docs content.
#
sub Purge
    {
    my ($self) = @_;

    my $filesToPurge = NaturalDocs::Project->FilesToPurge();

    foreach my $file (keys %$filesToPurge)
        {
        $self->DeleteFile($file);
        };
    };

###############################################################################
# Group: Interface Functions

#
#   Function: OnInterpretationChange
#
#   Called by <NaturalDocs::SymbolTable> whenever a class hierarchy reference's intepretation changes, meaning it switched
#   from one symbol to another.
#
#       reference - The <ReferenceString> whose current interpretation changed.
#
sub OnInterpretationChange #(reference)
    {
    my ($self, $reference) = @_;

    if (NaturalDocs::ReferenceString->TypeOf($reference) == ::REFERENCE_CH_PARENT())
        {
        # The approach here is simply to completely delete the reference and readd it.  This is less than optimal efficiency, since it's
        # being removed and added from %files too, even though that isn't required.  However, the simpler code is worth it
        # considering this will only happen when a parent reference becomes defined or undefined, or on the rare languages (like C#)
        # that allow relative parent references.

        my $oldTargetSymbol = $parentReferences{$reference};
        my $oldTargetObject = $classes{$oldTargetSymbol};

        my @classesWithReferenceParent = $oldTargetObject->Children();

        # Each entry is an arrayref of file names.  Indexes are the same as classesWithReferenceParent's.
        my @filesDefiningReferenceParent;

        foreach my $classWithReferenceParent (@classesWithReferenceParent)
            {
            my $fileList = [ $classes{$classWithReferenceParent}->ParentReferenceDefinitions($reference) ];
            push @filesDefiningReferenceParent, $fileList;

            foreach my $fileDefiningReferenceParent (@$fileList)
                {
                $self->DeleteParentReference($fileDefiningReferenceParent, $classWithReferenceParent, $reference);
                };
            };

        # This will force the reference to be reinterpreted on the next add.

        delete $parentReferences{$reference};

        # Now we can just readd it.

        for (my $i = 0; $i < scalar @classesWithReferenceParent; $i++)
            {
            foreach my $file (@{$filesDefiningReferenceParent[$i]})
                {
                $self->AddParentReference($file, $classesWithReferenceParent[$i], $reference);
                };
            };
        };

    # The only way for a REFERENCE_CH_CLASS reference to change is if the symbol is deleted.  That will be handled by
    # <AnalyzeChanges()>, so we don't need to do anything here.
    };

#
#   Function: OnTargetSymbolChange
#
#   Called by <NaturalDocs::SymbolTable> whenever a class hierarchy reference's target symbol changes, but the reference
#   still resolves to the same symbol.
#
#   Parameters:
#
#       reference - The <ReferenceString> that was affected by the change.
#
sub OnTargetSymbolChange #(reference)
    {
    my ($self, $reference) = @_;

    my $type = NaturalDocs::ReferenceString->TypeOf($reference);
    my $class;

    if ($type == ::REFERENCE_CH_PARENT())
        {  $class = $parentReferences{$reference};  }
    else # ($type == ::REFERENCE_CH_CLASS())
        {
        # Class references are global absolute, so we can just yank the symbol.
        (undef, $class, undef, undef, undef, undef) = NaturalDocs::ReferenceString->InformationOf($reference);
        };

    $self->RebuildFilesFor($class, 1, 0, 1);
    };

###############################################################################
# Group: Modification Functions

#
#   Function: AddClass
#
#   Adds a class to the hierarchy.
#
#   Parameters:
#
#       file - The <FileName> the class was defined in.
#       class - The class <SymbolString>.
#       languageName - The name of the language this applies to.
#
#   Note:
#
#       The file parameter must be defined when using this function externally.  It may be undef for internal use only.
#
sub AddClass #(file, class, languageName)
    {
    my ($self, $file, $class, $languageName) = @_;

    if (!exists $classes{$class})
        {
        $classes{$class} = NaturalDocs::ClassHierarchy::Class->New();
        NaturalDocs::SymbolTable->AddReference($self->ClassReferenceOf($class, $languageName), $file)
        };

    if (defined $file)
        {
        # If this was the first definition for this class...
        if ($classes{$class}->AddDefinition($file))
            {  $self->RebuildFilesFor($class, 1, 1, 1);  };

        if (!exists $files{$file})
            {  $files{$file} = NaturalDocs::ClassHierarchy::File->New();  };

        $files{$file}->AddClass($class);

        if (defined $watchedFileName)
            {  $watchedFile->AddClass($class);  };
        };
    };

#
#   Function: AddParentReference
#
#   Adds a class-parent relationship to the hierarchy.  The classes will be created if they don't already exist.
#
#   Parameters:
#
#       file - The <FileName> the reference was defined in.
#       class - The class <SymbolString>.
#       symbol - The parent class <SymbolString>.
#       scope - The package <SymbolString> that the reference appeared in.
#       using - An arrayref of package <SymbolStrings> that the reference has access to via "using" statements.
#       resolvingFlags - Any <Resolving Flags> to be used when resolving the reference.
#
#   Alternate Parameters:
#
#       file - The <FileName> the reference was defined in.
#       class - The class <SymbolString>.
#       reference - The parent <ReferenceString>.
#
sub AddParentReference #(file, class, symbol, scope, using, resolvingFlags) or (file, class, reference)
    {
    my ($self, $file, $class, $symbol, $parentReference);

    if (scalar @_ == 7)
        {
        my ($scope, $using, $resolvingFlags);
        ($self, $file, $class, $symbol, $scope, $using, $resolvingFlags) = @_;

        $parentReference = NaturalDocs::ReferenceString->MakeFrom(::REFERENCE_CH_PARENT(), $symbol,
                                                                                NaturalDocs::Languages->LanguageOf($file)->Name(),
                                                                                $scope, $using, $resolvingFlags);
        }
    else
        {
        ($self, $file, $class, $parentReference) = @_;
        $symbol = (NaturalDocs::ReferenceString->InformationOf($parentReference))[1];
        };

    # In case it doesn't already exist.
    $self->AddClass($file, $class);

    my $parent;
    if (exists $parentReferences{$parentReference})
        {
        $parent = $parentReferences{$parentReference};
        }
    else
        {
        NaturalDocs::SymbolTable->AddReference($parentReference, $file);
        my $parentTarget = NaturalDocs::SymbolTable->References($parentReference);

        if (defined $parentTarget)
            {  $parent = $parentTarget->Symbol();  }
        else
            {  $parent = $symbol;  };

        # In case it doesn't already exist.
        $self->AddClass(undef, $parent);

        $parentReferences{$parentReference} = $parent;
        };

    # If this defined a new parent...
    if ($classes{$class}->AddParentReference($parentReference, $file, \%parentReferences))
        {
        $classes{$parent}->AddChild($class);

        $self->RebuildFilesFor($class, 0, 1, 0);
        $self->RebuildFilesFor($parent, 0, 1, 0);
        };

    $files{$file}->AddParentReference($class, $parentReference);

    if (defined $watchedFileName)
        {  $watchedFile->AddParentReference($class, $parentReference);  };
    };

#
#   Function: WatchFileForChanges
#
#   Watches a file for changes, which can then be applied by <AnalyzeChanges()>.  Definitions are not deleted via a DeleteClass()
#   function.  Instead, a file is watched for changes, reparsed, and then a comparison is made to look for definitions that
#   disappeared and any other relevant changes.
#
#   Parameters:
#
#       file - The <FileName> to watch.
#
sub WatchFileForChanges #(file)
    {
    my ($self, $file) = @_;

    $watchedFile = NaturalDocs::ClassHierarchy::File->New();
    $watchedFileName = $file;
    };

#
#   Function: AnalyzeChanges
#
#   Checks the watched file for any changes that occured since the last time is was parsed, and updates the hierarchy as
#   necessary.  Also sends any files that are affected to <NaturalDocs::Project->RebuildFile()>.
#
sub AnalyzeChanges
    {
    my ($self) = @_;

    # If the file didn't have any classes before, and it still doesn't, it wont be in %files.
    if (exists $files{$watchedFileName})
        {
        my @originalClasses = $files{$watchedFileName}->Classes();

        foreach my $originalClass (@originalClasses)
            {
            # If the class isn't there the second time around...
            if (!$watchedFile->HasClass($originalClass))
                {  $self->DeleteClass($watchedFileName, $originalClass);  }

            else
                {
                my @originalParents = $files{$watchedFileName}->ParentReferencesOf($originalClass);

                foreach my $originalParent (@originalParents)
                    {
                    # If the parent reference wasn't there the second time around...
                    if (!$watchedFile->HasParentReference($originalClass, $originalParent))
                        {  $self->DeleteParentReference($watchedFileName, $originalClass, $originalParent);  };
                    };
                };
            };
        };

    $watchedFile = undef;
    $watchedFileName = undef;
    };

###############################################################################
# Group: Information Functions

#
#   Function: ParentsOf
#   Returns a <SymbolString> array of the passed class' parents, or an empty array if none.  Note that not all of them may be
#   defined.
#
sub ParentsOf #(class)
    {
    my ($self, $class) = @_;

    if (exists $classes{$class})
        {  return $classes{$class}->Parents();  }
    else
        {  return ( );  };
    };

#
#   Function: ChildrenOf
#   Returns a <SymbolString> array of the passed class' children, or an empty array if none.  Note that not all of them may be
#   defined.
#
sub ChildrenOf #(class)
    {
    my ($self, $class) = @_;

    if (exists $classes{$class})
        {  return $classes{$class}->Children();  }
    else
        {  return ( );  };
    };

###############################################################################
# Group: Support Functions

#
#   Function: DeleteFile
#
#   Deletes a file and everything defined in it.
#
#   Parameters:
#
#       file - The <FileName>.
#
sub DeleteFile #(file)
    {
    my ($self, $file) = @_;

    if (!exists $files{$file})
        {  return;  };

    my @classes = $files{$file}->Classes();
    foreach my $class (@classes)
        {
        $self->DeleteClass($file, $class);
        };

    delete $files{$file};
    };

#
#   Function: DeleteClass
#
#   Deletes a class definition from a file.  Will also delete any parent references from this class and file.  Will rebuild any file
#   affected unless <dontRebuildFiles> is set.
#
#   Parameters:
#
#       file - The <FileName> that defines the class.
#       class - The class <SymbolString>.
#
sub DeleteClass #(file, class)
    {
    my ($self, $file, $class) = @_;

    my @parents = $files{$file}->ParentReferencesOf($class);
    foreach my $parent (@parents)
        {
        $self->DeleteParentReference($file, $class, $parent);
        };

    $files{$file}->DeleteClass($class);

    # If we're deleting the last definition of this class.
    if ($classes{$class}->DeleteDefinition($file))
        {
        if (!$classes{$class}->HasChildren())
            {
            delete $classes{$class};

            if (!$dontRebuildFiles)
                {  NaturalDocs::Project->RebuildFile($file);  };
            }
        else
            {  $self->RebuildFilesFor($class, 0, 1, 1);  };

        };
    };

#
#   Function: DeleteParentReference
#
#   Deletes a class' parent reference and returns whether it resulted in the loss of a parent class.  Will rebuild any file affected
#   unless <dontRebuildFiles> is set.
#
#   Parameters:
#
#       file - The <FileName> that defines the reference.
#       class - The class <SymbolString>.
#       reference - The parent <ReferenceString>.
#
#   Returns:
#
#       If the class lost a parent as a result of this, it will return its <SymbolString>.  It will return undef otherwise.
#
sub DeleteParentReference #(file, class, reference)
    {
    my ($self, $file, $class, $reference) = @_;

    if (!exists $classes{$class})
        {  return;  };

    $files{$file}->DeleteParentReference($class, $reference);

    my $deletedParent = $classes{$class}->DeleteParentReference($reference, $file, \%parentReferences);

    if (defined $deletedParent)
        {
        my $deletedParentObject = $classes{$deletedParent};

        $deletedParentObject->DeleteChild($class);

        $self->RebuildFilesFor($deletedParent, 0, 1, 0);
        $self->RebuildFilesFor($class, 0, 1, 0);

        if (!$deletedParentObject->HasChildren() && !$deletedParentObject->IsDefined())
            {
            delete $classes{$deletedParent};
            NaturalDocs::SymbolTable->DeleteReference(
                $self->ClassReferenceOf($class, NaturalDocs::Languages->LanguageOf($file)->Name()) );
            };

        return $deletedParent;
        };

    return undef;
    };

#
#   Function: ClassReferenceOf
#
#   Returns the <REFERENCE_CH_CLASS> <ReferenceString> of the passed class <SymbolString>.
#
sub ClassReferenceOf #(class, languageName)
    {
    my ($self, $class, $languageName) = @_;

    return NaturalDocs::ReferenceString->MakeFrom(::REFERENCE_CH_CLASS(), $class, $languageName, undef, undef,
                                                                            ::RESOLVE_ABSOLUTE() | ::RESOLVE_NOPLURAL());
    };

#
#   Function: RebuildFilesFor
#
#   Calls <NaturalDocs::Project->RebuildFile()> for every file defining the passed class, its parents, and/or its children.
#   Returns without doing anything if <dontRebuildFiles> is set.
#
#   Parameters:
#
#       class - The class <SymbolString>.
#       rebuildParents - Whether to rebuild the class' parents.
#       rebuildSelf - Whether to rebuild the class.
#       rebuildChildren - Whether to rebuild the class' children.
#
sub RebuildFilesFor #(class, rebuildParents, rebuildSelf, rebuildChildren)
    {
    my ($self, $class, $rebuildParents, $rebuildSelf, $rebuildChildren) = @_;

    if ($dontRebuildFiles)
        {  return;  };

    my @classesToBuild;

    if ($rebuildParents)
        {  @classesToBuild = $classes{$class}->Parents();  };
    if ($rebuildSelf)
        {  push @classesToBuild, $class;  };
    if ($rebuildChildren)
        {  push @classesToBuild, $classes{$class}->Children();  };

    foreach my $classToBuild (@classesToBuild)
        {
        my @definitions = $classes{$classToBuild}->Definitions();

        foreach my $definition (@definitions)
            {  NaturalDocs::Project->RebuildFile($definition);  };
        };
    };

1;


text:
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */

import React, { PropTypes } from 'react';
import styles from './LoginPage.css';
import withStyles from '../../decorators/withStyles';

@withStyles(styles)
class LoginPage {

  static contextTypes = {
    onSetTitle: PropTypes.func.isRequired
  };

  render() {
    let title = 'Log In';
    this.context.onSetTitle(title);
    return (

{title}

Hi

          Login here

          Login here

    );
  }

}

export default LoginPage;


text:
using System;
//using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace P2PVOIP
{
    public partial class Main : Form
    {
        public string myNodeAddress = "";
        public string ipAddress;
        public int port;

        public Network network;
        public Commands commands;

        public List<string> nodeList = new List<string>();
        public List<PacketStackItem> PacketStack = new List<PacketStackItem>();

        delegate void SetTextCallback(string text);

        public Main()
        {
            InitializeComponent();
        }

        public void OutputText(string output)
        {
            if (rtbOutput.Text != "")
            {
                rtbOutput.Text = rtbOutput.Text + Environment.NewLine + output;
            }
            else
            {
                rtbOutput.Text = output;
            }
        }

        public void InputText(string input)
        {
            if (rtbInput.Text != "")
            {
                rtbInput.Text = rtbInput.Text + Environment.NewLine + input;
            }
            else
            {
                rtbInput.Text = input;
            }
        }

        private void Main_Load(object sender, EventArgs e)
        {
            network = new Network(this);
            ipAddress = network.GetIPAddress();
            port = network.GetUnusedPort();
            myNodeAddress = port.ToString() + '@' + ipAddress;

            StripAddress.Text = myNodeAddress;
            commands = new Commands(this);

            //tbHashAddress.Text = commands.CreateMessageID();
            network.StartListeningForData();
            OutputText(myNodeAddress);
            MenuStrip.Enabled = false;
        }

        private void tbConnect_Click(object sender, EventArgs e)
        {
            string nodeAddress = tbNodeAddress.Text;
            string[] address = nodeAddress.Split('@');
            string ipAddress = address[1];
            int port = Convert.ToInt32(address[0]);

            commands.NodeExchangeInvite(ipAddress,port);
        }

        public void SetInputText(string text)
        {
            if (this.rtbInput.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetInputText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                InputText(text);
            }
        }

        public void AddNode(string nodeAddress)
        {
            nodeList.Add(nodeAddress);
            UpdateNodeList(nodeAddress);
        }

        public void UpdateNodeList(string text)
        {
            if (this.listBoxNodes.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(UpdateNodeList);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                listBoxNodes.Items.Add(text);
            }
        }

        public void SetOutputText(string text)
        {
            if (this.rtbInput.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetOutputText);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                OutputText(text);
            }
        }

        private void listBoxNodes_SelectedIndexChanged(object sender, EventArgs e)
        {
            MenuStrip.Enabled = true;
        }

        private void btMessage_Click(object sender, EventArgs e)
        {
            MessageForm mf = new MessageForm(this,tbHashAddress.Text);
            mf.Show();
        }

        private void btCall_Click(object sender, EventArgs e)
        {
            CallForm call = new CallForm(this);
            call.Show();
        }

        public void ShowMessage(Message myMessage)
        {
            Application.Run(new MessageView(myMessage.FromHashAddress, myMessage.MessageBody));

        }

        public void ShowCallForm(CallForm callForm)
        {
            Application.Run(callForm);
        }
    }
}