text:
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// eslint-disable-next-line node/no-extraneous-import
import {Probot} from 'probot';
import {Runner} from './runner';
// eslint-disable-next-line node/no-extraneous-import
import {Octokit} from '@octokit/rest';
// We pull in @octokit/request to crreate an appropriate type for the
// GitHubAPI interface:
// eslint-disable-next-line node/no-extraneous-import
import {request} from '@octokit/request';
// eslint-disable-next-line node/no-extraneous-import
import {RequestError} from '@octokit/request-error';
import {getContextLogger, GCFLogger, getAuthenticatedOctokit} from 'gcf-utils';
import {
  getConfig,
  MultiConfigChecker,
} from '@google-automations/bot-config-utils';
import {syncLabels} from '@google-automations/label-utils';
import {
  Errors,
  GitHub,
  Manifest,
  ManifestOptions,
  ReleaseType,
  ReleaserConfig,
  getReleaserTypes,
  setLogger,
  manifestSchema,
  configSchema,
  Logger,
  PluginType,
} from 'release-please';
import schema from './config-schema.json';
import {
  BranchConfiguration,
  ConfigurationOptions,
  WELL_KNOWN_CONFIGURATION_FILE,
  DEFAULT_CONFIGURATION,
} from './config-constants';
import {FORCE_RUN_LABEL, RELEASE_PLEASE_LABELS} from './labels';
import {addOrUpdateIssue} from '@google-automations/issue-utils';
type RequestBuilderType = typeof request;
type DefaultFunctionType = RequestBuilderType['defaults'];
type RequestFunctionType = ReturnType<DefaultFunctionType>;

type OctokitType = InstanceType<typeof Octokit>;

interface GitHubAPI {
  graphql: Function;
  request: RequestFunctionType;
}
const DEFAULT_RELEASE_PLEASE_CONFIG = 'release-please-config.json';
const DEFAULT_RELEASE_PLEASE_MANIFEST = '.release-please-manifest.json';

class BotConfigurationError extends Error {}

function releaseTypeFromRepoLanguage(language: string | null): ReleaseType {
  if (language === null) {
    throw new BotConfigurationError('repository has no detected language');
  }
  switch (language.toLowerCase()) {
    case 'java':
      return 'java-yoshi';
    case 'typescript':
    case 'javascript':
      return 'node';
    case 'php':
      return 'php-yoshi';
    case 'go':
      return 'go-yoshi';
    default: {
      const releasers = getReleaserTypes();
      if (releasers.includes(language.toLowerCase() as ReleaseType)) {
        return language.toLowerCase() as ReleaseType;
      } else {
        throw new BotConfigurationError(`unknown release type: ${language}`);
      }
    }
  }
}

function findBranchConfiguration(
  branch: string,
  config: ConfigurationOptions
): BranchConfiguration[] {
  const configurations: BranchConfiguration[] = [];

  // look at primaryBranch first
  if (branch === config.primaryBranch) {
    configurations.push({
      ...config,
      ...{branch},
    });
  }

  if (config.branches) {
    for (const branchConfig of config.branches) {
      if (branch === branchConfig.branch) {
        configurations.push(branchConfig);
      }
    }
  }

  return configurations;
}

/**
 * Returns the repository's default/primary branch.
 *
 * @param {string} owner owner portion of GitHub repo URL.
 * @param {string} repo repo portion of GitHub repo URL.
 * @param {object} octokit authenticated Octokit instance.
 * @returns {string}
 */
async function getRepositoryDefaultBranch(
  owner: string,
  repo: string,
  octokit: OctokitType
) {
  const {data} = await octokit.repos.get({
    owner,
    repo,
  });
  return (
    data as {
      default_branch: string;
    }
  ).default_branch;
}

/**
 * Returns the repository's default/primary branch.
 *
 * @param {string} owner owner portion of GitHub repo URL.
 * @param {string} repo repo portion of GitHub repo URL.
 * @param {object} octokit authenticated Octokit instance.
 * @returns {string}
 */
async function getConfigWithDefaultBranch(
  owner: string,
  repo: string,
  octokit: OctokitType,
  defaultBranch?: string
): Promise<ConfigurationOptions | null> {
  const config = await getConfig<ConfigurationOptions>(
    octokit,
    owner,
    repo,
    WELL_KNOWN_CONFIGURATION_FILE
  );
  if (config && !config.primaryBranch) {
    config.primaryBranch =
      defaultBranch || (await getRepositoryDefaultBranch(owner, repo, octokit));
  }
  return config;
}

async function buildGitHub(
  owner: string,
  repo: string,
  octokit: GitHubAPI,
  defaultBranch?: string,
  logger?: Logger
): Promise<GitHub> {
  return await GitHub.create({
    owner,
    repo,
    defaultBranch,
    octokitAPIs: {
      octokit: octokit as {} as OctokitType,
      request: octokit.request,
      graphql: octokit.graphql,
    },
    logger,
  });
}

async function buildManifest(
  github: GitHub,
  repoLanguage: string | null,
  configuration: BranchConfiguration,
  logger: GCFLogger,
  plugins: Array<PluginType>
): Promise<Manifest> {
  if (configuration.manifest) {
    logger.info('building from manifest file');
    return await Manifest.fromManifest(
      github,
      configuration.branch,
      configuration.manifestConfig,
      configuration.manifestFile,
      {
        logger,
      }
    );
  }

  const releaseType = configuration.releaseType
    ? configuration.releaseType
    : configuration.manifest
    ? 'simple'
    : releaseTypeFromRepoLanguage(repoLanguage);

  const releaserConfig: ReleaserConfig = {
    releaseType,
    versioning: configuration.versioning,
    bumpMinorPreMajor: configuration.bumpMinorPreMajor,
    bumpPatchForMinorPreMajor: configuration.bumpPatchForMinorPreMajor,
    draft: configuration.draft,
    draftPullRequest: configuration.draftPullRequest,
    packageName: configuration.packageName,
    includeComponentInTag: !!configuration.monorepoTags,
    pullRequestTitlePattern: configuration.pullRequestTitlePattern,
    // changelogSections: configuration.changelogSections,
    changelogHost: configuration.changelogHost,
    changelogPath: configuration.changelogPath,
    changelogType: configuration.changelogType,
    versionFile: configuration.versionFile,
    extraFiles: configuration.extraFiles,
    initialVersion: configuration.initialVersion,
  };
  const manifestOverrides: ManifestOptions = {
    manifestPath: configuration.manifestFile,
    labels: configuration.releaseLabels,
    releaseLabels: configuration.releaseLabel?.split(','),
    plugins,
    logger,
  };
  return await Manifest.fromConfig(
    github,
    configuration.branch,
    releaserConfig,
    manifestOverrides,
    configuration.path
  );
}

async function runBranchConfigurationWithConfigurationHandling(
  github: GitHub,
  repoLanguage: string | null,
  repoUrl: string,
  branchConfiguration: BranchConfiguration,
  octokit: Octokit,
  logger: GCFLogger
) {
  try {
    await runBranchConfiguration(
      github,
      repoLanguage,
      repoUrl,
      branchConfiguration,
      octokit,
      logger
    );
  } catch (e) {
    if (e instanceof Errors.ConfigurationError) {
      // In the future, this could raise an issue against the
      // installed repository
      logger.warn(e);
      await addOrUpdateIssue(
        octokit,
        github.repository.owner,
        github.repository.repo,
        'Configuration error for release-please',
        e.message,
        ['release-please'],
        logger
      );
    } else if (e instanceof BotConfigurationError) {
      logger.warn(e);
      await addOrUpdateIssue(
        octokit,
        github.repository.owner,
        github.repository.repo,
        'Configuration error for release-please',
        e.message,
        ['release-please'],
        logger
      );
    } else {
      // re-raise
      throw e;
    }
  }
}

// TODO: Allow this functionality to be enabled via an
// org level config in a .github repository:
const ORG_SENTENCE_CASE_ENABLED = new Set<string>([
  'chingor13',
  'bcoe',
  'googleapis',
]);
function isSentenceCaseEnabled(repoUrl: string) {
  const [org] = repoUrl.split('/');
  return ORG_SENTENCE_CASE_ENABLED.has(org);
}

async function runBranchConfiguration(
  github: GitHub,
  repoLanguage: string | null,
  repoUrl: string,
  branchConfiguration: BranchConfiguration,
  octokit: Octokit,
  logger: GCFLogger
) {
  const plugins: Array<PluginType> = [
    ...(isSentenceCaseEnabled(repoUrl)
      ? [
          {
            type: 'sentence-case',
            specialWords: ['gRPC', 'npm'],
          },
        ]
      : []),
  ];
  let manifest = await buildManifest(
    github,
    repoLanguage,
    branchConfiguration,
    logger,
    plugins
  );

  // release-please can handle creating a release on GitHub, we opt not to do
  // this for our repos that have autorelease enabled.
  if (branchConfiguration.handleGHRelease) {
    logger.info(`handling GitHub release for (${repoUrl})`);
    try {
      const numReleases = await Runner.createReleases(manifest);
      logger.info(`Created ${numReleases} releases`);
      if (numReleases > 0) {
        // we created a release, reload config which may include the latest
        // version
        manifest = await buildManifest(
          github,
          repoLanguage,
          branchConfiguration,
          logger,
          plugins
        );
      }
    } catch (e) {
      if (e instanceof Errors.DuplicateReleaseError) {
        // In the future, this could raise an issue against the
        // installed repository
        logger.warn('Release tag already exists, skipping...', e);
      } else {
        throw e;
      }
    }
  }

  logger.info(`creating pull request for (${repoUrl})`);
  await Runner.createPullRequests(manifest);
}

