text:
namespace extensions {
namespace util {

namespace {

// Returns |extension_id|. See note below.
std::string ReloadExtensionIfEnabled(const std::string& extension_id,
                                     content::BrowserContext* context) {
  ExtensionRegistry* registry = ExtensionRegistry::Get(context);
  bool extension_is_enabled =
      registry->enabled_extensions().Contains(extension_id);

  if (!extension_is_enabled)
    return extension_id;

  // When we reload the extension the ID may be invalidated if we've passed it
  // by const ref everywhere. Make a copy to be safe. http://crbug.com/103762
  std::string id = extension_id;
  ExtensionService* service =
      ExtensionSystem::Get(context)->extension_service();
  CHECK(service);
  service->ReloadExtension(id);
  return id;
}

}  // namespace

bool HasIsolatedStorage(const std::string& extension_id,
                        content::BrowserContext* context) {
  const Extension* extension =
      ExtensionRegistry::Get(context)->enabled_extensions().GetByID(
          extension_id);

#if BUILDFLAG(IS_CHROMEOS_ASH)
  const bool is_policy_extension =
      extension && Manifest::IsPolicyLocation(extension->location());
  Profile* profile = Profile::FromBrowserContext(context);
  if (profile && ash::ProfileHelper::IsSigninProfile(profile) &&
      is_policy_extension) {
    return true;
  }
#endif

  return extension && AppIsolationInfo::HasIsolatedStorage(extension);
}

bool IsChromeApp(const std::string& extension_id,
                 content::BrowserContext* context) {
  const Extension* extension =
      ExtensionRegistry::Get(context)->enabled_extensions().GetByID(
          extension_id);
  return extension->is_platform_app();
}

void SetIsIncognitoEnabled(const std::string& extension_id,
                           content::BrowserContext* context,
                           bool enabled) {
  ExtensionRegistry* registry = ExtensionRegistry::Get(context);
  const Extension* extension =
      registry->GetExtensionById(extension_id, ExtensionRegistry::EVERYTHING);

  if (extension) {
    if (!util::CanBeIncognitoEnabled(extension))
      return;

    // TODO(treib,kalman): Should this be Manifest::IsComponentLocation(..)?
    // (which also checks for kExternalComponent).
    if (extension->location() == mojom::ManifestLocation::kComponent) {
      // This shouldn't be called for component extensions unless it is called
      // by sync, for syncable component extensions.
      // See http://crbug.com/112290 and associated CLs for the sordid history.
      bool syncable = sync_helper::IsSyncableComponentExtension(extension);
#if BUILDFLAG(IS_CHROMEOS_ASH)
      // For some users, the file manager app somehow ended up being synced even
      // though it's supposed to be unsyncable; see crbug.com/576964. If the bad
      // data ever gets cleaned up, this hack should be removed.
      syncable = syncable || extension->id() == file_manager::kFileManagerAppId;
#endif
      DCHECK(syncable);

      // If we are here, make sure the we aren't trying to change the value.
      DCHECK_EQ(enabled, IsIncognitoEnabled(extension_id, context));
      return;
    }
  }

  ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(context);
  // Broadcast unloaded and loaded events to update browser state. Only bother
  // if the value changed and the extension is actually enabled, since there is
  // no UI otherwise.
  bool old_enabled = extension_prefs->IsIncognitoEnabled(extension_id);
  if (enabled == old_enabled)
    return;

  extension_prefs->SetIsIncognitoEnabled(extension_id, enabled);

  std::string id = ReloadExtensionIfEnabled(extension_id, context);

  // Reloading the extension invalidates the |extension| pointer.
  extension = registry->GetExtensionById(id, ExtensionRegistry::EVERYTHING);
  if (extension) {
    Profile* profile = Profile::FromBrowserContext(context);
    ExtensionSyncService::Get(profile)->SyncExtensionChangeIfNeeded(*extension);
  }
}

bool CanLoadInIncognito(const Extension* extension,
                        content::BrowserContext* context) {
  CHECK(extension);
  if (extension->is_hosted_app())
    return true;
  // Packaged apps and regular extensions need to be enabled specifically for
  // incognito (and split mode should be set).
  return IncognitoInfo::IsSplitMode(extension) &&
         IsIncognitoEnabled(extension->id(), context);
}

bool AllowFileAccess(const std::string& extension_id,
                     content::BrowserContext* context) {
  return base::CommandLine::ForCurrentProcess()->HasSwitch(
             ::switches::kDisableExtensionsFileAccessCheck) ||
         ExtensionPrefs::Get(context)->AllowFileAccess(extension_id);
}

void SetAllowFileAccess(const std::string& extension_id,
                        content::BrowserContext* context,
                        bool allow) {
  // Reload to update browser state. Only bother if the value changed and the
  // extension is actually enabled, since there is no UI otherwise.
  if (allow == AllowFileAccess(extension_id, context))
    return;

  ExtensionPrefs::Get(context)->SetAllowFileAccess(extension_id, allow);

  ReloadExtensionIfEnabled(extension_id, context);
}

bool IsAppLaunchable(const std::string& extension_id,
                     content::BrowserContext* context) {
  int reason = ExtensionPrefs::Get(context)->GetDisableReasons(extension_id);
  return !((reason & disable_reason::DISABLE_UNSUPPORTED_REQUIREMENT) ||
           (reason & disable_reason::DISABLE_CORRUPTED));
}

bool IsAppLaunchableWithoutEnabling(const std::string& extension_id,
                                    content::BrowserContext* context) {
  return ExtensionRegistry::Get(context)->GetExtensionById(
             extension_id, ExtensionRegistry::ENABLED) != nullptr;
}

bool ShouldSync(const Extension* extension,
                content::BrowserContext* context) {
  ExtensionManagement* extension_management =
      ExtensionManagementFactory::GetForBrowserContext(context);
  // Update URL is overridden only for non webstore extensions and offstore
  // extensions should not be synced.
  if (extension_management->IsUpdateUrlOverridden(extension->id())) {
    const GURL update_url =
        extension_management->GetEffectiveUpdateURL(*extension);
    DCHECK(!extension_urls::IsWebstoreUpdateUrl(update_url))
        << "Update URL cannot be overridden to be the webstore URL!";
    return false;
  }
  return sync_helper::IsSyncable(extension) &&
         !ExtensionPrefs::Get(context)->DoNotSync(extension->id());
}

bool IsExtensionIdle(const std::string& extension_id,
                     content::BrowserContext* context) {
  std::vector<std::string> ids_to_check;
  ids_to_check.push_back(extension_id);

  const Extension* extension =
      ExtensionRegistry::Get(context)
          ->GetExtensionById(extension_id, ExtensionRegistry::ENABLED);
  if (extension && extension->is_shared_module()) {
    // We have to check all the extensions that use this shared module for idle
    // to tell whether it is really 'idle'.
    SharedModuleService* service = ExtensionSystem::Get(context)
                                       ->extension_service()
                                       ->shared_module_service();
    std::unique_ptr<ExtensionSet> dependents =
        service->GetDependentExtensions(extension);
    for (ExtensionSet::const_iterator i = dependents->begin();
         i != dependents->end();
         i++) {
      ids_to_check.push_back((*i)->id());
    }
  }

  ProcessManager* process_manager = ProcessManager::Get(context);
  for (std::vector<std::string>::const_iterator i = ids_to_check.begin();
       i != ids_to_check.end();
       i++) {
    const std::string id = (*i);
    ExtensionHost* host = process_manager->GetBackgroundHostForExtension(id);
    if (host)
      return false;

    scoped_refptr<content::SiteInstance> site_instance =
        process_manager->GetSiteInstanceForURL(
            Extension::GetBaseURLFromExtensionId(id));
    if (site_instance && site_instance->HasProcess())
      return false;

    if (!process_manager->GetRenderFrameHostsForExtension(id).empty())
      return false;
  }
  return true;
}

base::Value::Dict GetExtensionInfo(const Extension* extension) {
  DCHECK(extension);
  base::Value::Dict dict;

  dict.Set("id", extension->id());
  dict.Set("name", extension->name());

  GURL icon = extensions::ExtensionIconSource::GetIconURL(
      extension, extension_misc::EXTENSION_ICON_SMALLISH,
      ExtensionIconSet::MATCH_BIGGER,
      false);  // Not grayscale.
  dict.Set("icon", icon.spec());

  return dict;
}

const gfx::ImageSkia& GetDefaultAppIcon() {
  return *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
      IDR_APP_DEFAULT_ICON);
}

const gfx::ImageSkia& GetDefaultExtensionIcon() {
  return *ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
      IDR_EXTENSION_DEFAULT_ICON);
}

std::unique_ptr<const PermissionSet> GetInstallPromptPermissionSetForExtension(
    const Extension* extension,
    Profile* profile,
    bool include_optional_permissions) {
  // Initialize permissions if they have not already been set so that
  // any transformations are correctly reflected in the install prompt.
  PermissionsUpdater(profile, PermissionsUpdater::INIT_FLAG_TRANSIENT)
      .InitializePermissions(extension);

  std::unique_ptr<const PermissionSet> permissions_to_display =
      extension->permissions_data()->active_permissions().Clone();

  if (include_optional_permissions) {
    const PermissionSet& optional_permissions =
        PermissionsParser::GetOptionalPermissions(extension);
    permissions_to_display = PermissionSet::CreateUnion(*permissions_to_display,
                                                        optional_permissions);
  }
  return permissions_to_display;
}

std::vector<content::BrowserContext*> GetAllRelatedProfiles(
    Profile* profile,
    const Extension& extension) {
  std::vector<content::BrowserContext*> related_contexts;
  related_contexts.push_back(profile->GetOriginalProfile());

  // The returned `related_contexts` should include all the related incognito
  // profiles if the extension is globally allowed in incognito (this is a
  // global, rather than per-profile toggle - this is why we it can be checked
  // globally here, rather than once for every incognito profile looped over
  // below).
  if (IsIncognitoEnabled(extension.id(), profile)) {
    std::vector<Profile*> off_the_record_profiles =
        profile->GetAllOffTheRecordProfiles();
    related_contexts.reserve(related_contexts.size() +
                             off_the_record_profiles.size());
    for (Profile* off_the_record_profile : off_the_record_profiles)
      related_contexts.push_back(off_the_record_profile);
  }

  return related_contexts;
}

}  // namespace util
}  // namespace extensions


text:
namespace nspace{
  template<typename ScalarResult, typename MatrixInput>
  class MatrixMinimumElement{
  public:
    static inline void operation(ScalarResult & minimum, const MatrixInput & mat){
      minimum = mat(0,0);
      for(int i=0; i < mat.rows();i++){
        for(int j=0; j < mat.cols();j++){
          if(minimum> mat(i,j))minimum=mat(i,j);
        }
      }
    }
  };
}

redpajama_set_name: RedPajamaGithub


text:
import React, {useState, FC} from 'react'
import {
  Input,
  Icon,
  IconFont,
  ComponentStatus,
  DropdownMenu,
  DropdownDivider,
  DropdownItem,
  ClickOutside,
} from '@influxdata/clockface'

// Actions
import {search} from 'src/eventViewer/components/EventViewer.reducer'

// Utils
import {isSearchInputValid} from 'src/eventViewer/utils/search'

// Types
import {EventViewerChildProps} from 'src/eventViewer/types'

const SUGGESTION_CLASS = 'status-search-bar--suggestion'

type Props = EventViewerChildProps & {
  placeholder?: string
  exampleSearches: string[]
}

