text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace PumpingLemma
{
    public class Match {
        public readonly BooleanExpression constraint;
        public readonly SymbolicString remaining1;
        public readonly SymbolicString remaining2;

        private Match(BooleanExpression _c, SymbolicString _s1, SymbolicString _s2)
        {
            this.constraint = _c;
            this.remaining1 = _s1;
            this.remaining2 = _s2;
        }

        public Match reverse()
        {
            return new Match(constraint, remaining2, remaining1);
        }

        #region Factory Methods
        internal static Match MakeMatch(BooleanExpression _c, SymbolicString remaining1, SymbolicString remaining2)
        {
            return new Match(_c, remaining1, remaining2);
        }

        public static Match FullMatch(BooleanExpression _c)
        {
            return new Match(
                _c,
                SymbolicString.Epsilon(),
                SymbolicString.Epsilon()
                );
        }
        public static Match PartialFirst(BooleanExpression _c, SymbolicString remaining1)
        {
            return new Match(
                _c,
                remaining1,
                SymbolicString.Epsilon()
                );
        }
        public static Match PartialSecond(BooleanExpression _c, SymbolicString remaining2)
        {
            return new Match(
                _c,
                SymbolicString.Epsilon(),
                remaining2
                );
        }
        #endregion

        internal Match withAdditionalConstraint(BooleanExpression additionalConstraint)
        {
            return new Match(
                LogicalExpression.And(this.constraint, additionalConstraint),
                this.remaining1,
                this.remaining2
                );
        }
        internal IEnumerable<Match> continueMatch(SymbolicString rest1, SymbolicString rest2)
        {
            var cont1 = SymbolicString.Concat(this.remaining1, rest1);
            var cont2 = SymbolicString.Concat(this.remaining2, rest2);
            foreach (var mp in Matcher.match(cont1, cont2))
            {
                yield return mp.withAdditionalConstraint(this.constraint);
            }
        }
        public Match forceFinish()
        {
            BooleanExpression additionalConstraint = LogicalExpression.True();
            if (FirstRemaining)
                additionalConstraint = LogicalExpression.And(
                    additionalConstraint,
                    ComparisonExpression.Equal(remaining1.length(), 0)
                    );
            if (SecondRemaining)
                additionalConstraint = LogicalExpression.And(
                    additionalConstraint,
                    ComparisonExpression.Equal(remaining2.length(), 0)
                    );
            return FullMatch(LogicalExpression.And(this.constraint, additionalConstraint));
        }

        public override string ToString()
        {
            return "(" + remaining1.ToString() + ", " + remaining2.ToString() + ") when " + constraint.ToString();
        }
        public bool isFeasible()
        {
            return this.constraint.isSatisfiable();
        }
        public bool FirstRemaining
        {
            get { return !this.remaining1.isEpsilon();  }
        }
        public bool SecondRemaining
        {
            get { return !this.remaining2.isEpsilon();  }
        }
    }

    public static class Matcher
    {

        // Just dispatches to the appropriate helper method
        public static IEnumerable<Match> match(SymbolicString s1, SymbolicString s2)
        {
            Debug.Assert(s1.isFlat() && s2.isFlat());
            Func<SymbolicString.SymbolicStringType, string> toSignature = (ss_type) => {
                switch(ss_type) {
                    case SymbolicString.SymbolicStringType.Symbol: return "S";
                    case SymbolicString.SymbolicStringType.Repeat: return "R";
                    case SymbolicString.SymbolicStringType.Concat: return "C";
                    default: throw new ArgumentException();
                }
            };

            switch (toSignature(s1.expression_type) + toSignature(s2.expression_type))
            {
                case "RS":
                case "CS":
                case "CR":
                    return match(s2, s1).Select(x => x.reverse());
                case "SS":
                    return matchSymbolSymbol(s1, s2);
                case "SR":
                    return matchSymbolRepeat(s1, s2);
                case "SC":
                    return matchSymbolConcat(s1, s2);
                case "RR":
                    return matchRepeatRepeat(s1, s2);
                case "RC":
                    return matchRepeatConcat(s1, s2);
                case "CC":
                    return matchConcatConcat(s1, s2);
                default:
                    throw new ArgumentException();
            }
        }

        // Match only if both symbols are same
        private static IEnumerable<Match> matchSymbolSymbol(SymbolicString s1, SymbolicString s2)
        {
            if (s2.atomic_symbol == s1.atomic_symbol)
                yield return Match.FullMatch(LogicalExpression.True());
        }

        // Either consume symbol with first symbol of repeat and say repeat is positive
        // Or don't consume symbol and say repeat is zero
        private static IEnumerable<Match> matchSymbolRepeat(SymbolicString s1, SymbolicString s2)
        {
            Debug.Assert(s2.isFlat());

            // When repeat is 0
            yield return Match.PartialFirst(ComparisonExpression.Equal(s2.repeat, 0), s1);
            // When repeat is non-zero
            foreach (var m in match(s1, s2.root))
            {
                // Because the root is a word, we immediately know if the symbol matches or not
                // and get an m if and only if the symbol matches
                Debug.Assert(!m.FirstRemaining);
                yield return Match.PartialSecond(
                    LogicalExpression.And(m.constraint, ComparisonExpression.GreaterThan(s2.repeat, 0)),
                    SymbolicString.Concat(m.remaining2, SymbolicString.Repeat(s2.root, s2.repeat - 1))
                    );
            }
        }

        private static IEnumerable<Match> matchSymbolConcat(SymbolicString s1, SymbolicString s2)
        {
            if (s2.isEpsilon())
            {
                yield return Match.PartialFirst(LogicalExpression.True(), s1);
                yield break;
            }
            var rest = SymbolicString.Concat(s2.sub_strings.Skip(1));
            foreach (var m in match(s1, s2.sub_strings.First()))
                foreach (var mp in m.continueMatch(SymbolicString.Epsilon(), rest))
                    yield return mp;
        }

        private static IEnumerable<Match> matchConcatConcat(SymbolicString s1, SymbolicString s2)
        {
            if (s1.isEpsilon() || s2.isEpsilon())
            {
                yield return Match.MakeMatch(LogicalExpression.True(), s1, s2);
                yield break;
            }
            // Quick match prefix symbols
            int i;
            for (i = 0; i < s1.sub_strings.Count && i < s2.sub_strings.Count; i++)
            {
                if (s1.sub_strings[i].expression_type != SymbolicString.SymbolicStringType.Symbol ||
                    s2.sub_strings[i].expression_type != SymbolicString.SymbolicStringType.Symbol)
                    break;
                if (s1.sub_strings[i].atomic_symbol != s2.sub_strings[i].atomic_symbol)
                    yield break;
            }

            var sub1 = s1.sub_strings.Skip(i);
            var sub2 = s2.sub_strings.Skip(i);
            // If we have consumed something fully, just return the remaining bits
            if (i == s1.sub_strings.Count || i == s2.sub_strings.Count)
            {
                yield return Match.MakeMatch(
                    LogicalExpression.True(),
                    SymbolicString.Concat(sub1),
                    SymbolicString.Concat(sub2));
                yield break;
            }

            var rest1 = SymbolicString.Concat(sub1.Skip(1));
            var rest2 = SymbolicString.Concat(sub2.Skip(1));
            foreach (var m in match(sub1.First(), sub2.First()))
                foreach (var mp in m.continueMatch(rest1, rest2))
                    yield return mp;
        }

        private static IEnumerable<Match> matchRepeatConcat(SymbolicString s1, SymbolicString s2)
        {
            if (s2.isEpsilon())
            {
                yield return Match.FullMatch(ComparisonExpression.Equal(s1.length(), 0));
                yield return Match.PartialFirst(ComparisonExpression.GreaterThan(s1.length(), 0), s1);
                yield break;
            }
            var first = s2.sub_strings.First();
            var rest = SymbolicString.Concat(s2.sub_strings.Skip(1));
            foreach (var m in match(s1, first))
                foreach (var mp in m.continueMatch(SymbolicString.Epsilon(), rest))
                    yield return mp;
        }

        private static IEnumerable<Match> matchRepeatRepeat(SymbolicString s1, SymbolicString s2)
        {
            Debug.Assert(s1.root.isWord());
            Debug.Assert(s2.root.isWord());

            // Assume s1 is fully consumed
            foreach (var m in allLeftMatches(s1, s2))
                yield return m;

            // Assume s2 is fully consumed
            foreach (var m in allLeftMatches(s2, s1))
                yield return m.reverse();

            // Assume both are fully consumed
            if (omegaEqual(s1.root, s2.root))
            {
                yield return Match.FullMatch(ComparisonExpression.Equal(
                    LinearIntegerExpression.Times(s1.root.wordLength(), s1.repeat),
                    LinearIntegerExpression.Times(s2.root.wordLength(), s2.repeat)
                    ));
            }
            else
            {
                yield return Match.FullMatch(LogicalExpression.And(
                    ComparisonExpression.Equal(s2.length(), 0),
                    ComparisonExpression.Equal(s1.length(), 0)
                    ));
            }
        }

        #region Repeat Repeat match helpers
        private static int gcd(int a, int b)
        {
            while (a % b != 0)
            {
                int temp = a;
                a = b; b = temp % b;
            }
            return b;
        }

        // s1 and s2 are omega equal if s1^\omega = s2^\omega
        // Theorem: s1 and s2 are omega equal if and only if there
        // exists a w such that s1 = w^(l1/g) and s2 = w^(l2/g)
        // where l1, l2 are lengths of s1 and s2, and g = gcd(l1, l2)
        private static bool omegaEqual(SymbolicString s1, SymbolicString s2)
        {
            Debug.Assert(s1.isWord() && s2.isWord());

            var l1 = s1.wordLength();
            var l2 = s2.wordLength();
            var g = gcd(l1, l2);

            var w1 = s1.word().ToArray();
            for (int i = 0; i < l1; i++)
                if (w1[i] != w1[i % g]) return false;

            var w2 = s2.word().ToArray();
            for (int i = 0; i < l2; i++)
                if (w2[i] != w2[i % g]) return false;

            for (int i = 0; i < g; i++)
                if (w1[i] != w2[i]) return false;

            return true;
        }

        // Call only when omegaEqual(s1, s2) holds
        // TODO: There is definitely a more optimal implementation of this
        private static int getFirstMismatch(SymbolicString s1, SymbolicString s2)
        {
            Debug.Assert(s1.isWord() && s2.isWord());

            var l1 = s1.wordLength();
            var l2 = s2.wordLength();
            var w1 = s1.word().ToArray();
            var w2 = s2.word().ToArray();
            for (int i = 0; true; i++)
            {
                if (w1[i % l1] != w2[i % l2])
                    return i;
            }
        }
        private static IEnumerable<Match> shortLeftMatches(SymbolicString s1, SymbolicString s2, int firstMismatch)
        {
            int l1 = s1.root.wordLength();
            for (int i = 1; l1 * i <= firstMismatch; i++)
            {
                var s1r = SymbolicString.Concat(Enumerable.Repeat(s1.root, i));
                foreach (var m in match(s1r, s2))
                {
                    if (m.FirstRemaining)
                        continue;
                    yield return m.withAdditionalConstraint(LogicalExpression.And(
                        ComparisonExpression.Equal(s1.length(), s1r.length()),
                        ComparisonExpression.GreaterThan(m.remaining2.length(), 0)
                        ));
                }
            }
        }

        private static IEnumerable<Match> longLeftMatches(SymbolicString s1, SymbolicString s2)
        {
            var l1 = s1.root.wordLength();
            var l2 = s2.root.wordLength();
            var g = gcd(l1, l2);
            var v_beg = LinearIntegerExpression.FreshVariable();
            var v_end = LinearIntegerExpression.FreshVariable();

            // Split exactly at s2 root border
            yield return Match.PartialSecond(
                LogicalExpression.And(
                    // the beginning matches the s1
                    ComparisonExpression.Equal(
                        LinearIntegerExpression.Times(l2, v_beg),
                        LinearIntegerExpression.Times(l1, s1.repeat)
                    ),
                    // left over right bit is nonempty
                    ComparisonExpression.GreaterThan(
                        LinearIntegerExpression.Times(l2, v_end),
                        0
                    ),
                    // beginning and end match s2
                    ComparisonExpression.Equal(v_beg + v_end, s2.repeat),
                    ComparisonExpression.GreaterThanOrEqual(v_beg, 0),
                    ComparisonExpression.GreaterThanOrEqual(v_end, 0)
                ),
                SymbolicString.Repeat(s2.root, v_end)
            );
            // Split in the middle of s2 root
            if (l2 != 1)
            {
                for (int i = g; i < l2; i += g)
                {
                    var suffix = SymbolicString.Concat(s2.root.sub_strings.Skip(i));
                    yield return Match.PartialSecond(
                        LogicalExpression.And(
                            ComparisonExpression.Equal(
                                LinearIntegerExpression.Times(l2, v_beg) + g,
                                LinearIntegerExpression.Times(l1, s1.repeat)
                            ),
                            ComparisonExpression.GreaterThan(
                                LinearIntegerExpression.Times(l2, v_beg) + suffix.length(),
                                0
                            ),
                            ComparisonExpression.Equal(v_beg + v_end + 1, s2.repeat),
                            ComparisonExpression.GreaterThanOrEqual(v_beg, 0),
                            ComparisonExpression.GreaterThanOrEqual(v_end, 0)
                        ),
                        SymbolicString.Concat(suffix, SymbolicString.Repeat(s2.root, v_end))
                    );
                }
            }
        }

        // Returns only those matches where s1 is consumed fully
        private static IEnumerable<Match> allLeftMatches(SymbolicString s1, SymbolicString s2)
        {
            // First empty
            yield return Match.PartialSecond(
                LogicalExpression.And(
                    ComparisonExpression.Equal(s1.length(), 0),
                    ComparisonExpression.GreaterThan(s2.length(), 0)
                ),
                s2
            );

            // First non-empty
            if (!omegaEqual(s1.root, s2.root))
            { // They will mismatch at some point. So, just get small matches up to that point
                int firstMismatch = getFirstMismatch(s1.root, s2.root);
                foreach (var m in shortLeftMatches(s1, s2, firstMismatch))
                    yield return m.withAdditionalConstraint(ComparisonExpression.GreaterThan(s1.length(), 0));
            }
            else
            { // They will never mismatch. So, split s2 into two parts where s1 = first part
                foreach (var m in longLeftMatches(s1, s2))
                    yield return m.withAdditionalConstraint(ComparisonExpression.GreaterThan(s1.length(), 0));
            }
        }
        #endregion
    }
}