const handler = (app: Probot) => {
  app.on('push', async context => {
    const logger = getContextLogger(context);
    const repoUrl = context.payload.repository.full_name;
    const branch = context.payload.ref.replace('refs/heads/', '');
    const repoLanguage = context.payload.repository.language;
    const {owner, repo} = context.repo();
    let octokit: Octokit;
    if (context.payload.installation?.id) {
      octokit = await getAuthenticatedOctokit(context.payload.installation.id);
    } else {
      throw new Error(
        'Installation ID not provided in push event payload.' +
          ' We cannot authenticate Octokit.'
      );
    }

    const remoteConfiguration = await getConfigWithDefaultBranch(
      owner,
      repo,
      octokit,
      context.payload.repository.default_branch
    );

    // If no configuration is specified,
    if (!remoteConfiguration) {
      logger.info(`release-please not configured for (${repoUrl})`);
      return;
    }

    const configuration = {
      ...DEFAULT_CONFIGURATION,
      ...remoteConfiguration,
    };

    // use gcf-logger as logger for release-please
    setLogger(logger);

    logger.info(`push (${repoUrl}, ${branch})`);
    const branchConfigurations = findBranchConfiguration(branch, configuration);

    if (branchConfigurations.length === 0) {
      logger.info(`no configuration for (${repoUrl}, ${branch})`);
      return;
    }

    const github = await buildGitHub(
      owner,
      repo,
      octokit as GitHubAPI,
      context.payload.repository.default_branch,
      logger
    );

    for (const branchConfiguration of branchConfigurations) {
      logger.debug(branchConfiguration);
      await runBranchConfigurationWithConfigurationHandling(
        github,
        repoLanguage,
        repoUrl,
        branchConfiguration,
        octokit,
        logger
      );
    }
  });

  // See: https://github.com/octokit/webhooks.js/issues/277
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  app.on('schedule.repository' as any, async context => {
    const logger = getContextLogger(context);
    const repoUrl = context.payload.repository.full_name;
    const owner = context.payload.organization.login;
    const repo = context.payload.repository.name;
    let octokit: Octokit;
    if (context.payload.installation?.id) {
      octokit = await getAuthenticatedOctokit(context.payload.installation.id);
    } else {
      throw new Error(
        `Installation ID not provided in ${context.payload.action} event.` +
          ' We cannot authenticate Octokit.'
      );
    }

    const remoteConfiguration = await getConfigWithDefaultBranch(
      owner,
      repo,
      octokit
    );

    // If no configuration is specified,
    if (!remoteConfiguration) {
      logger.info(`release-please not configured for (${repoUrl})`);
      return;
    }

    // syncLabels is just a nice to have feature, so we ignore all the
    // errors and continue. If this strategy becomes problematic, we
    // can create another scheduler job.
    try {
      await syncLabels(octokit, owner, repo, RELEASE_PLEASE_LABELS);
    } catch (e) {
      const err = e as Error;
      err.message = `Failed to sync the labels: ${err.message}`;
      logger.error(err);
    }
  });

  app.on('pull_request.labeled', async context => {
    const logger = getContextLogger(context);
    // if missing the label, skip
    if (
      // See: https://github.com/probot/probot/issues/1366
      !context.payload.pull_request.labels.some(
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        (label: any) => label.name === FORCE_RUN_LABEL
      )
    ) {
      logger.info(
        `ignoring non-force label action (${context.payload.pull_request.labels
          .map(label => {
            return label.name;
          })
          .join(', ')})`
      );
      return;
    }

    const repoUrl = context.payload.repository.full_name;
    const owner = context.payload.repository.owner.login;
    const repo = context.payload.repository.name;
    const branch = context.payload.pull_request.base.ref;
    const repoLanguage = context.payload.repository.language;
    let octokit: Octokit;
    if (context.payload.installation?.id) {
      octokit = await getAuthenticatedOctokit(context.payload.installation.id);
    } else {
      throw new Error(
        `Installation ID not provided in ${context.payload.action} event.` +
          ' We cannot authenticate Octokit.'
      );
    }

    // remove the label
    try {
      await octokit.issues.removeLabel({
        name: FORCE_RUN_LABEL,
        issue_number: context.payload.pull_request.number,
        owner,
        repo,
      });
    } catch (e) {
      if (e instanceof RequestError && e.status === 404) {
        // on retries, the label may no longer exist on the PR
        logger.info('label no longer exists on PR');
      } else {
        throw e;
      }
    }

    // check release please config
    const remoteConfiguration = await getConfigWithDefaultBranch(
      owner,
      repo,
      octokit,
      context.payload.repository.default_branch
    );

    // If no configuration is specified,
    if (!remoteConfiguration) {
      logger.info(`release-please not configured for (${repoUrl})`);
      return;
    }

    const configuration = {
      ...DEFAULT_CONFIGURATION,
      ...remoteConfiguration,
    };

    logger.info(`pull_request.labeled (${repoUrl}, ${branch})`);
    const branchConfigurations = findBranchConfiguration(branch, configuration);
    if (branchConfigurations.length === 0) {
      logger.info(`no configuration for (${repoUrl}, ${branch})`);
      return;
    }

    const github = await buildGitHub(
      owner,
      repo,
      octokit as GitHubAPI,
      context.payload.repository.default_branch,
      logger
    );

    for (const branchConfiguration of branchConfigurations) {
      logger.debug(branchConfiguration);
      await runBranchConfigurationWithConfigurationHandling(
        github,
        repoLanguage,
        repoUrl,
        branchConfiguration,
        octokit,
        logger
      );
    }
  });

  app.on('release.created', async context => {
    const logger = getContextLogger(context);
    const repoUrl = context.payload.repository.full_name;
    const {owner, repo} = context.repo();
    let octokit: Octokit;
    if (context.payload.installation?.id) {
      octokit = await getAuthenticatedOctokit(context.payload.installation.id);
    } else {
      throw new Error(
        `Installation ID not provided in ${context.payload.action} event.` +
          ' We cannot authenticate Octokit.'
      );
    }
    const remoteConfiguration = await getConfig<ConfigurationOptions>(
      octokit,
      owner,
      repo,
      WELL_KNOWN_CONFIGURATION_FILE
    );

    // If no configuration is specified,
    if (!remoteConfiguration) {
      logger.info(`release-please not configured for (${repoUrl})`);
      return;
    }

    // Releases are still currently handled by autorelease, we hook into the
    // release.created webhook just to log this metric:
    logger.metric('release_please.release_created', {
      url: context.payload.repository.releases_url,
    });
  });

  // Check the config schema on PRs.
  app.on(['pull_request.opened', 'pull_request.synchronize'], async context => {
    const logger = getContextLogger(context);
    const repoUrl = context.payload.repository.full_name;
    const baseBranch = context.payload.pull_request.base.ref;
    const prNumber = context.payload.pull_request.number;
    const headSha = context.payload.pull_request.head.sha;
    const defaultBranch = context.payload.pull_request.base.repo.default_branch;

    const headOwner = context.payload.pull_request.head.repo.owner.login;
    const headRepo = context.payload.pull_request.head.repo.name;
    const headBranch = context.payload.pull_request.head.ref;
    let octokit: Octokit;
    if (context.payload.installation?.id) {
      octokit = await getAuthenticatedOctokit(context.payload.installation.id);
    } else {
      throw new Error(
        `Installation ID not provided in ${context.payload.action} event.` +
          ' We cannot authenticate Octokit.'
      );
    }

    const schemasByFile: Record<string, object> = {
      '.github/release-please.yml': schema,
    };
    const remoteConfiguration = await getConfig<ConfigurationOptions>(
      octokit,
      headOwner,
      headRepo,
      WELL_KNOWN_CONFIGURATION_FILE,
      {branch: headBranch}
    );

    // If no configuration is specified,
    if (!remoteConfiguration) {
      logger.info(`release-please not configured for (${repoUrl})`);
      return;
    }
    if (!remoteConfiguration.primaryBranch) {
      remoteConfiguration.primaryBranch = defaultBranch;
    }

    // Use a try/catch here because we are validating the `.github/release-please.yml`
    // file after the fact so it's possible that the config does not match as expected
    // (e.g. if `branches` is not an array)
    try {
      const branchConfigurations = findBranchConfiguration(
        baseBranch,
        remoteConfiguration
      );
      logger.info(
        `found ${branchConfigurations.length} configuration(s) for ${baseBranch}`
      );

      // Collect all manifest configs
      for (const branchConfig of branchConfigurations) {
        if (branchConfig.manifest) {
          schemasByFile[
            branchConfig.manifestConfig || DEFAULT_RELEASE_PLEASE_CONFIG
          ] = configSchema;
          schemasByFile[
            branchConfig.manifestFile || DEFAULT_RELEASE_PLEASE_MANIFEST
          ] = manifestSchema;
        }
      }
    } catch (e) {
      if (e instanceof Error) {
        logger.warn(e);
      } else {
        throw e;
      }
    }

    // The config checker fetches and validates each touched config file
    // against the specified schema. It creates a failing commit check for
    // each invalid file.
    const configChecker = new MultiConfigChecker(schemasByFile);
    const {owner, repo} = context.repo();
    await configChecker.validateConfigChanges(
      octokit,
      owner,
      repo,
      headSha,
      prNumber
    );
  });

  // If a release PR is closed unmerged, label with autorelease: closed
  app.on('pull_request.closed', async context => {
    const logger = getContextLogger(context);
    const repoUrl = context.payload.repository.full_name;
    const {owner, repo} = context.repo();
    let octokit: Octokit;
    if (context.payload.installation?.id) {
      octokit = await getAuthenticatedOctokit(context.payload.installation.id);
    } else {
      throw new Error(
        `Installation ID not provided in ${context.payload.action} event.` +
          ' We cannot authenticate Octokit.'
      );
    }
    const remoteConfiguration = await getConfig<ConfigurationOptions>(
      octokit,
      owner,
      repo,
      WELL_KNOWN_CONFIGURATION_FILE
    );

    // If no configuration is specified,
    if (!remoteConfiguration) {
      logger.info(`release-please not configured for (${repoUrl})`);
      return;
    }

    if (context.payload.pull_request.merged) {
      logger.info('ignoring merged pull request');
      return;
    }

    if (
      context.payload.pull_request.labels.some(label => {
        return label.name === 'autorelease: pending';
      })
    ) {
      await Promise.all([
        octokit.issues.removeLabel(
          context.repo({
            issue_number: context.payload.pull_request.number,
            name: 'autorelease: pending',
          })
        ),
        octokit.issues.addLabels(
          context.repo({
            issue_number: context.payload.pull_request.number,
            labels: ['autorelease: closed'],
          })
        ),
      ]);
    }
  });

  // If a closed release PR is reopened, re-label with autorelease: pending
  app.on('pull_request.reopened', async context => {
    const logger = getContextLogger(context);
    const repoUrl = context.payload.repository.full_name;
    const {owner, repo} = context.repo();
    let octokit: Octokit;
    if (context.payload.installation?.id) {
      octokit = await getAuthenticatedOctokit(context.payload.installation.id);
    } else {
      throw new Error(
        `Installation ID not provided in ${context.payload.action} event.` +
          ' We cannot authenticate Octokit.'
      );
    }
    const remoteConfiguration = await getConfig<ConfigurationOptions>(
      octokit,
      owner,
      repo,
      WELL_KNOWN_CONFIGURATION_FILE
    );

    // If no configuration is specified,
    if (!remoteConfiguration) {
      logger.info(`release-please not configured for (${repoUrl})`);
      return;
    }

    if (
      context.payload.pull_request.labels.some(label => {
        return label.name === 'autorelease: closed';
      })
    ) {
      await Promise.all([
        octokit.issues.removeLabel(
          context.repo({
            issue_number: context.payload.pull_request.number,
            name: 'autorelease: closed',
          })
        ),
        octokit.issues.addLabels(
          context.repo({
            issue_number: context.payload.pull_request.number,
            labels: ['autorelease: pending'],
          })
        ),
      ]);
    }
  });
};

export const api = {
  handler,
  getRepositoryDefaultBranch,
};


text:
This changelog is likely not to contain changes from individual commits!
Individual commits may be linked in this file for further information.
This file is not to be changed by anyone, other than active, contributing members of the project.

