text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using Runscope.Messages;
using Tavis;

namespace Runscope.Links
{
    [LinkRelationType("https://runscope.com/rels/collections")]
    public class CollectionsLink : Link
    {
        public CollectionsLink()
        {

        }

        public static List<Collection> InterpretMessageBody(RunscopeApiDocument document)
        {
            return RunscopeApiDocument<Collection>.ParseDataArray(document.Data as JArray, Collection.Parse);
        }
    }
}


text:
<?php
/**
 * File was created 30.05.2015 13:16
 *
 * @author Karsten J. Gerber <kontakt@karsten-gerber.de>
 */

namespace PeekAndPoke\Component\Psi\Psi;

use PeekAndPoke\Component\Psi\Functions\Unary\Matcher\NotSameAs;
use PeekAndPoke\Component\Psi\Functions\Unary\Matcher\SameAs;
use PeekAndPoke\Component\Psi\Stubs\UnitTestMockA;
use PeekAndPoke\Component\Psi\Stubs\UnitTestMockB;
use PeekAndPoke\Component\Psi\Stubs\UnitTestToString;
use PeekAndPoke\Types\GenericHolder;
use PHPUnit\Framework\TestCase;

/**
 * @author Karsten J. Gerber <kontakt@karsten-gerber.de>
 */
class IsSameAsIsNotSameAsTest extends TestCase
{
    /**
     * @param $subjectArgument
     * @param $psiValue
     * @param $expectedResult
     *
     * @dataProvider provide
     */
    public function testSameAs($subjectArgument, $psiValue, $expectedResult)
    {
        $subject = new IsSameAs($subjectArgument);
        $result  = $subject->__invoke($psiValue);

        $this->assertSame($expectedResult, $result);

        // deprecated
        /** @noinspection PhpDeprecationInspection */
        $subject = new SameAs($subjectArgument);
        $result  = $subject->__invoke($psiValue);

        $this->assertSame($expectedResult, $result);
    }

    /**
     * @param $subjectArgument
     * @param $psiValue
     * @param $expectedResult
     *
     * @dataProvider provide
     */
    public function testSameAsWithValueHolder($subjectArgument, $psiValue, $expectedResult)
    {
        $subject = new IsSameAs(
            new GenericHolder($subjectArgument)
        );
        $result  = $subject->__invoke($psiValue);

        $this->assertSame($expectedResult, $result);
    }

    /**
     * @param $subjectArgument
     * @param $psiValue
     * @param $expectedResult
     *
     * @dataProvider provide
     */
    public function testNotSameAs($subjectArgument, $psiValue, $expectedResult)
    {
        $expectedResult = ! $expectedResult;

        $subject = new IsNotSameAs($subjectArgument);
        $result  = $subject->__invoke($psiValue);

        $this->assertSame($expectedResult, $result);

        // deprecated
        /** @noinspection PhpDeprecationInspection */
        $subject = new NotSameAs($subjectArgument);
        $result  = $subject->__invoke($psiValue);

        $this->assertSame($expectedResult, $result);
    }

    /**
     * @param $subjectArgument
     * @param $psiValue
     * @param $expectedResult
     *
     * @dataProvider provide
     */
    public function testNotSameAsWithValueHolder($subjectArgument, $psiValue, $expectedResult)
    {
        $expectedResult = ! $expectedResult;

        $subject = new IsNotSameAs(
            new GenericHolder($subjectArgument)
        );
        $result  = $subject->__invoke($psiValue);

        $this->assertSame($expectedResult, $result);
    }

