text:
import AnalyzerResult from '../analyzer-result';
import Location from '../location';
import markdownSpellcheck from 'markdown-spellcheck';
import spellConfig from 'markdown-spellcheck/es5/spell-config';
import spellcheck from 'markdown-spellcheck/es5/spellcheck';

const opts = {
  ignoreAcronyms: true,
  ignoreNumbers: true,
  suggestions: false,
  dictionary: {
    language: 'en-us'
  }
};

export default class SpellingAnalyzer {
  constructor(args = { configurationFile: './.spelling' }) {
    this.configurationFile = args.configurationFile;
  }

  analyze(str) {
    return this
      .initialize()
      .then(() => {
        const result = new AnalyzerResult();

        const spellResult = markdownSpellcheck.spell(str, opts);

        spellResult.forEach(x => {
          result.addMessage(
            'spelling-error',
            x.word,
            Location.getLine(str, x.index),
            Location.getLineColumn(str, x.index));
        });

        return result;
      });
  }

  // The returned Promise resolves to `true` if initialization
  // was not required (as in, it already took place).
  // `false` is returned if initialization was ran.
  initialize() {
    return new Promise(resolve => {
      if (SpellingAnalyzer.initialized) {
        resolve(SpellingAnalyzer.initialized);
      } else {
        spellConfig.initialise(this.configurationFile, () => {
          spellcheck.initialise(opts);

          spellConfig
            .getGlobalWords()
            .forEach(x => spellcheck.addWord(x, /* temporary: */ true));

          SpellingAnalyzer.initialized = true;

          resolve(!SpellingAnalyzer.initialized);
        });
      }
    });
  }
}

SpellingAnalyzer.initialized = false;


text:
package sqlite3

import (
	"database/sql/driver"
	"errors"

	"context"
)

// Ping implement Pinger.
func (c *SQLiteConn) Ping(ctx context.Context) error {
	if c.db == nil {
		return errors.New("Connection was closed")
	}
	return nil
}

// QueryContext implement QueryerContext.
func (c *SQLiteConn) QueryContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Rows, error) {
	list := make([]namedValue, len(args))
	for i, nv := range args {
		list[i] = namedValue(nv)
	}
	return c.query(ctx, query, list)
}

// ExecContext implement ExecerContext.
func (c *SQLiteConn) ExecContext(ctx context.Context, query string, args []driver.NamedValue) (driver.Result, error) {
	list := make([]namedValue, len(args))
	for i, nv := range args {
		list[i] = namedValue(nv)
	}
	return c.exec(ctx, query, list)
}

// PrepareContext implement ConnPrepareContext.
func (c *SQLiteConn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
	return c.prepare(ctx, query)
}

// BeginTx implement ConnBeginTx.
func (c *SQLiteConn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
	return c.begin(ctx)
}

// QueryContext implement QueryerContext.
func (s *SQLiteStmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) {
	list := make([]namedValue, len(args))
	for i, nv := range args {
		list[i] = namedValue(nv)
	}
	return s.query(ctx, list)
}

// ExecContext implement ExecerContext.
func (s *SQLiteStmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) {
	list := make([]namedValue, len(args))
	for i, nv := range args {
		list[i] = namedValue(nv)
	}
	return s.exec(ctx, list)
}

redpajama_set_name: RedPajamaGithub


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.exceptions.CMException;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.CMClass.CMObjectType;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.core.exceptions.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.CMLibrary;
import com.planet_ink.coffee_mud.Libraries.interfaces.XMLLibrary;
import com.planet_ink.coffee_mud.Libraries.interfaces.XMLLibrary.XMLTag;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import com.planet_ink.coffee_mud.WebMacros.interfaces.WebMacro;

import java.util.*;

public class Generate extends StdCommand
{
	public Generate()
	{
	}

	private static final SHashtable<String,CMClass.CMObjectType> OBJECT_TYPES=new SHashtable<String,CMClass.CMObjectType>(new Object[][]{
			{"STRING",CMClass.CMObjectType.LIBRARY},
			{"AREA",CMClass.CMObjectType.AREA},
			{"MOB",CMClass.CMObjectType.MOB},
			{"ROOM",CMClass.CMObjectType.LOCALE},
			{"ITEM",CMClass.CMObjectType.ITEM},
			{"QUEST",CMClass.CMObjectType.WEBMACRO},
	});

	private final String[]	access	= I(new String[] { "GENERATE" });

	@Override
	public String[] getAccessWords()
	{
		return access;
	}

	public void createNewPlace(final MOB mob, final Room oldR, final Room R, final int direction, final boolean save)
	{
		if(R.roomID().length()==0)
		{
			R.setArea(oldR.getArea());
			R.setRoomID(oldR.getArea().getNewRoomID(oldR, direction));
		}
		Exit E=R.getExitInDir(Directions.getOpDirectionCode(direction));
		if(E==null)
			E = CMClass.getExit("Open");
		oldR.setRawExit(direction, E);
		oldR.rawDoors()[direction]=R;
		final int opDir=Directions.getOpDirectionCode(direction);
		if(R.getRoomInDir(opDir)!=null)
			mob.tell(L("An error has caused the following exit to be one-way."));
		else
		{
			R.setRawExit(opDir, E);
			R.rawDoors()[opDir]=oldR;
		}
		if(save)
			CMLib.database().DBUpdateExits(oldR);
		final String dirName=CMLib.directions().getDirectionName(direction, CMLib.flags().getDirType(R));
		oldR.showHappens(CMMsg.MSG_OK_VISUAL,L("A new place materializes to the @x1",dirName));
	}

	@Override
	public boolean execute(final MOB mob, final List<String> commands, final int metaFlags)
		throws java.io.IOException
	{
		boolean save=true;
		if(commands.size()>1)
		{
			if(commands.get(1).equalsIgnoreCase("nosave"))
			{
				save=false;
				commands.remove(1);
			}
		}
		if(commands.size()<3)
		{
			mob.tell(L("Generate what? Try GENERATE [TYPE] [ID] (FROM [DATA_FILE_PATH]) ([VAR=VALUE]..) [DIRECTION]"));
			return false;
		}
		final String finalLog = mob.Name()+" called generate command with parms: " + CMParms.combine(commands, 1);
		CMFile file = null;
		if((commands.size()>3)&&commands.get(3).equalsIgnoreCase("FROM"))
		{
			file = new CMFile(Resources.buildResourcePath(commands.get(4)),mob);
			commands.remove(3);
			commands.remove(3);
		}
		else
			file = new CMFile(Resources.buildResourcePath("randareas/example.xml"),mob);
		if(!file.canRead())
		{
			mob.tell(L("Random data file '@x1' not found.  Aborting.",file.getCanonicalPath()));
			return false;
		}
		final StringBuffer xml = file.textUnformatted();
		final List<XMLLibrary.XMLTag> xmlRoot = CMLib.xml().parseAllXML(xml);
		final Hashtable<String,Object> definedIDs = new Hashtable<String,Object>();
		definedIDs.putAll(CMParms.parseEQParms(commands,3,commands.size()));
		CMLib.percolator().buildDefinedIDSet(xmlRoot,definedIDs, new XTreeSet<String>(definedIDs.keys()));
		final String typeName = commands.get(1);
		String objectType = typeName.toUpperCase().trim();
		CMClass.CMObjectType codeI=OBJECT_TYPES.get(objectType);
		if(codeI==null)
		{
			for(final Enumeration<String> e=OBJECT_TYPES.keys();e.hasMoreElements();)
			{
				final String key =e.nextElement();
				if(key.startsWith(typeName.toUpperCase().trim()))
				{
					objectType = key;
					codeI=OBJECT_TYPES.get(key);
				}
			}
			if(codeI==null)
			{
				mob.tell(L("'@x1' is an unknown object type.  Try: @x2",typeName,CMParms.toListString(OBJECT_TYPES.keys())));
				return false;
			}
		}
		int direction=-1;
		if((codeI==CMClass.CMObjectType.AREA)||(codeI==CMClass.CMObjectType.LOCALE))
		{
			final String possDir=commands.get(commands.size()-1);
			direction = CMLib.directions().getGoodDirectionCode(possDir);
			if(direction<0)
			{
				mob.tell(L("When creating an area or room, the LAST parameter to this command must be a direction to link to this room by."));
				return false;
			}
			if(mob.location().getRoomInDir(direction)!=null)
			{
				final String dirName=CMLib.directions().getDirectionName(direction, CMLib.flags().getInDirType(mob));
				mob.tell(L("A room already exists in direction @x1. Action aborted.",dirName));
				return false;
			}
		}
		final String idName = commands.get(2).toUpperCase().trim();
		if((!(definedIDs.get(idName) instanceof XMLTag))
		||(!((XMLTag)definedIDs.get(idName)).tag().equalsIgnoreCase(objectType)))
		{
			if(!idName.equalsIgnoreCase("LIST"))
				mob.tell(L("The @x1 id '@x2' has not been defined in the data file.",objectType,idName));
			final StringBuffer foundIDs=new StringBuffer("");
			for(final Enumeration<String> tkeye=OBJECT_TYPES.keys();tkeye.hasMoreElements();)
			{
				final String tKey=tkeye.nextElement();
				foundIDs.append("^H"+tKey+"^N: \n\r");
				final Vector<String> xmlTagsV=new Vector<String>();
				for(final Enumeration<String> keys=definedIDs.keys();keys.hasMoreElements();)
				{
					final String key=keys.nextElement();
					if((definedIDs.get(key) instanceof XMLTag)
					&&(((XMLTag)definedIDs.get(key)).tag().equalsIgnoreCase(tKey)))
						xmlTagsV.add(key.toLowerCase());
				}
				foundIDs.append(CMParms.toListString(xmlTagsV)+"\n\r");
			}
			mob.tell(L("Found ids include: \n\r@x1",foundIDs.toString()));
			return false;
		}

		final XMLTag piece=(XMLTag)definedIDs.get(idName);
		definedIDs.putAll(CMParms.parseEQParms(commands,3,commands.size()));
		try
		{
			CMLib.percolator().checkRequirements(piece, definedIDs);
		}
		catch(final CMException cme)
		{
			mob.tell(L("Required ids for @x1 were missing: @x2",idName,cme.getMessage()));
			return false;
		}
		final Vector<Object> V = new Vector<Object>();
		try
		{
			switch(codeI)
			{
			case LIBRARY:
			{
				CMLib.percolator().preDefineReward(piece, definedIDs);
				CMLib.percolator().defineReward(piece,definedIDs);
				final String s=CMLib.percolator().findString("STRING", piece, definedIDs);
				if(s!=null)
					V.add(s);
				break;
			}
			case AREA:
				CMLib.percolator().preDefineReward(piece, definedIDs);
				CMLib.percolator().defineReward(piece,definedIDs);
				definedIDs.put("ROOMTAG_NODEGATEEXIT", CMLib.directions().getDirectionName(Directions.getOpDirectionCode(direction)));
				definedIDs.put("ROOMTAG_GATEEXITROOM", mob.location());
				final Area A=CMLib.percolator().findArea(piece, definedIDs, direction);
				if(A!=null)
					V.add(A);
				break;
			case MOB:
				CMLib.percolator().preDefineReward(piece, definedIDs);
				CMLib.percolator().defineReward(piece,definedIDs);
				V.addAll(CMLib.percolator().findMobs(piece, definedIDs));
				break;
			case LOCALE:
			{
				final Exit[] exits=new Exit[Directions.NUM_DIRECTIONS()];
				CMLib.percolator().preDefineReward(piece, definedIDs);
				CMLib.percolator().defineReward(piece,definedIDs);
				definedIDs.put("ROOMTAG_NODEGATEEXIT", CMLib.directions().getDirectionName(Directions.getOpDirectionCode(direction)));
				definedIDs.put("ROOMTAG_GATEEXITROOM", mob.location());
				final Room R=CMLib.percolator().buildRoom(piece, definedIDs, exits, direction);
				if(R!=null)
					V.add(R);
				break;
			}
			case ITEM:
				CMLib.percolator().preDefineReward(piece, definedIDs);
				CMLib.percolator().defineReward(piece,definedIDs);
				V.addAll(CMLib.percolator().findItems(piece, definedIDs));
				break;
			case WEBMACRO:
			{
				CMLib.percolator().preDefineReward(piece, definedIDs);
				CMLib.percolator().defineReward(piece,definedIDs);
				final String s=CMLib.percolator().buildQuestScript(piece, definedIDs, null);
				if(s!=null)
					V.add(s);
				break;
			}
			default:
				break;
			}
			if(V.size()==0)
				mob.tell(L("Nothing generated."));
			else
			for(int v=0;v<V.size();v++)
			{
				if(V.get(v) instanceof MOB)
				{
					((MOB)V.get(v)).bringToLife(mob.location(),true);
					mob.location().showHappens(CMMsg.MSG_OK_VISUAL,L("@x1 appears.",((MOB)V.get(v)).name()));
					CMLib.percolator().postProcess(definedIDs);
					Log.sysOut("Generate",mob.Name()+" generated mob "+((MOB)V.get(v)).name());
				}
				else
				if(V.get(v) instanceof Item)
				{
					mob.location().addItem((Item)V.get(v));
					mob.location().showHappens(CMMsg.MSG_OK_VISUAL,L("@x1 appears.",((Item)V.get(v)).name()));
					CMLib.percolator().postProcess(definedIDs);
					Log.sysOut("Generate",mob.Name()+" generated item "+((Item)V.get(v)).name());
				}
				else
				if(V.get(v) instanceof String)
				{
					CMLib.percolator().postProcess(definedIDs);
					if(codeI==CMObjectType.WEBMACRO)
					{
						if((!definedIDs.containsKey("QUEST_ID"))
						||(!(definedIDs.get("QUEST_ID") instanceof String)))
						{
							mob.tell("Unable to create your quest because a quest_id was not generated");
							return false;
						}
						final String name=(String)definedIDs.get("QUEST_ID");
						final Quest Q=(Quest)CMClass.getCommon("DefaultQuest");
						Q.setScript((String)V.get(0),true);
						if((Q.name().trim().length()==0)||(Q.duration()<0))
						{
							mob.tell("Unable to create your quest.  Please consult the log.");
							return false;
						}
						final Quest badQ=CMLib.quests().fetchQuest(name);
						if(badQ!=null)
						{
							mob.tell("Unable to create your quest.  One of that name already exists!");
							return false;
						}
						mob.tell("Generated quest '"+Q.name()+"'");
						Log.sysOut("Generate",mob.Name()+" created quest '"+Q.name()+"'");
						CMLib.quests().addQuest(Q);
						if(!Q.running())
						{
							if(!Q.startQuest())
							{
								CMLib.quests().delQuest(Q);
								mob.tell("Unable to start the quest.  Something went wrong.  Perhaps the problem was logged?");
								mob.tell((String)V.get(0));
								return false;
							}
						}
						CMLib.quests().save();
					}
					else
						mob.tell((String)V.get(v));
				}
				else
				if(V.get(v) instanceof Room)
				{
					final Room R=(Room)V.get(v);
					createNewPlace(mob,mob.location(),R,direction,save);
					CMLib.percolator().postProcess(definedIDs);
					if(save)
					{
						CMLib.database().DBCreateRoom(R);
						CMLib.database().DBUpdateExits(R);
						CMLib.database().DBUpdateItems(R);
						CMLib.database().DBUpdateMOBs(R);
					}
					Log.sysOut("Generate",mob.Name()+" generated room "+R.roomID());
				}
				else
				if(V.get(v) instanceof Area)
				{
					final Area A=(Area)V.get(v);
					CMLib.map().addArea(A);
					CMLib.map().registerWorldObjectLoaded(A, null, A);
					if(save)
						CMLib.database().DBCreateArea(A);
					Room R=A.getRoom(A.Name()+"#0");
					if(R==null)
						R=A.getFilledProperMap().nextElement();
					createNewPlace(mob,mob.location(),R,direction,save);
					CMLib.percolator().postProcess(definedIDs);
					if(save)
					{
						mob.tell(L("Saving remaining rooms for area '@x1'...",A.name()));
						for(final Enumeration<Room> e=A.getFilledProperMap();e.hasMoreElements();)
						{
							R=e.nextElement();
							CMLib.database().DBCreateRoom(R);
							CMLib.database().DBUpdateExits(R);
							CMLib.database().DBUpdateItems(R);
							CMLib.database().DBUpdateMOBs(R);
						}
						mob.tell(L("Done saving remaining rooms for area '@x1'",A.name()));
					}
					Log.sysOut("Generate",mob.Name()+" generated area "+A.name());
				}
			}
		}
		catch(final CMException cex)
		{
			mob.tell(L("Unable to fully generate: @x1",cex.getMessage()));
			if(CMSecurity.isDebugging(CMSecurity.DbgFlag.MUDPERCOLATOR))
				Log.debugOut("Generate",cex);
			return false;
		}
		Log.sysOut("Generate",finalLog);
		return true;
	}