## Alpha

 - Nothing to see here, alpha is not a stage. --

 ## Beta

 No builds released yet.
 Come back later.

redpajama_set_name: RedPajamaGithub


text:
package com.dihanov.musiq.models;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;

/**
 * Created by dimitar.dihanov on 2/12/2018.
 */

public class Recenttracks {
    @SerializedName("track")
    @Expose
    private List<Track> track = null;
    @SerializedName("@attr")
    @Expose
    private Attr_ attr;

    public List<Track> getTrack() {
        return track;
    }

    public void setTrack(List<Track> track) {
        this.track = track;
    }

    public Attr_ getAttr() {
        return attr;
    }

    public void setAttr(Attr_ attr) {
        this.attr = attr;
    }
}


text:
<?php

namespace Drupal\layout_builder\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseDialogCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\layout_builder\SectionStorageInterface;

/**
 * Provides AJAX responses to rebuild the Layout Builder.
 *
 * @internal
 */
trait LayoutRebuildTrait {

  /**
   * The class resolver.
   *
   * @var \Drupal\Core\DependencyInjection\ClassResolverInterface
   */
  protected $classResolver;

  /**
   * Rebuilds the layout.
   *
   * @param \Drupal\layout_builder\SectionStorageInterface $section_storage
   *   The section storage.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   An AJAX response to either rebuild the layout and close the dialog, or
   *   reload the page.
   */
  protected function rebuildAndClose(SectionStorageInterface $section_storage) {
    $response = $this->rebuildLayout($section_storage);
    $response->addCommand(new CloseDialogCommand('#drupal-off-canvas'));
    return $response;
  }

  /**
   * Rebuilds the layout.
   *
   * @param \Drupal\layout_builder\SectionStorageInterface $section_storage
   *   The section storage.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse
   *   An AJAX response to either rebuild the layout and close the dialog, or
   *   reload the page.
   */
  protected function rebuildLayout(SectionStorageInterface $section_storage) {
    $response = new AjaxResponse();
    $layout_controller = $this->classResolver->getInstanceFromDefinition(LayoutBuilderController::class);
    $layout = $layout_controller->layout($section_storage, TRUE);
    $response->addCommand(new ReplaceCommand('#layout-builder', $layout));
    return $response;
  }

}


text:
package top.cardone.authority.dto;

import top.cardone.authority.po.RolePermission;

/**
 * 角色与许可
 *
 * @author yao hai tao
 */
@lombok.ToString(callSuper = true)
public class RolePermissionDto extends RolePermission {
}


text:
which brew || /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew update
cat Brewfile.d/* | sort -u | brew bundle --verbose --file=-


text:
package lombok;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Ensures the variable declaration that you annotate will be cleaned up by calling its close method, regardless
 * of what happens. Implemented by wrapping all statements following the local variable declaration to the
 * end of your scope into a try block that, as a finally action, closes the resource.
 *

 * Example:
 *

 * public void copyFile(String in, String out) throws IOException {
 *     @Cleanup FileInputStream inStream = new FileInputStream(in);
 *     @Cleanup FileOutputStream outStream = new FileOutputStream(out);
 *     byte[] b = new byte[65536];
 *     while (true) {
 *         int r = inStream.read(b);
 *         if (r == -1) break;
 *         outStream.write(b, 0, r);
 *     }
 * }
 *

 *
 * Will generate:
 *

 * public void copyFile(String in, String out) throws IOException {
 *     @Cleanup FileInputStream inStream = new FileInputStream(in);
 *     try {
 *         @Cleanup FileOutputStream outStream = new FileOutputStream(out);
 *         try {
 *             byte[] b = new byte[65536];
 *             while (true) {
 *                 int r = inStream.read(b);
 *                 if (r == -1) break;
 *                 outStream.write(b, 0, r);
 *             }
 *         } finally {
 *             out.close();
 *         }
 *     } finally {
 *         in.close();
 *     }
 * }
 *

 *
 * Note that the final close method call, if it throws an exception, will overwrite any exception thrown
 * in the main body of the generated try block. You should NOT rely on this behaviour - future versions of
 * lombok intend to silently swallow any exception thrown by the cleanup method _IF the main body
 * throws an exception as well, as the earlier exception is usually far more useful.
 *

 * However, in java 1.6, generating the code to do this is prohibitively complicated.
 */
@Target(ElementType.LOCAL_VARIABLE)
@Retention(RetentionPolicy.SOURCE)
public @interface Cleanup {
	/** The name of the method that cleans up the resource. By default, 'close'. The method must not have any parameters. */
	String value() default "close";
}


text:
//// TODO:
//// [O] Contracts
//// [O] Documentation

namespace Splunk.Client
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Net;
    using System.Threading.Tasks;

    ///
    /// Provides a base class for representing a collection of Splunk resources.
    ///
    /// <remarks>
    /// <para>References:</para>
    /// <list type="number">
    /// <item><description>
    ///   Accessing Splunk resources,
    ///   especially "Other actions for Splunk REST API endpoints".
    /// </description></item>
    /// <item><description>
    ///   REST API Reference.
    /// </description></item>
    /// </list>
    /// </remarks>
    /// <typeparam name="TEntity">
    /// Type of the entity.
    /// </typeparam>
    /// <typeparam name="TResource">
    /// Type of the resource.
    /// </typeparam>
    /// <seealso cref="T:Splunk.Client.BaseEntity{Splunk.Client.ResourceCollection}"/>
    /// <seealso cref="T:Splunk.Client.IEntityCollection{TEntity,TResource}"/>
    public class EntityCollection<TEntity, TResource> : BaseEntity<ResourceCollection>, IEntityCollection<TEntity, TResource>
        where TEntity : BaseEntity<TResource>, new()
        where TResource : BaseResource, new()
    {
        #region Constructors

        ///
        /// Initializes a new <see cref="EntityCollection<TEntity,TResource>"/> instance.
        ///
        /// <param name="service">
        /// An object representing a root Splunk service endpoint.
        /// </param>
        /// <param name="name">
        /// An object identifying a Splunk resource within
        /// <paramref name= "service"/>.<see cref="Namespace"/>.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="service"/> or <paramref name="name"/> are <c>null</c>.
        /// </exception>
        protected internal EntityCollection(Service service, ResourceName name)
            : base(service, name)
        { }

        ///
        /// Initializes a new instance of the <see cref="EntityCollection<TEntity,TResource>"/> class.
        ///
        /// <param name="context">
        /// An object representing a Splunk server session.
        /// </param>
        /// <param name="ns">
        /// An object identifying a Splunk services namespace.
        /// </param>
        /// <param name="name">
        /// An object identifying a Splunk entity collection within
        /// <paramref name="ns"/>.
        /// </param>
        protected internal EntityCollection(Context context, Namespace ns, ResourceName name)
            : base(context, ns, name)
        { }

        ///
        /// Initializes a new instance of the <see cref="EntityCollection<TEntity,TResource>"/> class.
        ///
        /// <param name="context">
        /// An object representing a Splunk server session.
        /// </param>
        /// <param name="entry">
        /// A entry in a Splunk atom feed response.
        /// </param>
        /// <param name="generatorVersion">
        /// The generator version.
        /// </param>
        protected internal EntityCollection(Context context, AtomEntry entry, Version generatorVersion)
        {
            // We cannot use the base constructor because it will use base.CreateEntity, not this.CreateEntity
            this.Initialize(context, entry, generatorVersion);
        }

        ///
        /// Initializes a new instance of the <see cref="EntityCollection<TEntity,TResource>"/> class.
        ///
        /// <param name="context">
        /// An object representing a Splunk server session.
        /// </param>
        /// <param name="feed">
        /// A Splunk atom feed response.
        /// </param>
        protected internal EntityCollection(Context context, AtomFeed feed)
        {
            // We cannot use the base constructor because it will use base.CreateResource, not this.CreateResource
            this.Initialize(context, feed);
        }

        ///
        /// Infrastructure. Initializes a new instance of the <see cref= "EntityCollection<TEntity,TResource>"/> class.
        ///
        /// <remarks>
        /// This API supports the Splunk client infrastructure and is not intended to
        /// be used directly from your code.
        /// </remarks>
        public EntityCollection()
        { }

        #endregion

        #region Properties

        ///
        /// Gets the entity at the specified <paramref name="index"/>.
        ///
        /// <param name="index">
        /// The zero-based index of the entity to get.
        /// </param>
        /// <returns>
        /// An object representing the entity at <paramref name="index"/>.
        /// </returns>
        public TEntity this[int index]
        {
            get { return this.Create((TResource)this.Snapshot.Resources[index]); }
        }

        ///
        /// Gets the number of entries in the current
        /// <see cref="EntityCollection<TEntity,TResource>"/>.
        ///
        /// <value>
        /// The number of entries in the current
        /// <see cref="EntityCollection<TEntity,TResource>"/>.
        /// </value>
        public int Count
        {
            get { return this.Snapshot.Resources.Count; }
        }

        #endregion

        #region Methods

        #region Operational interface

        ///
        /// Asynchronously creates a new Splunk entity.
        ///
        /// <param name="arguments">
        /// Arguments to the Splunk REST API for creating the desired entity.
        /// </param>
        /// <returns>
        /// An object representing the entity created.
        /// </returns>
        public virtual async Task<TEntity> CreateAsync(params Argument[] arguments)
        {
            return await this.CreateAsync(arguments.AsEnumerable()).ConfigureAwait(false);
        }

        ///
        /// Asynchronously creates a new Splunk entity.
        ///
        /// <param name="arguments">
        /// Arguments to the Splunk REST API for creating the desired entity.
        /// </param>
        /// <returns>
        /// An object representing the entity created.
        /// </returns>
        public virtual async Task<TEntity> CreateAsync(IEnumerable<Argument> arguments)
        {
            using (var response = await this.Context.PostAsync(this.Namespace, this.ResourceName, arguments).ConfigureAwait(false))
            {
                await response.EnsureStatusCodeAsync(HttpStatusCode.Created).ConfigureAwait(false);
                return await BaseEntity<TResource>.CreateAsync<TEntity>(this.Context, response).ConfigureAwait(false);
            }
        }

        ///
        /// Asynchronously retrieves a <see cref="Entity<TResource>"/> in the current
        /// <see cref="EntityCollection<TEntity,TResource>"/> by name.
        ///
        /// <param name="name">
        /// Name of the entity to retrieve.
        /// </param>
        /// <returns>
        /// The entity retrieved.
        /// </returns>
        public virtual async Task<TEntity> GetAsync(string name)
        {
            var resourceName = new ResourceName(this.ResourceName, name);

            using (Response response = await this.Context.GetAsync(this.Namespace, resourceName).ConfigureAwait(false))
            {
                await response.EnsureStatusCodeAsync(HttpStatusCode.OK).ConfigureAwait(false);
                return await BaseEntity<TResource>.CreateAsync<TEntity>(this.Context, response).ConfigureAwait(false);
            }
        }

        ///
        /// Asynchronously retrieves a fresh copy of the full list of entities in the
        /// current <see cref="EntityCollection<TEntity,TResource>"/>.
        ///
        /// <remarks>
        /// Following completion of the operation the list of entites in the current
        /// <see cref="EntityCollection<TEntity,TREsource>"/> will contain all changes
        /// since the list was last retrieved.
        /// </remarks>
        /// <returns>
        /// A <see cref="Task"/> representing the operation.
        /// </returns>
        public virtual async Task GetAllAsync()
        {
            using (var response = await this.Context.GetAsync(this.Namespace, this.ResourceName, GetAll).ConfigureAwait(false))
            {
                await response.EnsureStatusCodeAsync(HttpStatusCode.OK).ConfigureAwait(false);
                await this.ReconstructSnapshotAsync(response).ConfigureAwait(false);
            }
        }

        ///
        /// Asynchronously retrieves an entity in the current collection by name.
        ///
        /// <param name="name">
        /// The name of the entity to retrieve.
        /// </param>
        /// <returns>
        /// An object representing entity <paramref name="name"/> or <c>null</c>,
        /// if no such entity exists.
        /// </returns>
        public virtual async Task<TEntity> GetOrNullAsync(string name)
        {
            var resourceName = new ResourceName(this.ResourceName, name);

            using (Response response = await this.Context.GetAsync(this.Namespace, resourceName).ConfigureAwait(false))
            {
                await response.EnsureStatusCodeAsync(HttpStatusCode.OK, HttpStatusCode.NotFound).ConfigureAwait(false);
                TEntity resourceEndpoint = null;

                if (response.Message.StatusCode == HttpStatusCode.OK)
                {
                    resourceEndpoint = await BaseEntity<TResource>.CreateAsync<TEntity>(this.Context, response).ConfigureAwait(false);
                }

                return resourceEndpoint;
            }
        }

        ///
        /// Asynchronously retrieves select entities from the list of entites in the
        /// current <see cref="EntityCollection<TEntity,TResource>"/>.
        ///
        /// <remarks>
        /// Following completion of the operation the list of entities in the current
        /// <see cref="EntityCollection<TEntity,TResource>"/> will contain all changes
        /// since the select entites were last retrieved.
        /// </remarks>
        /// <param name="arguments">
        /// A variable-length parameters list containing arguments.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> representing the operation.
        /// </returns>
        public virtual async Task GetSliceAsync(params Argument[] arguments)
        {
            await this.GetSliceAsync(arguments.AsEnumerable()).ConfigureAwait(false);
        }

        ///
        /// Asynchronously retrieves select entities from the list of entites in the
        /// current <see cref="EntityCollection<TEntity,TResource>"/>.
        ///
        /// <remarks>
        /// Following completion of the operation the list of entities in the current
        /// <see cref="EntityCollection<TEntity,TResource>"/> will contain all changes
        /// since the select entites were last retrieved.
        /// </remarks>
        /// <param name="arguments">
        /// The arguments.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> representing the operation.
        /// </returns>
        public virtual async Task GetSliceAsync(IEnumerable<Argument> arguments)
        {
            using (Response response = await this.Context.GetAsync(this.Namespace, this.ResourceName).ConfigureAwait(false))
            {
                await response.EnsureStatusCodeAsync(HttpStatusCode.OK).ConfigureAwait(false);
                await this.ReconstructSnapshotAsync(response).ConfigureAwait(false);
            }
        }

        ///
        /// Asynchronously forces the Splunk server to reload data for the current
        /// <see cref="EntityCollection<TEntity,TResource>"/>.
        ///
        /// <returns>
        /// A <see cref="Task"/> representing the operation.
        /// </returns>
        public async Task ReloadAsync()
        {
            var reload = new ResourceName(this.ResourceName, "_reload");

            using (Response response = await this.Context.GetAsync(this.Namespace, reload).ConfigureAwait(false))
            {
                await response.EnsureStatusCodeAsync(HttpStatusCode.OK).ConfigureAwait(false);
            }
        }

        #endregion

        #region IReadOnlyList<TEntity> methods

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        ///
        /// Gets an enumerator that iterates through the current <see cref=
        /// "EntityCollection<TEntity,TResource>"/>.
        ///
        /// <returns>
        /// An object for iterating through the current
        /// <see cref= "EntityCollection<TEntity,TResource>"/>.
        /// </returns>
        public IEnumerator<TEntity> GetEnumerator()
        {
            return this.Snapshot.Resources.Select(resource => {
                return Create((TResource)resource);
            }).GetEnumerator();
        }

        #endregion

        #region Infrastructure methods

        /// <inheritdoc/>
        protected override void CreateSnapshot(AtomEntry entry, Version generatorVersion)
        {
            this.Snapshot = new ResourceCollection();
            this.Snapshot.Initialize(entry, generatorVersion);
        }

        /// <inheritdoc/>
        protected override void CreateSnapshot(AtomFeed feed)
        {
            this.Snapshot = new ResourceCollection();
            this.Snapshot.Initialize<TResource>(feed);
        }

        /// <inheritdoc/>
        protected override void CreateSnapshot(ResourceCollection resource)
        {
            this.Snapshot = resource;
        }

        #endregion

        #endregion

        #region Privates/internals

        internal static readonly ReadOnlyCollection<Message> NoMessages = new ReadOnlyCollection<Message>(new List<Message>());
        static readonly Argument[] GetAll = new Argument[] { new Argument("count", 0) };

        TEntity Create(TResource resource)
        {
            var entity = new TEntity();

            entity.Initialize(this.Context, resource);
            return entity;
        }

        #endregion
    }
}