text:
"""Tests the AppEngine client."""

import mock

from tests.unittest_utils import ForsetiTestCase
from google.cloud.security.common.gcp_api import _base_client
from google.cloud.security.common.gcp_api import appengine

class AppEngineTest(ForsetiTestCase):
    """Test the AppEngine client."""

    @mock.patch('google.cloud.security.common.gcp_api._base_client.discovery')
    @mock.patch('google.cloud.security.common.gcp_api._base_client.GoogleCredentials')
    def setUp(self, mock_google_credential, mock_discovery):
        """Set up."""

        fake_global_configs = {
            'max_appengine_api_calls_per_second': 20}
        self.client = appengine.AppEngineClient(fake_global_configs)

    def test_get_app(self):
        self.client.service = mock.MagicMock()
        apps = mock.MagicMock()
        apps.get = mock.MagicMock()
        self.client.service.apps = mock.MagicMock(return_value=apps)
        self.client.rate_limiter = mock.MagicMock()
        self.client._execute = mock.MagicMock()

        app = self.client.get_app('aaaaa')

        self.assertTrue(self.client.service.apps.called)
        apps.get.assert_called_with(appsId='aaaaa')

redpajama_set_name: RedPajamaGithub


text:
using YouTown.Validation;

namespace YouTown.GameAction
{
    public class RollDice : GameActionBase
    {
        public static ActionType RollDiceType = new ActionType("RollDice");

        public RollDice(int id, IPlayer player) : base(id, player) { }
        public RollDice(RollDiceData data, IRepository repo) : base(data, repo)
        {
            DiceRoll = data.RolledDice != null ? new DiceRoll(data.RolledDice) : null;
            Production = data.Production != null ? new Production(data.Production, repo) : null;
        }

        public override ActionType ActionType => RollDiceType;
        public DiceRoll DiceRoll { get; private set; }
        public Production Production { get; private set; }

        public override bool IsAllowedInTurnPhase(ITurnPhase turnPhase) => turnPhase.IsDiceRoll;
        public override bool IsAllowedInGamePhase(IGamePhase gamePhase) => gamePhase.IsTurns; // TODO: determinefirstplayer

        public override GameActionData ToData() =>
            base.ToData(new RollDiceData
            {
                GameActionType = GameActionTypeData.RollDice,
                Production = Production?.ToData(),
            });

        public override IValidationResult Validate(IGame game) =>
            new ValidateAll()
                .WithObject<NotNull>(DiceRoll)
                .Validate();

        public override void PerformAtServer(IServerGame serverGame)
        {
            var random = serverGame.Random;
            var die1 = random.NextInt(1, 6);
            var die2 = random.NextInt(1, 6);
            DiceRoll = new DiceRoll(die1, die2);
        }

        public override void Perform(IGame game)
        {
            Production = game.GamePhase.RollDice(game, DiceRoll, Player);

            base.Perform(game);
        }
    }
}


text:
namespace TraktApiSharp.Tests.Objects.Get.Episodes.Json.Writer
{
    using FluentAssertions;
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Traits;
    using TraktApiSharp.Objects.Get.Episodes;
    using TraktApiSharp.Objects.Get.Episodes.Json.Writer;
    using Xunit;

    [Category("Objects.Get.Episodes.JsonWriter")]
    public partial class EpisodeTranslationObjectJsonWriter_Tests
    {
        [Fact]
        public void Test_EpisodeTranslationObjectJsonWriter_WriteObject_StringWriter_Exceptions()
        {
            var traktJsonWriter = new EpisodeTranslationObjectJsonWriter();
            ITraktEpisodeTranslation traktEpisodeTranslation = new TraktEpisodeTranslation();
            Func<Task<string>> action = () => traktJsonWriter.WriteObjectAsync(default(StringWriter), traktEpisodeTranslation);
            action.Should().Throw<ArgumentNullException>();
        }

        [Fact]
        public async Task Test_EpisodeTranslationObjectJsonWriter_WriteObject_StringWriter_Only_Title_Property()
        {
            ITraktEpisodeTranslation traktEpisodeTranslation = new TraktEpisodeTranslation
            {
                Title = "title"
            };

            using (var stringWriter = new StringWriter())
            {
                var traktJsonWriter = new EpisodeTranslationObjectJsonWriter();
                string json = await traktJsonWriter.WriteObjectAsync(stringWriter, traktEpisodeTranslation);
                json.Should().Be(@"{""title"":""title""}");
            }
        }

        [Fact]
        public async Task Test_EpisodeTranslationObjectJsonWriter_WriteObject_StringWriter_Only_Overview_Property()
        {
            ITraktEpisodeTranslation traktEpisodeTranslation = new TraktEpisodeTranslation
            {
                Overview = "overview"
            };

            using (var stringWriter = new StringWriter())
            {
                var traktJsonWriter = new EpisodeTranslationObjectJsonWriter();
                string json = await traktJsonWriter.WriteObjectAsync(stringWriter, traktEpisodeTranslation);
                json.Should().Be(@"{""overview"":""overview""}");
            }
        }

        [Fact]
        public async Task Test_EpisodeTranslationObjectJsonWriter_WriteObject_StringWriter_Only_LanguageCode_Property()
        {
            ITraktEpisodeTranslation traktEpisodeTranslation = new TraktEpisodeTranslation
            {
                LanguageCode = "language code"
            };

            using (var stringWriter = new StringWriter())
            {
                var traktJsonWriter = new EpisodeTranslationObjectJsonWriter();
                string json = await traktJsonWriter.WriteObjectAsync(stringWriter, traktEpisodeTranslation);
                json.Should().Be(@"{""language"":""language code""}");
            }
        }

        [Fact]
        public async Task Test_EpisodeTranslationObjectJsonWriter_WriteObject_StringWriter_Complete()
        {
            ITraktEpisodeTranslation traktEpisodeTranslation = new TraktEpisodeTranslation
            {
                Title = "title",
                Overview = "overview",
                LanguageCode = "language code"
            };

            using (var stringWriter = new StringWriter())
            {
                var traktJsonWriter = new EpisodeTranslationObjectJsonWriter();
                string json = await traktJsonWriter.WriteObjectAsync(stringWriter, traktEpisodeTranslation);
                json.Should().Be(@"{""title"":""title"",""overview"":""overview"",""language"":""language code""}");
            }
        }
    }
}


text:
package org.mifos.customers.persistence;

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

import org.joda.time.DateTime;
import org.mifos.accounts.business.AccountBO;
import org.mifos.accounts.fees.business.FeeBO;
import org.mifos.accounts.loan.business.LoanBO;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.customers.api.CustomerLevel;
import org.mifos.customers.business.CustomerBO;
import org.mifos.customers.business.CustomerFlagDetailEntity;
import org.mifos.customers.business.CustomerMeetingEntity;
import org.mifos.customers.business.CustomerPerformanceHistoryDto;
import org.mifos.customers.business.CustomerStatusEntity;
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.personnel.business.PersonnelBO;
import org.mifos.customers.personnel.business.PersonnelLevelEntity;
import org.mifos.dto.domain.CenterDisplayDto;
import org.mifos.dto.domain.CenterPerformanceHistoryDto;
import org.mifos.dto.domain.CustomerAccountSummaryDto;
import org.mifos.dto.domain.CustomerAddressDto;
import org.mifos.dto.domain.CustomerDetailDto;
import org.mifos.dto.domain.CustomerDto;
import org.mifos.dto.domain.CustomerFlagDto;
import org.mifos.dto.domain.CustomerMeetingDto;
import org.mifos.dto.domain.CustomerNoteDto;
import org.mifos.dto.domain.CustomerPositionOtherDto;
import org.mifos.dto.domain.LoanDetailDto;
import org.mifos.dto.domain.PersonnelDto;
import org.mifos.dto.domain.SavingsDetailDto;
import org.mifos.dto.domain.ValueListElement;
import org.mifos.dto.screen.ClientDisplayDto;
import org.mifos.dto.screen.GroupDisplayDto;
import org.mifos.dto.screen.LoanCycleCounter;
import org.mifos.framework.components.fieldConfiguration.business.FieldConfigurationEntity;
import org.mifos.framework.hibernate.helper.QueryResult;
import org.mifos.security.util.UserContext;

/**
 *
 */
public interface CustomerDao {

    void save(CustomerBO customer);

    void save(AccountBO customerAccount);

    void save(CustomerStatusEntity cse);

    void save(CustomerCheckListBO customerCheckListBO);

    void save(AccountCheckListBO accountCheckListBO);

    CustomerBO findCustomerById(Integer customerId);

    CustomerBO findCustomerBySystemId(String globalCustNum);

    ClientBO findClientBySystemId(String globalCustNum);

    GroupBO findGroupBySystemId(String globalCustNum);

    CenterBO findCenterBySystemId(String globalCustNum);

    List<ClientBO> findActiveClientsUnderGroup(CustomerBO customer);

    List<FeeBO> retrieveFeesApplicableToCenters();

    List<FeeBO> retrieveFeesApplicableToGroups();

    List<FeeBO> retrieveFeesApplicableToClients();

    List<FeeBO> retrieveFeesApplicableToGroupsRefinedBy(MeetingBO customerMeeting);

    List<FeeBO> retrieveFeesApplicableToClientsRefinedBy(MeetingBO customerMeetingValue);

    List<CustomerDetailDto> findClientsThatAreNotCancelledOrClosedReturningDetailDto(String searchId, Short branchId);

    List<CustomerDto> findClientsThatAreNotCancelledOrClosed(String parentSearchId, Short parentOfficeId);

    List<CustomerDto> findGroupsThatAreNotCancelledOrClosed(String parentSearchId, Short parentOfficeId);

    QueryResult search(String normalisedSearchString, PersonnelBO user);

    List<ValueListElement> retrieveSalutations();

    List<ValueListElement> retrieveTitles();

    List<ValueListElement> retrieveMaritalStatuses();

    List<ValueListElement> retrieveCitizenship();

    List<ValueListElement> retrieveBusinessActivities();

    List<ValueListElement> retrieveEducationLevels();

    List<ValueListElement> retrieveGenders();

