text:
require 'spec_helper'

describe Ridley::CookbookResource do
  let(:client) { double('client', connection: double('connection')) }

  subject { described_class.new(client) }

  describe "ClassMethods" do
    subject { described_class }
    let(:server_url) { "https://api.opscode.com/organizations/vialstudios" }
    let(:client_name) { "reset" }
    let(:client_key) { fixtures_path.join("reset.pem") }

    let(:client) do
      Ridley.new(
        server_url: server_url,
        client_name: client_name,
        client_key: client_key
      )
    end

    describe "::all" do
      subject { described_class.all(client) }

      before(:each) do
        stub_request(:get, File.join(server_url, "cookbooks")).
          to_return(status: 200, body: {
            "ant" => {
              "url" => "https://api.opscode.com/organizations/vialstudios/cookbooks/ant",
              "versions" => [
                {
                  "url" => "https://api.opscode.com/organizations/vialstudios/cookbooks/ant/0.10.1",
                  "version" => "0.10.1"
                }
              ]
            },
            "apache2" => {
              "url" => "https://api.opscode.com/organizations/vialstudios/cookbooks/apache2",
              "versions" => [
                {
                  "url" => "https://api.opscode.com/organizations/vialstudios/cookbooks/apache2/1.4.0",
                  "version" => "1.4.0"
                }
              ]
            }
          }
        )
      end

      it "returns a Hash" do
        subject.should be_a(Hash)
      end

      it "contains a key for each cookbook" do
        subject.should include("ant")
        subject.should include("apache2")
      end

      it "contains an array of versions for each cookbook" do
        subject["ant"].should be_a(Array)
        subject["ant"].should have(1).item
        subject["ant"].should include("0.10.1")
        subject["apache2"].should be_a(Array)
        subject["apache2"].should have(1).item
        subject["apache2"].should include("1.4.0")
      end
    end

    describe "::delete" do
      let(:name) { "ant" }
      let(:version) { "1.0.0" }

      it "sends a DELETE to the cookbook version URL" do
        stub_request(:delete, File.join(server_url, "cookbooks", name, version)).
          to_return(status: 200, body: {})

        described_class.delete(client, name, version)
      end

      context "when :purge is true" do
        it "appends ?purge=true to the end of the URL" do
          stub_request(:delete, File.join(server_url, "cookbooks", name, "#{version}?purge=true")).
            to_return(status: 200, body: {})

          described_class.delete(client, name, version, purge: true)
        end
      end
    end

    describe "::delete_all" do
      let(:name) { "ant" }
      let(:versions) { ["1.0.0", "1.2.0", "2.0.0"] }
      let(:options) { Hash.new }

      subject { described_class }

      it "deletes each version of the cookbook" do
        subject.should_receive(:versions).with(client, name).and_return(versions)

        versions.each do |version|
          subject.should_receive(:delete).with(client, name, version, options)
        end

        subject.delete_all(client, name, options)
      end
    end

    describe "::latest_version" do
      let(:name) { "ant" }
      subject { described_class }

      before(:each) do
        subject.should_receive(:versions).with(client, name).and_return(versions)
      end

      context "when the cookbook has no versions" do
        let(:versions) { Array.new }

        it "returns nil" do
          subject.latest_version(client, name).should be_nil
        end
      end

      context "when the cookbook has versions" do
        let(:versions) do
          [ "1.0.0", "1.2.0", "3.0.0", "1.4.1" ]
        end

        it "returns nil" do
          subject.latest_version(client, name).should eql("3.0.0")
        end
      end
    end

    describe "::versions" do
      let(:cookbook) { "artifact" }
      subject { described_class.versions(client, cookbook) }

      before(:each) do
        stub_request(:get, File.join(server_url, "cookbooks", cookbook)).
          to_return(status: 200, body: {
            cookbook => {
              "versions" => [
                {
                  "url" => "https://api.opscode.com/organizations/ridley/cookbooks/artifact/1.0.0",
                  "version" => "1.0.0"
                },
                {
                  "url" => "https://api.opscode.com/organizations/ridley/cookbooks/artifact/1.1.0",
                  "version" => "1.1.0"
                },
                {
                  "url" => "https://api.opscode.com/organizations/ridley/cookbooks/artifact/1.2.0",
                  "version" => "1.2.0"
                }
              ],
              "url" => "https://api.opscode.com/organizations/ridley/cookbooks/artifact"}
            }
          )
      end

      it "returns an array" do
        subject.should be_a(Array)
      end

      it "contains a version string for each cookbook version available" do
        subject.should have(3).versions
        subject.should include("1.0.0")
        subject.should include("1.1.0")
        subject.should include("1.2.0")
      end
    end

    describe "::upload" do
      pending
    end

    describe "::update" do
      pending
    end
  end

  describe "#download" do
    it "downloads each file" do
      subject.stub(:manifest) do
        {
          resources: [],
          providers: [],
          recipes: [
            {
              checksum: "aa3505d3eb8ce328ea84a4333df05b07",
              name: "default.rb",
              path: "recipes/default.rb",
              specificity: "default",
              url: "https://chef.lax1.riotgames.com/organizations/reset/cookbooks/ohai/1.0.2/files/aa3505d3eb8ce328ea84a4333df05b07"
            }
          ],
          definitions: [],
          libraries: [],
          attributes: [],
          files: [
            {
              checksum: "85bc3bb921efade3f2566a668ab4b639",
              name: "README",
              path: "files/default/plugins/README",
              specificity: "plugins",
              url: "https://chef.lax1.riotgames.com/organizations/reset/cookbooks/ohai/1.0.2/files/85bc3bb921efade3f2566a668ab4b639"
            }
          ],
          templates: [],
          root_files: []
        }
      end

      subject.should_receive(:download_file).with(:recipes, "recipes/default.rb", anything)
      subject.should_receive(:download_file).with(:files, "files/default/plugins/README", anything)

      subject.download
    end
  end

  describe "#download_file" do
    let(:destination) { tmp_path.join('fake.file').to_s }

    before(:each) do
      subject.stub(:root_files) { [ { path: 'metadata.rb', url: "http://test.it/file" } ] }
    end

    it "downloads the file from the file's url" do
      client.connection.should_receive(:stream).with("http://test.it/file", destination)

      subject.download_file(:root_file, "metadata.rb", destination)
    end

    context "when given an unknown filetype" do
      it "raises an UnknownCookbookFileType error" do
        expect {
          subject.download_file(:not_existant, "default.rb", destination)
        }.to raise_error(Ridley::Errors::UnknownCookbookFileType)
      end
    end

    context "when the cookbook doesn't have the specified file" do
      before(:each) do
        subject.stub(:root_files) { Array.new }
      end

      it "returns nil" do
        subject.download_file(:root_file, "metadata.rb", destination).should be_nil
      end
    end
  end

  describe "#manifest" do
    it "returns a Hash" do
      subject.manifest.should be_a(Hash)
    end

    it "has a key for each item in FILE_TYPES" do
      subject.manifest.keys.should =~ described_class::FILE_TYPES
    end

    it "contains an empty array for each key" do
      subject.manifest.should each be_a(Array)
      subject.manifest.values.should each be_empty
    end
  end