text:
package doslosmuertos.mechagontrail;

import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.os.Handler;

import doslosmuertos.mechagontrail.util.GameBattle;
import doslosmuertos.mechagontrail.util.GameEnemy;
import doslosmuertos.mechagontrail.util.GameMech;
import doslosmuertos.mechagontrail.util.MechagonTrailApplication;

public class BattleScreen extends ActionBarActivity {

    Button runButton, itemButton, attackButton, backButton;
    TextView mechHp, enemyHp, winLose, ammo;
    GameMech mech;
    GameEnemy enemy;
    MechagonTrailApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_battle_screen);
        app = (MechagonTrailApplication)getApplication();
        runButton = (Button)findViewById(R.id.runButton);
        itemButton = (Button)findViewById(R.id.useItemButton);
        attackButton = (Button)findViewById(R.id.attackButton);
        backButton = (Button)findViewById(R.id.backToTravelButton);
        mechHp = (TextView)findViewById(R.id.mechHealth);
        enemyHp = (TextView)findViewById(R.id.enemyHealth);
        winLose = (TextView)findViewById(R.id.winLose);
        ammo = (TextView)findViewById(R.id.ammoText);
        mech = app.getGameState().getMech();
        enemy = new GameEnemy();

        mechHp.setText(mech.getHealth() + " / " + mech.getMaxHealth());
        enemyHp.setText(enemy.getHp() + " / 50");
        ammo.setText(String.valueOf(mech.getAmmo()));
        final int chance = enemy.getChance();

        final GameBattle batt = new GameBattle(mech, enemy, app.getGameState().stats);

        backButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), GameLoop.class);
                startActivity(intent);
            }
        });

        attackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                batt.exchangeBlows();

                enemyHp.setText(enemy.getHp() + " / 50");
                mechHp.setText(mech.getHealth() + " / " + mech.getMaxHealth());
                ammo.setText(String.valueOf(mech.getAmmo()));

                if (batt.isOver()) {
                    if (batt.isWon()) {
                        winLose.setText("You win!");
                        app.getGameState().stats.obtainCash(50);
                        backButton.setClickable(true);
                        backButton.setVisibility(View.VISIBLE);
                    }
                    else {
                        winLose.setText("You lose!");
                    }
                }

            }
        });

        runButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean ran = batt.runaway(chance);
                if(ran){
                    winLose.setText("You coward!");
                } else {
                    winLose.setText("Nice try...");
                    batt.getHit();
                }

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_battle_screen, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}


text:
package gapidapk

import (
	"bufio"
	"bytes"
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"strings"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/google/gapid/core/app/crash"
	"github.com/google/gapid/core/event/task"
	"github.com/google/gapid/core/log"
	"github.com/google/gapid/core/os/android/adb"
	"github.com/google/gapid/core/os/device"
	"github.com/google/gapid/core/os/flock"
)

const (
	sendDevInfoAction        = "com.google.android.gapid.action.SEND_DEV_INFO"
	sendDevInfoService       = "com.google.android.gapid.DeviceInfoService"
	sendDevInfoPort          = "gapid-devinfo"
	startServiceAttempts     = 3
	portListeningAttempts    = 5
	perfettoProducerLauncher = "launch_producer"
	launcherPath             = "/data/local/tmp/gapid_launch_producer"
	launcherScript           = "nohup %[1]s &"
)

func init() {
	adb.RegisterDeviceInfoProvider(fetchDeviceInfo)
}

// Returns true if the device is listening to sendDevInfoPort, false if not.
// Error if failed at getting the port info.
func devInfoPortListening(ctx context.Context, d adb.Device) (bool, error) {
	var stdout bytes.Buffer
	if err := d.Shell("cat", "/proc/net/unix").Capture(&stdout, nil).Run(ctx); err != nil {
		return false, log.Errf(ctx, err, "Getting unix abstract port info...")
	}
	if strings.Contains(stdout.String(), sendDevInfoPort) {
		return true, nil
	}
	return false, nil
}

// startDevInfoService tries to start the fresh run of the package and start
// the service to send device info.
func startDevInfoService(ctx context.Context, d adb.Device, apk *APK) error {
	ctx = log.Enter(ctx, "startDevInfoService")
	var listening bool

	action := apk.ServiceActions.FindByName(sendDevInfoAction, sendDevInfoService)
	if action == nil {
		return log.Err(ctx, nil, "Service intent was not found")
	}

	// Try to start service.
	err := task.Retry(ctx, startServiceAttempts, 100*time.Millisecond,
		func(ctx context.Context) (bool, error) {
			log.I(ctx, "Attempt to start service: %s", sendDevInfoService)
			if err := d.StartService(ctx, *action); err != nil {
				return false, err
			}
			err := task.Retry(ctx, portListeningAttempts, time.Second, func(
				ctx context.Context) (bool, error) {
				var err error
				listening, err = devInfoPortListening(ctx, d)
				return listening, err
			})
			return listening, err
		})
	if listening {
		return nil
	}
	return log.Errf(ctx, err, "Start DevInfo service: Run out of attempts: %v",
		startServiceAttempts)
}