	@Override
	public boolean canBeOrdered()
	{
		return false;
	}

	@Override
	public boolean securityCheck(final MOB mob)
	{
		return CMSecurity.isAllowedAnywhere(mob, CMSecurity.SecFlag.CMDAREAS);
	}
}


text:
using DotCommon.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Xunit;

namespace DotCommon.Test.Utility
{
    public class RandomUtilTest
    {
        [Fact]
        public void GetRandomSeed_Test()
        {
            var seed1 = RandomUtil.GetRandomSeed(8);
            Assert.True(seed1 != 0);
        }

        [Fact]
        public void GetRandomInt_Test()
        {
            var r = RandomUtil.GetRandomInt(1, 9999);
            Assert.True(r >= 1);
            Assert.True(r <= 99999);
        }

        [Fact]
        public void GetRandomStr_Test()
        {
            var s1 = RandomUtil.GetRandomStr(5, RandomStringType.Fix);
            Assert.Equal(5, s1.Length);
            var matchs1 = Regex.IsMatch(s1, @"^[A-Za-z0-9]{5}$");
            Assert.True(matchs1);

            var s2 = RandomUtil.GetRandomStr(10, RandomStringType.NumberLower);
            var matchs2 = Regex.IsMatch(s2, @"^[a-z0-9]{10}$");
            Assert.True(matchs2);
        }

        [Fact]
        public void GetRandomArray_Test()
        {
            var constArray = new int[] { 1, 2, 3 };
            var array = new int[] { 1, 2, 3 };
            RandomUtil.GetRandomArray(array);
            Assert.Equal(3, array.Length);
            Assert.Equal(constArray, array.OrderBy(x => x).ToArray());
        }

    }
}


text: """The cert_expiry component."""


text:
from builtins import object

class Module(object):

    def __init__(self, mainMenu, params=[]):

        # metadata info about the module, not modified during runtime
        self.info = {
            # name for the module that will appear in module menus
            'Name': 'RemoveLaunchDaemon',

            # list of one or more authors for the module
            'Author': ['@xorrior'],

            # more verbose multi-line description of the module
            'Description': ('Remove an Empire Launch Daemon.'),

            'Software': '',

            'Techniques': ['T1055'],

            # True if the module needs to run in the background
            'Background' : False,

            # File extension to save the file as
            'OutputExtension' : None,

            # if the module needs administrative privileges
            'NeedsAdmin' : False,

            # True if the method doesn't touch disk/is reasonably opsec safe
            'OpsecSafe' : True,

            # the module language
            'Language' : 'python',

            # the minimum language version needed
            'MinLanguageVersion' : '2.6',

            # list of any references/other comments
            'Comments': []
        }

        # any options needed by the module, settable during runtime
        self.options = {
            # format:
            #   value_name : {description, required, default_value}
            'Agent' : {
                # The 'Agent' option is the only one that MUST be in a module
                'Description'   :   'Agent to execute module on.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'PlistPath' : {
                'Description'   :   'Full path to the plist file to remove.',
                'Required'      :   True,
                'Value'         :   ''
            },
            'ProgramPath' : {
                'Description'   :   'Full path to the bash script/ binary file to remove.',
                'Required'      :   True,
                'Value'         :   ''
            }

        }

        # save off a copy of the mainMenu object to access external functionality
        #   like listeners/agent handlers/etc.
        self.mainMenu = mainMenu

        # During instantiation, any settable option parameters
        #   are passed as an object set to the module and the
        #   options dictionary is automatically set. This is mostly
        #   in case options are passed on the command line
        if params:
            for param in params:
                # parameter format is [Name, Value]
                option, value = param
                if option in self.options:
                    self.options[option]['Value'] = value

    def generate(self, obfuscate=False, obfuscationCommand=""):

        plistpath = self.options['PlistPath']['Value']
        programpath = self.options['ProgramPath']['Value']

        script = """
import subprocess

process = subprocess.Popen('launchctl unload %s', stdout=subprocess.PIPE, shell=True)
process.communicate()

process = subprocess.Popen('rm %s', stdout=subprocess.PIPE, shell=True)
process.communicate()

process = subprocess.Popen('rm %s', stdout=subprocess.PIPE, shell=True)
process.communicate()

print("\\n [+] %s has been removed")
print("\\n [+] %s has been removed")
""" %(plistpath,plistpath,programpath,plistpath,programpath)

        return script


text:
  #pragma warning(disable: 4101)
  #pragma warning(disable: 4267)
#endif

  #include <cmdline.h>

#if defined(_MSC_VER)
  #pragma warning(default: 4267)
  #pragma warning(default: 4101)
#endif

#include <fstream>
#include <random>
#include <thread>

#if defined(_MSC_VER)
  #pragma warning(disable: 4229)
#endif

  #include <unicode/uclean.h> // for u_cleanup

#if defined(_MSC_VER)
  #pragma warning(default: 4229)
#endif

#include "common.hpp"
#include "analysis/analyzers.hpp"
#include "analysis/token_attributes.hpp"
#include "index/directory_reader.hpp"
#include "search/bm25.hpp"
#include "search/boolean_filter.hpp"
#include "search/filter.hpp"
#include "search/phrase_filter.hpp"
#include "search/prefix_filter.hpp"
#include "search/score.hpp"
#include "search/term_filter.hpp"
#include "store/fs_directory.hpp"
#include "utils/memory_pool.hpp"

#include "index-search.hpp"

// std::regex support only starting from GCC 4.9
#if !defined(__GNUC__) || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 8))
  #include <regex>
#else
  #include "boost/regex.hpp"

  NS_BEGIN(std)
    typedef ::boost::regex regex;
    typedef ::boost::match_results<string::const_iterator> smatch;

    template <typename... Args>
    bool regex_match(Args&&... args) { return ::boost::regex_match(std::forward<Args>(args)...); }
  NS_END // std
#endif

NS_LOCAL

const std::string HELP = "help";
const std::string INDEX_DIR = "index-dir";
const std::string OUTPUT = "out";
const std::string INPUT = "in";
const std::string MAX = "max-tasks";
const std::string THR = "threads";
const std::string TOPN = "topN";
const std::string RND = "random";
const std::string RPT = "repeat";
const std::string CSV = "csv";
const std::string SCORED_TERMS_LIMIT = "scored-terms-limit";
const std::string SCORER = "scorer";
const std::string SCORER_ARG = "scorer-arg";
const std::string SCORER_ARG_FMT = "scorer-arg-format";
const std::string DIR_TYPE = "dir-type";
const std::string FORMAT = "format";

