text:
#ifndef _PCACHE_H_

typedef struct PgHdr PgHdr;
typedef struct PCache PCache;

/*
** Every page in the cache is controlled by an instance of the following
** structure.
*/
struct PgHdr {
  sqlite3_pcache_page *pPage;    /* Pcache object page handle */
  void *pData;                   /* Page data */
  void *pExtra;                  /* Extra content */
  PCache *pCache;                /* PRIVATE: Cache that owns this page */
  PgHdr *pDirty;                 /* Transient list of dirty sorted by pgno */
  Pager *pPager;                 /* The pager this page is part of */
  Pgno pgno;                     /* Page number for this page */
#ifdef SQLITE_CHECK_PAGES
  u32 pageHash;                  /* Hash of page content */
#endif
  u16 flags;                     /* PGHDR flags defined below */

  /**********************************************************************
  ** Elements above, except pCache, are public.  All that follow are
  ** private to pcache.c and should not be accessed by other modules.
  ** pCache is grouped with the public elements for efficiency.
  */
  i16 nRef;                      /* Number of users of this page */
  PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
  PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
                          /* NB: pDirtyNext and pDirtyPrev are undefined if the
                          ** PgHdr object is not dirty */
};

/* Bit values for PgHdr.flags */
#define PGHDR_CLEAN           0x001  /* Page not on the PCache.pDirty list */
#define PGHDR_DIRTY           0x002  /* Page is on the PCache.pDirty list */
#define PGHDR_WRITEABLE       0x004  /* Journaled and ready to modify */
#define PGHDR_NEED_SYNC       0x008  /* Fsync the rollback journal before
                                     ** writing this page to the database */
#define PGHDR_DONT_WRITE      0x010  /* Do not write content to disk */
#define PGHDR_MMAP            0x020  /* This is an mmap page object */

#define PGHDR_WAL_APPEND      0x040  /* Appended to wal file */

/* Initialize and shutdown the page cache subsystem */
int sqlite3PcacheInitialize(void);
void sqlite3PcacheShutdown(void);

/* Page cache buffer management:
** These routines implement SQLITE_CONFIG_PAGECACHE.
*/
void sqlite3PCacheBufferSetup(void *, int sz, int n);

/* Create a new pager cache.
** Under memory stress, invoke xStress to try to make pages clean.
** Only clean and unpinned pages can be reclaimed.
*/
int sqlite3PcacheOpen(
  int szPage,                    /* Size of every page */
  int szExtra,                   /* Extra space associated with each page */
  int bPurgeable,                /* True if pages are on backing store */
  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  void *pStress,                 /* Argument to xStress */
  PCache *pToInit                /* Preallocated space for the PCache */
);

/* Modify the page-size after the cache has been created. */
int sqlite3PcacheSetPageSize(PCache *, int);

/* Return the size in bytes of a PCache object.  Used to preallocate
** storage space.
*/
int sqlite3PcacheSize(void);

/* One release per successful fetch.  Page is pinned until released.
** Reference counted.
*/
sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
void sqlite3PcacheRelease(PgHdr*);

void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
void sqlite3PcacheClearWritable(PCache*);

/* Change a page number.  Used by incr-vacuum. */
void sqlite3PcacheMove(PgHdr*, Pgno);

/* Remove all pages with pgno>x.  Reset the cache if x==0 */
void sqlite3PcacheTruncate(PCache*, Pgno x);

/* Get a list of all dirty pages in the cache, sorted by page number */
PgHdr *sqlite3PcacheDirtyList(PCache*);

/* Reset and close the cache object */
void sqlite3PcacheClose(PCache*);

/* Clear flags from pages of the page cache */
void sqlite3PcacheClearSyncFlags(PCache *);

/* Discard the contents of the cache */
void sqlite3PcacheClear(PCache*);

/* Return the total number of outstanding page references */
int sqlite3PcacheRefCount(PCache*);

/* Increment the reference count of an existing page */
void sqlite3PcacheRef(PgHdr*);

int sqlite3PcachePageRefcount(PgHdr*);

/* Return the total number of pages stored in the cache */
int sqlite3PcachePagecount(PCache*);

#if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
/* Iterate through all dirty pages currently stored in the cache. This
** interface is only available if SQLITE_CHECK_PAGES is defined when the
** library is built.
*/
void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
#endif

#if defined(SQLITE_DEBUG)
/* Check invariants on a PgHdr object */
int sqlite3PcachePageSanity(PgHdr*);
#endif

/* Set and get the suggested cache-size for the specified pager-cache.
**
** If no global maximum is configured, then the system attempts to limit
** the total number of pages cached by purgeable pager-caches to the sum
** of the suggested cache-sizes.
*/
void sqlite3PcacheSetCachesize(PCache *, int);
#ifdef SQLITE_TEST
int sqlite3PcacheGetCachesize(PCache *);
#endif

/* Set or get the suggested spill-size for the specified pager-cache.
**
** The spill-size is the minimum number of pages in cache before the cache
** will attempt to spill dirty pages by calling xStress.
*/
int sqlite3PcacheSetSpillsize(PCache *, int);

/* Free up as much memory as possible from the page cache */
void sqlite3PcacheShrink(PCache*);

#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
/* Try to return memory used by the pcache module to the main memory heap */
int sqlite3PcacheReleaseMemory(int);
#endif

#ifdef SQLITE_TEST
void sqlite3PcacheStats(int*,int*,int*,int*);
#endif

void sqlite3PCacheSetDefault(void);

/* Return the header size */
int sqlite3HeaderSizePcache(void);
int sqlite3HeaderSizePcache1(void);

/* Number of dirty pages as a percentage of the configured cache size */
int sqlite3PCachePercentDirty(PCache*);

#ifdef SQLITE_DIRECT_OVERFLOW_READ
int sqlite3PCacheIsDirty(PCache *pCache);
#endif

#endif /* _PCACHE_H_ */


text:
xpProOption(shapelib DBG)
set(VER 1.2.10)
set(REPO github.com/asapnet/shapelib)
set(FORK github.com/smanders/shapelib)
set(PRO_SHAPELIB
  NAME shapelib
  WEB "shapelib" http://shapelib.maptools.org/ "Shapefile C Library website"
  LICENSE "open" http://shapelib.maptools.org/license.html "MIT Style -or- LGPL"
  DESC "reading, writing, updating ESRI Shapefiles"
  REPO "repo" https://${FORK} "forked shapelib repo on github"
  VER ${VER}
  GIT_ORIGIN https://${FORK}.git
  GIT_UPSTREAM https://${REPO}.git
  GIT_TAG xp${VER} # what to 'git checkout'
  GIT_REF v${VER} # create patch from this tag to 'git checkout'
  DLURL http://download.osgeo.org/shapelib/shapelib-${VER}.tar.gz
  DLMD5 4d96bd926167193d27bf14d56e2d484e
  PATCH ${PATCH_DIR}/shapelib.patch
  DIFF https://${FORK}/compare/
  )
########################################
function(build_shapelib)
  if(NOT (XP_DEFAULT OR XP_PRO_SHAPELIB))
    return()
  endif()
  xpGetArgValue(${PRO_SHAPELIB} ARG NAME VALUE NAME)
  xpGetArgValue(${PRO_SHAPELIB} ARG VER VALUE VER)
  set(XP_CONFIGURE
    -DCMAKE_INSTALL_INCLUDEDIR=include/${NAME}_${VER}
    -DCMAKE_INSTALL_LIBDIR=lib
    -DXP_INSTALL_CMAKEDIR=share/cmake/tgt-${NAME}
    -DXP_NAMESPACE:STRING=xpro
    )
  set(TARGETS_FILE tgt-${NAME}/${NAME}-targets.cmake)
  set(LIBRARIES xpro::shape)
  configure_file(${PRO_DIR}/use/template-lib-tgt.cmake
    ${STAGE_DIR}/share/cmake/usexp-${NAME}-config.cmake
    @ONLY NEWLINE_STYLE LF
    )
  xpCmakeBuild(${NAME} "" "${XP_CONFIGURE}")
endfunction()

redpajama_set_name: RedPajamaGithub


text:
// Copyright 2008 Google Inc. All Rights Reserved.

/* 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.
 */

package com.google.documents.core.treesync;

/**
 * Merge conflict.
 *
 * @author tancred (Tancred Lindholm)
 */

// This class needs to gather useful information about conflicts
// Currently, this has not yet stabilized, but it seems we want at least
// - Nodes involved in the conflict
// - Some high-level categorization (colliding insert, colliding update, etc...)
// - Whether reason is user or programming error (e.g. inconsistent node types)

public class ConflictException extends Exception {

  /**
   * Create conflict with unspecified reason.
   */
  public ConflictException() {
    this(null);
  }

  /**
   * Create conflict with specified reason.
   * @param reason Reason for conflict, suitable for logging (but not the end user).
   */
  public ConflictException(String reason) {
    super("Merging conflict: " + (reason == null ? "(no reason)" : reason));
  }

}


text:
.class public Landroid/security/keystore/AndroidKeyStoreKeyGeneratorSpi$HmacSHA224;
.super Landroid/security/keystore/AndroidKeyStoreKeyGeneratorSpi$HmacBase;
.source "AndroidKeyStoreKeyGeneratorSpi.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/security/keystore/AndroidKeyStoreKeyGeneratorSpi;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "HmacSHA224"
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 1

    const/4 v0, 0x3

    invoke-direct {p0, v0}, Landroid/security/keystore/AndroidKeyStoreKeyGeneratorSpi$HmacBase;-><init>(I)V

    return-void
.end method


text:
import glob
import hashlib
import logging
import os
import platform
import re
import shutil
import subprocess

from telemetry.core import util
from telemetry.core.platform.profiler import android_prebuilt_profiler_helper
from telemetry.util import support_binaries

try:
  import sqlite3
except ImportError:
  sqlite3 = None

_TEXT_SECTION = '.text'

def _ElfMachineId(elf_file):
  headers = subprocess.check_output(['readelf', '-h', elf_file])
  return re.match(r'.*Machine:\s+(\w+)', headers, re.DOTALL).group(1)

def _ElfSectionAsString(elf_file, section):
  return subprocess.check_output(['readelf', '-p', section, elf_file])

def _ElfSectionMd5Sum(elf_file, section):
  result = subprocess.check_output(
      'readelf -p%s "%s" | md5sum' % (section, elf_file), shell=True)
  return result.split(' ', 1)[0]