const SearchBar: FC<Props> = ({
  placeholder,
  exampleSearches,
  state,
  dispatch,
  loadRows,
}) => {
  const [isFocused, setIsFocused] = useState(false)

  const inputStatus = isSearchInputValid(state.searchInput)
    ? ComponentStatus.Default
    : ComponentStatus.Error

  const handleClickSuggestion = (suggestion: string) => {
    search(state, dispatch, loadRows, suggestion, true)
    setIsFocused(false)
  }

  const handleClickOutside = e => {
    const didClickSuggestion =
      e.target.classList.contains(SUGGESTION_CLASS) ||
      e.target.parentNode.classList.contains(SUGGESTION_CLASS)

    if (!didClickSuggestion) {
      setIsFocused(false)
    }
  }

  return (
    <div className="status-search-bar">
      <ClickOutside onClickOutside={handleClickOutside}>
        <Input
          icon={IconFont.Search}
          placeholder={placeholder}
          style={{width: '100%'}}
          value={state.searchInput}
          status={inputStatus}
          onChange={e => search(state, dispatch, loadRows, e.target.value)}
          onFocus={() => setIsFocused(true)}
          testID="check-status-input"
        />
      </ClickOutside>
      {state.searchInput.trim() !== '' && (
        <div
          className="status-search-bar--clear"
          onClick={() => search(state, dispatch, loadRows, '', true)}
        >
          <Icon glyph={IconFont.Remove} />
        </div>
      )}
      {isFocused && (
        <DropdownMenu
          testID="check-status-dropdown"
          className="status-search-bar--suggestions"
          noScrollX={true}
          noScrollY={true}
        >
          <DropdownDivider text="Examples" />
          {exampleSearches.map(s => (
            <DropdownItem
              key={s}
              value={s}
              className={SUGGESTION_CLASS}
              onClick={handleClickSuggestion}
            >
              {s}
            </DropdownItem>
          ))}
        </DropdownMenu>
      )}
    </div>
  )
}

export default SearchBar


text:
package de.paul_woitaschek.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity
      implements NavigationView.OnNavigationItemSelectedListener {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);

      NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
      navigationView.setNavigationItemSelectedListener(this);

      if (savedInstanceState == null) {
         getSupportFragmentManager().beginTransaction()
               .replace(R.id.fragmentContainer, new MainFragment(), "mainfragment")
               .commit();
      }

      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
         int fullscreenFlags = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) ? View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN : 0;
         getWindow().getDecorView().setSystemUiVisibility(fullscreenFlags);
      }
   }

   @Override
   public void onBackPressed() {
      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
      if (drawer.isDrawerOpen(GravityCompat.START)) {
         drawer.closeDrawer(GravityCompat.START);
      } else {
         super.onBackPressed();
      }
   }

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

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

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

      return super.onOptionsItemSelected(item);
   }

   @SuppressWarnings("StatementWithEmptyBody")
   @Override
   public boolean onNavigationItemSelected(MenuItem item) {
      // Handle navigation view item clicks here.
      int id = item.getItemId();

      if (id == R.id.nav_camera) {
         // Handle the camera action
      } else if (id == R.id.nav_gallery) {

      } else if (id == R.id.nav_slideshow) {

      } else if (id == R.id.nav_manage) {

      } else if (id == R.id.nav_share) {

      } else if (id == R.id.nav_send) {

      }

      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
      drawer.closeDrawer(GravityCompat.START);
      return true;
   }
}


text:
var
  fs = require('fs'),
  path = require('path');

var
  objects = {}
  files = {
    install : '../install/oos_utils_install.sql',
    uninstall : '../install/oos_utils_uninstall.sql',
    createSynonyms : '../install/create_synonyms.sql',
    createGrants : '../install/grant_to_oos_utils.sql'
  },
  preInstall = {
    prereqs : '../source/scripts/prereqs.sql'
  },
  postInstall = {
    recompile : '../source/scripts/recompile.sql'
  }
;

// Tables
objects.tables = {};

objects.tables.oos_util_values = {
  src : '../source/tables/oos_util_values.sql',
  uninstall: 'drop table oos_util_values;'
};

// Data
objects.data = {};

objects.data.oos_util_values = {
  src : '../data/oos_util_values.sql'
};

// Packages
objects.packages = {
};

var packages = fs.readdirSync(path.resolve(__dirname,'../source/packages'));
for (var i = 0; i < packages.length; i++){
  var ext = path.extname(packages[i]);

  if (ext === '.pks'){
    var packageName = packages[i].slice(0, (-1 * ext.length));
    objects.packages[packageName] = {
      pks : '../source/packages/' + packageName + '.pks',
      pkb : '../source/packages/' + packageName + '.pkb'
    }
  }//if
}//packages

module.exports.objects = objects;
module.exports.files = files;
module.exports.preInstall = preInstall;
module.exports.postInstall = postInstall;


text:
using System.Collections.Generic;

using Decider.Csp.Integer;

namespace Decider.Csp.Global
{
	internal class Node
	{
		internal int Index { get; set; }
		internal int Link { get; set; }
		internal LinkedList<Node> AdjoiningNodes { get; set; }
		internal string Label { get; private set; }
		internal int CycleIndex { get; set; }

		internal Node()
		{
			this.AdjoiningNodes = new LinkedList<Node>();
			this.Index = -1;
			this.Link = -1;
			this.CycleIndex = -1;
		}

		internal Node(string label)
			: this()
		{
			this.Label = label;
		}

		public override string ToString()
		{
			return this.Label;
		}
	}

	internal class NodeVariable : Node
	{
		internal VariableInteger Variable { get; set; }

		internal NodeVariable(VariableInteger variable, string label)
			: base(label)
		{
			this.Variable = variable;
		}

		internal NodeVariable(VariableInteger variable)
		{
			this.Variable = variable;
		}

	}

	internal class NodeValue : Node
	{
		internal int Value { get; set; }

		internal NodeValue(int value, string label)
			: base(label)
		{
			this.Value = value;
		}

		internal NodeValue(int value)
		{
			this.Value = value;
		}
	}
}


text:
<?php

namespace Spaark\CompositeUtils\Model\Collection\ListCollection;

use Spaark\CompositeUtils\Model\Collection\Collection;

/**
 * Represents an abstract collection which acts as a list of items
 */
interface ArrayList extends Collection
{
    /**
     * Adds a new item to the end of the list
     *
     * @param ValueType $item The item to add
     */
    public function add($item);

    /**
     * Adds a new item at the specified position
     *
     * @param int $index The index to set
     * @param ValueType $value The value to set
     */
    public function set(int $index, $value);

    /**
     * Remove items from the list, and optionally replace them
     *
     * @param int $offset The offset to cut out
     * @param int $length The number of elements to remove
     * @param array $items Items to add
     */
    public function splice
    (
        int $offset,
        ?int$length = null,
        array $items = []
    );

    /**
     * Gets the item, looking it up by the specified index
     *
     * @param int $index The index to get
     * @return ValueType The item
     */
    public function get(int $index);

    /**
     * Removes an item from the list, specified by its index
     *
     * @param int $index The index of the item to remove
     */
    public function remove(int $index);
}