    List<ValueListElement> retrieveHandicapped();

    List<ValueListElement> retrieveEthnicity();

    List<ValueListElement> retrievePoverty();

    List<ValueListElement> retrieveLivingStatus();

    CenterDisplayDto getCenterDisplayDto(Integer centerId, UserContext userContext);

    CustomerAccountSummaryDto getCustomerAccountSummaryDto(Integer centerId);

    CustomerAddressDto getCustomerAddressDto(CustomerBO center);

    List<CustomerDetailDto> getGroupsOtherThanClosedAndCancelledForGroup(String searchId, Short branchId);

    List<CustomerNoteDto> getRecentCustomerNoteDto(Integer centerId);

    List<CustomerPositionOtherDto> getCustomerPositionDto(Integer centerId, UserContext userContext);

    CustomerMeetingDto getCustomerMeetingDto(CustomerMeetingEntity customerMeeting, UserContext userContext);

    CenterPerformanceHistoryDto getCenterPerformanceHistory(String searchId, Short branchId);

    Integer getActiveAndOnHoldClientCountForGroup(String searchId, Short branchId);

    List<CustomerDetailDto> findActiveCentersUnderUser(PersonnelBO personnel);

    List<CustomerDetailDto> findGroupsUnderUser(PersonnelBO personnel);

    CustomerStatusEntity findClientPendingStatus();

    CustomerStatusEntity findGroupPendingStatus();

    int countOfClients();

    int countOfGroups();

    int retrieveLastSearchIdValueForNonParentCustomersInOffice(Short officeIdValue);

    List<FieldConfigurationEntity> findMandatoryConfigurableFieldsApplicableToCenter();

    void updateLoanOfficersForAllChildrenAndAccounts(Short loanOfficerId, String searchId, Short officeId);

    boolean validateGovernmentIdForClient(String governmentId);

    void validateClientForDuplicateNameOrGovtId(String name, Date dob, String governmentId) throws CustomerException;

    void validateGroupNameIsNotTakenForOffice(String displayName, Short officeId) throws CustomerException;

    void validateCenterNameIsNotTakenForOffice(String displayName, Short officeId) throws CustomerException;

    void checkPermissionForStatusChange(Short value, UserContext userContext, Short statusFlagId, Short officeId, Short personnelId) throws CustomerException;

    void checkPermissionForEditMeetingSchedule(UserContext userContext, CustomerBO customer) throws CustomerException;

    boolean validateForClosedClientsOnNameAndDob(final String name, final DateTime dateOfBirth);

    boolean validateForBlackListedClientsOnNameAndDob(String clientName, DateTime dateOfBirth);

    // FIXME - #000003 - keithw - inspect below methods to check are they non customer related methods to be moved out to other DAOs
    List<SavingsDetailDto> getSavingsDetailDto(Integer centerId, UserContext userContext);

    List<SavingsDetailDto> retrieveSavingOfferingsApplicableToClient();

    List<PersonnelDto> findLoanOfficerThatFormedOffice(Short officeId);

    String getAvgLoanAmountForMemberInGoodOrBadStanding(String searchId, Short branchId);

    String getTotalLoanAmountForGroup(String groupSearchId, Short groupOfficeId);

    String getTotalOutstandingLoanAmountForGroupAndClientsOfGroups(String searchId, Short branchId);

    String getTotalSavingsAmountForGroupandClientsOfGroup(String searchId, Short branchId);

    List<LoanCycleCounter> fetchLoanCycleCounter(Integer groupId, Short value);

    GroupDisplayDto getGroupDisplayDto(Integer customerId, UserContext userContext);

    ClientDisplayDto getClientDisplayDto(Integer customerId, UserContext userContext);

    List<CustomerFlagDto> getCustomerFlagDto(Set<CustomerFlagDetailEntity> customerFlags);

    List<LoanDetailDto> getLoanDetailDto(List<LoanBO> openLoanAccounts);

    CustomerPerformanceHistoryDto numberOfMeetings(boolean bool, Integer clientId);

    List<AccountBO> findGLIMLoanAccountsApplicableTo(Integer customerId, Integer customerWithActiveAccount);

    void checkPermissionForDefaultFeeRemoval(UserContext userContext, Short officeId, Short personnelId) throws CustomerException;

    void checkPermissionForDefaultFeeRemovalFromLoan(UserContext userContext, CustomerBO customer) throws CustomerException;

    List<PersonnelLevelEntity> retrievePersonnelLevels();

    /**
     * phoneNumber is stripped to contain numeric characters only
     */
    List<CustomerDto> findCustomersWithGivenPhoneNumber(String phoneNumber);

    List<AccountBO> retrieveAllClosedLoanAndSavingsAccounts(Integer customerId);

    List<CustomerDto> findTopOfHierarchyCustomersUnderLoanOfficer(CustomerLevel customerLevel, Short loanOfficerId,
            Short officeId);

    List<ClientBO> findActiveClientsUnderParent(String searchId, Short branchId);

    List<ClientBO> findAllExceptClosedAndCancelledClientsUnderParent(String searchId, Short officeId);

    List<ClientBO> findAllExceptClosedAndCancelledClientsWithoutGroupForLoanOfficer(Short loanOfficerId, Short officeId);

    ClientBO findClientById(Integer integer);

	Date getLastMeetingDateForCustomer(Integer customerId);

	Date getFirstMeetingDateForCustomer(Integer customerId);
}


text:
<?xml version="1.0"?>
<JDepend>
    <Packages>

        <Package name="com.cardatechnologies.utils.validators.abaroutevalidator">
            <Stats>
                <TotalClasses>2</TotalClasses>
                <ConcreteClasses>2</ConcreteClasses>
                <AbstractClasses>0</AbstractClasses>
                <Ca>0</Ca>
                <Ce>2</Ce>
                0
                1
                <D>0</D>
                <V>1</V>
            </Stats>

            <AbstractClasses>
            </AbstractClasses>

            <ConcreteClasses>
                <Class sourceFile="AbaRouteValidator.java">
                    com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator
                </Class>
                <Class sourceFile="ErrorCodes.java">
                    com.cardatechnologies.utils.validators.abaroutevalidator.ErrorCodes
                </Class>
            </ConcreteClasses>

            <DependsUpon>
                <Package>com.cardatechnologies.utils.validators.abaroutevalidator.exceptions</Package>
                <Package>java.lang</Package>
            </DependsUpon>

            <UsedBy>
            </UsedBy>
        </Package>

        <Package name="com.cardatechnologies.utils.validators.abaroutevalidator.exceptions">
            <Stats>
                <TotalClasses>1</TotalClasses>
                <ConcreteClasses>1</ConcreteClasses>
                <AbstractClasses>0</AbstractClasses>
                <Ca>1</Ca>
                <Ce>1</Ce>
                0
                0.5
                <D>0.5</D>
                <V>1</V>
            </Stats>

            <AbstractClasses>
            </AbstractClasses>

            <ConcreteClasses>
                <Class sourceFile="AbaRouteValidationException.java">
                    com.cardatechnologies.utils.validators.abaroutevalidator.exceptions.AbaRouteValidationException
                </Class>
            </ConcreteClasses>

            <DependsUpon>
                <Package>java.lang</Package>
            </DependsUpon>

            <UsedBy>
                <Package>com.cardatechnologies.utils.validators.abaroutevalidator</Package>
            </UsedBy>
        </Package>

        <Package name="java.lang">
            <error>No stats available: package referenced, but not analyzed.</error>
        </Package>
    </Packages>

    <Cycles>
    </Cycles>
</JDepend>


text:
/*
* X.509 CRL
* (C) 1999-2007 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#ifndef BOTAN_X509_CRL_H_
#define BOTAN_X509_CRL_H_

#include <botan/x509_obj.h>
#include <botan/asn1_obj.h>
#include <botan/pkix_enums.h>
#include <vector>

namespace Botan {

class Extensions;
class X509_Certificate;
class X509_DN;

struct CRL_Entry_Data;
struct CRL_Data;

/**
* This class represents CRL entries
*/
class BOTAN_PUBLIC_API(2,0) CRL_Entry final : public ASN1_Object
   {
   public:
      void encode_into(class DER_Encoder&) const override;
      void decode_from(class BER_Decoder&) override;

      /**
      * Get the serial number of the certificate associated with this entry.
      * @return certificate's serial number
      */
      const std::vector<uint8_t>& serial_number() const;

      /**
      * Get the revocation date of the certificate associated with this entry
      * @return certificate's revocation date
      */
      const X509_Time& expire_time() const;

      /**
      * Get the entries reason code
      * @return reason code
      */
      CRL_Code reason_code() const;

      /**
      * Get the extensions on this CRL entry
      */
      const Extensions& extensions() const;

      /**
      * Create uninitialized CRL_Entry object
      */
      CRL_Entry() = default;

      /**
      * Construct an CRL entry.
      * @param cert the certificate to revoke
      * @param reason the reason code to set in the entry
      */
      CRL_Entry(const X509_Certificate& cert,
                CRL_Code reason = UNSPECIFIED);

   private:
      friend class X509_CRL;

      const CRL_Entry_Data& data() const;

      std::shared_ptr<CRL_Entry_Data> m_data;
   };

/**
* Test two CRL entries for equality in all fields.
*/
BOTAN_PUBLIC_API(2,0) bool operator==(const CRL_Entry&, const CRL_Entry&);

/**
* Test two CRL entries for inequality in at least one field.
*/
BOTAN_PUBLIC_API(2,0) bool operator!=(const CRL_Entry&, const CRL_Entry&);

/**
* This class represents X.509 Certificate Revocation Lists (CRLs).
*/
class BOTAN_PUBLIC_API(2,0) X509_CRL final : public X509_Object
   {
   public:
      /**
      * This class represents CRL related errors.
      *
      * In a future major release this exception type will be removed and
      * replaced with Decoding_Error
      */
      class BOTAN_PUBLIC_API(2,0) X509_CRL_Error final : public Decoding_Error
         {
         public:
            explicit X509_CRL_Error(const std::string& error) :
               Decoding_Error("X509_CRL: " + error) {}
         };

      /**
      * Check if this particular certificate is listed in the CRL
      */
      bool is_revoked(const X509_Certificate& cert) const;

      /**
      * Get the entries of this CRL in the form of a vector.
      * @return vector containing the entries of this CRL.
      */
      const std::vector<CRL_Entry>& get_revoked() const;

      /**
      * Get the issuer DN of this CRL.
      * @return CRLs issuer DN
      */
      const X509_DN& issuer_dn() const;

      /**
      * @return extension data for this CRL
      */
      const Extensions& extensions() const;

      /**
      * Get the AuthorityKeyIdentifier of this CRL.
      * @return this CRLs AuthorityKeyIdentifier
      */
      const std::vector<uint8_t>& authority_key_id() const;

      /**
      * Get the serial number of this CRL.
      * @return CRLs serial number
      */
      uint32_t crl_number() const;

      /**
      * Get the CRL's thisUpdate value.
      * @return CRLs thisUpdate
      */
      const X509_Time& this_update() const;

      /**
      * Get the CRL's nextUpdate value.
      * @return CRLs nextdUpdate
      */
      const X509_Time& next_update() const;

      /**
      * Get the CRL's distribution point
      * @return CRL.IssuingDistributionPoint from the CRL's Data_Store
      */
      std::string crl_issuing_distribution_point() const;

      /**
      * Create an uninitialized CRL object. Any attempts to access
      * this object will throw an exception.
      */
      X509_CRL() = default;

      /**
      * Construct a CRL from a data source.
      * @param source the data source providing the DER or PEM encoded CRL.
      */
      X509_CRL(DataSource& source);

#if defined(BOTAN_TARGET_OS_HAS_FILESYSTEM)
      /**
      * Construct a CRL from a file containing the DER or PEM encoded CRL.
      * @param filename the name of the CRL file
      */
      X509_CRL(const std::string& filename);
#endif

      /**
      * Construct a CRL from a binary vector
      * @param vec the binary (DER) representation of the CRL
      */
      X509_CRL(const std::vector<uint8_t>& vec);

      /**
      * Construct a CRL
      * @param issuer issuer of this CRL
      * @param thisUpdate valid from
      * @param nextUpdate valid until
      * @param revoked entries to be included in the CRL
      */
      X509_CRL(const X509_DN& issuer, const X509_Time& thisUpdate,
               const X509_Time& nextUpdate, const std::vector<CRL_Entry>& revoked);

   private:
      std::string PEM_label() const override;

      std::vector<std::string> alternate_PEM_labels() const override;

      void force_decode() override;

      const CRL_Data& data() const;

      std::shared_ptr<CRL_Data> m_data;
   };

}