    /**
     * @return array
     */
    public static function provide()
    {
        $mock = new UnitTestMockA();

        return [
            // positives
            [0, 0, true],
            ['0', '0', true],
            ['1', '1', true],
            [true, true, true],
            [$mock, $mock, true],

            // negatives - ensure substitution
            ['1', '0', false],
            ['0', '1', false],

            // negatives
            [0, false, false],
            [1, true, false],
            [1, '1', false],
            [0, '0', false],
            [0, 0.0, false],
            [(int) 1.0, 1.0, false],
            [new UnitTestMockA(), new UnitTestMockB(), false],

            // test magic __toString is NOT invoked when comparing with "==="
            ['A', new UnitTestToString('A'), false],
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
@implementation MapAnnotation

@end


text:
import {LogicalQueryPlanNode} from './logical_query_plan_node';

export class SkipNode extends LogicalQueryPlanNode {
  constructor(readonly skip: number) {
    super();
  }

  toString(): string {
    return `skip(${this.skip})`;
  }
}


text:
title:  "Enviando e-mail no linux usando o utilitario mail"
date:   2015-06-10 17:20:00
categories: posts
layout: post
---
Simples script para enviar e-mails usando o utilitario mail, que é padrão em diversas distribuições linux.
<!--more-->
{% highlight bash %}

#!/bin/bash
######################################################
#ENVIAR E-MAIL USANDO O UTILITARIO MAIL              #
#CRIADO POR ADRIANO TANAKA adriano.tanakaa@gmail.com #
#VERSAO 1: 10/06/2015                                #
######################################################

#VARIAVEIS
MENSAGEM=${1:-"mensagem"}

EMAIL=${2:-"adriano.tanakaa@gmail.com"}

echo "Enviando e-mail para: $EMAIL" `date`
echo "$MENSAGEM" | mail -s "Teste" $EMAIL

echo "Mensagem: " $MENSAGEM
echo "####"
echo "Destinatario: "
echo $EMAIL
echo "Email enviado para $2  -  `date` "

{% endhighlight %}

Como usar:

{% highlight bash %}

./envia_email_mail.sh "Sua mensagem" email@destinatario.com

{% endhighlight %}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Empedoclesia stipitata Luteyn

### Remarks
null


text:
module Gouge
  module UserStamp
    extend ::ActiveSupport::Concern

    included do
      belongs_to :created_by, class_name: "User", optional: true
      belongs_to :updated_by, class_name: "User", optional: true
      after_create :stamp_created_by
      after_save :stamp_updated_by
    end

    def stamp_created_by
      self.update_column(:created_by_id, self.class.user_stamp_class.current_user_id)
    end

    def stamp_updated_by
      self.update_column(:updated_by_id, self.class.user_stamp_class.current_user_id)
    end

    module ClassMethods
      # NOP
    end
  end
end


text:
import { expect } from "chai";
import * as express from "express";
import * as identity from "../../../src/common/providers/identity";

const EVENT = "EVENT_TYPE";
const now = new Date();

describe("identity", () => {
  describe("userRecordConstructor", () => {
    it("will provide falsey values for fields that are not in raw wire data", () => {
      const record = identity.userRecordConstructor({ uid: "123" });
      expect(record.toJSON()).to.deep.equal({
        uid: "123",
        email: null,
        emailVerified: false,
        displayName: null,
        photoURL: null,
        phoneNumber: null,
        disabled: false,
        providerData: [],
        customClaims: {},
        passwordSalt: null,
        passwordHash: null,
        tokensValidAfterTime: null,
        metadata: {
          creationTime: null,
          lastSignInTime: null,
        },
      });
    });

    it("will not interfere with fields that are in raw wire data", () => {
      const raw: any = {
        uid: "123",
        email: "email@gmail.com",
        emailVerified: true,
        displayName: "User",
        photoURL: "url",
        phoneNumber: "1233332222",
        disabled: true,
        providerData: [],
        customClaims: {},
        passwordSalt: "abc",
        passwordHash: "def",
        tokensValidAfterTime: "2027-02-02T23:01:19.797Z",
        metadata: {
          creationTime: "2017-02-02T23:06:26.124Z",
          lastSignInTime: "2017-02-02T23:01:19.797Z",
        },
      };
      const record = identity.userRecordConstructor(raw);
      expect(record.toJSON()).to.deep.equal(raw);
    });

    it("will convert raw wire fields createdAt and lastSignedInAt to creationTime and lastSignInTime", () => {
      const raw: any = {
        uid: "123",
        metadata: {
          createdAt: "2017-02-02T23:06:26.124Z",
          lastSignedInAt: "2017-02-02T23:01:19.797Z",
        },
      };
      const record = identity.userRecordConstructor(raw);
      expect(record.metadata).to.deep.equal({
        creationTime: "2017-02-02T23:06:26.124Z",
        lastSignInTime: "2017-02-02T23:01:19.797Z",
      });
    });

    it("should stringify the record", () => {
      const raw: any = {
        uid: "123",
        email: "email@gmail.com",
        emailVerified: true,
        displayName: "User",
        photoURL: "url",
        phoneNumber: "1233332222",
        disabled: true,
        providerData: ["something"],
        customClaims: {
          claim: "value",
          another: {
            inner: "value",
          },
        },
        passwordSalt: "abc",
        passwordHash: "def",
        tokensValidAfterTime: "2027-02-02T23:01:19.797Z",
        metadata: {
          creationTime: "2017-02-02T23:06:26.124Z",
          lastSignInTime: "2017-02-02T23:01:19.797Z",
        },
      };
      const record = identity.userRecordConstructor(raw);
      expect(() => JSON.stringify(record)).to.not.throw;
    });
  });

  describe("isValidRequest", () => {
    it("should error on non-post", () => {
      const req = {
        method: "GET",
        header: {
          "Content-Type": "application/json",
        },
        body: {
          data: {
            jwt: "1.2.3",
          },
        },
      } as unknown as express.Request;

      expect(identity.isValidRequest(req)).to.be.false;
    });

    it("should error on bad Content-Type", () => {
      const req = {
        method: "POST",
        header() {
          return "text/css";
        },
        body: {
          data: {
            jwt: "1.2.3",
          },
        },
      } as unknown as express.Request;

      expect(identity.isValidRequest(req)).to.be.false;
    });

    it("should error without req body", () => {
      const req = {
        method: "POST",
        header() {
          return "application/json";
        },
      } as unknown as express.Request;

      expect(identity.isValidRequest(req)).to.be.false;
    });

    it("should error without req body data", () => {
      const req = {
        method: "POST",
        header() {
          return "application/json";
        },
        body: {},
      } as unknown as express.Request;

      expect(identity.isValidRequest(req)).to.be.false;
    });

    it("should error without req body", () => {
      const req = {
        method: "POST",
        header() {
          return "application/json";
        },
        body: {
          data: {},
        },
      } as unknown as express.Request;

      expect(identity.isValidRequest(req)).to.be.false;
    });

    it("should not error on valid request", () => {
      const req = {
        method: "POST",
        header() {
          return "application/json";
        },
        body: {
          data: {
            jwt: "1.2.3",
          },
        },
      } as unknown as express.Request;

      expect(identity.isValidRequest(req)).to.be.true;
    });
  });

  describe("parseMetadata", () => {
    const decodedMetadata = {
      last_sign_in_time: 1476235905,
      creation_time: 1476136676,
    };
    const metadata = {
      lastSignInTime: new Date(1476235905000).toUTCString(),
      creationTime: new Date(1476136676000).toUTCString(),
    };

    it("should parse an undefined object", () => {
      expect(identity.parseMetadata({})).to.deep.equal({
        creationTime: null,
        lastSignInTime: null,
      });
    });

    it("should parse a decoded metadata object", () => {
      const md = identity.parseMetadata(decodedMetadata);

      expect(md).to.deep.equal(metadata);
    });
  });

  describe("parseProviderData", () => {
    const decodedUserInfo = {
      provider_id: "google.com",
      display_name: "John Doe",
      photo_url: "https://lh3.googleusercontent.com/1234567890/photo.jpg",
      uid: "1234567890",
      email: "user@gmail.com",
    };
    const userInfo = {
      providerId: "google.com",
      displayName: "John Doe",
      photoURL: "https://lh3.googleusercontent.com/1234567890/photo.jpg",
      uid: "1234567890",
      email: "user@gmail.com",
      phoneNumber: undefined,
    };
    const decodedUserInfoPhone = {
      provider_id: "phone",
      phone_number: "+11234567890",
      uid: "+11234567890",
    };
    const userInfoPhone = {
      providerId: "phone",
      displayName: undefined,
      photoURL: undefined,
      uid: "+11234567890",
      email: undefined,
      phoneNumber: "+11234567890",
    };

    it("should parse the user info", () => {
      expect(identity.parseProviderData([decodedUserInfo])).to.deep.equal([userInfo]);
    });

    it("should parse the user info with phone", () => {
      expect(identity.parseProviderData([decodedUserInfoPhone])).to.deep.equal([userInfoPhone]);
    });
  });

  describe("parseDate", () => {
    it("should return null if tokens undefined", () => {
      expect(identity.parseDate()).to.be.null;
    });

    it("should parse the date", () => {
      expect(identity.parseDate(1476136676)).to.equal(new Date(1476136676000).toUTCString());
    });
  });

  describe("parseMultiFactor", () => {
    const decodedMultiFactors = {
      enrolled_factors: [
        {
          uid: "enrollmentId1",
          display_name: "displayName1",
          enrollment_time: now.toISOString(),
          phone_number: "+16505551234",
        },
        {
          uid: "enrollmentId2",
          enrollment_time: now.toISOString(),
        },
      ],
    };
    const multiFactors = {
      enrolledFactors: [
        {
          uid: "enrollmentId1",
          displayName: "displayName1",
          enrollmentTime: now.toUTCString(),
          phoneNumber: "+16505551234",
          factorId: "phone",
        },
        {
          uid: "enrollmentId2",
          displayName: undefined,
          enrollmentTime: now.toUTCString(),
          factorId: undefined,
          phoneNumber: undefined,
        },
      ],
    };

    it("should return null on undefined factor", () => {
      expect(identity.parseMultiFactor()).to.be.null;
    });

    it("should return null without enrolled factors", () => {
      expect(identity.parseMultiFactor({})).to.be.null;
    });

    it("should error on an invalid factor", () => {
      const factors = {
        enrolled_factors: [{} as identity.DecodedPayloadMfaInfo],
      };

      expect(() => identity.parseMultiFactor(factors)).to.throw(
        "INTERNAL ASSERT FAILED: Invalid multi-factor info response"
      );
    });

    it("should correctly parse factors", () => {
      expect(identity.parseMultiFactor(decodedMultiFactors)).to.deep.equal(multiFactors);
    });
  });

  describe("parseUserRecord", () => {
    const decodedUserRecord = {
      uid: "abcdefghijklmnopqrstuvwxyz",
      email: "user@gmail.com",
      email_verified: true,
      display_name: "John Doe",
      phone_number: "+11234567890",
      provider_data: [
        {
          provider_id: "google.com",
          display_name: "John Doe",
          photo_url: "https://lh3.googleusercontent.com/1234567890/photo.jpg",
          email: "user@gmail.com",
          uid: "1234567890",
        },
        {
          provider_id: "facebook.com",
          display_name: "John Smith",
          photo_url: "https://facebook.com/0987654321/photo.jpg",
          email: "user@facebook.com",
          uid: "0987654321",
        },
        {
          provider_id: "phone",
          uid: "+11234567890",
          phone_number: "+11234567890",
        },
        {
          provider_id: "password",
          email: "user@gmail.com",
          uid: "user@gmail.com",
          display_name: "John Doe",
        },
      ],
      password_hash: "passwordHash",
      password_salt: "passwordSalt",
      photo_url: "https://lh3.googleusercontent.com/1234567890/photo.jpg",
      tokens_valid_after_time: 1476136676,
      metadata: {
        last_sign_in_time: 1476235905,
        creation_time: 1476136676,
      },
      custom_claims: {
        admin: true,
        group_id: "group123",
      },
      tenant_id: "TENANT_ID",
      multi_factor: {
        enrolled_factors: [
          {
            uid: "enrollmentId1",
            display_name: "displayName1",
            enrollment_time: now.toISOString(),
            phone_number: "+16505551234",
            factor_id: "phone",
          },
          {
            uid: "enrollmentId2",
            enrollment_time: now.toISOString(),
            phone_number: "+16505556789",
            factor_id: "phone",
          },
        ],
      },
    };

    const userRecord = {
      uid: "abcdefghijklmnopqrstuvwxyz",
      email: "user@gmail.com",
      phoneNumber: "+11234567890",
      emailVerified: true,
      disabled: false,
      displayName: "John Doe",
      providerData: [
        {
          providerId: "google.com",
          displayName: "John Doe",
          photoURL: "https://lh3.googleusercontent.com/1234567890/photo.jpg",
          email: "user@gmail.com",
          uid: "1234567890",
          phoneNumber: undefined,
        },
        {
          providerId: "facebook.com",
          displayName: "John Smith",
          photoURL: "https://facebook.com/0987654321/photo.jpg",
          email: "user@facebook.com",
          uid: "0987654321",
          phoneNumber: undefined,
        },
        {
          providerId: "phone",
          displayName: undefined,
          photoURL: undefined,
          email: undefined,
          uid: "+11234567890",
          phoneNumber: "+11234567890",
        },
        {
          providerId: "password",
          displayName: "John Doe",
          photoURL: undefined,
          email: "user@gmail.com",
          uid: "user@gmail.com",
          phoneNumber: undefined,
        },
      ],
      passwordHash: "passwordHash",
      passwordSalt: "passwordSalt",
      photoURL: "https://lh3.googleusercontent.com/1234567890/photo.jpg",
      metadata: {
        lastSignInTime: new Date(1476235905000).toUTCString(),
        creationTime: new Date(1476136676000).toUTCString(),
      },
      customClaims: {
        admin: true,
        group_id: "group123",
      },
      tokensValidAfterTime: new Date(1476136676000).toUTCString(),
      tenantId: "TENANT_ID",
      multiFactor: {
        enrolledFactors: [
          {
            uid: "enrollmentId1",
            displayName: "displayName1",
            enrollmentTime: now.toUTCString(),
            phoneNumber: "+16505551234",
            factorId: "phone",
          },
          {
            uid: "enrollmentId2",
            displayName: undefined,
            enrollmentTime: now.toUTCString(),
            phoneNumber: "+16505556789",
            factorId: "phone",
          },
        ],
      },
    };

    it("should error if decoded does not have uid", () => {
      expect(() => identity.parseAuthUserRecord({} as identity.DecodedPayloadUserRecord)).to.throw(
        "INTERNAL ASSERT FAILED: Invalid user response"
      );
    });

    it("should parse user record", () => {
      const ur = identity.parseAuthUserRecord(decodedUserRecord);

      expect(ur).to.deep.equal(userRecord);
    });
  });

  describe("parseAuthEventContext", () => {
    const rawUserInfo = {
      name: "John Doe",
      granted_scopes:
        "openid https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
      id: "123456789",
      verified_email: true,
      given_name: "John",
      locale: "en",
      family_name: "Doe",
      email: "johndoe@gmail.com",
      picture: "https://lh3.googleusercontent.com/1233456789/mo/photo.jpg",
    };

    it("should parse an unknown event", () => {
      const decodedJwt = {
        aud: "https://us-east1-project_id.cloudfunctions.net/function-1",
        exp: 60 * 60 + 1,
        iat: 1,
        iss: "https://securetoken.google.com/project_id",
        sub: "someUid",
        uid: "someUid",
        event_id: "EVENT_ID",
        event_type: EVENT,
        ip_address: "1.2.3.4",
        user_agent: "USER_AGENT",
        locale: "en",
        raw_user_info: JSON.stringify(rawUserInfo),
      };
      const context = {
        locale: "en",
        ipAddress: "1.2.3.4",
        userAgent: "USER_AGENT",
        eventId: "EVENT_ID",
        eventType: EVENT,
        authType: "UNAUTHENTICATED",
        resource: {
          service: "identitytoolkit.googleapis.com",
          name: "projects/project-id",
        },
        timestamp: new Date(1000).toUTCString(),
        additionalUserInfo: {
          providerId: undefined,
          profile: rawUserInfo,
          username: undefined,
          isNewUser: false,
        },
        credential: null,
        params: {},
      };

      expect(identity.parseAuthEventContext(decodedJwt, "project-id")).to.deep.equal(context);
    });

    it("should parse a beforeSignIn event", () => {
      const time = now.getTime();
      const decodedJwt = {
        aud: "https://us-east1-project_id.cloudfunctions.net/function-1",
        exp: 60 * 60 + 1,
        iat: 1,
        iss: "https://securetoken.google.com/project_id",
        sub: "someUid",
        uid: "someUid",
        event_id: "EVENT_ID",
        event_type: "beforeSignIn",
        ip_address: "1.2.3.4",
        user_agent: "USER_AGENT",
        locale: "en",
        sign_in_method: "password",
        raw_user_info: JSON.stringify(rawUserInfo),
        oauth_id_token: "ID_TOKEN",
        oauth_access_token: "ACCESS_TOKEN",
        oauth_refresh_token: "REFRESH_TOKEN",
        oauth_token_secret: "OAUTH_TOKEN_SECRET",
        oauth_expires_in: 3600,
      };
      const context = {
        locale: "en",
        ipAddress: "1.2.3.4",
        userAgent: "USER_AGENT",
        eventId: "EVENT_ID",
        eventType: "providers/cloud.auth/eventTypes/user.beforeSignIn:password",
        authType: "UNAUTHENTICATED",
        resource: {
          service: "identitytoolkit.googleapis.com",
          name: "projects/project-id",
        },
        timestamp: new Date(1000).toUTCString(),
        additionalUserInfo: {
          providerId: "password",
          profile: rawUserInfo,
          username: undefined,
          isNewUser: false,
        },
        credential: {
          claims: undefined,
          idToken: "ID_TOKEN",
          accessToken: "ACCESS_TOKEN",
          refreshToken: "REFRESH_TOKEN",
          expirationTime: new Date(time + 3600 * 1000).toUTCString(),
          secret: "OAUTH_TOKEN_SECRET",
          providerId: "password",
          signInMethod: "password",
        },
        params: {},
      };

      expect(identity.parseAuthEventContext(decodedJwt, "project-id", time)).to.deep.equal(context);
    });

    it("should parse a beforeCreate event", () => {
      const time = now.getTime();
      // beforeCreate
      const decodedJwt = {
        aud: "https://us-east1-project_id.cloudfunctions.net/beforeCreate",
        exp: 60 * 60 + 1,
        iat: 1,
        iss: "https://securetoken.google.com/project_id",
        sub: "abcdefghijklmnopqrstuvwxyz",
        uid: "abcdefghijklmnopqrstuvwxyz",
        event_id: "EVENT_ID",
        event_type: "beforeCreate",
        ip_address: "1.2.3.4",
        user_agent: "USER_AGENT",
        locale: "en",
        sign_in_method: "oidc.provider",
        tenant_id: "TENANT_ID",
        user_record: {
          uid: "abcdefghijklmnopqrstuvwxyz",
          email: "user@gmail.com",
          email_verified: true,
          display_name: "John Doe",
          phone_number: "+11234567890",
          provider_data: [
            {
              provider_id: "oidc.provider",
              email: "user@gmail.com",
              uid: "user@gmail.com",
              display_name: "John Doe",
            },
          ],
          photo_url: "https://lh3.googleusercontent.com/1234567890/photo.jpg",
          tokens_valid_after_time: 1476136676,
          metadata: {
            last_sign_in_time: 1476235905,
            creation_time: 1476136676,
          },
          custom_claims: {
            admin: true,
            group_id: "group123",
          },
          tenant_id: "TENANT_ID",
        },
        oauth_id_token: "ID_TOKEN",
        oauth_access_token: "ACCESS_TOKEN",
        oauth_refresh_token: "REFRESH_TOKEN",
        oauth_token_secret: "OAUTH_TOKEN_SECRET",
        oauth_expires_in: 3600,
        raw_user_info: JSON.stringify(rawUserInfo),
      };
      const context = {
        locale: "en",
        ipAddress: "1.2.3.4",
        userAgent: "USER_AGENT",
        eventId: "EVENT_ID",
        eventType: "providers/cloud.auth/eventTypes/user.beforeCreate:oidc.provider",
        authType: "USER",
        resource: {
          service: "identitytoolkit.googleapis.com",
          name: "projects/project-id/tenants/TENANT_ID",
        },
        timestamp: new Date(1000).toUTCString(),
        additionalUserInfo: {
          username: undefined,
          providerId: "oidc.provider",
          profile: rawUserInfo,
          isNewUser: true,
        },
        credential: {
          claims: undefined,
          accessToken: "ACCESS_TOKEN",
          expirationTime: new Date(time + 3600 * 1000).toUTCString(),
          idToken: "ID_TOKEN",
          providerId: "oidc.provider",
          refreshToken: "REFRESH_TOKEN",
          secret: "OAUTH_TOKEN_SECRET",
          signInMethod: "oidc.provider",
        },
        params: {},
      };

      expect(identity.parseAuthEventContext(decodedJwt, "project-id", time)).to.deep.equal(context);
    });
  });

  describe("validateAuthResponse", () => {
    it("should not throw on undefined request", () => {
      expect(() => identity.validateAuthResponse("event", undefined)).to.not.throw;
    });

    it("should throw an error if customClaims have a blocked claim", () => {
      expect(() =>
        identity.validateAuthResponse("beforeCreate", {
          customClaims: { acr: "something" },
        })
      ).to.throw('The customClaims claims "acr" are reserved and cannot be specified.');
    });

    it("should throw an error if customClaims size is too big", () => {
      const str = "x".repeat(1000);

      expect(() =>
        identity.validateAuthResponse("beforeCreate", {
          customClaims: { idk: str },
        })
      ).to.throw("The customClaims payload should not exceed 1000 characters.");
    });

    it("should throw an error if sessionClaims have a blocked claim", () => {
      expect(() =>
        identity.validateAuthResponse("beforeSignIn", {
          sessionClaims: { acr: "something" },
        })
      ).to.throw('The sessionClaims claims "acr" are reserved and cannot be specified.');
    });

    it("should throw an error if sessionClaims size is too big", () => {
      const str = "x".repeat(1000);

      expect(() =>
        identity.validateAuthResponse("beforeSignIn", {
          sessionClaims: { idk: str },
        })
      ).to.throw("The sessionClaims payload should not exceed 1000 characters.");
    });

    it("should throw an error if the combined customClaims & sessionClaims size is too big", () => {
      const str = "x".repeat(501);

      expect(() =>
        identity.validateAuthResponse("beforeSignIn", {
          customClaims: { cc: str },
          sessionClaims: { sc: str },
        })
      ).to.throw(
        "The customClaims and sessionClaims payloads should not exceed 1000 characters combined."
      );
    });
  });

  describe("getUpdateMask", () => {
    it("should return empty string on undefined response", () => {
      expect(identity.getUpdateMask()).to.eq("");
    });

    it("should return the right claims on a response", () => {
      const response = {
        displayName: "john",
        disabled: false,
        emailVerified: true,
        photoURL: "google.com",
        customClaims: {
          claim1: "abc",
        },
        sessionClaims: {
          claim2: "def",
        },
      };

      expect(identity.getUpdateMask(response)).to.eq(
        "displayName,disabled,emailVerified,photoURL,customClaims,sessionClaims"
      );
    });
  });
});


text:
package com.ea.orbit.container;

import com.ea.orbit.annotation.Config;
import com.ea.orbit.concurrent.Task;
import com.ea.orbit.configuration.ContainerConfig;
import com.ea.orbit.configuration.ContainerConfigImpl;
import com.ea.orbit.configuration.Secret;
import com.ea.orbit.configuration.SecretManager;
import com.ea.orbit.exception.UncheckedException;
import com.ea.orbit.injection.DependencyRegistry;
import com.ea.orbit.reflect.ClassCache;
import com.ea.orbit.reflect.FieldDescriptor;

import org.yaml.snakeyaml.Yaml;

import javax.annotation.PostConstruct;
import javax.inject.Singleton;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Container
{
    private ContainerConfig properties;
    private Map<String, ComponentState> componentMap = new ConcurrentHashMap<>();

    private CompletableFuture<?> stopFuture = new CompletableFuture<>();

    @Config("orbit.components")
    private List<Object> components = new ArrayList<>();

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Container.class);

    static
    {
        // Initializes orbit async, but only if the application uses it.
        try
        {
            Class.forName("com.ea.orbit.async.Async");
            try
            {
                // async is present in the classpath, let's make sure await is initialized
                Class.forName("com.ea.orbit.async.Await");
            }
            catch (Exception ex)
            {
                // this might be a problem, logging.
                logger.error("Error initializing orbit-async", ex);
            }
        }
        catch (Exception ex)
        {
            // no problem, application doesn't use orbit async.
        }
    }

    private final DependencyRegistry registry = new DependencyRegistry()
    {
        @Override
        protected void postInject(final Object o)
        {
            super.postInject(o);
            try
            {
                Container.this.injectConfig(o);
            }
            catch (IllegalAccessException e)
            {
                throw new UncheckedException(e);
            }
        }
    };

    public List<Class<?>> getClasses()
    {
        return componentMap.values().stream().map(c -> c.implClass).collect(Collectors.toList());
    }

    public void join() throws ExecutionException, InterruptedException
    {
        stopFuture.get();
    }

    protected static class ComponentState
    {
        boolean initialized;
        Class<?> implClass;
        List<ComponentState> dependsOn = new ArrayList<>();

        Object instance;
        boolean isSingleton;
        boolean isStartable;
    }

    protected enum ContainerState
    {
        CREATED,
        STARTING,
        STARTED,
        STOPPING,
        STOPPED,
        FAILED
    }

    private ContainerState state = ContainerState.CREATED;

    public void add(final Class<?> componentClass)
    {
        ComponentState state = componentMap.get(componentClass.getName());
        if (state == null)
        {
            state = new ComponentState();
            componentMap.put(componentClass.getName(), state);
            state.isSingleton = componentClass.isAnnotationPresent(Singleton.class);
            if (state.isSingleton)
            {
                registry.addSingleton(componentClass);
            }
            state.isStartable = Startable.class.isAssignableFrom(componentClass);
        }
        state.implClass = componentClass;
    }

    public <T> void addInstance(T instance)
    {
        registry.addSingleton(instance.getClass(), instance);
        ComponentState state = componentMap.get(instance.getClass().getName());
        if (state == null)
        {
            state = new ComponentState();
            componentMap.put(instance.getClass().getName(), state);
        }
        if (state.implClass == null)
        {
            state.implClass = instance.getClass();
        }
        state.instance = instance;
    }

    public void setProperties(final Map<String, Object> properties)
    {
        if (this.properties == null)
        {
            this.properties = new ContainerConfigImpl();
            this.properties.putAll(System.getProperties());
            addInstance(this.properties);
        }
        this.properties.putAll(properties);
    }

    @SuppressWarnings({"unchecked", "rawtypes"})
    protected void injectConfig(Object o, java.lang.reflect.Field f) throws IllegalAccessException
    {
        final Config config = f.getAnnotation(Config.class);
        if (config != null)
        {
            if (Modifier.isFinal(f.getModifiers()))
            {
                throw new RuntimeException("Configurable fields should never be final: " + f);
            }

            f.setAccessible(true);

            if (f.getType() == Integer.TYPE || f.getType() == Integer.class)
            {
                f.set(o, properties.getAsInt(config.value(), (Integer) f.get(o)));
            }
            else if (f.getType() == Boolean.TYPE || f.getType() == Boolean.class)
            {
                f.set(o, properties.getAsBoolean(config.value(), (Boolean) f.get(o)));
            }
            else if (f.getType() == String.class)
            {
                f.set(o, properties.getAsString(config.value(), (String) f.get(o)));
            }
            else if (f.getType() == Secret.class)
            {
                final Secret secret = get(SecretManager.class).decrypt((String) f.get(o));
                f.set(o, secret);
            }
            else if (f.getType().isEnum())
            {
                final String enumValue = properties.getAsString(config.value(), null);
                if (enumValue != null)
                {
                    f.set(o, Enum.valueOf((Class<Enum>) f.getType(), enumValue));
                }
            }
            else if (properties.getAll().get(config.value()) != null)
            {
                final Object val = properties.getAll().get(config.value());
                f.set(o, val);
            }
            else if (List.class.isAssignableFrom(f.getType()))
            {
                if ((properties.getAll().get(config.value()) != null))
                {
                    final Object val = properties.getAll().get(config.value());
                    f.set(o, val);
                }
            }
            else
            {
                throw new UncheckedException("Field type not supported for configuration injection: " + f);
            }
        }
    }

    protected void injectConfig(Object o) throws IllegalAccessException
    {
        for (FieldDescriptor fd : ClassCache.shared.getClass(o.getClass()).getAllInstanceFields())
        {
            injectConfig(o, fd.getField());
        }
    }

    public void inject(Object object)
    {
        registry.inject(object);
    }

    public void postConstruct(final Object o)
    {
        for (Class<?> cl = o.getClass(); cl != null && cl != Object.class; cl = cl.getSuperclass())
        {
            for (final Method m : cl.getDeclaredMethods())
            {
                if (m.isAnnotationPresent(PostConstruct.class))
                {
                    try
                    {
                        m.setAccessible(true);
                        m.invoke(o);
                        return;
                    }
                    catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e)
                    {
                        throw new UncheckedException(e);
                    }
                }
            }
        }
    }

    /**
     *

Compiles a list of classes that will be stored inside this container:
     *

     *
Reads the configuration from the properties

     *
Looks for component declarations in the classpath: META-INF/services/orbit/*

     *

     *

     *
Instantiates all the componentMap

     *
Wires the componentMap together by injecting fields and the configuration

     *
Calls @PostConstructor on all componentMap

     *
Calls start on all componentMap that implement Startable

     *

     */
    @SuppressWarnings("unchecked")
    public void start()
    {
        logger.info("Starting Orbit Container");

        if (state != ContainerState.CREATED)
        {
            throw new IllegalStateException(state.toString());
        }
        state = ContainerState.STARTING;
        try
        {
            if (properties == null)
            {
                final Set<String> activeProfiles = Stream.of(System.getProperty("orbit.profiles", "").split(",")).collect(Collectors.toSet());
                final URL res = getClass().getResource("/conf/orbit.yaml");
                if (res != null)
                {
                    readConfig(activeProfiles, res.openStream());
                }
                else
                {
                    setProperties(Collections.emptyMap());
                }
                if (System.getProperty("orbit.configuration.overload") != null)
                {
                    final String props = System.getProperty("orbit.configuration.overload");
                    readConfig(activeProfiles, new FileInputStream(props));
                }
            }
            addInstance(this);
            injectConfig(this);
            addInstance(registry);
            registry.addSingleton(ContainerConfig.class, properties);

            if (components != null)
            {
                for (final Object service : components)
                {
                    if (logger.isDebugEnabled())
                    {
                        logger.debug("Adding Component: {0}", service.toString());
                    }

                    add((service instanceof Class) ? (Class<?>) service : Class.forName(String.valueOf(service)));
                }
            }

            // Instantiating modules
            for (ComponentState state : componentMap.values())
            {
                if (state.instance == null && Module.class.isAssignableFrom(state.implClass))
                {
                    state.instance = registry.locate(state.implClass);
                }
            }

            // Getting module classes
            Set<Class<?>> newComps = new LinkedHashSet<>();
            for (ComponentState state : componentMap.values())
            {
                if (state.instance != null && Module.class.isAssignableFrom(state.implClass))
                {
                    newComps.addAll(((Module) state.instance).getClasses());
                }
            }
            newComps.forEach(c -> add(c));

            // component snapshot
            Set<ComponentState> comps = new LinkedHashSet<>(componentMap.values());

            // Instantiating the singletons
            for (ComponentState state : comps)
            {
                if (state.instance == null && state.isSingleton)
                {
                    state.instance = registry.locate(state.implClass);
                }
            }

            // just in case the post constructor added new componentMap
            if (componentMap.size() != comps.size())
            {
                comps.addAll(componentMap.values());
            }

            List<Task<?>> futures = new ArrayList<>();
            // Call start methods
            for (ComponentState state : comps)
            {
                if (state.instance != null && state.instance instanceof Startable)
                {

                    final Task<?> future = ((Startable) state.instance).start();
                    if (future != null && !future.isDone())
                    {
                        futures.add(future);
                    }
                }
            }
            if (futures.size() > 0)
            {
                Task.allOf(futures).join();
            }
            state = ContainerState.STARTED;

            logger.info("Orbit Container started");
        }
        catch (Throwable ex)
        {
            state = ContainerState.FAILED;
            throw new UncheckedException(ex);
        }
    }

    private void readConfig(final Set<String> activeProfiles, final InputStream in) throws UnsupportedEncodingException
    {
        final Reader reader = new InputStreamReader(in, "UTF-8");
        Yaml yaml = new Yaml();
        final Iterable<Object> iter = yaml.loadAll(reader);
        final Map<String, Object> newProperties = new LinkedHashMap<>();
        iter.forEach(item -> {
            final Map<String, Object> section = (Map<String, Object>) item;
            final Object sectionProfile = section.get("orbit.profile");
            if (sectionProfile == null || activeProfiles.contains(sectionProfile))
            {
                // if no profile or if the profile is in the current list of profiles.
                newProperties.putAll(section);
            }
        });
        setProperties(newProperties);
    }

    public void stop()
    {
        logger.info("Stopping Orbit Container");
        if (state != ContainerState.STARTED)
        {
            throw new IllegalStateException(state.toString());
        }

        state = ContainerState.STOPPING;
        for (ComponentState componentState : componentMap.values())
        {
            if (componentState.instance != null && componentState.instance instanceof Startable)
            {
                try
                {
                    ((Startable) componentState.instance).stop();
                }
                catch (Exception e)
                {
                    state = ContainerState.FAILED;
                    throw new UncheckedException("Error stopping " + componentState.implClass.getName(), e);
                }
            }
        }
        stopFuture.complete(null);
        state = ContainerState.STOPPED;
        logger.info("Orbit Container stopped");
    }

    protected ComponentState getState(final Class<?> componentClass)
    {
        ComponentState state = componentMap.get(componentClass.getName());
        if (state != null && state.instance != null)
        {
            return state;
        }
        for (ComponentState s : componentMap.values())
        {
            if (s.instance != null && componentClass.isInstance(s.instance))
            {
                return s;
            }
        }
        return state;
    }

    @SuppressWarnings("unchecked")
    public <T> T get(final Class<T> componentClass)
    {
        ComponentState state = getState(componentClass);
        if (state != null && state.instance != null)
        {
            return (T) state.instance;
        }
        return registry.locate(componentClass);
    }

    public List<Object> components()
    {
        List<Object> list = new ArrayList<>(componentMap.size());
        for (ComponentState state : componentMap.values())
        {
            if (state.instance != null)
            {
                list.add(state.instance);
            }
        }
        return Collections.unmodifiableList(list);
    }

    @SuppressWarnings("unchecked")
    public <T> List<T> components(final Class<T> actorClass)
    {
        List<T> list = new ArrayList<T>();
        for (ComponentState s : componentMap.values())
        {
            if (s.instance != null && actorClass.isInstance(s.instance))
            {
                list.add((T) s.instance);
            }
        }
        return list;
    }

}


text:
package com.ltsllc.miranda.mina;

import com.ltsllc.miranda.Message;
import com.ltsllc.miranda.Panic;
import com.ltsllc.miranda.clientinterface.MirandaException;
import com.ltsllc.miranda.cluster.Cluster;
import com.ltsllc.miranda.mina.messages.ConnectionCreatedMessage;
import com.ltsllc.miranda.mina.states.MinaUnecryptedConnectionListenerReadyState;
import com.ltsllc.miranda.miranda.Miranda;
import com.ltsllc.miranda.network.Network;
import com.ltsllc.miranda.network.UnencryptedConnectionListener;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.BlockingQueue;

public class MinaUnencryptedConnectionListener extends UnencryptedConnectionListener {