end


text:
require 'factory_girl'

FactoryGirl.define do
  sequence :url do |n|
    "url_#{n}"
  end
  factory :site do
    url
  end
end

redpajama_set_name: RedPajamaGithub


text:
"""Tool for manipulating naclports packages in python.

This tool can be used to for working with naclports packages.
It can also be incorporated into other tools that need to
work with packages (e.g. 'update_mirror.py' uses it to iterate
through all packages and mirror them on Google Cloud Storage).
"""
import optparse
import os
import posixpath
import shlex
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import urlparse

import sha1check

MIRROR_URL = 'http://storage.googleapis.com/naclports/mirror'
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
NACLPORTS_ROOT = os.path.dirname(SCRIPT_DIR)
PORTS_DIR = os.path.join(NACLPORTS_ROOT, "ports")
OUT_DIR = os.path.join(NACLPORTS_ROOT, 'out')
STAMP_DIR = os.path.join(OUT_DIR, 'stamp')
BUILD_ROOT = os.path.join(OUT_DIR, 'build')
ARCHIVE_ROOT = os.path.join(OUT_DIR, 'tarballs')
PACKAGES_ROOT = os.path.join(OUT_DIR, 'packages')
PUBLISH_ROOT = os.path.join(OUT_DIR, 'publish')
PAYLOAD_DIR = 'payload/'

NACL_SDK_ROOT = os.environ.get('NACL_SDK_ROOT')

if NACL_SDK_ROOT:
  sys.path.append(os.path.join(NACL_SDK_ROOT, 'tools'))

arch_to_pkgarch = {
  'x86_64': 'x86-64',
  'i686': 'i686',
  'arm': 'arm',
  'pnacl': 'pnacl',
}

# Inverse of arch_to_pkgarch
pkgarch_to_arch = {v:k for k, v in arch_to_pkgarch.items()}

# TODO(sbc): use this code to replace the bash logic in build_tools/common.sh

class Error(Exception):
  pass

class DisabledError(Error):
  pass

def FormatTimeDelta(delta):
  rtn = ''
  if delta > 60:
    mins = delta / 60
    rtn += '%dm' % mins
    delta -= mins * 60

  if delta:
    rtn += '%.0fs' % delta
  return rtn

def WriteStamp(filename, contents=''):
  """Write a file with the give filename and contents."""
  dirname = os.path.dirname(filename)
  if not os.path.isdir(dirname):
    os.makedirs(dirname)
  Trace('stamp: %s' % filename)
  with open(filename, 'w') as f:
    f.write(contents)

def CheckStamp(filename, contents=None, timestamp=None):
  """Check that a given stamp file is up-to-date.

  Returns False is the file does not exists or is older
  that that given comparison file, or does not contain
  the given contents.

  Return True otherwise.
  """
  if not os.path.exists(filename):
    return False

  if contents is not None:
    with open(filename) as f:
      if f.read() != contents:
        return False

  return True

def Log(message):
  sys.stdout.write(str(message) + '\n')
  sys.stdout.flush()

def Trace(message):
  if Trace.verbose:
    Log(message)
Trace.verbose = False

def GetCurrentArch():
  arch = os.environ.get('NACL_ARCH')
  if not arch:
    if GetCurrentToolchain() == 'pnacl':
      return 'pnacl'
    else:
      return 'x86_64'
  return arch

def GetCurrentLibc():
  libc = GetCurrentToolchain()
  if libc == 'pnacl':
    libc = 'newlib'
  return libc

def GetCurrentToolchain():
  if os.environ.get('NACL_ARCH') == 'pnacl':
    return 'pnacl'
  return os.environ.get('TOOLCHAIN') or 'newlib'

def GetDebug():
  if os.environ.get('NACL_DEBUG') == '1':
    return 'debug'
  else:
    return 'release'

def GetToolchainRoot(toolchain=None, arch=None):
  """Returns the toolchain folder for a given NaCl toolchain."""
  import getos
  platform = getos.GetPlatform()
  if toolchain == 'pnacl':
    tc_dir = '%s_pnacl' % platform
  else:
    tc_arch = {
      'arm': 'arm',
      'i686': 'x86',
      'x86_64': 'x86'
    }[arch]
    tc_dir = '%s_%s_%s' % (platform, tc_arch, toolchain)
    tc_dir = os.path.join(tc_dir, '%s-nacl' % arch)

  return os.path.join(NACL_SDK_ROOT, 'toolchain', tc_dir)

def GetInstallRoot(toolchain, arch):
  """Returns the installation used by naclports within a given toolchain."""
  tc_root = GetToolchainRoot(toolchain, arch)
  if toolchain == 'pnacl':
    return os.path.join(tc_root, 'usr', 'local')
  else:
    return os.path.join(tc_root, 'usr')

def GetInstallStampRoot(toolchain, arch):
  tc_root = GetInstallRoot(toolchain, arch)
  return os.path.join(tc_root, 'var', 'lib', 'npkg')

def GetInstallStamp(package_name):
  root = GetInstallStampRoot(GetCurrentToolchain(), GetCurrentArch())
  return os.path.join(root, package_name)

def IsInstalled(package_name):
  stamp = GetInstallStamp(package_name)
  return CheckStamp(stamp)