#endif


text:
import Control.Monad
import Control.Monad.Trans
import Network
import System.IO
import System.Environment

import IRC

server   = "irc.freenode.org"
port     = fromIntegral 6667
chan     = "#testlogo"
userName = "maaantrh5rhguyr"

connectToServer :: String -> PortNumber -> IO IRCInfo
connectToServer server port = do
    h <- connectTo server (PortNumber port)
    hSetBuffering h (BlockBuffering Nothing)
    return IRCInfo { ircHandle = h
                   , ircName   = server
                   , ircPort   = port
                   }

withConnection :: UserName -> IO IRCInfo -> IRCT IO () -> IO ()
withConnection un conn act = do
    i <- conn
    runIRCT un i $ do
        sendMessage $ nick un
        sendMessage $ user un "*" "*" un
        act
        sendMessage $ quit Nothing
        return ()

test_connectJoin :: IRCT IO ()
test_connectJoin = do
    sendMessage $ joinChan chan
    forever $ popMessage >>= liftIO . print

test_connectJoinMsg :: IRCT IO ()
test_connectJoinMsg = do
    sendMessage $ joinChan chan
    sendMessage $ privmsg chan "hello!"
    sendMessage $ part chan
    forever $ popMessage >>= liftIO . print

main :: IO ()
main = do
    args <- getArgs
    let un = case args of
            [s] -> s
            _   -> userName
        conn = connectToServer server port
    withConnection un conn test_connectJoin
    -- withConnection un conn test_connectJoinMsg


text:
#ifndef itkLevelSetEquationOverlapPenaltyTerm_h
#define itkLevelSetEquationOverlapPenaltyTerm_h

#include "itkLevelSetEquationTermBase.h"
#include "itkCompensatedSummation.h"

namespace itk
{
/**
 *  \class LevelSetEquationOverlapPenaltyTerm
 *  \brief Class to represent the overlap penalty among many level-sets
 *
 *  \f[
 *    \sum_{i \neq j } \left(H_{\epsilon}\left(\phi_j \left( p \right) \right)\right)
 *  \f]
 *
 *  \li \f$ i  \f$ is the current level-set id,
 *  \li \f$ j  \f$ is any level-set id,
 *  \li \f$ p  \f$ is the given location,
 *  \li \f$ H_{\epsilon}  \f$ is regularized Heaviside function.
 *
 *  \tparam TInput Input Image Type
 *  \tparam TLevelSetContainer Level set function container type
 *
 *  \ingroup ITKLevelSetsv4
 */
template< typename TInput, // Input image or mesh
          typename TLevelSetContainer >
class ITK_TEMPLATE_EXPORT LevelSetEquationOverlapPenaltyTerm :
    public LevelSetEquationTermBase< TInput, TLevelSetContainer >
{
public:
  ITK_DISALLOW_COPY_AND_ASSIGN(LevelSetEquationOverlapPenaltyTerm);

  using Self = LevelSetEquationOverlapPenaltyTerm;
  using Pointer = SmartPointer< Self >;
  using ConstPointer = SmartPointer< const Self >;
  using Superclass = LevelSetEquationTermBase< TInput, TLevelSetContainer >;

  /** Method for creation through object factory */
  itkNewMacro( Self );

  /** Run-time type information */
  itkTypeMacro( LevelSetEquationOverlapPenaltyTerm, LevelSetEquationTermBase );

  using InputImageType = typename Superclass::InputImageType;
  using InputImagePointer = typename Superclass::InputImagePointer;
  using InputPixelType = typename Superclass::InputPixelType;
  using InputPixelRealType = typename Superclass::InputPixelRealType;

  using LevelSetContainerType = typename Superclass::LevelSetContainerType;
  using LevelSetContainerPointer = typename Superclass::LevelSetContainerPointer;
  using LevelSetType = typename Superclass::LevelSetType;
  using LevelSetPointer = typename Superclass::LevelSetPointer;
  using LevelSetOutputPixelType = typename Superclass::LevelSetOutputPixelType;
  using LevelSetOutputRealType = typename Superclass::LevelSetOutputRealType;
  using LevelSetInputIndexType = typename Superclass::LevelSetInputIndexType;
  using LevelSetGradientType = typename Superclass::LevelSetGradientType;
  using LevelSetHessianType = typename Superclass::LevelSetHessianType;
  using LevelSetIdentifierType = typename Superclass::LevelSetIdentifierType;

  using HeavisideType = typename Superclass::HeavisideType;
  using HeavisideConstPointer = typename Superclass::HeavisideConstPointer;

  using LevelSetDataType = typename Superclass::LevelSetDataType;

  using DomainMapImageFilterType = typename Superclass::DomainMapImageFilterType;
  using CacheImageType = typename Superclass::CacheImageType;

  using IdListType = typename LevelSetContainerType::IdListType;
  using IdListIterator = typename LevelSetContainerType::IdListIterator;
  using IdListConstIterator = typename LevelSetContainerType::IdListConstIterator;

  using CompensatedSummationType = CompensatedSummation<LevelSetOutputRealType>;

  /** Update the term parameter values at end of iteration */
  void Update() override;

  /** Initialize parameters in the terms prior to an iteration */
  void InitializeParameters() override;

  /** Initialize term parameters in the dense case by computing for each pixel location */
  void Initialize( const LevelSetInputIndexType& index ) override;

  /** Compute the sum of Heaviside functions in the multi-levelset cases
   *  except the current levelset */
  virtual void ComputeSumTerm( const LevelSetInputIndexType& index,
                                  LevelSetOutputRealType& sum );

  /** Supply updates at pixels to keep the term parameters always updated */
  void UpdatePixel( const LevelSetInputIndexType& index,
                            const LevelSetOutputRealType& oldValue,
                            const LevelSetOutputRealType& newValue ) override;

protected:
  LevelSetEquationOverlapPenaltyTerm();

  ~LevelSetEquationOverlapPenaltyTerm() override;

  /** Returns the term contribution for a given location index */
  LevelSetOutputRealType Value( const LevelSetInputIndexType& index ) override;

  /** Returns the term contribution for a given location index */
  LevelSetOutputRealType Value( const LevelSetInputIndexType& index,
                                        const LevelSetDataType& data ) override;

private:
  DomainMapImageFilterType *m_DomainMapImageFilter;
  CacheImageType           *m_CacheImage;
};

}
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkLevelSetEquationOverlapPenaltyTerm.hxx"
#endif

#endif


text:
package fmt

import (
	"errors"
	"io"
	"os"
	"reflect"
	"sync"
	"unicode/utf8"
)

// Strings for use with buffer.WriteString.
// This is less overhead than using buffer.Write with byte arrays.
const (
	commaSpaceString  = ", "
	nilAngleString    = "<nil>"
	nilParenString    = "(nil)"
	nilString         = "nil"
	mapString         = "map["
	percentBangString = "%!"
	missingString     = "(MISSING)"
	badIndexString    = "(BADINDEX)"
	panicString       = "(PANIC="
	extraString       = "%!(EXTRA "
	badWidthString    = "%!(BADWIDTH)"
	badPrecString     = "%!(BADPREC)"
	noVerbString      = "%!(NOVERB)"
	invReflectString  = "<invalid reflect.Value>"
)

// State represents the printer state passed to custom formatters.
// It provides access to the io.Writer interface plus information about
// the flags and options for the operand's format specifier.
type State interface {
	// Write is the function to call to emit formatted output to be printed.
	Write(b []byte) (n int, err error)
	// Width returns the value of the width option and whether it has been set.
	Width() (wid int, ok bool)
	// Precision returns the value of the precision option and whether it has been set.
	Precision() (prec int, ok bool)

	// Flag reports whether the flag c, a character, has been set.
	Flag(c int) bool
}

// Formatter is the interface implemented by values with a custom formatter.
// The implementation of Format may call Sprint(f) or Fprint(f) etc.
// to generate its output.
type Formatter interface {
	Format(f State, c rune)
}

// Stringer is implemented by any value that has a String method,
// which defines the ``native'' format for that value.
// The String method is used to print values passed as an operand
// to any format that accepts a string or to an unformatted printer
// such as Print.
type Stringer interface {
	String() string
}

// GoStringer is implemented by any value that has a GoString method,
// which defines the Go syntax for that value.
// The GoString method is used to print values passed as an operand
// to a %#v format.
type GoStringer interface {
	GoString() string
}

// Use simple []byte instead of bytes.Buffer to avoid large dependency.
type buffer []byte

func (b *buffer) Write(p []byte) {
	*b = append(*b, p...)
}

func (b *buffer) WriteString(s string) {
	*b = append(*b, s...)
}

func (b *buffer) WriteByte(c byte) {
	*b = append(*b, c)
}

func (bp *buffer) WriteRune(r rune) {
	if r < utf8.RuneSelf {
		*bp = append(*bp, byte(r))
		return
	}

	b := *bp
	n := len(b)
	for n+utf8.UTFMax > cap(b) {
		b = append(b, 0)
	}
	w := utf8.EncodeRune(b[n:n+utf8.UTFMax], r)
	*bp = b[:n+w]
}

// pp is used to store a printer's state and is reused with sync.Pool to avoid allocations.
type pp struct {
	buf buffer

	// arg holds the current item, as an interface{}.
	arg interface{}

	// value is used instead of arg for reflect values.
	value reflect.Value

	// fmt is used to format basic items such as integers or strings.
	fmt fmt

	// reordered records whether the format string used argument reordering.
	reordered bool
	// goodArgNum records whether the most recent reordering directive was valid.
	goodArgNum bool
	// panicking is set by catchPanic to avoid infinite panic, recover, panic, ... recursion.
	panicking bool
	// erroring is set when printing an error string to guard against calling handleMethods.
	erroring bool
}

var ppFree = sync.Pool{
	New: func() interface{} { return new(pp) },
}

// newPrinter allocates a new pp struct or grabs a cached one.
func newPrinter() *pp {
	p := ppFree.Get().(*pp)
	p.panicking = false
	p.erroring = false
	p.fmt.init(&p.buf)
	return p
}

// free saves used pp structs in ppFree; avoids an allocation per invocation.
func (p *pp) free() {
	p.buf = p.buf[:0]
	p.arg = nil
	p.value = reflect.Value{}
	ppFree.Put(p)
}

func (p *pp) Width() (wid int, ok bool) { return p.fmt.wid, p.fmt.widPresent }

func (p *pp) Precision() (prec int, ok bool) { return p.fmt.prec, p.fmt.precPresent }

func (p *pp) Flag(b int) bool {
	switch b {
	case '-':
		return p.fmt.minus
	case '+':
		return p.fmt.plus || p.fmt.plusV
	case '#':
		return p.fmt.sharp || p.fmt.sharpV
	case ' ':
		return p.fmt.space
	case '0':
		return p.fmt.zero
	}
	return false
}

// Implement Write so we can call Fprintf on a pp (through State), for
// recursive use in custom verbs.
func (p *pp) Write(b []byte) (ret int, err error) {
	p.buf.Write(b)
	return len(b), nil
}

// These routines end in 'f' and take a format string.

// Fprintf formats according to a format specifier and writes to w.
// It returns the number of bytes written and any write error encountered.
func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
	p := newPrinter()
	p.doPrintf(format, a)
	n, err = w.Write(p.buf)
	p.free()
	return
}

// Printf formats according to a format specifier and writes to standard output.
// It returns the number of bytes written and any write error encountered.
func Printf(format string, a ...interface{}) (n int, err error) {
	return Fprintf(os.Stdout, format, a...)
}

// Sprintf formats according to a format specifier and returns the resulting string.
func Sprintf(format string, a ...interface{}) string {
	p := newPrinter()
	p.doPrintf(format, a)
	s := string(p.buf)
	p.free()
	return s
}

// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, a ...interface{}) error {
	return errors.New(Sprintf(format, a...))
}

// These routines do not take a format string

// Fprint formats using the default formats for its operands and writes to w.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
func Fprint(w io.Writer, a ...interface{}) (n int, err error) {
	p := newPrinter()
	p.doPrint(a)
	n, err = w.Write(p.buf)
	p.free()
	return
}