text:
{-# LANGUAGE CPP #-}
{-# LANGUAGE TypeFamilies, FlexibleContexts #-}
module Database.Persist.Class.PersistUnique
    ( PersistUnique (..)
    , getByValue
    , insertBy
    , replaceUnique
    , checkUnique
    , onlyUnique
    ) where

import Database.Persist.Types
import qualified Prelude
import Prelude hiding ((++))

import Control.Exception (throwIO)
import Control.Monad (liftM, when)
import Control.Monad.IO.Class (liftIO)
import Data.List ((\\))

import Control.Monad.Trans.Reader   ( ReaderT  )
import Control.Monad.IO.Class (MonadIO)

import Database.Persist.Class.PersistStore
import Database.Persist.Class.PersistEntity
import Data.Monoid (mappend)
import Data.Text (unpack, Text)

-- | Queries against 'Unique' keys (other than the id 'Key').
--
-- Please read the general Persistent documentation to learn how to create
-- 'Unique' keys.
--
-- Using this with an Entity without a Unique key leads to undefined behavior.
-- A few of these functions require a *single* 'Unique', so using an Entity with multiple 'Unique's is also undefined. In these cases persistent's goal is to throw an exception as soon as possible, but persistent is still transitioning to that.
--
-- SQL backends automatically create uniqueness constraints, but for MongoDB you must manually place a unique index on a field to have a uniqueness constraint.
--
-- Some functions in this module (insertUnique, insertBy, and replaceUnique) first query the unique indexes to check for conflicts.
-- You could instead optimistically attempt to perform the operation (e.g. replace instead of replaceUnique). However,
--
--  * there is some fragility to trying to catch the correct exception and determing the column of failure.
--
--  * an exception will automatically abort the current SQL transaction
class PersistStore backend => PersistUnique backend where
    -- | Get a record by unique key, if available. Returns also the identifier.
    getBy :: (MonadIO m, backend ~ PersistEntityBackend val, PersistEntity val) => Unique val -> ReaderT backend m (Maybe (Entity val))

    -- | Delete a specific record by unique key. Does nothing if no record
    -- matches.
    deleteBy :: (MonadIO m, PersistEntityBackend val ~ backend, PersistEntity val) => Unique val -> ReaderT backend m ()

    -- | Like 'insert', but returns 'Nothing' when the record
    -- couldn't be inserted because of a uniqueness constraint.
    insertUnique :: (MonadIO m, PersistEntityBackend val ~ backend, PersistEntity val) => val -> ReaderT backend m (Maybe (Key val))
    insertUnique datum = do
        conflict <- checkUnique datum
        case conflict of
          Nothing -> Just `liftM` insert datum
          Just _ -> return Nothing

    -- | update based on a uniquness constraint or insert
    --
    -- insert the new record if it does not exist
    -- update the existing record that matches the uniqueness contraint
    --
    -- Throws an exception if there is more than 1 uniqueness contraint
    upsert :: (MonadIO m, PersistEntityBackend val ~ backend, PersistEntity val)
           => val          -- ^ new record to insert
           -> [Update val] -- ^ updates to perform if the record already exists.
                           -- leaving this empty is the equivalent of performing a 'repsert' on a unique key.
           -> ReaderT backend m (Entity val) -- ^ the record in the database after the operation
    upsert record updates = do
        uniqueKey <- onlyUnique record
        mExists <- getBy uniqueKey
        k <- case mExists of
            Just (Entity k _) -> do
              when (null updates) (replace k record)
              return k
            Nothing           -> insert record
        Entity k `liftM` updateGet k updates

-- | Insert a value, checking for conflicts with any unique constraints.  If a
-- duplicate exists in the database, it is returned as 'Left'. Otherwise, the
-- new 'Key is returned as 'Right'.
insertBy :: (MonadIO m, PersistEntity val, PersistUnique backend, PersistEntityBackend val ~ backend)
         => val -> ReaderT backend m (Either (Entity val) (Key val))
insertBy val = do
    res <- getByValue val
    case res of
      Nothing -> Right `liftM` insert val
      Just z -> return $ Left z

-- | Return the single unique key for a record
onlyUnique :: (MonadIO m, PersistEntity val, PersistUnique backend, PersistEntityBackend val ~ backend)
           => val -> ReaderT backend m (Unique val)
onlyUnique record = case onlyUniqueEither record of
    Right u -> return u
    Left us -> requireUniques record us >>= liftIO . throwIO . OnlyUniqueException . show . length

onlyUniqueEither :: (PersistEntity val) => val -> Either [Unique val] (Unique val)
onlyUniqueEither record = case persistUniqueKeys record of
    (u:[]) -> Right u
    us     -> Left us

-- | A modification of 'getBy', which takes the 'PersistEntity' itself instead
-- of a 'Unique' record. Returns a record matching /one/ of the unique keys. This
-- function makes the most sense on entities with a single 'Unique'
-- constructor.
getByValue :: (MonadIO m, PersistEntity record, PersistUnique backend, PersistEntityBackend record ~ backend)
           => record -> ReaderT backend m (Maybe (Entity record))
getByValue record = checkUniques =<< requireUniques record (persistUniqueKeys record)
  where
    checkUniques [] = return Nothing
    checkUniques (x:xs) = do
        y <- getBy x
        case y of
            Nothing -> checkUniques xs
            Just z -> return $ Just z

requireUniques :: (MonadIO m, PersistEntity record) => record -> [Unique record] -> m [Unique record]
requireUniques record [] = liftIO $ throwIO $ userError errorMsg
  where
    errorMsg = "getByValue: " `mappend` unpack (recordName record) `mappend` " does not have any Unique"
requireUniques _ xs = return xs

-- TODO: expose this to users
recordName :: (PersistEntity record) => record -> Text
recordName = unHaskellName . entityHaskell . entityDef . Just

-- | Attempt to replace the record of the given key with the given new record.
-- First query the unique fields to make sure the replacement maintains uniqueness constraints.
-- Return 'Nothing' if the replacement was made.
-- If uniqueness is violated, return a 'Just' with the 'Unique' violation
--
-- Since 1.2.2.0
replaceUnique :: (MonadIO m, Eq record, Eq (Unique record), PersistEntityBackend record ~ backend, PersistEntity record, PersistUnique backend)
              => Key record -> record -> ReaderT backend m (Maybe (Unique record))
replaceUnique key datumNew = getJust key >>= replaceOriginal
  where
    uniqueKeysNew = persistUniqueKeys datumNew
    replaceOriginal original = do
        conflict <- checkUniqueKeys changedKeys
        case conflict of
          Nothing -> replace key datumNew >> return Nothing
          (Just conflictingKey) -> return $ Just conflictingKey
      where
        changedKeys = uniqueKeysNew \\ uniqueKeysOriginal
        uniqueKeysOriginal = persistUniqueKeys original

-- | Check whether there are any conflicts for unique keys with this entity and
-- existing entities in the database.
--
-- Returns 'Nothing' if the entity would be unique, and could thus safely be inserted.
-- on a conflict returns the conflicting key
checkUnique :: (MonadIO m, PersistEntityBackend record ~ backend, PersistEntity record, PersistUnique backend)
            => record -> ReaderT backend m (Maybe (Unique record))
checkUnique = checkUniqueKeys . persistUniqueKeys

checkUniqueKeys :: (MonadIO m, PersistEntity record, PersistUnique backend, PersistEntityBackend record ~ backend)
                => [Unique record] -> ReaderT backend m (Maybe (Unique record))
checkUniqueKeys [] = return Nothing
checkUniqueKeys (x:xs) = do
    y <- getBy x
    case y of
        Nothing -> checkUniqueKeys xs
        Just _ -> return (Just x)


text:
class Debunker
  class Command::ShowInfo < Debunker::ClassCommand
    extend Debunker::Helpers::BaseHelpers

    command_options :shellwords => false, :interpolate => false

    def initialize(*)
      super

      @used_super = nil
    end

    def options(opt)
      opt.on :s, :super, "Select the 'super' method. Can be repeated to traverse the ancestors", :as => :count
      opt.on :l, "line-numbers", "Show line numbers"
      opt.on :b, "base-one", "Show line numbers but start numbering at 1 (useful for `amend-line` and `play` commands)"
      opt.on :a, :all,  "Show all definitions and monkeypatches of the module/class"
    end

    def process
      code_object = Debunker::CodeObject.lookup(obj_name, _debunker_, :super => opts[:super])
      raise CommandError, no_definition_message if !code_object
      @original_code_object = code_object

      if !obj_name && code_object.c_module? && !opts[:all]
        result = "Warning: You're inside an object, whose class is defined by means\n" +
                 "         of the C Ruby API. Debunker cannot display the information for\n" +
                 "         this class."
        if code_object.candidates.any?
          result += "\n         However, you can view monkey-patches applied to this class.\n" +
                    "         Just execute the same command with the '--all' switch."
        end
      elsif show_all_modules?(code_object)
        # show all monkey patches for a module

        result = content_and_headers_for_all_module_candidates(code_object)
      else
        # show a specific code object
        co = code_object_with_accessible_source(code_object)
        result = content_and_header_for_code_object(co)
      end

      set_file_and_dir_locals(code_object.source_file)
      _debunker_.pager.page result
    end

    # This method checks whether the `code_object` is a WrappedModule,
    # if it is, then it returns the first candidate (monkeypatch) with
    # accessible source (or docs). If `code_object` is not a WrappedModule (i.e a
    # method or a command) then the `code_object` itself is just
    # returned.
    #
    # @return [Debunker::WrappedModule, Debunker::Method, Debunker::Command]
    def code_object_with_accessible_source(code_object)
      if code_object.is_a?(WrappedModule)
        candidate = code_object.candidates.find(&:source)
        if candidate
          return candidate
        else
          raise CommandError, no_definition_message if !valid_superclass?(code_object)

          @used_super = true
          code_object_with_accessible_source(code_object.super)
        end
      else
        code_object
      end
    end

    def valid_superclass?(code_object)
      code_object.super && code_object.super.wrapped != Object
    end

    def content_and_header_for_code_object(code_object)
      header(code_object) << content_for(code_object)
    end

    def content_and_headers_for_all_module_candidates(mod)
      result = "Found #{mod.number_of_candidates} candidates for `#{mod.name}` definition:\n"
      mod.number_of_candidates.times do |v|
        candidate = mod.candidate(v)
        begin
          result << "\nCandidate #{v+1}/#{mod.number_of_candidates}: #{candidate.source_file} @ line #{candidate.source_line}:\n"
          content = content_for(candidate)

          result << "Number of lines: #{content.lines.count}\n\n" << content
        rescue Debunker::RescuableException
          result << "\nNo content found.\n"
          next
        end
      end
      result
    end

    def no_definition_message
      "Couldn't locate a definition for #{obj_name}!"
    end

    # Generate a header (meta-data information) for all the code
    # object types: methods, modules, commands, procs...
    def header(code_object)
      file_name, line_num = file_and_line_for(code_object)
      h = "\n#{Debunker::Helpers::Text.bold('From:')} #{file_name} "
      h << code_object_header(code_object, line_num)
      h << "\n#{Debunker::Helpers::Text.bold('Number of lines:')} " <<
        "#{content_for(code_object).lines.count}\n\n"
      h << Helpers::Text.bold('** Warning:') << " Cannot find code for #{@original_code_object.nonblank_name}. Showing superclass #{code_object.nonblank_name} instead. **\n\n" if @used_super
      h
    end

    def code_object_header(code_object, line_num)
      if code_object.real_method_object?
        method_header(code_object, line_num)

        # It sucks we have to test for both Debunker::WrappedModule and WrappedModule::Candidate,
        # probably indicates a deep refactor needs to happen in those classes.
      elsif code_object.is_a?(Debunker::WrappedModule) || code_object.is_a?(Debunker::WrappedModule::Candidate)
        module_header(code_object, line_num)
      else
        ""
      end
    end

    def method_header(code_object, line_num)
      h = ""
      h << (code_object.c_method? ? "(C Method):" : "@ line #{line_num}:")
      h << method_sections(code_object)[:owner]
      h << method_sections(code_object)[:visibility]
      h << method_sections(code_object)[:signature]
      h
    end

    def module_header(code_object, line_num)
      h = ""
      h << "@ line #{line_num}:\n"
      h << text.bold(code_object.module? ? "Module" : "Class")
      h << " #{text.bold('name:')} #{code_object.nonblank_name}"

      if code_object.number_of_candidates > 1
        h << (text.bold("\nNumber of monkeypatches: ") << code_object.number_of_candidates.to_s)
        h << ". Use the `-a` option to display all available monkeypatches"
      end
      h
    end

    def method_sections(code_object)
      {
        :owner => "\n#{text.bold("Owner:")} #{code_object.owner || "N/A"}\n",
        :visibility => "#{text.bold("Visibility:")} #{code_object.visibility}",
        :signature => "\n#{text.bold("Signature:")} #{code_object.signature}"
      }.merge(header_options) { |key, old, new| (new && old).to_s }
    end

    def header_options
      {
        :owner => true,
        :visibility => true,
        :signature => nil
      }
    end

    def show_all_modules?(code_object)
      code_object.is_a?(Debunker::WrappedModule) && opts.present?(:all)
    end

    def obj_name
      @obj_name ||= args.empty? ? nil : args.join(' ')
    end

    def use_line_numbers?
      opts.present?(:b) || opts.present?(:l)
    end

    def start_line_for(code_object)
      if opts.present?(:'base-one')
        1
      else
        code_object.source_line || 1
      end
    end

    # takes into account possible yard docs, and returns yard_file / yard_line
    # Also adjusts for start line of comments (using start_line_for), which it has to infer
    # by subtracting number of lines of comment from start line of code_object
    def file_and_line_for(code_object)
      if code_object.module_with_yard_docs?
        [code_object.yard_file, code_object.yard_line]
      else
        [code_object.source_file, start_line_for(code_object)]
      end
    end

    def complete(input)
      if input =~ /([^ ]*)#([a-z0-9_]*)\z/
        prefix, search = [$1, $2]
        methods = begin
                    Debunker::Method.all_from_class(binding.eval(prefix))
                  rescue RescuableException
                    return super
                  end
        methods.map do |method|
          [prefix, method.name].join('#') if method.name.start_with?(search)
        end.compact
      else
        super
      end
    end
  end
end


text:
.swipe-header-left-button {
    float: left;
}

.swipe-header-right-button {
    float: right;
}


text:
describe('Trak', function() {
  var Exceptions;
  Exceptions = null;
  before(function(done) {
    sinon.stub(trak.io, 'track');
    sinon.stub(trak.io, 'url').returns('page_url');
    sinon.stub(trak.io, 'page_title').returns('A page title');
    sinon.stub(trak.io, 'should_track').returns(true);
    return requirejs(['exceptions'], function(E) {
      Exceptions = E;
      return done();
    });
  });
  after(function() {
    trak.io.track.restore();
    trak.io.page_title.restore();
    trak.io.url.restore();
    return trak.io.should_track.restore();
  });
  describe('#page_view()', function() {
    return it("should call #track", function() {
      trak.io.page_view();
      return trak.io.track.should.have.been.calledWith('page_view', {
        url: 'page_url',
        page_title: 'A page title'
      });
    });
  });
  describe('#page_view(url)', function() {
    return it("should call #track", function() {
      trak.io.page_view('custom_page_url');
      return trak.io.track.should.have.been.calledWith('page_view', {
        url: 'custom_page_url',
        page_title: 'A page title'
      });
    });
  });
  return describe('#page_view(url, title)', function() {
    return it("should call #track", function() {
      trak.io.page_view('custom_page_url', 'custom page title');
      return trak.io.track.should.have.been.calledWith('page_view', {
        url: 'custom_page_url',
        page_title: 'custom page title'
      });
    });
  });
});


text:
using System;

namespace SkiaSharpSample
{
	[Flags]
	public enum SamplePlatforms
	{
		iOS = 1 << 0,
		Android = 1 << 1,
		OSX = 1 << 2,
		WindowsDesktop = 1 << 3,
		UWP = 1 << 4,
		tvOS = 1 << 5,

		All = iOS | Android | OSX | WindowsDesktop | UWP | tvOS,

		AllWindows = WindowsDesktop | UWP,
		AllAndroid = Android,
		AlliOS = iOS | tvOS,
		AllApple = iOS | tvOS | OSX,
		AllMobile = iOS | tvOS | Android | UWP,
		AllDesktop = WindowsDesktop | OSX,
	}
}


text:
<?php include(STATIC_DIR.'/inc/header_inner.php'); ?>

<form action="" method="post" class="validate" enctype="multipart/form-data">

        <?php foreach ($sections as $s){ ?>

            <?php $section = $template->getSection($s->name); ?>

                <section class="ui_input_wrapper <?= $s->name; ?> <?= ($default_section != $s->name ? 'uim-hidden' : ''); ?>">

                    <?php foreach ($section->input as $input){ ?>
                        <?php if (!in_array($input->attr->name, array())){ ?>
                            <?php
                                switch ($input->attr->type){
                                    case 'hidden':
                                        $hidden[] = $input;
                                    break;
                                    case 'url':
                                        $url[] = $input;
                                        $url[0]->attr->value = $snippets->{$input->attr->name};
                                    break;
                                    case 'group':
                                        if (!is_array($input->input)){
                                            $input->input = $input->{0};
                                            unset($input->{0});
                                        }
                                        echo '
';
                                            echo '
';
                                                foreach ($input->input as $group_input){
                                                    echo $template->buildInput($group_input, ($snippets->fields->{$group_input->attr->name} ? $snippets->fields->{$group_input->attr->name} : $snippets->{$group_input->attr->name}));
                                                }
                                            echo '
';
                                        echo '
';
                                    break;
                                    default:
                                        echo '
';
                                                echo $template->buildInput($input, ($snippets->fields->{$input->attr->name} ? $snippets->fields->{$input->attr->name} : $snippets->{$input->attr->name}));
                                        echo '
';
                                    break;
                                }
                            ?>
                        <?php } ?>
                    <?php } ?>

                <?php if ($hidden || $snippets_parentid || $snippets_template){ ?>

                        <?php if ($hidden){ ?>

                            <?php $hidden_object = array(); ?>

                            <?php foreach ($hidden as $input){ ?>
                                <?php $hidden_object[$input->attr->name] = $input->attr->value; ?>
                                <?= $template->buildInput($input, ($snippets->fields->{$input->attr->name} ? $snippets->fields->{$input->attr->name} : $snippets->{$input->attr->name})); ?>

                            <?php } ?>

                            <?php $hidden_object = (object) $hidden_object; ?>

                        <?php } ?>

                        <?php if ($snippets_parentid){ ?>
                            <input type="hidden" name="parentid" value="<?= $snippets_parentid; ?>" />
                        <?php } ?>

                        <?php if ($snippets_template){ ?>
                            <input type="hidden" name="template" value="<?= $snippets_template; ?>" />
                        <?php } ?>

                        <?php if (isset($snippets->deletable)){ ?>
                            <input type="hidden" name="deletable" value="<?= $snippets->deletable; ?>" />
                        <?php } ?>

                        <?php if (isset($snippets->editable)){ ?>
                            <input type="hidden" name="editable" value="<?= $snippets->editable; ?>" />
                        <?php } ?>

                        <?php if (isset($snippets->publishable)){ ?>
                            <input type="hidden" name="publishable" value="<?= $snippets->publishable; ?>" />
                        <?php } ?>

                        <?php if (isset($snippets->subpagable)){ ?>
                            <input type="hidden" name="subpagable" value="<?= $snippets->subpagable; ?>" />
                        <?php } ?>

				<?php } ?>

                        <?php if ($id){ ?>
                            <input type="hidden" name="id" value="<?= $id; ?>" />
                        <?php } ?>

		<?php } ?>

			<button type="submit" class="uim-button green save-page">Edit</button>

        <?php if($url[0]) {?>

    			<?= $template->buildInput($url[0], $url[0]->attr->value); ?>

        <?php }?>

</form>

<?php include(STATIC_DIR.'/inc/footer_inner.php'); ?>


text:
<?php

namespace Enqueue\Util;

use Ramsey\Uuid\Uuid as RamseyUuid;
use Rhumsaa\Uuid\Uuid as RhumsaaUuid;

class UUID
{
    /**
     * @return string
     */
    public static function generate()
    {
        if (class_exists(RamseyUuid::class)) {
            return RamseyUuid::uuid4()->toString();
        }

        return RhumsaaUuid::uuid4()->toString();
    }
}


text:
package com.dianping.cat.message.context;

import javax.servlet.http.HttpServletRequest;

import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;

import com.dianping.cat.ComponentTestCase;
import com.dianping.cat.message.Transaction;

public class MessageContextTest extends ComponentTestCase {
	@Test
	public void testInstrument() {
		int index = 1;
		TraceContext ctx = TraceContextHelper.threadLocal();
		Transaction t = ctx.newTransaction("TransactionType", "TransactionName-" + (index++));

		try {
			Transaction t2 = ctx.newTransaction("TransactionType", "TransactionName-" + (index++));

			ctx.newEvent("EventType", "EventName-" + (index++)).success().complete();
			ctx.newEvent("EventType", "EventName-" + (index++)).success().complete();
			ctx.newEvent("EventType", "EventName-" + (index++)).success().complete();

			t2.success().complete();

			ctx.newEvent("EventType", "EventName-" + (index++)).success().complete();
			ctx.newEvent("EventType", "EventName-" + (index++)).success().complete();
			ctx.newEvent("EventType", "EventName-" + (index++)).success().complete();

			ctx.newHeartbeat("HeartbeatType", "HeartbeatName-" + (index++)).success().complete();
			ctx.newHeartbeat("HeartbeatType", "HeartbeatName-" + (index++)).success().complete();

			ctx.newTrace("OrderService", "placeOrder").success().complete();

			t.success();
		} catch (Exception e) {
			t.setStatus(e);
		} finally {
			t.complete();
		}
	}

	@Test
	@Ignore
	public void testAsyncContext() {
		TraceContext ctx = TraceContextHelper.threadLocal();

		Assert.assertNotNull(ctx);

		HttpServletRequest req = null;

		TraceContextHelper.extractFrom(req);
	}
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<workingSetManager>
<workingSet aggregate="true" factoryID="org.eclipse.ui.internal.WorkingSetFactory" id="1508786179188_0" label="Window Working Set" name="Aggregate for window 1508786179188"/>
</workingSetManager>


text:
<?php
/**
 * Created by JetBrains PhpStorm.
 * User: joey
 * Date: 1/28/13
 * Time: 3:15 AM
 * To change this template use File | Settings | File Templates.
 */

class Infusionsoft_LowLevelMockService {
    var $data;
    public function __construct(Infusionsoft_AppData $data){
        $this->data = $data;
    }
}


text:
package trafficstats

import (
	"database/sql"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"

	"github.com/apache/trafficcontrol/lib/go-tc"

	"github.com/apache/trafficcontrol/lib/go-log"
	"github.com/apache/trafficcontrol/lib/go-rfc"
	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/api"
	"github.com/apache/trafficcontrol/traffic_ops/traffic_ops_golang/tenant"

	influx "github.com/influxdata/influxdb/client/v2"
)

const (
	dsTenantIDFromXMLIDQuery = `
		SELECT tenant_id
		FROM deliveryservice
		WHERE xml_id = $1`

	xmlidFromIDQuery = `
		SELECT xml_id
		FROM deliveryservice
		WHERE id = $1`

	// TODO: Pretty sure all of this could actually be calculated using the fetched data (assuming an
	// interval is given). Check to see if that's faster than doing another synchronous HTTP request.
	dsSummaryQuery = `
		SELECT mean(value) AS "average",
		       percentile(value, 5) AS "fifthPercentile",
		       percentile(value, 95) AS "ninetyFifthPercentile",
		       percentile(value, 98) AS "ninetyEighthPercentile",
		       min(value) AS "min",
		       max(value) AS "max",
		       count(value) AS "count"
		FROM "%s"."monthly"."%s.ds.1min"
		WHERE time >= $start
		AND time <= $end
		AND cachegroup = 'total'
		AND deliveryservice = $xmlid`

	dsSeriesQuery = `
		SELECT mean(value)
		FROM "%s"."monthly"."%s.ds.1min"
		WHERE cachegroup = 'total'
		AND deliveryservice = $xmlid
		AND time >= $start
		AND time <= $end
		GROUP BY time(%s, %s), cachegroup%s`
)

func dsConfigFromRequest(r *http.Request, i *api.APIInfo) (tc.TrafficDSStatsConfig, int, error) {
	c := tc.TrafficDSStatsConfig{}
	statsConfig, rc, e := tsConfigFromRequest(r, i)
	if e != nil {
		return c, rc, e
	}
	c.TrafficStatsConfig = statsConfig
	c.MetricType = i.Params["metricType"]
	if _, found := findMetric(i.Config.ConfigTrafficOpsGolang.SupportedDSMetrics, c.MetricType); !found {
		e = fmt.Errorf("Metric is not supported: %s", c.MetricType)
		return c, http.StatusBadRequest, e
	}

	var ok bool
	if c.DeliveryService, ok = i.Params["deliveryServiceName"]; !ok {
		if c.DeliveryService, ok = i.Params["deliveryService"]; !ok {
			e = errors.New("You must specify deliveryService or deliveryServiceName!")
			return c, http.StatusBadRequest, e
		}

		if dsID, err := strconv.ParseUint(c.DeliveryService, 10, 64); err == nil {
			// sql.ErrNoRows does not *necessarily* mean the DS doesn't exist - an XMLID can simply
			// be numeric, and so it was wrong to treat it as an ID in the first place.
			xmlid := c.DeliveryService
			var exists bool
			if exists, c.DeliveryService, err = getXMLIDFromID(dsID, i.Tx.Tx); err != nil {
				log.Errorf("Converting DSID to XMLID: %v", err)
				e = errors.New("Internal Server Error")
				return c, http.StatusInternalServerError, e
			} else if !exists {
				c.DeliveryService = xmlid
			}
		}
	}

	return c, http.StatusOK, nil
}

// GetDSStats handler for getting deliveryservice stats
func GetDSStats(w http.ResponseWriter, r *http.Request) {
	// Perl didn't require "interval", but it would only return summary data if it was not given
	inf, userErr, sysErr, errCode := api.NewInfo(r, []string{"metricType", "startDate", "endDate"}, nil)
	tx := inf.Tx.Tx
	if userErr != nil || sysErr != nil {
		api.HandleErr(w, r, tx, errCode, userErr, sysErr)
		return
	}
	defer inf.Close()

	var c tc.TrafficDSStatsConfig
	if c, errCode, userErr = dsConfigFromRequest(r, inf); userErr != nil {
		sysErr = fmt.Errorf("Unable to process deliveryservice_stats request: %v", userErr)
		api.HandleErr(w, r, tx, errCode, userErr, sysErr)
		return
	}

	client, err := inf.CreateInfluxClient()
	if err != nil {
		errCode = http.StatusInternalServerError
		sysErr = err
		api.HandleErr(w, r, tx, errCode, nil, sysErr)
		return
	} else if client == nil {
		sysErr = errors.New("Traffic Stats is not configured, but DS stats were requested")
		errCode = http.StatusInternalServerError
		api.HandleErr(w, r, tx, errCode, nil, sysErr)
		return
	}
	defer (*client).Close()

	exists, dsTenant, err := dsTenantIDFromXMLID(c.DeliveryService, tx)
	if err != nil {
		sysErr = err
		errCode = http.StatusInternalServerError
		api.HandleErr(w, r, tx, errCode, nil, sysErr)
		return
	} else if !exists {
		userErr = fmt.Errorf("No such Delivery Service: %s", c.DeliveryService)
		errCode = http.StatusNotFound
		api.HandleErr(w, r, tx, errCode, userErr, nil)
		return
	}

	authorized, err := tenant.IsResourceAuthorizedToUserTx(int(dsTenant), inf.User, tx)
	if err != nil {
		api.HandleErr(w, r, tx, http.StatusInternalServerError, nil, err)
		return
	} else if !authorized {
		// If the Tenant is not authorized to use the resource, then we DON'T tell them that.
		// Instead, we don't disclose that such a Delivery Service exists at all - in keeping with
		// the behavior of /deliveryservices
		// This is different from what Perl used to do, but then again Perl didn't check tenancy at
		// all.
		userErr = fmt.Errorf("No such Delivery Service: %s", c.DeliveryService)
		sysErr = fmt.Errorf("GetDSStats: unauthorized Tenant (#%d) access", inf.User.TenantID)
		errCode = http.StatusNotFound
		api.HandleErr(w, r, tx, errCode, userErr, sysErr)
		return
	}

	if inf.Version.Major > 1 {
		handleRequest(w, r, client, c, inf)
	} else {
		handleLegacyRequest(w, r, client, c, inf)
	}
}

func handleRequest(w http.ResponseWriter, r *http.Request, client *influx.Client, cfg tc.TrafficDSStatsConfig, inf *api.APIInfo) {
	// TODO: as above, this could be done on TO itself, thus sending only one synchronous request
	// per hit on this endpoint, rather than the current two. Not sure if that's worth it for large
	// data sets, though.
	var resp tc.TrafficDSStatsResponse
	if !cfg.ExcludeSummary {
		summary, kBs, txns, err := getDSSummary(client, &cfg, inf.Config.ConfigInflux.DSDBName)

		if err != nil {
			sysErr := fmt.Errorf("Getting summary response from Influx: %v", err)
			api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, sysErr)
			return
		}

		// match Perl implementation and set summary to zero values if no data
		if summary != nil {
			resp.Summary = &tc.TrafficDSStatsSummary{
				TrafficStatsSummary: *summary,
				TotalKiloBytes:      kBs,
				TotalTransactions:   txns,
			}
		} else {
			resp.Summary = &tc.TrafficDSStatsSummary{}
		}

	}

	if !cfg.ExcludeSeries {
		series, err := getDSSeries(client, &cfg, inf.Config.ConfigInflux.DSDBName)

		if err != nil {
			sysErr := fmt.Errorf("Getting summary response from Influx: %v", err)
			api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, sysErr)
			return
		}

		// match Perl implementation and omit series if no data
		if series != nil {
			if !cfg.Unix {
				series.FormatTimestamps()
			}

			resp.Series = series
		}
	}

	var respObj struct {
		Response interface{} `json:"response"`
	}
	respObj.Response = resp

	respBts, err := json.Marshal(respObj)
	if err != nil {
		sysErr := fmt.Errorf("Marshalling response: %v", err)
		errCode := http.StatusInternalServerError
		api.HandleErr(w, r, inf.Tx.Tx, errCode, nil, sysErr)
		return
	}

	if cfg.Unix {
		w.Header().Set(rfc.ContentType, jsonWithUnixTimestamps.String())
	} else {
		w.Header().Set(rfc.ContentType, jsonWithRFCTimestamps.String())
	}
	w.Header().Set(http.CanonicalHeaderKey("vary"), http.CanonicalHeaderKey("Accept"))
	w.Write(append(respBts, '\n'))
}

func handleLegacyRequest(w http.ResponseWriter, r *http.Request, client *influx.Client, cfg tc.TrafficDSStatsConfig, inf *api.APIInfo) {
	// TODO: as above, this could be done on TO itself, thus sending only one synchronous request
	// per hit on this endpoint, rather than the current two. Not sure if that's worth it for large
	// data sets, though.
	var resp tc.TrafficDSStatsResponseV1
	if !cfg.ExcludeSummary {
		summary, kBs, txns, err := getDSSummary(client, &cfg, inf.Config.ConfigInflux.DSDBName)

		if err != nil {
			sysErr := fmt.Errorf("Getting summary response from Influx: %v", err)
			api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, sysErr)
			return
		}

		// match Perl implementation and set summary to zero values if no data
		if summary != nil {
			resp.Summary = &tc.LegacyTrafficDSStatsSummary{
				TrafficStatsSummary: *summary,
				TotalBytes:          kBs,
				TotalTransactions:   txns,
			}
		} else {
			resp.Summary = &tc.LegacyTrafficDSStatsSummary{}
		}

	}

	if !cfg.ExcludeSeries {
		series, err := getDSSeries(client, &cfg, inf.Config.ConfigInflux.DSDBName)

		if err != nil {
			sysErr := fmt.Errorf("Getting summary response from Influx: %v", err)
			api.HandleErr(w, r, inf.Tx.Tx, http.StatusInternalServerError, nil, sysErr)
			return
		}

		// match Perl implementation and omit series if no data
		if series != nil {
			if !cfg.Unix {
				series.FormatTimestamps()
			}

			resp.Series = series
		}
	}

	var respObj struct {
		Response interface{} `json:"response"`
	}
	respObj.Response = resp

	respBts, err := json.Marshal(respObj)
	if err != nil {
		sysErr := fmt.Errorf("Marshalling response: %v", err)
		errCode := http.StatusInternalServerError
		api.HandleErr(w, r, inf.Tx.Tx, errCode, nil, sysErr)
		return
	}

	if cfg.Unix {
		w.Header().Set(rfc.ContentType, jsonWithUnixTimestamps.String())
	} else {
		w.Header().Set(rfc.ContentType, jsonWithRFCTimestamps.String())
	}
	w.Header().Set(http.CanonicalHeaderKey("vary"), http.CanonicalHeaderKey("Accept"))
	w.Write(append(respBts, '\n'))
}