class BinaryPackage(object):
  def __init__(self, filename):
    self.filename = filename
    if not os.path.exists(self.filename):
      raise Error('package not found: %s'% self.filename)
    basename, extension = os.path.splitext(os.path.basename(filename))
    basename = os.path.splitext(basename)[0]
    if extension != '.bz2':
      raise Error('invalid file extension: %s' % extension)
    if '_' not in basename:
      raise Error('package filename must contain underscores: %s' % basename)
    parts = basename.split('_')
    if len(parts) < 3 or len(parts) > 5:
      raise Error('invalid package filename: %s' % basename)
    if parts[-1] == 'debug':
      parts = parts[:-1]

    if parts[-1] in ('newlib', 'glibc', 'bionic'):
      self.toolchain = parts[-1]
      parts = parts[:-1]
    self.name, self.version, arch = parts[:3]
    if arch == 'pnacl':
      self.toolchain = 'pnacl'
    self.arch = pkgarch_to_arch[arch]

  def IsInstalled(self):
    GetInstallStamp(self.name)

  def InstallFile(self, filename, old_root, new_root):
    oldname = os.path.join(old_root, filename)
    if os.path.isdir(oldname):
      return

    if not filename.startswith(PAYLOAD_DIR):
      return

    newname = filename[len(PAYLOAD_DIR):]
    Trace('install: %s' % newname)

    newname = os.path.join(new_root, newname)
    dirname = os.path.dirname(newname)
    if not os.path.isdir(dirname):
      os.makedirs(dirname)
    os.rename(oldname, newname)

  def RelocateFile(self, filename, dest):
    # Only relocate files in the payload.
    if not filename.startswith(PAYLOAD_DIR):
      return

    # Only relocate certain file types.
    filename = filename[len(PAYLOAD_DIR):]
    modify = False

    # boost build scripts
    # TODO(sbc): move this to the boost package metadata
    if filename.startswith('build-1'):
      modify = True
    # pkg_config (.pc) files
    if filename.startswith('lib/pkgconfig'):
      modify = True
    # <foo>-config scripts that live in usr/bin
    if filename.startswith('bin') and filename.endswith('-config'):
      modify = True
    # libtool's .la files which can contain absolute paths to
    # dependencies.
    if filename.startswith('lib/') and filename.endswith('.la'):
      modify = True
    # headers can sometimes also contain absolute paths.
    if filename.startswith('include/') and filename.endswith('.h'):
      modify = True

    filename = os.path.join(dest, filename)
    if os.path.isdir(filename):
      return

    if modify:
      with open(filename) as f:
        data = f.read()
      with open(filename, 'r+') as f:
        f.write(data.replace('/naclports-dummydir', dest))

  def Install(self):
    """Install binary package into toolchain directory."""
    dest = GetInstallRoot(self.toolchain, self.arch)
    dest_tmp = os.path.join(dest, 'install_tmp')
    if os.path.exists(dest_tmp):
      shutil.rmtree(dest_tmp)

    Log("Installing '%s' [%s/%s]" % (self.name, self.arch, self.toolchain))
    os.makedirs(dest_tmp)

    try:
      with tarfile.open(self.filename) as t:
        names = [posixpath.normpath(name) for name in t.getnames()]
        if 'pkg_info' not in names:
          raise Error('package does not contain pkg_info file')
        for name in names:
          if name not in ('.', 'pkg_info', 'payload'):
            if not name.startswith(PAYLOAD_DIR):
              raise Error('invalid file in package: %s' % name)
        t.extractall(dest_tmp)

      for name in names:
        self.InstallFile(name, dest_tmp, dest)

      for name in names:
        self.RelocateFile(name, dest)

      with open(os.path.join(dest_tmp, 'pkg_info')) as f:
        pkg_info = f.read()
      WriteStamp(GetInstallStamp(self.name), pkg_info)
    finally:
      shutil.rmtree(dest_tmp)