// Print formats using the default formats for its operands and writes to standard output.
// Spaces are added between operands when neither is a string.
// It returns the number of bytes written and any write error encountered.
func Print(a ...interface{}) (n int, err error) {
	return Fprint(os.Stdout, a...)
}

// Sprint formats using the default formats for its operands and returns the resulting string.
// Spaces are added between operands when neither is a string.
func Sprint(a ...interface{}) string {
	p := newPrinter()
	p.doPrint(a)
	s := string(p.buf)
	p.free()
	return s
}

// These routines end in 'ln', do not take a format string,
// always add spaces between operands, and add a newline
// after the last operand.

// Fprintln formats using the default formats for its operands and writes to w.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
	p := newPrinter()
	p.doPrintln(a)
	n, err = w.Write(p.buf)
	p.free()
	return
}

// Println formats using the default formats for its operands and writes to standard output.
// Spaces are always added between operands and a newline is appended.
// It returns the number of bytes written and any write error encountered.
func Println(a ...interface{}) (n int, err error) {
	return Fprintln(os.Stdout, a...)
}

// Sprintln formats using the default formats for its operands and returns the resulting string.
// Spaces are always added between operands and a newline is appended.
func Sprintln(a ...interface{}) string {
	p := newPrinter()
	p.doPrintln(a)
	s := string(p.buf)
	p.free()
	return s
}

// getField gets the i'th field of the struct value.
// If the field is itself is an interface, return a value for
// the thing inside the interface, not the interface itself.
func getField(v reflect.Value, i int) reflect.Value {
	val := v.Field(i)
	if val.Kind() == reflect.Interface && !val.IsNil() {
		val = val.Elem()
	}
	return val
}

// tooLarge reports whether the magnitude of the integer is
// too large to be used as a formatting width or precision.
func tooLarge(x int) bool {
	const max int = 1e6
	return x > max || x < -max
}

// parsenum converts ASCII to integer.  num is 0 (and isnum is false) if no number present.
func parsenum(s string, start, end int) (num int, isnum bool, newi int) {
	if start >= end {
		return 0, false, end
	}
	for newi = start; newi < end && '0' <= s[newi] && s[newi] <= '9'; newi++ {
		if tooLarge(num) {
			return 0, false, end // Overflow; crazy long number most likely.
		}
		num = num*10 + int(s[newi]-'0')
		isnum = true
	}
	return
}

func (p *pp) unknownType(v reflect.Value) {
	if !v.IsValid() {
		p.buf.WriteString(nilAngleString)
		return
	}
	p.buf.WriteByte('?')
	p.buf.WriteString(v.Type().String())
	p.buf.WriteByte('?')
}

func (p *pp) badVerb(verb rune) {
	p.erroring = true
	p.buf.WriteString(percentBangString)
	p.buf.WriteRune(verb)
	p.buf.WriteByte('(')
	switch {
	case p.arg != nil:
		p.buf.WriteString(reflect.TypeOf(p.arg).String())
		p.buf.WriteByte('=')
		p.printArg(p.arg, 'v')
	case p.value.IsValid():
		p.buf.WriteString(p.value.Type().String())
		p.buf.WriteByte('=')
		p.printValue(p.value, 'v', 0)
	default:
		p.buf.WriteString(nilAngleString)
	}
	p.buf.WriteByte(')')
	p.erroring = false
}

func (p *pp) fmtBool(v bool, verb rune) {
	switch verb {
	case 't', 'v':
		p.fmt.fmt_boolean(v)
	default:
		p.badVerb(verb)
	}
}

// fmt0x64 formats a uint64 in hexadecimal and prefixes it with 0x or
// not, as requested, by temporarily setting the sharp flag.
func (p *pp) fmt0x64(v uint64, leading0x bool) {
	sharp := p.fmt.sharp
	p.fmt.sharp = leading0x
	p.fmt.fmt_integer(v, 16, unsigned, ldigits)
	p.fmt.sharp = sharp
}

// fmtInteger formats a signed or unsigned integer.
func (p *pp) fmtInteger(v uint64, isSigned bool, verb rune) {
	switch verb {
	case 'v':
		if p.fmt.sharpV && !isSigned {
			p.fmt0x64(v, true)
		} else {
			p.fmt.fmt_integer(v, 10, isSigned, ldigits)
		}
	case 'd':
		p.fmt.fmt_integer(v, 10, isSigned, ldigits)
	case 'b':
		p.fmt.fmt_integer(v, 2, isSigned, ldigits)
	case 'o':
		p.fmt.fmt_integer(v, 8, isSigned, ldigits)
	case 'x':
		p.fmt.fmt_integer(v, 16, isSigned, ldigits)
	case 'X':
		p.fmt.fmt_integer(v, 16, isSigned, udigits)
	case 'c':
		p.fmt.fmt_c(v)
	case 'q':
		if v <= utf8.MaxRune {
			p.fmt.fmt_qc(v)
		} else {
			p.badVerb(verb)
		}
	case 'U':
		p.fmt.fmt_unicode(v)
	default:
		p.badVerb(verb)
	}
}

// fmtFloat formats a float. The default precision for each verb
// is specified as last argument in the call to fmt_float.
func (p *pp) fmtFloat(v float64, size int, verb rune) {
	switch verb {
	case 'v':
		p.fmt.fmt_float(v, size, 'g', -1)
	case 'b', 'g', 'G':
		p.fmt.fmt_float(v, size, verb, -1)
	case 'f', 'e', 'E':
		p.fmt.fmt_float(v, size, verb, 6)
	case 'F':
		p.fmt.fmt_float(v, size, 'f', 6)
	default:
		p.badVerb(verb)
	}
}

// fmtComplex formats a complex number v with
// r = real(v) and j = imag(v) as (r+ji) using
// fmtFloat for r and j formatting.
func (p *pp) fmtComplex(v complex128, size int, verb rune) {
	// Make sure any unsupported verbs are found before the
	// calls to fmtFloat to not generate an incorrect error string.
	switch verb {
	case 'v', 'b', 'g', 'G', 'f', 'F', 'e', 'E':
		oldPlus := p.fmt.plus
		p.buf.WriteByte('(')
		p.fmtFloat(real(v), size/2, verb)
		// Imaginary part always has a sign.
		p.fmt.plus = true
		p.fmtFloat(imag(v), size/2, verb)
		p.buf.WriteString("i)")
		p.fmt.plus = oldPlus
	default:
		p.badVerb(verb)
	}
}

func (p *pp) fmtString(v string, verb rune) {
	switch verb {
	case 'v':
		if p.fmt.sharpV {
			p.fmt.fmt_q(v)
		} else {
			p.fmt.fmt_s(v)
		}
	case 's':
		p.fmt.fmt_s(v)
	case 'x':
		p.fmt.fmt_sx(v, ldigits)
	case 'X':
		p.fmt.fmt_sx(v, udigits)
	case 'q':
		p.fmt.fmt_q(v)
	default:
		p.badVerb(verb)
	}
}

func (p *pp) fmtBytes(v []byte, verb rune, typeString string) {
	switch verb {
	case 'v', 'd':
		if p.fmt.sharpV {
			p.buf.WriteString(typeString)
			if v == nil {
				p.buf.WriteString(nilParenString)
				return
			}
			p.buf.WriteByte('{')
			for i, c := range v {
				if i > 0 {
					p.buf.WriteString(commaSpaceString)
				}
				p.fmt0x64(uint64(c), true)
			}
			p.buf.WriteByte('}')
		} else {
			p.buf.WriteByte('[')
			for i, c := range v {
				if i > 0 {
					p.buf.WriteByte(' ')
				}
				p.fmt.fmt_integer(uint64(c), 10, unsigned, ldigits)
			}
			p.buf.WriteByte(']')
		}
	case 's':
		p.fmt.fmt_s(string(v))
	case 'x':
		p.fmt.fmt_bx(v, ldigits)
	case 'X':
		p.fmt.fmt_bx(v, udigits)
	case 'q':
		p.fmt.fmt_q(string(v))
	default:
		p.printValue(reflect.ValueOf(v), verb, 0)
	}
}

func (p *pp) fmtPointer(value reflect.Value, verb rune) {
	var u uintptr
	switch value.Kind() {
	case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.Slice, reflect.UnsafePointer:
		u = value.Pointer()
	default:
		p.badVerb(verb)
		return
	}

	switch verb {
	case 'v':
		if p.fmt.sharpV {
			p.buf.WriteByte('(')
			p.buf.WriteString(value.Type().String())
			p.buf.WriteString(")(")
			if u == 0 {
				p.buf.WriteString(nilString)
			} else {
				p.fmt0x64(uint64(u), true)
			}
			p.buf.WriteByte(')')
		} else {
			if u == 0 {
				p.fmt.padString(nilAngleString)
			} else {
				p.fmt0x64(uint64(u), !p.fmt.sharp)
			}
		}
	case 'p':
		p.fmt0x64(uint64(u), !p.fmt.sharp)
	case 'b', 'o', 'd', 'x', 'X':
		p.fmtInteger(uint64(u), unsigned, verb)
	default:
		p.badVerb(verb)
	}
}

func (p *pp) catchPanic(arg interface{}, verb rune) {
	if err := recover(); err != nil {
		// If it's a nil pointer, just say "<nil>". The likeliest causes are a
		// Stringer that fails to guard against nil or a nil pointer for a
		// value receiver, and in either case, "<nil>" is a nice result.
		if v := reflect.ValueOf(arg); v.Kind() == reflect.Ptr && v.IsNil() {
			p.buf.WriteString(nilAngleString)
			return
		}
		// Otherwise print a concise panic message. Most of the time the panic
		// value will print itself nicely.
		if p.panicking {
			// Nested panics; the recursion in printArg cannot succeed.
			panic(err)
		}

		oldFlags := p.fmt.fmtFlags
		// For this output we want default behavior.
		p.fmt.clearflags()

		p.buf.WriteString(percentBangString)
		p.buf.WriteRune(verb)
		p.buf.WriteString(panicString)
		p.panicking = true
		p.printArg(err, 'v')
		p.panicking = false
		p.buf.WriteByte(')')

		p.fmt.fmtFlags = oldFlags
	}
}

func (p *pp) handleMethods(verb rune) (handled bool) {
	if p.erroring {
		return
	}
	// Is it a Formatter?
	if formatter, ok := p.arg.(Formatter); ok {
		handled = true
		defer p.catchPanic(p.arg, verb)
		formatter.Format(p, verb)
		return
	}

	// If we're doing Go syntax and the argument knows how to supply it, take care of it now.
	if p.fmt.sharpV {
		if stringer, ok := p.arg.(GoStringer); ok {
			handled = true
			defer p.catchPanic(p.arg, verb)
			// Print the result of GoString unadorned.
			p.fmt.fmt_s(stringer.GoString())
			return
		}
	} else {
		// If a string is acceptable according to the format, see if
		// the value satisfies one of the string-valued interfaces.
		// Println etc. set verb to %v, which is "stringable".
		switch verb {
		case 'v', 's', 'x', 'X', 'q':
			// Is it an error or Stringer?
			// The duplication in the bodies is necessary:
			// setting handled and deferring catchPanic
			// must happen before calling the method.
			switch v := p.arg.(type) {
			case error:
				handled = true
				defer p.catchPanic(p.arg, verb)
				p.fmtString(v.Error(), verb)
				return

			case Stringer:
				handled = true
				defer p.catchPanic(p.arg, verb)
				p.fmtString(v.String(), verb)
				return
			}
		}
	}
	return false
}