def _FindMatchingUnstrippedLibraryOnHost(device, lib):
  lib_base = os.path.basename(lib)

  device_md5 = device.RunShellCommand('md5 "%s"' % lib, as_root=True)[0]
  device_md5 = device_md5.split(' ', 1)[0]

  def FindMatchingStrippedLibrary(out_path):
    # First find a matching stripped library on the host. This avoids the need
    # to pull the stripped library from the device, which can take tens of
    # seconds.
    host_lib_pattern = os.path.join(out_path, '*_apk', 'libs', '*', lib_base)
    for stripped_host_lib in glob.glob(host_lib_pattern):
      with open(stripped_host_lib) as f:
        host_md5 = hashlib.md5(f.read()).hexdigest()
        if host_md5 == device_md5:
          return stripped_host_lib

  for build_dir, build_type in util.GetBuildDirectories():
    out_path = os.path.join(build_dir, build_type)
    stripped_host_lib = FindMatchingStrippedLibrary(out_path)
    if stripped_host_lib:
      break
  else:
    return None

  # The corresponding unstripped library will be under out/Release/lib.
  unstripped_host_lib = os.path.join(out_path, 'lib', lib_base)

  # Make sure the unstripped library matches the stripped one. We do this
  # by comparing the hashes of text sections in both libraries. This isn't an
  # exact guarantee, but should still give reasonable confidence that the
  # libraries are compatible.
  # TODO(skyostil): Check .note.gnu.build-id instead once we're using
  # --build-id=sha1.
  # pylint: disable=W0631
  if (_ElfSectionMd5Sum(unstripped_host_lib, _TEXT_SECTION) !=
      _ElfSectionMd5Sum(stripped_host_lib, _TEXT_SECTION)):
    return None
  return unstripped_host_lib

# Ignored directories for libraries that aren't useful for symbolization.
_IGNORED_LIB_PATHS = [
  '/data/dalvik-cache',
  '/tmp'
]

def GetRequiredLibrariesForPerfProfile(profile_file):
  """Returns the set of libraries necessary to symbolize a given perf profile.

  Args:
    profile_file: Path to perf profile to analyse.

  Returns:
    A set of required library file names.
  """
  with open(os.devnull, 'w') as dev_null:
    perfhost_path = support_binaries.FindPath('perfhost', 'linux')
    perf = subprocess.Popen([perfhost_path, 'script', '-i', profile_file],
                             stdout=dev_null, stderr=subprocess.PIPE)
    _, output = perf.communicate()
  missing_lib_re = re.compile(
      r'^Failed to open (.*), continuing without symbols')
  libs = set()
  for line in output.split('\n'):
    lib = missing_lib_re.match(line)
    if lib:
      lib = lib.group(1)
      path = os.path.dirname(lib)
      if any(path.startswith(ignored_path)
             for ignored_path in _IGNORED_LIB_PATHS) or path == '/':
        continue
      libs.add(lib)
  return libs

def GetRequiredLibrariesForVTuneProfile(profile_file):
  """Returns the set of libraries necessary to symbolize a given VTune profile.

  Args:
    profile_file: Path to VTune profile to analyse.

  Returns:
    A set of required library file names.
  """
  db_file = os.path.join(profile_file, 'sqlite-db', 'dicer.db')
  conn = sqlite3.connect(db_file)

  try:
    # The 'dd_module_file' table lists all libraries on the device. Only the
    # ones with 'bin_located_path' are needed for the profile.
    query = 'SELECT bin_path, bin_located_path FROM dd_module_file'
    return set(row[0] for row in conn.cursor().execute(query) if row[1])
  finally:
    conn.close()

def CreateSymFs(device, symfs_dir, libraries, use_symlinks=True):
  """Creates a symfs directory to be used for symbolizing profiles.

  Prepares a set of files ("symfs") to be used with profilers such as perf for
  converting binary addresses into human readable function names.

  Args:
    device: DeviceUtils instance identifying the target device.
    symfs_dir: Path where the symfs should be created.
    libraries: Set of library file names that should be included in the symfs.
    use_symlinks: If True, link instead of copy unstripped libraries into the
      symfs. This will speed up the operation, but the resulting symfs will no
      longer be valid if the linked files are modified, e.g., by rebuilding.

  Returns:
    The absolute path to the kernel symbols within the created symfs.
  """
  logging.info('Building symfs into %s.' % symfs_dir)

  mismatching_files = {}
  for lib in libraries:
    device_dir = os.path.dirname(lib)
    output_dir = os.path.join(symfs_dir, device_dir[1:])
    if not os.path.exists(output_dir):
      os.makedirs(output_dir)
    output_lib = os.path.join(output_dir, os.path.basename(lib))

    if lib.startswith('/data/app-lib/'):
      # If this is our own library instead of a system one, look for a matching
      # unstripped library under the out directory.
      unstripped_host_lib = _FindMatchingUnstrippedLibraryOnHost(device, lib)
      if not unstripped_host_lib:
        logging.warning('Could not find symbols for %s.' % lib)
        logging.warning('Is the correct output directory selected '
                        '(CHROMIUM_OUT_DIR)? Did you install the APK after '
                        'building?')
        continue
      if use_symlinks:
        if os.path.lexists(output_lib):
          os.remove(output_lib)
        os.symlink(os.path.abspath(unstripped_host_lib), output_lib)
      # Copy the unstripped library only if it has been changed to avoid the
      # delay. Add one second to the modification time to guard against file
      # systems with poor timestamp resolution.
      elif not os.path.exists(output_lib) or \
          (os.stat(unstripped_host_lib).st_mtime >
           os.stat(output_lib).st_mtime + 1):
        logging.info('Copying %s to %s' % (unstripped_host_lib, output_lib))
        shutil.copy2(unstripped_host_lib, output_lib)
    else:
      # Otherwise save a copy of the stripped system library under the symfs so
      # the profiler can at least use the public symbols of that library. To
      # speed things up, only pull files that don't match copies we already
      # have in the symfs.
      if not device_dir in mismatching_files:
        changed_files = device.old_interface.GetFilesChanged(output_dir,
                                                             device_dir)
        mismatching_files[device_dir] = [
            device_path for _, device_path in changed_files]

      if not os.path.exists(output_lib) or lib in mismatching_files[device_dir]:
        logging.info('Pulling %s to %s' % (lib, output_lib))
        device.PullFile(lib, output_lib)

  # Also pull a copy of the kernel symbols.
  output_kallsyms = os.path.join(symfs_dir, 'kallsyms')
  if not os.path.exists(output_kallsyms):
    device.PullFile('/proc/kallsyms', output_kallsyms)
  return output_kallsyms

def PrepareDeviceForPerf(device):
  """Set up a device for running perf.

  Args:
    device: DeviceUtils instance identifying the target device.

  Returns:
    The path to the installed perf binary on the device.
  """
  android_prebuilt_profiler_helper.InstallOnDevice(device, 'perf')
  # Make sure kernel pointers are not hidden.
  device.WriteFile('/proc/sys/kernel/kptr_restrict', '0', as_root=True)
  return android_prebuilt_profiler_helper.GetDevicePath('perf')

def GetToolchainBinaryPath(library_file, binary_name):
  """Return the path to an Android toolchain binary on the host.

  Args:
    library_file: ELF library which is used to identify the used ABI,
        architecture and toolchain.
    binary_name: Binary to search for, e.g., 'objdump'
  Returns:
    Full path to binary or None if the binary was not found.
  """
  # Mapping from ELF machine identifiers to GNU toolchain names.
  toolchain_configs = {
    'x86': 'i686-linux-android',
    'MIPS': 'mipsel-linux-android',
    'ARM': 'arm-linux-androideabi',
    'x86-64': 'x86_64-linux-android',
    'AArch64': 'aarch64-linux-android',
  }
  toolchain_config = toolchain_configs[_ElfMachineId(library_file)]
  host_os = platform.uname()[0].lower()
  host_machine = platform.uname()[4]

  elf_comment = _ElfSectionAsString(library_file, '.comment')
  toolchain_version = re.match(r'.*GCC: \(GNU\) ([\w.]+)',
                               elf_comment, re.DOTALL)
  if not toolchain_version:
    return None
  toolchain_version = toolchain_version.group(1)

  path = os.path.join(util.GetChromiumSrcDir(), 'third_party', 'android_tools',
                      'ndk', 'toolchains',
                      '%s-%s' % (toolchain_config, toolchain_version),
                      'prebuilt', '%s-%s' % (host_os, host_machine), 'bin',
                      '%s-%s' % (toolchain_config, binary_name))
  path = os.path.abspath(path)
  return path if os.path.exists(path) else None


text:
using Snake_DesignPatterns.Controllers;
using Snake_DesignPatterns.Controllers.Events;
using Snake_DesignPatterns.Views;
using System;
using System.IO;
using System.Text;

namespace Snake_DesignPatterns
{
    class Snake
    {
        public static CTick TickThread;
        public static EventManager EventManager;
        public static VInput InputThread;

        static void Main(string[] args)
        {
            Console.OutputEncoding = Encoding.Unicode;

            EventManager = new EventManager();
            TickThread = new CTick();
            InputThread = new VInput();

            //Starts the input manager thread
            InputThread.Start();

            //Start the ticks trigger thread
            TickThread.Start();

            //Starts a new game
            CGame.NewGame();

            string[] soundFile = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), "*.wav");
            System.Media.SoundPlayer sp = new System.Media.SoundPlayer();

            //Infinite loop for the game
            while (true)
            {
                foreach (string music in soundFile)
                {
                    sp.SoundLocation = music;
                    sp.PlaySync();
                }
            }

        }
    }
}