static bool v = false;

typedef std::unique_ptr<std::string> ustringp;

NS_END

struct Line {
    typedef std::shared_ptr<Line> ptr;
    std::string category;
    std::string text;

    Line(const std::string& c, const std::string& t): category(c), text(t) {}
};

struct Task {
    std::string category;
    std::string text;

    typedef std::shared_ptr<Task> ptr;

    irs::filter::prepared::ptr prepared;

    int taskId;
    int totalHitCount;
    int topN;

    size_t tdiff_msec;
    std::thread::id tid;

    Task(std::string& s, std::string& t, int n, irs::filter::prepared::ptr p) :
    category(s),
    text(t),
    prepared(p),
    taskId(0),
    totalHitCount(0),
    topN(n) {
    }

    virtual ~Task() {
    }

    void go(std::thread::id id, irs::directory_reader& reader) {
        tid = id;
        auto start = std::chrono::system_clock::now();

        query(reader);

        tdiff_msec = std::chrono::duration_cast<std::chrono::milliseconds>(
          std::chrono::system_clock::now() - start
        ).count();
    }

    virtual int query(irs::directory_reader& reader) = 0;

    virtual void print(std::ostream& out) = 0;
    virtual void print_csv(std::ostream& out) = 0;
};

struct SearchTask : public Task {
    SearchTask(std::string& s, std::string& t, int n, irs::filter::prepared::ptr p) :
    Task(s, t, n, p) {
    }

    struct Entry {
        irs::doc_id_t id;
        float score;

        Entry(irs::doc_id_t i, float s) :
        id(i),
        score(s) {
        }
    };

    std::vector<Entry> top_docs;

    virtual int query(irs::directory_reader& reader) override {
        SCOPED_TIMER("Query execution + Result processing time");

        for (auto& segment : reader) { // iterate segments
            irs::order order;
            order.add<irs::bm25_sort>(true);
            auto prepared_order = order.prepare();
            auto docs = prepared->execute(segment, prepared_order); // query segment
            const irs::score* score = docs->attributes().get<iresearch::score>().get();
            auto comparer = [&prepared_order](const irs::bstring& lhs, const irs::bstring& rhs)->bool {
              return prepared_order.less(lhs.c_str(), rhs.c_str());
            };
            std::multimap<irs::bstring, Entry, decltype(comparer)> sorted(comparer);

            // ensure we avoid COW for pre c++11 std::basic_string
            const irs::bytes_ref score_value = score->value();

            while (docs->next()) {
              SCOPED_TIMER("Result processing time");
              ++totalHitCount;
              score->evaluate();
              sorted.emplace(
                std::piecewise_construct,
                std::forward_as_tuple(score_value),
                std::forward_as_tuple(docs->value(), score ? prepared_order.get<float>(score_value.c_str(), 0) : .0)
              );

              if (sorted.size() > topN) {
                sorted.erase(--(sorted.end()));
              }
            }

            for (auto& entry: sorted) {
              top_docs.emplace_back(std::move(entry.second));
            }
        }
        return 0;
    }

    void print(std::ostream& out) override {
        out << "TASK: cat=" << category << " q='body:" << text << "' hits=" << totalHitCount << std::endl;
        out << "  " << tdiff_msec / 1000. << " msec" << std::endl;
        out << "  thread " << tid << std::endl;
        for (auto& doc : top_docs) {
            out << "  doc=" << doc.id << " score=" << doc.score << std::endl;
        }
        out << std::endl;
    }

    void print_csv(std::ostream& out) override {
        out << category << "," << text << "," << totalHitCount << "," << tdiff_msec / 1000. << "," << tdiff_msec << std::endl;
    }
};

class TaskSource {
    std::atomic<int> idx;
    std::vector<Task::ptr> tasks;
    std::random_device rd;
    std::mt19937 g;

    int parseLines(std::string& line, Line::ptr& p) {
        static const std::regex m1("(\\S+): (.+)");
        std::smatch res;
        std::string category;
        std::string text;

        if (std::regex_match(line, res, m1)) {
            category.assign(res[1].first, res[1].second);
            text.assign(res[2].first, res[2].second);
            p = Line::ptr(new Line(category, text));

            return 0;
        }

        return -1;
    }

    int loadLines(std::vector<Line::ptr>& lines, std::istream& stream) {
        while (!stream.eof()) {
            std::string line;
            std::getline(stream, line);
            Line::ptr p;

            if (0 == parseLines(line, p)) {
                lines.push_back(p);
            }
        }

        return 0;
    }

    void shuffle(std::vector<Line::ptr>& line) {
        // @todo provide custom random?
        std::shuffle(line.begin(), line.end(), g);
    }

    static int pruneLines(std::vector<Line::ptr>& lines, std::vector<Line::ptr>& pruned_lines, int maxtasks) {
        std::map<std::string, int> cat_counts;

        for (auto& t : lines) {
            std::map<std::string, int>::iterator cat = cat_counts.find(t->category);
            int count = 0;

            if (cat != cat_counts.end()) {
                count = cat->second;
            }

            if (count < maxtasks) {
                ++count;

                if (cat != cat_counts.end()) {
                    cat->second = count;
                } else {
                    cat_counts[t->category] = count;
                }

                pruned_lines.push_back(t);
            }
        }

        return 0;
    }

    bool splitFreq(std::string& text, std::string& term) {
        static const std::regex freqPattern1("(\\S+)\\s*#\\s*(.+)"); // single term, prefix
        static const std::regex freqPattern2("\"(.+)\"\\s*#\\s*(.+)"); // phrase
        static const std::regex freqPattern3("((?:\\S+\\s+)+)\\s*#\\s*(.+)"); // AND/OR groups
        std::smatch res;

        if (std::regex_match(text, res, freqPattern1)) {
            term.assign(res[1].first, res[1].second);
            return true;
        } else if (std::regex_match(text, res, freqPattern2)) {
            term.assign(res[1].first, res[1].second);
            return true;
        } else if (std::regex_match(text, res, freqPattern3)) {
            term.assign(res[1].first, res[1].second);
            return true;
        }

        return false;
    }

    int prepareQueries(std::vector<Line::ptr>& lines, irs::directory_reader& reader, int topN) {
        irs::order order;
        order.add<irs::bm25_sort>(true);
        auto ord = order.prepare();

        for (auto& line : lines) {
            irs::filter::prepared::ptr prepared = nullptr;
            std::string terms;

            if (line->category == "HighTerm" || line->category == "MedTerm" || line->category == "LowTerm") {
                if (splitFreq(line->text, terms)) {
                    irs::by_term query;
                    query.field("body").term(terms);
                    prepared = query.prepare(reader, ord);
                }
            } else if (line->category == "HighPhrase" || line->category == "MedPhrase" || line->category == "LowPhrase") {
                // @todo what's the difference between irs::by_phrase and irs::And?
                if (splitFreq(line->text, terms)) {
                    std::istringstream f(terms);
                    std::string term;
                    irs::by_phrase query;
                    query.field("body");
                    while (getline(f, term, ' ')) {
                        query.push_back(term);
                    }
                    prepared = query.prepare(reader, ord);
                }
            } else if (line->category == "AndHighHigh" || line->category == "AndHighMed" || line->category == "AndHighLow") {
                if (splitFreq(line->text, terms)) {
                    std::istringstream f(terms);
                    std::string term;
                    irs::And query;
                    while (getline(f, term, ' ')) {
                        irs::by_term& part = query.add<irs::by_term>();
                        part.field("body").term(term.c_str() + 1); // skip '+' at the start of the term
                    }
                    prepared = query.prepare(reader, ord);
                }
            } else if (line->category == "OrHighHigh" || line->category == "OrHighMed" || line->category == "OrHighLow") {
                if (splitFreq(line->text, terms)) {
                    std::istringstream f(terms);
                    std::string term;
                    irs::Or query;
                    while (getline(f, term, ' ')) {
                        irs::by_term& part = query.add<irs::by_term>();
                        part.field("body").term(term);
                    }
                    prepared = query.prepare(reader, ord);
                }
            } else if (line->category == "Prefix3") {
                irs::by_prefix query;
                terms.assign(line->text.begin(), line->text.end() - 1); // cut '~' at the end of the text
                query.field("body").term(terms);
                prepared = query.prepare(reader, ord);
            }

            if (prepared != nullptr) {
                tasks.emplace_back(new SearchTask(line->category, terms, topN, prepared));
                if (v) std::cout << tasks.size() << ": cat=" << line->category << "; term=" << terms << std::endl;
            }
        }

        if (v) std::cout << "Tasks prepared=" << tasks.size() << std::endl;

        return 0;
    }

    int repeatLines(std::vector<Line::ptr>& lines, std::vector<Line::ptr>& rep_lines, int repeat, bool do_shuffle) {
        while (repeat != 0) {
            if (do_shuffle) {
                shuffle(lines);
            }

            rep_lines.insert(std::end(rep_lines), std::begin(lines), std::end(lines));
            --repeat;
        }

        return 0;
    }

public:
    TaskSource() : idx(0), g(rd()) {
    }

    int load(std::istream& stream, int maxtasks, int repeat, irs::directory_reader& reader, int topN, bool do_shuffle) {
        ///
        ///  this fn mimics lucene-util's LocalTaskSource behavior
        ///  -- many similar tasks generated
        ///
        std::vector<Line::ptr> rep_lines;
        {
            std::vector<Line::ptr> pruned_lines;
            {
                std::vector<Line::ptr> lines;
                // parse all lines to category:text
                loadLines(lines, stream);

                // shuffle
                if (do_shuffle) {
                    shuffle(lines);
                }

                // prune tasks
                pruneLines(lines, pruned_lines, maxtasks);
            }

            // multiply pruned with shuffling
            repeatLines(pruned_lines, rep_lines, repeat, do_shuffle);
        }

        // prepare queries
        prepareQueries(rep_lines, reader, topN);

        return 0;
    }

    Task::ptr next() {
        int next = idx++; // atomic get and increment

        if (next < tasks.size()) {
            return tasks[next];
        }

        return nullptr;
    }

    std::vector<Task::ptr>& getTasks() {
        return tasks;
    }
};

class TaskThread {
public:
    typedef std::shared_ptr<TaskThread> ptr;

    struct Args {
        TaskSource& tasks;
        irs::directory_reader& reader;

        Args(TaskSource& t,
                irs::directory_reader& r) :
        tasks(t),
        reader(r) {
        }
    };

private:
    std::thread* thr;

    void worker(Args a) {
        auto task = a.tasks.next();

        while (task != nullptr) {
            task->go(thr->get_id(), a.reader);
            task = a.tasks.next();
        }
    }

public:
    void start(Args a) {
        thr = new std::thread(std::bind(&TaskThread::worker, this, a));
    }

    void join() {
        thr->join();
        delete thr;
    }
};

enum class category_t {
  HighTerm,
  MedTerm,
  LowTerm,
  HighPhrase,
  MedPhrase,
  LowPhrase,
  AndHighHigh,
  AndHighMed,
  AndHighLow,
  OrHighHigh,
  OrHighMed,
  OrHighLow,
  Prefix3,
  UNKNOWN
};

struct task_t {
  category_t category;
  std::string text;
  task_t(category_t v_category, std::string&& v_text): category(v_category), text(std::move(v_text)) {}
};