func (p *pp) printArg(arg interface{}, verb rune) {
	p.arg = arg
	p.value = reflect.Value{}

	if arg == nil {
		switch verb {
		case 'T', 'v':
			p.fmt.padString(nilAngleString)
		default:
			p.badVerb(verb)
		}
		return
	}

	// Special processing considerations.
	// %T (the value's type) and %p (its address) are special; we always do them first.
	switch verb {
	case 'T':
		p.fmt.fmt_s(reflect.TypeOf(arg).String())
		return
	case 'p':
		p.fmtPointer(reflect.ValueOf(arg), 'p')
		return
	}

	// Some types can be done without reflection.
	switch f := arg.(type) {
	case bool:
		p.fmtBool(f, verb)
	case float32:
		p.fmtFloat(float64(f), 32, verb)
	case float64:
		p.fmtFloat(f, 64, verb)
	case complex64:
		p.fmtComplex(complex128(f), 64, verb)
	case complex128:
		p.fmtComplex(f, 128, verb)
	case int:
		p.fmtInteger(uint64(f), signed, verb)
	case int8:
		p.fmtInteger(uint64(f), signed, verb)
	case int16:
		p.fmtInteger(uint64(f), signed, verb)
	case int32:
		p.fmtInteger(uint64(f), signed, verb)
	case int64:
		p.fmtInteger(uint64(f), signed, verb)
	case uint:
		p.fmtInteger(uint64(f), unsigned, verb)
	case uint8:
		p.fmtInteger(uint64(f), unsigned, verb)
	case uint16:
		p.fmtInteger(uint64(f), unsigned, verb)
	case uint32:
		p.fmtInteger(uint64(f), unsigned, verb)
	case uint64:
		p.fmtInteger(f, unsigned, verb)
	case uintptr:
		p.fmtInteger(uint64(f), unsigned, verb)
	case string:
		p.fmtString(f, verb)
	case []byte:
		p.fmtBytes(f, verb, "[]byte")
	case reflect.Value:
		// Handle extractable values with special methods
		// since printValue does not handle them at depth 0.
		if f.IsValid() && f.CanInterface() {
			p.arg = f.Interface()
			if p.handleMethods(verb) {
				return
			}
		}
		p.printValue(f, verb, 0)
	default:
		// If the type is not simple, it might have methods.
		if !p.handleMethods(verb) {
			// Need to use reflection, since the type had no
			// interface methods that could be used for formatting.
			p.printValue(reflect.ValueOf(f), verb, 0)
		}
	}
}

// printValue is similar to printArg but starts with a reflect value, not an interface{} value.
// It does not handle 'p' and 'T' verbs because these should have been already handled by printArg.
func (p *pp) printValue(value reflect.Value, verb rune, depth int) {
	// Handle values with special methods if not already handled by printArg (depth == 0).
	if depth > 0 && value.IsValid() && value.CanInterface() {
		p.arg = value.Interface()
		if p.handleMethods(verb) {
			return
		}
	}
	p.arg = nil
	p.value = value

	switch f := value; value.Kind() {
	case reflect.Invalid:
		if depth == 0 {
			p.buf.WriteString(invReflectString)
		} else {
			switch verb {
			case 'v':
				p.buf.WriteString(nilAngleString)
			default:
				p.badVerb(verb)
			}
		}
	case reflect.Bool:
		p.fmtBool(f.Bool(), verb)
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		p.fmtInteger(uint64(f.Int()), signed, verb)
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		p.fmtInteger(f.Uint(), unsigned, verb)
	case reflect.Float32:
		p.fmtFloat(f.Float(), 32, verb)
	case reflect.Float64:
		p.fmtFloat(f.Float(), 64, verb)
	case reflect.Complex64:
		p.fmtComplex(f.Complex(), 64, verb)
	case reflect.Complex128:
		p.fmtComplex(f.Complex(), 128, verb)
	case reflect.String:
		p.fmtString(f.String(), verb)
	case reflect.Map:
		if p.fmt.sharpV {
			p.buf.WriteString(f.Type().String())
			if f.IsNil() {
				p.buf.WriteString(nilParenString)
				return
			}
			p.buf.WriteByte('{')
		} else {
			p.buf.WriteString(mapString)
		}
		keys := f.MapKeys()
		for i, key := range keys {
			if i > 0 {
				if p.fmt.sharpV {
					p.buf.WriteString(commaSpaceString)
				} else {
					p.buf.WriteByte(' ')
				}
			}
			p.printValue(key, verb, depth+1)
			p.buf.WriteByte(':')
			p.printValue(f.MapIndex(key), verb, depth+1)
		}
		if p.fmt.sharpV {
			p.buf.WriteByte('}')
		} else {
			p.buf.WriteByte(']')
		}
	case reflect.Struct:
		if p.fmt.sharpV {
			p.buf.WriteString(f.Type().String())
		}
		p.buf.WriteByte('{')
		for i := 0; i < f.NumField(); i++ {
			if i > 0 {
				if p.fmt.sharpV {
					p.buf.WriteString(commaSpaceString)
				} else {
					p.buf.WriteByte(' ')
				}
			}
			if p.fmt.plusV || p.fmt.sharpV {
				if name := f.Type().Field(i).Name; name != "" {
					p.buf.WriteString(name)
					p.buf.WriteByte(':')
				}
			}
			p.printValue(getField(f, i), verb, depth+1)
		}
		p.buf.WriteByte('}')
	case reflect.Interface:
		value := f.Elem()
		if !value.IsValid() {
			if p.fmt.sharpV {
				p.buf.WriteString(f.Type().String())
				p.buf.WriteString(nilParenString)
			} else {
				p.buf.WriteString(nilAngleString)
			}
		} else {
			p.printValue(value, verb, depth+1)
		}
	case reflect.Array, reflect.Slice:
		switch verb {
		case 's', 'q', 'x', 'X':
			// Handle byte and uint8 slices and arrays special for the above verbs.
			t := f.Type()
			if t.Elem().Kind() == reflect.Uint8 {
				var bytes []byte
				if f.Kind() == reflect.Slice {
					bytes = f.Bytes()
				} else if f.CanAddr() {
					bytes = f.Slice(0, f.Len()).Bytes()
				} else {
					// We have an array, but we cannot Slice() a non-addressable array,
					// so we build a slice by hand. This is a rare case but it would be nice
					// if reflection could help a little more.
					bytes = make([]byte, f.Len())
					for i := range bytes {
						bytes[i] = byte(f.Index(i).Uint())
					}
				}
				p.fmtBytes(bytes, verb, t.String())
				return
			}
		}
		if p.fmt.sharpV {
			p.buf.WriteString(f.Type().String())
			if f.Kind() == reflect.Slice && f.IsNil() {
				p.buf.WriteString(nilParenString)
				return
			}
			p.buf.WriteByte('{')
			for i := 0; i < f.Len(); i++ {
				if i > 0 {
					p.buf.WriteString(commaSpaceString)
				}
				p.printValue(f.Index(i), verb, depth+1)
			}
			p.buf.WriteByte('}')
		} else {
			p.buf.WriteByte('[')
			for i := 0; i < f.Len(); i++ {
				if i > 0 {
					p.buf.WriteByte(' ')
				}
				p.printValue(f.Index(i), verb, depth+1)
			}
			p.buf.WriteByte(']')
		}
	case reflect.Ptr:
		// pointer to array or slice or struct?  ok at top level
		// but not embedded (avoid loops)
		if depth == 0 && f.Pointer() != 0 {
			switch a := f.Elem(); a.Kind() {
			case reflect.Array, reflect.Slice, reflect.Struct, reflect.Map:
				p.buf.WriteByte('&')
				p.printValue(a, verb, depth+1)
				return
			}
		}
		fallthrough
	case reflect.Chan, reflect.Func, reflect.UnsafePointer:
		p.fmtPointer(f, verb)
	default:
		p.unknownType(f)
	}
}

// intFromArg gets the argNumth element of a. On return, isInt reports whether the argument has integer type.
func intFromArg(a []interface{}, argNum int) (num int, isInt bool, newArgNum int) {
	newArgNum = argNum
	if argNum < len(a) {
		num, isInt = a[argNum].(int) // Almost always OK.
		if !isInt {
			// Work harder.
			switch v := reflect.ValueOf(a[argNum]); v.Kind() {
			case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
				n := v.Int()
				if int64(int(n)) == n {
					num = int(n)
					isInt = true
				}
			case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
				n := v.Uint()
				if int64(n) >= 0 && uint64(int(n)) == n {
					num = int(n)
					isInt = true
				}
			default:
				// Already 0, false.
			}
		}
		newArgNum = argNum + 1
		if tooLarge(num) {
			num = 0
			isInt = false
		}
	}
	return
}

// parseArgNumber returns the value of the bracketed number, minus 1
// (explicit argument numbers are one-indexed but we want zero-indexed).
// The opening bracket is known to be present at format[0].
// The returned values are the index, the number of bytes to consume
// up to the closing paren, if present, and whether the number parsed
// ok. The bytes to consume will be 1 if no closing paren is present.
func parseArgNumber(format string) (index int, wid int, ok bool) {
	// There must be at least 3 bytes: [n].
	if len(format) < 3 {
		return 0, 1, false
	}

	// Find closing bracket.
	for i := 1; i < len(format); i++ {
		if format[i] == ']' {
			width, ok, newi := parsenum(format, 1, i)
			if !ok || newi != i {
				return 0, i + 1, false
			}
			return width - 1, i + 1, true // arg numbers are one-indexed and skip paren.
		}
	}
	return 0, 1, false
}

// argNumber returns the next argument to evaluate, which is either the value of the passed-in
// argNum or the value of the bracketed integer that begins format[i:]. It also returns
// the new value of i, that is, the index of the next byte of the format to process.
func (p *pp) argNumber(argNum int, format string, i int, numArgs int) (newArgNum, newi int, found bool) {
	if len(format) <= i || format[i] != '[' {
		return argNum, i, false
	}
	p.reordered = true
	index, wid, ok := parseArgNumber(format[i:])
	if ok && 0 <= index && index < numArgs {
		return index, i + wid, true
	}
	p.goodArgNum = false
	return argNum, i + wid, ok
}

func (p *pp) badArgNum(verb rune) {
	p.buf.WriteString(percentBangString)
	p.buf.WriteRune(verb)
	p.buf.WriteString(badIndexString)
}

func (p *pp) missingArg(verb rune) {
	p.buf.WriteString(percentBangString)
	p.buf.WriteRune(verb)
	p.buf.WriteString(missingString)
}

func (p *pp) doPrintf(format string, a []interface{}) {
	end := len(format)
	argNum := 0         // we process one argument per non-trivial format
	afterIndex := false // previous item in format was an index like [3].
	p.reordered = false
formatLoop:
	for i := 0; i < end; {
		p.goodArgNum = true
		lasti := i
		for i < end && format[i] != '%' {
			i++
		}
		if i > lasti {
			p.buf.WriteString(format[lasti:i])
		}
		if i >= end {
			// done processing format string
			break
		}

		// Process one verb
		i++

		// Do we have flags?
		p.fmt.clearflags()
	simpleFormat:
		for ; i < end; i++ {
			c := format[i]
			switch c {
			case '#':
				p.fmt.sharp = true
			case '0':
				p.fmt.zero = !p.fmt.minus // Only allow zero padding to the left.
			case '+':
				p.fmt.plus = true
			case '-':
				p.fmt.minus = true
				p.fmt.zero = false // Do not pad with zeros to the right.
			case ' ':
				p.fmt.space = true
			default:
				// Fast path for common case of ascii lower case simple verbs
				// without precision or width or argument indices.
				if 'a' <= c && c <= 'z' && argNum < len(a) {
					if c == 'v' {
						// Go syntax
						p.fmt.sharpV = p.fmt.sharp
						p.fmt.sharp = false
						// Struct-field syntax
						p.fmt.plusV = p.fmt.plus
						p.fmt.plus = false
					}
					p.printArg(a[argNum], rune(c))
					argNum++
					i++
					continue formatLoop
				}
				// Format is more complex than simple flags and a verb or is malformed.
				break simpleFormat
			}
		}

		// Do we have an explicit argument index?
		argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))

		// Do we have width?
		if i < end && format[i] == '*' {
			i++
			p.fmt.wid, p.fmt.widPresent, argNum = intFromArg(a, argNum)

			if !p.fmt.widPresent {
				p.buf.WriteString(badWidthString)
			}

			// We have a negative width, so take its value and ensure
			// that the minus flag is set
			if p.fmt.wid < 0 {
				p.fmt.wid = -p.fmt.wid
				p.fmt.minus = true
				p.fmt.zero = false // Do not pad with zeros to the right.
			}
			afterIndex = false
		} else {
			p.fmt.wid, p.fmt.widPresent, i = parsenum(format, i, end)
			if afterIndex && p.fmt.widPresent { // "%[3]2d"
				p.goodArgNum = false
			}
		}

		// Do we have precision?
		if i+1 < end && format[i] == '.' {
			i++
			if afterIndex { // "%[3].2d"
				p.goodArgNum = false
			}
			argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
			if i < end && format[i] == '*' {
				i++
				p.fmt.prec, p.fmt.precPresent, argNum = intFromArg(a, argNum)
				// Negative precision arguments don't make sense
				if p.fmt.prec < 0 {
					p.fmt.prec = 0
					p.fmt.precPresent = false
				}
				if !p.fmt.precPresent {
					p.buf.WriteString(badPrecString)
				}
				afterIndex = false
			} else {
				p.fmt.prec, p.fmt.precPresent, i = parsenum(format, i, end)
				if !p.fmt.precPresent {
					p.fmt.prec = 0
					p.fmt.precPresent = true
				}
			}
		}

		if !afterIndex {
			argNum, i, afterIndex = p.argNumber(argNum, format, i, len(a))
		}

		if i >= end {
			p.buf.WriteString(noVerbString)
			break
		}

		verb, w := utf8.DecodeRuneInString(format[i:])
		i += w

		switch {
		case verb == '%': // Percent does not absorb operands and ignores f.wid and f.prec.
			p.buf.WriteByte('%')
		case !p.goodArgNum:
			p.badArgNum(verb)
		case argNum >= len(a): // No argument left over to print for the current verb.
			p.missingArg(verb)
		case verb == 'v':
			// Go syntax
			p.fmt.sharpV = p.fmt.sharp
			p.fmt.sharp = false
			// Struct-field syntax
			p.fmt.plusV = p.fmt.plus
			p.fmt.plus = false
			fallthrough
		default:
			p.printArg(a[argNum], verb)
			argNum++
		}
	}

	// Check for extra arguments unless the call accessed the arguments
	// out of order, in which case it's too expensive to detect if they've all
	// been used and arguably OK if they're not.
	if !p.reordered && argNum < len(a) {
		p.fmt.clearflags()
		p.buf.WriteString(extraString)
		for i, arg := range a[argNum:] {
			if i > 0 {
				p.buf.WriteString(commaSpaceString)
			}
			if arg == nil {
				p.buf.WriteString(nilAngleString)
			} else {
				p.buf.WriteString(reflect.TypeOf(arg).String())
				p.buf.WriteByte('=')
				p.printArg(arg, 'v')
			}
		}
		p.buf.WriteByte(')')
	}
}