class Package(object):
  """Representation of a single naclports package.

  Package objects correspond to folders on disk which
  contain a 'pkg_info' file.
  """
  VALID_KEYS = ('NAME', 'VERSION', 'URL', 'ARCHIVE_ROOT', 'LICENSE', 'DEPENDS',
                'MIN_SDK_VERSION', 'LIBC', 'ARCH', 'DISABLED_ARCH',
                'URL_FILENAME', 'BUILD_OS', 'SHA1', 'DISABLED')
  VALID_SUBDIRS = ('', 'ports', 'python_modules')

  def __init__(self, pkg_root):
    self.root = os.path.abspath(pkg_root)
    self.basename = os.path.basename(self.root)
    keys = []
    for key in Package.VALID_KEYS:
      setattr(self, key, None)
    self.DEPENDS = []
    self.info = None
    for subdir in Package.VALID_SUBDIRS:
        info = os.path.join(PORTS_DIR, subdir, self.basename, 'pkg_info')
        if os.path.exists(info):
          self.info = info
          break
    if self.info is None:
      raise Error('Invalid package folder: %s' % pkg_root)
    self.root = os.path.dirname(self.info)

    with open(self.info) as f:
      for i, line in enumerate(f):
        if line[0] == '#':
          continue
        key, value = self.ParsePkgInfoLine(line, i+1)
        keys.append(key)
        setattr(self, key, value)

    for required_key in ('NAME', 'VERSION'):
      if required_key not in keys:
        raise Error('%s: pkg_info missing required key: %s' %
                    (self.info, required_key))

    if '_' in self.NAME:
      raise Error('%s: package NAME cannot contain underscores' % self.info)
    if '_' in self.VERSION:
      raise Error('%s: package VERSION cannot contain underscores' % self.info)
    if self.NAME != os.path.basename(self.root):
      raise Error('%s: package NAME must match directory name' % self.info)
    if self.DISABLED_ARCH is not None and self.ARCH is not None:
      raise Error('%s: contains both ARCH and DISABLED_ARCH' % self.info)

  def __cmp__(self, other):
    return cmp(self.NAME, other.NAME)

  def ParsePkgInfoLine(self, line, line_no):
    if '=' not in line:
      raise Error('Invalid pkg_info line %d: %s' % (line_no, self.info))
    key, value = line.split('=', 1)
    key = key.strip()
    if key not in Package.VALID_KEYS:
      raise Error("Invalid key '%s' in pkg_info: %s" % (key, self.info))
    value = value.strip()
    if value[0] == '(':
      array_value = []
      if value[-1] != ')':
        raise Error('Error parsing %s: %s (%s)' % (self.info, key, value))
      value = value[1:-1]
      for single_value in value.split():
        array_value.append(single_value)
      value = array_value
    else:
      value = shlex.split(value)[0]
    return (key, value)

  def CheckDeps(self, valid_dependencies):
    for dep in self.DEPENDS:
      if dep not in valid_dependencies:
        Log('%s: Invalid dependency: %s' % (self.info, dep))
        return False
    return True

  def GetBasename(self):
    basename = os.path.splitext(self.GetArchiveFilename())[0]
    if basename.endswith('.tar'):
      basename = os.path.splitext(basename)[0]
    return basename

  def GetBuildLocation(self):
    package_dir = self.ARCHIVE_ROOT or '%s-%s' % (self.NAME, self.VERSION)
    return os.path.join(BUILD_ROOT, self.NAME, package_dir)

  def GetArchiveFilename(self):
    if self.URL_FILENAME:
      return self.URL_FILENAME

    if self.URL and '.git' not in self.URL:
      return os.path.basename(urlparse.urlparse(self.URL)[2])

    return None

  def DownloadLocation(self):
    archive = self.GetArchiveFilename()
    if not archive:
      return
    return os.path.join(ARCHIVE_ROOT, archive)

  def InstallDeps(self, verbose, force):
    for dep in self.DEPENDS:
      if not IsInstalled(dep):
        dep_dir = os.path.join(os.path.dirname(self.root), dep)
        dep = Package(dep_dir)
        try:
          dep.Install(verbose, True, force)
        except DisabledError as e:
          Log(str(e))

  def PackageFile(self):
    toolchain = GetCurrentToolchain()
    arch = GetCurrentArch()
    fullname = [os.path.join(PACKAGES_ROOT, self.NAME)]
    fullname.append(self.VERSION)
    fullname.append(arch_to_pkgarch[arch])
    if toolchain != arch: # for pnacl toolchain and arch are the same
      fullname.append(toolchain)
    if os.environ.get('NACL_DEBUG') == '1':
      fullname.append('debug')
    return '_'.join(fullname) + '.tar.bz2'

  def IsInstalled(self):
    return IsInstalled(self.NAME)

  def IsBuilt(self):
    return os.path.exists(self.PackageFile())

  def Install(self, verbose, build_deps, force=None):
    force_install = force in ('build', 'install', 'all')

    if not force_install and self.IsInstalled():
      Log("Already installed '%s' [%s/%s]" % (self.NAME, GetCurrentArch(),
          GetCurrentLibc()))
      return

    if not self.IsBuilt() or force:
      self.Build(verbose, build_deps, force)

    BinaryPackage(self.PackageFile()).Install()

  def Build(self, verbose, build_deps, force=None):
    self.CheckEnabled()

    if build_deps or force == 'all':
      self.InstallDeps(verbose, force)

    annotate = os.environ.get('NACLPORTS_ANNOTATE') == '1'
    arch = GetCurrentArch()
    libc = GetCurrentLibc()

    force_build = force in ('build', 'all')
    if not force_build and self.IsBuilt():
      Log("Already built '%s' [%s/%s]" % (self.NAME, arch, libc))
      return

    log_root = os.path.join(OUT_DIR, 'logs')
    if not os.path.isdir(log_root):
      os.makedirs(log_root)

    stdout = os.path.join(log_root, '%s.log' % self.NAME)
    if os.path.exists(stdout):
      os.remove(stdout)

    if verbose:
      prefix = '*** '
    else:
      prefix = ''
    Log("%sBuilding '%s' [%s/%s]" % (prefix, self.NAME, arch, libc))

    start = time.time()
    self.RunBuildSh(verbose, stdout)

    duration = FormatTimeDelta(time.time() - start)
    Log("Build complete '%s' [%s/%s] [took %s]"
        % (self.NAME, arch, libc, duration))

  def RunBuildSh(self, verbose, stdout, args=None):
    build_port = os.path.join(SCRIPT_DIR, 'build_port.sh')
    cmd = [build_port]
    if args is not None:
      cmd += args

    if verbose:
      rtn = subprocess.call(cmd, cwd=self.root)
      if rtn != 0:
        raise Error("Building %s: failed." % (self.NAME))
    else:
      with open(stdout, 'a+') as log_file:
        rtn = subprocess.call(cmd,
                              cwd=self.root,
                              stdout=log_file,
                              stderr=subprocess.STDOUT)
      if rtn != 0:
        with open(stdout) as log_file:
          sys.stdout.write(log_file.read())
        raise Error("Building '%s' failed." % (self.NAME))

  def Verify(self, verbose=False):
    """Download upstream source and verify hash."""
    archive = self.DownloadLocation()
    if not archive:
      Log("no archive: %s" % self.NAME)
      return True

    if self.SHA1 is None:
      Log("missing SHA1 attribute: %s" % self.info)
      return False

    self.Download()
    try:
      sha1check.VerifyHash(archive, self.SHA1)
      Log("verified: %s" % archive)
    except sha1check.Error as e:
      Log("verification failed: %s: %s" % (archive, str(e)))
      return False

    return True

  def Clean(self):
    pkg = self.PackageFile()
    Log('removing %s' % pkg)
    if os.path.exists(pkg):
      os.remove(pkg)

    stamp_dir = os.path.join(STAMP_DIR, self.NAME)
    Log('removing %s' % stamp_dir)
    if os.path.exists(stamp_dir):
      shutil.rmtree(stamp_dir)

  def Extract(self):
    self.ExtractInto(os.path.join(BUILD_ROOT, self.NAME))

  def ExtractInto(self, output_path):
    """Extract the package archive into the given location.

    This method assumes the package has already been downloaded.
    """
    archive = self.DownloadLocation()
    if not archive:
      return

    if not os.path.exists(output_path):
      os.makedirs(output_path)

    new_foldername = os.path.basename(self.GetBuildLocation())
    dest = os.path.join(output_path, new_foldername)
    if os.path.exists(dest):
      Trace('Already exists: %s' % dest)
      return

    tmp_output_path = tempfile.mkdtemp(dir=OUT_DIR)
    try:
      ext = os.path.splitext(archive)[1]
      if ext in ('.gz', '.tgz', '.bz2'):
        cmd = ['tar', 'xf', archive, '-C', tmp_output_path]
      elif ext in ('.zip',):
        cmd = ['unzip', '-q', '-d', tmp_output_path, archive]
      else:
        raise Error('unhandled extension: %s' % ext)
      Log("Extracting '%s'" % self.NAME)
      Trace(cmd)
      subprocess.check_call(cmd)
      src = os.path.join(tmp_output_path, new_foldername)
      os.rename(src, dest)
    finally:
      shutil.rmtree(tmp_output_path)

  def GetMirrorURL(self):
    return MIRROR_URL + '/' + self.GetArchiveFilename()

  def CheckEnabled(self):
    if self.LIBC is not None and self.LIBC != GetCurrentLibc():
      raise DisabledError('%s: cannot be built with %s.'
                          % (self.NAME, GetCurrentLibc()))

    if self.ARCH is not None:
      arch = GetCurrentArch()
      if arch not in self.ARCH:
        raise DisabledError('%s: disabled for current arch: %s.'
                            % (self.NAME, arch))

    if self.DISABLED_ARCH is not None:
      arch = GetCurrentArch()
      if arch in self.DISABLED_ARCH:
        raise DisabledError('%s: disabled for current arch: %s.'
                            % (self.NAME, arch))

    if self.BUILD_OS is not None:
      import getos
      if getos.GetPlatform() != self.BUILD_OS:
        raise DisabledError('%s: can only be built on %s.'
                            % (self.NAME, self.BUILD_OS))

  def Download(self, mirror=True):
    filename = self.DownloadLocation()
    if not filename or os.path.exists(filename):
      return
    if not os.path.exists(os.path.dirname(filename)):
      os.makedirs(os.path.dirname(filename))

    temp_filename = filename + '.partial'
    mirror_download_successfull = False
    curl_cmd = ['curl', '--fail', '--location', '--stderr', '-',
                '-o', temp_filename]
    if os.isatty(sys.stdout.fileno()):
      # Add --progress-bar but only if stdout is a TTY device.
      curl_cmd.append('--progress-bar')
    else:
      # otherwise suppress all status output, since curl always
      # assumes a TTY and writes \r and \b characters.
      curl_cmd.append('--silent')

    if mirror:
      try:
        mirror_url = self.GetMirrorURL()
        Log('Downloading: %s [%s]' % (mirror_url, temp_filename))
        subprocess.check_call(curl_cmd + [mirror_url])
        mirror_download_successfull = True
      except subprocess.CalledProcessError:
        pass

    if not mirror_download_successfull:
      Log('Downloading: %s [%s]' % (self.URL, temp_filename))
      subprocess.check_call(curl_cmd + [self.URL])

    os.rename(temp_filename, filename)