category_t parseCategory(const irs::string_ref& value) {
  if (value == "HighTerm") return category_t::HighTerm;
  if (value == "MedTerm") return category_t::MedTerm;
  if (value == "LowTerm") return category_t::LowTerm;
  if (value == "HighPhrase") return category_t::HighPhrase;
  if (value == "MedPhrase") return category_t::MedPhrase;
  if (value == "LowPhrase") return category_t::LowPhrase;
  if (value == "AndHighHigh") return category_t::AndHighHigh;
  if (value == "AndHighMed") return category_t::AndHighMed;
  if (value == "AndHighLow") return category_t::AndHighLow;
  if (value == "OrHighHigh") return category_t::OrHighHigh;
  if (value == "OrHighMed") return category_t::OrHighMed;
  if (value == "OrHighLow") return category_t::OrHighLow;
  if (value == "Prefix3") return category_t::Prefix3;

  return category_t::UNKNOWN;
}

irs::string_ref stringCategory(category_t category) {
  switch(category) {
   case category_t::HighTerm: return "HighTerm";
   case category_t::MedTerm: return "MedTerm";
   case category_t::LowTerm: return "LowTerm";
   case category_t::HighPhrase: return "HighPhrase";
   case category_t::MedPhrase: return "MedPhrase";
   case category_t::LowPhrase: return "LowPhrase";
   case category_t::AndHighHigh: return "AndHighHigh";
   case category_t::AndHighMed: return "AndHighMed";
   case category_t::AndHighLow: return "AndHighLow";
   case category_t::OrHighHigh: return "OrHighHigh";
   case category_t::OrHighMed: return "OrHighMed";
   case category_t::OrHighLow: return "OrHighLow";
   case category_t::Prefix3: return "Prefix3";
   default: return "<unknown>";
  }
}

irs::string_ref splitFreq(const std::string& text) {
  static const std::regex freqPattern1("(\\S+)\\s*#\\s*(.+)"); // single term, prefix
  static const std::regex freqPattern2("\"(.+)\"\\s*#\\s*(.+)"); // phrase
  static const std::regex freqPattern3("((?:\\S+\\s+)+)\\s*#\\s*(.+)"); // AND/OR groups
  std::smatch res;

  if (std::regex_match(text, res, freqPattern1)) {
    return irs::string_ref(&*(res[1].first), std::distance(res[1].first, res[1].second));
  } else if (std::regex_match(text, res, freqPattern2)) {
    return irs::string_ref(&*(res[1].first), std::distance(res[1].first, res[1].second));
  } else if (std::regex_match(text, res, freqPattern3)) {
    return irs::string_ref(&*(res[1].first), std::distance(res[1].first, res[1].second));
  }

  return irs::string_ref::NIL;
}

irs::filter::prepared::ptr prepareFilter(
    const irs::directory_reader& reader,
    const irs::order::prepared& order,
    category_t category,
    const std::string& text,
    const irs::analysis::analyzer::ptr& analyzer,
    std::string& tmpBuf,
    size_t scored_terms_limit
) {
  irs::string_ref terms;

  switch (category) {
   case category_t::HighTerm: // fall through
   case category_t::MedTerm: // fall through
   case category_t::LowTerm: {
    if ((terms = splitFreq(text)).null()) {
      return nullptr;
    }

    irs::by_term query;

    query.field("body").term(terms);

    return query.prepare(reader, order);
   }
   case category_t::HighPhrase: // fall through
   case category_t::MedPhrase: // fall through
   case category_t::LowPhrase: {
    if ((terms = splitFreq(text)).null()) {
      return nullptr;
    }

    irs::by_phrase query;

    query.field("body");
    analyzer->reset(terms);

    for (auto& term = analyzer->attributes().get<irs::term_attribute>(); analyzer->next();) {
      query.push_back(term->value());
    }

    return query.prepare(reader, order);
   }
   case category_t::AndHighHigh: // fall through
   case category_t::AndHighMed: // fall through
   case category_t::AndHighLow: {
    if ((terms = splitFreq(text)).null()) {
      return nullptr;
    }

    irs::And query;

    for (std::istringstream in(terms); std::getline(in, tmpBuf, ' ');) {
      query.add<irs::by_term>().field("body").term(tmpBuf.c_str() + 1); // +1 for skip '+' at the start of the term
    }

    return query.prepare(reader, order);
   }
   case category_t::OrHighHigh: // fall through
   case category_t::OrHighMed: // fall through
   case category_t::OrHighLow: {
    if ((terms = splitFreq(text)).null()) {
      return nullptr;
    }

    irs::Or query;

    for (std::istringstream in(terms); std::getline(in, tmpBuf, ' ');) {
      query.add<irs::by_term>().field("body").term(tmpBuf);
    }

    return query.prepare(reader, order);
   }
   case category_t::Prefix3: {
    irs::by_prefix query;
    query.scored_terms_limit(scored_terms_limit);

    terms = irs::string_ref(text, text.size() - 1); // cut '~' at the end of the text
    query.field("body").term(terms);

    return query.prepare(reader, order);
   }
  }

  return nullptr;
}

void prepareTasks(std::vector<task_t>& buf, std::istream& in, size_t tasks_per_category) {
  std::map<category_t, size_t> category_counts;
  std::string tmpBuf;

  // parse all lines to category:text
  while (!in.eof()) {
    static const std::regex m1("(\\S+): (.+)");
    std::smatch res;

    std::getline(in, tmpBuf);

    if (std::regex_match(tmpBuf, res, m1)) {
      auto category = parseCategory(irs::string_ref(&*(res[1].first), std::distance(res[1].first, res[1].second)));
      auto& count = category_counts.emplace(category, 0).first->second;

      if (++count <= tasks_per_category) {
        buf.emplace_back(category, std::string(res[2].first, res[2].second));
      }
    }
  }
}

static int testQueries(std::vector<Task::ptr>& tasks, irs::directory_reader& reader) {
    for (auto& segment : reader) { // iterate segments
        int cnt = 0;

        for (auto& task : tasks) {
            ++cnt;
            std::cout << "running query=" << cnt << std::endl;

            auto& query = task->prepared;
            auto docs = query->execute(segment); // query segment

            while (docs->next()) {
                const irs::doc_id_t doc_id = docs->value(); // get doc id

                std::cout << cnt << " : " << doc_id << std::endl;
            }
        }
    }

    return 0;
}

static int printResults(std::vector<Task::ptr>& tasks, std::ostream& out, bool csv) {
    for (auto& task : tasks) {
        csv ? task->print_csv(out) : task->print(out);
    }
    return 0;
}

int search(
    const std::string& path,
    const std::string& dir_type,
    const std::string& format,
    std::istream& in,
    std::ostream& out,
    size_t tasks_max,
    size_t repeat,
    size_t search_threads,
    size_t limit,
    bool shuffle,
    bool csv,
    size_t scored_terms_limit,
    const std::string& scorer,
    const std::string& scorer_arg_format,
    const irs::string_ref& scorer_arg
) {
  static const std::map<std::string, const irs::text_format::type_id&> text_formats = {
    { "csv", irs::text_format::csv },
    { "json", irs::text_format::json },
    { "text", irs::text_format::text },
    { "xml", irs::text_format::xml },
  };
  auto arg_format_itr = text_formats.find(scorer_arg_format);

  if (arg_format_itr == text_formats.end()) {
    std::cerr << "Unknown scorer argument format '" << scorer_arg_format << "'" << std::endl;
    return 1;
  }

  auto scr = irs::scorers::get(scorer, arg_format_itr->second, scorer_arg);

  if (!scr) {
    if (scorer_arg.null()) {
      std::cerr << "Unable to instantiate scorer '" << scorer << "' with argument format '" << scorer_arg_format << "' with nil arguments" << std::endl;
    } else {
      std::cerr << "Unable to instantiate scorer '" << scorer << "' with argument format '" << scorer_arg_format << "' with arguments '" << scorer_arg << "'" << std::endl;
    }
    return 1;
  }

  auto dir = create_directory(dir_type, path);

  if (!dir) {
    std::cerr << "Unable to create directory of type '" << dir_type << "'" << std::endl;
    return 1;
  }

  auto codec = irs::formats::get(format);

  if (!codec) {
    std::cerr << "Unable to find format of type '" << format << "'" << std::endl;
    return 1;
  }

  repeat = (std::max)(size_t(1), repeat);
  search_threads = (std::max)(size_t(1), search_threads);
  scored_terms_limit = (std::max)(size_t(1), scored_terms_limit);

  SCOPED_TIMER("Total Time");
  std::cout << "Configuration: " << std::endl;
  std::cout << INDEX_DIR << "=" << path << std::endl;
  std::cout << MAX << "=" << tasks_max << std::endl;
  std::cout << RPT << "=" << repeat << std::endl;
  std::cout << THR << "=" << search_threads << std::endl;
  std::cout << TOPN << "=" << limit << std::endl;
  std::cout << RND << "=" << shuffle << std::endl;
  std::cout << CSV << "=" << csv << std::endl;
  std::cout << SCORED_TERMS_LIMIT << "=" << scored_terms_limit << std::endl;
  std::cout << SCORER << "=" << scorer << std::endl;
  std::cout << SCORER_ARG_FMT << "=" << scorer_arg_format << std::endl;
  std::cout << SCORER_ARG << "=" << scorer_arg << std::endl;

  irs::directory_reader reader;
  irs::order::prepared order;
  irs::async_utils::thread_pool thread_pool(search_threads);

  {
    SCOPED_TIMER("Index read time");
    reader = irs::directory_reader::open(*dir, codec);
  }

  {
    SCOPED_TIMER("Order build time");
    irs::order sort;

    sort.add(true, scr);
    order = sort.prepare();
  }

  struct task_provider_t {
    std::mutex mutex;
    size_t next_task;
    std::mt19937 randomizer;
    size_t repeat;
    bool shuffle;
    std::vector<task_t> tasks;
    std::vector<size_t> task_ids;

    task_provider_t(): repeat(0), shuffle(false) {}

    void operator=(std::vector<task_t>&& lines) {
      next_task = 0;
      tasks = std::move(lines);
      task_ids.resize(tasks.size());

      for (size_t i = 0, count = task_ids.size(); i < count; ++i) {
        task_ids[i] = i;
      }

      // initial shuffle
      if (shuffle) {
        std::shuffle(task_ids.begin(), task_ids.end(), randomizer);
      }
    }

    const task_t* operator++() {
      SCOPED_LOCK(mutex);

      if (next_task >= task_ids.size()) {
        return nullptr;
      }

      auto& task = tasks[task_ids[next_task++]];

      // prepare tasks for next iteration if repeat requested
      if (next_task >= task_ids.size() && repeat) {
        next_task = 0;
        --repeat;

        // shuffle
        if (shuffle) {
          std::shuffle(task_ids.begin(), task_ids.end(), randomizer);
        }
      }

      return &task;
    }

  } task_provider;

  // prepare tasks set
  {
    std::vector<task_t> tasks;

    prepareTasks(tasks, in, tasks_max);
    task_provider.repeat = repeat - 1; // -1 for first run (i.e. additional repeats)
    task_provider.shuffle = shuffle;
    task_provider = std::move(tasks);
  }

  struct Entry {
    Entry(irs::doc_id_t i, float s)
      : id(i), score(s) {
    }

    irs::doc_id_t id;
    float score;
  };

  // indexer threads
  for (size_t i = search_threads; i; --i) {
    thread_pool.run([&task_provider, &dir, &reader, &order, limit, &out, csv, scored_terms_limit]()->void {
      static const std::string analyzer_name("text");
      static const std::string analyzer_args("{\"locale\":\"en\", \"stopwords\":[\"abc\", \"def\", \"ghi\"]}"); // from index-put
      auto analyzer = irs::analysis::analyzers::get(analyzer_name, irs::text_format::json, analyzer_args);
      irs::filter::prepared::ptr filter;
      std::string tmpBuf;

#ifdef IRESEARCH_COMPLEX_SCORING
      #if defined(_MSC_VER) && defined(IRESEARCH_DEBUG)
        typedef irs::memory::memory_multi_size_pool<irs::memory::identity_grow> pool_t;
        typedef irs::memory::memory_pool_multi_size_allocator<Entry, pool_t> alloc_t;
      #else
        typedef irs::memory::memory_pool<irs::memory::identity_grow> pool_t;
        typedef irs::memory::memory_pool_allocator<Entry, pool_t> alloc_t;
      #endif

      pool_t pool(limit + 1); // +1 for least significant overflow element

      auto comparer = [&order](const irs::bstring& lhs, const irs::bstring& rhs)->bool {
        return order.less(lhs.c_str(), rhs.c_str());
      };
      std::multimap<irs::bstring, Entry, decltype(comparer), alloc_t> sorted(
        comparer, alloc_t{pool}
      );
#else
      std::vector<std::pair<float_t, irs::doc_id_t>> sorted;
      sorted.reserve(limit + 1); // +1 for least significant overflow element
#endif

      // process a single task
      for (const task_t* task; (task = ++task_provider) != nullptr;) {
        SCOPED_TIMER("Full task processing time");
        size_t doc_count = 0;
        auto start = std::chrono::system_clock::now();

        sorted.clear();

        // parse task
        {
          static struct timers_t {
            std::vector<irs::timer_utils::timer_stat_t*> stat;
            timers_t() {
              for (size_t i = 0, count = size_t(category_t::UNKNOWN); i <= count; ++i) {
                stat.emplace_back(&irs::timer_utils::get_stat(std::string("Query building (") + stringCategory(category_t(i)).c_str() + ") time"));
              }
            }
          } timers;
          SCOPED_TIMER("Query building time");
          irs::timer_utils::scoped_timer timer(*(timers.stat[size_t(task->category)]));
          filter = prepareFilter(reader, order, task->category, task->text, analyzer, tmpBuf, scored_terms_limit);

          if (!filter) {
            continue;
          }
        }

        // execute task
        {
          static struct timers_t {
            std::vector<irs::timer_utils::timer_stat_t*> stat;
            timers_t() {
              for (size_t i = 0, count = size_t(category_t::UNKNOWN); i <= count; ++i) {
                stat.emplace_back(&irs::timer_utils::get_stat(std::string("Query execution (") + stringCategory(category_t(i)).c_str() + ") time"));
              }
            }
          } timers;
          SCOPED_TIMER("Query execution time");
          irs::timer_utils::scoped_timer timer(*(timers.stat[size_t(task->category)]));

          const float EMPTY_SCORE = 0.f;

          for (auto& segment: reader) {
            auto docs = filter->execute(segment, order); // query segment
            auto& attributes = docs->attributes();
            const irs::score& score = irs::score::extract(attributes);
            const irs::document* doc = attributes.get<irs::document>().get();

#ifdef IRESEARCH_COMPLEX_SCORING
            // ensure we avoid COW for pre c++11 std::basic_string
            const irs::bytes_ref raw_score_value = score->value();
#endif
            const auto& score_value = &score != &irs::score::no_score()
              ? order.get<float>(score.c_str(), 0)
              : EMPTY_SCORE;

            while (docs->next()) {
              ++doc_count;
              score.evaluate();

#ifdef IRESEARCH_COMPLEX_SCORING
              sorted.emplace(
                std::piecewise_construct,
                std::forward_as_tuple(raw_score_value),
                std::forward_as_tuple(docs->value(), score_value)
              );

              sorted.emplace(score_value, doc->value);

              if (sorted.size() > limit) {
                sorted.erase(--(sorted.end()));
              }
#else
              std::push_heap(
                sorted.begin(), sorted.end(),
                [](const std::pair<float_t, irs::doc_id_t>& lhs,
                   const std::pair<float_t, irs::doc_id_t>& rhs) NOEXCEPT {
                  return lhs.first < rhs.first;
              });

              if (sorted.size() > limit) {
                std::pop_heap(
                  sorted.begin(), sorted.end(),
                  [](const std::pair<float_t, irs::doc_id_t>& lhs,
                     const std::pair<float_t, irs::doc_id_t>& rhs) NOEXCEPT {
                    return lhs.first < rhs.first;
                });

                sorted.pop_back();
              }

              auto end = sorted.end();
              for (auto begin = sorted.begin(); begin != end; --end) {
                std::pop_heap(
                  begin, end,
                  [](const std::pair<float_t, irs::doc_id_t>& lhs,
                     const std::pair<float_t, irs::doc_id_t>& rhs) NOEXCEPT {
                    return lhs.first < rhs.first;
                });
              }
#endif
            }
          }
        }

        // output task results
        {
          static std::mutex mutex;
          SCOPED_LOCK(mutex);
          SCOPED_TIMER("Result processing time");
          auto tdiff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);

          if (csv) {
            out << stringCategory(task->category) << "," << task->text << "," << doc_count << "," << tdiff.count() / 1000. << "," << tdiff.count() << std::endl;
          } else {
            out << "TASK: cat=" << stringCategory(task->category) << " q='body:" << task->text << "' hits=" << doc_count << std::endl;
            out << "  " << tdiff.count() / 1000. << " msec" << std::endl;
            out << "  thread " << std::this_thread::get_id() << std::endl;

            for (auto& entry : sorted) {
#ifdef IRESEARCH_COMPLEX_SCORING
              out << "  doc=" << entry.second.id << " score=" << entry.second.score << std::endl;
#else
              out << "  doc=" << entry.second << " score=" << entry.first<< std::endl;
#endif
            }

            out << std::endl;
          }
        }
      }
    });
  }

  thread_pool.stop();

  u_cleanup();

  return 0;
}