func fetchDeviceInfo(ctx context.Context, d adb.Device) error {
	apk, err := EnsureInstalled(ctx, d, device.UnknownABI)
	if err != nil {
		// The gapid.apk was not found. This can happen with partial builds used
		// for testing.
		// Don't return an error as this will prevent the device from being
		// registered and the device already comes with basic usable
		// information.
		log.W(ctx, "Couldn't find gapid.apk for device. Error: %v", err)
		return nil
	}

	if d.Instance().GetConfiguration().GetOS().GetAPIVersion() >= 29 {
		startSignal, startFunc := task.NewSignal()
		startFunc = task.Once(startFunc)
		crash.Go(func() {
			err := launchPerfettoProducerFromApk(ctx, d, startFunc)
			if err != nil {
				log.E(ctx, "[launchPerfettoProducerFromApk] error: %v", err)
			}

			// Ensure the start signal is fired on failure/immediate return.
			startFunc(ctx)
		})
		startSignal.Wait(ctx)
	}

	// Make sure the device is available to query device info, this is to prevent
	// Vulkan trace from happening at the same time than device info query.
	m := flock.Lock(d.Instance().GetSerial())
	defer m.Unlock()

	// Tries to start the device info service.
	if err := startDevInfoService(ctx, d, apk); err != nil {
		return log.Err(ctx, err, "Starting service")
	}

	sock, err := adb.ForwardAndConnect(ctx, d, sendDevInfoPort)
	if err != nil {
		return log.Err(ctx, err, "Connecting to service port")
	}

	defer sock.Close()

	data, err := ioutil.ReadAll(sock)
	if err != nil {
		return log.Err(ctx, err, "Reading data")
	}

	if err := proto.UnmarshalMerge(data, d.Instance()); err != nil {
		return log.Err(ctx, err, "Unmarshalling device Instance")
	}

	return nil
}

func preparePerfettoProducerLauncherFromApk(ctx context.Context, d adb.Device) error {
	packageName := PackageName(d.Instance().GetConfiguration().PreferredABI(nil))
	res, err := d.Shell("pm", "path", packageName).Call(ctx)
	if err != nil {
		return log.Errf(ctx, err, "Failed to query path to apk %v", packageName)
	}
	packagePath := strings.Split(res, ":")[1]
	d.Shell("rm", "-f", launcherPath).Call(ctx)
	if _, err := d.Shell("unzip", "-o", packagePath, "assets/"+perfettoProducerLauncher, "-p", ">", launcherPath).Call(ctx); err != nil {
		return log.Errf(ctx, err, "Failed to unzip %v from %v", perfettoProducerLauncher, packageName)
	}

	// Finally, make sure the binary is executable
	d.Shell("chmod", "a+x", launcherPath).Call(ctx)
	return nil
}

func launchPerfettoProducerFromApk(ctx context.Context, d adb.Device, startFunc task.Task) error {
	driver, err := d.GraphicsDriver(ctx)
	if err != nil {
		return err
	}

	// Extract the producer launcher from the APK.
	if err := preparePerfettoProducerLauncherFromApk(ctx, d); err != nil {
		return err
	}

	// Construct IO pipe, shell command outputs to stdout, GAPID reads from
	// reader for logging purpose.
	reader, stdout := io.Pipe()
	fail := make(chan error, 1)
	crash.Go(func() {
		buf := bufio.NewReader(reader)
		for {
			line, e := buf.ReadString('\n')
			// As long as there's output, consider the binary starting running.
			startFunc(ctx)
			switch e {
			default:
				log.E(ctx, "[launch producer] Read error %v", e)
				fail <- e
				return
			case io.EOF:
				fail <- nil
				return
			case nil:
				log.E(ctx, "[launch producer] %s", strings.TrimSuffix(adb.AnsiRegex.ReplaceAllString(line, ""), "\n"))
			}
		}
	})

	// Start the shell command to launch producer
	script := fmt.Sprintf(launcherScript, launcherPath)
	if driver.Package != "" {
		abi := d.Instance().GetConfiguration().PreferredABI(nil)
		script = "export LD_LIBRARY_PATH=\"" + driver.Path + "!/lib/" + abi.Name + "/\";" + script
	}
	process, err := d.Shell(script).
		Capture(stdout, stdout).
		Start(ctx)
	if err != nil {
		stdout.Close()
		return err
	}

	wait := make(chan error, 1)
	crash.Go(func() {
		wait <- process.Wait(ctx)
	})

	// Wait until either an error or EOF is read, or shell command exits.
	select {
	case err = <-fail:
		return err
	case err = <-wait:
		// Do nothing.
	}
	stdout.Close()
	if err != nil {
		return err
	}
	return <-fail
}


text:
<?php

/**
 * @file
 * Contains \Drupal\vcl\Plugin\Swap\.
 */

namespace Drupal\swaps\Plugin\Swap;

use Drupal\swaps\SwapBase;

/**
 * Provides a 'List Element' swap.
 *
 * @Swap(
 *   id = "swap_li",
 *   name = "List Element",
 *   container = true,
 *   description = @Translation("Add a element for the list."),
 * )
 */

class SwapListElement extends SwapBase {

  /**
   * Get all attributes of the swap and validate it.
   */
  public function processCallback($attrs, $text) {

    // Concatenate the classes
    if (array_key_exists('extraclass', $attrs)) {
      if (array_key_exists('class', $attrs)) {
        $attrs['class'] = $this->addClass($attrs['class'], $attrs['extraclass']);
      }else{
        $attrs['class'] = $attrs['extraclass'];
      }
    }
    $attrs['style'] = $this->getStyle($attrs);

    return $this->theme($attrs, $text);
  }

  /**
   * Create the string of the swap.
   */
  public function theme($attrs, $text) {

    // Define variables with HTML code of the attributes
    $id = (array_key_exists('id', $attrs)) ? ' id="' . $attrs['id'] . '" ' : "";
    $class = (array_key_exists('class', $attrs)) ? ' class="' . $attrs['class'] . '" ' : "";

    return '<li ' . $id . $class . $attrs['style'] . ' >' . $text . '</li>';
  }
}


text:
package se.itg.operation;

public class OperationPower extends Operation {

	public OperationPower() {
		super("^", 2);
	}

	public double execute(double x) {
		System.err.println("You can't do this, plzz stahwp " + toString());
		return 0;
	}

	public double execute(double x, double y) {
		return Math.pow(x, y);
	}
}


text:
package stroom.search.extraction;

import stroom.query.api.v2.Query;

public interface AnnotationsDecoratorFactory {

    ExtractionReceiver create(ExtractionReceiver receiver, Query query);
}


text:
    curl -s http://getcomposer.org/installer | php

### Install symfony skeleton

Light version

    composer.phar create-project rithis/symfony-skeleton <target-directory> dev-master

With Doctrine ORM

    composer.phar create-project rithis/symfony-skeleton <target-directory> dev-orm

With Doctrine ORM and Sonata Admin

    composer.phar create-project rithis/symfony-skeleton <target-directory> dev-admin

## Web Servers

Better way to start server is `php app/console server:run`, but sometimes web servers is necessary.

### apache

```
<VirtualHost *:80>
    DocumentRoot /var/www
    RewriteEngine On
    RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
    RewriteRule ^ /app_dev.php
</VirtualHost>
```

### nginx

```
server {
    root /var/www;

    location / {
        location ~ \.php$ {
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        }

        try_files $uri @backend;
    }

    location @backend {
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root/app_dev.php;
    }
}
```


text:
PROJECT_NAME := pvcd_cli
VERSION_NAME := 0.0.0
BUILD_DIR    := $(realpath $(PROJECT_NAME)_$(VERSION_NAME)/build)
DOC_DIR      := $(realpath $(PROJECT_NAME)_$(VERSION_NAME)/doc)
INSTALL_DIR  := $(realpath $(PROJECT_NAME)_$(VERSION_NAME)/install)
EXECUTABLE   := $(BUILD_DIR)/$(PROJECT_NAME)$(SUFFIX_EXE)

##########

CFLAGS   +=
LDFLAGS  +=

##########