func getDSSummary(client *influx.Client, conf *tc.TrafficDSStatsConfig, db string) (*tc.TrafficStatsSummary, *float64, *float64, error) {
	qStr := fmt.Sprintf(dsSummaryQuery, db, conf.MetricType)
	q := influx.NewQueryWithParameters(qStr,
		db,
		"rfc3339", //this doesn't actually seem to have any effect...
		map[string]interface{}{
			"xmlid":    conf.DeliveryService,
			"start":    conf.Start,
			"end":      conf.End,
			"interval": string(conf.Interval),
		})
	ts, err := getSummary(db, q, client)
	if err != nil || ts == nil {
		return nil, nil, nil, err
	}

	var totalKB *float64
	var totalTXN *float64
	value := float64(ts.Count*60) * ts.Average
	if strings.HasPrefix(conf.MetricType, "kbps") {
		// TotalBytes is actually in units of kB....
		value /= 8
		totalKB = &value
	} else {
		totalTXN = &value
	}

	return ts, totalKB, totalTXN, nil
}

func dsTenantIDFromXMLID(xmlid string, tx *sql.Tx) (bool, uint, error) {
	row := tx.QueryRow(dsTenantIDFromXMLIDQuery, xmlid)
	var tid uint
	err := row.Scan(&tid)
	if err == sql.ErrNoRows {
		return false, 0, nil
	}
	return true, tid, err
}