int search(const cmdline::parser& args) {
  if (!args.exist(INDEX_DIR) || !args.exist(INPUT)) {
    return 1;
  }

  const auto& path = args.get<std::string>(INDEX_DIR);

  if (path.empty()) {
    return 1;
  }

  const size_t maxtasks = args.get<size_t>(MAX);
  const size_t repeat = args.get<size_t>(RPT);
  const bool shuffle = args.exist(RND);
  const size_t thrs = args.get<size_t>(THR);
  const size_t topN = args.get<size_t>(TOPN);
  const bool csv = args.exist(CSV);
  const size_t scored_terms_limit = args.get<size_t>(SCORED_TERMS_LIMIT);
  const auto scorer = args.get<std::string>(SCORER);
  const auto scorer_arg = args.exist(SCORER_ARG) ? irs::string_ref(args.get<std::string>(SCORER_ARG)) : irs::string_ref::NIL;
  const auto scorer_arg_format = args.get<std::string>(SCORER_ARG_FMT);
  const auto dir_type = args.exist(DIR_TYPE) ? args.get<std::string>(DIR_TYPE) : std::string("fs");
  const auto format = args.exist(FORMAT) ? args.get<std::string>(FORMAT) : std::string("1_0");

  std::cout << "Max tasks in category="                      << maxtasks           << '\n'
            << "Task repeat count="                          << repeat             << '\n'
            << "Do task list shuffle="                       << shuffle            << '\n'
            << "Search threads="                             << thrs               << '\n'
            << "Number of top documents to collect="         << topN               << '\n'
            << "Number of terms to in range/prefix queries=" << scored_terms_limit << '\n'
            << "Scorer used for ranking query results="      << scorer             << '\n'
            << "Configuration argument format for query scorer=" << scorer_arg_format << '\n'
            << "Configuration argument for query scorer="    << scorer_arg         << '\n'
            << "Output CSV="                                 << csv                << std::endl;

  std::fstream in(args.get<std::string>(INPUT), std::fstream::in);

  if (!in) {
    return 1;
  }

  if (args.exist(OUTPUT)) {
    std::fstream out(
      args.get<std::string>(OUTPUT),
      std::fstream::out | std::fstream::trunc
    );

    if (!out) {
      return 1;
    }

    return search(path, dir_type, format, in, out, maxtasks, repeat, thrs, topN, shuffle, csv, scored_terms_limit, scorer, scorer_arg_format, scorer_arg);
  }

  return search(path, dir_type, format, in, std::cout, maxtasks, repeat, thrs, topN, shuffle, csv, scored_terms_limit, scorer, scorer_arg_format, scorer_arg);
}