ifneq ($(shell find . -maxdepth 0),.)
    $(error command "find" is incorrect, please add GNU's find command to PATH.)
endif

SOURCE_DIR  := src
H_FILES     := $(shell find $(SOURCE_DIR) -type f -name \*.h)
C_FILES     := $(shell find $(SOURCE_DIR) -type f -name \*.c)
C_O_FILES   := $(addprefix $(BUILD_DIR)/c/,$(C_FILES:.c=.o))
HPP_FILES   := $(shell find $(SOURCE_DIR) -type f -name \*.hpp)
CPP_FILES   := $(shell find $(SOURCE_DIR) -type f -name \*.cpp)
CPP_O_FILES := $(addprefix $(BUILD_DIR)/cpp/,$(CPP_FILES:.cpp=.o))

#### RULES ####

.PHONY: all install clean

all: $(EXECUTABLE)

$(EXECUTABLE): $(C_O_FILES) $(CPP_O_FILES)
	mkdir -p "$(BUILD_DIR)"
	g++ -o "$(EXECUTABLE)" $(C_O_FILES) $(CPP_O_FILES) $(LDFLAGS)

$(BUILD_DIR)/c/%.o: %.c $(H_FILES)
	mkdir -p $(@D)
	gcc -std=gnu99 -c $(CFLAGS) -o $@ $<

$(BUILD_DIR)/cpp/%.o: %.cpp $(HPP_FILES) $(H_FILES)
	mkdir -p $(@D)
	g++ -std=gnu++11 -c $(CFLAGS) -o $@ $<

install:
	install -d "$(INSTALL_DIR)/bin"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_db$(SUFFIX_EXE)"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_detect$(SUFFIX_EXE)"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_localMatches$(SUFFIX_EXE)"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_partitionImage$(SUFFIX_EXE)"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_search$(SUFFIX_EXE)"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_mergeLocalToGlobal$(SUFFIX_EXE)"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_mergeNN$(SUFFIX_EXE)"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_evaluate$(SUFFIX_EXE)"
	install "$(EXECUTABLE)" "$(INSTALL_DIR)/bin/pvcd_view$(SUFFIX_EXE)"

clean:
	rm -rf "$(BUILD_DIR)"


text:
// <copyright file="ExceptionExtensions.cs" company="TEAM Palow">
// Copyright (c) TEAM Palow. All rights reserved.
// </copyright>

using System;
using System.Collections.Generic;
using System.Text;

namespace Palow.Library.Extensions
{
    /// <summary>
    /// Extensions for the Exception class.
    /// </summary>
    public static class ExceptionExtensions
    {
        /// <summary>
        /// Get's the exception text from an exception object.
        /// </summary>
        /// <param name="ex">The exception object.</param>
        /// <returns>Exception as string.</returns>
        public static string GetExceptionText(this Exception ex)
        {
            if (ex != null)
            {
                return ex.ToString();
            }
            else
            {
                return "Exception is null.";
            }
        }
    }
}


text:
package com.microrisc.simply.iqrf.dpa.v21x.devices;

import com.microrisc.simply.DeviceInterface;
import com.microrisc.simply.DeviceInterfaceMethodId;
import com.microrisc.simply.di_services.GenericAsyncCallable;
import com.microrisc.simply.di_services.MethodIdTransformer;
import com.microrisc.simply.iqrf.dpa.v21x.di_services.DPA_StandardServices;
import com.microrisc.simply.iqrf.types.VoidType;
import java.util.UUID;

/**
 * DPA EEEPROM Device Interface.
 *

 * IMPORTANT NOTE:

 * Every method returns {@code NULL}, if an error has occurred during processing
 * of this method.
 *
 * @author Michal Konopa
 */
@DeviceInterface
public interface EEEPROM
extends DPA_StandardServices, GenericAsyncCallable, MethodIdTransformer {
    /**
     * Identifiers of this device interface's methods.
     */
    enum MethodID implements DeviceInterfaceMethodId {
        READ,
        WRITE
    }

    // ASYNCHRONOUS METHODS

    /**
     * Sends method call request for reading from peripheral.
     * @param blockNumber number of (zero based) block to read from
     * @param length length of the data to read (in bytes), must be equal to the block size
     * @return unique identifier of sent request
     */
    UUID async_read(int blockNumber, int length);

    /**
     * Sends method call request for writing to peripheral.
     * @param blockNumber number of (zero based) block to write the data into
     * @param data actual data to be written to the memory, its length must be
     *             equal to the block size
     * @return unique identifier of sent request
     */
    UUID async_write(int blockNumber, short[] data);

    // SYNCHRONOUS WRAPPERS

    /**
     * Synchronous wrapper for {@link #async_read(int, int) async_read} method.
     * @param blockNumber number of (zero based) block to read from
     * @param length length of the data to read (in bytes), must be equal to the block size
     * @return read data
     */
    short[] read(int blockNumber, int length);

    /**
     * Synchronous wrapper for {@link #async_write(int, short[])  async_write} method.
     * @param blockNumber number of (zero based) block to write the data into
     * @param data actual data to be written to the memory, its length must be
     *             equal to the block size
     * @return {@code VoidType} object, if method call has processed allright
     */
    VoidType write(int blockNumber, short[] data);
}


text:
import * as Icons from './assets/icons';
export { Icons };
export * from './components/Autocomplete';
export * from './components/Button';
export * from './components/TextButton';
export * from './components/Card';
export * from './components/Checkbox';
export * from './components/CheckboxGroup';
export * from './components/RadioButtonGroup';
export * from './components/Counter';
export * from './components/CounterBadge';
export * from './components/MobileDrawer';
export * from './components/Divider';
export * from './components/Grid';
export * from './components/Input';
export * from './components/OverlappingCard';
export * from './components/StatesButton';
export * from './components/StripCard';
export * from './components/Tabs';
export * from './components/Text';
export * from './components/TextField';
export * from './components/ToggleSwitch';
export * from './components/Tooltip';
export * from './components/Pagination';
export * from './components/Ratings';
export * from './components/TPAComponentsConfig';
export * from './components/CalendarPopover';


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://java.sun.com/xml/ns/javaee"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">

    <alternatives>
        <class>it.mock.TimeServiceMock</class>
    </alternatives>
</beans>


text:
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser;

import android.content.Context;
import android.content.pm.PackageManager;

import com.google.android.gms.common.GoogleApiAvailability;

import org.chromium.base.ContextUtils;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.components.externalauth.ExternalAuthUtils;

import java.util.Locale;

/**
 * A utility class for querying information about Play Services Version.
 */
public class PlayServicesVersionInfo {
    /**
     * Returns info about the Google Play services setup for Chrome and the device.
     *
     * Contains the version number of the SDK Chrome was built with and the one for the installed
     * Play Services app. It also contains whether First Party APIs are available.
     */
    @CalledByNative
    public static String getGmsInfo() {
        Context context = ContextUtils.getApplicationContext();

        final long sdkVersion = GoogleApiAvailability.GOOGLE_PLAY_SERVICES_VERSION_CODE;
        final long installedGmsVersion = getApkVersionNumber(context);

        final String accessType;
        ExternalAuthUtils externalAuthUtils = ExternalAuthUtils.getInstance();
        if (externalAuthUtils.canUseFirstPartyGooglePlayServices()) {
            accessType = "1p";
        } else if (externalAuthUtils.canUseGooglePlayServices()) {
            accessType = "3p";
        } else {
            accessType = "none";
        }

        return String.format(Locale.US, "SDK=%s; Installed=%s; Access=%s", sdkVersion,
                installedGmsVersion, accessType);
    }

    /**
     *
     * @param context A Context with which to retrieve the PackageManager.
     * @return The version code for the Google Play Services installed on the device or 0 if the
     *         package is not found.
     */
    public static int getApkVersionNumber(Context context) {
        try {
            return context.getPackageManager()
                    .getPackageInfo(GoogleApiAvailability.GOOGLE_PLAY_SERVICES_PACKAGE, 0)
                    .versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return 0;
        }
    }
}


text:
<link rel="import" href="../../bower_components/polymer/polymer.html">

<dom-module id="view404-view">
  <template>

    Oops you hit a 404.
    Head back to home.

    <theme-manager></theme-manager>
  </template>

</dom-module>


text:
https://github.com/mfpiccolo/minitest-vcr

Please use: `gem minitest-vcr` from now on.


text:
@extends('voyager::master_metronic')

@section('page_title', __('voyager.generic.viewing').' '.$dataType->display_name_plural)

@section('content')
    @php
        foreach (explode(',', Illuminate\Support\Facades\DB::table('posts')->value('vip_users')) as $users) {
            $user_id[$users] = $users;
        }

        $arrayJsonData = [];
        $counter = 1;
        if(Illuminate\Support\Facades\Auth::user()->role_id != 5) {
            if($dataType->display_name_plural == 'Biens immobiliers') {
                foreach ($dataTypeContent as $data) {
                    if(!empty($_GET['client_id']) && (in_array($_GET['client_id'], explode(',', $data->vip_users)))) {
                        $reference =  'HIS-' . str_pad($data->id, 4, '0', STR_PAD_LEFT);
                        $arrayJsonData[] = [
                            'id'            => $data->id,
                            'reference'     => $reference,
                            'image'         => (!empty(json_decode($data->image)[0])) ? json_decode($data->image)[0] : 'posts/no_image.png',
                            'ann_type'      => ($data->ann_type == 0) ? 'Location' : 'Vente',
                            'category_id'   => Illuminate\Support\Facades\DB::table('categories')->where('id', '=', $data->category_id)->value('name'),
                            'title_fr'      => $data->title_fr,
                            'zip_code'      => $data->zip_code,
                            'town'          => $data->town,
                            'price'         => ($data->show_price == 1) ? $data->price . ' ' . Illuminate\Support\Facades\DB::table('admin_currency')->where('reference', '=', $data->сurrency)->value('value') : '',
                            'vip_users'     => $data->vip_users
                        ];
                    } elseif(empty($_GET['client_id'])) {
                        $reference =  'HIS-' . str_pad($data->id, 4, '0', STR_PAD_LEFT);
                        $arrayJsonData[] = [
                            'id'            => $data->id,
                            'reference'     => $reference,
                            'image'         => (!empty(json_decode($data->image)[0])) ? json_decode($data->image)[0] : 'posts/no_image.png',
                            'ann_type'      => ($data->ann_type == 0) ? 'Location' : 'Vente',
                            'category_id'   => Illuminate\Support\Facades\DB::table('categories')->where('id', '=', $data->category_id)->value('name'),
                            'title_fr'      => $data->title_fr,
                            'zip_code'      => $data->zip_code,
                            'town'          => $data->town,
                            'price'         => ($data->show_price == 1) ? $data->price . ' ' . Illuminate\Support\Facades\DB::table('admin_currency')->where('reference', '=', $data->сurrency)->value('value') : '',
                            'vip_users'     => $data->vip_users
                        ];
                    }
                }
            } elseif($dataType->display_name_plural == 'Clients') {
                foreach ($dataTypeContent->where('role_id', '=', 5) as $data) {
                    $arrayJsonData[] = [
                        'id'            => $data->id,
                        'number'        => $counter++,
                        'name'          => $data->name . ' ' . $data->last_name,
                        'email'         => $data->email,
                        'avatar'        => $data->avatar,
                        'created_at'    => $data->created_at->format('d.m.Y /  H:m'),
                    ];
                }
            } elseif($dataType->display_name_plural == 'Utilisateurs') {
                foreach ($dataTypeContent->where('role_id', '!=', 5)->where('role_id', '>=', Auth::user()->role_id) as $data) {
                    $arrayJsonData[] = [
                        'id'            => $data->id,
                        'number'        => $counter++,
                        'name'          => $data->name . ' ' . $data->last_name,
                        'email'         => $data->email,
                        'avatar'        => $data->avatar,
                        'created_at'    => $data->created_at->format('d.m.Y / H:m'),
                    ];
                }
            } else {
                foreach ($dataTypeContent as $data) {
                    foreach ($dataType->browseRows as $row) {
                        $data[$row->display_name] = $data->{$row->field};
                    }
                    $arrayJsonData[] = $data;
                }
            }
        } else {
            foreach (Illuminate\Support\Facades\DB::table('posts')->where('vip_users', 'rlike', '(^|,)' . array_search(Illuminate\Support\Facades\Auth::user()->id, $user_id) . '(,|$)')->get() as $data) {
                if($dataType->display_name_plural == 'Biens immobiliers') {
                    $reference =  'HIS-' . str_pad($data->id, 4, '0', STR_PAD_LEFT);
                    $arrayJsonData[] = [
                        'id'            => $data->id,
                        'reference'     => $reference,
                        'image'         => (!empty(json_decode($data->image)[0])) ? json_decode($data->image)[0] : 'posts/no_image.png',
                        'ann_type'      => ($data->ann_type == 0) ? 'Location' : 'Vente',
                        'category_id'   => Illuminate\Support\Facades\DB::table('categories')->where('id', '=', $data->category_id)->value('name'),
                        'title_fr'      => $data->title_fr,
                        'zip_code'      => $data->zip_code,
                        'town'          => $data->town,
                        'price'         => ($data->show_price == 1) ? $data->price . ' ' . Illuminate\Support\Facades\DB::table('admin_currency')->where('reference', '=', $data->сurrency)->value('value') : '',
                    ];
                }
            }
        }
    @endphp

                    @if(Auth::user()->role_id == 5)

                            Bonjour {{ Auth::user()->name }} {{ Auth::user()->last_name }}

Voici les objets que nous avons sélectionnés pour vous.

                    @endif

                                {{ $dataType->display_name_plural }}

                                            <input type="text" class="form-control m-input m-input--solid" placeholder="Rechercher..." id="m_form_search">

                            @if(Auth::user()->role_id != 5)

                                    slug.'.create') }}" class="btn btn-accent m-btn m-btn--custom m-btn--icon m-btn--air m-btn--pill">