text:
namespace overflow_menu {
// WARNING - PLEASE READ: Sadly, we cannot switch over strings in C++, so be
// very careful when updating this method to ensure all enums are accounted for.
Destination DestinationForStringName(std::string destination) {
  if (destination == "overflow_menu::Destination::Bookmarks") {
    return overflow_menu::Destination::Bookmarks;
  } else if (destination == "overflow_menu::Destination::History") {
    return overflow_menu::Destination::History;
  } else if (destination == "overflow_menu::Destination::ReadingList") {
    return overflow_menu::Destination::ReadingList;
  } else if (destination == "overflow_menu::Destination::Passwords") {
    return overflow_menu::Destination::Passwords;
  } else if (destination == "overflow_menu::Destination::Downloads") {
    return overflow_menu::Destination::Downloads;
  } else if (destination == "overflow_menu::Destination::RecentTabs") {
    return overflow_menu::Destination::RecentTabs;
  } else if (destination == "overflow_menu::Destination::SiteInfo") {
    return overflow_menu::Destination::SiteInfo;
  } else if (destination == "overflow_menu::Destination::Settings") {
    return overflow_menu::Destination::Settings;
  } else {
    NOTREACHED();
    // Randomly chosen destination which should never be returned due to
    // NOTREACHED() above.
    return overflow_menu::Destination::Settings;
  }
}

std::string StringNameForDestination(Destination destination) {
  switch (destination) {
    case overflow_menu::Destination::Bookmarks:
      return "overflow_menu::Destination::Bookmarks";
    case overflow_menu::Destination::History:
      return "overflow_menu::Destination::History";
    case overflow_menu::Destination::ReadingList:
      return "overflow_menu::Destination::ReadingList";
    case overflow_menu::Destination::Passwords:
      return "overflow_menu::Destination::Passwords";
    case overflow_menu::Destination::Downloads:
      return "overflow_menu::Destination::Downloads";
    case overflow_menu::Destination::RecentTabs:
      return "overflow_menu::Destination::RecentTabs";
    case overflow_menu::Destination::SiteInfo:
      return "overflow_menu::Destination::SiteInfo";
    case overflow_menu::Destination::Settings:
      return "overflow_menu::Destination::Settings";
  }
}

void RecordUmaActionForDestination(Destination destination) {
  switch (destination) {
    case Destination::Bookmarks:
      base::RecordAction(base::UserMetricsAction("MobileMenuAllBookmarks"));
      break;
    case Destination::History:
      base::RecordAction(base::UserMetricsAction("MobileMenuHistory"));
      break;
    case Destination::ReadingList:
      base::RecordAction(base::UserMetricsAction("MobileMenuReadingList"));
      break;
    case Destination::Passwords:
      base::RecordAction(base::UserMetricsAction("MobileMenuPasswords"));
      break;
    case Destination::Downloads:
      base::RecordAction(
          base::UserMetricsAction("MobileDownloadFolderUIShownFromToolsMenu"));
      break;
    case Destination::RecentTabs:
      base::RecordAction(base::UserMetricsAction("MobileMenuRecentTabs"));
      break;
    case Destination::SiteInfo:
      base::RecordAction(base::UserMetricsAction("MobileMenuSiteInformation"));
      break;
    case Destination::Settings:
      base::RecordAction(base::UserMetricsAction("MobileMenuSettings"));
      break;
  }
}
}  // namespace overflow_menu


text:
define([
    'underscore',
    'jquery',
    'backbone',
    'dX/libs/debug',
    'dX/libs/pipe'
], function(
    _, $,
    Backbone,
    debug,
    pipe
) {

    /**
     * This basic collection in the dexter framework
     * is used to connect the collections to the pipe
     * event emitter network for further communication
     * between distant views, models and collections.
     * It provides the necessary (dis)connect methods
     * and initializes the pipe connection on
     * {@link dXCollection#initialize}.
     *
     * @class dXCollection
     * @author Riplexus <riplexus@gmail.com>
     */

    var dXCollection = Backbone.Collection.extend(/** @lends dXCollection.prototype */{

        /**
         * Connect with the dXPipe network on initializing.
         */

        initialize: function() {
            this.dXConnect();
        },

        /**
         * To communicate between views, distant collections
         * and models, dexter uses an event emitter as a 'Pipe
         * Network'. It can be (dis)connected with
         * {@link dXView#dXDisconnect} and {@link dXView#dXConnect}.
         */

        dXPipe: null,

        /**
         * Disconnect from the dXPipe Network. If disconnected,
         * events can still be bound, but will only be called
         * when reconnected.
         */

        dXDisconnect: function dXDisconnect() {
            this.dXPipe.isOffline = true;
        },

        /**
         * (Re)connect to the dXPipe event emitter network.
         */

        dXConnect: function dXConnect() {
            var self = this;

            if (self.dXPipe) {
                self.dXPipe.isOffline = false;
                return;
            }

            self.dXPipe = {
                isOffline: false,

                emit: function() {
                    if (!self.dXPipe.isOffline) {
                        pipe.emit.apply(self, arguments);
                    }
                },

                on: function(event, fn) {
                    (function(fn) {
                        pipe.on(event, function() {
                            if (!self.dXPipe.isOffline) {
                                fn.apply(self, arguments);
                            }
                        });
                    })(fn);
                }
            };
        }
    });

    return dXCollection;
});


text: ALTER TABLE CATGENOME.PROJECT_NOTE ALTER COLUMN CONTENT DROP NOT NULL;


text:
#ifndef SQUID_STORE_STATS_H
#define SQUID_STORE_STATS_H

/// High-level store statistics used by mgr:info action. Used inside PODs!
class StoreInfoStats
{
public:
    /// Info common to memory and disk parts of the storage. Used inside PODs!
    class Part
    {
    public:
        double size; ///< bytes currently in use
        double count; ///< number of cached objects
        double capacity; ///< the size limit

        /// mean size of a cached object
        double meanObjectSize() const { return count > 0 ? size/count : 0.0; }

        /// number of unused bytes
        double available() const { return capacity - size; }
    };

    /// disk cache (all cache_dirs) storage stats
    class Swap: public Part
    {
    public:
        double open_disk_fd; ///< number of opened disk files
    };

    /// memory cache (cache_mem) storage stats
    class Mem: public Part
    {
    public:
        bool shared; ///< whether memory cache is shared among workers
    };

    StoreInfoStats();
    StoreInfoStats &operator +=(const StoreInfoStats &stats);

    Swap swap; ///< cache_mem stats
    Mem mem; ///< all cache_dirs stats

    /* stats that could be shared by memory and disk storage */
    double store_entry_count; ///< number of StoreEntry objects in existence
    double mem_object_count; ///< number of MemObject objects in existence
};

// TODO: this should be adjusted for use in StoreIoActionData, DiskdActionData
/// Store statistics related to low-level I/O.
class StoreIoStats
{
public:
    StoreIoStats();

    struct {
        int calls;
        int select_fail;
        int create_fail;
        int success;
    } create; ///< cache_dir selection and disk entry creation stats
};

#endif /* SQUID_STORE_STATS_H */


text:
//
//  UITextDragging.h
//  UIKit
//
//  Copyright © 2017 Apple Inc. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIDragInteraction.h>
#import <UIKit/UITextInput.h>

NS_ASSUME_NONNULL_BEGIN

typedef NS_OPTIONS(NSInteger, UITextDragOptions) {
    UITextDragOptionsNone = 0,

    /* By default, previews generated by the system will retain
     * the foreground and background text colors.
     * Activating this option causes those colors to be stripped away,
     * resulting in a text preview with black text on a clear background.
     * This affects only the preview, not the contents of the drag.
     * Any embedded images in the preview will remain as they are.
     */
    UITextDragOptionStripTextColorFromPreviews = (1 << 0)
} API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos);

@protocol UITextDragDelegate;

/* Defines a text draggable control.
 */
API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos)
@protocol UITextDraggable <UITextInput>

@property (nonatomic, weak, nullable) id<UITextDragDelegate> textDragDelegate;

/* The text drag interaction that UIKit installs on the text control.
 * Use this to explicitly disable drag interactions on system text controls,
 * if desired.
 */
@property (nonatomic, readonly, nullable) UIDragInteraction *textDragInteraction;

/* Returns whether this control currently has at least one active drag session.
 */
@property (nonatomic, readonly, getter=isTextDragActive) BOOL textDragActive;

@property (nonatomic) UITextDragOptions textDragOptions;

@end

@class UIDragItem, UITargetedDragPreview;
@protocol UIDragSession, UITextDragRequest;

API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos)
@protocol UITextDragDelegate <NSObject>

@optional

/* Implement this to provide custom drag items when dragging out of a text control.
 * If you return an empty array here, no drag will occur.
 * The drag request provides the text range from which the user is dragging, and
 * a set of default drag items which would be used if this delegate method were
 * not implemented. You can modify and/or augment these at will.
 *
 * Note: this method might be called more than once. For instance, if the control
 * is asked to provide more items to add to an existing session.
 * You can detect this by checking the `existingItems` in the drag request.
 */
- (NSArray<UIDragItem *> *)textDraggableView:(UIView<UITextDraggable> *)textDraggableView itemsForDrag:(id<UITextDragRequest>)dragRequest;

/* Provide a preview for lifting the item out of the text control.
 * If you return nil, the drag interaction will provide a default preview.
 *
 * Note: This will not be called for items obtained from a UITextDragRequest's suggestedItems
 * (via textDraggableView:itemsForDrag:).
 * The text control will use its own previews for those items.
 */
- (nullable UITargetedDragPreview *)textDraggableView:(UIView<UITextDraggable> *)textDraggableView dragPreviewForLiftingItem:(UIDragItem *)item session:(id<UIDragSession>)session;

/* Called when the lift animation is about to start.
 * Use the animator to animate your own changes alongside the system animation,
 * or to be called when the lift animation completes.
 */
- (void)textDraggableView:(UIView<UITextDraggable> *)textDraggableView willAnimateLiftWithAnimator:(id<UIDragAnimating>)animator session:(id<UIDragSession>)session;

/* Called when the user actually begins dragging.
 * At that point, the text has lifted out of the text control.
 * `textDraggableView:dragSessionDidEnd:withOperation:` will be called when the drag ends.
 */
- (void)textDraggableView:(UIView<UITextDraggable> *)textDraggableView dragSessionWillBegin:(id<UIDragSession>)session;

/* Called when a drag out of this text control has ended.
 * The operation tells you what happened on the drop side.
 */
- (void)textDraggableView:(UIView<UITextDraggable> *)textDraggableView dragSessionDidEnd:(id<UIDragSession>)session withOperation:(UIDropOperation)operation;

@end

API_AVAILABLE(ios(11.0)) API_UNAVAILABLE(watchos, tvos)
@protocol UITextDragRequest <NSObject>

@required

/* The text range being dragged.
 */
@property (nonatomic, readonly) UITextRange *dragRange;

/* The suggested items that the text control would return,
 * if the responsible delegate method were not implemented.
 * This is populated lazily, so only use it when you need it.
 */