func getXMLIDFromID(id uint64, tx *sql.Tx) (bool, string, error) {
	row := tx.QueryRow(xmlidFromIDQuery, id)
	var xmlid string
	err := row.Scan(&xmlid)
	if err == sql.ErrNoRows {
		return false, "", nil
	}
	return true, xmlid, err
}

func getDSSeries(client *influx.Client, conf *tc.TrafficDSStatsConfig, db string) (*tc.TrafficStatsSeries, error) {
	extraClauses := buildExtraClauses(&conf.TrafficStatsConfig)
	qStr := fmt.Sprintf(dsSeriesQuery, db, conf.MetricType, conf.Interval, conf.TrafficStatsConfig.OffsetString(), extraClauses)
	q := influx.NewQueryWithParameters(qStr,
		db,
		"rfc3339", // this doesn't seem to do anything...
		map[string]interface{}{
			"xmlid": conf.DeliveryService,
			"start": conf.Start,
			"end":   conf.End,
		})
	return getSeries(db, q, client)
}

func findMetric(slice []string, val string) (int, bool) {
	for i, item := range slice {
		if item == val {
			return i, true
		}
	}
	return -1, false
}


text:
.index {
	margin: 0px auto; width: 1200px; height: 100%;
}
.i_top {
	margin: 0px auto; width: 1000px; height: 100px; padding-top: 10px;
}
.i_top_logo {
	width: 472px; height: 81px; float: left;
}
.i_top_phone {
	width: 300px; height: 81px; float: right;
}
.i_news {
	margin: 0px auto; width: 1000px; height: 30px;
}
.i_news ul {
	padding-left: 75px;
}
.i_news ul li {
	width: 105px; height: 30px; text-align: center; float: left;
}
.i_news ul li a {
	color: rgb(74, 74, 74); text-decoration: none;
}
.i_news ul li a:hover {
	color: rgb(169, 23, 26); text-decoration: none;
}
.img_show {
	margin: 0px auto; left: 0px; top: 0px; width: 1200px; height: 420px; position: relative;
}
.login {
	background: url("../images/img/login_bk.png") no-repeat; left: 770px; top: 25px; width: 311px; height: 347px; position: absolute; _background: url(../images/img/login_bk2.png) no-repeat;
}
.login ul {
	width: 250px; height: 300px; padding-top: 30px; padding-left: 34px;
}
.h1 {
	text-align: left; color: rgb(35, 24, 21); font-family: "΢ÈíÑźÚ"; font-size: 20px;
}
.login ul li {

}
.login ul li a {
	text-decoration: underline;
}
.login ul li a:hover {
	text-decoration: underline;
}
.input_user {
	background: url("../images/img/login_user_bk.png") no-repeat; border: currentColor; border-image: none; width: 244px; height: 38px; line-height: 38px; text-indent: 35px;
}
.input_pas {
	background: url("../images/img/login_pas_bk.png") no-repeat; border: currentColor; border-image: none; width: 244px; height: 38px; line-height: 38px; text-indent: 35px;
}
.login_button {
	background: url("../images/img/login_bt.png") no-repeat; border: currentColor; border-image: none; width: 244px; height: 41px; cursor: pointer;
}
.white-con {
	background: rgb(255, 255, 255); margin: 0px auto; width: 990px; height: auto !important; min-height: 680px; _height: 680px;
}
.help_con {
	background: rgb(255, 255, 255); width: 850px; height: auto !important; float: right; min-height: 680px;
}
.con_left {
	background: rgb(255, 255, 255); width: 199px; height: auto !important; border-right-color: rgb(193, 16, 0); border-right-width: 1px; border-right-style: solid; float: left; min-height: 780px; _height: 780px;
}
.con_right {
	background: rgb(255, 255, 255); width: 790px; height: auto !important; overflow: hidden; float: left; min-height: 700px; _height: 700px;
}
.help {
	margin: 0px auto; width: 990px; height: auto;
}
.help_menu {
	width: 140px; height: auto !important; float: left; min-height: 500px;
}
.help_menu ul {

}
.help_menu ul li {
	background: rgb(229, 229, 229); width: 140px; height: 48px; text-align: center; line-height: 47px; font-size: 14px; margin-bottom: 5px; display: block; cursor: pointer;
}
.help_menu ul li a {
	width: 140px; height: 48px; color: rgb(62, 62, 62); text-decoration: none; display: block; cursor: pointer;
}
.help_menu ul li a:hover {
	background: rgb(198, 31, 15); width: 140px; height: 48px; color: rgb(255, 255, 255); text-decoration: none; display: block; cursor: pointer;
}
.help_menu ul li.hovered {
	background: rgb(198, 31, 15); width: 140px; height: 48px; color: rgb(255, 255, 255); margin-bottom: 5px; display: block; cursor: pointer;
}
.news {
	padding: 0px 20px; height: auto; line-height: 28px;
}
.news p {
	color: rgb(51, 51, 51); text-indent: 20px; padding-top: 10px; font-size: 14px;
}
h1 {
	text-align: center; color: rgb(35, 35, 35); font-size: 24px;
}
.yinlian_top {
	background: url("../images/img/yinlian.png") no-repeat; margin: 0px auto; width: 1200px; height: 112px;
}
.time_out {
	margin: 0px auto 5px; width: 500px; height: 20px; text-align: center; color: rgb(184, 17, 17); font-size: 16px;
}
.table_question {

}
.table_question a {
	color: rgb(51, 51, 51); text-decoration: underline;
}
.table_question a:hover {
	color: rgb(51, 51, 51); text-decoration: underline;
}
ul#menu {
	margin: 0px; padding: 0px; position: relative; z-index: 10;
}
ul#menu ul {
	margin: 0px; padding: 0px; position: relative; z-index: 10;
}
ul#menu li {
	background: rgb(255, 255, 255); width: 170px; position: relative; z-index: 1000; min-height: 50px;
}
ul#menu a {
	text-decoration: none; display: block;
}
ul#menu a.m1 {
	background: url("../images/new_images/icon_1.jpg") no-repeat 0px -104px; padding-left: 35px;
}
ul#menu a.m2 {
	background: url("../images/new_images/icon_1.jpg") no-repeat 0px -50px; padding-left: 35px;
}
ul#menu a.m3 {
	background: url("../images/new_images/icon_1.jpg") no-repeat 0px -158px; padding-left: 35px;
}
ul#menu a.m4 {
	background: url("../images/new_images/icon_1.jpg") no-repeat 0px -212px; padding-left: 35px;
}
ul#menu li {
	line-height: 42px; font-size: 16px; margin-top: 10px; margin-bottom: 10px; _margin-top: 10px; _margin-bottom: 0px;
}
ul#menu li a {
	color: rgb(51, 51, 51);
}
ul#menu li a:hover {
	color: rgb(193, 16, 0);
}
ul#menu li ul li {
	height: 32px; _margin-bottom: -10px;
}
ul#menu li ul li a {
	color: rgb(102, 102, 102); text-indent: 15px; padding-left: 25px; font-size: 14px; _display: block;
}
ul#menu li ul li a:hover {
	color: rgb(193, 16, 0); padding-left: 25px;
}
ul#menu li ul li a.a_hovered {
	color: rgb(193, 16, 0);
}
.right_con {
	margin: 0px auto; width: 720px; height: auto;
}
.table1_top_bk {
	background: rgb(238, 238, 238); width: 380px; height: 34px; line-height: 34px; text-indent: 20px; font-size: 16px; font-weight: bold;
}
.table1_mid_bk {
	background: rgb(255, 255, 255); width: 380px; height: auto;
}
.right_con1 {
	background: rgb(255, 255, 255); width: 560px; height: 500px;
}
.message {
	background: url("../images/img/notice_bk.png") no-repeat; height: 70px; line-height: 70px; padding-left: 60px;
}
.menu_hovered {
	color: rgb(255, 255, 255);
}
.yl_div {

}
.yl_div ul li {
	color: rgb(68, 68, 68);
}
.yl_box {
	background: rgb(241, 240, 254); margin: 15px 0px; width: 620px; height: 180px; padding-left: 50px;
}
.banks {
	width: 720px; height: 540px; overflow: auto; -ms-overflow-x: hidden; min-height: 540px; _height: 540px;
}
.banks ul {

}
.banks ul li {
	width: 140px; color: rgb(76, 75, 75); padding-bottom: 12px; float: left;
}
.banks_url {
	margin: 8px 0px; width: 400px; height: 19px; padding-top: 2px; float: left;
}
.banks_url a {
	color: rgb(44, 90, 196); font-size: 14px; text-decoration: underline;
}
.banks_url a {
	color: rgb(39, 82, 188); text-decoration: underline;
}
.open_details {
	background: url("../images/img/open_hide.gif") no-repeat right -23px; width: 62px; height: 23px; float: left; display: block;
}
.open_details2 {
	background: url("../images/img/open_hide.gif") no-repeat right 0px; width: 62px; height: 23px; float: left; display: block;
}
.hidecontent {
	display: none;
}
.qustion {
	width: 720px; height: 520px; overflow: auto; -ms-overflow-x: hidden; min-height: 520px; _height: 520px;
}
.qustion ul {
	padding-top: 10px; padding-left: 50px;
}
.qustion ul li {
	padding-top: 20px;
}
.qustion ul li p {
	margin: -5px 0px 0px; padding: 0px;
}
.qustion ul li p span {
	color: rgb(51, 51, 51); _vertical-align: middle;
}
.guide_step1 {
	margin: 10px auto 20px; width: 324px; height: 39px;
}
.guide_step2 {
	margin: 10px auto 20px; width: 324px; height: 39px;
}
.guide_step3 {
	margin: 10px auto 20px; width: 324px; height: 39px;
}
.guide_step1 {
	background: url("../images/img/guide_1.png") no-repeat;
}
.guide_step2 {
	background: url("../images/img/guide_1.png") no-repeat;
}
.guide_step3 {
	background: url("../images/img/guide_1.png") no-repeat;
}
.radioimg {
	margin: 10px auto; width: 680px; height: auto; text-align: center;
}
.radioimg li {
	display: none;
}
.rz_type {
	background: url("../images/img/rz.png") no-repeat; border: 1px solid rgb(223, 223, 223); border-image: none; color: rgb(68, 68, 68); line-height: 40px; font-size: 14px; margin-left: 5px; display: inline-block; cursor: pointer;
}
.cfca {
	width: 210px; height: 40px; text-indent: 85px;
}
.yl {
	width: 210px; height: 40px; text-indent: 85px;
}
.kba {
	width: 210px; height: 40px; text-indent: 85px;
}
.phone_card {
	width: 210px; height: 40px; text-indent: 85px;
}
.cfca {
	background-position: 0px 0px;
}
.yl {
	background-position: 0px -40px;
}
.kba {
	background-position: 0px -80px;
}
.phone_card {
	background-position: 0px -120px;
}
.checked {
	border: 1px solid rgb(222, 59, 59); border-image: none;
}
.rz_0_div {
	margin: 0px auto; width: 600px; height: auto; font-size: 14px;
}
.rz_0_div p {
	margin: 15px 0px; color: rgb(68, 68, 68); line-height: 24px;
}
.rz_1 {
	background: url("../images/img/rz_1.png") no-repeat; width: 150px; height: 16px; color: rgb(184, 17, 17); line-height: 15px; text-indent: 120px; padding-top: 1px; font-size: 14px; margin-top: 4px; float: left; position: absolute; _margin-top: 0px;
}
.rz_2 {
	background: url("../images/img/rz_2.png") no-repeat; width: 150px; height: 16px; color: rgb(60, 127, 170); line-height: 15px; text-indent: 120px; padding-top: 1px; font-size: 14px; margin-top: 4px; float: left; position: absolute; _margin-top: 0px;
}
.rz_3 {
	background: url("../images/img/rz_3.png") no-repeat; width: 150px; height: 16px; color: rgb(71, 132, 59); line-height: 15px; text-indent: 120px; padding-top: 1px; font-size: 14px; margin-top: 4px; float: left; position: absolute; _margin-top: 0px;
}
.notice {
	background: url("../images/img/notice.png") no-repeat; width: 400px; height: 16px; line-height: 15px; padding-left: 20px; margin-top: 20px; margin-left: 30px;
}
.notice1 {
	background: url("../images/img/notice.png") no-repeat; margin: 10px; width: 220px; height: 16px; color: rgb(198, 13, 13); line-height: 15px; padding-top: 1px; padding-left: 20px; float: left; display: none; position: absolute;
}
.notice2 {
	background: url("../images/img/notice.png") no-repeat; margin: 8px 10px; width: 150px; height: 16px; color: rgb(198, 13, 13); line-height: 15px; padding-top: 1px; padding-left: 20px; float: left; display: none; position: absolute;
}
.notice3 {
	margin: 10px; width: 220px; height: 16px; color: rgb(198, 13, 13); line-height: 15px; padding-top: 1px; padding-left: 20px; float: left; display: none; position: absolute;
}
.yes {
	background: url("../images/img/right.png") no-repeat left top; margin: 8px 10px; width: 220px; height: 19px; padding-top: 3px; padding-left: 22px; position: absolute;
}
.no {
	background: url("../images/img/erro.png") no-repeat left top; margin: 8px 10px; width: 220px; height: 20px; padding-top: 3px; padding-left: 22px; position: absolute;
}
.position_re {
	display: inline; position: relative;
}
.s_notice1_t {
	margin: 2px; left: 5px; top: 12px; width: 15px; height: 15px; position: relative;
}
.position_top2 {
	top: 2px;
}
.s_notice1_t a {
	background: url("../images/img/notice1.png") no-repeat; width: 15px; height: 15px; display: inline-block; position: relative; z-index: 1;
}
.s_notice1_t a:hover {
	background: url("../images/img/notice.png") no-repeat; width: 15px; height: 15px; display: inline-block; position: relative;
}
#s_notice1_con1 {
	background: rgb(243, 243, 243); padding: 10px; left: 25px; top: -5px; width: 280px; height: auto; color: rgb(104, 104, 104); line-height: 24px; text-indent: 10px; clear: both; display: none; position: absolute; z-index: 9; _top: 15px;
}
#s_notice1_con2 {
	background: rgb(243, 243, 243); padding: 10px; left: 25px; top: -5px; width: 280px; height: auto; color: rgb(104, 104, 104); line-height: 24px; text-indent: 10px; clear: both; display: none; position: absolute; z-index: 9; _top: 15px;
}
#s_notice1_con3 {
	background: rgb(243, 243, 243); padding: 10px; left: 25px; top: -5px; width: 280px; height: auto; color: rgb(104, 104, 104); line-height: 24px; text-indent: 10px; clear: both; display: none; position: absolute; z-index: 9; _top: 15px;
}
#s_notice1_con4 {
	background: rgb(243, 243, 243); padding: 10px; left: 25px; top: -5px; width: 280px; height: auto; color: rgb(104, 104, 104); line-height: 24px; text-indent: 10px; clear: both; display: none; position: absolute; z-index: 9; _top: 15px;
}
#s_notice1_con5 {
	background: rgb(243, 243, 243); padding: 10px; left: 25px; top: -5px; width: 280px; height: auto; color: rgb(104, 104, 104); line-height: 24px; text-indent: 10px; clear: both; display: none; position: absolute; z-index: 9; _top: 15px;
}
#s_notice1_con6 {
	background: rgb(243, 243, 243); padding: 10px; left: 25px; top: -5px; width: 280px; height: auto; color: rgb(104, 104, 104); line-height: 24px; text-indent: 10px; clear: both; display: none; position: absolute; z-index: 9; _top: 15px;
}
#s_notice1_con7 {
	background: rgb(243, 243, 243); padding: 10px; left: 25px; top: -5px; width: 280px; height: auto; color: rgb(104, 104, 104); line-height: 24px; text-indent: 10px; clear: both; display: none; position: absolute; z-index: 9; _top: 15px;
}
#s_notice1_con8 {
	background: rgb(243, 243, 243); padding: 10px; left: 25px; top: -5px; width: 280px; height: auto; color: rgb(104, 104, 104); line-height: 24px; text-indent: 10px; clear: both; display: none; position: absolute; z-index: 9; _top: 15px;
}
.display_none {
	display: none;
}
#all {
	left: 0px; top: 0px; width: 100%; height: 100%; display: none; position: fixed; z-index: 88888; _position: absolute;
}
.rz_popup {
	background: rgb(255, 255, 255); border: 1px solid rgb(212, 212, 212); border-image: none; left: 50%; top: 50%; width: 380px; height: 220px; margin-top: -240px; margin-left: -260px !important; display: none; position: absolute; z-index: 99999; box-shadow: 0px 0px 20px #555; _position: absolute; _margin-left: -260px;
}
.rz_popup1 {
	background: rgb(255, 255, 255); border: 1px solid rgb(212, 212, 212); border-image: none; left: 50%; top: 50%; width: 380px; height: 494px; margin-top: -280px; margin-left: -260px !important; display: none; position: absolute; z-index: 99999; _position: absolute; _margin-left: -260px;
}
.text_div {
	width: 330px; height: 90px; line-height: 26px;
}
.margin_left_-190 {
	margin-left: -190px;
}
.close {
	background: url("../images/img/close.png") no-repeat left top; top: 7px; width: 21px; height: 21px; right: 15px; text-indent: -9999px; display: block; position: absolute;
}
.cancel {

}
.user_text {
	width: 140px; line-height: 40px; float: left; display: inline;
}
.mess_search {
	margin: 20px auto 0px; width: 740px; height: 50px; color: rgb(68, 68, 68); font-size: 14px;
}
.mess_search ul li {
	margin: 0px 3px; width: auto; line-height: 30px; float: left; display: inline;
}
.mess_search ul li span {
	float: left; display: block;
}
.mess_table {
	margin: 10px auto 0px; width: 720px; height: auto;
}
.table01 {
	border: currentColor; border-image: none; width: 100%; border-collapse: collapse;
}
.table02 {
	border: currentColor; border-image: none; width: 100%; border-collapse: collapse;
}
.table01 td {
	border: 1px solid rgb(212, 212, 212); border-image: none; text-align: center;
}
.table02 td {
	border: 1px solid rgb(212, 212, 212); border-image: none; text-align: center;
}
.table02 {
	margin-top: -1px;
}
.table01 td {
	background: rgb(245, 245, 245); height: 34px; color: rgb(64, 64, 64); font-size: 14px; font-weight: bold;
}
.table02 td {
	height: 32px; color: rgb(68, 68, 68); font-size: 12px;
}
#mobiletab {
	display: none;
}
.notice_div1 {
	width: 600px; height: 200px; line-height: 24px; margin-top: 60px;
}
.result_btn1 {
	margin: 0px auto; width: 100px; height: 32px;
}
.error {
	background: url("../images/img/error_img.gif") no-repeat; left: 50%; top: 50%; width: 700px; height: 340px; text-align: center; margin-top: -250px; margin-left: -350px; position: absolute;
}
.index_notice {
	margin: 0px auto; padding: 20px; width: 800px; height: 600px; font-family: "΢ÈíÑźÚ";
}
.index_notice p {
	color: rgb(51, 51, 51); text-indent: 20px; padding-top: 10px; font-size: 15px;
}
h2 {
	text-align: center; color: rgb(35, 35, 35); font-size: 20px;
}
.height32 {
	height: 32px;
}