int search(int argc, char* argv[]) {
  // mode search
  cmdline::parser cmdsearch;
  cmdsearch.add(HELP, '?', "Produce help message");
  cmdsearch.add<std::string>(INDEX_DIR, 0, "Path to index directory", true);
  cmdsearch.add<std::string>(DIR_TYPE, 0, "Directory type (fs|mmap)", false, std::string("fs"));
  cmdsearch.add(FORMAT, 0, "Format (1_0|1_0-optimized)", false, std::string("1_0"));
  cmdsearch.add<std::string>(INPUT, 0, "Task file", true);
  cmdsearch.add<std::string>(OUTPUT, 0, "Stats file", false);
  cmdsearch.add<size_t>(MAX, 0, "Maximum tasks per category", false, size_t(1));
  cmdsearch.add<size_t>(RPT, 0, "Task repeat count", false, size_t(20));
  cmdsearch.add<size_t>(THR, 0, "Number of search threads", false, size_t(1));
  cmdsearch.add<size_t>(TOPN, 0, "Number of top search results", false, size_t(10));
  cmdsearch.add<size_t>(SCORED_TERMS_LIMIT, 0, "Number of terms to score in range/prefix queries", false, size_t(1024));
  cmdsearch.add<std::string>(SCORER, 0, "Scorer used for ranking query results", false, "bm25");
  cmdsearch.add<std::string>(SCORER_ARG, 0, "Configuration argument for query scorer", false);
  cmdsearch.add<std::string>(SCORER_ARG_FMT, 0, "Configuration argument format for query scorer", false, "json"); // 'json' is the argument format for 'bm25'
  cmdsearch.add(RND, 0, "Shuffle tasks");
  cmdsearch.add(CSV, 0, "CSV output");

  cmdsearch.parse(argc, argv);

  if (cmdsearch.exist(HELP)) {
    std::cout << cmdsearch.usage() << std::endl;
    return 0;
  }

  return search(cmdsearch);
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------


text:
module PfrpgCore
  class Filters::ProwessMod
    attr_reader :character
    def initialize(character)
      @character = character
    end

    def filter(skill)
      if (skill.name.downcase == 'intimidate')
        feat = character.char_feats.select { |x| x.pathfinder_feat.name == 'Intimidating Prowess' }
        modify_skill_for_prowess(skill) if feat
      end
    end

    def modify_skill_for_prowess(skill)
      skill.misc_bonus += character.attributes.str_mod
    end
  end
end


text:
title: CSS animations
category: Hidden
redirect_to: /css#animation
---


text:
import React from 'react'
import PropTypes from 'prop-types'
import { LinkVertical } from '@vx/shape'
import colors from 'src/components/colors'

class LinkPrimitive extends React.Component {
  static propTypes = {
    link: PropTypes.object.isRequired,
    warnings: PropTypes.array.isRequired,
    errors: PropTypes.array.isRequired
  }

  checkNode (node, events) {
    switch (node.type) {
      case 'logical':
        return events.find(e => e.logicalDeviceId === node.deviceId) !== void 0
      case 'physical':
        return events.find(e => e.physicalDeviceId === node.deviceId) !== void 0
      case 'merchant':
        return events.find(e => e.merchantId === node.merchantId) !== void 0
      case 'account':
        return events.find(e => e.accountId === node.accountId) !== void 0
      case 'customer':
        return events.find(e => e.customerId === node.customerId) !== void 0
      case 'tradePoint':
        return events.find(e => e.tradePointId === node.tradePointId) !== void 0
      case 'address':
        return events.find(e => e.addressId === node.addressId) !== void 0
        // return events.find(e => [e.addressId, e.customerAddressId].includes(node.addressId)) !== void 0
      case 'city':
        return events.find(e => e.cityId === node.cityId) !== void 0
        // return events.find(e => [e.cityId, e.customerCityId].includes(node.cityId)) !== void 0
      case 'region':
        return events.find(e => e.regionId === node.regionId) !== void 0
        // return events.find(e => [e.regionId, e.customerRegionId].includes(node.regionId)) !== void 0
      case 'country':
        return events.find(e => e.countryId === node.countryId) !== void 0
        // return events.find(e => [e.countryId, e.customerCountryId].includes(node.countryId)) !== void 0
    }
    return false
  }

  checkLink (link, events) {
    return this.checkNode(link.target, events) && this.checkNode(link.source, events)
  }

  render () {
    const { link, errors, warnings } = this.props
    const isError = this.checkLink(link, errors)
    const isWarning = this.checkLink(link, warnings)
    const statusColor =
      isError ? colors.error :
      isWarning ? colors.warning :
      void 0
    const isAddress = link.type.match(/(address)|(city)|(region)|(country)/)
    if (isAddress !== null) {
      return (
        <LinkVertical
          data={link}
          stroke={statusColor || '#00afa3'}
          strokeDasharray='8, 12'
          strokeWidth={1.5}
          strokeOpacity={0.5}
          fill='none'
        />
      )
    }
    const isOwner = link.type.match(/(merchant)|(account)|(customer)|(tradePoint)/)
    if (isOwner !== null) {
      return (
        <LinkVertical
          data={link}
          stroke={statusColor || '#008ba0'}
          strokeDasharray='8, 4'
          strokeWidth={1}
          strokeOpacity={0.5}
          fill='none'
        />
      )
    }
    const isLogical = link.type.match(/(logical)/)
    if (isLogical !== null) {
      return (
        <LinkVertical
          data={link}
          stroke={statusColor || '#00d8d4'}
          strokeWidth={1.5}
          strokeOpacity={0.5}
          fill='none'
        />
      )
    }
    const isPhysical = link.type.match(/(physical)/)
    if (isPhysical !== null) {
      if (link.type === 'physical - physical') {
        return (
          <LinkVertical
            data={link}
            stroke={statusColor || '#03c0dc'}
            // strokeDasharray='12, 4'
            strokeWidth={3.0}
            strokeOpacity={0.5}
            fill='none'
          />
        )
      } else {
        return (
          <LinkVertical
            data={link}
            stroke={statusColor || '#00bde7'}
            strokeWidth={1.5}
            strokeOpacity={0.5}
            fill='none'
          />
        )
      }
    }
  }
}

export default LinkPrimitive


text:
let out = "";
let $lineNumber = 1;
let $filename = "{{__dirname}}index.edge";
try {
out += await template.compileComponent("components-isolated-state/alert")(template, template.getComponentState({}, { $context: Object.assign({}, $context), main: function () { return "" } }, { filename: $filename, line: $lineNumber, col: 0 }), $context);
} catch (error) {
template.reThrow(error, $filename, $lineNumber);
}
return out;


text:
void enter_button(GtkWidget *widget, gpointer data)
{
  GdkColor color;
  color.red = 27000;
  color.green = 30325;
  color.blue = 34181;
  gtk_widget_modify_bg(widget, GTK_STATE_PRELIGHT, &color);
}

int main( int argc, char *argv[])
{

  GtkWidget *window;
  GtkWidget *fixed;
  GtkWidget *button;

  gtk_init(&argc, &argv);

  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);
  gtk_window_set_default_size(GTK_WINDOW(window), 230, 150);
  gtk_window_set_title(GTK_WINDOW(window), "enter signal");

  fixed = gtk_fixed_new();
  gtk_container_add(GTK_CONTAINER(window), fixed);

  button = gtk_button_new_with_label("Button");
  gtk_widget_set_size_request(button, 80, 35);
  gtk_fixed_put(GTK_FIXED(fixed), button, 50, 50);

  g_signal_connect(G_OBJECT(button), "enter",
      G_CALLBACK(enter_button), NULL);

  g_signal_connect_swapped(G_OBJECT(window), "destroy",
      G_CALLBACK(gtk_main_quit), NULL);

  gtk_widget_show_all(window);

  gtk_main();

  return 0;
}


text:
app.controller('userdashboard', function($scope, $http){

    $http.get('/cafeinfos2').then(function (res) {
        console.log(res)
    })

})


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>OFMatchReconcile</title>
<meta name="date" content="2014-02-26">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

etri.sdn.controller.module.flowcache

Class OFMatchReconcile

java.lang.Object

etri.sdn.controller.module.flowcache.OFMatchReconcile

public class OFMatchReconcile
extends java.lang.Object

OFMatchReconcile class to indicate result of a flow-reconciliation.

Nested Class Summary

Nested Classes

Modifier and Type
Class and Description

static class
OFMatchReconcile.ReconcileAction

The enum ReconcileAction.

Field Summary

Fields

Modifier and Type
Field and Description

byte
action

Action of this flow-mod PERMIT or DENY

java.lang.String
appInstName

The application instance name.

MessageContext
cntx

long
cookie

flow mod. cookie

java.lang.String
newAppInstName

The new application instance name.

OFMatchWithSwDpid
ofmWithSwDpid

The open flow match after reconciliation.

short
priority

flow mod. priority

OFMatchReconcile.ReconcileAction
rcAction

The reconcile action.

Constructor Summary

Constructors

Constructor and Description

OFMatchReconcile()

Instantiates a new oF match reconcile object.

OFMatchReconcile(OFMatchReconcile copy)

Method Summary

Methods

Modifier and Type
Method and Description

java.lang.String
toString()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Field Detail

ofmWithSwDpid

public OFMatchWithSwDpid ofmWithSwDpid

The open flow match after reconciliation.

priority

public short priority

flow mod. priority

action

public byte action

Action of this flow-mod PERMIT or DENY

cookie

public long cookie

flow mod. cookie

appInstName

public java.lang.String appInstName

The application instance name.

newAppInstName

public java.lang.String newAppInstName

The new application instance name. This is null unless the flow
 has moved to a different BVS due to BVS config change or device
 move to a different switch port etc.

rcAction

public OFMatchReconcile.ReconcileAction rcAction

The reconcile action.

cntx

public MessageContext cntx

Constructor Detail

OFMatchReconcile

public OFMatchReconcile()

Instantiates a new oF match reconcile object.

OFMatchReconcile

public OFMatchReconcile(OFMatchReconcile copy)

Method Detail

toString

public java.lang.String toString()

Overrides:

toString in class java.lang.Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
package com.karuslabs.commons.item.builders;

import java.util.Collection;

import org.bukkit.*;
import org.bukkit.inventory.meta.*;

/**
 * A knowledge book builder.
 */
public final class KnowledgeBookBuilder extends Builder<KnowledgeBookMeta, KnowledgeBookBuilder> {

    /**
     * Creates a {@code KnowledgeBookBuilder}.
     *
     * @return a {@code KnowledgeBookBuilder}
     */
    public static KnowledgeBookBuilder of() {
        return new KnowledgeBookBuilder();
    }

    KnowledgeBookBuilder() {
        super(Material.KNOWLEDGE_BOOK);
    }

    KnowledgeBookBuilder(Builder<ItemMeta, ?> source) {
        super(source);
    }

    /**
     * Adds the given recipes.
     *
     * @param recipes the recipes
     * @return {@code this}
     */
    public KnowledgeBookBuilder recipes(NamespacedKey... recipes) {
        meta.addRecipe(recipes);
        return this;
    }

    /**
     * Adds the given recipes.
     *
     * @param recipes the recipes
     * @return {@code this}
     */
    public KnowledgeBookBuilder recipes(Collection<NamespacedKey> recipes) {
        meta.addRecipe(recipes.toArray(new NamespacedKey[0]));
        return this;
    }

    @Override
    KnowledgeBookBuilder self() {
        return this;
    }

}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uporaba zaganjalnika za zaganjanje programov</title>
<link rel="stylesheet" type="text/css" href="../vodnik_1404.css">
<link rel="stylesheet" type="text/css" >

Ubuntu Slovenija | Uradna spletna stran slovenske skupnosti Linux distribucije Ubuntu

Novice

Forum

Kaj je Ubuntu?

Pogosta vprašanja

Skupnost

Povezave

					</script>

  Namizni vodnik Ubuntu »

Uporaba zaganjalnika za zaganjanje programov

Zaganjalnik je ena izmed ključnih komponent novega namizja Unity. Ko se boste prvič prijavili, se bo pojavil na levi strani zaslona. Zaganjalnik vam ponuja hiter dostop do programov, delovnih okolj Unity in leč, kot tudi smeti.

V primeru da se program, ki ga želite uporabljati, nahaja v Zaganjalniku, lahko kliknete na ikono programa in začel se bo pripravljen za uporabo.

Odpiranje Zaganjalnika

Morda boste opazili, da Zaganjalnik skrije, ko pride v stik z odprtim programom. Zaganjalnik lahko ponovno prikličete na številne načine. Preizkušajte in poskusite vsakega od naslednjih načinov za odprtje Zaganjalnika:

Premaknite svoj miškin kazalec na levo stran zaslona in potisnite kazalec proti robu zaslona. Zaganjalnik se bo pojavil po kratkem zamiku.

Premaknite miški kazalec v zgornji levi kot zaslona. Zaganjalnik se bo hipoma pojavil.

Dvakrat pritisnite tipko meta. Zaganjalnik se bo za kratek čas pojavil, vendar bo izginil, če miške ne premaknete nad Zaganjalnik.

Pritisnite in držite tipko meta. Pojavil se bo Zaganjalnik. Na vrhu ikon zaganjalnika se bodo pojavila števila. To vam omogoča zagon programa s pritiskom na eno od števil.

Kateri pristop vam je najbolj všeč? Kateri pristop vam bo pomagal izvršiti delo kar najbolj učinkovito?

Za več o Zaganjalniku raziščite katerokoli od tem pomoči o Zaganjalniku spodaj.

Osnove Zaganjalnika

Prilagajanje Zaganjalnika

Pripenjanje priljubljenih programov na zaganjalnik — Dodajanje, premikanje ali odstranjevanje ikon pogosto uporabljenih programov na zaganjalnik.
Sprememba velikosti ikon v zaganjalniku — Naredite ikone v zaganjalniku večje ali manjše, da ustrezajo vašim željam.

Nadaljnje branje

Več podrobnosti

Namizni vodnik Ubuntu — Namizni vodnik Ubuntu

Material v tem dokumentu je na voljo pod prosto licenco. To je prevod dokumentacije Ubuntu, ki jo je sestavila Ubuntu dokumentacijska ekpa za Ubuntu. V slovenščino jo je prevedla skupina Ubuntu prevajalcev. Za poročanje napak v prevodih v tej dokumentaciji ali Ubuntuju pošljite sporočilo na dopisni seznam.


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

    <string name="app_name">DigitalSignalAnalyzer</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="select_signal">Select signal</string>
    <string name="calculate_spectrum">Spectrum</string>
    <string name="select_periodic_component">Periodic component (Hz)</string>
    <string name="selected_periodic_components">Selected periodic components (Hz):</string>
    <string name="periodic_component">Periodic component</string>
    <string name="done">Done</string>
    <string name="add_frequency">Add</string>
    <string name="convert_to_signals">To signals</string>
    <string name="navigation_drawer_open">Open navigation drawer</string>
    <string name="navigation_drawer_close">Close navigation drawer</string>
    <string name="action_example">Example action</string>
    <string name="raw_spectrum">Raw spectrum</string>
    <string name="periodic_spectrum">Periodic spectrum</string>
    <string name="noise_spectrum">Noise spectrum</string>

</resources>