@property (nonatomic, readonly) NSArray<UIDragItem *> *suggestedItems;

/* The existing items in the session.
 * Will be filled when we request new items.
 */
@property (nonatomic, readonly) NSArray<UIDragItem *> *existingItems;

/* Indicates whether the drag context contains a selection.
 * Use this to disable dragging from an attachment or links
 * without them being selected. (In those cases, `selected` will be false.)
 * For regular dragged text, this will always be true.
 */
@property (nonatomic, readonly, getter=isSelected) BOOL selected;

/* The current drag session.
 */
@property (nonatomic, readonly) id<UIDragSession> dragSession;

@end

NS_ASSUME_NONNULL_END


text:
package org.apache.wiki.tags;

import org.apache.wiki.api.core.Attachment;
import org.apache.wiki.api.core.Engine;
import org.apache.wiki.api.core.Page;
import org.apache.wiki.render.RenderingManager;
import org.apache.wiki.util.TextUtil;

import java.io.IOException;

/**
 *  Returns the currently requested page name.
 *
 *  @since 2.0
 */
public class PageNameTag extends WikiTagBase {

    private static final long serialVersionUID = 0L;

    @Override
    public final int doWikiStartTag() throws IOException {
        final Engine engine = m_wikiContext.getEngine();
        final Page page = m_wikiContext.getPage();

        if( page != null ) {
            if( page instanceof Attachment ) {
                pageContext.getOut().print( TextUtil.replaceEntities( ((Attachment)page).getFileName() ) );
            } else {
                pageContext.getOut().print( engine.getManager( RenderingManager.class ).beautifyTitle( m_wikiContext.getName() ) );
            }
        }

        return SKIP_BODY;
    }

}


text:
package views;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.border.Border;

import controllers.TileMapController;
import framework.communication.internal.signal.arguments.AbstractEventArgs;
import framework.core.factories.AbstractFactory;
import framework.core.factories.ModelFactory;
import framework.core.graphics.RawData;
import framework.core.mvc.view.PanelView;
import models.TileModel;

/**
 * This view represents the visuals of a single tile
 *
 * @author {@literal Daniel Ricci <thedanny09@gmail.com>}
 */
public class TileView extends PanelView {

    /**
     * Selected border style of this view
     */
    private final Border SELECTED_BORDER = BorderFactory.createLineBorder(Color.RED, 2);

    /**
     * Normal border style of this view
     */
    private final Border NORMAL_BORDER = BorderFactory.createLineBorder(Color.BLACK, 1);

    /**
     * Constructs a new instance of this class type
     *
     * @param tileMapController The controller of the tile map that owns this tile
     */
    public TileView(TileMapController tileMapController) {

        // Use the tile map controller as the controller for this view
        getViewProperties().setEntity(tileMapController);

        // Create the tile model that this view will be populated from
        TileModel tileModel = AbstractFactory.getFactory(ModelFactory.class).add(
                new TileModel(this, tileMapController),
                false
                );

        // Add a new tile model that will be associated to this entity
        tileMapController.addTileEntity(tileModel);

        // Set the layout of this view
        setLayout(new BorderLayout());
    }

    @Override public void onViewInitialized() {
    }

    @Override public void initializeComponentBindings() {
        this.addMouseListener(new MouseAdapter() {
            @Override public void mouseEntered(MouseEvent args) {
                PropertiesDialogView propertiesView = AbstractFactory.getFactory(ViewFactory.class).get(PropertiesDialogView.class);
                if(propertiesView != null && propertiesView.isVisible()) {
                    getViewProperties().getEntity(TileMapController.class).updateProperties(TileView.this);
                }
            }
            @Override public void mouseExited(MouseEvent args) {
                PropertiesDialogView propertiesView = AbstractFactory.getFactory(ViewFactory.class).get(PropertiesDialogView.class);
                if(propertiesView != null && propertiesView.isVisible()) {
                    getViewProperties().getEntity(TileMapController.class).updateProperties(null);
                }
            }
            @Override public void mouseReleased(MouseEvent args) {
                getViewProperties().getEntity(TileMapController.class).toggleSelectedTile(TileView.this);
            }
        });
    }

    @Override public void update(AbstractEventArgs event) {
        super.update(event);

        if(event.getSource() instanceof TileModel) {

            // Get the tile map model of the signal event received
            TileModel tileMapModel = (TileModel) event.getSource();

            // Set the border of the tile based on the selected state of the model
            setBorder(tileMapModel.getSelected() ? SELECTED_BORDER : NORMAL_BORDER);

            // If there is an image to be rendered, submit it to the graphics
            // rendering pipeline
            if(tileMapModel.getImage() != null) {
                addRenderableContent(new RawData(tileMapModel.getImage()));
            }
        }

        // Repaint the view
        repaint();
    }

    @Override public void render() {
        setVisible(true);
    }

    @Override public void clear() {
    }

    @Override public void registerSignalListeners() {
    }
}


text:
module Archimate
  module FileFormats
    module Sax
      module ModelExchangeFile
        class Metadata < FileFormats::Sax::Handler
          def initialize(name, attrs, parent_handler)
            super
            @schema_infos = []
            @schema = nil
            @schema_version = nil
            @elements = []
            @metadata = nil
            @lone_schema_info = nil
          end

          def complete
            [
              event(:on_metadata, metadata)
            ]
          end

          def on_schema(string, _source)
            @schema = string
            false
          end

          def on_schemaversion(string, _source)
            @schema_version = string
            false
          end

          def on_any_element(any_element, _source)
            @elements << any_element
            false
          end

          def on_schema_info(schema_info, _source)
            @schema_infos << schema_info
            false
          end

          private

          def metadata
            return @metadata if @metadata
            @schema_infos << lone_schema_info if @schema
            @metadata = DataModel::Metadata.new(
              schema_infos: @schema_infos
            )
          end

          def lone_schema_info
            return nil unless @schema
            @lone_schema_info = DataModel::SchemaInfo.new(
              schema: @schema,
              schemaversion: @schema_version,
              elements: @elements
            )
          end
        end
      end
    end
  end
end


text:
package com.github.genium_framework.appium.support.server;

import com.github.genium_framework.server.IMobileServer;
import com.github.genium_framework.appium.support.command.CommandManager;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.OS;
import org.apache.commons.io.FileUtils;
import com.github.genium_framework.appium.support.server.arguments.AppiumCommonArgs;
import com.github.genium_framework.server.ServerArguments;
import com.github.genium_framework.server.exception.InvalidAppiumJSFilePathException;
import com.github.genium_framework.server.exception.InvalidNodeFilePathException;
import com.github.genium_framework.server.exception.InvalidServerFileException;
import com.github.genium_framework.server.exception.ServerDirectoryNotFoundException;
import com.github.genium_framework.server.exception.ServerTimeoutException;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * An implementation to Appium server which is responsible for all server
 * operations including: Start, Stop & Checking if the server is alive.
 *
 * @author Hassan Radi
 */
public class AppiumServer implements IMobileServer {

    private final File _absoluteServerDirectory;
    private final File _nodeExecutableFilePath;
    private final File _appiumJavaScriptFilePath;
    private final ServerArguments _serverArguments;
    private final static Logger LOGGER = Logger.getLogger(AppiumServer.class.getName());
    private static final String NODE_RELATIVE_PATH_WINDOWS = "/node.exe";
    private static final String NODE_RELATIVE_PATH_MAC_OS = "/node/bin/node";
    private static final String APPIUM_FILE_RELATIVE_PATH = "/node_modules/appium/lib/server/main.js";
    private static final String APPIUM_SERVER_MAC_DEFAULT_DIRECTORY = "/Applications/Appium.app/Contents/Resources";

    /**
     * Constructs an Appium server instance. Searches automatically for an
     * installed Appium server on your machine using the default installation
     * location according to your operating system.
     *
     * The searched directories are:

Windows OS: "C:/Program
     * Files/Appium" & "C:/Program Files (x86)/Appium"

Mac OS:
     * "/Applications/Appium.app/Contents/Resources"

zz
     *
     * @param serverArguments The server arguments to be used when working with
     * the server.
     */
    public AppiumServer(ServerArguments serverArguments) {
        this._serverArguments = serverArguments;

        // search for installed Appium server
        _absoluteServerDirectory = searchForServerDirectory();

        // make sure to get the node executable file path along with the appium.js path too.
        _nodeExecutableFilePath = new File(OS.isFamilyWindows()
                ? _absoluteServerDirectory + NODE_RELATIVE_PATH_WINDOWS
                : _absoluteServerDirectory + NODE_RELATIVE_PATH_MAC_OS);
        _appiumJavaScriptFilePath = new File(_absoluteServerDirectory
                + APPIUM_FILE_RELATIVE_PATH);
    }

    /**
     * Constructs an Appium server instance. You specify the custom directory to
     * your Appium server.
     *
     * @param absoluteServerDirectory The custom directory to your Appium
     * server. The directory that contains the "node_modules" directory &
     * the NodeJS executable.
     * @param serverArguments The server arguments to be used when working with
     * the server.
     */
    public AppiumServer(File absoluteServerDirectory, ServerArguments serverArguments) {
        this._absoluteServerDirectory = absoluteServerDirectory;
        this._serverArguments = serverArguments;

        // make sure to get the node executable file path along with the appium.js path too.
        _nodeExecutableFilePath = new File(OS.isFamilyWindows()
                ? _absoluteServerDirectory + NODE_RELATIVE_PATH_WINDOWS
                : _absoluteServerDirectory + NODE_RELATIVE_PATH_MAC_OS);
        _appiumJavaScriptFilePath = new File(_absoluteServerDirectory
                + APPIUM_FILE_RELATIVE_PATH);
    }

    /**
     * Constructs an Appium server instance. This constructor can be used in
     * case the Appium server is installed via npm or in case the necessary
     * files to start the server are not in their default locations.
     *
     * @param nodeExecutableFilePath The absolute path to the node executable
     * file and not a shortcut to it.
     * @param appiumJavaScriptFilePath The absolute path to the appium.js file
     * and not a shortcut to it.
     * @param serverArguments The server arguments to be used when working with
     * the server.
     */
    public AppiumServer(File nodeExecutableFilePath, File appiumJavaScriptFilePath,
            ServerArguments serverArguments) {
        this._nodeExecutableFilePath = nodeExecutableFilePath;
        this._appiumJavaScriptFilePath = appiumJavaScriptFilePath;
        this._serverArguments = serverArguments;
        this._absoluteServerDirectory = new File("DUMMY_DATA");
    }