text:
<?php

namespace Magento\Catalog\Api;

use Magento\Framework\Webapi\Exception as HTTPExceptionCodes;

class ProductAttributeRepositoryTest extends \Magento\TestFramework\TestCase\WebapiAbstract
{
    const SERVICE_NAME = 'catalogProductAttributeRepositoryV1';
    const SERVICE_VERSION = 'V1';
    const RESOURCE_PATH = '/V1/products/attributes';

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/product_attribute.php
     */
    public function testGet()
    {
        $attributeCode = 'test_attribute_code_333';
        $attribute = $this->getAttribute($attributeCode);

        $this->assertTrue(is_array($attribute));
        $this->assertArrayHasKey('attribute_id', $attribute);
        $this->assertArrayHasKey('attribute_code', $attribute);
        $this->assertEquals($attributeCode, $attribute['attribute_code']);
    }

    public function testGetList()
    {
        $searchCriteria = [
            'searchCriteria' => [
                'filter_groups' => [
                    [
                        'filters' => [
                            [
                                'field' => 'frontend_input',
                                'value' => 'textarea',
                                'condition_type' => 'eq',
                            ],
                        ],
                    ],
                ],
                'current_page' => 1,
                'page_size' => 2,
            ],
            'entityTypeCode' => \Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE,
        ];

        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '?' . http_build_query($searchCriteria),
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'GetList',
            ],
        ];
        $response = $this->_webApiCall($serviceInfo, $searchCriteria);

        $this->assertArrayHasKey('search_criteria', $response);
        $this->assertArrayHasKey('total_count', $response);
        $this->assertArrayHasKey('items', $response);

        $this->assertEquals($searchCriteria['searchCriteria'], $response['search_criteria']);
        $this->assertTrue($response['total_count'] > 0);
        $this->assertTrue(count($response['items']) > 0);

        $this->assertNotNull($response['items'][0]['default_frontend_label']);
        $this->assertNotNull($response['items'][0]['attribute_id']);
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/Model/Product/Attribute/_files/create_attribute_service.php
     */
    public function testCreate()
    {
        $attributeCode = 'label_attr_code3df4tr3';
        $attribute = $this->createAttribute($attributeCode);
        $this->assertArrayHasKey('attribute_id', $attribute);
        $this->assertEquals($attributeCode, $attribute['attribute_code']);
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/product_attribute.php
     */
    public function testCreateWithExceptionIfAttributeAlreadyExists()
    {
        $attributeCode = 'test_attribute_code_333';
        try {
            $this->createAttribute($attributeCode);
            $this->fail("Expected exception");
        } catch (\SoapFault $e) {
            //Expects soap exception
        } catch (\Exception $e) {
            $this->assertEquals(HTTPExceptionCodes::HTTP_BAD_REQUEST, $e->getCode());
        }
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/product_attribute.php
     */
    public function testUpdate()
    {
        $attributeCode = 'test_attribute_code_333';
        $attribute = $this->getAttribute($attributeCode);

        $attributeData = [
            'attribute' => [
                'attribute_id' => $attribute['attribute_id'],
                'frontend_labels' => [
                    ['store_id' => 0, 'label' => 'front_lbl_new'],
                ],
                'default_value' => 'default value new',
                'is_required' => false,
                'frontend_input' => 'text',
            ],
        ];

        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Save',
            ],
        ];

        if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
            $attributeData['attribute']['attributeCode'] = $attributeCode;
        }
        $result = $this->_webApiCall($serviceInfo, $attributeData);

        $this->assertEquals($attribute['attribute_id'], $result['attribute_id']);
        $this->assertEquals($attributeCode, $result['attribute_code']);
        $this->assertEquals('default value new', $result['default_value']);
        $this->assertEquals('front_lbl_new', $result['default_frontend_label']);
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/product_attribute.php
     */
    public function testDeleteById()
    {
        $attributeCode = 'test_attribute_code_333';
        $this->assertTrue($this->deleteAttribute($attributeCode));
    }

    /**
     * @magentoApiDataFixture Magento/Catalog/_files/product_attribute.php
     */
    public function testDeleteNoSuchEntityException()
    {
        $attributeCode = 'some_test_code';
        $expectedMessage = 'Attribute with attributeCode "%1" does not exist.';

        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'deleteById',
            ],
        ];

        try {
            $this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]);
            $this->fail("Expected exception");
        } catch (\SoapFault $e) {
            $this->assertContains(
                $expectedMessage,
                $e->getMessage(),
                "SoapFault does not contain expected message."
            );
        } catch (\Exception $e) {
            $errorObj = $this->processRestExceptionResult($e);
            $this->assertEquals($expectedMessage, $errorObj['message']);
            $this->assertEquals([$attributeCode], $errorObj['parameters']);
            $this->assertEquals(HTTPExceptionCodes::HTTP_NOT_FOUND, $e->getCode());
        }
    }

    /**
     * @param $attributeCode
     * @return array|bool|float|int|string
     */
    protected function createAttribute($attributeCode)
    {
        $attributeData = [
            'attribute' => [
                'attribute_code' => $attributeCode,
                'frontend_labels' => [
                    ['store_id' => 0, 'label' => 'front_lbl'],
                ],
                'default_value' => 'default value',
                'frontend_input' => 'textarea',
                'is_required' => true,
            ],
        ];

        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '/',
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_POST,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Save',
            ],
        ];
        return $this->_webApiCall($serviceInfo, $attributeData);
    }

    /**
     * @param $attributeCode
     * @return array|bool|float|int|string
     */
    protected function getAttribute($attributeCode)
    {
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_GET,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'Get',
            ],
        ];

        return $this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]);
    }

    /**
     * Delete attribute by code
     *
     * @param $attributeCode
     * @return array|bool|float|int|string
     */
    protected function deleteAttribute($attributeCode)
    {
        $serviceInfo = [
            'rest' => [
                'resourcePath' => self::RESOURCE_PATH . '/' . $attributeCode,
                'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_DELETE,
            ],
            'soap' => [
                'service' => self::SERVICE_NAME,
                'serviceVersion' => self::SERVICE_VERSION,
                'operation' => self::SERVICE_NAME . 'deleteById',
            ],
        ];
        return $this->_webApiCall($serviceInfo, ['attributeCode' => $attributeCode]);
    }
}