text:
import * as React from 'react';
import { HeroImage } from '..';
import { classes } from './HeroImageWiringExample.st.css';

export const HeroImageWiringExample = () => {
  return (
    <HeroImage
      src="c5f754_186e90ba2c9b47de8a4a0a0346865b72~mv2.png"
      width={820}
      height={312}
      alt="One narrow vase with two wide vases"
      className={classes.root}
    />
  );
};


text:
/* automatically generated by rust-bindgen */

#![allow(
    dead_code,
    non_snake_case,
    non_camel_case_types,
    non_upper_case_globals
)]

#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct Entry<K, V> {
    pub _base: K,
    pub mData: V,
    pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<K>>,
    pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell<V>>,
}
impl<K, V> Default for Entry<K, V> {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}
#[repr(C)]
#[derive(Debug, Default, Copy, Clone)]
pub struct nsBaseHashtable {
    pub _address: u8,
}
pub type nsBaseHashtable_EntryType<K, V> = Entry<K, V>;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct nsBaseHashtable_EntryPtr<K, V> {
    pub mEntry: *mut nsBaseHashtable_EntryType<K, V>,
    pub mExistingEntry: bool,
    pub _phantom_0: ::std::marker::PhantomData<::std::cell::UnsafeCell<K>>,
    pub _phantom_1: ::std::marker::PhantomData<::std::cell::UnsafeCell<V>>,
}
impl<K, V> Default for nsBaseHashtable_EntryPtr<K, V> {
    fn default() -> Self {
        unsafe { ::std::mem::zeroed() }
    }
}


text:
import {RoomOptions} from './RoomOptions'
import {StreamPeer} from './StreamPeer'

export class StreamRoom {
	// TODO: This should not be hard-coded ideally... but it won't hurt for now
	private static ICE_CONFIG: Object = {
		'iceServers': [{
			'url': 'stun:stun.l.google.com:19302'
		}]
	}

	private _roomOptions: RoomOptions;
	private _localStreams: Array<MediaStream>;
	private _socket: Socket;
	private _sessionToken: string;

	private _peerMap: Object = {};
	private _channelMap: Object = {};

	constructor(localStreams: Array<MediaStream>, options: RoomOptions, socket: Socket, sessionToken: string) {
		this._localStreams = localStreams;
		this._roomOptions = options;
		this._socket = socket;
		this._sessionToken = sessionToken;

		var self = this;

		alert('reg')
		// Register handlers as needed
		this._socket.on('msg', (data) => {
			console.log("Handling payload...");
			self.handleMessages(data);
		});

		this._socket.on('peer.connected', (data) => {
			self.makeOfferFor(data.id);
		});

		this._socket.on('peer.disconnected', (data) => {
			self.trigger('peer.removed', { id: data.id });
		})

	}

	private getPeerConnection(id: string): RTCPeerConnection {
		if (this._peerMap[id]) {
			return this._peerMap[id];
		}

		var pc: RTCPeerConnection = new RTCPeerConnection(StreamRoom.ICE_CONFIG);

		// TODO: Implement a stack that uses the {StreamPeer}
		// Right now, we rely on the bare metal implementation.

		var streamPeer : StreamPeer = new StreamPeer(pc, id);

		this._peerMap[id] = pc;

		var self = this;

		// Add all streams
		this._localStreams.forEach((stream) => {
			pc.addStream(stream);
		})

		pc.onicecandidate = function(evnt) {
			console.log("ICE candidate recieved... broadcasting request");
			console.log(self._sessionToken);
			self._socket.emit('msg', { by: self._sessionToken, to: id, ice: evnt.candidate, type: 'ice' });
		};

		pc.onaddstream = function(event) {
			console.log("Got new stream.. inform UI?");
			self.trigger('newstream', event);
		};

		pc.onremovestream = function(event) {
			console.log("Stream lost");
		}

		// Callbacks for text streams
		var options = {
			ordered: false
		}

		var _channel: RTCDataChannel = pc.createDataChannel("data", options);

		_channel.onopen = () => {
			console.log("Attempted to send data down the pipe.");
		};

		// Maps to the channel
		this._channelMap[id] = _channel;

		pc.ondatachannel = (event: any) => {
			console.log(event);
			console.log("Channel was created");
			event.channel.onmessage = (payload) => {
				self.trigger('data', payload.data);
			}
		}

		return pc;
	}

	private makeOfferFor(id: string) {
		var peer: RTCPeerConnection = this.getPeerConnection(id);

		peer.createOffer((description: RTCSessionDescription) => {
			peer.setLocalDescription(description);
			console.log("Creating offer for Peer... ID: " + id);
			this._socket.emit('msg', { by: this._sessionToken, to: id, sdp: description, type: 'sdp-offer' });
		}, () => {
			alert('failed');
		})
	}

	private handleMessages(messageData: any) {
		var peer: RTCPeerConnection = this.getPeerConnection(messageData.by);
		var self = this;

		switch (messageData.type) {
			case 'sdp-offer':
				peer.setRemoteDescription(new RTCSessionDescription(messageData.sdp), function() {
					console.log('Setting remote description by offer');
					peer.createAnswer(function(sdp) {
						console.log('set the local description');
						peer.setLocalDescription(sdp);
						self._socket.emit('msg', { by: self._sessionToken, to: messageData.by, sdp: sdp, type: 'sdp-answer' });
					}, function(error) {
						console.log(error);
					});
				}, function(error) {
					console.log(error);
				});
				break;

			case 'sdp-answer':
				peer.setRemoteDescription(new RTCSessionDescription(messageData.sdp), function() {
					console.log('Setting remote description by answer');
				}, function(e) {
					console.error(e);
				});
				break;

			case 'ice':
				if (messageData.ice) {
					console.log('Adding ice candidates... OK!');
					console.log(messageData);
					var cand: RTCIceCandidate = new RTCIceCandidate(messageData.ice);
					peer.addIceCandidate(cand, () => { }, () => { });
				}
				break;
		}
	}

	sendMessage(message: string): void {
		Object.keys(this._channelMap).forEach((key) => {
			let channel: RTCDataChannel = this._channelMap[key];
			channel.send(message);
		});
	}

	private _eventMap: Object = {};

	/**
	 * Allows listening for a particular set of listeners for a certain event
	 */
	on(eventType: string, listener: Function) {
		if (!this._eventMap[eventType])
			this._eventMap[eventType] = [];

		this._eventMap[eventType].push(listener);
	}

	private trigger(eventType: string, data: any) {
		console.log("Dispatching event; " + eventType + " to all listeners.");
		this._eventMap[eventType].forEach(listener => {
			listener(data);
		});
	}

	get roomName(): string {
		return this._roomOptions.roomName;
	}

}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ITopInterface.cs" company="OBeautifulCode">
//   Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace OBeautifulCode.Serialization.Test
{
    using System;
    using System.Diagnostics.CodeAnalysis;

    [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "required for test")]
    public interface ITopInterface
    {
        string Species { get; set; }
    }

    [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "required for test")]
    public interface IMiddleInterface : ITopInterface
    {
        string Name { get; set; }
    }

    [Serializable]
    [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "required for test")]
    public class BottomClass : IMiddleInterface
    {
        public string Species { get; set; }

        public string Name { get; set; }
    }
}


text:
<?php
namespace App\Security;

use App\Model\Match\MatchId;
use App\Service\FindMatchService;
use App\Uid64\Uid64;
use Doctrine\ORM\EntityNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;

/**
 * Class MatchPlayerProvider
 *
 * @package App\Security
 * @author  Maarten Bicknese <maarten.bicknese@devmob.com>
 */
class MatchPlayerProvider implements UserProviderInterface
{
    /**
     * @var FindMatchService
     */
    private $findMatchService;

    /**
     * MatchProvider constructor.
     * @param FindMatchService $findMatchService
     */
    public function __construct(FindMatchService $findMatchService)
    {
        $this->findMatchService = $findMatchService;
    }

    /**
     * @param string $matchId Text representation of the match id
     *
     * @return MatchPlayer
     *
     * @throws UsernameNotFoundException if the user is not found
     */
    public function loadUserByUsername($matchId): MatchPlayer
    {
        try {
            $match = $this->findMatchService->execute(new MatchId(Uid64::fromText($matchId)));
        } catch (EntityNotFoundException $entityNotFoundException) {
            throw new UsernameNotFoundException();
        }

        return new MatchPlayer($match, 1);
    }

    /**
     * Refreshes the user for the account interface.
     *
     * It is up to the implementation to decide if the user data should be
     * totally reloaded (e.g. from the database), or if the UserInterface
     * object can just be merged into some internal array of users / identity
     * map.
     *
     * @param UserInterface $user
     *
     * @return UserInterface
     *
     * @throws UnsupportedUserException if the account is not supported
     */
    public function refreshUser(UserInterface $user)
    {
        return $user;
    }