func (p *pp) doPrint(a []interface{}) {
	prevString := false
	for argNum, arg := range a {
		isString := arg != nil && reflect.TypeOf(arg).Kind() == reflect.String
		// Add a space between two non-string arguments.
		if argNum > 0 && !isString && !prevString {
			p.buf.WriteByte(' ')
		}
		p.printArg(arg, 'v')
		prevString = isString
	}
}

// doPrintln is like doPrint but always adds a space between arguments
// and a newline after the last argument.
func (p *pp) doPrintln(a []interface{}) {
	for argNum, arg := range a {
		if argNum > 0 {
			p.buf.WriteByte(' ')
		}
		p.printArg(arg, 'v')
	}
	p.buf.WriteByte('\n')
}


text:
export class A {
  foo() {
    throw new Error('test-intepreter');
  }
}


text:
#include "tensorflow/core/kernels/cwise_ops_common.h"
#include "tensorflow/core/kernels/cwise_ops_gradients.h"

namespace tensorflow {
REGISTER4(UnaryOp, CPU, "Asinh", functor::asinh, float, double, complex64,
          complex128);

#ifdef TENSORFLOW_USE_SYCL
REGISTER2(UnaryOp, SYCL, "Asinh", functor::asinh, float, double);
#endif  // TENSORFLOW_USE_SYCL

#if GOOGLE_CUDA
REGISTER2(UnaryOp, GPU, "Asinh", functor::asinh, float, double);
#endif
}  // namespace tensorflow


text:
class Libpointmatcher < Formula
  desc "An Iterative Closest Point library for 2-D/3-D mapping in robotic
"
  homepage "https://github.com/ethz-asl/libpointmatcher"
  url  "https://github.com/ethz-asl/libpointmatcher.git", :branch => "master"
  head "https://github.com/ethz-asl/libpointmatcher.git"
  version "1.2.1"

  depends_on "cmake" => :build
  depends_on "boost"
  depends_on "eigen"
  depends_on "libnabo"

  def install
    cmake_args = std_cmake_args + %W[
      -DBoost_DIR=#{Formula["boost"].opt_prefix}
    ]

    mkdir "build" do
      system "cmake", "-G", "Unix Makefiles", "..", *cmake_args
      system "make"
      system "make", "install"
   end
  end

  test do
    system "false"
  end
end


text:
START_ATF_NAMESPACE
    namespace Detail
    {
        extern ::std::array<hook_record, 2> _pt_notify_final_decision_functions;
    }; // end namespace Detail
END_ATF_NAMESPACE


text:
FROM microsoft/nanoserver:10.0.14393.206

# Install .NET Core
ENV DOTNET_VERSION 1.0.1
ENV DOTNET_DOWNLOAD_URL https://dotnetcli.blob.core.windows.net/dotnet/preview/Binaries/$DOTNET_VERSION/dotnet-win-x64.$DOTNET_VERSION.zip

RUN powershell -NoProfile -Command \
        $ErrorActionPreference = 'Stop'; \
        Invoke-WebRequest %DOTNET_DOWNLOAD_URL% -OutFile dotnet.zip; \
        Expand-Archive dotnet.zip -DestinationPath '%ProgramFiles%\dotnet'; \
        Remove-Item -Force dotnet.zip

RUN setx /M PATH "%PATH%;%ProgramFiles%\dotnet"


text:
import      os

class   Make_P2:

    conf_lst = {}
    e = False
    root_dir = ""

    def     init(self, c_lst, ex, root_dir):
        self.conf_lst = c_lst
        self.e = ex
        self.root_dir = root_dir
        self.config = {
            "name": "make", # Name of the package
            "version": "4.2.1", # Version of the package
            "size": 12.6, # Size of the installed package (MB)
            "archive": "make-4.2.1.tar.bz2", # Archive name
            "SBU": 0.6, # SBU (Compilation time)
            "tmp_install": False, # Is this package part of the temporary install
            "next": "patch", # Next package to install
            "before": False,
            "after": False,
            "urls": [ # Url to download the package. The first one must be morphux servers
                "https://install.morphux.org/packages/make-4.2.1.tar.bz2"
            ]
        }
        return self.config

    def     configure(self):
        return self.e(["./configure",
                "--prefix=/usr",
        ])

    def     make(self):
        return self.e(["make", "-j", self.conf_lst["cpus"]])

    def     install(self):
        return self.e(["make", "install"])


text:
import os, sys, getopt
import cv

from socket import *
cs = socket(AF_INET, SOCK_DGRAM)
cs.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
#cs.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)

udp_ip = '127.0.0.1'
udp_port = 45454
capture_size = [320,200]
haarfile ='haarcascade_frontalface_alt.xml'
showvideo = False

class FaceDetect():
	def __init__(self):
		if showvideo:
			cv.NamedWindow ("CamShiftDemo", 1)
		device = 0
		self.capture = cv.CaptureFromCAM(device)
		cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_WIDTH, capture_size[0])
		cv.SetCaptureProperty(self.capture, cv.CV_CAP_PROP_FRAME_HEIGHT, capture_size[1])

	def detect(self):
		cv.CvtColor(self.frame, self.grayscale, cv.CV_RGB2GRAY)

		#equalize histogram
		cv.EqualizeHist(self.grayscale, self.grayscale)

		# detect objects
		faces = cv.HaarDetectObjects(image=self.grayscale, cascade=self.cascade, storage=self.storage, scale_factor=1.2,\
									 min_neighbors=2, flags=cv.CV_HAAR_DO_CANNY_PRUNING)
		if faces:
			#print 'face detected!'
			for i in faces:
				if i[1] > 10:
					center = ((2*i[0][0]+i[0][2])/2,(2*i[0][1]+i[0][3])/2)
					#print  center, i, i[0][2]*i[0][3], framesize,size
					packet = '%d %d %d %d' % (center[0], center[1], i[0][2], i[0][3])
					cs.sendto(packet, (udp_ip, udp_port))
					if showvideo:
						radius = (i[0][2]+i[0][3])/4
						cv.Circle(self.frame, center, radius, (128, 255, 128), 2, 8, 0)

	def run(self):
		# check if capture device is OK
		if not self.capture:
			print "Error opening capture device"
			sys.exit(1)

		self.frame = cv.QueryFrame(self.capture)
		self.image_size = cv.GetSize(self.frame)

		# create grayscale version
		self.grayscale = cv.CreateImage(self.image_size, 8, 1)

		# create storage
		self.storage = cv.CreateMemStorage(128)
		self.cascade = cv.Load(haarfile)

		while 1:
			# do forever
			# capture the current frame
			self.frame = cv.QueryFrame(self.capture)
			if self.frame is None:
				break

			# mirror
			cv.Flip(self.frame, None, 1)

			# face detection
			self.detect()

			# display webcam image
			if showvideo:
				cv.ShowImage('CamShiftDemo', self.frame)

			# handle events
			k = cv.WaitKey(10)

if __name__ == "__main__":
	help_string = """python haar_stream.py [PARAMS]
	-o --ip     defaults to '127.0.0.1'
	-p --port   defaults to 45454
	-v --video  open a window with the video preview
	-s --size   defaults to '320x200'
	-f --file   defaults to 'haarcascade_frontalface_alt.xml'"""

	argv = sys.argv[1:]
	try:
		opts, args = getopt.getopt(argv,"hvo:p:s:f:",["help","view","ip=", "port=", "size=", "file="])
	except getopt.GetoptError:
		print help_string
		sys.exit(2)
	for opt, arg in opts:
		if opt in ("-h", "--help"):
			print help_string
			sys.exit()
		elif opt in ("-v", "--video"):
			showvideo = True
		elif opt in ("-f", "--file"):
			haarfile = arg
		elif opt in ("-o", "--ip"):
			udp_ip = arg
		elif opt in ("-p", "--port"):
			udp_port = int(arg)
		elif opt in ("-s", "--size"):
			capture_size = [int(n) for n in arg.split('x', 2 )];

	face_detect = FaceDetect()
	face_detect.run()


text:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.grid_search import GridSearchCV
from sklearn.externals import joblib

import time
import datetime
import math

months = ["apr", "may", "jun", "jul", "aug", "sep"]
days_eng = ["Mon", "Tues", "Wed", "Thurs", "Fri", "Sat", "Sun"]

for month in months:
    for day in days_eng:

        filename = month+day+"2014.csv"
        df = pd.read_csv(filename)
        X = []
        y = []

        datetimedf=df.loc[:,'Date/Time']
        t=pd.to_datetime(datetimedf, format="%m/%d/%Y %H:%M:%S")

        df["Hour"] = t.dt.hour
        df["Week"] = t.dt.week

        dataframes = []

        for i in range(24):
            # doing this to get each hour for each week. So if there are 5 weeks
            # we need to get 5 data points for each of 24 hour intervals
            # df.Hour % 24 is done by using groupby('Hour').count() few lines below.
            df_new = df.loc[df.Week % 24 == i]
            dataframes.append(df_new)

        for dframe in dataframes:
            dframe = dframe.groupby("Hour").count()
            dframe = dframe[dframe.columns[0]]

            for idx, i in enumerate(dframe.as_matrix()):
                y.append([i])
                X.append([idx])

            # one week scatter plot
            # if month == 'jul' and day == 'Sun':
            #     plt.scatter(X, y, s = 1)
            #     plt.legend(loc="lower right")
            #     plt.title("RandomForest Regression " + month + " " + day)
            #     plt.xlabel("Hours")
            #     plt.ylabel("Number of Pickups")
            #     plt.show()

        y = np.asarray(y)
        X = np.asarray(X)

        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4, random_state = 42)

        # perform gridsearch with cv = 5
        rf = RandomForestRegressor()
        params = {'n_estimators': [x for x in range(10, 40, 2)], 'max_depth': [x for x in range(1, 7)]}
        reg = GridSearchCV(estimator = rf, param_grid = params, cv = 5)
        reg.fit(X_train, y_train)
        print("best params: ", reg.best_params_)

        rf = RandomForestRegressor(n_estimators = reg.best_params_['n_estimators'], max_depth = reg.best_params_['max_depth'])
        rf.fit(X_train, y_train)

        r2_train = r2_score(y_train, rf.predict(X_train))
        r2_test = r2_score(y_test, rf.predict(X_test))

        # filename = "./Result/" + month+day+"2014.pkl"
        # joblib.dump(rf, filename, compress=9)

        filename = "./Result/rep.txt"

        with open(filename, 'a') as f:
            f.write("year: 2014 month: " + month + " day: " + day + " train r2: "
                + str(r2_train) + " test r2: " + str(r2_test) + "\n")

        print("train r2", r2_train)
        print("test r2",r2_test)

        scatter plot (all weeks cumulative)

        # if month == 'jul' and day == 'Fri':
        #     plt.scatter(X, y, s = 1)
        #     plt.legend(loc="lower right")
        #     plt.title("RandomForest Regression " + month + " " + day)
        #     plt.xlabel("Hours")
        #     plt.ylabel("Number of Pickups")
        #     plt.show()


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