text:
package actors

import javax.inject.{Inject, Singleton}

import actors.GlobalLimitSupervisor.GetOrCreateLimiter
import actors.GlobalLimiter._
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import models.TwitterAuthCredentials
import models.twitter.TwitterAPI
import play.api.Logger
import play.api.libs.concurrent.InjectedActorSupport

import scala.concurrent.ExecutionContext
import scala.language.postfixOps

object GlobalLimitSupervisor {

  //------------------------------------------------------------------------------------------//
  // MESSAGES
  //------------------------------------------------------------------------------------------//
  sealed trait GlobalLimitSupervisorMessages extends Serializable

  @SerialVersionUID(1L)
  case class GetOrCreateLimiter(account: TwitterAuthCredentials, apiCall: TwitterAPI.Call) extends GlobalLimitSupervisorMessages

  //------------------------------------------------------------------------------------------//
  // CONSTRUCTOR HELPERS
  //------------------------------------------------------------------------------------------//
  def props(childFactory: GlobalLimiter.Factory)(implicit executionContext: ExecutionContext, system: ActorSystem): Props =
  Props(new GlobalLimitSupervisor(childFactory))

  def actorRef(childFactory: GlobalLimiter.Factory)(implicit executionContext: ExecutionContext, system: ActorSystem): ActorRef = {
    system.actorOf(props(childFactory), "GlobalLimitSupervisor")
  }
}

// TODO: maybe back to uninjected child?
@Singleton
class GlobalLimitSupervisor @Inject()(childFactory: GlobalLimiter.Factory)
                                     (implicit executionContext: ExecutionContext,
                                      system: ActorSystem) extends Actor with InjectedActorSupport {
  //------------------------------------------------------------------------------------------//
  // CONSTRUCTOR
  //------------------------------------------------------------------------------------------//
  private val log: Logger = Logger(this.getClass)

  //------------------------------------------------------------------------------------------//
  // ACTOR LOGIC
  //------------------------------------------------------------------------------------------//
  override def receive: Receive = default

  def default: Receive = {
    case GetOrCreateLimiter(account, apiCall) =>
      val name = apiCall.toString.replace("/", "-") + account.toString
      val child: ActorRef = context.child(name).getOrElse(
        injectedChild(childFactory(
          GlobalLimiterConfiguration(apiCall.userRateLimit,
            TwitterAPI.RATE_LIMIT_RESET_DURATION + (TwitterAPI.REQUEST_TIMEOUT / 2),
            apiCall.userRateLimit)
        ), name)
      )

      sender ! child
  }

  //------------------------------------------------------------------------------------------//
  // PRIVATE METHODS
  //------------------------------------------------------------------------------------------//
}