    /**
     * Search the operating system for an Appium server installation directory.
     *
     * @return A File representation to the Appium server installation
     * directory.
     */
    private File searchForServerDirectory() {
        if (OS.isFamilyWindows()) {
            if (getArch().equals("32")) {
                return doesDirectoryExists(System.getenv("ProgramFiles")
                        + "/Appium");
            } else {
                // must be the x86_64
                return doesDirectoryExists(System.getenv("ProgramFiles")
                        + " (x86)/Appium");
            }
        } else if (OS.isFamilyMac()) {
            return doesDirectoryExists(APPIUM_SERVER_MAC_DEFAULT_DIRECTORY);
        }

        // server directrory was not found.
        throw new ServerDirectoryNotFoundException();
    }

    /**
     * Checks if a certain directory exists or not on your HDD.
     *
     * @param directoryString A string representation of the directory you want
     * to check.
     * @return File representation of the directory.
     */
    private File doesDirectoryExists(String directoryString) {
        File directory = new File(directoryString);
        if (directory.exists()) {
            return directory;
        } else {
            throw new ServerDirectoryNotFoundException();
        }
    }

    /**
     * Checks whether an Appium server instance is running or not.
     *
     * @return True if an Appium server is already running, false otherwise.
     */
    @Override
    public boolean isServerRunning() {
        // public exposed function should always log info messages.
        return isServerRunning(false);
    }

    /**
     * Checks whether an Appium server instance is running or not by sending an
     * HTTP request to the server asking for status.
     *
     * @param silentMode Whether or not to log info messages. True will activate
     * silent mode and no messages would be logged.
     * @return True if an Appium server is already running, false otherwise.
     */
    private boolean isServerRunning(boolean silentMode) {
        HttpURLConnection openConnection;

        try {
            if (silentMode == false) {
                LOGGER.log(Level.INFO, "Checking to see if a server instance is running or not ...");
            }

            String serverIPAddress = _serverArguments.get(AppiumCommonArgs.IP_ADDRESS).toString();
            String serverPortNumber = _serverArguments.get(AppiumCommonArgs.PORT_NUMBER).toString();
            URL url = new URL("http://" + serverIPAddress + ":"
                    + serverPortNumber + "/wd/hub/status");
            openConnection = (HttpURLConnection) url.openConnection();
            openConnection.connect();

            /**
             * If the server is up an running it will return a response massage
             * that says "OK"
             */
            return openConnection.getResponseMessage().equalsIgnoreCase("ok");
        } catch (java.net.ConnectException ex) {
            return false;
        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, "An exception was thrown.", ex);
        }
        return false;
    }

    /**
     * Stops an already running Appium server.
     */
    @Override
    public void stopServer() {
        String[] stopServerCommand = null;

        try {
            if (OS.isFamilyWindows()) {
                stopServerCommand = new String[]{"cmd", "/c",
                    "echo off & FOR /F \"usebackq tokens=5\" %a in (`netstat -nao ^| findstr /R /C:\""
                    + _serverArguments.get(AppiumCommonArgs.PORT_NUMBER)
                    + " \"`) do (FOR /F \"usebackq\" %b in (`TASKLIST /FI \"PID "
                    + "eq %a\" ^| findstr /I node.exe`) do taskkill /F /PID %a)"};
            } else if (OS.isFamilyMac()) {
                // Using command substitution
                stopServerCommand = new String[]{"/bin/sh", "-c",
                    "PID=\"$(lsof -i -P | pgrep -f node)\";kill -9 $PID"};
            } else if (OS.isFamilyUnix()) {
                // Using command substitution
                stopServerCommand = new String[]{"/bin/env",
                    "PID=\"$(lsof -i -P | pgrep -f node)\";kill -9 $PID"};
            } else {
                throw new UnsupportedOperationException("Not supported yet for this operating system...");
            }

            LOGGER.log(Level.INFO, "Stopping the server with the command: {0}",
                    CommandManager.convertCommandStringArrayToString(stopServerCommand));
            String stopServerOutput = CommandManager.executeCommandUsingJavaRuntime(stopServerCommand, true);
            LOGGER.log(Level.INFO, "Server stopping output: {0}", stopServerOutput);
        } catch (UnsupportedOperationException ex) {
            throw ex;
        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, "An exception was thrown.", ex);
        }
    }

    /**
     * Start an Appium server instance. The server is started asynchronously, so
     * as not to block the execution. By default the function checks to see if
     * the server has actually started or not and times out after 30 seconds.
     */
    public void startServer() {
        // pass the default timeout value of 30 seconds
        this.startServer(30000);
    }

    /**
     * Start an Appium server instance. The server is started asynchronously, so
     * as not to block the execution. By default the function checks to see if
     * the server has actually started or not.
     *
     * @param timeoutInMilliseonds The amount of milliseconds to wait before
     * declaring that the server failed to start and throw a
     * ServerTimeoutException.
     */
    public void startServer(long timeoutInMilliseonds) {
        try {
            // make sure that the above files exist
            if (_nodeExecutableFilePath.exists() == false) {
                throw new InvalidNodeFilePathException(_nodeExecutableFilePath.getAbsolutePath());
            }
            if (_appiumJavaScriptFilePath.exists() == false) {
                throw new InvalidAppiumJSFilePathException(_appiumJavaScriptFilePath.getAbsolutePath());
            }

            // create the command line to be executed
            LOGGER.log(Level.INFO, "Server is starting...");
            CommandLine cmdLine = CommandManager.createCommandLine(
                    _nodeExecutableFilePath.getAbsolutePath(),
                    new String[]{_appiumJavaScriptFilePath.getAbsolutePath()},
                    _serverArguments.toStringArray());
            final File processOutputError = Files.createTempFile("AppiumServerStreamHandler",
                    ".txt").toFile();
            CommandManager.executeCommandUsingApacheExec(cmdLine,
                    new FileOutputStream(processOutputError));

            /**
             * Register a shutdown hook to delete the process output error
             * stream file.
             */
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    processOutputError.deleteOnExit();
                }
            });

            /**
             * Make sure that the server has started. Check for the server
             * running in silent mode to prevent showing a lot of info messages
             * to the user.
             */
            long startTime = System.currentTimeMillis();
            long endTime = startTime + timeoutInMilliseonds;
            while (isServerRunning(true) == false) {
                if (System.currentTimeMillis() > endTime) {
                    throw new ServerTimeoutException(FileUtils.readFileToString(
                            processOutputError, "UTF8"), timeoutInMilliseonds);
                }
                LOGGER.log(Level.INFO, "Server has not started yet. Trying again in one second...");
                Thread.sleep(1000);
            }

            LOGGER.log(Level.INFO, "Server has been started successfully.");
        } catch (ServerTimeoutException ex) {
            throw ex;
        } catch (InvalidServerFileException ex) {
            throw ex;
        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, "An exception was thrown.", ex);
        }
    }

    /**
     * Get the real architecture of the operating system (Not the architecture
     * of the underlying Java VM).
     *
     * @return A string representation of the operating system architecture.
     */
    private String getArch() {
        String arch = System.getenv("PROCESSOR_ARCHITECTURE");
        String wow64Arch = System.getenv("PROCESSOR_ARCHITEW6432");

        return arch.endsWith("64")
                || wow64Arch != null && wow64Arch.endsWith("64")
                ? "64" : "32";
    }
}


text:
import java.util.zip.*;
import java.io.*;
import javax.imageio.ImageIO;
import java.awt.Image;

public class Lecture {
	private String[] paths;
	public Image[] images;
	public String dir, name;

	public Lecture (String[] theImages, Gypsum app) {
		paths = new String[theImages.length];
		images = new Image[theImages.length];

		for (int i = 0; i < theImages.length; i++) {
			paths[i] = theImages[i];

			File imageFile = new File(paths[i]);
			try {
				images[i] = (Image) ImageIO.read(imageFile);
			} catch (java.io.IOException e) {
				app.showWarning("there was an IO error while trying to load the image \"" + imageFile.getName() + "\".\nPlease make sure the file exists and is readable, and try again", (Exception) e);
				return;
			}

		}

		dir = null;
		name = null;
	}

	private Lecture() {
		dir = null;
		name = null;
	}

	public void save(String theDir, String theName, Gypsum app) {
		if (theName.endsWith(".lec")) {
			theName = theName.substring(0, theName.length()-4);
		}

		dir = theDir;
		name = theName;

		_save(app);
	}

	public void save(Gypsum app) {
		_save(app);
	}

	private void _save(Gypsum app) {
		try {
			File lec = new File(dir + name + ".lec");
			if (lec.exists()) {
				lec.delete();
			}
			lec.createNewFile();

			File saveDst = new File(dir + name);
			if (saveDst.exists()) {
				saveDst.delete();
			}

			saveDst.mkdirs();

			String path = dir + name;
			String[] savedImages = new String[paths.length];

			// copy all of the paths to the destination folder
			for (int i = 0; i < paths.length; i++) {

				String suffix = "";
				String[] imageFormats = ImageIO.getReaderFormatNames();

				for (int j = 0; j < imageFormats.length; j++) {
					if (paths[i].toLowerCase().endsWith("." + imageFormats[j].toLowerCase())) {
						suffix = imageFormats[j].toLowerCase();
					}
				}

				InputStream src = new FileInputStream(paths[i]);
				OutputStream dst = new FileOutputStream(path + "/" + (i+1) + "." + suffix);

				byte[] buf = new byte[1024];
				int len;

				while ((len = src.read(buf)) > 0) {
					dst.write(buf, 0, len);
				}

				src.close();
				dst.close();

				savedImages[i] = (i+1) + "." + suffix;
			}

			// zip up the destination folder into the .lec file
			lec.delete();
			ZipOutputStream zipout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(lec)));
			BufferedInputStream in = null;

			byte[] buf = new byte[1024];

			for (int i = 0; i < savedImages.length; i++) {

				in = new BufferedInputStream(new FileInputStream(path + "/" + savedImages[i]), 1024);
				zipout.putNextEntry(new ZipEntry(savedImages[i]));
				int len;
				while ((len = in.read(buf, 0, 1024)) > 0) {
					zipout.write(buf, 0, len);
				}
				zipout.closeEntry();
			}

			zipout.flush();
			zipout.close();