using MonoDevelop.Core;
using Paket;

namespace MonoDevelop.Paket
{
	public class SimplifyPaketAction : PaketAction
	{
		FilePath dependenciesFileName;

		public SimplifyPaketAction (FilePath dependenciesFileName)
		{
			this.dependenciesFileName = dependenciesFileName;
		}

		public override void Run ()
		{
			Dependencies.Locate (dependenciesFileName)
				.Simplify (false);
			PaketServices.FileChangedNotifier.NotifyAllPaketAndProjectFilesChangedInSolution ();
		}
	}
}


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="css/normalize.min.css">
        <link rel="stylesheet" href="css/trg.css">
        <link rel="stylesheet" href="css/main.css">

                        <form id="search-form" class="debug">
                            <input type="text" class="bdw-1 bds-solid bdc-fog bgc-bone p-xs debug bdrds-lg">
                        </form>

                        login

                big background image

                    profile info

                    timeline

                    ads n' shit


text:
const fs = require('fs-extra');
const path = require("path");

const ErrorHandlerAPI = require('../../api/errorHandlerAPI');

class LocalCopyExport extends ErrorHandlerAPI {
	constructor(config) {
		super(config);
	}

	exportFile(sourceFileName, runId, errorLog) {

        return new Promise((resolve, reject) => {

            if(!this.config.file) {
                reject('No target file name.');
                return;
            }

            if(sourceFileName) {
                let targetFileName;

	            if(this.config.base) {
		            targetFileName = path.resolve(this.config.base, this.config.file);
	            } else {
		            targetFileName = path.resolve(this.config.file);
	            }

                fs.copySync(sourceFileName, targetFileName);

	            if(this.config.doLog) {
		            this.warning('File copied');
	            }

				resolve(path.basename(targetFileName));
			} else {
	            resolve(null);
            }
        });
    }

    static get Type() {
        return "exporter";
    }

    static get ConfigProperties() {
        return [
            {
                name: 'file',
                label: 'Destination file path',
                type: 'string',
                tooltip: 'The full path to where the processed file should be placed'
            },
	        {
		        name: 'base',
		        label: 'Destination file base path',
		        type: 'string',
		        tooltip: 'The full path to a base folder where the file should be placed (optional and pre-pended to the file)'
	        }
        ];
    }

};

module.exports = LocalCopyExport;


text:
An array **a** is called *beautiful* if for every pair of numbers **ai**, **aj**, (**i ≠ j**), there exists an **ak** such that **ak = ai * aj**. Note that **k** can be equal to **i** or **j** too.

Find out whether the given array **a** is *beautiful* or not!

### Input ###
First line of the input contains an integer **T** denoting the number of test cases. **T** test cases follow.

First line of each test case contains an integer **n** denoting number of elements in **a**.

Next line contains **n** space separated integers denoting the array **a**.

### Output ###

For each test case, output a single line containing "yes" or "no" (without quotes) corresponding to the answer of the problem.

### Constraints ###

 - **1 ≤ T ≤ 106**
 - **1 ≤ n ≤ 105**
 - Sum of **n** over all the test cases ≤ **106**
 - **-109 ≤ ai ≤ 109**

### Example ###

Input:
3
2
0 1
2
1 2
2
5 6

Output:
yes
yes
no

### Explanation ###

**Test case 1.** If you multiply 0 with 1, you get 0, we see that **a0 = 0**. So, the array is beautiful.

**Test case 3.** If you multiply 5 with 6, you get 30, there does not exist an **k** such that **ak = 30**. So, the array is not *beautiful*.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using log4net;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Tests
{
    [TestClass]
    public class Base
    {
        [AssemblyInitialize()]
        public static void AssemblyInit(TestContext context)
        {

        }
    }
}


text:
import argparse
import logging
import asyncio

parser = argparse.ArgumentParser(
    description='Upload a file or a directory to s3')
parser.add_argument('path', nargs=1,
                    help='location of files to upload')
parser.add_argument('--bucket', '-b', nargs=1, required=True,
                    help='Bucket name to upload files to')
parser.add_argument('--region', '-r', dest='region', default='us-east-1',
                    help='S3 region to upload files')

args = parser.parse_args()

def upload(options, loop=None):
    from cloud.aws import AsyncioBotocore
    bucket = options.bucket[0]
    bits = bucket.split('/')
    bucket = bits[0]
    key = '/'.join(bits[1:])
    s3 = AsyncioBotocore('s3', options.region, loop=loop)
    return s3.upload_folder(bucket, options.path[0], key=key)

if __name__ == "__main__":
    logging.basicConfig(format='%(message)s', level=logging.INFO)
    loop = asyncio.get_event_loop()
    result = upload(parser.parse_args(), loop=loop)
    loop.run_until_complete(result)


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
Uses of Interface org.codemonkey.util.Executable (Swift Socket Server)
</TITLE>

<META NAME="date" CONTENT="2011-08-21">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
org.codemonkey.util.Executable

Packages that use Executable

org.codemonkey.swiftsocketserver
Provides the classes to create a TCP / UDP socket server that communicates using custom serialized Java messages objects.

Uses of Executable in org.codemonkey.swiftsocketserver

Classes in org.codemonkey.swiftsocketserver that implement Executable

 class
ClientMessageToServer<Controller>

          Defines a base for decodable and executable message types.

(package private)  class
ClientMessageToServerByeBye

          Message that handles graceful disconnection attempts by the client.

(package private)  class
ClientMessageToServerInvalid

          Wrapper class of which instances substitute bad client-to-server messages.

(package private)  class
ClientMessageToServerPingPong

          Message that decodes pong datagrams.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2009 under Apache v2 license.


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace Binance.Cache
{
    public class InMemoryCache<T> : IObjectCache<T>
    {
        private readonly IDictionary<string, T> _cache;

        private readonly object _sync = new object();

        public InMemoryCache()
        {
            _cache = new Dictionary<string, T>();
        }

        public void Clear()
        {
            lock (_sync)
            {
                _cache.Clear();
            }
        }

        public IEnumerable<T> GetAll()
        {
            lock (_sync)
            {
                return _cache.Values;
            }
        }

        public T Get(string key)
        {
            if (key == null)
                return default;

            var _key = key.FormatSymbol();

            lock (_sync)
            {
                return _cache.ContainsKey(_key) ? _cache[_key] : default;
            }
        }

        public void Set(string key, T symbol)
        {
            lock (_sync)
            {
                _cache[string.Intern(key)] = symbol;
            }
        }

        public void Set(IEnumerable<T> symbols)
        {
            Throw.IfNull(symbols, nameof(symbols));

            // ReSharper disable once PossibleMultipleEnumeration
            if (!symbols.Any())
                throw new ArgumentException("Enumerable must not be empty.", nameof(symbols));

            lock (_sync)
            {
                // Update existing and add any new symbols.
                // ReSharper disable once PossibleMultipleEnumeration
                foreach (var symbol in symbols)
                {
                    _cache[string.Intern(symbol.ToString())] = symbol;
                }
            }
        }
    }
}


text:
using System.Collections.Generic;

namespace Ffb
{
    internal interface ICalculationProvider
    {
        double GetEnvelope(ENVELOPE envParms, double elapsedTime, double duration);

        List<double> GetDirection(SET_EFFECT effectParms);

        List<double> GetCondition(List<CONDITION> condInput, List<double> joystickInput);
        double ApplyGain(double value, double gain);
    }
}


text:
from bs4 import BeautifulSoup
import requests
import os, datetime
import time,json
import re
_basedir = os.path.abspath(os.path.dirname(__file__))
print datetime.datetime.now()

h_ago = re.compile('(\d) hours ago')
pm = re.compile('(\d\d):(\d\d) (AM|PM) (\d{2})\/(\d{2})\/(\d{2})')
min_ago = re.compile('\d\d min ago')
yesterday_wali  = re.compile('(\d\d:\d\d) (PM) (yesterday)|(\d\d:\d\d) (AM) (yesterday)')

username = 'alafazam'
print 'looking for ' + username
url = 'https://www.codechef.com/recent/user/page=1&user_handle='+str(username)
r = requests.get(url).json()
number_of_pages = r["max_page"]
print 'max pages are ' + str(number_of_pages)

time_data = []
obj_data = []
data_hours = []
data_mins = []
chart_data = [['minutes','hours']]

for x in range(0,number_of_pages):
	time.sleep(0.5)
	print "sending request for page "+ str(x)
	url = 'https://www.codechef.com/recent/user?page='+str(x)+'&user_handle='+str(username)
	r = requests.get(url).json()
	e = r["content"]
	soup = BeautifulSoup(e, 'html.parser')
	trs = soup.find_all('tr','kol')

	for q in trs:
		times = str(q.contents[0].text)
		problem_code = str(q.contents[1].a['href']).split('/')[-1]
		status = str(q.contents[2].span['title'])
		lang = str(q.contents[3].text)
		obj = {'time':times,'problem_code':problem_code,'status':status,'lang':lang}
		obj_data.append(obj)

		time_data.append(times)

		hours_search = re.search(pm,times)
		if hours_search:
			hours = int(hours_search.group(1))
			mins = int(hours_search.group(2))
			if hours_search.group(3)=='AM':
				data_hours.append(int(hours))
			else:
				data_hours.append(int(hours)+12)
				hours +=12

			chrt = [mins,hours]
			chart_data.append(chrt)

			data_mins.append(int(mins))

		# string_to_match  = str(trs[q].text)
		# if h_ago.match(string_to_match) or am.match(string_to_match) or pm.match(string_to_match) or time_arr.append(string_to_match):
		# 	time_arr.append(string_to_match)
		# 	problem_arr.append(str(trs[q+1].text))
		# 	langu_arr.append(str(trs[q+2].text))
		# all_text.append(str(trs[q].text))
	print "page "+str(x)+" done"

# w = open('output.json','w')
# w.write(json.dumps(hours_mins))
# w.close()

w = open('chart_data.json','w')
w.write(json.dumps(chart_data))
w.close()

# w = open('mins.json','w')
# w.write(json.dumps(data_mins))
# w.close()


text:
package com.martinkl.samza.newsfeed;

import java.util.HashMap;

import org.apache.samza.system.IncomingMessageEnvelope;
import org.apache.samza.system.OutgoingMessageEnvelope;
import org.apache.samza.task.MessageCollector;
import org.apache.samza.task.StreamTask;
import org.apache.samza.task.TaskCoordinator;
import org.apache.samza.task.WindowableTask;

/**
 * Generates fake messages posted by a given number of fake users, by emitting
 * "postMessage" events. The output is partitioned by sender.
 */
public class GenerateMessagesTask implements StreamTask, WindowableTask {

  @Override
  public void process(IncomingMessageEnvelope envelope, MessageCollector collector, TaskCoordinator coordinator) {
    // no input streams, nothing to process
  }

  @Override
  public void window(MessageCollector collector, TaskCoordinator coordinator) {
    for (int i = 0; i < NewsfeedConfig.MESSAGES_PER_WINDOW; i++) {
      String sender = NewsfeedConfig.randomUser();

      HashMap<String, Object> message = new HashMap<String, Object>();
      message.put("event", "postMessage");
      message.put("sender", sender);
      message.put("text", "Hello world");
      message.put("time", NewsfeedConfig.currentDateTime());
      collector.send(new OutgoingMessageEnvelope(NewsfeedConfig.MESSAGES_STREAM, sender, null, message));
    }
  }
}