    public static class ConnectionHandler extends IoHandlerAdapter {
        private BlockingQueue<Message> listener;

        public ConnectionHandler (BlockingQueue<Message> listener) {
            this.listener = listener;
        }

        @Override
        public void sessionCreated(IoSession session) throws Exception {
            super.sessionCreated(session);

            ConnectionCreatedMessage connectionCreatedMessage = new ConnectionCreatedMessage(null, this,
                    session);

            listener.put(connectionCreatedMessage);
        }
    }

    public static class ConnectionThread implements Runnable {
        private BlockingQueue<Message> listener;
        private int port;

        public ConnectionThread (BlockingQueue<Message> queue) {
            listener = queue;
        }

        public void run () {
            try {
                ConnectionHandler connectionHandler = new ConnectionHandler(listener);
                IoAcceptor ioAcceptor = new NioSocketAcceptor();
                ioAcceptor.setHandler(connectionHandler);
                SocketAddress socketAddress = new InetSocketAddress(port);
                ioAcceptor.bind(socketAddress);
                try {
                    wait();
                } catch (InterruptedException e) {
                }
                ioAcceptor.dispose(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    private Exception exception;

    @Override
    public void stopListening() {
        getConnectionThread().interrupt();
    }

    @Override
    public void startListening() {
        ConnectionThread connectionThread = new ConnectionThread(getQueue());
        Thread thread = new Thread(connectionThread);
        setConnectionThread(thread);
        getConnectionThread().start();
    }

    public MinaUnencryptedConnectionListener (Network network, Cluster cluster, int port) throws MirandaException {
        super(network, cluster, port);
        exception = new Exception();

        setCurrentState(new MinaUnecryptedConnectionListenerReadyState());
    }

}


text:
template <class T>
struct is_boost_rational<boost::rational<T> > : public boost::mpl::true_{};

namespace boost{ namespace multiprecision{

template<>
struct number_category<rational<tom_int> > : public mpl::int_<number_kind_rational> {};

}}

int main()
{
   test<boost::rational<boost::multiprecision::tom_int> >();
   return boost::report_errors();
}


text:
/*************************************************************************/
/*  regex.cpp                                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2016 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* 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.                */
/*************************************************************************/
#include "regex.h"
#include "nrex.hpp"
#include "core/os/memory.h"

void RegEx::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("compile","pattern", "capture"),&RegEx::compile, DEFVAL(9));
	ObjectTypeDB::bind_method(_MD("find","text","start","end"),&RegEx::find, DEFVAL(0), DEFVAL(-1));
	ObjectTypeDB::bind_method(_MD("clear"),&RegEx::clear);
	ObjectTypeDB::bind_method(_MD("is_valid"),&RegEx::is_valid);
	ObjectTypeDB::bind_method(_MD("get_capture_count"),&RegEx::get_capture_count);
	ObjectTypeDB::bind_method(_MD("get_capture","capture"),&RegEx::get_capture);
	ObjectTypeDB::bind_method(_MD("get_capture_start","capture"),&RegEx::get_capture_start);
	ObjectTypeDB::bind_method(_MD("get_captures"),&RegEx::_bind_get_captures);

};

StringArray RegEx::_bind_get_captures() const {

	StringArray ret;
	int count = get_capture_count();
	for (int i=0; i<count; i++) {

		String c = get_capture(i);
		ret.push_back(c);
	};

	return ret;

};

void RegEx::clear() {

	text.clear();
	captures.clear();
	exp.reset();

};

bool RegEx::is_valid() const {

	return exp.valid();

};

int RegEx::get_capture_count() const {

	ERR_FAIL_COND_V( !exp.valid(), 0 );

	return exp.capture_size();
}

String RegEx::get_capture(int capture) const {

	ERR_FAIL_COND_V( get_capture_count() <= capture, String() );

	return text.substr(captures[capture].start, captures[capture].length);

}

int RegEx::get_capture_start(int capture) const {

	ERR_FAIL_COND_V( get_capture_count() <= capture, -1 );

	return captures[capture].start;

}

Error RegEx::compile(const String& p_pattern, int capture) {

	clear();

	exp.compile(p_pattern.c_str(), capture);

	ERR_FAIL_COND_V( !exp.valid(), FAILED );

	captures.resize(exp.capture_size());

	return OK;

};

int RegEx::find(const String& p_text, int p_start, int p_end) const {

	ERR_FAIL_COND_V( !exp.valid(), -1 );
	ERR_FAIL_COND_V( p_text.length() < p_start, -1 );
	ERR_FAIL_COND_V( p_text.length() < p_end, -1 );

	bool res = exp.match(p_text.c_str(), &captures[0], p_start, p_end);

	if (res) {
		text = p_text;
		return captures[0].start;
	}
	text.clear();
	return -1;

};

RegEx::RegEx(const String& p_pattern) {

	compile(p_pattern);

};

RegEx::RegEx() {

};

RegEx::~RegEx() {

	clear();

};


text:
<?php

class Salesmachine_Consumer_ForkCurl extends Salesmachine_QueueConsumer {