			// if mac os, set the creator code
			com.apple.eio.FileManager.setFileCreator(dir + name + ".lec", 0x4770736D);

			// delete the temporary folder we created to copy the paths into
			for (int i = 0; i < savedImages.length; i++) {
				File img = new File(path + "/" + savedImages[i]);
				img.delete();
			}
			saveDst.delete();

		} catch (Exception e) {
			app.showWarning("An error occurred while trying to save \"" + name + "\".\nPlease make sure you have permission to write to\nthe directory, and try again.", e);
		}
	}

	public static Lecture open(String theDir, String theName, Gypsum app) {
		try {
			String path = theDir + theName;
			ZipFile zipped = new ZipFile(path);
			int imageIndex = 1;

			Lecture lecture = new Lecture();
			lecture.dir = theDir;
			lecture.name = theName;
			lecture.images = new Image[0];

			while(true) {
				String suffix = "";
				String[] imageFormats = ImageIO.getReaderFormatNames();
				ZipEntry image = null;
				boolean foundImage = false;

				// try every available imageformat as a suffix
				for (int j = 0; j < imageFormats.length; j++) {
					if ((image = zipped.getEntry(imageIndex + "." + imageFormats[j])) != null) {
						foundImage = true;
						imageIndex++;
						break;
					}
				}
				if (!foundImage) {
					break;
				}

				InputStream imagein = zipped.getInputStream(image);

				// copy over the previously found images
				Image[] previousImages = lecture.images;
				lecture.images = new Image[lecture.images.length + 1];
				for (int i = 0; i < previousImages.length; i++) {
					lecture.images[i] = previousImages[i];
				}

				// add this image
				lecture.images[previousImages.length] = (Image) ImageIO.read(imagein);

			}

			return lecture;
		} catch (IOException e) {
			app.showWarning("An error occurred while trying to open \"" + theName + "\".\nPlease make sure the file is readable, and try again.", e);
			return null;
		}

	}
}


text:
"""Smoke tests for the genomics environment."""

# We use unittest and not TF Test because the point of this test is to be
# able to test our environment without having to build TensorFlow.
import unittest

class EnvironmentSmokeTest(unittest.TestCase):

  def test_imports(self):
    """End-to-end test of model_train script."""
    # Test various imports work
    # pylint: disable=unused-variable
    # pylint: disable=g-import-not-at-top
    import enum
    import intervaltree
    import contextlib2
    # pylint: enable=unused-variable
    # pylint: enable=g-import-not-at-top

if __name__ == '__main__':
  unittest.main()


text:
namespace TicTacToe.Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<TicTacToeDbContext>
    {
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = false;
        }
    }
}


text:
<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Lumen User Model
    |--------------------------------------------------------------------------
    |
    | Since Lumen by default has no auth.providers configuration we'll set
    | a configuration value here. Make sure this matches the namespace
    | for your User model and table name.
    |
    */
    'users' => [
        'model' => 'App\User',
        'table' => 'users',
    ],

    /*
    |--------------------------------------------------------------------------
    | Lumineer Role Model
    |--------------------------------------------------------------------------
    |
    | This is the Role model used by Lumineer to create correct relations.  Update
    | the role if it is in a different namespace.
    |
    */
    'role' => 'App\Role',

    /*
    |--------------------------------------------------------------------------
    | Lumineer Roles Table
    |--------------------------------------------------------------------------
    |
    | This is the roles table used by Lumineer to save roles to the database.
    |
    */
    'roles_table' => 'roles',

    /*
    |--------------------------------------------------------------------------
    | Lumineer Permission Model
    |--------------------------------------------------------------------------
    |
    | This is the Permission model used by Lumineer to create correct relations.
    | Update the permission if it is in a different namespace.
    |
    */
    'permission' => 'App\Permission',

    /*
    |--------------------------------------------------------------------------
    | Lumineer Permissions Table
    |--------------------------------------------------------------------------
    |
    | This is the permissions table used by Lumineer to save permissions to the
    | database.
    |
    */
    'permissions_table' => 'permissions',

    /*
    |--------------------------------------------------------------------------
    | Lumineer permission_role Table
    |--------------------------------------------------------------------------
    |
    | This is the permission_role table used by Lumineer to save relationship
    | between permissions and roles to the database.
    |
    */
    'permission_role_table' => 'permission_role',

    /*
    |--------------------------------------------------------------------------
    | Lumineer role_user Table
    |--------------------------------------------------------------------------
    |
    | This is the role_user table used by Lumineer to save assigned roles to the
    | database.
    |
    */
    'role_user_table' => 'role_user',

    /*
    |--------------------------------------------------------------------------
    | User Foreign key on Lumineer's role_user Table (Pivot)
    |--------------------------------------------------------------------------
    */
    'user_foreign_key' => 'user_id',

    /*
    |--------------------------------------------------------------------------
    | Role Foreign key on Lumineer's role_user and permission_role Tables (Pivot)
    |--------------------------------------------------------------------------
    */
    'role_foreign_key' => 'role_id',

    /*
    |--------------------------------------------------------------------------
    | Permission Foreign key on Lumineer's permission_role Table (Pivot)
    |--------------------------------------------------------------------------
    */
    'permission_foreign_key' => 'permission_id',
];


text:
/**
 *  SSOConfig set authorised configuration.
 *
 *  @author  haozuo
 *  @date    Oct 13, 2015
 *
 */
(function(define) {
    'use strict';

    define(['lib/ConfiguratorBase'], function(Base) {

        var Configurator = function(features, app) {
            Base.call(this, features, app);
        };

        Configurator.prototype = new Base();

        Configurator.prototype.constructor = Configurator;

        Configurator.prototype.run = function() {
            this.app.config([
                '$httpProvider',
                function($httpProvider) {
                    $httpProvider.defaults.headers.common.Accept = 'application/json;charset=utf-8';
                    $httpProvider.defaults.withCredentials = true;
                }
            ]);
        };

        return Configurator;

    });

}(define));


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>PathBoundsX</title>

PathBoundsX()

语法

Result.d = PathBoundsX()

概要

Returns the X coordinate (top/left corner) of the bounding box for the current vector
drawing path. The result is the lowest X coordinate that stroking/filling the current
path would reach.

参数

无.

返回值

The X coordinate of the bounding box.