{{--                                                {{ __('voyager.generic.add_new') }}--}}
                                                Nouveau

                            @endif

    {{-- Single delete modal --}}

                    <button type="button" class="close" data-dismiss="modal" aria-label="{{ __('voyager.generic.close') }}">×</button>

 {{ __('voyager.generic.delete_question') }} {{ strtolower($dataType->display_name_singular) }}?

                    <form action="{{ route('voyager.'.$dataType->slug.'.index') }}" id="delete_form" method="POST">
                        {{ method_field("DELETE") }}
                        {{ csrf_field() }}
                        <input type="submit" class="btn btn-danger pull-right delete-confirm"
                               value="{{ __('voyager.generic.delete_confirm') }} {{ strtolower($dataType->display_name_singular) }}">
                    </form>
                    <button type="button" class="btn btn-default pull-right" data-dismiss="modal">{{ __('voyager.generic.cancel') }}</button>

@stop

@section('javascript')

    {{----}}
@stop


text:
package sorm.test.types

import org.scalatest.FunSuite
import org.scalatest.matchers.ShouldMatchers
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

import sorm._
import sorm.test.MultiInstanceSuite

@RunWith(classOf[JUnitRunner])
class RangeSupportSuite extends FunSuite with ShouldMatchers with MultiInstanceSuite {

  import RangeSupportSuite._

  def entities =  Set() + Entity[A]()
  instancesAndIds foreach { case (db, dbId) =>

    val a1 = db.save(A( 2 to 4 ))
    val a2 = db.save(A( 9 to 1 ))

    test(dbId + " - saved entities are correct"){
      db.fetchById[A](a1.id).a should equal (2 to 4)
      db.fetchById[A](a2.id).a should equal (9 to 1)
    }
    test(dbId + " - equality filter"){
      db.query[A]
        .whereEqual("a", 2 to 4)
        .fetch()
        .map(_.id)
        .should(
          have size(1) and
          contain(a1.id)
        )
    }
    test(dbId + " - 0 to 0 range"){
      val a = db.save(A(0 to 0))
      db.fetchById[A](a.id).a should equal (0 to 0)
    }

  }
}
object RangeSupportSuite {

  case class A
    ( a : Range )

}