  protected $type = "ForkCurl";
  protected $endpoint;

  /**
   * Creates a new queued fork consumer which queues fork and identify
   * calls before adding them to
   * @param string $secret
   * @param array  $options
   *     boolean  "debug" - whether to use debug output, wait for response.
   *     number   "max_queue_size" - the max size of messages to enqueue
   *     number   "batch_size" - how many messages to send in a single request
   */
  public function __construct($token, $secret, $endpoint, $options = array()) {
    $this->endpoint = $endpoint;
    parent::__construct($token, $secret, $options);
  }

  /**
   * Make an async request to our API. Fork a curl process, immediately send
   * to the API. If debug is enabled, we wait for the response.
   * @param  array   $messages array of all the messages to send
   * @return boolean whether the request succeeded
   */
  public function flushBatch($messages) {

    $body = $this->payload($messages);
    $payload = json_encode($body);

    # Escape for shell usage.
    $payload = escapeshellarg($payload);

    $protocol = $this->ssl() ? "https://" : "http://";
    $id = $this->token . ":" . $this->secret . "@";
    $host = $this->host();
    $path = "/v1/" . $this->endpoint;
    $url = $protocol . $id . $host . $path;

    $cmd = "curl -X POST -H 'Content-Type: application/json'";
    $cmd.= " -d " . $payload . " '" . $url . "'";

    if (!$this->debug()) {
      $cmd .= " > /dev/null 2>&1 &";
    }

    exec($cmd, $output, $exit);

    if ($exit != 0) {
      $this->handleError($exit, $output);
    }

    return $exit == 0 && (!isset($output[0]) || !isset(json_decode($output[0], true)['error']));
  }
}


text:
<?php
  /*****Curl******/
  $curl="Can't Checked";
  $mbstring="Can't Checked";
  $safe_mode="Can't Checked";
  $open_basedir="Can't Checked";
  $allow_url_fopen="Can't Checked";