    /**
     * Whether this provider supports the given user class.
     *
     * @param string $class
     *
     * @return bool
     */
    public function supportsClass($class)
    {
        return true;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

  <bean id="folderListingResourceTypeDefinition" parent="primaryResourceType">
    <property name="name" value="folder-listing" />
    <property name="namespace" ref="DEFAULT_NAMESPACE" />
    <property name="parentTypeDefinition" ref="collectionResourceTypeDefinition" />
    <property name="assertions">
      <list>
        <bean class="vtk.repository.resourcetype.ResourcePropertyAssertion">
          <property name="namespace" ref="DEFAULT_NAMESPACE" />
          <property name="name" value="collection-type" />
          <property name="value" value="folder-listing" />
          <property name="checkExistenceOnly" value="false" />
        </bean>
      </list>
    </property>
  </bean>

  <bean id="resourceIsFolderListing" class="vtk.repository.resourcetype.ResourceTypeAssertion"
        parent="repositoryAware">
    <property name="resourceTypeDefinition" ref="folderListingResourceTypeDefinition" />
    <property name="exactMatch" value="true" />
  </bean>

</beans>


text:
var tracks = {

    ground  : 'surface.ogg',      //'166823__quistard__water-drop-big.wav',
    wall    : 'reflection.ogg',   //'81258__jesterdyne__splash2-hi.wav',
    cloud   : 'vortex.ogg',       //'166158__adam-n__slurp.wav',
    bullet  : 'water.ogg'         //'95087__nicstage__pewitswater2.wav'

  },

  loop = 'bullet'

        .split(' ');

//----------------------------------------------------------//

if ( !window.URL ) window.URL = window.webkitURL || window.msURL || window.oURL;

//----------------------------------------------------------//

var entries   = Object.keys( tracks ),

    pending   = entries.length,

    percent   = 0,

    step      = 1/pending * 100,

    callbackProgress, callbackReady;

for ( var i = 0, l = pending; i < l; i++ ) request( entries[i] );

function request ( key ) {

  var xhr = new XMLHttpRequest();

  xhr.open( 'GET', 'assets/sounds/' + tracks[ key ] );

  xhr.onload = function ( e ) { loaded( key, e.currentTarget.response ); };

  xhr.responseType = 'blob';

  xhr.send();
}

function loaded ( key, data ) {

  var url = URL.createObjectURL( data );

  // make sure data URL exists
  setTimeout(function(){

    new Audio( url ).addEventListener( 'canplay' , function storeTrack(){

      this.removeEventListener( 'canplay', storeTrack );

      URL.revokeObjectURL( url );

      if ( ~loop.indexOf(key) ) this.loop = true;

      tracks[ key ] = this;

      callbackProgress( percent += step );

      if ( ! --pending && typeof callbackReady === 'function' ) callbackReady();
    });

  }, 16.7 );
}

function loading ( progress ) {

  callbackProgress = progress;
}

function ready ( init ) {

  callbackReady = init;

  if ( !pending ) callbackReady();
}


text:
package org.jkiss.dbeaver.ui.controls;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.menus.WorkbenchWindowControlContribution;
import org.jkiss.dbeaver.ui.DBeaverIcons;
import org.jkiss.dbeaver.ui.UIIcon;

/**
 * ToolbarVerticalSeparator
 */
public class ToolbarVerticalSeparator extends WorkbenchWindowControlContribution {
    public ToolbarVerticalSeparator()
    {
        super();
    }

    @Override
    protected Control createControl(Composite parent)
    {
        Label label = new Label(parent, SWT.NONE);
        label.setImage(DBeaverIcons.getImage(UIIcon.DRAG_HANDLE));
        return label;
    }
}


text:
package huobi

import (
	"crypto/ecdsa"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"io/ioutil"
	"strconv"
	"strings"
	"testing"

	"github.com/thrasher-/gocryptotrader/common"
	"github.com/thrasher-/gocryptotrader/config"
)

// Please supply you own test keys here for due diligence testing.
const (
	apiKey    = ""
	apiSecret = ""
)

var h HUOBI

// getDefaultConfig returns a default huobi config
func getDefaultConfig() config.ExchangeConfig {
	return config.ExchangeConfig{
		Name:                    "Huobi",
		Enabled:                 true,
		Verbose:                 true,
		Websocket:               false,
		UseSandbox:              false,
		RESTPollingDelay:        10,
		HTTPTimeout:             15000000000,
		AuthenticatedAPISupport: true,
		APIKey:                  "",
		APISecret:               "",
		ClientID:                "",
		AvailablePairs:          "BTC-USDT,BCH-USDT",
		EnabledPairs:            "BTC-USDT",
		BaseCurrencies:          "USD",
		AssetTypes:              "SPOT",
		SupportsAutoPairUpdates: false,
		ConfigCurrencyPairFormat: &config.CurrencyPairFormatConfig{
			Uppercase: true,
			Delimiter: "-",
		},
		RequestCurrencyPairFormat: &config.CurrencyPairFormatConfig{
			Uppercase: false,
		},
	}
}

func TestSetDefaults(t *testing.T) {
	h.SetDefaults()
}

func TestSetup(t *testing.T) {
	cfg := config.GetConfig()
	cfg.LoadConfig("../../testdata/configtest.json")
	hConfig, err := cfg.GetExchangeConfig("Huobi")
	if err != nil {
		t.Error("Test Failed - Huobi Setup() init error")
	}

	hConfig.AuthenticatedAPISupport = true
	hConfig.APIKey = apiKey
	hConfig.APISecret = apiSecret

	h.Setup(hConfig)
}

func TestGetFee(t *testing.T) {
	t.Parallel()
	if h.GetFee() != 0 {
		t.Errorf("test failed - Huobi GetFee() error")
	}
}

func TestGetSpotKline(t *testing.T) {
	t.Parallel()
	_, err := h.GetSpotKline(KlinesRequestParams{
		Symbol: "btcusdt",
		Period: TimeIntervalHour,
		Size:   0,
	})
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetSpotKline: %s", err)
	}
}

func TestGetMarketDetailMerged(t *testing.T) {
	t.Parallel()
	_, err := h.GetMarketDetailMerged("btcusdt")
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetMarketDetailMerged: %s", err)
	}
}

func TestGetDepth(t *testing.T) {
	t.Parallel()
	_, err := h.GetDepth(OrderBookDataRequestParams{
		Symbol: "btcusdt",
		Type:   OrderBookDataRequestParamsTypeStep1,
	})

	if err != nil {
		t.Errorf("Test failed - Huobi TestGetDepth: %s", err)
	}
}

func TestGetTrades(t *testing.T) {
	t.Parallel()
	_, err := h.GetTrades("btcusdt")
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetTrades: %s", err)
	}
}

func TestGetLatestSpotPrice(t *testing.T) {
	t.Parallel()
	_, err := h.GetLatestSpotPrice("btcusdt")
	if err != nil {
		t.Errorf("Test failed - Huobi GetLatestSpotPrice: %s", err)
	}
}

func TestGetTradeHistory(t *testing.T) {
	t.Parallel()
	_, err := h.GetTradeHistory("btcusdt", "50")
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetTradeHistory: %s", err)
	}
}

func TestGetMarketDetail(t *testing.T) {
	t.Parallel()
	_, err := h.GetMarketDetail("btcusdt")
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetTradeHistory: %s", err)
	}
}

func TestGetSymbols(t *testing.T) {
	t.Parallel()
	_, err := h.GetSymbols()
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetSymbols: %s", err)
	}
}

func TestGetCurrencies(t *testing.T) {
	t.Parallel()
	_, err := h.GetCurrencies()
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetCurrencies: %s", err)
	}
}

func TestGetTimestamp(t *testing.T) {
	t.Parallel()
	_, err := h.GetTimestamp()
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetTimestamp: %s", err)
	}
}

func TestGetAccounts(t *testing.T) {
	t.Parallel()

	if h.APIKey == "" || h.APISecret == "" || h.APIAuthPEMKey == "" {
		t.Skip()
	}

	_, err := h.GetAccounts()
	if err != nil {
		t.Errorf("Test failed - Huobi GetAccounts: %s", err)
	}
}

func TestGetAccountBalance(t *testing.T) {
	t.Parallel()

	if h.APIKey == "" || h.APISecret == "" || h.APIAuthPEMKey == "" {
		t.Skip()
	}

	result, err := h.GetAccounts()
	if err != nil {
		t.Errorf("Test failed - Huobi GetAccounts: %s", err)
	}

	userID := strconv.FormatInt(result[0].ID, 10)
	_, err = h.GetAccountBalance(userID)
	if err != nil {
		t.Errorf("Test failed - Huobi GetAccountBalance: %s", err)
	}
}

func TestSpotNewOrder(t *testing.T) {
	t.Parallel()

	if h.APIKey == "" || h.APISecret == "" || h.APIAuthPEMKey == "" {
		t.Skip()
	}

	arg := SpotNewOrderRequestParams{
		Symbol:    "btcusdt",
		AccountID: 000000,
		Amount:    0.01,
		Price:     10.1,
		Type:      SpotNewOrderRequestTypeBuyLimit,
	}

	_, err := h.SpotNewOrder(arg)
	if err != nil {
		t.Errorf("Test failed - Huobi SpotNewOrder: %s", err)
	}
}

func TestCancelOrder(t *testing.T) {
	t.Parallel()

	_, err := h.CancelOrder(1337)
	if err == nil {
		t.Error("Test failed - Huobi TestCancelOrder: Invalid orderID returned true")
	}
}

func TestGetOrder(t *testing.T) {
	t.Parallel()

	_, err := h.GetOrder(1337)
	if err == nil {
		t.Error("Test failed - Huobi TestCancelOrder: Invalid orderID returned true")
	}
}

func TestGetMarginLoanOrders(t *testing.T) {
	t.Parallel()

	if h.APIKey == "" || h.APISecret == "" || h.APIAuthPEMKey == "" {
		t.Skip()
	}

	_, err := h.GetMarginLoanOrders("btcusdt", "", "", "", "", "", "", "")
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetMarginLoanOrders: %s", err)
	}
}

func TestGetMarginAccountBalance(t *testing.T) {
	t.Parallel()

	if h.APIKey == "" || h.APISecret == "" || h.APIAuthPEMKey == "" {
		t.Skip()
	}

	_, err := h.GetMarginAccountBalance("btcusdt")
	if err != nil {
		t.Errorf("Test failed - Huobi TestGetMarginAccountBalance: %s", err)
	}
}

func TestCancelWithdraw(t *testing.T) {
	t.Parallel()

	_, err := h.CancelWithdraw(1337)
	if err == nil {
		t.Error("Test failed - Huobi TestCancelWithdraw: Invalid withdraw-ID was valid")
	}
}

func TestPEMLoadAndSign(t *testing.T) {
	t.Parallel()

	pemKey := strings.NewReader(h.APIAuthPEMKey)
	pemBytes, err := ioutil.ReadAll(pemKey)
	if err != nil {
		t.Fatalf("Test Failed. TestPEMLoadAndSign Unable to ioutil.ReadAll PEM key: %s", err)
	}

	block, _ := pem.Decode(pemBytes)
	if block == nil {
		t.Fatalf("Test Failed. TestPEMLoadAndSign Block is nil")
	}

	x509Encoded := block.Bytes
	privKey, err := x509.ParseECPrivateKey(x509Encoded)
	if err != nil {
		t.Fatalf("Test Failed. TestPEMLoadAndSign Unable to ParseECPrivKey: %s", err)
	}

	_, _, err = ecdsa.Sign(rand.Reader, privKey, common.GetSHA256([]byte("test")))
	if err != nil {
		t.Fatalf("Test Failed. TestPEMLoadAndSign Unable to sign: %s", err)
	}
}


text:
//* Bobo Browse Engine - High performance faceted/parametric search implementation
//* that handles various types of semi-structured data.  Originally written in Java.
//*
//* Ported and adapted for C# by Shad Storhaug.
//*
//* Copyright (C) 2015  Shad Storhaug
//*
//* Licensed under the Apache License, Version 2.0 (the "License");
//* you may not use this file except in compliance with the License.
//* You may obtain a copy of the License at
//*
//*   http://www.apache.org/licenses/LICENSE-2.0
//*
//* Unless required by applicable law or agreed to in writing, software
//* distributed under the License is distributed on an "AS IS" BASIS,
//* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//* See the License for the specific language governing permissions and
//* limitations under the License.

// Version compatibility level: 4.0.2
namespace BoboBrowse.Net.Support
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    public static class DictionaryExtensions
    {
        public static TValue Get<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
        {
            if (key == null)
                return default(TValue);
            TValue value;
            if (dictionary.TryGetValue(key, out value))
                return value;
            else
                return default(TValue);
        }

        /// <summary>
        /// Converts a dictionary of string, Type to a display string by calling ToString() on the inner type.
        /// Note that this won't work if TValue is an IEnumerable or IDictionary.
        /// </summary>
        /// <typeparam name="TValue">The type of object in dictionary that overrides ToString().</typeparam>
        /// <param name="dictionary">A dictionary with a string key.</param>
        /// <returns>A string suitable for display or debugging.</returns>
        public static string ToDisplayString<TValue>(this IDictionary<string, TValue> dictionary)
        {
            if (dictionary == null)
            {
                return string.Empty;
            }

            return "{" + string.Join(", ", dictionary.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value.ToString())).ToArray()) + "}";
        }
    }
}


text:
<!DOCTYPE HTML>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8;"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="robots" content="all" />
    <meta name="robots" content="index,follow"/>
</head>
<body>

<script type="text/javascript" src="http://www.qq.com/404/search_children.js" charset="utf-8" homePageUrl="your site url " homePageName="回到我的主页"></script>

</body>
</html>


text:
class Light
{
    public:
        Light(const Point &position) {
            pos = position;
        };
        virtual void reactToPoints(const Point points[], const byte count) = 0;
        Point pos;
    private:
};

#endif


text:
const resourcesRouter = require('express').Router();
const resourcesCtrl = require('./resources.controller');
const logger = require('./../../../../applogger');

// get the sectionConfig
resourcesRouter.get('/sectionConfig', function (req, res) {
    try {
        resourcesCtrl.getSectionConfig().then((successResult) => {
            return res.status(201).send(successResult);
        }, (errResult) => {
            // Log the error for internal use
            logger.error('Internal error occurred');
            return res.status(500).send({ error: 'Internal error occurred, please try later..!' });
        });
    } catch (err) {
        // Log the Error for internal use
        logger.fatal('Exception occurred' + err);
        res.send({ error: 'Failed to complete successfully, please check the request and try again..!' });
        return;
    }
});

module.exports = resourcesRouter;