def PackageIterator(folders=None):
  """Iterator which yield a Package object for each
  naclport package."""
  if not folders:
    folders = [os.path.join(NACLPORTS_ROOT, 'ports')]

  for folder in folders:
    for root, dirs, files in os.walk(folder):
      if 'pkg_info' in files:
        yield Package(root)

def run_main(args):
  usage = "Usage: %prog [options] <command> [<package_dir>]"
  parser = optparse.OptionParser(description=__doc__, usage=usage)
  parser.add_option('-v', '--verbose', action='store_true',
                    help='Output extra information.')
  parser.add_option('-V', '--verbose-build', action='store_true',
                    help='Make the build itself version (e.g. pass V=1 to make')
  parser.add_option('--all', action='store_true',
                    help='Perform action on all known ports.')
  parser.add_option('-f', '--force', action='store_const', const='build',
                    dest='force', help='Force building specified targets, '
                    'even if timestamps would otherwise skip it.')
  parser.add_option('-F', '--force-all', action='store_const', const='all',
                    dest='force', help='Force building target and all '
                    'dependencies, even if timestamps would otherwise skip '
                    'them.')
  parser.add_option('--force-install', action='store_const', const='install',
                    dest='force', help='Force installing of ports')
  parser.add_option('--no-deps', dest='build_deps', action='store_false',
                    default=True,
                    help='Disable automatic building of dependencies.')
  parser.add_option('--ignore-disabled', action='store_true',
                    help='Ignore attempts to build disabled packages.\n'
                    'Normally attempts to build such packages will result\n'
                    'in an error being returned.')
  options, args = parser.parse_args(args)
  if not args:
    parser.error('You must specify a sub-command. See --help.')

  command = args[0]
  package_dirs = ['.']
  if len(args) > 1:
    if options.all:
      parser.error('Package name and --all cannot be specified together')
    package_dirs = args[1:]

  if not NACL_SDK_ROOT:
    raise Error('$NACL_SDK_ROOT not set')

  if not os.path.isdir(NACL_SDK_ROOT):
    raise Error('$NACL_SDK_ROOT does not exist: %s' % NACL_SDK_ROOT)

  verbose = options.verbose or os.environ.get('VERBOSE') == '1'
  Trace.verbose = verbose
  if options.verbose_build:
    os.environ['VERBOSE'] = '1'
  else:
    os.environ['VERBOSE'] = '0'
    os.environ['V'] = '0'

  def DoCmd(package):
    try:
      if command == 'download':
        package.Download()
      elif command == 'check':
        # Fact that we've got this far means the pkg_info
        # is basically valid.  This final check verifies the
        # dependencies are valid.
        package_names = [os.path.basename(p.root) for p in PackageIterator()]
        package.CheckDeps(package_names)
      elif command == 'enabled':
        package.CheckEnabled()
      elif command == 'verify':
        package.Verify()
      elif command == 'clean':
        package.Clean()
      elif command == 'build':
        package.Build(verbose, options.build_deps, options.force)
      elif command == 'install':
        package.Install(verbose, options.build_deps, options.force)
      else:
        parser.error("Unknown subcommand: '%s'\n"
                     "See --help for available commands." % command)
    except DisabledError as e:
      if options.ignore_disabled:
        Log('naclports: %s' % e)
      else:
        raise e

  def rmtree(path):
    Log('removing %s' % path)
    if os.path.exists(path):
      shutil.rmtree(path)

  if options.all:
    options.ignore_disabled = True
    if command == 'clean':
      rmtree(STAMP_DIR)
      rmtree(BUILD_ROOT)
      rmtree(PACKAGES_ROOT)
      rmtree(PUBLISH_ROOT)
      rmtree(GetInstallStampRoot(GetCurrentToolchain(), GetCurrentArch()))
      rmtree(GetInstallRoot(GetCurrentToolchain(), GetCurrentArch()))
    else:
      for p in PackageIterator():
        if not p.DISABLED:
          DoCmd(p)
  else:
    for package_dir in package_dirs:
      p = Package(package_dir)
      DoCmd(p)

def main(args):
  try:
    run_main(args)
  except Error as e:
    sys.stderr.write('naclports: %s\n' % e)
    return 1

  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))


text:
<?php