  $mysql_support="";
  $install_allow = 1;

  if(function_exists('curl_version'))
    $curl="
 curl : Ok. Enabled.
";
  else{
    $install_allow = 0;
    $curl="
 curl : Error. Curl is not enabled.Please Enable it.
";
  }

  if(function_exists( "mb_detect_encoding" ) )
    $mbstring="
 mbstring : Ok. Enabled.
";
  else{
    $install_allow = 0;
    $mbstring="
 mbstring : Error.Mbstring is not Enabled. Please enable it.
";
  }

  if(function_exists('ini_get')){
    if( ini_get('safe_mode') ){
      $install_allow = 0;
      $safe_mode="
 safe mode : Error. safe_mode=on, please make safe_mode=off.
";
    }
    else
      $safe_mode="
 safe mode : OK
";

    if(ini_get('open_basedir')=="")
      $open_basedir="
 open basedir : Ok.
";
    else{
      $install_allow = 0;
      $open_basedir="
 open basedirError. open_basedir has value. Please clear value for open_basedir from php.ini
";
    }

    if(ini_get('allow_url_fopen'))
      $allow_url_fopen="
 allow url open : Ok. Enabled
";
    else{
      $install_allow = 0;
      $allow_url_fopen="
 allow url open : Error. Please make allow_url_fopen=1 from php.ini file
";
    }

  }

  if(function_exists('mysqli_connect'))
    $mysqli_support="
 mysqli support : Ok. Supported
";
  else{
    $install_allow = 0;
    $mysqli_support="
 mysqli support : Error. MySql Support is not available. Please enable MySql Support.
";
  }
?>

 Install <?php echo $this->config->item('product_short_name');?> Package

    <?php
    if($this->session->userdata('mysql_error')!="")
      {
        echo "

";
        echo $this->session->userdata('mysql_error');
        $this->session->unset_userdata('mysql_error');
        echo "

";
      }
    ?>

    <?php
      if(validation_errors())
      {
        echo "
";
        print_r(validation_errors());
        echo "

";
      }
    ?>

      <form class="form-horizontal" action="<?php echo site_url().'home/installation_action';?>" method="POST">

           Host Name *
           <input type="text" value="localhost" name="host_name" required class="form-control col-xs-12"  placeholder="Host Name *">

           Database Name *
           <input type="text" value="<?php echo set_value('database_name'); ?>" name="database_name" required class="form-control col-xs-12"  placeholder="Database Name *">

           Database Username *
           <input type="text" value="<?php echo set_value('database_username'); ?>" name="database_username" required class="form-control col-xs-12"  placeholder="Database Username *">

           Database Password
           <input type="password" name="database_password" class="form-control col-xs-12"  placeholder="Database Password ">

           <?php echo $this->config->item('product_short_name') ?> Admin Panel Login Email*
           <input type="email" value="<?php echo set_value('app_username'); ?>" name="app_username" required class="form-control col-xs-12"  placeholder="Application Username *">

           <?php echo $this->config->item('product_short_name') ?> Admin Panel Login Password *
           <input type="password" name="app_password" required class="form-control col-xs-12"  placeholder="Application Password *">

            Language
              <?php
              $select_lan="english";
              if(set_value('language')!="") $select_lan=set_value('language');
              ?>
              <select name="language" autocomplete="off" id="language" class="form-control">
                <?php
                foreach($language_info as $val=>$language)
                {
                  if($select_lan==$val) $is_selected="selected='selected'";
                  else $is_selected="";
                  ?>
                  <option <?php echo $is_selected;?> value="<?php echo $val;?>"><?php echo $language['label'];?></option>
                <?php
                }
                ?>
              </select>

              <?php echo form_error('language'); ?>

           Company Name
           <input type="text" value="<?php echo set_value('institute_name'); ?>" name="institute_name" class="form-control col-xs-12"  placeholder="Company Name">

           Company Address
           <input type="text" value="<?php echo set_value('institute_address'); ?>" name="institute_address" class="form-control col-xs-12"  placeholder="Company Address">

           Company Phone / Mobile
           <input type="text" value="<?php echo set_value('institute_mobile'); ?>" name="institute_mobile" class="form-control col-xs-12"  placeholder="Company Phone / Mobile">

          <button type="submit" style="margin-top:20px" class="btn btn-warning btn-lg" <?php if($install_allow == 0) echo "disabled"; ?> > Install <?php echo $this->config->item('product_short_name');?> Now</button>

      </form>

 Server Requirements

      <?php
      echo $curl;
      echo $mbstring;
      echo $safe_mode;
      echo $open_basedir;
      echo $allow_url_fopen;
      echo $mysqli_support;
      ?>

Please make sure that the following folders and file have write permission

Folder : application/config (777)

Folder : application/core (777)

Folder : download (777)

Folder : js/analytics_js (777)

File : application/install.txt (777)

      <?php if($install_allow==1) :?>

Congratulation ! Your server is fully configured to install this application.

      <?php else : ?>

Warning ! Please fullfill the above requirements (red colored) first.

      <?php endif; ?>


text:
<?php

namespace Concrete\Core\Board\Command;

use Concrete\Core\Board\Instance\Item\Populator\PopulatorInterface;
use Concrete\Core\Entity\Board\InstanceItem;
use Concrete\Core\Entity\Board\InstanceItemBatch;
use Concrete\Core\Logging\Channels;
use Concrete\Core\Logging\LoggerAwareInterface;
use Concrete\Core\Logging\LoggerAwareTrait;
use Doctrine\ORM\EntityManager;

class PopulateBoardInstanceDataPoolCommandHandler implements LoggerAwareInterface
{

    use LoggerAwareTrait;

    public function getLoggerChannel()
    {
        return Channels::CHANNEL_CONTENT;
    }

    /**
     * @var EntityManager
     */
    protected $entityManager;

    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function __invoke(PopulateBoardInstanceDataPoolCommand $command)
    {
        $instance = $command->getInstance();
        $board = $instance->getBoard();
        $configuredDataSources = $board->getDataSources();

        $batch = new InstanceItemBatch();
        $batch->setInstance($instance);
        $this->entityManager->persist($batch);

        foreach ($configuredDataSources as $configuredDataSource) {
            $dataSource = $configuredDataSource->getDataSource();
            $dataSourceDriver = $dataSource->getDriver();
            $populator = $dataSourceDriver->getItemPopulator();

            $items = $populator->createItemsFromDataSource($instance, $configuredDataSource);

            $this->logger->debug(
                t(/*i18n: %1$s is a number, %2$s is the name of a data source*/'Retrieved %1$s objects from %2$s data source',
            count($items), $dataSource->getName()
                )
            );

            $db = $this->entityManager->getConnection();
            foreach ($items as $item) {
                $existing = $db->executeQuery('select count(boardInstanceItemID) from BoardInstanceItems bi
                inner join BoardItems i on bi.boardItemID = i.boardItemID where i.uniqueItemId = ? and bi.configuredDataSourceID = ?', [
                    $item->getUniqueItemId(), $configuredDataSource->getConfiguredDataSourceID()
                ]);
                if ($existing->fetchColumn() === "0") {
                    $instanceItem = new InstanceItem();
                    $instanceItem->setInstance($instance);
                    $instanceItem->setDataSource($configuredDataSource);
                    $instanceItem->setBatch($batch);
                    $instanceItem->setItem($item);
                    $this->entityManager->persist($item);
                    $this->entityManager->persist($instanceItem);
                }
            }
        }
        $instance->setDateDataPoolLastUpdated(time());
        $this->entityManager->flush();
    }

}


text:
package com.vaadin.tests.application;

import com.vaadin.server.VaadinRequest;
import com.vaadin.tests.components.AbstractReindeerTestUIWithLog;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;

public class ReconnectDialogUI extends AbstractReindeerTestUIWithLog {

