text:
"""Performs DELG-based image retrieval on Revisited Oxford/Paris datasets."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import time

from absl import app
from absl import flags
import numpy as np
import tensorflow as tf

from delf import datum_io
from delf.python.detect_to_retrieve import dataset
from delf.python.detect_to_retrieve import image_reranking

FLAGS = flags.FLAGS

flags.DEFINE_string(
    'dataset_file_path', '/tmp/gnd_roxford5k.mat',
    'Dataset file for Revisited Oxford or Paris dataset, in .mat format.')
flags.DEFINE_string('query_features_dir', '/tmp/features/query',
                    'Directory where query DELG features are located.')
flags.DEFINE_string('index_features_dir', '/tmp/features/index',
                    'Directory where index DELG features are located.')
flags.DEFINE_boolean(
    'use_geometric_verification', False,
    'If True, performs re-ranking using local feature-based geometric '
    'verification.')
flags.DEFINE_float(
    'local_feature_distance_threshold', 1.0,
    'Optional, only used if `use_geometric_verification` is True. '
    'Distance threshold below which a pair of local descriptors is considered '
    'a potential match, and will be fed into RANSAC.')
flags.DEFINE_float(
    'ransac_residual_threshold', 20.0,
    'Optional, only used if `use_geometric_verification` is True. '
    'Residual error threshold for considering matches as inliers, used in '
    'RANSAC algorithm.')
flags.DEFINE_string(
    'output_dir', '/tmp/retrieval',
    'Directory where retrieval output will be written to. A file containing '
    "metrics for this run is saved therein, with file name 'metrics.txt'.")

# Extensions.
_DELG_GLOBAL_EXTENSION = '.delg_global'
_DELG_LOCAL_EXTENSION = '.delg_local'

# Precision-recall ranks to use in metric computation.
_PR_RANKS = (1, 5, 10)

# Pace to log.
_STATUS_CHECK_LOAD_ITERATIONS = 50

# Output file names.
_METRICS_FILENAME = 'metrics.txt'

def _ReadDelgGlobalDescriptors(input_dir, image_list):
  """Reads DELG global features.

  Args:
    input_dir: Directory where features are located.
    image_list: List of image names for which to load features.

  Returns:
    global_descriptors: NumPy array of shape (len(image_list), D), where D
      corresponds to the global descriptor dimensionality.
  """
  num_images = len(image_list)
  global_descriptors = []
  print('Starting to collect global descriptors for %d images...' % num_images)
  start = time.time()
  for i in range(num_images):
    if i > 0 and i % _STATUS_CHECK_LOAD_ITERATIONS == 0:
      elapsed = (time.time() - start)
      print('Reading global descriptors for image %d out of %d, last %d '
            'images took %f seconds' %
            (i, num_images, _STATUS_CHECK_LOAD_ITERATIONS, elapsed))
      start = time.time()

    descriptor_filename = image_list[i] + _DELG_GLOBAL_EXTENSION
    descriptor_fullpath = os.path.join(input_dir, descriptor_filename)
    global_descriptors.append(datum_io.ReadFromFile(descriptor_fullpath))

  return np.array(global_descriptors)

def main(argv):
  if len(argv) > 1:
    raise RuntimeError('Too many command-line arguments.')

  # Parse dataset to obtain query/index images, and ground-truth.
  print('Parsing dataset...')
  query_list, index_list, ground_truth = dataset.ReadDatasetFile(
      FLAGS.dataset_file_path)
  num_query_images = len(query_list)
  num_index_images = len(index_list)
  (_, medium_ground_truth,
   hard_ground_truth) = dataset.ParseEasyMediumHardGroundTruth(ground_truth)
  print('done! Found %d queries and %d index images' %
        (num_query_images, num_index_images))

  # Read global features.
  query_global_features = _ReadDelgGlobalDescriptors(FLAGS.query_features_dir,
                                                     query_list)
  index_global_features = _ReadDelgGlobalDescriptors(FLAGS.index_features_dir,
                                                     index_list)

  # Compute similarity between query and index images, potentially re-ranking
  # with geometric verification.
  ranks_before_gv = np.zeros([num_query_images, num_index_images],
                             dtype='int32')
  if FLAGS.use_geometric_verification:
    medium_ranks_after_gv = np.zeros([num_query_images, num_index_images],
                                     dtype='int32')
    hard_ranks_after_gv = np.zeros([num_query_images, num_index_images],
                                   dtype='int32')
  for i in range(num_query_images):
    print('Performing retrieval with query %d (%s)...' % (i, query_list[i]))
    start = time.time()

    # Compute similarity between global descriptors.
    similarities = np.dot(index_global_features, query_global_features[i])
    ranks_before_gv[i] = np.argsort(-similarities)

    # Re-rank using geometric verification.
    if FLAGS.use_geometric_verification:
      medium_ranks_after_gv[i] = image_reranking.RerankByGeometricVerification(
          input_ranks=ranks_before_gv[i],
          initial_scores=similarities,
          query_name=query_list[i],
          index_names=index_list,
          query_features_dir=FLAGS.query_features_dir,
          index_features_dir=FLAGS.index_features_dir,
          junk_ids=set(medium_ground_truth[i]['junk']),
          local_feature_extension=_DELG_LOCAL_EXTENSION,
          ransac_seed=0,
          feature_distance_threshold=FLAGS.local_feature_distance_threshold,
          ransac_residual_threshold=FLAGS.ransac_residual_threshold)
      hard_ranks_after_gv[i] = image_reranking.RerankByGeometricVerification(
          input_ranks=ranks_before_gv[i],
          initial_scores=similarities,
          query_name=query_list[i],
          index_names=index_list,
          query_features_dir=FLAGS.query_features_dir,
          index_features_dir=FLAGS.index_features_dir,
          junk_ids=set(hard_ground_truth[i]['junk']),
          local_feature_extension=_DELG_LOCAL_EXTENSION,
          ransac_seed=0,
          feature_distance_threshold=FLAGS.local_feature_distance_threshold,
          ransac_residual_threshold=FLAGS.ransac_residual_threshold)

    elapsed = (time.time() - start)
    print('done! Retrieval for query %d took %f seconds' % (i, elapsed))

  # Create output directory if necessary.
  if not tf.io.gfile.exists(FLAGS.output_dir):
    tf.io.gfile.makedirs(FLAGS.output_dir)

  # Compute metrics.
  medium_metrics = dataset.ComputeMetrics(ranks_before_gv, medium_ground_truth,
                                          _PR_RANKS)
  hard_metrics = dataset.ComputeMetrics(ranks_before_gv, hard_ground_truth,
                                        _PR_RANKS)
  if FLAGS.use_geometric_verification:
    medium_metrics_after_gv = dataset.ComputeMetrics(medium_ranks_after_gv,
                                                     medium_ground_truth,
                                                     _PR_RANKS)
    hard_metrics_after_gv = dataset.ComputeMetrics(hard_ranks_after_gv,
                                                   hard_ground_truth, _PR_RANKS)

  # Write metrics to file.
  mean_average_precision_dict = {
      'medium': medium_metrics[0],
      'hard': hard_metrics[0]
  }
  mean_precisions_dict = {'medium': medium_metrics[1], 'hard': hard_metrics[1]}
  mean_recalls_dict = {'medium': medium_metrics[2], 'hard': hard_metrics[2]}
  if FLAGS.use_geometric_verification:
    mean_average_precision_dict.update({
        'medium_after_gv': medium_metrics_after_gv[0],
        'hard_after_gv': hard_metrics_after_gv[0]
    })
    mean_precisions_dict.update({
        'medium_after_gv': medium_metrics_after_gv[1],
        'hard_after_gv': hard_metrics_after_gv[1]
    })
    mean_recalls_dict.update({
        'medium_after_gv': medium_metrics_after_gv[2],
        'hard_after_gv': hard_metrics_after_gv[2]
    })
  dataset.SaveMetricsFile(mean_average_precision_dict, mean_precisions_dict,
                          mean_recalls_dict, _PR_RANKS,
                          os.path.join(FLAGS.output_dir, _METRICS_FILENAME))

if __name__ == '__main__':
  app.run(main)


text:
<?php

namespace Mtf\Client\Driver\Selenium\Element;

use Mtf\Client\Element;

/**
 * Class JquerytreeElement
 * Typified element class for JqueryTree elements
 *
 * @package Mtf\Client\Element
 */
class JquerytreeElement extends Tree
{
    /**
     * Css class for finding tree nodes.
     *
     * @var string
     */
    protected $nodeCssClass = ' > ul';

    /**
     * Css class for detecting tree nodes.
     *
     * @var string
     */
    protected $nodeSelector = 'li[data-id]';

    /**
     * Css class for detecting tree nodes.
     *
     * @var string
     */
    protected $checkedNodeSelector = 'li.jstree-checked[data-id]';

    /**
     * Css class for fetching node's name.
     *
     * @var string
     */
    protected $nodeName = 'a';

    /**
     * Array, which holds all selected elements paths.
     *
     * @var array
     */
    protected $checkedNodesPaths = [];

    /**
     * Returns structure of the jquerytree element.
     *
     * @return array
     */
    public function getStructure()
    {
        return $this->_getNodeContent($this, 'div[class*=jstree] > ul');
    }

    /**
     *  Recursive walks tree
     *
     * @param Element $node
     * @param string $parentCssClass
     * @return array
     */
    protected function _getNodeContent($node, $parentCssClass)
    {
        $counter = 1;
        $nextNodeSelector = $parentCssClass . " > " . $this->nodeSelector . ":nth-of-type($counter)";
        $nodeArray = [];
        //Get list of all children nodes to work with
        $newNode = $node->find($nextNodeSelector);
        while ($newNode->isVisible()) {
            $nextCheckedNodeSelector = $parentCssClass . " > " . $this->checkedNodeSelector . ":nth-of-type($counter)";
            $nodesNames = $newNode->find($this->nodeName);
            $text = ltrim($nodesNames->getText());
            $childNodeSelector = $nextNodeSelector . $this->nodeCssClass;
            $nodesContents = $newNode->find($childNodeSelector);
            $subNodes = null;
            if ($nodesContents->isVisible()) {
                $subNodes = $this->_getNodeContent($nodesContents, $childNodeSelector);
            }
            $nodeArray[] = [
                'name' => $text,
                'isChecked' => $node->find($nextCheckedNodeSelector)->isVisible() ? true : false,
                'element' => $newNode,
                'subnodes' => $subNodes,
            ];
            ++$counter;
            $nextNodeSelector = $parentCssClass . " > " . $this->nodeSelector . ":nth-of-type($counter)";
            $newNode = $node->find($nextNodeSelector);
        }
        return $nodeArray;
    }

    /**
     * Retrieve array of checked nodes from structure array.
     *
     * @param array $structure
     * @return array|null
     */
    protected function getCheckedNodes($structure)
    {
        $pathArray = [];
        if ($structure['isChecked'] == true) {
            array_push($pathArray, $structure['name']);
            if (is_array($structure['subnodes'])) {
                foreach ($structure['subnodes'] as $node) {
                    array_push($pathArray, $this->getCheckedNodes($node));
                }
            }
            return $pathArray;
        }
        return null;
    }

    /**
     * Method for recursive walk array of checked elements.
     * If element haven't subnodes, adds element's path to $checkedNodesPaths
     *
     * @param array $pathArray
     * @param string $rootPath
     * @return string
     */
    protected function getPathFromArray($pathArray, $rootPath = '')
    {
        $path = '';
        $rootPath = $rootPath == '' ? $pathArray[0] : $rootPath . '/' . $pathArray[0];
        if (count($pathArray) > 1) {
            for ($counter = 1; $counter < count($pathArray); $counter++) {
                $path .= $this->getPathFromArray($pathArray[$counter], $rootPath);
            }
        } else {
            $path = $rootPath;
            $this->checkedNodesPaths[] = $path;
        }
        return $path;
    }

    /**
     * Returns array of paths of all selected elements.
     *
     * @return array
     */
    public function getValue()
    {
        $pathsArray = [];
        $structure = $this->getStructure();
        foreach ($structure as $structureChunk) {
            $pathsArray[] = $this->getCheckedNodes($structureChunk);
        }
        foreach ($pathsArray as $pathArray) {
            $this->getPathFromArray($pathArray);
        }
        return array_filter($this->checkedNodesPaths);
    }
}

redpajama_set_name: RedPajamaGithub


text:
import {Component} from 'angular2/core';
import {DataService} from './services/data.service';
import {AuthUser, AuthType, NotificationPermission} from './interfaces/interfaces';
import {AuthService} from './services/auth.service';

declare let Firebase;

@Component({
    selector: 'psi-stats',
    templateUrl: 'app/stats.html',
    directives: []
})
export class Stats {
    authUser: AuthUser;
    testHistory: any;

    constructor(
        private _authService: AuthService,
        private _dataService: DataService) { }

    ngOnInit() {
        this._dataService.psiHistory$.subscribe(testHistory => this.testHistory = testHistory);
        this._dataService.loadPsiHistory();

        this._authService.authUser$.subscribe(authUser => this.authUser = authUser);
        this._authService.loadAuthUser();
    }

    loginTwitter() {
        this._authService.login(AuthType.TWITTER);
    }

    loginGithub() {
        this._authService.login(AuthType.GITHUB);
    }
}


text:
package org.apache.metamodel.excel;

import java.util.Iterator;

import org.apache.metamodel.data.DataSet;
import org.apache.metamodel.data.EmptyDataSet;
import org.apache.metamodel.data.MaxRowsDataSet;
import org.apache.metamodel.schema.Column;
import org.apache.metamodel.schema.ColumnType;
import org.apache.metamodel.schema.MutableColumn;
import org.apache.metamodel.schema.MutableSchema;
import org.apache.metamodel.schema.MutableTable;
import org.apache.metamodel.schema.Schema;
import org.apache.metamodel.schema.Table;
import org.apache.metamodel.schema.naming.ColumnNamingContext;
import org.apache.metamodel.schema.naming.ColumnNamingContextImpl;
import org.apache.metamodel.schema.naming.ColumnNamingSession;
import org.apache.metamodel.schema.naming.ColumnNamingStrategy;
import org.apache.metamodel.util.FileHelper;
import org.apache.metamodel.util.Resource;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The default {@link SpreadsheetReaderDelegate}, which uses POI's main user
 * model to read spreadsheets: the Workbook class.
 */
final class DefaultSpreadsheetReaderDelegate implements SpreadsheetReaderDelegate {

    private static final Logger logger = LoggerFactory.getLogger(DefaultSpreadsheetReaderDelegate.class);

    private final Resource _resource;
    private final ExcelConfiguration _configuration;

    public DefaultSpreadsheetReaderDelegate(Resource resource, ExcelConfiguration configuration) {
        _resource = resource;
        _configuration = configuration;
    }

    @Override
    public Schema createSchema(String schemaName) {
        final MutableSchema schema = new MutableSchema(schemaName);
        final Workbook wb = ExcelUtils.readWorkbook(_resource);
        try {
            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                final Sheet currentSheet = wb.getSheetAt(i);
                final MutableTable table = createTable(wb, currentSheet);
                table.setSchema(schema);
                schema.addTable(table);
            }

            return schema;
        } finally {
            FileHelper.safeClose(wb);
        }
    }

    @Override
    public DataSet executeQuery(Table table, Column[] columns, int maxRows) {
        final Workbook wb = ExcelUtils.readWorkbook(_resource);
        final Sheet sheet = wb.getSheet(table.getName());

        if (sheet == null || sheet.getPhysicalNumberOfRows() == 0) {
            return new EmptyDataSet(columns);
        }

        DataSet dataSet = ExcelUtils.getDataSet(wb, sheet, table, _configuration);

        if (maxRows > 0) {
            dataSet = new MaxRowsDataSet(dataSet, maxRows);
        }
        return dataSet;
    }

    @Override
    public void notifyTablesModified() {
        // do nothing
    }

    private MutableTable createTable(final Workbook wb, final Sheet sheet) {
        final MutableTable table = new MutableTable(sheet.getSheetName());

        if (sheet.getPhysicalNumberOfRows() <= 0) {
            // no physical rows in sheet
            return table;
        }

        final Iterator<Row> rowIterator = ExcelUtils.getRowIterator(sheet, _configuration, false);

        if (!rowIterator.hasNext()) {
            // no physical rows in sheet
            return table;
        }

        Row row = null;

        if (_configuration.isSkipEmptyLines()) {
            while (row == null && rowIterator.hasNext()) {
                row = rowIterator.next();
            }
        } else {
            row = rowIterator.next();
        }

        final int columnNameLineNumber = _configuration.getColumnNameLineNumber();
        if (columnNameLineNumber == ExcelConfiguration.NO_COLUMN_NAME_LINE) {

            // get to the first non-empty line (no matter if lines are skipped
            // or not we need to read ahead to figure out how many columns there
            // are!)
            while (row == null && rowIterator.hasNext()) {
                row = rowIterator.next();
            }

            // build columns without any intrinsic column names
            final ColumnNamingStrategy columnNamingStrategy = _configuration.getColumnNamingStrategy();
            try (final ColumnNamingSession columnNamingSession = columnNamingStrategy.startColumnNamingSession()) {
                final int offset = getColumnOffset(row);
                for (int i = 0; i < offset; i++) {
                    columnNamingSession.getNextColumnName(new ColumnNamingContextImpl(i));
                }

                for (int j = offset; j < row.getLastCellNum(); j++) {
                    final ColumnNamingContext namingContext = new ColumnNamingContextImpl(table, null, j);
                    final Column column = new MutableColumn(columnNamingSession.getNextColumnName(namingContext),
                            ColumnType.STRING, table, j, true);
                    table.addColumn(column);
                }
            }

        } else {

            boolean hasColumns = true;

            // iterate to the column name line number (if above 1)
            for (int j = 1; j < columnNameLineNumber; j++) {
                if (rowIterator.hasNext()) {
                    row = rowIterator.next();
                } else {
                    hasColumns = false;
                    break;
                }
            }

            if (hasColumns) {
                createColumns(table, wb, row);
            }
        }

        return table;
    }

    /**
     * Builds columns based on row/cell values.
     *
     * @param table
     * @param wb
     * @param row
     */
    private void createColumns(MutableTable table, Workbook wb, Row row) {
        if (row == null) {
            logger.warn("Cannot create columns based on null row!");
            return;
        }
        final short rowLength = row.getLastCellNum();

        final int offset = getColumnOffset(row);

        // build columns based on cell values.
        try (final ColumnNamingSession columnNamingSession = _configuration.getColumnNamingStrategy()
                .startColumnNamingSession()) {
            for (int j = offset; j < rowLength; j++) {
                final Cell cell = row.getCell(j);
                final String intrinsicColumnName = ExcelUtils.getCellValue(wb, cell);
                final ColumnNamingContext columnNamingContext = new ColumnNamingContextImpl(table, intrinsicColumnName,
                        j);
                final String columnName = columnNamingSession.getNextColumnName(columnNamingContext);
                final Column column = new MutableColumn(columnName, ColumnType.VARCHAR, table, j, true);
                table.addColumn(column);
            }
        }
    }

    /**
     * Gets the column offset (first column to include). This is dependent on
     * the row used for column processing and whether the skip empty columns
     * property is set.
     *
     * @param row
     * @return
     */
    private int getColumnOffset(Row row) {
        final int offset;
        if (_configuration.isSkipEmptyColumns()) {
            offset = row.getFirstCellNum();
        } else {
            offset = 0;
        }
        return offset;
    }
}


text:
#ifndef MODULE_DESCRIPTION_LOOKUP_H
#define MODULE_DESCRIPTION_LOOKUP_H

#include <Dataflow/Network/ModuleDescription.h>
#include <Dataflow/Network/Module.h>
#include <boost/functional/factory.hpp>
#include <Modules/Factory/share.h>

namespace SCIRun {
  namespace Modules {
    namespace Factory {

      class SCISHARE ModuleDescriptionLookup
      {
      public:
        ModuleDescriptionLookup();
        Dataflow::Networks::ModuleDescription lookupDescription(const Dataflow::Networks::ModuleLookupInfo& info) const;
        Dataflow::Networks::ModuleDescriptionMap descMap_;
        Dataflow::Networks::DirectModuleDescriptionLookupMap lookup_;
      private:
        bool includeTestingModules_;

        /// @todo: remove this function and use static MLI from each module
        template <class ModuleType>
        void addModuleDesc(const std::string& name, const std::string& category, const std::string& package, const std::string& status, const std::string& desc)
        {
          Dataflow::Networks::ModuleLookupInfo info(name, category, package);
          addModuleDesc<ModuleType>(info, status, desc);
        }

        template <class ModuleType>
        void addModuleDesc(const Dataflow::Networks::ModuleLookupInfo& info, const std::string& status, const std::string& desc)
        {
          Dataflow::Networks::ModuleDescription description;
          description.lookupInfo_ = info;

          description.input_ports_ = IPortDescriber<ModuleType::NumIPorts, ModuleType>::inputs();
          description.output_ports_ = OPortDescriber<ModuleType::NumOPorts, ModuleType>::outputs();
          description.maker_ = boost::factory<ModuleType*>();
          description.moduleStatus_ = status;
          description.moduleInfo_ = desc;
          description.hasUI_ = HasUI<ModuleType>::value;
          description.hasAlgo_ = HasAlgorithm<ModuleType>::value;

          lookup_[info] = description;

          descMap_[info.package_name_][info.category_name_][info.module_name_] = description;
        }

        template <class ModuleType>
        void addModuleDesc(const std::string& status, const std::string& desc)
        {
          addModuleDesc<ModuleType>(ModuleType::staticInfo_, status, desc);
        }

        void addEssentialModules();
        void addTestingModules();
        void addBrainSpecificModules();
        void addMoreModules();
        void addGeneratedModules();
      };
    }
  }
}

#endif


text:
var wizardSpellList = [
'orc _ fire _ blade _ storm _ night _ lightnight _ fire _ rainbow',
'force _ bolt',
'drain _ life',
'magic _ missile',
'cone _ of _ cold',
'fireball',
'finger _ of _ death',
'protection',
'turn _ undead',
'create _ monster',
'remove _ curse',
'create _ familiar',
'detect _ monster',
'light',
'detect _ food',
'clairvoyance',
'detect _ unseen',
'identity',
'detect _ treasure',
'magic _ mapping',
'sleep',
'confuse _ monster',
'slow _ monster',
'cause _ fear',
'charm _ monster',
'jumping',
'haste _ self',
'invisibility',
'levitation',
'teleport _ away',
'knock',
'wizard _ lock',
'dig',
'polymorph',
'cancellation',
'amplify _ damage',
'dim _ vision',
'weaken',
'iron _ maiden',
'terror',
'confuse',
'life _ tap',
'attract',
'decrepify',
'lower _ resist',
'teeth',
'bone _ armor',
'poison _ dagger',
'corpse _ explosion',
'bone _ wall',
'poison _ explosion',
'bone _ spear',
'bone _ prison',
'poison _ nova',
'bone _ spirit',
'raise _ skeleton',
'skeleton _ mastery',
'clay _ golem',
'golem _ mastery',
'raise _ skeletal _ mage',
'blood _ golem',
'summon _ resist',
'iron _ golem',
'fire _ golem',
'revive',
'ice _ bolt',
'frozen _ armor',
'frost _ nova',
'ice _ blast',
'shiver _ armor',
'glacial _ spike',
'blizzard',
'chilling _ armor',
'frozen _ orb',
'cold _ mastery',
'fire _ bolt',
'warmth',
'inferno',
'blaze',
'fireball',
'fire _ wall',
'enchant',
'meteor',
'fire _ mastery',
'hydra',
'charged _ bolt',
'telekinesis',
'static _ field',
'lightning',
'nova',
'chain _ lightning',
'teleport',
'thunder _ storm',
'energy _ shield',
'lightning _ mastery',
'firestorm',
'molten _ boulder',
'arctic _ blast',
'fissure',
'cyclone _ armor',
'twister',
'volcano',
'tornado',
'hurricane',
'armageddon',
'werewolf',
'lycanthropy',
'werebear',
'maul',
'feral _ rage',
'fire _ claws',
'rabies',
'shock _ wave',
'hunger',
'fury',
'raven',
'poison _ creeper',
'oak _ sage',
'summon _ spirit _ wolf',
'carrion _ vine',
'heart _ of _ wolverine',
'summon _ dire _ wolf',
'solar _ creeper',
'spirit _ of _ barbs',
'summon _ grizzly',
"acid _ arrow",
"acid _ fog",
"acid _ splash",
"aid",
"air _ walk",
"alarm",
"align _ weapon",
"alter _ self",
"analyze _ dweomer",
"animal _ growth",
"animal _ messenger",
"animal _ shapes",
"animal _ trance",
"animate _ dead",
"animate _ objects",
"animate _ plants",
"animate _ rope",
"antilife _ shell",
"antimagic _ field",
"antipathy",
"antiplant _ shell",
"arcane _ eye",
"arcane _ lock",
"arcane _ mark",
"arcane _ sight",
"greater _ arcane _ sight",
"astral _ projection",
"atonement",
"augury",
"awaken",
"baleful _ polymorph",
"bane",
"banishment",
"barkskin",
"bear's _ endurance",
"mass _ bear's _ endurance",
"bestow _ curse",
"binding",
"black _ tentacles",
"blade _ barrier",
"blasphemy",
"bless",
"bless _ water",
"bless _ weapon",
"blight",
"blindness",
"deafness",
"blink",
"blur",
"break _ enchantment",
"bull's _ strength",
"mass _ bull's _ strength",
"burning _ hands",
"call _ lightning",
"call _ lightning _ storm",
"calm _ animals",
"calm _ emotions",
"cat's _ grace",
"mass _ cat's _ grace",
"cause _ fear",
"chain _ lightning",
"changestaff",
"chaos _ hammer",
"charm _ animal",
"charm _ monster",
"mass _ charm _ monster",
"charm _ person",
"chill _ metal",
"chill _ touch",
"circle _ of _ death",
"clairaudience",
"clairvoyance",
"clenched _ fist",
"cloak _ of _ chaos",
"clone",
"cloudkill",
"color _ spray",
"command",
"greater _ command",
"command _ plants",
"command _ undead",
"commune",
"commune _ with _ nature",
"comprehend _ languages",
"cone _ of _ cold",
"confusion",
"lesser _ confusion",
"consecrate",
"contact _ other _ plane",
"contagion",
"contingency",
"continual _ flame",
"control _ plants",
"control _ undead",
"control _ water",
"control _ weather",
"control _ winds",
"create _ food _ and _ water",
"create _ greater _ undead",
"create _ undead",
"create _ water",
"creeping _ doom",
"crushing _ despair",
"crushing _ hand",
"cure _ critical _ wounds",
"mass _ cure _ critical _ wounds",
"cure _ light _ wounds",
"mass _ cure _ light _ wounds",
"cure _ minor _ wounds",
"cure _ moderate _ wounds",
"mass _ cure _ moderate _ wounds",
"cure _ serious _ wounds",
"mass _ cure _ serious _ wounds",
"curse _ water",
"dancing _ lights",
"darkness",
"darkvision",
"daylight",
"daze",
"daze _ monster",
"death _ knell",
"death _ ward",
"deathwatch",
"deep _ slumber",
"deeper _ darkness",
"delay _ poison",
"delayed _ blast _ fireball",
"demand",
"desecrate",
"destruction",
"detect _ animals _ or _ plants",
"detect _ chaos",
"detect _ evil",
"detect _ good",
"detect _ law",
"detect _ magic",
"detect _ poison",
"detect _ scrying",
"detect _ secret _ doors",
"detect _ snares _ and _ pits",
"detect _ thoughts",
"detect _ undead",
"dictum",
"dimension _ door",
"dimensional _ anchor",
"dimensional _ lock",
"diminish _ plants",
"discern _ lies",
"discern _ location",
"disguise _ self",
"disintegrate",
"dismissal",
"dispel _ chaos",
"dispel _ evil",
"dispel _ good",
"dispel _ law",
"dispel _ magic",
"greater _ dispel _ magic",
"displacement",
"disrupt _ undead",
"disrupting _ weapon",
"divination",
"divine _ favor",
"divine _ power",
"dominate _ animal",
"dominate _ monster",
"dominate _ person",
"doom",
"dream",
"eagle's _ splendor",
"mass _ eagle's _ splendor",
"earthquake",
"elemental _ swarm",
"endure _ elements",
"energy _ drain",
"enervation",
"enlarge _ person",
"mass _ enlarge _ person",
"entangle",
"enthrall",
"entropic _ shield",
"erase",
"ethereal _ jaunt",
"etherealness",
"expeditious _ retreat",
"explosive _ runes",
"eyebite",
"fabricate",
"faerie _ fire",
"false _ life",
"false _ vision",
"fear",
"feather _ fall",
"feeblemind",
"find _ the _ path",
"find _ traps",
"finger _ of _ death",
"fire _ seeds",
"fire _ shield",
"fire _ storm",
"fire _ trap",
"fireball",
"flame _ arrow",
"flame _ blade",
"flame _ strike",
"flaming _ sphere",
"flare",
"flesh _ to _ stone",
"fly",
"floating _ disk",
"fog _ cloud",
"forbiddance",
"forcecage",
"forceful _ hand",
"foresight",
"fox's _ cunning",
"mass _ fox's _ cunning",
"freedom",
"freedom _ of _ movement",
"freezing _ sphere",
"gaseous _ form",
"gate",
"geas",
"quest",
"lesser _ geas",
"gentle _ repose",
"ghost _ sound",
"ghoul _ touch",
"giant _ vermin",
"glibness",
"glitterdust",
"globe _ of _ invulnerability",
"lesser _ globe _ of _ invulnerability",
"glyph _ of _ warding",
"greater _ glyph _ of _ warding",
"goodberry",
"good _ hope",
"grasping _ hand",
"grease",
"guards _ and _ wards",
"guidance",
"gust _ of _ wind",
"hallow",
"hallucinatory _ terrain",
"halt _ undead",
"harm",
"haste",
"heal",
"mass _ heal",
"heal _ mount",
"heat _ metal",
"helping _ hand",
"heroes' _ feast",
"heroism",
"greater _ heroism",
"hide _ from _ animals",
"hide _ from _ undead",
"hideous _ laughter",
"hold _ animal",
"hold _ monster",
"mass _ hold _ monster",
"hold _ person",
"mass _ hold _ person",
"hold _ portal",
"holy _ aura",
"holy _ smite",
"holy _ sword",
"holy _ word",
"horrid _ wilting",
"hypnotic _ pattern",
"hypnotism",
"ice _ storm",
"identify",
"illusory _ script",
"illusory _ wall",
"imbue _ with _ spell _ ability",
"implosion",
"imprisonment",
"incendiary _ cloud",
"inflict _ critical _ wounds",
"mass _ inflict _ critical _ wounds",
"inflict _ light _ wounds",
"mass _ inflict _ light _ wounds",
"inflict _ minor _ wounds",
"inflict _ moderate _ wounds",
"mass _ inflict _ moderate _ wounds",
"inflict _ serious _ wounds",
"mass _ inflict _ serious _ wounds",
"insanity",
"insect _ plague",
"instant _ summons",
"interposing _ hand",
"invisibility",
"greater _ invisibility",
"mass _ invisibility",
"invisibility _ purge",
"invisibility _ sphere",
"iron _ body",
"ironwood",
"irresistible _ dance",
"jump",
"keen _ edge",
"knock",
"know _ direction",
"legend _ lore",
"lesser _ (spell _ name)",
"levitate",
"light",
"lightning _ bolt",
"limited _ wish",
"liveoak",
"locate _ creature",
"locate _ object",
"longstrider",
"lullaby",
"mage _ armor",
"mage _ hand",
"mage's _ disjunction",
"mage's _ faithful _ hound",
"mage's _ lucubration",
"mage's _ magnificent _ mansion",
"mage's _ private _ sanctum",
"mage's _ sword",
"magic _ aura",
"magic _ circle _ against _ chaos",
"magic _ circle _ against _ evil",
"magic _ circle _ against _ good",
"magic _ circle _ against _ law",
"magic _ fang",
"greater _ magic _ fang",
"magic _ jar",
"magic _ missile",
"magic _ mouth",
"magic _ stone",
"magic _ vestment",
"magic _ weapon",
"greater _ magic _ weapon",
"major _ creation",
"major _ image",
"make _ whole",
"mark _ of _ justice",
"mass _ (spell _ name)",
"maze",
"meld _ into _ stone",
"mending",
"message",
"meteor _ swarm",
"mind _ blank",
"mind _ fog",
"minor _ creation",
"minor _ image",
"miracle",
"mirage _ arcana",
"mirror _ image",
"misdirection",
"mislead",
"mnemonic _ enhancer",
"modify _ memory",
"moment _ of _ prescience",
"mount",
"move _ earth",
"neutralize _ poison",
"nightmare",
"nondetection",
"obscure _ object",
"obscuring _ mist",
"open",
"close",
"order's _ wrath",
"overland _ flight",
"owl's _ wisdom",
"mass _ owl's _ wisdom",
"passwall",
"pass _ without _ trace",
"permanency",
"permanent _ image",
"persistent _ image",
"phantasmal _ killer",
"phantom _ steed",
"phantom _ trap",
"phase _ door",
"planar _ ally",
"greater _ planar _ ally",
"lesser _ planar _ ally",
"planar _ binding",
"greater _ planar _ binding",
"lesser _ planar _ binding",
"plane _ shift",
"plant _ growth",
"poison",
"polar _ ray",
"polymorph",
"polymorph _ any _ object",
"power _ word _ blind",
"power _ word _ kill",
"power _ word _ stun",
"prayer",
"prestidigitation",
"prismatic _ sphere",
"prismatic _ spray",
"prismatic _ wall",
"produce _ flame",
"programmed _ image",
"project _ image",
"protection _ from _ arrows",
"protection _ from _ chaos",
"protection _ from _ energy",
"protection _ from _ evil",
"protection _ from _ good",
"protection _ from _ law",
"protection _ from _ spells",
"prying _ eyes",
"greater _ prying _ eyes",
"purify _ food _ and _ drink",
"pyrotechnics",
"quench",
"rage",
"rainbow _ pattern",
"raise _ dead",
"ray _ of _ enfeeblement",
"ray _ of _ exhaustion",
"ray _ of _ frost",
"read _ magic",
"reduce _ animal",
"reduce _ person",
"mass _ reduce _ person",
"refuge",
"regenerate",
"reincarnate",
"remove _ blindness",
"remove _ deafness",
"remove _ curse",
"remove _ disease",
"remove _ fear",
"remove _ paralysis",
"repel _ metal _ or _ stone",
"repel _ vermin",
"repel _ wood",
"repulsion",
"resilient _ sphere",
"resistance",
"resist _ energy",
"restoration",
"greater _ restoration",
"lesser _ restoration",
"resurrection",
"reverse _ gravity",
"righteous _ might",
"rope _ trick",
"rusting _ grasp",
"sanctuary",
"scare",
"scintillating _ pattern",
"scorching _ ray",
"screen",
"scrying",
"greater _ scrying",
"sculpt _ sound",
"searing _ light",
"secret _ chest",
"secret _ page",
"secure _ shelter",
"see _ invisibility",
"seeming",
"sending",
"sepia _ snake _ sigil",
"sequester",
"shades",
"shadow _ conjuration",
"greater _ shadow _ conjuration",
"shadow _ evocation",
"greater _ shadow _ evocation",
"shadow _ walk",
"shambler",
"shapechange",
"shatter",
"shield",
"shield _ of _ faith",
"shield _ of _ law",
"shield _ other",
"shillelagh",
"shocking _ grasp",
"shout",
"greater _ shout",
"shrink _ item",
"silence",
"silent _ image",
"simulacrum",
"slay _ living",
"sleep",
"sleet _ storm",
"slow",
"snare",
"soften _ earth _ and _ stone",
"solid _ fog",
"song _ of _ discord",
"soul _ bind",
"sound _ burst",
"speak _ with _ animals",
"speak _ with _ dead",
"speak _ with _ plants",
"spectral _ hand",
"spell _ immunity",
"greater _ spell _ immunity",
"spell _ resistance",
"spellstaff",
"spell _ turning",
"spider _ climb",
"spike _ growth",
"spike _ stones",
"spiritual _ weapon",
"statue",
"status",
"stinking _ cloud",
"stone _ shape",
"stoneskin",
"stone _ tell",
"stone _ to _ flesh",
"storm _ of _ vengeance",
"suggestion",
"mass _ suggestion",
"summon _ instrument",
"summon _ monster",
"summon _ nature's _ ally",
"summon _ swarm",
"sunbeam",
"sunburst",
"symbol _ of _ death",
"symbol _ of _ fear",
"symbol _ of _ insanity",
"symbol _ of _ pain",
"symbol _ of _ persuasion",
"symbol _ of _ sleep",
"symbol _ of _ stunning",
"symbol _ of _ weakness",
"sympathetic _ vibration",
"sympathy",
"telekinesis",
"telekinetic _ sphere",
"telepathic _ bond",
"teleport",
"teleport _ object",
"greater _ teleport",
"teleportation _ circle",
"temporal _ stasis",
"time _ stop",
"tiny _ hut",
"tongues",
"touch _ of _ fatigue",
"touch _ of _ idiocy",
"transformation",
"transmute _ metal _ to _ wood",
"transmute _ mud _ to _ rock",
"transmute _ rock _ to _ mud",
"transport _ via _ plants",
"trap _ the _ soul",
"tree _ shape",
"tree _ stride",
"true _ resurrection",
"true _ seeing",
"true _ strike",
"undeath _ to _ death",
"undetectable _ alignment",
"unhallow",
"unholy _ aura",
"unholy _ blight",
"unseen _ servant",
"vampiric _ touch",
"veil",
"ventriloquism",
"virtue",
"vision",
"wail _ of _ the _ banshee",
"wall _ of _ fire",
"wall _ of _ force",
"wall _ of _ ice",
"wall _ of _ iron",
"wall _ of _ stone",
"wall _ of _ thorns",
"warp _ wood",
"water _ breathing",
"water _ walk",
"waves _ of _ exhaustion",
"waves _ of _ fatigue",
"web",
"weird",
"whirlwind",
"whispering _ wind",
"wind _ walk",
"wind _ wall",
"wish",
"wood _ shape",
"word _ of _ chaos",
"word _ of _ recall",
"zone _ of _ silence",
"zone _ of _ truth",
];
var thiefSpellList = [
'orc _ fire _ blade _ storm _ night _ lightnight _ fire _ rainbow',
'backstab',
'magic _ arrow',
'fire _ arrow',
'cold _ arrow',
'multiple _ shot',
'exploding _ arrow',
'ice _ arrow',
'guided _ arrow',
'strafe',
'immolation _ arrow',
'freezing _ arrow',
'critical _ strike',
'penetrate',
'valkyrie',
'pierce',
'jab',
'power _ strike',
'poison _ javelin',
'impale',
'lightning _ bolt',
'charged _ strike',
'plague _ javelin',
'fend',
'lightning _ strike',
'lightning _ fury',
'tiger _ strike',
'dragon _ talon',
'dragon _ claw',
'fists _ of _ fire',
'cobra _ strike',
'dragon _ tail',
'claws _ of _ thunder',
'blades _ of _ ice',
'dragon _ flight',
'phoenix _ strike',
'claw _ mastery',
'psychic _ hammer',
'burst _ of _ speed',
'cloak _ of _ shadows',
'weapon _ block',
'fade',
'shadow _ warrior',
'mind _ blast',
'venom',
'shadow _ master',
'fire _ blast',
'shock _ web',
'blade _ sentinel',
'charged _ bolt _ sentry',
'wake _ of _ fire',
'blade _ fury',
'lightning _ sentry',
'wake _ of _ inferno',
'death _ sentry',
'blade _ shield',
];
var fighterSpellList = [
'orc _ fire _ blade _ storm _ night _ lightnight _ fire _ rainbow',
'bash',
'leap',
'double _ swing',
'stun',
'double _ throw',
'leap _ attack',
'concentrate',
'frenzy',
'whirlwind',
'berserk',
'howl',
'find _ potion',
'taunt',
'shout',
'battle _ cry',
'battle _ orders',
'grim _ ward',
'war _ cry',
'battle _ command',
'sacrifice',
'smite',
'holy _ bolt',
'zeal',
'charge',
'vengeance',
'blessed _ hammer',
'conversion',
'holy _ shield',
'fist _ of _ the _ heavens',
'prayer',
'resist _ fire',
'resist _ cold',
'resist _ lightning',
'defiance',
'cleansing',
'vigor',
'meditation',
'redemption',
'salvation',
'might',
'holy _ fire',
'thorns',
'blessed _ aim',
'concentration',
'holy _ freeze',
'holy _ shock',
'sanctuary',
'fanaticism',
'conviction',
];


text:
/**
 *
 *
 * @description :: Server-side logic for managing your account
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */
 /*global Article User Like Share  ArticleQueryService ArticleService UserService*/
 /*eslint no-unused-vars: 0*/

var Promise = require('bluebird');

var config = {
  _limit : 0,
  _skipe : 0,
  _totalSize : 0,
  _setLimit : function setLimit(limit) {
    this._limit = limit;
  },
  _setSkip : function setSkip(skip) {
    this._skip = skip;
  },
  _setTotalSize : function setTotalSize(size) {
    this._totalSize = size;
  },
  _successRate : 0.5
};

var self = {
  _accentMap : function () {
    return {
      'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a', // a
      'ç': 'c',                                                   // c
      'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e',                     // e
      'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i',                     // i
      'ñ': 'n',                                                   // n
      'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ø': 'o', // o
      'ß': 's',                                                   // s
      'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u',                     // u
      'ÿ': 'y'                                                    // y
    };
  },
  _accentFold : function (str) {
    if (_.isNull(str) || _.isUndefined(str)) { return ''; }

    var ret = '';
    for (var i = 0; i < str.length; i++) {
      if(self._accentMap[str.charAt(i)])
        ret += self._accentMap[str.charAt(i)];
      else
        if(self._accentMap[str.charAt(i).toLowerCase()] && self._accentMap[str.charAt(i).toLowerCase()].toUpperCase())
          ret += self._accentMap[str.charAt(i).toLowerCase()].toUpperCase();
        else
          ret += str.charAt(i);
    }
    return ret;
  },
  searchString : function (str,wstr){
    if (_.isNull(str) || _.isUndefined(str)) { return false; }

    if(_.isArray(str) || _.isObject(str)) str = JSON.stringify(str);
    str = JSON.stringify(str);
    // Convert accent of the string , and search by reg expression
    return self._accentFold(str).search(new RegExp(self._accentFold(wstr), 'i')) > -1;
  },
  isSuccessfulQuery : function (arr,cnt){
    return !!(cnt >= (Math.round(_.size(arr)*config._successRate)));
  },
  isNotSuccessfulQuery : function (arr,cnt){
    sails.log(cnt,(Math.round(_.size(arr)*config._successRate)),(cnt >= (Math.round(_.size(arr)*config._successRate))));
    return !!(cnt >= (Math.round(_.size(arr)*config._successRate)));
  },
  matchWord : function (content,prms) {
    var success = 0;
    if (_.isNull(content) || _.isUndefined(content)) { return 0; }

    if(_.isArray(content) || _.isObject(content)) content = JSON.stringify(content);

    if(_.isArray(prms)){
      _.each(prms,function(pElem){
        if(self.searchString(content,pElem)) success = success + 1;
      });
      if(self.isSuccessfulQuery(prms,success)) return success;
    }
    else{
      if(self.searchString(content,prms)) return 1;
    }

    return 0;
  },
  notMatchWord : function (content,prms) {
    var success = true;
    if (_.isNull(content) || _.isUndefined(content)) { return true; }

    if(_.isArray(content) || _.isObject(content)) content = JSON.stringify(content);

    if(_.isArray(prms)){
      _.each(prms,function(pElem){
        if(self.searchString(content,pElem)){
          success = false;
          return false;
        }
      });
    }
    else{
      if(self.searchString(content,prms)) return false;
    }

    return success;
  },
  filterGeneral : function (arr,prms) {
    return _.filter(arr,function(aElem){
      var success = 0;
      _.each(prms,function(pElem){ //Parameters of query
        _.each(_.keys(aElem),function(akElem){
          var matches = self.matchWord(aElem[akElem],pElem);
          if(matches > 0) success = success + matches;
        });
      });
      aElem.success = success;
      return self.isSuccessfulQuery(prms,success);
    });
  },
  filterDate : function (arr,prm) {
    if(!Date.parse(_.values(prm.date)[0]))
      return [];

    return _.filter(arr,function(aElem){
      aElem.date = aElem.state === 'edit' ?
      new Date(aElem.updatedAt) : new Date(aElem.createdAt);

      if(_.has(prm.date,'before'))
        return aElem.date.setHours(0,0,0) <= new Date(prm.date.before).setHours(0,0,0);

      if(_.has(prm.date,'after'))
        return aElem.date.setHours(0,0,0) >= new Date(prm.date.after).setHours(0,0,0);
    });
  },
  filterByNotContain : function (arr,prms) {
    return _.filter(arr,function(aElem){
      var sucess = false;
      var not_match = true;
      _.each(prms,function(pElem){ //Parameters of query
        _.each(_.keys(aElem),function(akElem){
          var match = self.notMatchWord(aElem[akElem],pElem);
          if(!match) {
            not_match = false;
            return false;
          }
        });
      });
      aElem.success = not_match;
      return not_match;
    });
  },
  filterByParams : function (arr,prms) {
    return _.filter(arr,function(aElem){
      var success = 0;
      _.each(_.keys(prms),function(wkElem){ //Parameters of query
        if(_.has(aElem,wkElem))
        {
          var matches = self.matchWord(aElem[wkElem],prms[wkElem]);
          if(matches > 0) success = success + matches;
        }
      });
      aElem.success = success;
      return self.isSuccessfulQuery(prms,success);
    });
  }
};

module.exports = {
  /**
   * Base query with default conditions on sort & state filter
   * @param  {request} req
   * @param  {string} sortQuery
   * @param  {Criteria} stateCondition
   * @return {query}
   */
  _baseQuery :function (req,sortQuery,stateCondition) {
    UserService.current(req.user); // Set  current user

    ArticleQueryService.getTotalSize().then(function (size) {
      config._setTotalSize(size); // All size of articles in DB
    });
    config._setLimit(ArticleQueryService.getLimit(req));
    config._setSkip(ArticleQueryService.getSkip(req));
    var query = Article.find(stateCondition || { state: { '!': 'disable' }})
                        .limit(ArticleQueryService.getLimit(req))
                        .skip(ArticleQueryService.getSkip(req))
                        .sort(sortQuery || 'updatedAt DESC')
                        .populate('creator')
                        .populate('categories')
                        .populate('likes')
                        .populate('shares')
                        .populate('visits');

    return query;
  },
  _baseOneQuery :function (req) {
    UserService.current(req.user); // Set  current user

    var field = req.param('field');
    var fvalue = req.param('value');
    var fquery = {};
    fquery[field] = fvalue ;

    var query = Article.findOne(fquery)
                        .populate('creator')
                        .populate('categories')
                        .populate('likes')
                        .populate('shares')
                        .populate('visits');

    return query;
  },
  getTotalSize : function (){
    return new Promise(function (resolve){
      Article.count({state:['create', 'edit']}).exec(function countCB(err, found){
        if(err) sails.log.warn(err);
        resolve(found);
      });
    });
  },
  getLimit: function (req) {
    var DEFAULT_LIMIT = sails.config.blueprints.defaultLimit || 10;
    var limit = req.param('limit') || (typeof req.options.limit !== 'undefined' ? req.options.limit : DEFAULT_LIMIT);
    if (limit) { limit = +limit; }
    return limit;
  },
  getSkip: function (req) {
    var DEFAULT_SKIP = 0;
    var skip = req.param('skip') || (typeof req.options.skip !== 'undefined' ? req.options.skip : DEFAULT_SKIP);
    if (skip) { skip = +skip; }
    return skip;
  },
  getArticleListBase : function (articleListData){
    return new Promise(function(resolve){
      var articlesList = [];

      sails.log.debug('-->Total Original Size of Elements:',config._totalSize,'>',
      'Total Size of Elements Found:',articleListData.length);
      articleListData.some(function (article,index) {
        //   if(article.state !== 'disable')
        if(!_.isUndefined(article)){
          sails.log.debug('-i:',index+1,'id:',article.id,'>:',article.success || article.title,'+:',article.updatedAt);
          articlesList.push(ArticleService.getArticleStructure(article));
        }
        return articlesList.length === config._limit;
      });

      resolve({
        size:articleListData.length, // Total Size of Elements
        total:articlesList.length, // Number Elements respect to limit & state
        results:articlesList //Elements
      });
    });
  },
  //Get One article
  getArticleByField : function (articleQuery){
    return new Promise(function(resolve,reject){
      articleQuery.then(function (article) {

        if(_.isUndefined(article))
        {
          sails.log.debug('-->Not found element');
          return  reject(new Error('No found element'));
        }

        sails.log.debug('-->Element Found:');
        sails.log.debug('-i:',1,'id:',article.id,'>:',article.success || article.title,'+:',article.updatedAt);

        article = ArticleService.getArticleStructure(article);

        return resolve({
          total: 1, // 1
          results: article //Element
        });
      });

    });
  },
  getArticleListByQuery : function (articleQuery,whereQuery){
    return new Promise(function(resolve){

      var blacklist = ['general', 'date','not'];
      var whereGeneral,whereDate,whereNot;
      whereGeneral = whereDate = whereNot = [];

      delete articleQuery._criteria['limit'];

      articleQuery.then(function (articles){

        // Omit built-in runtime config (like query modifiers)
        whereNot = _.pick(whereQuery, 'not');
        whereGeneral = _.pick(whereQuery, 'general');
        whereDate = _.pick(whereQuery, 'date');
        whereQuery = _.omit(whereQuery, blacklist);

        if(!_.isEmpty(whereNot))
        {
          sails.log('->Query Not Contain');
          articles = self.filterByNotContain(articles,whereNot);
        }

        if(!_.isEmpty(whereGeneral))
        {
          sails.log('->Query General');
          articles = self.filterGeneral(articles,whereGeneral);
        }

        if(!_.isEmpty(whereQuery) && !_.isNull(whereQuery))
        {
          sails.log('->Query By Params');
          articles = self.filterByParams(articles,whereQuery);
        }

        articles.sort(function(a, b) {
          return b.success - a.success;
        });

        if(!_.isEmpty(whereDate))
        {
          sails.log('->Query Date');
          articles = self.filterDate(articles,whereDate);
        }

        sails.log.debug('-->After of Query');
        _.each(articles,function (el) {
          sails.log.debug(el.id,'>:',el.title,'sc:',el.success);
        });

        ArticleQueryService.getArticleListBase(articles)
        .then(function (response) {
          resolve(response);
        });
      });
    });
  },
  getArticleListNormal : function (articleQuery){
    sails.log.debug('+ List of all elements');
    return new Promise(function(resolve){
      articleQuery.then(function (articles){

        articles.sort(function(a, b) {
          return (b.date - a.date)+(b.id - a.id);
        });

        ArticleQueryService.getArticleListBase(articles)
        .then(function (response) {
          response.size = config._totalSize;
          resolve(response);
        });
      });
    });
  },
  getArticleListRecommend : function (articleQuery){
    sails.log.debug('+ List of elements recommends based on formula');
    return new Promise(function(resolve){

      delete articleQuery._criteria['limit'];

      articleQuery.then(function (articles){

        articles.sort(function(a, b) {
          return ArticleService.getRecom(b.likes.length,b.shares.length,b.visits.length) -
                        ArticleService.getRecom(a.likes.length,a.shares.length,a.visits.length);
        });

        ArticleQueryService.getArticleListBase(articles)
        .then(function (response) {
          resolve(response);
        });

      });
    });
  },
  getArticleListByCreator : function (articleQuery,creator){
    sails.log.debug('+ List of elements filter by creator');
    return new Promise(function(resolve,reject){

      delete articleQuery._criteria['limit'];

      User.findOne({name:creator}).then( function(creatorRecord){

        sails.log.debug('+ Filter By Creator >',JSON.stringify(creatorRecord));
        if(_.isUndefined(creatorRecord))
        {
          sails.log.debug('-->Not found element of the creator');
          return  reject(new Error('No found element of the creator'));
        }

        articleQuery.where({'creator':creatorRecord.id});

        articleQuery.then(function (articles){
          articles.sort(function(a, b) {
            return b.date - a.date;
          });

          ArticleQueryService.getArticleListBase(articles)
          .then(function (response) {
            resolve(response);
          });
        })
        .catch(function(err){
          sails.log.error(err);
        });

      });

    });
  },
  getArticleListByCategory : function (articleQuery,category){
    sails.log.debug('+ List of elements filter by category');
    return new Promise(function(resolve){
      delete articleQuery._criteria['limit'];
      articleQuery.then(function (articles){

        articles = _.filter(articles,function (article) {
          return _.some(article.categories, function(acElem) {
            return acElem.name === category;
          });
        });

        articles.sort(function(a, b) {
          return b.date - a.date;
        });

        ArticleQueryService.getArticleListBase(articles)
        .then(function (response) {
          resolve(response);
        });

      });
    });
  },
  getArticleListMostLiked : function (articleQuery){
    sails.log.debug('+ List of most liked elements:');
    return new Promise(function(resolve){
      delete articleQuery._criteria['limit'];
      articleQuery.then(function (articles){

        articles.sort(function(a, b) {
          return b.likes.length - a.likes.length;
        });

        ArticleQueryService.getArticleListBase(articles)
        .then(function (response) {
          resolve(response);
        });

      });
    });
  },
  getArticleListMostShared : function (articleQuery){
    sails.log.debug('+ List of most shared elements:');
    return new Promise(function(resolve){
      delete articleQuery._criteria['limit'];
      articleQuery.then(function (articles){

        articles.sort(function(a, b) {
          return b.shares.length - a.shares.length;
        });

        ArticleQueryService.getArticleListBase(articles)
        .then(function (response) {
          resolve(response);
        });

      });
    });
  }
};


text:
package org.apache.directory.server.xdbm;

import org.apache.directory.api.ldap.model.schema.comparators.SerializableComparator;

/**
 * A comparator used to compare {@link ParentIdAndRdn} stored in the Rdn index.
 *
 * @author Apache Directory Project
 */
public class ParentIdAndRdnComparator<I extends Comparable> extends SerializableComparator<ParentIdAndRdn>
{
    /** The serial version UID */
    private static final long serialVersionUID = 2L;

    /**
     * Creates a new instance of ParentIdAndRdnComparator.
     *
     * @param matchingRuleOid The associated MatchingRule
     */
    public ParentIdAndRdnComparator( String matchingRuleOid )
    {
        super( matchingRuleOid );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public int compare( ParentIdAndRdn rdn1, ParentIdAndRdn rdn2 )
    {
        return rdn1.compareTo( rdn2 );
    }
}


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

using System.Diagnostics.CodeAnalysis;
using Microsoft.OData.Edm;

namespace System.Web.OData.Routing
{
    /// <summary>
    /// Exposes the ability to parse an OData path template as an <see cref="ODataPathTemplate"/>.
    /// </summary>
    public interface IODataPathTemplateHandler
    {
        /// <summary>
        /// Parses the specified OData path template as an <see cref="ODataPathTemplate"/>.
        /// </summary>
        /// <param name="model">The model to use for path template parsing.</param>
        /// <param name="odataPathTemplate">The OData path template to parse.</param>
        /// <returns>A parsed representation of the template, or <c>null</c> if the template does not match the model.</returns>
        [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "odata", Justification = "odata is spelled correctly")]
        ODataPathTemplate ParseTemplate(IEdmModel model, string odataPathTemplate);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<feed><tipo>Rua</tipo><logradouro>Gurgel</logradouro><bairro>Tabuba</bairro><cidade>Caucaia</cidade><uf>CE</uf><cep>61618450</cep></feed>


text:
import * as React from 'react';

export default class Func3 extends React.Component<any,any> {

  render() {
    return (

        func3

    )
  };
}


text:
/*
 * ppp_pg.c: packet generator ppp interface
 *
 * Copyright (c) 2008 Eliot Dresselhaus
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include <vlib/vlib.h>
#include <vnet/pg/pg.h>
#include <vnet/ppp/ppp.h>

typedef struct {
  pg_edit_t address;
  pg_edit_t control;
  pg_edit_t protocol;
} pg_ppp_header_t;

static inline void
pg_ppp_header_init (pg_ppp_header_t * e)
{
  pg_edit_init (&e->address, ppp_header_t, address);
  pg_edit_init (&e->control, ppp_header_t, control);
  pg_edit_init (&e->protocol, ppp_header_t, protocol);
}

uword
unformat_pg_ppp_header (unformat_input_t * input, va_list * args)
{
  pg_stream_t * s = va_arg (*args, pg_stream_t *);
  pg_ppp_header_t * h;
  u32 group_index, error;

  h = pg_create_edit_group (s, sizeof (h[0]), sizeof (ppp_header_t),
			    &group_index);
  pg_ppp_header_init (h);

  pg_edit_set_fixed (&h->address, 0xff);
  pg_edit_set_fixed (&h->control, 0x03);

  error = 1;
  if (! unformat (input, "%U",
		  unformat_pg_edit,
		    unformat_ppp_protocol_net_byte_order, &h->protocol))
    goto done;

  {
    ppp_main_t * pm = &ppp_main;
    ppp_protocol_info_t * pi = 0;
    pg_node_t * pg_node = 0;

    if (h->protocol.type == PG_EDIT_FIXED)
      {
	u16 t = *(u16 *) h->protocol.values[PG_EDIT_LO];
	pi = ppp_get_protocol_info (pm, clib_net_to_host_u16 (t));
	if (pi && pi->node_index != ~0)
	  pg_node = pg_get_node (pi->node_index);
      }

    if (pg_node && pg_node->unformat_edit
	&& unformat_user (input, pg_node->unformat_edit, s))
      ;

    else if (! unformat_user (input, unformat_pg_payload, s))
      goto done;
  }

  error = 0;
 done:
  if (error)
    pg_free_edit_group (s);
  return error == 0;
}


text:
Thanks for being willing to contribute!

**Working on your first Pull Request?** You can learn how from this *free* series
[How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github)

## Project setup

```bash
# Install dependencies
$ npm install
# Build files in watch mode
$ npm run dev
```


text:
ironic_dnsmasq
==============

Do not under any circumstances run this code, it will ruin your life. Caveat emptor.

Get the code:

        git clone https://github.com/marios/ironic_dnsmasq.git
        cd ironic_dnsmasq

Edit the configuration to your needs - there are 2 parts:

        1. The dnsmasq configuration - IP range, PXE options:
        vim example_dnsmasq_conf

        2. The config for this script at ironic_dnsmasq_conf
        This file _must_ be kept in the same location that ironic_dnsmasq.sh
        is invoked from (it is sourced to set the configuration for the script)

Run discovery dnsmasq:

        ./ironic_dnsmasq.sh

Kill discovery dnsmasq:

        cd ironic_dnsmasq
        sed -i 's/RUN_DISCOVERY=True/RUN_DISCOVERY=False/g' ironic_dnsmasq_conf


text:
package org.apache.hadoop.hdfs.web;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.DelegationTokenRenewer;
import org.apache.hadoop.fs.DelegationTokenRenewer.RenewAction;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.security.token.delegation.DelegationTokenIdentifier;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.security.SecurityUtilTestHelper;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.TokenIdentifier;
import org.apache.hadoop.util.Progressable;
import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;

public class TestTokenAspect {

  private static class DummyFs extends FileSystem implements
      DelegationTokenRenewer.Renewable, TokenAspect.TokenManagementDelegator {

    private static final Text TOKEN_KIND = new Text("DummyFS Token");
    private boolean emulateSecurityEnabled;
    private TokenAspect<DummyFs> tokenAspect;
    private UserGroupInformation ugi = UserGroupInformation
        .createUserForTesting("foo", new String[] { "bar" });
    private URI uri;

    @Override
    public FSDataOutputStream append(Path f, int bufferSize,
        Progressable progress) throws IOException {
      return null;
    }

    @Override
    public void cancelDelegationToken(Token<?> token) throws IOException {
    }

    @Override
    public FSDataOutputStream create(Path f, FsPermission permission,
        boolean overwrite, int bufferSize, short replication, long blockSize,
        Progressable progress) throws IOException {
      return null;
    }

    @Override
    public boolean delete(Path f, boolean recursive) throws IOException {
      return false;
    }

    @Override
    public URI getCanonicalUri() {
      return super.getCanonicalUri();
    }

    @Override
    public FileStatus getFileStatus(Path f) throws IOException {
      return null;
    }

    @Override
    public Token<?> getRenewToken() {
      return null;
    }

    @Override
    public URI getUri() {
      return uri;
    }

    @Override
    public Path getWorkingDirectory() {
      return null;
    }

    @Override
    public void initialize(URI name, Configuration conf) throws IOException {
      super.initialize(name, conf);
      setConf(conf);
      try {
        this.uri = new URI(name.getScheme(), name.getAuthority(), null, null,
            null);
      } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
      }

      tokenAspect = new TokenAspect<DummyFs>(this, DummyFs.TOKEN_KIND);
      if (emulateSecurityEnabled || UserGroupInformation.isSecurityEnabled()) {
        tokenAspect.initDelegationToken(ugi);
      }
    }

    @Override
    public FileStatus[] listStatus(Path f) throws FileNotFoundException,
        IOException {
      return null;
    }

    @Override
    public boolean mkdirs(Path f, FsPermission permission) throws IOException {
      return false;
    }

    @Override
    public FSDataInputStream open(Path f, int bufferSize) throws IOException {
      return null;
    }

    @Override
    public boolean rename(Path src, Path dst) throws IOException {
      return false;
    }

    @Override
    public long renewDelegationToken(Token<?> token) throws IOException {
      return 0;
    }

    @Override
    public <T extends TokenIdentifier> void setDelegationToken(Token<T> token) {
    }

    @Override
    public void setWorkingDirectory(Path new_dir) {
    }
  }

  private static RenewAction<?> getActionFromTokenAspect(
      TokenAspect<DummyFs> tokenAspect) {
    return (RenewAction<?>) Whitebox.getInternalState(tokenAspect, "action");
  }

  @Test
  public void testCachedInitialization() throws IOException, URISyntaxException {
    Configuration conf = new Configuration();
    DummyFs fs = spy(new DummyFs());
    Token<TokenIdentifier> token = new Token<TokenIdentifier>(new byte[0],
        new byte[0], DummyFs.TOKEN_KIND, new Text("127.0.0.1:1234"));

    doReturn(token).when(fs).getDelegationToken(anyString());
    doReturn(token).when(fs).getRenewToken();

    fs.emulateSecurityEnabled = true;
    fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf);

    fs.tokenAspect.ensureTokenInitialized();
    verify(fs, times(1)).getDelegationToken(null);
    verify(fs, times(1)).setDelegationToken(token);

    // For the second iteration, the token should be cached.
    fs.tokenAspect.ensureTokenInitialized();
    verify(fs, times(1)).getDelegationToken(null);
    verify(fs, times(1)).setDelegationToken(token);
  }

  @Test
  public void testGetRemoteToken() throws IOException, URISyntaxException {
    Configuration conf = new Configuration();
    DummyFs fs = spy(new DummyFs());
    Token<TokenIdentifier> token = new Token<TokenIdentifier>(new byte[0],
        new byte[0], DummyFs.TOKEN_KIND, new Text("127.0.0.1:1234"));

    doReturn(token).when(fs).getDelegationToken(anyString());
    doReturn(token).when(fs).getRenewToken();

    fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf);

    fs.tokenAspect.ensureTokenInitialized();

    // Select a token, store and renew it
    verify(fs).setDelegationToken(token);
    assertNotNull(Whitebox.getInternalState(fs.tokenAspect, "dtRenewer"));
    assertNotNull(Whitebox.getInternalState(fs.tokenAspect, "action"));
  }

  @Test
  public void testGetRemoteTokenFailure() throws IOException,
      URISyntaxException {
    Configuration conf = new Configuration();
    DummyFs fs = spy(new DummyFs());
    IOException e = new IOException();
    doThrow(e).when(fs).getDelegationToken(anyString());

    fs.emulateSecurityEnabled = true;
    fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf);
    try {
      fs.tokenAspect.ensureTokenInitialized();
    } catch (IOException exc) {
      assertEquals(e, exc);
    }
  }

  @Test
  public void testInitWithNoTokens() throws IOException, URISyntaxException {
    Configuration conf = new Configuration();
    DummyFs fs = spy(new DummyFs());
    doReturn(null).when(fs).getDelegationToken(anyString());
    fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf);

    fs.tokenAspect.ensureTokenInitialized();

    // No token will be selected.
    verify(fs, never()).setDelegationToken(
        Mockito.<Token<? extends TokenIdentifier>> any());
  }

  @Test
  public void testInitWithUGIToken() throws IOException, URISyntaxException {
    Configuration conf = new Configuration();
    DummyFs fs = spy(new DummyFs());
    doReturn(null).when(fs).getDelegationToken(anyString());

    Token<TokenIdentifier> token = new Token<TokenIdentifier>(new byte[0],
        new byte[0], DummyFs.TOKEN_KIND, new Text("127.0.0.1:1234"));
    fs.ugi.addToken(token);
    fs.ugi.addToken(new Token<TokenIdentifier>(new byte[0], new byte[0],
        new Text("Other token"), new Text("127.0.0.1:8021")));
    assertEquals("wrong tokens in user", 2, fs.ugi.getTokens().size());

    fs.emulateSecurityEnabled = true;
    fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf);
    fs.tokenAspect.ensureTokenInitialized();

    // Select a token from ugi (not from the remote host), store it but don't
    // renew it
    verify(fs).setDelegationToken(token);
    verify(fs, never()).getDelegationToken(anyString());
    assertNull(Whitebox.getInternalState(fs.tokenAspect, "dtRenewer"));
    assertNull(Whitebox.getInternalState(fs.tokenAspect, "action"));
  }

  @Test
  public void testRenewal() throws Exception {
    Configuration conf = new Configuration();
    Token<?> token1 = mock(Token.class);
    Token<?> token2 = mock(Token.class);
    final long renewCycle = 100;
    DelegationTokenRenewer.renewCycle = renewCycle;

    UserGroupInformation ugi = UserGroupInformation.createUserForTesting("foo",
        new String[] { "bar" });
    DummyFs fs = spy(new DummyFs());

    doReturn(token1).doReturn(token2).when(fs).getDelegationToken(null);
    doReturn(token1).when(fs).getRenewToken();
    // cause token renewer to abandon the token
    doThrow(new IOException("renew failed")).when(token1).renew(conf);
    doThrow(new IOException("get failed")).when(fs).addDelegationTokens(null,
        null);

    TokenAspect<DummyFs> tokenAspect = new TokenAspect<DummyFs>(fs,
        DummyFs.TOKEN_KIND);
    fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf);
    tokenAspect.initDelegationToken(ugi);

    // trigger token acquisition
    tokenAspect.ensureTokenInitialized();
    DelegationTokenRenewer.RenewAction<?> action = getActionFromTokenAspect(tokenAspect);
    verify(fs).setDelegationToken(token1);
    assertTrue(action.isValid());

    // upon renewal, token will go bad based on above stubbing
    Thread.sleep(renewCycle * 2);
    assertSame(action, getActionFromTokenAspect(tokenAspect));
    assertFalse(action.isValid());

    // now that token is invalid, should get a new one
    tokenAspect.ensureTokenInitialized();
    verify(fs, times(2)).getDelegationToken(anyString());
    verify(fs).setDelegationToken(token2);
    assertNotSame(action, getActionFromTokenAspect(tokenAspect));

    action = getActionFromTokenAspect(tokenAspect);
    assertTrue(action.isValid());
  }

  @Test
  public void testTokenSelectionPreferences() throws IOException,
      URISyntaxException {
    Configuration conf = new Configuration();
    DummyFs fs = spy(new DummyFs());
    doReturn(null).when(fs).getDelegationToken(anyString());
    fs.initialize(new URI("dummyfs://localhost:1234"), conf);
    TokenAspect<DummyFs> aspect = new TokenAspect<DummyFs>(fs,
        DummyFs.TOKEN_KIND);
    UserGroupInformation ugi = UserGroupInformation.createUserForTesting("foo",
        new String[] { "bar" });

    // use ip-based tokens
    SecurityUtilTestHelper.setTokenServiceUseIp(true);

    // test fallback to hdfs token
    Token<TokenIdentifier> hdfsToken = new Token<TokenIdentifier>(new byte[0],
        new byte[0], DelegationTokenIdentifier.HDFS_DELEGATION_KIND, new Text(
            "127.0.0.1:8020"));
    ugi.addToken(hdfsToken);

    // test fallback to hdfs token
    Token<?> token = aspect.selectDelegationToken(ugi);
    assertEquals(hdfsToken, token);

    // test dummyfs is favored over hdfs
    Token<TokenIdentifier> dummyFsToken = new Token<TokenIdentifier>(
        new byte[0], new byte[0], DummyFs.TOKEN_KIND,
        new Text("127.0.0.1:1234"));
    ugi.addToken(dummyFsToken);
    token = aspect.selectDelegationToken(ugi);
    assertEquals(dummyFsToken, token);

    // switch to using host-based tokens, no token should match
    SecurityUtilTestHelper.setTokenServiceUseIp(false);
    token = aspect.selectDelegationToken(ugi);
    assertNull(token);

    // test fallback to hdfs token
    hdfsToken = new Token<TokenIdentifier>(new byte[0], new byte[0],
        DelegationTokenIdentifier.HDFS_DELEGATION_KIND, new Text(
            "localhost:8020"));
    ugi.addToken(hdfsToken);
    token = aspect.selectDelegationToken(ugi);
    assertEquals(hdfsToken, token);

    // test dummyfs is favored over hdfs
    dummyFsToken = new Token<TokenIdentifier>(new byte[0], new byte[0],
        DummyFs.TOKEN_KIND, new Text("localhost:1234"));
    ugi.addToken(dummyFsToken);
    token = aspect.selectDelegationToken(ugi);
    assertEquals(dummyFsToken, token);
  }
}


text:
import { SofeventsShowComponent } from './show/sofevents.show.component';
import { SofeventsAddComponent } from './add/sofevents.add.component';
// import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { ChartsModule } from 'ng2-charts/ng2-charts';
import { CommonModule } from '@angular/common';
import { SofeventsComponent } from './sofevents.component';
import { SofeventsRoutingModule } from './sofevents-routing.module';

@NgModule({
  imports: [
    SofeventsRoutingModule,
    // BrowserAnimationsModule,
    ChartsModule,
    CommonModule
  ],
  declarations: [
    SofeventsComponent,
    SofeventsAddComponent,
    SofeventsShowComponent,
     ]
})
export class SofeventsModule { }


text:
import random

print random.choice([
    "You're awesome",
    "You're incredible",
    "Have a great day",
    "Show em how it's done",
    "Shoot for the moon",
    "Be excellent",
    "Hakuna Matata",
    "Don't worry, be happy",
    "Smile",
    "Keep calm and HACK",
    "Let's Go",
    "Take it easy",
    "You got this",
    "Go get em",
    "Great job"
    ]) + '! :)'


text:
package logger_test

import (
	"testing"

	"github.com/govlas/logger"
)

func TestLogger(t *testing.T) {

	logger.Info("Info")
	logger.Warning("Warning")
	logger.Error("Error")
	logger.Debug("Debug")

	logger.EnableColored()

	logger.Info("Info colored")
	logger.Warning("Warning colored")
	logger.Error("Error colored")
	logger.Debug("Debug colored")

	logger.DisableBTrace()

	logger.Info("Info colored")
	logger.Warning("Warning colored")
	logger.Error("Error colored")
	logger.Debug("Debug colored")

	logger.SetFileName(logger.FileNameShort)

	logger.Info("Info short filename")
	logger.Warning("Warning short filename")
	logger.Error("Error short filename")
	logger.Debug("Debug short filename")

	logger.SetFileName(logger.FileNameLong)

	logger.Info("Info long filename")
	logger.Warning("Warning long filename")
	logger.Error("Error long filename")
	logger.Debug("Debug long filename")
}


text:
void hilti_abort(hlt_exception** excpt)
{
    fprintf(stderr, "Hilti::abort() called.");
    abort();
}

void hilti_terminate(hlt_exception** excpt, hlt_execution_context* ctx)
{
    hlt_set_exception(excpt, &hlt_exception_termination, 0, ctx);
}

// A non-yielding sleep.
void hilti_sleep(double secs, hlt_exception** excpt, hlt_execution_context* ctx)
{
    hlt_thread_mgr* mgr = hlt_global_thread_mgr();

    // Flush our job queues so that the stuff can get processes.
    for ( int i = 0; i < mgr->num_workers; ++i )
        hlt_thread_queue_flush(mgr->workers[i]->jobs, 0);

    struct timespec sleep_time;
    sleep_time.tv_sec = (time_t)secs;
    sleep_time.tv_nsec = (time_t)((secs - sleep_time.tv_sec) * 1e9);

    while ( nanosleep(&sleep_time, &sleep_time) )
        continue;
}

void hilti_wait_for_threads()
{
    hlt_thread_mgr_set_state(hlt_global_thread_mgr(), HLT_THREAD_MGR_FINISH);
}


text:
require 'spec_helper'

module SearchResults
  describe ResultMapperBuilder do

  end
end


text:
package cab2b.server.caarray.resulttransformer;

import java.util.Set;

import cab2b.common.caarray.CaArrayRecord;
import cab2b.common.caarray.ICaArrayRecord;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.wustl.cab2b.common.queryengine.result.RecordId;

/**
 * The default implementation of caArray result transformer that creates the
 * basic {@link ICaArrayRecord}.
 *
 * @author srinath_k
 *
 */
public class DefaultCaArrayResultTransformer extends AbstractCaArrayResultTransfomer<ICaArrayRecord> {

    /**
     * Creates the basic {@link CaArrayRecord}.
     *
     * @see cab2b.server.caarray.resulttransformer.AbstractCaArrayResultTransfomer#createCaArrayRecord(java.util.Set,
     *      edu.wustl.cab2b.common.queryengine.result.RecordId)
     */
    @Override
    protected ICaArrayRecord createCaArrayRecord(Set<AttributeInterface> attributes, RecordId id) {
        return new CaArrayRecord((attributes), id);
    }

}


text:
package diffson.lcs

import cats.Eq
import cats.implicits._

import scala.annotation.tailrec
import scala.collection.SortedMap
import scala.collection.immutable.TreeMap
import scala.collection.compat._

/** Implementation of the patience algorithm [1] to compute the longest common subsequence
 *
 *  [1] http://alfedenzo.livejournal.com/170301.html
 *
 *  @param withFallback whether to fallback to classic LCS when patience could not find the LCS
 *  @author Lucas Satabin
 */
class Patience[T: Eq](withFallback: Boolean = true) extends Lcs[T] {

  // algorithm we fall back to when patience algorithm is unable to find the LCS
  private val classicLcs =
    if (withFallback) Some(new DynamicProgLcs[T]) else None

  /** An occurrence of a value associated to its index */
  type Occurrence = (T, Int)

  /** Returns occurrences that appear only once in the list, associated with their index */
  private def uniques(l: List[T]): Map[T, Int] = {
    @tailrec
    def loop(l: List[Occurrence], acc: Map[T, Int]): Map[T, Int] = l match {
      case (value, idx) :: tl =>
        if (acc.contains(value))
          // not unique, remove it from the accumulator and go further
          loop(tl, acc - value)
        else
          loop(tl, acc + (value -> idx))
      case Nil =>
        acc
    }
    loop(l.zipWithIndex, Map.empty)
  }

  /** Takes all occurences from the first sequence and order them as in the second sequence if it is present */
  private def common(l1: Map[T, Int], l2: Map[T, Int]): List[(Occurrence, Int)] = {
    @tailrec
    def loop(l: List[Occurrence], acc: List[(Occurrence, Int)]): List[(Occurrence, Int)] = l match {
      case occ :: tl =>
        // find the element in the second sequence if present
        l2.get(occ._1) match {
          case Some(idx2) => loop(tl, (occ -> idx2) :: acc)
          case None       => loop(tl, acc)
        }
      case Nil =>
        // sort by order of appearance in the second sequence
        acc sortWith (_._2 < _._2)
    }
    loop(l1.toList, Nil)
  }

  /** Returns the list of elements that appear only once in both l1 and l2 ordered as they appear in l2 with their index in l1 */
  private def uniqueCommons(seq1: List[T], seq2: List[T]): List[(Occurrence, Int)] = {
    // the values that occur only once in the first sequence
    val uniques1 = uniques(seq1)
    // the values that occur only once in the second sequence
    val uniques2 = uniques(seq2)
    // now order the unique occurrences as they appear in the second list
    common(uniques1, uniques2)
  }

  /** Returns the longest sequence */
  private def longest(l: List[(Occurrence, Int)]): List[(Int, Int)] = {
    if (l.isEmpty) {
      Nil
    } else {
      type Stack = List[Stacked]

      def push(idx1: Int, idx2: Int, stacks: TreeMap[Int, Stack]): TreeMap[Int, Stack] = {
        stacks.iteratorFrom(idx1).take(1).toList.headOption match {
          case None =>
            // corresponding stack not found, create a new one
            val chainCont = stacks.lastOption.flatMap(_._2.headOption)
            stacks.updated(idx1, Stacked(idx1, idx2, chainCont) :: Nil)
          case Some((idx, oldStack)) =>
            // we found the right stack, replace it by new version
            val chainCont = {
              // we have to find a previous stack
              // don't know how efficient `until` is...
              stacks.rangeUntil(idx).lastOption.flatMap(_._2.headOption)
            }
            (stacks - idx).updated(idx1, Stacked(idx1, idx2, chainCont) :: oldStack)
        }
      }

      def sort(l: List[(Occurrence, Int)]): TreeMap[Int, Stack] = {
        // foreach item push it onto earliest stack for which: stack.idx1 > item.idx1
        // or create a new stack for it if none can be found

        // stacks are kept in a treeMap (minValue -> stack)
        // it makes it efficient to find the correct stack to update

        l.foldLeft(TreeMap.empty[Int, Stack]) { case (acc, ((_, idx1), idx2)) =>
          push(idx1, idx2, acc)
        }
      }
      val sorted = sort(l)
      // this call is safe as we know that the list of occurrence is not empty here and that there are no empty stacks
      val greatest = sorted.last._2.head
      // make the lcs in increasing order
      greatest.chain
    }
  }

  /** Checks if two sequences have at least one common element */
  private def haveCommonElements(s1: List[T], s2: List[T]): Boolean = {
    val s2Set = s2.toSet
    s1.exists(s2Set)
  }

  /** Computes the longest common subsequence between both sequences.
   *  It is encoded as the list of common indices in the first and the second sequence.
   */
  def lcs(s1: List[T], s2: List[T], low1: Int, high1: Int, low2: Int, high2: Int): List[(Int, Int)] = {
    val seq1 = s1.slice(low1, high1)
    val seq2 = s2.slice(low2, high2)
    if (seq1.isEmpty || seq2.isEmpty) {
      // shortcut if at least on sequence is empty, the lcs, is empty as well
      Nil
    } else if (seq1 === seq2) {
      // both sequences are equal, the lcs is either of them
      seq1.indices.map(i => (i + low1, i + low2)).toList
    } else if (seq1.startsWith(seq2)) {
      // the second sequence is a prefix of the first one
      // the lcs is the second sequence
      seq2.indices.map(i => (i + low1, i + low2)).toList
    } else if (seq2.startsWith(seq1)) {
      // the first sequence is a prefix of the second one
      // the lcs is the first sequence
      seq1.indices.map(i => (i + low1, i + low2)).toList
    } else if (!haveCommonElements(seq1, seq2)) {
      // sequences have no common elements
      Nil
    } else {
      // fill the holes with possibly common (not unique) elements
      def loop(low1: Int, low2: Int, high1: Int, high2: Int, acc: List[(Int, Int)]): List[(Int, Int)] =
        if (low1 == high1 || low2 == high2) {
          acc
        } else {
          var lastPos1 = low1 - 1
          var lastPos2 = low2 - 1
          var answer = acc
          for ((p1, p2) <- longest(
              uniqueCommons(seq1.view.slice(low1, high1).toList, seq2.view.slice(low2, high2).toList))) {
            // recurse between lines which are unique in each sequence
            val pos1 = p1 + low1
            val pos2 = p2 + low2
            // most of the time we have sequences of similar entries
            if (lastPos1 + 1 != pos1 || lastPos2 + 1 != pos2)
              answer = loop(lastPos1 + 1, lastPos2 + 1, pos1, pos2, answer)
            lastPos1 = pos1
            lastPos2 = pos2
            answer = (pos1, pos2) :: answer
          }
          if (answer.size > acc.size) {
            // the size of the accumulator increased, find
            // matches between the last match and the end
            loop(lastPos1 + 1, lastPos2 + 1, high1, high2, answer)
          } else if (seq1(low1) === seq2(low2)) {
            // find lines that match at the beginning
            var newLow1 = low1
            var newLow2 = low2
            while (newLow1 < high1 && newLow2 < high2 && seq1(newLow1) === seq2(newLow2)) {
              answer = (newLow1, newLow2) :: answer
              newLow1 += 1
              newLow2 += 1
            }
            loop(newLow1, newLow2, high1, high2, answer)
          } else if (seq1(high1 - 1) === seq2(high2 - 1)) {
            // find lines that match at the end
            var newHigh1 = high1 - 1
            var newHigh2 = high2 - 1
            while (newHigh1 > low1 && newHigh2 > low2 && seq1(newHigh1 - 1) === seq2(newHigh2 - 1)) {
              newHigh1 -= 1
              newHigh2 -= 1
            }
            answer = loop(lastPos1 + 1, lastPos2 + 1, newHigh1, newHigh2, answer)
            for (i <- 0 until (high1 - newHigh1))
              answer = (newHigh1 + i, newHigh2 + i) :: answer
            answer
          } else {
            classicLcs match {
              case Some(classicLcs) =>
                // fall back to classic LCS algorithm when there is no unique common elements
                // between both sequences and they have no common prefix nor suffix
                // raw patience algorithm is not good for finding LCS in such cases
                classicLcs.lcs(seq1, seq2, low1, high1, low2, high2) reverse_::: answer

              case _ =>
                answer
            }
          }

        }
      // we start with first indices in both sequences
      loop(low1, low2, high1, high2, Nil).reverse
    }
  }

  def savedHashes: Lcs[T] =
    new HashedLcs(new Patience[Hashed[T]](withFallback))

}

private case class Stacked(idx1: Int, idx2: Int, next: Option[Stacked]) {
  def chain: List[(Int, Int)] = {
    @tailrec
    def loop(stacked: Stacked, acc: List[(Int, Int)]): List[(Int, Int)] =
      stacked.next match {
        case Some(next) =>
          loop(next, (stacked.idx1, stacked.idx2) :: acc)
        case None =>
          (stacked.idx1, stacked.idx2) :: acc
      }
    loop(this, Nil)
  }
}


text:
<? if ($action == "cancel" && $action_status == TRUE):
alert(ALERT_LEVEL_SUCCESS, "Die Ausbildung eines Bürgers zur Einheit wurde abgebrochen!");
elseif ($action == "cancel" && $action_status == FALSE):
alert(ALERT_LEVEL_DANGER, "Die Ausbildung eines Bürgers zur Einheit konnte nicht abgebrochen werden!");
endif;
if (empty($units)): // no units message
alert(ALERT_LEVEL_WARNING, "Derzeit werden keine Einheiten ausgebildet, bitte bilde Einheiten über die Auswahl aus!");
else: ?>

      Titel
      Volumen
      Fortschritt
      Restzeit

    <? foreach ($units as $id => $unit):
        if (!empty($unit)):
          $time = ($unit["end_round"] - $round_number) * $update_interval;
          $round_diff = $unit["end_round"] - $unit["start_round"];
          if ($round_diff > 0):
            $progress = 100 -
              (100/$round_diff) * ($unit["end_round"] - $round_number);
          else:
            $progress = 100;
          endif;
          if ($progress < 0):
            $progress = 0;
          endif;
        else:
          $progress = 0;
          $time = 0;
        endif; ?>

      <?=$unit["title"]?> [<?=$unit["number"]?>] <abbr title="<?=$unit["text"]?>">?
      <?=get_numeric_value($unit["volume"])?>

        <div class="progress-bar" role="progressbar" aria-valuenow="<?=$progress?>" aria-valuemin="0" aria-valuemax="100" style="width: <?=$progress?>%;">
          <?=$progress?>%

      <?=get_numeric_time_value($time)?>
      <a href="<?=base_url()?>units/training/cancel/<?=$id?>">Abbrechen

    <? endforeach; ?>

<? endif; ?>


text:
/*
Particle Photon 'COnnected Ambient Light' with Node.js and Johnny-Five
By: Doug Seven
Licence: MIT

This example uses Nitrogen, an open source IoT service.
Read more about Nitrogen at http://nitrogen.io
*/

// Define the Johnny Five and Spark-IO variables
var five = require("johnny-five"),
    board, photoresistor, led;
var particle = require("particle-io");
var Store = require("nitrogen-file-store"),
    nitrogen = require("nitrogen"),
    service, lightSensor;

var config = {
    host: process.env.HOST_NAME || 'api.nitrogen.io',
    http_port: process.env.PORT || 443,
    protocol: process.env.PROTOCOL || 'https',
    api_key: process.env.API_KEY || 'YOUR API KEY HERE'
};
config.store = new Store(config);
service = new nitrogen.Service(config);

// Create a new Nitrogen device for the photoresistor
// This device will send data it reads from a sensor
lightSensor = new nitrogen.Device({
    nickname: 'lab05_lightSensor',
    name: 'Lab 05 Light Sensor',
    tags: ['sends:_lightState', 'executes:_lightLevel']
});

// Define the Johnny Five board as your Particle Photon
board = new five.Board({
  io: new particle({
    token: process.env.PARTICLE_KEY || 'YOUR API KEY HERE',
    deviceId: process.env.PARTICLE_DEVICE || 'YOUR DEVICE ID OR ALIAS HERE'
  })
});

var LEDPIN = "D0";

// Connect the lightSensor device defined above
// to the Nitrogen service instance.
service.connect(lightSensor, function(err, session, lightSensor) {
    if (err) { return console.log('Failed to connect lightSensor: ' + err); }

    // Create an instance of the subclassed CommandManager object for the lightSensor
    new LightManager(lightSensor).start(session, function(err, message) {
        if (err) return session.log.error(JSON.stringify(err));
    });

    // The board.on() executes the anonymous function when the
    // Partile Photon reports back that it is initialized and ready.
    board.on("ready", function() {
        console.log("Board connected...");

        // Create a new `photoresistor` hardware instance.
        photoresistor = new five.Sensor({
            pin: 'A0',  // Analog pin 0
            freq: 1000  // Collect data once per second
        });

        // Define the LED object using the pin
        led = new five.Led(LEDPIN);

        // Inject the `sensor` hardware into the Repl instance's context;
        // Allows direct command line access
        board.repl.inject({
            pot: photoresistor,
            led:led
        });

        // Define the event handler for the photo resistor reading
        // The freq value used when the photoresistor was defined
        // determines how often this is invoked, thus controlling
        // the frequency of Nitrogen messages.
        photoresistor.on('data', function() {
            // Capture the ambient light level from the photo resistor
            var lightLevel = this.value;

            // Create a Nitrogen Message to send the _lightLevel
            var ambientLightMessage = new nitrogen.Message({
                type: '_lightLevel',
                tags: nitrogen.CommandManager.commandTag(lightSensor.id),
                body: {
                    command: {
                        ambientLight: lightLevel
                    }
                },
                to: lightSensor.id
            });

            // Send the message
            ambientLightMessage.send(session);

            console.log("Message sent: " + JSON.stringify(ambientLightMessage));
        });
    });
});

// Create a command manager object and
// set it's prototype to the generic nitrogen.CommandManager
function LightManager() {
    nitrogen.CommandManager.apply(this, arguments);
}

LightManager.prototype = Object.create(nitrogen.CommandManager.prototype);
LightManager.prototype.constructor = LightManager;

// Override: CommandManager.isRelevant(message)
// Return true if this message is relevant to the CommandManager
// _lightState and _lightLevel are the messages the LightManager cares about
LightManager.prototype.isRelevant = function(message) {
    var relevant = ( (message.is('_lightState') || message.is('_lightLevel')) &&
                     (!this.device || message.from === this.device.id || message.to == this.device.id) );

    return relevant;
};

// Override: CommandManager.isCommand(message)
// Return true if this message is a command that this
// CommandManager should process.
LightManager.prototype.isCommand = function(message) {
    return message.is('_lightLevel');
};

// Override: CommandManager.obsoletes(downstreamMsg, upstreamMsg)
// Returns true if the given message upstream
// is obsoleted by the downstream message.
LightManager.prototype.obsoletes = function(downstreamMsg, upstreamMsg) {
    if (nitrogen.CommandManager.obsoletes(downstreamMsg, upstreamMsg))
        return true;

    var value = downstreamMsg.is('_lightState') &&
                downstreamMsg.isResponseTo(upstreamMsg) &&
                upstreamMsg.is('_lightLevel');

    return value;
};

// Override: CommandManager.executeQueue()
// Executes the active commands in the message queue
LightManager.prototype.executeQueue = function(callback) {
    if (!this.device) return callback(new Error('no device attached to control manager.'));

    var self = this;

    // CommandManager.activeCommands()
    // Returns the array of commands that are currently active for this manager
    var activeCommands = this.activeCommands();

    // Verify there are activeCommands
    if (activeCommands.length === 0) {
        this.session.log.warn('LightManager::executeQueue: no active commands to execute.');
        return callback();
    }

    var commandIds = [];
    var lightOn;

    // Find the final state and collect all the active command ids
    // You will use them in a moment.
    activeCommands.forEach(function(activeCommand) {
        // Collect active command IDs
        commandIds.push(activeCommand.id);

        var light = activeCommand.body.command.ambientLight;

        // Determine the final state of the light (on/true or off/false)
        lightOn = light > 950;
    });

    // Turn the light on or off based on final state
    if (led != null) { // Make sure the led sensor is available before using it
        if(lightOn) {
           led.on();
        } else {
           led.off();
        }
    }
    else {
        console.log("ERROR: 'led' was null.");
    }

    // This is the response to the _lightLevel command.
    // Notice the response_to is the array of command ids from above. This is used in the obsoletes method above as well.
    var lightMessage = new nitrogen.Message({
        type: '_lightState',
        tags: nitrogen.CommandManager.commandTag(self.device.id),
        body: {
            command: {
                on: lightOn
            }
        },
        response_to: commandIds
    });

    lightMessage.send(this.session, function(err, message) {
        if (err) return callback(err);

        console.log("Message sent: " + JSON.stringify(message));

        // let the command manager know we processed this message.
        self.process(new nitrogen.Message(message));

        // need to callback if there aren't any issues so commandManager can proceed.
        return callback();
    });
};

// Override: start
// Starts command processing on the message stream using the principal's session.
// It fetches all the current messages, processes them, and then starts execution.
// It also establishes a subscription to handle new messages and automatically executes
// them as they are received.
LightManager.prototype.start = function(session, callback) {

    var filter = {
        tags: nitrogen.CommandManager.commandTag(this.device.id)
    };

    return nitrogen.CommandManager.prototype.start.call(this, session, filter, callback);
};


text:
class GURL;

namespace extensions {

// Encodes |type| and |extension_id| as an identifiability surface.
blink::IdentifiableSurface SurfaceForExtension(
    blink::IdentifiableSurface::Type type,
    const ExtensionId& extension_id);

// Used for histograms. Do not reorder.
enum class ExtensionResourceAccessResult : int {
  kSuccess,
  kCancel,   // Only logged on navigation when the navigation is cancelled and
             // the document stays in place.
  kFailure,  // resource load failed or navigation to some sort of error page.
};

// Records results of attempts to access an extension resource at the url
// |gurl|. Done as part of a study to see if this is being used as a
// fingerprinting method.
void RecordExtensionResourceAccessResult(ukm::SourceIdObj ukm_source_id,
                                         const GURL& gurl,
                                         ExtensionResourceAccessResult result);

// Records that the extension |extension_id| has injected a content script into
// page identified by |ukm_source_id|.
void RecordContentScriptInjection(ukm::SourceIdObj ukm_source_id,
                                  const ExtensionId& extension_id);

// Records that the extension |extension_id| has blocked a network request on
// page identified by |ukm_source_id|.
void RecordNetworkRequestBlocked(ukm::SourceIdObj ukm_source_id,
                                 const ExtensionId& extension_id);

}  // namespace extensions

#endif  // EXTENSIONS_COMMON_IDENTIFIABILITY_METRICS_H_


text:
package com.example.administrator.boomtimer.Fragment;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Administrator on 2016/9/7.
 */
public abstract class BaseFragment extends Fragment {
    /**
     * 控件是否初始化完成
     */
    private boolean isViewCreated;
    /**
     * 数据是否已加载完毕
     */
    private boolean isLoadDataCompleted;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(getLayout(), container, false);
        initViews(view);
        isViewCreated = true;
        return view;
    }

    public abstract int getLayout();
    public abstract void initViews(View view);

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isViewCreated && !isLoadDataCompleted) {
            isLoadDataCompleted = true;
            loadData();
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        if (getUserVisibleHint()) {
            isLoadDataCompleted = true;
            loadData();
        }
    }

    /**
     * 子类实现加载数据的方法
     */
    public abstract  void loadData();
}