示例

  If OpenWindow(0, 0, 0, 400, 200, "VectorDrawing", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
    CanvasGadget(0, 0, 0, 400, 200)

    If StartVectorDrawing(CanvasVectorOutput(0))

      ; construct path
      MovePathCursor(150, 125)
      AddPathCurve(0, 270, 0, -150, 350, 180)

      ; get path bounds
      x = PathBoundsX()
      y = PathBoundsY()
      w = PathBoundsWidth()
      h = PathBoundsHeight()

      ; stroke the path
      VectorSourceColor($FF0000FF)
      StrokePath(5)

      ; draw bounding box
      AddPathBox(x, y, w, h)
      VectorSourceColor($FF000000)
      DashPath(2, 5)

      StopVectorDrawing()
    EndIf

    Repeat
      Event = WaitWindowEvent()
    Until Event = #PB_Event_CloseWindow
  EndIf

参阅

PathBoundsY(), PathBoundsWidth(), PathBoundsHeight()

已支持操作系统
所有

<- PathBoundsWidth() - VectorDrawing Index - PathBoundsY() ->


text:
<?xml version="1.0"?>
<!--

-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <attribute name="body_attribute_name" value="body_attribute_value" />
    </body>
</page>


text:
require 'spec_helper'

module ResourceMethodsSpec
  class MyController < ActionController::Base
    resources_controller_for :users
  end

  if Rails.respond_to?(:version) && Rails.version >= "2.3"
    describe "#new_resource" do
      it "should accept block syntax" do
        c = MyController.new
        c.resource_service = User
        allow(c).to receive(:params).and_return({})
        r = c.send(:new_resource) do |u|
          u.login = "Fred"
        end
        expect(r).to be_kind_of User
        expect(r.login).to eq("Fred")
      end
    end
  end

  describe "An rc for collection :users" do
    before do
      @controller = MyController.new
      allow(@controller).to receive(:params).and_return({})
    end

    describe "when no enclosing resource" do
      it "#find_resource(<id>) should call User.find(<id>)" do
        expect(User).to receive(:find).with("42")
        @controller.send(:find_resource, "42")
      end

      it "#find_resources should call User.find(:all)" do
        expect(User).to receive(:all)
        @controller.send(:find_resources)
      end

      it "#new_resource({}) should call User.new({})" do
        expect(User).to receive(:new).with({})
        @controller.send(:new_resource, {})
      end

      it "#destroy_resource(<id>) should call User.find(<id>).destroy" do
        expect(User).to receive(:find).with("42").and_return(user = double)
        expect(user).to receive(:destroy).and_return(user)
        expect(@controller.send(:destroy_resource, "42")).to eq(user)
      end
    end

    describe "when an enclosing resource is added (a forum)" do
      before do
        @forum = Forum.create!
        allow(@forum).to receive(:users).and_return(@users = double)
        @controller.send :add_enclosing_resource, @forum
      end

      it "#find_resource(<id>) should find the forum user" do
        expect(@users).to receive(:find).with("42").and_return(user = double)
        expect(@controller.send(:find_resource, "42")).to eq(user)
      end

      it "#find_resources should return the forum users" do
        expect(@users).to receive(:all).and_return(users = double)
        expect(@controller.send(:find_resources)).to eq(users)
      end

      it "#new_resource({}) should call forum.users.build({})" do
        expect(@users).to receive(:build).with({}).and_return(user = double)
        expect(@controller.send(:new_resource, {})).to eq(user)
      end

      it "#destroy_resource(<id>) should call forum.users.find(<id>) and forum.users.destroy(<id>) and return the resource" do
        expect(@users).to receive(:find).with("42").and_return(user = double)
        expect(@users).to receive(:destroy).with("42")
        expect(@controller.send(:destroy_resource, "42")).to eq(user)
      end
    end
  end

  class MySingletonController < ActionController::Base
    resources_controller_for :info, :singleton => true
  end

  describe "An rc for singleton :info" do
    before do
      @controller = MySingletonController.new
      allow(@controller).to receive(:params).and_return({})
    end

    describe "with an enclosing resource (a user)" do
      before do
        @user = User.create!
        @controller.send :add_enclosing_resource, @user
      end

      it "#find_resource should call user.info" do
        expect(@user).to receive(:info)
        @controller.send(:find_resource)
      end

      it "#new_resource({}) should call user.build_info({})" do
        expect(@user).to receive(:build_info).with({})
        @controller.send :new_resource, {}
      end

      it "#destroy_resource should call user.info.destroy" do
        expect(@user).to receive(:info).and_return(info = double)
        expect(info).to receive(:destroy)
        @controller.send(:destroy_resource)
      end
    end
  end

  module MyResourceMethods
  protected
    def new_resource(attrs = (params[resource_name] || {}), &block)
      "my new_resource"
    end

    def find_resource(id = params[:id])
      "my find_resource"

    end

    def find_resources
      "my find_resources"
    end

    def destroy_resource(id = params[:id])
      "my destroy_resource"
    end
  end

  shared_examples_for "A controller with its own resource methods" do
    it "#new_resource should call MyResourceMethods#new_resource" do
      expect(@controller.send(:new_resource, {})).to eq('my new_resource')
    end

    it "#find_resource should call MyResourceMethods#find_resource" do
      expect(@controller.send(:find_resource, 1)).to eq('my find_resource')
    end

    it "#find_resources should call MyResourceMethods#new_resource" do
      expect(@controller.send(:find_resources)).to eq('my find_resources')
    end

    it "#destroy_resource should call MyResourceMethods#destroy_resource" do
      expect(@controller.send(:destroy_resource, 1)).to eq('my destroy_resource')
    end
  end

  class MyControllerWithMyResourceMethodsMixedIn < ActionController::Base
    resources_controller_for :users
    include MyResourceMethods
  end

  describe "A controller with resource methods mixed in after resources_controller_for" do
    before do
      @controller = MyControllerWithMyResourceMethodsMixedIn.new
      @controller.resource_service = User
      allow(@controller).to receive(:params).and_return({})
    end

    it_should_behave_like "A controller with its own resource methods"
  end

  class MyAbstractControllerWithOwnResourceMethods < ActionController::Base
    include MyResourceMethods
  end

  class InhertedMyAbstractControllerWithOwnResourceMethods < MyAbstractControllerWithOwnResourceMethods
    resources_controller_for :users, :resource_methods => false
  end

  describe "A controller inheriting resource methods which declares :resource_methods => false" do
    before do
      @controller = InhertedMyAbstractControllerWithOwnResourceMethods.new
      @controller.resource_service = User
      allow(@controller).to receive(:params).and_return({})
    end

    it_should_behave_like "A controller with its own resource methods"
  end

  class MyAbstractControllerWithResourceMethodsOverridden < ActionController::Base
    include ResourcesController::ResourceMethods
    include MyResourceMethods
  end

  class InhertedMyAbstractControllerWithResourceMethodsOverridden < MyAbstractControllerWithResourceMethodsOverridden
    resources_controller_for :users
  end

  describe "A controller inheriting from a controller which mixes in ResourceMethods, and overrides them" do
    before do
      @controller = InhertedMyAbstractControllerWithResourceMethodsOverridden.new
      @controller.resource_service = User
      allow(@controller).to receive(:params).and_return({})
    end

    it_should_behave_like "A controller with its own resource methods"
  end
end


text:
from __future__ import absolute_import, division, print_function, unicode_literals
from six.moves import zip, range
import itertools as it
import numpy as np
import matplotlib as mpl
import utool as ut
from plottool_ibeis import color_funcs as color_fns
ut.noinject(__name__, '[pt.mpl_sift]')

TAU = 2 * np.pi  # References: tauday.com
BLACK  = np.array((0.0, 0.0, 0.0, 1.0))
RED    = np.array((1.0, 0.0, 0.0, 1.0))

def testdata_sifts():
    # make random sifts
    randstate = np.random.RandomState(1)
    sifts_float = randstate.rand(1, 128)
    sifts_float = sifts_float / np.linalg.norm(sifts_float)
    sifts_float[sifts_float > .2] = .2
    sifts_float = sifts_float / np.linalg.norm(sifts_float)
    sifts = (sifts_float * 512).astype(np.uint8)
    return sifts

# Create a patch collection with attributes
def _circl_collection(patch_list, color, alpha):
    coll = mpl.collections.PatchCollection(patch_list)
    coll.set_alpha(alpha)
    coll.set_edgecolor(color)
    coll.set_facecolor('none')
    return coll

def get_sift_collection(sift, aff=None, bin_color=BLACK, arm1_color=RED,
                        arm2_color=BLACK, arm_alpha=1.0, arm1_lw=1.0,
                        arm2_lw=2.0, stroke=1.0, circ_alpha=.5, fidelity=256,
                        scaling=True, **kwargs):
    """
    Creates a collection of SIFT matplotlib patches

    get_sift_collection

    Args:
        sift (?):
        aff (None):
        bin_color (ndarray):
        arm1_color (ndarray):
        arm2_color (ndarray):
        arm_alpha (float):
        arm1_lw (float):
        arm2_lw (float):
        circ_alpha (float):
        fidelity (int): quantization factor

    Returns:
        ?: coll_tup

    CommandLine:
        python -m plottool_ibeis.mpl_sift --test-get_sift_collection

    Example:
        >>> from plottool_ibeis.mpl_sift import *  # NOQA
        >>> sift = testdata_sifts()[0]
        >>> aff = None
        >>> bin_color = np.array([ 0.,  0.,  0.,  1.])
        >>> arm1_color = np.array([ 1.,  0.,  0.,  1.])
        >>> arm2_color = np.array([ 0.,  0.,  0.,  1.])
        >>> arm_alpha = 1.0
        >>> arm1_lw = 0.5
        >>> arm2_lw = 1.0
        >>> circ_alpha = 0.5
        >>> coll_tup = get_sift_collection(sift, aff, bin_color, arm1_color,
        >>>                                arm2_color, arm_alpha, arm1_lw,
        >>>                                arm2_lw, circ_alpha)
        >>> print(coll_tup)
    """
    # global offset scale adjustments
    if aff is None:
        aff = mpl.transforms.Affine2D()
    MULTI_COLORED_ARMS = kwargs.pop('multicolored_arms', False)
    _kwarm = kwargs.copy()
    _kwarm.update(dict(head_width=1e-10, length_includes_head=False,
                       transform=aff, color=[1, 1, 0]))
    _kwcirc = dict(transform=aff)
    DSCALE   =  0.25  # Descriptor scale factor
    XYSCALE  =  0.5   # Position scale factor
    XYOFFST  = -0.75  # Position offset
    NORI, NX, NY = 8, 4, 4  # SIFT BIN CONSTANTS
    NBINS = NX * NY
    discrete_ori = (np.arange(0, NORI) * (TAU / NORI))

    # import utool
    # utool.embed()
    # Arm magnitude and orientations
    #arm_mag = sift / 255.0
    # If given the correct fidelity, each arm will have a max magnitude of 1.0
    # Because the diameter of each circle is 1.0
    arm_mag = sift / (float(fidelity))
    # arm_mag = sift / 512.0  # technically correct
    # arm_mag = sift / 256.0  # but use this instead as it is max bin

    arm_ori = np.tile(discrete_ori, (NBINS, 1)).flatten()

    if scaling and False:
        # Use entropy as a scaling factor to more clearly visualize differences
        p = np.bincount(sift) / len(sift)
        maximum_entropy = -np.log2(1 / len(sift))
        entropy = -np.nansum(p * np.log2(p))
        # Alpha is 1 when entropy is maximum
        # When entropy is maximum, we want to scale things up a bit
        alpha = (entropy / maximum_entropy)

        max_ = arm_mag.max()
        # Always scale up, but no more than max.
        pt1 = min(max_, 1)  # max_
        pt2 = max(max_, 1)  # 1
        denom = (pt2 * alpha) + (pt1 * (1 - alpha))
        scale_factor = 1 / denom
        arm_mag = arm_mag * scale_factor
    # arm_mag *= 4

    ori_dxy = np.hstack([np.cos(arm_ori)[:, None],
                         np.sin(arm_ori)[:, None]])

    # Arm orientation in dxdy format
    # arm_dx = np.cos(arm_ori) * arm_mag
    # arm_dy = np.sin(arm_ori) * arm_mag
    # arm_dxy = np.hstack([arm_dx[:, None], arm_dy[:, None]])
    # assert np.all(np.isclose(np.sqrt(arm_dy ** 2 + arm_dx ** 2), arm_mag))
    #np.linalg.norm(arm_dxy, axis=1).max()

    # Arm locations and dxdy index
    yxt_gen = it.product(range(NY), range(NX), range(NORI))
    # Circle x,y locations
    yx_gen  = it.product(range(NY), range(NX))
    # Draw 8 directional arms in each of the 4x4 grid cells

    # MOVETO = mpl.path.Path.MOVETO
    # LINETO = mpl.path.Path.LINETO
    # STOP = mpl.path.Path.STOP

    arm_patches = []
    for y, x, t in yxt_gen:
        index = (y * NX * NORI) + (x * NORI) + (t)
        (dx, dy) = ori_dxy[index]
        mag = arm_mag[index]
        # (mdx, mdy) = arm_dxy[index]
        arm_x  = (x * XYSCALE) + XYOFFST  # MULTIPLY BY -1 to invert X axis
        arm_y  = (y * XYSCALE) + XYOFFST
        arm_dy = (dy * mag * DSCALE)
        arm_dx = (dx * mag * DSCALE)

        # Move arms a little bit away from the center
        nudge = .05
        arm_x = arm_x + dx * (nudge * DSCALE)
        arm_y = arm_y + dy * (nudge * DSCALE)
        arm_dx = arm_dx + dx * (nudge * DSCALE)
        arm_dy = arm_dy + dy * (nudge * DSCALE)

        if 0:
            _args = [arm_x, arm_y, arm_dx, arm_dy]
            arm_patch = mpl.patches.FancyArrow(*_args, **_kwarm)
        else:
            arm_x2 = arm_x + arm_dx
            arm_y2 = arm_y + arm_dy
            pt1 = np.array([arm_x, arm_y])
            pt2 = np.array([arm_x2, arm_y2])
            # Hack a small eps rectangle to make the ends of the line also have
            # a stroke
            eps = 1e-6
            verts = [pt1, pt2, pt2 + eps, pt2 - eps]
            path = mpl.path.Path(verts, closed=True)
            arm_patch = mpl.patches.PathPatch(
                path,
                # joinstyle='bevel',
                # joinstyle='round',
                edgecolor='k',
                transform=aff,
            )
        arm_patches.append(arm_patch)

    # Draw circles around each of the 4x4 grid cells
    circle_patches = []
    for y, x in yx_gen:
        circ_xy = (x * XYSCALE + XYOFFST, y * XYSCALE + XYOFFST)
        circ_radius = DSCALE
        patch = mpl.patches.Circle(circ_xy, circ_radius, **_kwcirc)
        circle_patches.append(patch)

    circ_coll = mpl.collections.PatchCollection(circle_patches)
    circ_coll.set_alpha(circ_alpha)
    circ_coll.set_edgecolor(bin_color)
    circ_coll.set_facecolor('none')

    # arm2_coll = _arm_collection(arm_patches, arm2_color, arm_alpha, arm2_lw)

    # Add stroke instead of another arm
    path_effects = []

    ENABLE_PATH_EFFECTS = 0
    if ENABLE_PATH_EFFECTS:
        from matplotlib import patheffects
        print('stroke = %r' % (stroke,))
        if stroke > 0:
            path_effects.append(
                patheffects.withStroke(linewidth=arm1_lw + stroke, foreground='k')
            )
        path_effects.append(patheffects.Normal())

    if MULTI_COLORED_ARMS:
        # Hack in same colorscheme for arms as the sift bars
        ori_colors = color_fns.distinct_colors(16)
        arm_collections = [
            mpl.collections.PatchCollection(patches)
            for patches in ut.ichunks(arm_patches, 8)
        ]
        for col, color in zip(arm_collections, ori_colors):
            col.set_color(color)
    else:
        # Just use a single color for all the arms
        arm1_coll = mpl.collections.PatchCollection(arm_patches)
        arm1_coll.set_color(arm1_color)
        arm_collections = [arm1_coll]

    for col in arm_collections:
        col.set_alpha(arm_alpha)
        col.set_path_effects(path_effects)
        col.set_linewidth(arm1_lw)

    coll_tup = [circ_coll] + arm_collections
    return coll_tup

def draw_sifts(ax, sifts, invVR_aff2Ds=None, **kwargs):
    """
    Gets sift patch collections, transforms them and then draws them.

    CommandLine:
        python -m plottool_ibeis.mpl_sift --test-draw_sifts --show

    Example:
        >>> # ENABLE_DOCTEST
        >>> from plottool_ibeis.mpl_sift import *  # NOQA
        >>> # build test data
        >>> import plottool_ibeis as pt
        >>> pt.figure(1)
        >>> ax = pt.gca()
        >>> ax.set_xlim(-1.1, 1.1)
        >>> ax.set_ylim(-1.1, 1.1)
        >>> sifts = testdata_sifts()
        >>> sifts[:, 0:8] = 0
        >>> invVR_aff2Ds = None
        >>> kwargs = dict(multicolored_arms=False)
        >>> kwargs['arm1_lw'] = 3
        >>> kwargs['stroke'] = 5
        >>> result = draw_sifts(ax, sifts, invVR_aff2Ds, **kwargs)
        >>> ax.set_aspect('equal')
        >>> print(result)
        >>> pt.show_if_requested()
    """
    if invVR_aff2Ds is None:
        invVR_aff2Ds = [mpl.transforms.Affine2D() for _ in range(len(sifts))]
    if isinstance(invVR_aff2Ds, (list, np.ndarray)):
        invVR_aff2Ds = [mpl.transforms.Affine2D(matrix=aff_)
                        for aff_ in invVR_aff2Ds]
    colltup_list = [get_sift_collection(sift, aff, **kwargs)
                    for sift, aff in zip(sifts, invVR_aff2Ds)]
    ax.invert_xaxis()

    for coll_tup in colltup_list:
        for coll in coll_tup:
            coll.set_transform(ax.transData)

    for coll_tup in colltup_list:
        for coll in coll_tup:
            ax.add_collection(coll)
    ax.invert_xaxis()

def draw_sift_on_patch(patch, sift, **kwargs):
    import plottool_ibeis as pt
    pt.imshow(patch)
    ax = pt.gca()
    half_size = patch.shape[0] / 2
    invVR = np.array([[half_size, 0, half_size], [0, half_size, half_size], [0, 0, 1]])
    invVR_aff2Ds = np.array([invVR])
    sifts = np.array([sift])
    return draw_sifts(ax, sifts, invVR_aff2Ds)

def render_sift_on_patch(patch, sift):
    import plottool_ibeis as pt
    with pt.RenderingContext() as render:
        draw_sift_on_patch(patch, sift)
    rendered = render.image
    return rendered

if __name__ == '__main__':
    """
    CommandLine:
        python -m plottool_ibeis.mpl_sift
        python -m plottool_ibeis.mpl_sift --allexamples
        python -m plottool_ibeis.mpl_sift --allexamples --noface --nosrc
    """
    import multiprocessing
    multiprocessing.freeze_support()  # for win32
    import utool as ut  # NOQA
    ut.doctest_funcs()


text:
@interface FuncButton : UIButton
/// 是否显示红点
@property (nonatomic, assign) BOOL showBadge;
/// 描述文字
@property (nonatomic, copy) NSString *descStr;
@end


text:
CSJTools is an Objective-C library for iOS developers.

##Version
####0.0.5
* first version

####0.0.6
* add custom UINavigationController
* add use coredata FetchedResults tableviewcontroller

#####0.0.7
* add CSJToolKit

##Requirements
* iOS 6.0 or later
* must support ARC

##Installation with CocoaPods
#####Podfile
```
platform :ios, '6.0'
pod 'CSJTools'
```

##List
#####CSJMaster.h
```
//import all .h
```

#####CSJLog.h
```
//common define & log
```
#####CSJBase64.h
```
//return NSString/NSData base64 String
//NSString
+(NSString *)stringFromBase64String:(NSString *)base64String;
-(NSString *)base64String;

//NSData
+(NSData *)dataWithBase64String:(NSString *)base64String;
-(NSString *)base64String;

+(NSData *)dataFromBase64String:(NSString *)base64String;
+(NSString *)base64StringFromData:(NSData *)data;
```

#####CSJData.h
```
//天数差
+(NSInteger)daysBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime;
//小时差
+(NSInteger)hoursBetweenDate:(NSDate *)fromDateTime andDate:(NSDate*)toDateTime;
//分钟差
+(NSInteger)minsBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime;
//秒差
+(NSInteger)secondBetweenDate:(NSDate*)fromDateTime andDate:(NSDate*)toDateTime;

//返回当前年,月,日..
-(int)year;
-(int)month;
-(int)day;
-(int)hour;
-(int)minute;
-(int)second;
```

#####CSJDES.h
```
//与服务器的加密解密
//加密
- (NSString *) DESEncryptByKey:(NSString *)key;
//解密
- (NSString *) DESDecryptByKey:(NSString *)key;
```

#####CSJMD5.h
```
-(NSString *)fileMD5;
-(NSString *)stringMD5;
+(NSString *)md5:(NSString *)inPutText;
```

#####CSJString.h
```
//判断是否是电话号码
- (BOOL)isMobileNumber;
//email
-(BOOL)isEmailAddress;
```

#####CSJURL.h
```
-(NSString *)parameterForKey:(NSString *)key;
-(NSDictionary  *)parameters;

```

#####CSJ_NavGestureViewController
A custom gesture to return Navigationcontroller

#####CSJ_CoredataTableViewController
A automatic NSFetchedResults Coredata Tableviewcontroller

#####CSJToolKit
```
+ (CGSize)textSize:(NSString*)text withFont:(UIFont*)font inWidth:(CGFloat)width;
```

##Special thanks to
Thank them sparked my inspiration. Thank them for their contributions to the open source community.

* [ZXTools](https://github.com/zhangxigithub/ZXTools)
* [RCNavigationController](https://github.com/RoCry/RCNavigationController)
* [cs193p Coredata](http://www.stanford.edu/class/cs193p/cgi-bin/drupal/node/389)

## License
CSJTools is available under the MIT license.


text:
include(CMakeParseArguments)

function(tz_add_library)
	cmake_parse_arguments(
		TZ_ADD_LIBRARY
		""
		"TARGET"
		"SOURCES"
		${ARGN}
	)

	hdk_base_add_library(
		TARGET ${TZ_ADD_LIBRARY_TARGET}
		BASE topaz
		SOURCES ${TZ_ADD_LIBRARY_SOURCES}
	)
endfunction()

function(tz_add_executable)
	cmake_parse_arguments(
		TZ_ADD_EXECUTABLE
		""
		"TARGET"
		"SOURCES"
		${ARGN}
	)

	hdk_base_add_executable(
		TARGET ${TZ_ADD_EXECUTABLE_TARGET}
		BASE topaz
		SOURCES ${TZ_ADD_EXECUTABLE_SOURCES}
	)
endfunction()


text:
This currently provides three provisioners:

* Furnish::Provisioner::VirtualBox::Import -- import a VM from an .ova file
* Furnish::Provisioner::VirtualBox::Machine -- clone and start a VM from an imported VM
* Furnish::Provisioner::VirtualBox::HostOnly -- work with hostonly networks.

furnish-virtualbox currently does not work on Linux due to a bug with port
forwarding on that system. While we hope to rectify that, in the meantime we
will provide alternatives that will be edited in here later.

## Installation

Add this line to your application's Gemfile:

    gem 'furnish-virtualbox'

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install furnish-virtualbox

## Usage

Please read the documentation for
[furnish](https://github.com/chef-workflow/furnish) and the above classes.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
<!DOCTYPE html>
<html ng-app='chattyWeather'>
  <head>
    <meta charset="utf-8" />
    <title>Chatty Weather</title>
    <link href="https://fonts.googleapis.com/css?family=Lobster|Raleway:100,400,900" rel="stylesheet">
    <link rel="stylesheet" href="./style/style.css">
  </head>
  <body>

    <div ng-view class="box"></div>

    <script src="lib/angular.min.js"></script>
    <script src="lib/angular-route.min.js"></script>

    <script src="weather/weather.js"></script>
    <script src="activities/activities.js"></script>
    <script src="services/service.js"></script>
    <script src="food/food.js"></script>
    <script src="app.js"></script>
    <script src="style/skycons.js"></script>

  </body>
</html>


text:
.top-section {
    position: absolute;
    top: 0;
}