    @Override
    protected void setup(VaadinRequest request) {
        if (request.getParameter("reconnectAttempts") != null) {
            getReconnectDialogConfiguration().setReconnectAttempts(Integer
                    .parseInt(request.getParameter("reconnectAttempts")));
        }
        Button b = new Button("Say hello");
        b.addClickListener(new ClickListener() {

            @Override
            public void buttonClick(ClickEvent event) {
                log("Hello from the server");
            }
        });

        addComponent(b);
    }

}


text:
<?php
/**
 * Author: Richard Green
 * Date: 28/09/2016
 * Time: 4:04 PM
 */

namespace JsonRpc\Validator;

use JsonRpc\Validator\Validator;
use JsonRpc\Exception\JsonRpcFormatInvalidException;

class JsonRpcResponseFormatValidator extends Validator
{
    public function validate($response)
    {
        if (!isset($response['jsonrpc']) || $response['jsonrpc'] !== '2.0' && (!isset($response['result']) || !isset($response['error'])) || !isset
            ($response['id'])) {
            throw new JsonRpcFormatInvalidException('Invalid JSON-RPC response format');
        }

        if (isset($response['result']) && !is_array($response['result'])) {
            throw new JsonRpcFormatInvalidException('Invalid JSON-RPC response format');
        }

        if (isset($response['error'])) {
            if (is_array($response['error']) && isset($response['error']['message'])) {
                throw new JsonRpcFormatInvalidException($response['error']['message']);
            }

            throw new JsonRpcFormatInvalidException('Invalid JSON-RPC error');
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="sunwin.zhangdong.dao.UserMapper">
    <resultMap id="BaseResultMap" type="sunwin.zhangdong.domain.User">
        <id column="user_id" property="userId" jdbcType="INTEGER"/>
        <result column="user_name" property="userName" jdbcType="VARCHAR"/>
        <result column="password" property="password" jdbcType="VARCHAR"/>
        <result column="last_visit" property="lastVisit" jdbcType="TIMESTAMP"/>
        <result column="last_ip" property="lastIp" jdbcType="VARCHAR"/>
        <result column="user_role" property="userRole"/>
        <result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
    </resultMap>
    <sql id="Base_Column_List">
    user_id, user_name, password, last_visit, last_ip,user_role,create_time
  </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List"/>
        from user
        where user_id = #{userId,jdbcType=INTEGER}
    </select>

    <select id="selectByCondition" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        from user
        WHERE user_name = #{userName} AND password = #{password}
    </select>

    <select id="selectByUserName" resultMap="BaseResultMap">
        SELECT
        <include refid="Base_Column_List"/>
        from user
        WHERE user_name = #{userName}
    </select>

    <select id="selectAllUsers" resultMap="BaseResultMap">
        SELECT *
        from user
        <where>
            <if test="userName != null and userName !='' ">
                user_name = #{userName}
            </if>
            <if test="userRole != null and userRole !='' and userRole !='请选择' ">
                AND user_role = #{userRole}
            </if>
        </where>
    </select>
    <select id="selectMaxId" resultType="INTEGER">
        select max(user_id) from user;
    </select>

    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where user_id = #{userId,jdbcType=INTEGER}
  </delete>
    <insert id="insert" parameterType="sunwin.zhangdong.domain.User">
    insert into user (user_id, user_name, password,
      last_visit, last_ip,user_role,create_time)
    values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
      #{lastVisit,jdbcType=TIMESTAMP}, #{lastIp,jdbcType=VARCHAR}, #{userRole,jdbcType=VARCHAR},
      #{createTime,jdbcType=TIMESTAMP})
  </insert>
    <insert id="insertSelective" parameterType="sunwin.zhangdong.domain.User">
        insert into user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="userId != null">
                user_id,
            </if>
            <if test="userName != null">
                user_name,
            </if>
            <if test="password != null">
                password,
            </if>
            <if test="lastVisit != null">
                last_visit,
            </if>
            <if test="lastIp != null">
                last_ip,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="userId != null">
                #{userId,jdbcType=INTEGER},
            </if>
            <if test="userName != null">
                #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="lastVisit != null">
                #{lastVisit,jdbcType=TIMESTAMP},
            </if>
            <if test="lastIp != null">
                #{lastIp,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="sunwin.zhangdong.domain.User">
        update user
        <set>
            <if test="userName != null">
                user_name = #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                password = #{password,jdbcType=VARCHAR},
            </if>
            <if test="lastVisit != null">
                last_visit = #{lastVisit,jdbcType=TIMESTAMP},
            </if>
            <if test="lastIp != null">
                last_ip = #{lastIp,jdbcType=VARCHAR},
            </if>
        </set>
        where user_id = #{userId,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="sunwin.zhangdong.domain.User">
    update user
    set user_name = #{userName,jdbcType=VARCHAR},
      password = #{password,jdbcType=VARCHAR},
      last_visit = #{lastVisit,jdbcType=TIMESTAMP},
      last_ip = #{lastIp,jdbcType=VARCHAR}
    where user_id = #{userId,jdbcType=INTEGER}
  </update>
</mapper>


text:
package org.magicnexus.interfaces.data;

public interface IDeckLineData
{

	public Integer getQuantity();

	public String getCardName();

	public boolean getSideboard();

	public boolean getCommander();

}


text:
package com.cronutils.model.time.generator;

import com.cronutils.model.field.CronField;
import com.cronutils.model.field.expression.FieldExpression;

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

class NullFieldValueGenerator extends FieldValueGenerator {
    public NullFieldValueGenerator(final CronField cronField) {
        super(cronField);
    }

    @Override
    public int generateNextValue(final int reference) throws NoSuchValueException {
        throw new NoSuchValueException();
    }

    @Override
    public int generatePreviousValue(final int reference) throws NoSuchValueException {
        throw new NoSuchValueException();
    }

    @Override
    protected List<Integer> generateCandidatesNotIncludingIntervalExtremes(final int start, final int end) {
        return new ArrayList<>();
    }

    @Override
    public boolean isMatch(final int value) {
        return false;
    }

    @Override
    protected boolean matchesFieldExpressionClass(final FieldExpression fieldExpression) {
        return true;
    }
}


text:
package mil.emp3.core.storage;

import android.util.Log;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import mil.emp3.api.enums.VisibilityStateEnum;
import mil.emp3.api.exceptions.EMP_Exception;
import mil.emp3.api.interfaces.IContainer;
import mil.emp3.api.interfaces.IContainerSet;
import mil.emp3.api.interfaces.IMap;
import mil.emp3.api.interfaces.IUUIDSet;
import mil.emp3.api.interfaces.core.storage.IParentRelationship;
import mil.emp3.api.interfaces.core.storage.IStorageObjectWrapper;
import mil.emp3.api.utils.ContainerSet;
import mil.emp3.api.utils.UUIDSet;

/**
 *
 * This class is used by the storage manager to wrap all EMP object and their relationships.
 * @param <T> A Type that extends the Container class.
 */
public class StorageObjectWrapper<T extends IContainer> implements IStorageObjectWrapper<T> {
    private static String TAG = StorageObjectWrapper.class.getSimpleName();
    private T container;
    private final Map<UUID, IParentRelationship> parentList;
    private final Map<UUID, IStorageObjectWrapper> childrenList;

    protected StorageObjectWrapper(T oContainer) {
        this.container = oContainer;
        this.parentList = new HashMap<>();
        this.childrenList = new HashMap<>();
    }

    /**
     * This is used when we are restoring the ClientMap object after activity restart.
     * We definitely shouldn't touch the container. We definitely need to copy the childrenList.
     * Doesn't hurt to copy the parentList.
     * Newly create clientMap needs to be retrofitted with children of the old clientmap after activity
     * restart.
     * @param from
     */
    protected void copy(IStorageObjectWrapper from) {
        this.parentList.putAll(from.getParentList());
        this.childrenList.putAll(from.getChildrenList());
    }

    protected java.util.Set<java.util.UUID> getChildIdList() {
        return this.childrenList.keySet();
    }

    protected void setObject(T newContainer) {
        this.container = newContainer;
    }

    @Override
    public T getObject() {
        return this.container;
    }

    protected IContainerSet getParents() {
        IContainerSet oSet = new ContainerSet();

        for (IParentRelationship oParentRelationship: this.parentList.values()) {
            oSet.add(oParentRelationship.getParentWrapper().getObject());
        }
        return oSet;
    }

    protected int getChildrenCount() {
        return this.childrenList.size();
    }

    protected int getParentCount() {
        return this.parentList.size();
    }

    @Override
    public boolean hasParents() {
        return (this.parentList.size() > 0);
    }

    @Override
    public boolean hasChildren() {
        return (this.childrenList.size() > 0);
    }

    @Override
    public boolean hasParent(java.util.UUID id) {
        return this.parentList.containsKey(id);
    }

    @Override
    public void setChildrenVisibilityOnMap(java.util.UUID mapId, VisibilityStateEnum visibilityEnum) {
        java.util.UUID parentId = this.container.getGeoId();

        for (IStorageObjectWrapper oWrapper: this.childrenList.values()) {
            if (oWrapper.getVisibilityWithParentOnMap(mapId, parentId) == null) {
                oWrapper.setVisibilityWithParentOnMap(mapId, parentId, visibilityEnum);
                oWrapper.setChildrenVisibilityOnMap(mapId, visibilityEnum);
            }
        }
    }

    private void addParent(StorageObjectWrapper parent, VisibilityStateEnum visibilityEnum)
            throws EMP_Exception {

        if (!this.hasParent(parent.getObject().getGeoId())) {
            VisibilityStateEnum visibilityStateEnum;
            IUUIDSet parentMapIdList = parent.getMapList();
            IUUIDSet MapIdList = this.getMapList();
            ParentRelationship oParentRelationship = new ParentRelationship(parent);

            this.parentList.put(parent.getObject().getGeoId(), oParentRelationship);

            for (java.util.UUID uuId: parentMapIdList) {
                    visibilityStateEnum = VisibilityStateEnum.HIDDEN;
                    switch (visibilityEnum) {
                        case VISIBLE:
                            switch (parent.getVisibilityOnMap(uuId)) {
                                case VISIBLE:
                                    visibilityStateEnum = VisibilityStateEnum.VISIBLE;
                                    break;
                                case HIDDEN:
                                    visibilityStateEnum = VisibilityStateEnum.VISIBLE_ANCESTOR_HIDDEN;
                                    break;
                                case VISIBLE_ANCESTOR_HIDDEN:
                                    visibilityStateEnum = VisibilityStateEnum.VISIBLE_ANCESTOR_HIDDEN;
                                    break;
                            }
                            break;
                        case VISIBLE_ANCESTOR_HIDDEN:
                            visibilityStateEnum = VisibilityStateEnum.HIDDEN;
                            break;
                        case HIDDEN:
                            visibilityStateEnum = VisibilityStateEnum.HIDDEN;
                            break;
                    }
                    oParentRelationship.setVisibilityOnMap(uuId, visibilityStateEnum);
                    this.setChildrenVisibilityOnMap(uuId, visibilityEnum);
            }
        }
    }

    @Override
    public boolean hasChild(java.util.UUID id) {
        return this.childrenList.containsKey(id);
    }

    protected void addChild(StorageObjectWrapper newChild, VisibilityStateEnum visibilityEnum)
            throws EMP_Exception {
        if (!this.hasChild(newChild.getObject().getGeoId())) {
            if (this.childCreatesParadox(newChild)) {
                throw new EMP_Exception(EMP_Exception.ErrorDetail.INVALID_CHILD, "The object can not be its own ancestor.");
            } else {
                this.childrenList.put(newChild.getObject().getGeoId(), newChild);
                newChild.addParent(this, visibilityEnum);
            }
        }
    }

    @Override
    public boolean childCreatesParadox(IStorageObjectWrapper newChild) {
        // Make sure its not trying to add an object as its own parent nor ancestor.
        if (this.container.getGeoId().compareTo(newChild.getObject().getGeoId()) != 0) {
            for (IParentRelationship oParentRelationship: this.parentList.values()) {
                if (!(oParentRelationship.getParentWrapper().getObject() instanceof IMap)) {
                    if (oParentRelationship.getParentWrapper().childCreatesParadox(newChild)) {
                        return true;
                    }
                }
            }

            return false;
        }
        return true;
    }

    @Override
    public void setVisibilityWithParentOnMap(java.util.UUID mapId, java.util.UUID parentId, VisibilityStateEnum visibilitystate) {
        IParentRelationship parentRelationship = this.parentList.get(parentId);

        if (parentRelationship != null) {
            parentRelationship.setVisibilityOnMap(mapId, visibilitystate);
        }
    }

    @Override
    public VisibilityStateEnum getVisibilityWithParentOnMap(java.util.UUID mapId, java.util.UUID parentId) {
        if (this.container instanceof IMap) {
            if (this.container.getGeoId().compareTo(mapId) == 0) {
                return VisibilityStateEnum.VISIBLE;
            }
        } else {
            IParentRelationship parentRelationship = this.parentList.get(parentId);

            if (parentRelationship != null) {
                return parentRelationship.getVisibilityOnMap(mapId);
            }
        }

        return null;
    }

    @Override
    public VisibilityStateEnum getVisibilityOnMap(java.util.UUID mapId) {
        if (this.container instanceof IMap) {
            if (this.container.getGeoId().compareTo(mapId) == 0) {
                return VisibilityStateEnum.VISIBLE;
            }
        } else for (IParentRelationship parentRelationship: this.parentList.values()) {
            if (parentRelationship.getVisibilityOnMap(mapId) == VisibilityStateEnum.VISIBLE) {
                return VisibilityStateEnum.VISIBLE;
            }
        }

        return VisibilityStateEnum.HIDDEN;
    }

    protected IUUIDSet getMapList() {
        IUUIDSet oList = new UUIDSet();

        if (this.container instanceof IMap) {
            oList.add(this.container.getGeoId());
        } else for (IParentRelationship parentRelationship: this.parentList.values()) {
            parentRelationship.getMapList(oList);
        }
        return oList;
    }

    @Override
    public java.util.UUID getGeoId() {
        return this.container.getGeoId();
    }

    protected void removeChild(java.util.UUID childId) {
        if (this.childrenList.containsKey(childId)) {
            IStorageObjectWrapper childWrapper = this.childrenList.get(childId);

            this.childrenList.remove(childId);
            childWrapper.removeParent(this);
        }
    }

    @Override
    public void removeParent(IStorageObjectWrapper parentWrapper) {
        if (this.parentList.containsKey(parentWrapper.getGeoId())) {
            this.parentList.remove(parentWrapper.getGeoId());
        }
    }

    protected boolean isOnMap(java.util.UUID mapId) {
        boolean bRet = false;

        for (IParentRelationship parentRelationship: this.parentList.values()) {
            bRet = parentRelationship.isOnMap(mapId);
            if (bRet) {
                Log.d(TAG, "isOnMap parentRelationship " + parentRelationship.getParentWrapper().getGeoId());
                break;
            }
        }
        return bRet;
    }

    protected void clearMapVisibility(StorageObjectWrapper parentWrapper, UUID mapId) {
        Log.d(TAG, "clearMapVisibility " + parentWrapper.getGeoId());
        for (IParentRelationship parentRelationship: this.parentList.values()) {
            if(parentWrapper.getGeoId().equals(parentRelationship.getParentWrapper().getGeoId())) {
                parentRelationship.resetVisibilityOnMap(mapId);
            }
        }
    }

    @Override
    public Map<UUID, IStorageObjectWrapper> getChildrenList() {
        return this.childrenList;
    }

    @Override
    public Map<UUID, IParentRelationship> getParentList() {
        return this.parentList;
    }
}


text:
package dagger.internal.codegen;

import static com.google.common.collect.Maps.uniqueIndex;

import com.google.common.collect.ImmutableMap;
import dagger.Binds;
import dagger.Module;
import dagger.Provides;
import dagger.multibindings.IntoSet;
import java.lang.annotation.Annotation;
import java.util.Set;

/**
 * Binds each {@link BindingMethodValidator} into a map, keyed by {@link
 * BindingMethodValidator#methodAnnotation()}.
 */
@Module
interface BindingMethodValidatorsModule {
  @Provides
  static ImmutableMap<Class<? extends Annotation>, BindingMethodValidator> indexValidators(
      Set<BindingMethodValidator> validators) {
    return uniqueIndex(validators, BindingMethodValidator::methodAnnotation);
  }

  @Binds
  @IntoSet
  BindingMethodValidator provides(ProvidesMethodValidator validator);

  @Binds
  @IntoSet
  BindingMethodValidator produces(ProducesMethodValidator validator);

  @Binds
  @IntoSet
  BindingMethodValidator binds(BindsMethodValidator validator);

  @Binds
  @IntoSet
  BindingMethodValidator multibinds(MultibindsMethodValidator validator);

  @Binds
  @IntoSet
  BindingMethodValidator bindsOptionalOf(BindsOptionalOfMethodValidator validator);
}


text:
var enums = require("ui/enums");
var common = require("./font-common");
var application;
function ensureApplication() {
    if (!application) {
        application = require("application");
    }
}
var types;
function ensureTypes() {
    if (!types) {
        types = require("utils/types");
    }
}
var trace;
function ensureTrace() {
    if (!trace) {
        trace = require("trace");
    }
}
var fs;
function ensureFS() {
    if (!fs) {
        fs = require("file-system");
    }
}
var typefaceCache = new Map();
var appAssets;
var FONTS_BASE_PATH = "/fonts/";
var Font = (function (_super) {
    __extends(Font, _super);
    function Font(family, size, style, weight) {
        _super.call(this, family, size, style, weight);
    }
    Font.prototype.withFontFamily = function (family) {
        return new Font(family, this.fontSize, this.fontStyle, this.fontWeight);
    };
    Font.prototype.withFontStyle = function (style) {
        return new Font(this.fontFamily, this.fontSize, style, this.fontWeight);
    };
    Font.prototype.withFontWeight = function (weight) {
        return new Font(this.fontFamily, this.fontSize, this.fontStyle, weight);
    };
    Font.prototype.withFontSize = function (size) {
        return new Font(this.fontFamily, size, this.fontStyle, this.fontWeight);
    };
    Font.prototype.getAndroidTypeface = function () {
        if (!this._typeface) {
            var fontStyle = 0;
            if (this.isBold) {
                fontStyle |= android.graphics.Typeface.BOLD;
            }
            if (this.isItalic) {
                fontStyle |= android.graphics.Typeface.ITALIC;
            }
            var typeFace = createTypeface(this);
            this._typeface = android.graphics.Typeface.create(typeFace, fontStyle);
        }
        return this._typeface;
    };
    Font.default = new Font(undefined, undefined, enums.FontStyle.normal, enums.FontWeight.normal);
    return Font;
}(common.Font));
exports.Font = Font;
function loadFontFromFile(fontFamily) {
    ensureApplication();
    appAssets = appAssets || application.android.context.getAssets();
    if (!appAssets) {
        return null;
    }
    ensureTypes();
    var result = typefaceCache.get(fontFamily);
    if (types.isUndefined(result)) {
        result = null;
        ensureTrace();
        ensureFS();
        var fontAssetPath;
        var basePath = fs.path.join(fs.knownFolders.currentApp().path, "fonts", fontFamily);
        if (fs.File.exists(basePath + ".ttf")) {
            fontAssetPath = FONTS_BASE_PATH + fontFamily + ".ttf";
        }
        else if (fs.File.exists(basePath + ".otf")) {
            fontAssetPath = FONTS_BASE_PATH + fontFamily + ".otf";
        }
        else {
            trace.write("Could not find font file for " + fontFamily, trace.categories.Error, trace.messageType.error);
        }
        if (fontAssetPath) {
            try {
                fontAssetPath = fs.path.join(fs.knownFolders.currentApp().path, fontAssetPath);
                result = android.graphics.Typeface.createFromFile(fontAssetPath);
            }
            catch (e) {
                trace.write("Error loading font asset: " + fontAssetPath, trace.categories.Error, trace.messageType.error);
            }
        }
        typefaceCache.set(fontFamily, result);
    }
    return result;
}
function createTypeface(font) {
    var fonts = common.parseFontFamily(font.fontFamily);
    var result = null;
    if (fonts.length === 0) {
        return null;
    }
    for (var i = 0; i < fonts.length; i++) {
        switch (fonts[i].toLowerCase()) {
            case common.genericFontFamilies.serif:
                result = android.graphics.Typeface.create("serif" + getFontWeightSuffix(font.fontWeight), 0);
                break;
            case common.genericFontFamilies.sansSerif:
            case common.genericFontFamilies.system:
                result = android.graphics.Typeface.create("sans-serif" + getFontWeightSuffix(font.fontWeight), 0);
                break;
            case common.genericFontFamilies.monospace:
                result = android.graphics.Typeface.create("monospace" + getFontWeightSuffix(font.fontWeight), 0);
                break;
            default:
                result = loadFontFromFile(fonts[i]);
                break;
        }
        if (result) {
            return result;
        }
    }
    return null;
}
function getFontWeightSuffix(fontWeight) {
    switch (fontWeight) {
        case enums.FontWeight.thin:
            return android.os.Build.VERSION.SDK_INT >= 16 ? "-thin" : "";
        case enums.FontWeight.extraLight:
        case enums.FontWeight.light:
            return android.os.Build.VERSION.SDK_INT >= 16 ? "-light" : "";
        case enums.FontWeight.normal:
        case "400":
        case undefined:
        case null:
            return "";
        case enums.FontWeight.medium:
        case enums.FontWeight.semiBold:
            return android.os.Build.VERSION.SDK_INT >= 21 ? "-medium" : "";
        case enums.FontWeight.bold:
        case "700":
        case enums.FontWeight.extraBold:
            return "";
        case enums.FontWeight.black:
            return android.os.Build.VERSION.SDK_INT >= 21 ? "-black" : "";
        default:
            throw new Error("Invalid font weight: \"" + fontWeight + "\"");
    }
}


text:
package dot

import (
	"fmt"
	"io"
	"io/ioutil"

	"github.com/gonum/graph/formats/dot/ast"
	"github.com/gonum/graph/formats/dot/internal/lexer"
	"github.com/gonum/graph/formats/dot/internal/parser"
)

// ParseFile parses the given Graphviz DOT file into an AST.
func ParseFile(path string) (*ast.File, error) {
	buf, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, err
	}
	return ParseBytes(buf)
}

// Parse parses the given Graphviz DOT file into an AST, reading from r.
func Parse(r io.Reader) (*ast.File, error) {
	buf, err := ioutil.ReadAll(r)
	if err != nil {
		return nil, err
	}
	return ParseBytes(buf)
}

// ParseBytes parses the given Graphviz DOT file into an AST, reading from b.
func ParseBytes(b []byte) (*ast.File, error) {
	l := lexer.NewLexer(b)
	p := parser.NewParser()
	file, err := p.Parse(l)
	if err != nil {
		return nil, err
	}
	f, ok := file.(*ast.File)
	if !ok {
		return nil, fmt.Errorf("invalid file type; expected *ast.File, got %T", file)
	}
	if err := check(f); err != nil {
		return nil, err
	}
	return f, nil
}

// ParseString parses the given Graphviz DOT file into an AST, reading from s.
func ParseString(s string) (*ast.File, error) {
	return ParseBytes([]byte(s))
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:background="@android:color/white">

    <Button
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="测试"
        android:gravity="center" />
</LinearLayout>


text:
import atk from 'atk';

/**
 * Wrapper for Fomantic-UI dropdown component into a lookup component.
 *
 * Props:
 * config:
 * url: the callback URL. Callback should return model data in form of { key: modelId, text: modelTitle, value: modelId }
 * reference: the reference field name associate with model or hasOne name. This field name will be sent along with URL callback parameter as of 'field=name'.
 * ui: the css class name to apply to dropdown.
 * Note: The remaining config object may contain any or sui-dropdown { props: value } pair.
 *
 * value: The selected value.
 * optionalValue: The initial list of options for the dropdown.
 */

const template = `<sui-dropdown
                    ref="drop"
                    v-bind="dropdownProps"
                    :loading="isLoading"
                    @input="onChange"
                    @filtered="onFiltered"
                    v-model="current"
                    :class="css"></sui-dropdown>`;

export default {
    name: 'atk-lookup',
    template: template,
    props: ['config', 'value', 'optionalValue'],
    data: function () {
        const {
            url, reference, ui, ...suiDropdown
        } = this.config;
        suiDropdown.selection = true;

        return {
            dropdownProps: suiDropdown,
            current: this.value,
            url: url || null,
            css: [ui],
            isLoading: false,
            field: reference,
            query: '',
            temp: '',
        };
    },
    mounted: function () {
        if (this.optionalValue) {
            this.dropdownProps.options = Array.isArray(this.optionalValue) ? this.optionalValue : [this.optionalValue];
        }
    },
    methods: {
        onChange: function (value) {
            this.$emit('onChange', value);
        },
        /**
         * Receive user input text for search.
         */
        onFiltered: function (inputValue) {
            if (inputValue) {
                this.isLoading = true;
            }

            if (!this.onFiltered.debouncedFx) {
                this.onFiltered.debouncedFx = atk.createDebouncedFx(() => {
                    this.onFiltered.debouncedFx = null;
                    if (this.query !== this.temp) {
                        this.query = this.temp;
                        if (this.query) {
                            this.fetchItems(this.query);
                        }
                    }
                }, 250);
            }
            this.temp = inputValue;
            this.onFiltered.debouncedFx(this);
        },
        /**
         * Fetch new data from server.
         */
        fetchItems: async function (q) {
            try {
                const data = { atkVueLookupQuery: q, atkVueLookupField: this.field };
                const response = await atk.apiService.suiFetch(this.url, { method: 'get', data: data });
                if (response.success) {
                    this.dropdownProps.options = response.results;
                }
            } catch (e) {
                console.error(e);
            } finally {
                this.isLoading = false;
            }
        },
    },
};


text:
{% extends "withoutnav_template.html" %}

{% from "components/sub-navigation.html" import sub_navigation %}
{% from "components/page-header.html" import page_header %}

{% block per_page_title %}
  {{ content_page_title }}
{% endblock %}

{% block maincolumn_content %}

    {% if navigation_links and navigation_label_prefix %}

        {{ sub_navigation(navigation_links, navigation_label_prefix) }}

    {% else %}

    {% endif %}

    {% block content_column_content %}
    {% endblock %}

{% endblock %}


text:
#import <Foundation/Foundation.h>

@class USPort;
@class USSchema;

@interface USService : NSObject {
	NSString *name;
	NSMutableArray *ports;

	USSchema *__weak schema;
}

@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSMutableArray *ports;
@property (nonatomic, weak) USSchema *schema;
@property (weak, nonatomic, readonly) NSString *className;

- (USPort *)portForName:(NSString *)aName;

- (NSString *)templateFileHPath;
- (NSString *)templateFileMPath;
- (NSDictionary *)templateKeyDictionary;

@end


text:
var fs = require('fs-extra');
var path = require('path');
var archiver = require('archiver');

var svgsDir = path.join(__dirname, '..', 'dist', 'svg');
var distzipDir = path.join(__dirname, '..', 'docs');
var distzipFile = path.join(distzipDir, 'ionicons.designerpack.zip');

console.log('designerpack source:', svgsDir);

const svgCount = fs.readdirSync(svgsDir).length;

console.log('Total svg files to zip:', svgCount);
fs.ensureDirSync(distzipDir);

var archive = archiver('zip', {
  zlib: { level: 9 }
});

var output = fs.createWriteStream(distzipFile);
output.on('close', () => {
  console.log('designerpack created:', distzipFile);
});

archive.pipe(output);
archive.directory(svgsDir, false);
archive.on('error', (err) => {
  throw err;
});
archive.finalize();


text:
package annotations.one;

/**
 * @author Andreas Volz (andreas.volz@valtech.de)
 */
public class Car {

	@Agile(MCars.M6Cabrio)
	Type type;

}


text:
@if(config('sharp.theme.favicon_url'))
    <link rel="icon" href="{{ config('sharp.theme.favicon_url') }}">
@endif


text:
package libcore.java.math;

import java.math.MathContext;
import java.math.RoundingMode;

public class MathContextTest extends junit.framework.TestCase {
    public void testConstructor() throws Exception {
        // All the rounding modes.
        for (RoundingMode rm : RoundingMode.values()) {
            MathContext mc = new MathContext("precision=1 roundingMode=" + rm);
            assertEquals(1, mc.getPrecision());
            assertEquals(rm, mc.getRoundingMode());
        }

        // A few precisions.
        for (int p = 0; p < 10; ++p) {
            MathContext mc = new MathContext("precision=" + p + " roundingMode=" + RoundingMode.UP);
            assertEquals(p, mc.getPrecision());
            assertEquals(RoundingMode.UP, mc.getRoundingMode());
        }

        // Case-sensitive keywords.
        new MathContext("precision=1 roundingMode=UP");
        try {
            new MathContext("Precision=1 roundingMode=UP");
            fail();
        } catch (IllegalArgumentException expected) {
        }
        try {
            new MathContext("precision=1 RoundingMode=UP");
            fail();
        } catch (IllegalArgumentException expected) {
        }

        // Case-sensitive rounding modes.
        try {
            new MathContext("precision=1 roundingMode=up");
            fail();
        } catch (IllegalArgumentException expected) {
        }

        // Exactly one space (U+0020).
        try {
            new MathContext("precision=1roundingMode=UP");
            fail();
        } catch (IllegalArgumentException expected) {
        }
        try {
            new MathContext("precision=1  roundingMode=UP");
            fail();
        } catch (IllegalArgumentException expected) {
        }
        try {
            new MathContext("precision=1\troundingMode=UP");
            fail();
        } catch (IllegalArgumentException expected) {
        }

        // No leading or trailing space.
        try {
            new MathContext(" precision=1 roundingMode=UP");
            fail();
        } catch (IllegalArgumentException expected) {
        }
        try {
            new MathContext("precision=1 roundingMode=UP ");
            fail();
        } catch (IllegalArgumentException expected) {
        }
    }
}


text:
onready(function(){
	var showBackLinks = function() {
		var reply_id = $(this).attr('id').replace(/^reply_/, '');

		$(this).find('div.body a:not([rel="nofollow"])').each(function() {
			var id, post, $mentioned;

			if(id = $(this).text().match(/^>>(\d+)$/))
				id = id[1];
			else
				return;

			$post = $('#reply_' + id);
			if($post.length == 0)
				return;

			$mentioned = $post.find('p.intro span.mentioned');
			if($mentioned.length == 0)
				$mentioned = $('').appendTo($post.find('p.intro'));

			if ($mentioned.find('a.mentioned-' + reply_id).length != 0)
				return;

			var $link = $('>>' +
				reply_id + '');
			$link.appendTo($mentioned)

			if (window.init_hover) {
				$link.each(init_hover);
			}
		});
	};

	$('div.post.reply').each(showBackLinks);

        $(document).bind('new_post', function(e, post) {
		if ($(post).hasClass("reply")) {
			showBackLinks.call(post);
		}
		else {
			$(post).find('div.post.reply').each(showBackLinks);
		}
	});
});