text:
package com.arangodb.async;

import com.arangodb.ArangoSerializationAccessor;
import com.arangodb.entity.EdgeEntity;
import com.arangodb.entity.EdgeUpdateEntity;
import com.arangodb.model.*;

import javax.annotation.concurrent.ThreadSafe;
import java.util.concurrent.CompletableFuture;

/**
 * Interface for operations on ArangoDB edge collection level.
 *
 * @author Mark Vollmary
 * @see API Documentation
 */
@SuppressWarnings("unused")
@ThreadSafe
public interface ArangoEdgeCollectionAsync extends ArangoSerializationAccessor {

    /**
     * The the handler of the named graph the edge collection is within
     *
     * @return graph handler
     */
    ArangoGraphAsync graph();

    /**
     * The name of the edge collection
     *
     * @return collection name
     */
    String name();

    /**
     * Creates a new edge in the collection
     *
     * @param value A representation of a single edge (POJO, VPackSlice or String for Json)
     * @return information about the edge
     * @see API Documentation
     */
    <T> CompletableFuture<EdgeEntity> insertEdge(final T value);

    /**
     * Creates a new edge in the collection
     *
     * @param value   A representation of a single edge (POJO, VPackSlice or String for Json)
     * @param options Additional options, can be null
     * @return information about the edge
     * @see API Documentation
     */
    <T> CompletableFuture<EdgeEntity> insertEdge(final T value, final EdgeCreateOptions options);

    /**
     * Fetches an existing edge
     *
     * @param key  The key of the edge
     * @param type The type of the edge-document (POJO class, VPackSlice or String for Json)
     * @return the edge identified by the key
     * @see API Documentation
     */
    <T> CompletableFuture<T> getEdge(final String key, final Class<T> type);

    /**
     * Fetches an existing edge
     *
     * @param key     The key of the edge
     * @param type    The type of the edge-document (POJO class, VPackSlice or String for Json)
     * @param options Additional options, can be null
     * @return the edge identified by the key
     * @see API Documentation
     */
    <T> CompletableFuture<T> getEdge(final String key, final Class<T> type, final GraphDocumentReadOptions options);

    /**
     * Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is
     * violated
     *
     * @param key The key of the edge
     * @return information about the edge
     * @see API Documentation
     */
    <T> CompletableFuture<EdgeUpdateEntity> replaceEdge(final String key, final T value);

    /**
     * Replaces the edge with key with the one in the body, provided there is such a edge and no precondition is
     * violated
     *
     * @param key     The key of the edge
     * @param options Additional options, can be null
     * @return information about the edge
     * @see API Documentation
     */
    <T> CompletableFuture<EdgeUpdateEntity> replaceEdge(
            final String key,
            final T value,
            final EdgeReplaceOptions options);

    /**
     * Partially updates the edge identified by document-key. The value must contain a document with the attributes to
     * patch (the patch document). All attributes from the patch document will be added to the existing document if they
     * do not yet exist, and overwritten in the existing document if they do exist there.
     *
     * @param key The key of the edge
     * @return information about the edge
     * @see API Documentation
     */
    <T> CompletableFuture<EdgeUpdateEntity> updateEdge(final String key, final T value);

    /**
     * Partially updates the edge identified by document-key. The value must contain a document with the attributes to
     * patch (the patch document). All attributes from the patch document will be added to the existing document if they
     * do not yet exist, and overwritten in the existing document if they do exist there.
     *
     * @param key     The key of the edge
     * @param options Additional options, can be null
     * @return information about the edge
     * @see API Documentation
     */
    <T> CompletableFuture<EdgeUpdateEntity> updateEdge(
            final String key,
            final T value,
            final EdgeUpdateOptions options);

    /**
     * Removes a edge
     *
     * @param key The key of the edge
     * @see API Documentation
     */
    CompletableFuture<Void> deleteEdge(final String key);

    /**
     * Removes a edge
     *
     * @param key     The key of the edge
     * @param options Additional options, can be null
     * @see API Documentation
     */
    CompletableFuture<Void> deleteEdge(final String key, final EdgeDeleteOptions options);

}


text:
package samples.powermockito.junit4.rule.xstream;

import org.junit.Rule;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.rule.PowerMockRule;
import samples.powermockito.junit4.staticmocking.MockStaticCases;
import samples.singleton.SimpleStaticService;
import samples.singleton.StaticService;

/**
 * Test class to demonstrate static mocking with PowerMockito.
 */
@PrepareForTest({StaticService.class, SimpleStaticService.class})
public class MockStaticTest extends MockStaticCases {
    @Rule
    public PowerMockRule rule = new PowerMockRule();

}


text:
declare module "dre-react-progressbar" {
    import React = require("react");
    var _m: React.ComponentClass<DRE.ReactProgressBarProps>;
    export = _m;
}


text:
import styled from 'styled-components';
import colors from 'themes/colors';

const Header = styled.div`
  display: flex;
  justify-content: center;
  margin: 40px auto;
  color: ${colors.base2};
  font-size: 14px;
`;

export default Header;


text:
package cyclops.stream.pushable;

import cyclops.reactive.ReactiveSeq;
import com.oath.cyclops.async.adapters.Queue;

/**
 * A more concrete Tuple2 impl
 * _1 is Queue<T>
 * _2 is Seq<T>
 *
 * @author johnmcclean
 *
 * @param <T> data type
 */
public class PushableReactiveSeq<T> extends AbstractPushableStream<T, Queue<T>, ReactiveSeq<T>> {

    public PushableReactiveSeq(final Queue<T> v1, final ReactiveSeq<T> v2) {
        super(v1, v2);

    }

    private static final long serialVersionUID = 1L;

}


text:
import { downgradeComponent} from '@angular/upgrade/static';

import { Ng2RouterRoot } from './app2.module';

/** Wrapper root module for angular 1 */
export const routerRootModule = angular.module('routerRootModule', ['ngRoute']);

routerRootModule.directive('ng2RouterRoot', downgradeComponent({
  component: Ng2RouterRoot,
  outputs: ['ng2RouterRoot'],
}) as ng.IDirectiveFactory);

// Tell the angular 1 router to render the placeholder
routerRootModule.config(['$routeProvider', ($routeProvider: angular.route.IRouteProvider) => {
  $routeProvider
    .otherwise({template : '<ng2-router-root></ng2-router-root>',
        reloadOnSearch: false});
}]);


text:
<?php

require_once(dirname(__FILE__).'/iocontroller.class.php');

class LEDController extends IOController
{

  private $LEDPin = 2;

  function __construct($pin) {

    $this->LEDPin = $pin;
  }

  public function setHeartbeatTrigger()
  {
    $this->write(1);
    $this->write_string_to_port("/sys/class/leds/beaglebone::usr".$this->LEDPin."/trigger", 'heartbeat');
  }
  public function setNoTrigger()
  {
    $this->write(1);
    $this->write_string_to_port("/sys/class/leds/beaglebone::usr".$this->LEDPin."/trigger", 'none');
  }

  public function blink($delay_on=500, $delay_off=500)
  {
    $this->write(1);
    $this->write_string_to_port("/sys/class/leds/beaglebone::usr".$this->LEDPin."/trigger", 'timer');
    $this->write_to_port("/sys/class/leds/beaglebone::usr".$this->LEDPin."/delay_on", $delay_on);
    $this->write_to_port("/sys/class/leds/beaglebone::usr".$this->LEDPin."/delay_off", $delay_off);
  }
  public function write($value) {

    return $this->write_to_port("/sys/class/leds/beaglebone::usr".$this->LEDPin."/brightness",$value);
  }

}


text:
<project>
  <groupId>edu.berkeley</groupId>
  <artifactId>sparkPCA</artifactId>
  <modelVersion>4.0.0</modelVersion>
  <name>Spark Principal component analysis </name>
  <packaging>jar</packaging>
  <version>1.0</version>
  <repositories>
    <repository>
      <id>Akka repository</id>
      <url>http://repo.akka.io/releases</url>
    </repository>
  </repositories>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>2.3</version>
        <configuration>
         <filters>
            <filter>
               <artifact>*:*</artifact>
               <excludes>
                <exclude>META-INF/*.SF</exclude>
                <exclude>META-INF/*.DSA</exclude>
                <exclude>META-INF/*.RSA</exclude>
               </excludes>
        </filter>
    </filters>
        </configuration>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency> <!-- Spark dependency -->
      <groupId>org.apache.spark</groupId>
      <artifactId>spark-core_2.10</artifactId>
      <version>1.0.0</version>
    </dependency>
   <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-mllib_2.10</artifactId>
        <version>1.0.0</version>
   </dependency>
  <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-core</artifactId>
        <version>1.2.1</version>
  </dependency>
  <dependency>
        <groupId>org.apache.mahout</groupId>
        <artifactId>mahout-core</artifactId>
        <version>0.8</version>
    </dependency>
  </dependencies>
</project>


text:
from setuptools import setup

setup(
    name = 'pacardxlink',
    version = '1.2',
    author = 'Bert Wesarg',
    author_email = 'bertwesarg@users.noreply.github.com',
    description = 'A PulseAudio AppIndicator to cross link the inputs and outputs of two audio devices',
    license = '3-clause BSD',
    url = 'https://github.com/bertwesarg/pacardxlink',
    scripts = ['pacardxlink.py'],
    install_requires = [
        'pygtk>=2.24',
        'appindicator>=12.10.1',
        'pulsectl>=16.8.14'
    ]
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<job
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="urn:proactive:jobdescriptor:3.11" xsi:schemaLocation="urn:proactive:jobdescriptor:3.11 http://www.activeeon.com/public_content/schemas/proactive/jobdescriptor/3.11/schedulerjob.xsd"  name="Print_File_Name" projectName="1. Basic Workflows" priority="normal" onTaskError="continueJobExecution"  maxNumberOfExecution="2" >
  <variables>
    <variable name="file" value="undefined" />
  </variables>
  <genericInformation>
    <info name="bucketName" value="basic-examples"/>
    <info name="workflow.icon" value="/automation-dashboard/styles/patterns/img/wf-icons/print_file_name.png"/>
    <info name="group" value="public-objects"/>
  </genericInformation>
  <taskFlow>
    <task name="print_file_name" >
      <description>
        <![CDATA[ The simplest task, ran by a javascript engine. ]]>
      </description>
      <genericInformation>
        <info name="task.icon" value="/automation-dashboard/styles/patterns/img/wf-icons/print_file_name.png"/>
      </genericInformation>

      </scriptExecutable>
      <metadata>
        <positionTop>
            185.05209350585938
        </positionTop>
        <positionLeft>
            380.97222900390625
        </positionLeft>
      </metadata>
    </task>
  </taskFlow>
  <metadata>
    <visualization>
      <![CDATA[ <link rel="stylesheet" href="/studio/styles/studio-standalone.css">

 print_file_name

<svg style="position:absolute;left:0px;top:0px" width="20" height="20" pointer-events="all" position="absolute" version="1.1"
      xmlns="http://www.w3.org/1999/xhtml"><circle cx="10" cy="10" r="10" version="1.1"
      xmlns="http://www.w3.org/1999/xhtml" fill="#666" stroke="none" style=""></circle></svg>

 ]]>
    </visualization>
  </metadata>
</job>