// include class.secure.php to protect this file and the whole CMS!
if (defined('WB_PATH')) {
    if (defined('LEPTON_VERSION')) include(WB_PATH.'/framework/class.secure.php');
} else {
    $oneback = "../";
    $root = $oneback;
    $level = 1;
    while (($level < 10) && (!file_exists($root.'/framework/class.secure.php'))) {
        $root .= $oneback;
        $level += 1;
    }
    if (file_exists($root.'/framework/class.secure.php')) {
        include($root.'/framework/class.secure.php');
    } else {
        trigger_error(sprintf("[ <b>%s</b> ] Can't include class.secure.php!",
                $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
    }
}
// end include class.secure.php

$module_directory = 'lib_markdown';
$module_name = 'libMarkdown';
$module_function = (defined('LEPTON_VERSION')) ? 'library' : 'snippet';
$module_version = '0.12';
$module_status = 'Stable';
$module_platform = '2.8';
$module_author = 'Ralf Hertsch - Berlin (Germany)';
$module_license = 'MIT License (MIT)';
$module_description = 'Library to convert Markdown formatted files to XHTML';
$module_home = 'https://addons.phpmanufaktur.de/de/addons/libmarkdown.php';
$module_guid = '295186D4-5D33-483D-A17C-3BA19333115C';

?>


text:
function onFormSubmit() {
  var filterService = document.getElementById('service').value;
  if (filterService.startsWith('0x')) {
    filterService = parseInt(filterService, 16);
  }

  log('Requesting Bluetooth Device...');
  navigator.bluetooth.requestDevice({filters:[{services:[ filterService ]}]})
  .then(device => {
    log('> Device Name:       ' + device.name);
    log('> Device InstanceID: ' + device.instanceID);
    log('> Device Paired:     ' + device.paired);
    log('> Device Class:      ' + device.deviceClass);
    log('> Device UUIDs:      ' + device.uuids.join('\n' + ' '.repeat(21)));
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}


text:
/*
 * ISP: MPI Dynamic Verification Tool
 *
 * File:        HashMap.h
 * Description: Implements a HashMap to store the MPI_Request objects
 * Contact:     isp-dev@cs.utah.edu
 */

#ifndef _HASHMAP_H
#define _HASHMAP_H

#include <mpi.h>
#include <string.h>
#include <stdlib.h>

#define HASH_SIZE    10

/*
 * This structure stores the mapping between an MPI-Request
 * and the corresponding Envelope and Request.
 */

typedef struct HashNode_t {
    struct HashNode_t   *next; /* MUST be first because of HashMap_Delete */
    int                 key;
    MPI_Request         *req;
    char                *env;
} HashNode;

typedef HashNode * HashNodep;

typedef HashNodep HashMap[HASH_SIZE];

/*
 * Initialize the HashMap.
 */
void HashMap_Init (HashMap *);
/*
 * Insert into the HashMap.
 */
void HashMap_Insert (HashMap *, int, MPI_Request *, char *);
/*
 * Search for a request in the HashMap.
 */
MPI_Request * HashMap_GetRequest (HashMap *, int);
/*
 * Search for a environment in the HashMap.
 */
char * HashMap_GetEnv (HashMap *, int);
/*
 * Delete from the HashMap.
 */
void HashMap_Delete (HashMap *, int);
/* Update the envelope of an entry */
void HashMap_UpdateEnv(HashMap*, int, char*);

void HashMap_Destroy(HashMap*);
#endif


text:
package edu.umd.cs.findbugs.ba.generic;

import junit.framework.TestCase;

/**
 * @author pugh
 */
public class GenericSignatureParserTest extends TestCase {

    public void test1() {
        GenericSignatureParser parser = new GenericSignatureParser(
                "(Lcom/sleepycat/persist/EntityJoin<TPK;TE;>.JoinForwardCursor<TV;>;)V");
        assertEquals(1, parser.getNumParameters());
    }

    public void test2() {
        GenericSignatureParser parser = new GenericSignatureParser("(Ljava/lang/String;^TE1;^TE2;^TE3;)V");
        assertEquals(1, parser.getNumParameters());
    }

}


text:
'use strict';
/**
 * @fileOverview EventEmitter.
 */

/**
 * Наделяет объект событийной моделью.
 * @constructor
 * @extend {EventEmitter}
 */
function EventEmitter() {
    this._event = null;
    this._events = this._events;
    this._maxListeners = this._maxListeners;
}

/**
 * Сообщение об ошибке попытки подписки некорректного обработчика.
 * @const
 * @type {String}
 */
EventEmitter.LISTENER_TYPE_ERROR = 'Listener must be a function or EventEmitter';

try {
    var EE = require('events').EventEmitter;
} catch (error) {
}

EventEmitter.prototype = new (EE || Object);
EventEmitter.prototype.constructor = EventEmitter;

/**
 * Количество обработчиков одного события по-умолчанию.
 * @static
 * @const
 * @default 10
 * @type {Number}
 */
EventEmitter.MAX_LISTENERS = 10;

/**
 * Имя события добавления нового обработчика.
 * @static
 * @const
 * @default 'newListener'
 * @type {String}
 */
EventEmitter.EVENT_NEW_LISTENER = 'newListener';

/**
 * Имя события добавления нового обработчика.
 * @static
 * @const
 * @default 'newListener'
 * @type {String}
 */
EventEmitter.EVENT_REMOVE_LISTENER = 'removeListener';

/**
 * Возвращает количество обработчиков определенного события.
 * @param {EventEmitter} emitter Объект {@link EventEmitter}.
 * @param {String} type Тип события.
 * @returns {number}
 */
EventEmitter.listenerCount = function (emitter, type) {
    var listeners = emitter._events && emitter._events[type];

    return listeners ? listeners.length : 0;
};

/**
 * Объект, в котором хранятся обработчики событий.
 * @type {Object}
 * @default null
 * @protected
 */
EventEmitter.prototype._events = null;

/**
 * Объект события.
 * @type {Event}
 * @default null
 * @protected
 */
EventEmitter.prototype._event = null;

/**
 * Максимальное количество обработчиков для одного события.
 * @type {Number}
 * @default 10
 * @private
 */
EventEmitter.prototype._maxListeners = EventEmitter.MAX_LISTENERS;

/**
 * Останавливает выполение обработчиков события.
 * @param {String|Number} [type] Если передан тип и он не соответствует типу выполняемого события,
 *                               выполнение не будет остановлено.
 * @example
 * var EventEmitter = require('EventEmitter');
 *
 * new EventEmitter()
 *   .on('event', function () {
 *      new EventEmitter().stopEmit(); // false
 *      this.stopEmit(); // true
 *   })
 *   .emit('event');
 * @returns {Boolean} Возвращает true, если выполнение обработчиков события было остановлено.
 */
EventEmitter.prototype.stopEmit = function (type) {
    var _event = this._event;

    if (_event && (!arguments.length || _event.type == type)) {
        return _event.stop = true;
    }

    return false;
};

/**
 * Заменяет данные события, если оно есть.
 * @param {...*} [args]
 * @example
 * new EventEmitter()
 *   .on('event', function (data) {
 *     data; // 'foo'
 *     this.updateEventData('bar');
 *   })
 *   .on('event', function (data) {
 *     data; // 'bar'
 *   })
 *   .emit('event', 'foo');
 */
EventEmitter.prototype.setEventData = function (args) {
    var length = arguments.length;
    var data = this._event && this._event.data;

    if (data) {
        data.length = length;

        while (length) {
            data[--length] = arguments[length];
        }
    }

    return this;
};

/**
 * Возвращает текущие данные события в виде массива.
 * @returns {Array|null}
 * @example
 * new EventEmitter()
 *   .on('event', function () {
 *     this.getEventData(); // ['foo', 'bar'];
 *   })
 *   .emit('event', 'foo', 'bar');
 */
EventEmitter.prototype.getEventData = function () {
    if (this._event) {
        var data = this._event.data;
        var length = data.length;
        var result = new Array(length);

        while (length) {
            result[--length] = data[length];
        }

        return result;
    } else {
        return null;
    }
};

/**
 * Возвращает текущий тип события.
 * @returns {String|Number|null}
 */
EventEmitter.prototype.getEventType = function () {
    return this._event && this._event.type;
};

/**
 * Устанавливает максимальное количество обработчиков одного события.
 * @param {Number} count Новое количество обработчиков.
 * @throws {Error} Бросает исключение при некорректном значении count.
 */
EventEmitter.prototype.setMaxListeners = function (count) {
    if (typeof count !== 'number' || count < 0 || isNaN(count)) {
        throw new Error('Count must be a positive number');
    }

    this._maxListeners = count;
};

/**
 * Устанавливает обработчик события.
 * @param {String} type Тип события.
 * @param {Function|EventEmitter} listener Обработчик события.
 * @param {Object} [context=this] Контекст выполнения обработчика.
 * @throws {Error} Бросает исключение, если listener имеет некорректный тип.
 * @returns {EventEmitter}
 */
EventEmitter.prototype.on = function (type, listener, context) {
    if (!isListener(listener)) {
        throw new Error(EventEmitter.LISTENER_TYPE_ERROR);
    }

    var _events = this._events || (this._events = {});
    var listeners = _events[type] || (_events[type] = new Array(0));

    if (_events.newListener) {
        this.emit('newListener', type, listener, context == null ? this : context);
    }

    listeners[listeners.length] = {
        type: type,
        callback: listener,
        context: context,
        isOnce: false
    };

    return this;
};

/**
 * То же, что и {@link EventEmitter#on}.
 * @param {String} type Тип события.
 * @param {Function|EventEmitter} listener Обработчик события.
 * @param {Object|null} [context] Контекст выполнения обработчика.
 * @function
 * @returns {EventEmitter}
 */
EventEmitter.prototype.addListener = EventEmitter.prototype.on;

/**
 * Устанавливает одноразовый обработчик события.
 * @param {String} type Тип события.
 * @param {Function|EventEmitter} listener Обработчик события.
 * @param {Object|null} [context=this] Контекст выполнения обработчика.
 * @returns {EventEmitter}
 * @example
 * new EventEmitter()
 *   .once('type', function () {
 *     // Обработчик выполнится только один раз
 *   })
 *   .emit('type')
 *   .emit('type');
 */
EventEmitter.prototype.once = function (type, listener, context) {
    this.on(type, listener, context);

    getLastListener(this, type).isOnce = true;

    return this;
};

/**
 * Удаляет обработчик события.
 * @param {String} type Тип события.
 * @param {Function|EventEmitter} listener Обработчик, который необходимо удалить.
 * @throws {Error} Бросает исключение, если listener имеет некорректный тип.
 * @returns {EventEmitter}
 */
EventEmitter.prototype.off = function (type, listener) {
    var _events = this._events;
    var listeners = _events && _events[type];

    if (!listeners) {
        return this;
    }

    if (isListener(listener)) {
        if (removeListener(listeners, listener)) {
            if (_events.removeListener) {
                this.emit('removeListener', type, listener);
            }

            if (listeners.length === 0) {
                _events[type] = null;
            }
        }
    } else {
        throw new Error(EventEmitter.LISTENER_TYPE_ERROR);
    }

    return this;
};

/**
 * То же, что и {@link EventEmitter#off}.
 * @param {String} type Тип события.
 * @param {Function|EventEmitter} [listener] Обработчик, который необходимо удалить.
 * @function
 * @returns {EventEmitter}
 */
EventEmitter.prototype.removeListener = EventEmitter.prototype.off;

/**
 * Если был передан тип события, метод работает аналогично {@link EventEmitter#off}, иначе удаляет все обработчики для всех событий.
 * @param {String} [type] Тип события.
 * @returns {EventEmitter}
 */
EventEmitter.prototype.removeAllListeners = function (type) {
    var _events = this._events;
    var key;
    var hasNotType = arguments.length === 0;

    if (!_events) {
        return this;
    }

    if (_events.removeListener) {
        if (hasNotType) {
            for (key in _events) {
                if (key !== 'removeListener' && _events.hasOwnProperty(key)) {
                    removeAllListeners(this, key, _events);
                }
            }

            removeAllListeners(this, 'removeListener', _events);
        } else {
            removeAllListeners(this, type, _events);

            return this;
        }
    }

    if (hasNotType) {
        this._events = {};
    } else {
        _events[type] = null;
    }

    return this;
};

/**
 * Возвращает массив обработчиков события.
 * @param {String|Number} [type] Тип события.
 * @returns {Array} Массив объектов события.
 */
EventEmitter.prototype.listeners = function (type) {
    var _events = this._events;
    var listeners = _events && _events[type];

    if (listeners) {
        var length = listeners.length;
        var res = new Array(length);

        while (length) {
            res[--length] = listeners[length].callback;
        }

        return res;
    } else {
        return new Array(0);
    }
};

/**
 * Генерирует событие.
 * @param {String} type Тип события.
 * @param {...*} [args] Аргументы, которые будут переданы в обработчик события.
 * @returns {Boolean} Вернет true, если был отработан хотя бы один обработчик события.
 * @example
 * new EventEmitter()
 *   .on('error', function (reason) {
 *     throw reason; // 'foo'
 *   })
 *   .emit('error', 'foo');
 * @throws {Error} Бросает исключение, если генерируется событие error и на него не подписан ни один обработчик.
 */
EventEmitter.prototype.emit = function (type, args) {
    var events = this._events && this._events[type];
    var length = events && events.length;
    var index;
    var data;
    var listener;
    var callback;
    var listeners;
    var currentEvent;
    var _event;

    if (!length) {
        if (type === 'error') {
            throw (args instanceof Error) ? args : new Error('Uncaught, unspecified "error" event.');
        } else {
            return false;
        }
    }

    index = arguments.length && arguments.length - 1;
    data  = new Array(index);

    while (index) {
        data[index - 1] = arguments[index--];
    }

    index = length;
    listeners = new Array(length);
    currentEvent = this._event;
    _event = this._event = {
        type: type,
        data: data,
        stop: false
    };

    while (index) {
        listeners[--index] = events[index];
    }

    while (index < length) {
        listener = listeners[index++];
        callback = listener.callback;

        if (listener.isOnce === true) {
            this.off(type, callback);
        }

        if (isFunction(callback)) {
            call(callback, listener.context == null ? this : listener.context, _event.data);
        } else {
            emit(callback, listener.type, _event.data);
        }

        if (_event.stop) {
            break;
        }
    }

    this._event = currentEvent;

    return true;
};

/**
 * Назначает делегирование события на другой экземпляр {@link EventEmitter}.
 * @param {EventEmitter} emitter Объект, на который необходимо делегировать событие type.
 * @param {String} type Тип события, которое должно делегироваться.
 * @param {String} [alias=type] Тип события, которое должно возникать на объекте emitter.
 * @example
 * var emitter1 = new EventEmitter();
 * var emitter2 = new EventEmitter();
 *
 * emitter2
 *   .on('some', function (result) {
 *     // result is 'foo'
 *   });
 *
 * emitter1
 *   .delegate(emitter2, 'event', 'some')
 *   .emit('event', 'foo');
 *
 * @returns {EventEmitter}
 */
EventEmitter.prototype.delegate = function (emitter, type, alias) {
    this.on(type, emitter);

    if (!(alias == null || alias === type)) {
        getLastListener(this, type).type = alias;
    }

    return this;
};

/**
 * Останавливает делегирование события на другой экземпляр {@link EventEmitter}.
 * @param {EventEmitter} emitter Объект, на который необходимо прекратить делегирование.
 * @param {String} type Тип события.
 * @returns {EventEmitter}
 */
EventEmitter.prototype.unDelegate = function (emitter, type) {
    return this.off(type, emitter);
};

/**
 * Exports: {@link EventEmitter}
 * @exports EventEmitter
 */
module.exports = EventEmitter;

function call(listener, context, data) {
    switch (data.length) {
        case 0:
            listener.call(context);
            break;
        case 1:
            listener.call(context, data[0]);
            break;
        case 2:
            listener.call(context, data[0], data[1]);
            break;
        case 3:
            listener.call(context, data[0], data[1], data[2]);
            break;
        default:
            listener.apply(context, data);
    }
}

function emit(emitter, type, data) {
    switch (data.length) {
        case 0:
            emitter.emit(type);
            break;
        case 1:
            emitter.emit(type, data[0]);
            break;
        case 2:
            emitter.emit(type, data[0], data[1]);
            break;
        case 3:
            emitter.emit(type, data[0], data[1], data[2]);
            break;
        default:
            var a = new Array(1);
            a[0] = type;
            emitter.emit.apply(emitter, a.concat(data));
    }
}

function removeListener(listeners, listener) {
    var length = listeners.length;
    var index = length;

    while (index--) {
        if (listeners[index].callback === listener) {
            break;
        }
    }

    if (index < 0) {
        return false;
    }

    if (length === 1) {
        listeners.length = 0;
    } else {
        listeners.splice(index, 1);
    }

    return true;
}

function removeAllListeners(emitter, type, events) {
    var listeners = events[type];

    if (!listeners) {
        return;
    }

    var index = listeners.length;

    while (index--) {
        emitter.emit('removeListener', type, listeners.pop().callback);
    }

    events[type] = null;
}

function isFunction(fnc) {
    return typeof fnc === 'function';
}

function isListener(listener) {
    return listener && (isFunction(listener) || isFunction(listener.emit));
}

function getLastListener(emitter, type) {
    var listeners = emitter._events[type];

    return listeners[listeners.length - 1];
}


text:
package com.aquafx_project.controls.skin.styles.styler;

import javafx.scene.control.Slider;

import com.aquafx_project.controls.skin.styles.ControlSizeVariant;

/**
 * The SliderStyler with fluent API to change the default style of a Slider.
 *
 * @author claudinezillmann
 *
 */
public class SliderStyler extends Styler<Slider> {

    /**
     * Creates a new Instance of SliderStyler. This has to be the first invocation on SliderStyler.
     *
     * @return The SliderStyler.
     */
    public static SliderStyler create() {
        return new SliderStyler();
    }

    @Override public SliderStyler setSizeVariant(ControlSizeVariant sizeVariant) {
        return (SliderStyler) super.setSizeVariant(sizeVariant);
    }
}


text:
use learn_english;

DROP TABLE IF EXISTS `sentences`;
CREATE TABLE `sentences` (
   `id` bigint(20) NOT NULL AUTO_INCREMENT,
   `sentence` varchar(1024) DEFAULT NULL,
   PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


text:
<?php

namespace IronCore;

/**
 * JsonException
 *
 * The JSON_Exception class represents an failures of decoding json strings.
 *
 * @package IronCore
 * @author Tino Ehrich (tino@bigpun.me)
 */
class JSONException extends \Exception
{
    public $error = null;
    public $error_code = JSON_ERROR_NONE;

    public function __construct($error_code)
    {
        $this->error_code = $error_code;
        switch ($error_code)
        {
            case JSON_ERROR_DEPTH:
                $this->error = 'Maximum stack depth exceeded.';
                break;
            case JSON_ERROR_CTRL_CHAR:
                $this->error = "Unexpected control characted found.";
                break;
            case JSON_ERROR_SYNTAX:
                $this->error = "Syntax error, malformed JSON";
                break;
            default:
                $this->error = $error_code;
                break;

        }
        parent::__construct();
    }

    public function __toString()
    {
        return $this->error;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- pressed-->
    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/bootstrap_default_pressed" />
            <stroke android:width="1dp" android:color="@color/bootstrap_default_pressed_border" />
            <corners android:radius="@dimen/rounded_corner_bootstrap" />
        </shape>
    </item>

    <!-- disabled-->
    <item android:state_enabled="false">
        <shape>
            <solid android:color="@color/bootstrap_default_disabled" />
            <stroke android:width="1dp" android:color="@color/bootstrap_default_disabled_border" />
            <corners android:radius="@dimen/rounded_corner_bootstrap" />
        </shape>
    </item>

    <!-- default-->
    <item>
        <shape>
            <solid android:color="@color/bootstrap_default" />
            <stroke android:width="1dp" android:color="@color/bootstrap_default_border" />
            <corners android:radius="@dimen/rounded_corner_bootstrap" />
        </shape>
    </item>

</selector>


text:
package net.derohimat.bakingapp.di.component;

import net.derohimat.bakingapp.di.ActivityScope;
import net.derohimat.bakingapp.features.recipelist.RecipeListActivity;
import net.derohimat.bakingapp.features.steps.StepsDetailActivity;
import net.derohimat.bakingapp.features.widgets.WidgetConfigurationActivity;

import dagger.Component;

@ActivityScope
@Component(dependencies = ApplicationComponent.class)
public interface ActivityComponent extends ApplicationComponent {

    void inject(RecipeListActivity activity);
    void inject(StepsDetailActivity activity);

    void inject(WidgetConfigurationActivity activity);
}