text:
function Header(calendar, options) {
	var t = this;

	// exports
	t.render = render;
	t.destroy = destroy;
	t.updateTitle = updateTitle;
	t.activateButton = activateButton;
	t.deactivateButton = deactivateButton;
	t.disableButton = disableButton;
	t.enableButton = enableButton;

	// locals
	var element = $([]);
	var tm;

	function render() {
		tm = options.theme ? 'ui' : 'fc';
		var sections = options.header;
		if (sections) {
			element = $("
")
				.append($("
")
					.append($("")
						.append(renderSection(sections.left)))
					.append($("")
						.append(renderSection(sections.center)))
					.append($("")
						.append(renderSection(sections.right))));
			return element;
		}
	}

	function destroy() {
		element.remove();
	}

	function renderSection(buttonStr) {
		if (buttonStr) {
			var tr = $("
");
			$.each(buttonStr.split(' '), function(i) {
				if (i > 0) {
					tr.append("	");
				}
				var prevButton;
				$.each(this.split(','), function(j, buttonName) {
					if (buttonName == 'title') {
						tr.append("

	");
						if (prevButton) {
							prevButton.addClass(tm + '-corner-right');
						}
						prevButton = null;
					}else{
						var buttonClick;
						if (calendar[buttonName]) {
							buttonClick = calendar[buttonName]; // calendar method
						}
						else if (fcViews[buttonName]) {
							buttonClick = function() {
								button.removeClass(tm + '-state-hover'); // forget why
								calendar.changeView(buttonName);
							};
						}
						if (buttonClick) {
							if (prevButton) {
								prevButton.addClass(tm + '-no-right');
							}
							var button;
							var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null;
							var text = smartProperty(options.buttonText, buttonName);
							if (icon) {
								button = $("
" +
									"
");
							}
							else if (text) {
								button = $("
" +
									"" + text + "
");
							}
							if (button) {
								button
									.click(function() {
										if (!button.hasClass(tm + '-state-disabled')) {
											buttonClick();
										}
									})
									.mousedown(function() {
										button
											.not('.' + tm + '-state-active')
											.not('.' + tm + '-state-disabled')
											.addClass(tm + '-state-down');
									})
									.mouseup(function() {
										button.removeClass(tm + '-state-down');
									})
									.hover(
										function() {
											button
												.not('.' + tm + '-state-active')
												.not('.' + tm + '-state-disabled')
												.addClass(tm + '-state-hover');
										},
										function() {
											button
												.removeClass(tm + '-state-hover')
												.removeClass(tm + '-state-down');
										}
									)
									.appendTo($("").appendTo(tr));
								if (prevButton) {
									prevButton.addClass(tm + '-no-right');
								}else{
									button.addClass(tm + '-corner-left');
								}
								prevButton = button;
							}
						}
					}
				});
				if (prevButton) {
					prevButton.addClass(tm + '-corner-right');
				}
			});
			return $("
").append(tr);
		}
	}

	function updateTitle(html) {
		element.find('h2.fc-header-title')
			.html(html);
	}

	function activateButton(buttonName) {
		element.find('div.fc-button-' + buttonName)
			.addClass(tm + '-state-active');
	}

	function deactivateButton(buttonName) {
		element.find('div.fc-button-' + buttonName)
			.removeClass(tm + '-state-active');
	}

	function disableButton(buttonName) {
		element.find('div.fc-button-' + buttonName)
			.addClass(tm + '-state-disabled');
	}

	function enableButton(buttonName) {
		element.find('div.fc-button-' + buttonName)
			.removeClass(tm + '-state-disabled');
	}

}


text:
package org.rfcx.guardian.guardian.audio.capture;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import org.rfcx.guardian.guardian.RfcxGuardian;
import org.rfcx.guardian.utility.audio.RfcxAudioUtils;
import org.rfcx.guardian.utility.datetime.DateTimeUtils;
import org.rfcx.guardian.utility.misc.FileUtils;
import org.rfcx.guardian.utility.rfcx.RfcxLog;

public class AudioCaptureService extends Service {

	private static final String SERVICE_NAME = "AudioCapture";

	private static final String logTag = RfcxLog.generateLogTag(RfcxGuardian.APP_ROLE, "AudioCaptureService");

	private RfcxGuardian app;

	private boolean runFlag = false;
	private AudioCaptureSvc audioCaptureSvc;

	private int audioCycleDuration = 0;
	private int audioSampleRate = 0;

	private long innerLoopIterationDuration = 0;
	private static final int innerLoopIterationCount = 4;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		this.audioCaptureSvc = new AudioCaptureSvc();
		app = (RfcxGuardian) getApplication();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		super.onStartCommand(intent, flags, startId);
		Log.v(logTag, "Starting service: "+logTag);
		this.runFlag = true;
		app.rfcxServiceHandler.setRunState(SERVICE_NAME, true);
		try {
			this.audioCaptureSvc.start();
		} catch (IllegalThreadStateException e) {
			RfcxLog.logExc(logTag, e);
		}
		return START_NOT_STICKY;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		this.runFlag = false;
		app.rfcxServiceHandler.setRunState(SERVICE_NAME, false);
		this.audioCaptureSvc.interrupt();
		this.audioCaptureSvc = null;
	}

	private class AudioCaptureSvc extends Thread {

		public AudioCaptureSvc() {
			super("AudioCaptureService-AudioCaptureSvc");
		}

		@Override
		public void run() {
			AudioCaptureService audioCaptureService = AudioCaptureService.this;

			app = (RfcxGuardian) getApplication();
			Context context = app.getApplicationContext();

			app.rfcxServiceHandler.reportAsActive(SERVICE_NAME);

			app.audioCaptureUtils.queueCaptureTimeStamp = new long[] { 0, 0 };

			String captureDir = RfcxAudioUtils.captureDir(context);
			FileUtils.deleteDirectoryContents(captureDir);

			AudioCaptureWavRecorder wavRecorder = null;

			long captureTimeStamp = 0; // timestamp at beginning of capture loop

			while (audioCaptureService.runFlag) {

				try {

					boolean isCaptureAllowed = app.audioCaptureUtils.isAudioCaptureAllowed(true);

					if (confirmOrSetAudioCaptureParameters() && isCaptureAllowed) {

						// in this case, we are starting the audio capture from a stopped/pre-initialized state
						captureTimeStamp = System.currentTimeMillis();
						wavRecorder = AudioCaptureUtils.initializeWavRecorder(captureDir, captureTimeStamp, audioSampleRate);
						wavRecorder.startRecorder();

					} else if (wavRecorder != null) {
						// in this case, we assume that the state has changed and capture is no longer allowed...
						// ...but there is a capture in progress, so we take a snapshot and halt the recorder.
						captureTimeStamp = 0;
						wavRecorder.haltRecording();
						wavRecorder = null;
						Log.i(logTag, "Stopping audio capture.");
					}

					// queueing the last capture file for encoding, if there is one
					if (app.audioCaptureUtils.updateCaptureQueue(captureTimeStamp, audioSampleRate)) {
						app.rfcxServiceHandler.triggerIntentServiceImmediately("AudioQueueEncode");
					}

					// If capture is not allowed, we extend the capture cycle duration by a factor of AudioCaptureUtils.inReducedCaptureModeExtendCaptureCycleByFactorOf
					int currInnerLoopIterationCount = isCaptureAllowed ? innerLoopIterationCount : (AudioCaptureUtils.inReducedCaptureModeExtendCaptureCycleByFactorOf * innerLoopIterationCount);
					// This ensures that the service registers as active more frequently than the capture loop duration
					for (int innerLoopIteration = 0; innerLoopIteration < currInnerLoopIterationCount; innerLoopIteration++) {
						app.rfcxServiceHandler.reportAsActive(SERVICE_NAME);
						Thread.sleep(innerLoopIterationDuration);
					}

					// Triggering creation of a metadata snapshot.
					// This is not directly related to audio capture, but putting it here ensures that snapshots will...
					// ...continue to be taken, whether or not CheckIns are actually being sent or whether audio is being captured.
					app.rfcxServiceHandler.triggerIntentServiceImmediately("ApiCheckInMetaSnapshot");

				} catch (Exception e) {
					RfcxLog.logExc(logTag, e);
					app.rfcxServiceHandler.setRunState(SERVICE_NAME, false);
					audioCaptureService.runFlag = false;
				}
			}

			app.rfcxServiceHandler.setRunState(SERVICE_NAME, false);
			audioCaptureService.runFlag = false;

			Log.v(logTag, "Stopping service: "+logTag);

		}
	}

	private boolean confirmOrSetAudioCaptureParameters() {

		if (app != null) {

			int prefsAudioSampleRate = app.rfcxPrefs.getPrefAsInt("audio_sample_rate");
			int prefsAudioCycleDuration = app.rfcxPrefs.getPrefAsInt("audio_cycle_duration");

			if (	(this.audioSampleRate != prefsAudioSampleRate)
				||	(this.audioCycleDuration != prefsAudioCycleDuration)
				) {

				this.audioSampleRate = prefsAudioSampleRate;
				this.audioCycleDuration = prefsAudioCycleDuration;
				innerLoopIterationDuration = (long) Math.round( (prefsAudioCycleDuration * 1000) / innerLoopIterationCount );

				Log.d(logTag, "Audio Capture Params: " + prefsAudioCycleDuration + " seconds, " + prefsAudioSampleRate + " Hz");
			}

		} else {
			return false;
		}

		return true;
	}

}


text:
<!DOCTYPE html>

    <title>My Test From</title>
    <base href="http://www.baidu.com" target="_blank">
    <link rel="stylesheet" type="text/css" href="../css/headstyle.css">

    <meta http-equiv="refresh" content="30"></meta>

    <form action="" method="">
        UserName: <input type="text" name="firstname">

 Password: <input type="password" name="password">

        <input type="radio" name="sex" value="male"> Male

        <input type="radio" name="sex" value="female"> Famale

        <input type="checkbox" name="vehicle" value="Bike"> Bick

        <input type="checkbox" name="vehicle" value="Car"> Car

        <input type="submit" name="button" value="Submit">

        <select name="cars">
                <option value="volvo">Volvo</option>
                <option value="saab" selected>Saab</opttion>
                <option value="fiat">Fiat</option>
                <option value="audi">Audi</option>
            </select>

        <textarea rows="10" cols="30">
                文本框
            </textarea>

        <fieldset>
            <legend>Personality Information</legend>
            UserName: <input type="text" name="firstname">

 Password: <input type="password" name="password">

            <input type="radio" name="sex" value="male"> Male

            <input type="radio" name="sex" value="female"> Famale

            <input type="checkbox" name="vehicle" value="Bike"> Bick

            <input type="checkbox" name="vehicle" value="Car"> Car
        </fieldset>
    </form>


text:
<?php

namespace GraphQLGen\Generator\Writer\Namespaced;

use GraphQLGen\Generator\FragmentGenerators\FragmentGeneratorInterface;
use GraphQLGen\Generator\Writer\Namespaced\Classes\DTO;
use GraphQLGen\Generator\Writer\Namespaced\Classes\ObjectType;
use GraphQLGen\Generator\Writer\Namespaced\Classes\Resolver;
use GraphQLGen\Generator\Writer\Namespaced\Classes\ResolverFactory;
use GraphQLGen\Generator\Writer\Namespaced\Classes\TypeStore;

class ClassesFactory {
    /**
     * @param FragmentGeneratorInterface $fragmentGenerator
     * @param bool $skipResolver
     * @return ObjectType
     */
	public function createObjectTypeClassWithFragmentGenerator($fragmentGenerator, $skipResolver) {
		$generatorClass = new ObjectType($skipResolver);
		$generatorClass->setClassName($fragmentGenerator->getName() . ClassComposer::TYPE_DEFINITION_CLASS_NAME_SUFFIX);
		$generatorClass->setFragmentGenerator($fragmentGenerator);

		return $generatorClass;
	}

	/**
	 * @param FragmentGeneratorInterface $fragmentGenerator
	 * @return Resolver
	 */
	public function createResolverClassWithFragmentGenerator($fragmentGenerator) {
		$resolverClass = new Resolver();
		$resolverClass->setClassName($fragmentGenerator->getName() . ClassComposer::RESOLVER_CLASS_NAME_SUFFIX);
		$resolverClass->setFragmentGenerator($fragmentGenerator);

		return $resolverClass;
	}

	/**
	 * @return TypeStore
	 */
	public function createTypeStoreClass() {
		$typeStoreClass = new TypeStore();
		$typeStoreClass->setClassName(ClassComposer::TYPE_STORE_CLASS_NAME);

		return $typeStoreClass;
	}

	/**
	 * @return ClassStubFile
	 */
	public function createStubFile() {
		$stubFile = new ClassStubFile();

		return $stubFile;
	}

    /**
     * @param bool $skipResolver
     * @return ClassComposer
     */
	public function createClassComposer($skipResolver) {
		$classComposer = new ClassComposer($this, $skipResolver);

		return $classComposer;
	}

	/**
	 * @return ClassesWriter
	 */
	public function createClassesWriter() {
		$classesWriter = new ClassesWriter($this);

		return $classesWriter;
	}

	/**
	 * @return ClassMapper
	 */
	public function createClassMapper() {
		$classMapper = new ClassMapper();

		return $classMapper;
	}

	/**
	 * @param FragmentGeneratorInterface $fragmentGenerator
	 * @return DTO
	 */
	public function createDTOClassWithFragmentGenerator($fragmentGenerator) {
		$dtoClass = new DTO();
		$dtoClass->setClassName($fragmentGenerator->getName() . ClassComposer::DTO_CLASS_NAME_SUFFIX);
		$dtoClass->setFragmentGenerator($fragmentGenerator);

		return $dtoClass;
	}

	/**
	 * @return ResolverFactory
	 */
	public function createResolverFactoryClass() {
		$resolverFactoryClass = new ResolverFactory();
		$resolverFactoryClass->setClassName(ClassComposer::RESOLVER_FACTORY);

		return $resolverFactoryClass;
  }

	/**
	 * @param FragmentGeneratorInterface $fragmentGenerator
	 * @return DTO
	 */
	public function createTraitDTOClassWithFragmentGenerator($fragmentGenerator) {
		$dtoClass = new DTO();
		$dtoClass->setClassName($fragmentGenerator->getName() . ClassComposer::INTERFACE_TRAIT_SUFFIX);
		$dtoClass->setFragmentGenerator($fragmentGenerator);

		return $dtoClass;
	}

}


text:
import { revive } from 'vs/base/common/marshalling';
import { UriDto } from 'vs/base/common/types';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { IFileService } from 'vs/platform/files/common/files';
import { ILogService } from 'vs/platform/log/common/log';
import { IStateService } from 'vs/platform/state/node/state';
import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity';
import { IUserDataProfilesService, UserDataProfilesService as BaseUserDataProfilesService, StoredUserDataProfile, StoredProfileAssociations } from 'vs/platform/userDataProfile/common/userDataProfile';

export class UserDataProfilesService extends BaseUserDataProfilesService implements IUserDataProfilesService {

	constructor(
		@IStateService private readonly stateService: IStateService,
		@IUriIdentityService uriIdentityService: IUriIdentityService,
		@IEnvironmentService environmentService: IEnvironmentService,
		@IFileService fileService: IFileService,
		@ILogService logService: ILogService,
	) {
		super(environmentService, fileService, uriIdentityService, logService);
	}

	protected override getStoredProfiles(): StoredUserDataProfile[] {
		return revive(this.stateService.getItem<UriDto<StoredUserDataProfile>[]>(UserDataProfilesService.PROFILES_KEY, []));
	}

	protected override getStoredProfileAssociations(): StoredProfileAssociations {
		return revive(this.stateService.getItem<UriDto<StoredProfileAssociations>>(UserDataProfilesService.PROFILE_ASSOCIATIONS_KEY, {}));
	}

}


text:
class CreateMcPayloadStagerInstances < ActiveRecord::Migration
  #
  # CONSTANTS
  #
  # Name of the table being created
  TABLE_NAME = :mc_payload_stager_instances

  #
  # Instance Methods
  #

  # Drop {TABLE_NAME}.
  #
  # @return [void]
  def down
    drop_table TABLE_NAME
  end

  # Create {TABLE_NAME}.
  #
  # @return [void]
  def up
    create_table TABLE_NAME do |t|
      t.text :description,
             null: false
      t.string :name,
               null: false
      t.boolean :privileged,
                null: false

      #
      # References
      #

      t.references :handler,
                   null: false
      t.references :payload_stager_class,
                   null: false
    end

    change_table TABLE_NAME do |t|
      t.index :handler_id,
              unique: false
      t.index :payload_stager_class_id,
              unique: true
    end
  end
end


text: converts JSON to YAML


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">

<title>org.archive.io.arc package</title>

Contains html form login and basic and digest credentials
used by Heritrix logging into sites.

To watch credentials running, enable logging setting the following
logging level for FetchHttp class:
org.archive.crawler.fetcher.FetchHTTP.level = FINE


text:
package com.jiwhiz.config;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author Yuan Ji
 */
public class TestUtils {

    public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        return mapper.writeValueAsBytes(object);
    }

    public static Date parseDate(String dateString) throws Exception{
        String format = "yyyy-MM-dd";
        return new SimpleDateFormat(format).parse(dateString);
    }
}


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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/layout_toolbar"/>
    <android.support.v7.widget.CardView

        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        app:cardCornerRadius="1dp"
        app:cardElevation="8dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#FF8C00"
            android:orientation="horizontal">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:layout_weight="1"
                    android:elevation="10dp"
                    android:gravity="center"
                    android:text="应到人数"
                    android:textSize="20sp"

                    />

                <TextView
                    android:id="@+id/number_course"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="32dp"
                    android:layout_weight="1"
                    android:elevation="10dp"
                    android:gravity="center"
                    android:shadowColor="#ff0000ff"
                    android:shadowDx="5"
                    android:shadowDy="5"
                    android:shadowRadius="10"
                    android:text="0"
                    android:textSize="30sp" />

            </LinearLayout>

            <View
                android:layout_width="1dp"
                android:layout_height="120dp"
                android:layout_marginTop="12dp"
                android:layout_weight="0"
                android:background="@color/cardview_dark_background"
                android:gravity="center">

            </View>

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:gravity="center"
                android:orientation="vertical">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:layout_weight="1"
                    android:elevation="10dp"
                    android:gravity="center"
                    android:text="实到人数"
                    android:textSize="20sp" />

                <TextView
                    android:id="@+id/number_people"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="32dp"
                    android:layout_weight="1"
                    android:elevation="10dp"
                    android:gravity="center"
                    android:shadowColor="#ff0000ff"
                    android:shadowDx="5"
                    android:shadowDy="5"
                    android:shadowRadius="10"
                    android:text="0"
                    android:textSize="30sp" />
            </LinearLayout>

        </LinearLayout>

    </android.support.v7.widget.CardView>

    <com.amap.api.maps2d.MapView
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="150dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FF0000"
        android:orientation="vertical">

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="30dp"
            app:cardBackgroundColor="#FF0000"
            app:cardCornerRadius="1dp"
            app:cardElevation="8dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center"
                android:orientation="horizontal">

                <View
                    android:layout_width="80dp"
                    android:layout_height="1dp"
                    android:background="#000000"></View>

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="   未 签 到 学 生   " />

                <View
                    android:layout_width="80dp"
                    android:layout_height="1dp"
                    android:background="#000000"></View>

            </LinearLayout>

        </android.support.v7.widget.CardView>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/list_callinfo"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </android.support.v7.widget.RecyclerView>

    </LinearLayout>

</LinearLayout>


text:
// This file is automatically generated.

package adila.db;

/*
 * Samsung Galaxy Young
 *
 * DEVICE: royss
 * MODEL: GT-S6310T
 */
final class royss_gt2ds6310t {
    public static final String DATA = "Samsung|Galaxy Young|";
}