text:
<?php

class MMB_Helper
{
    public $mmb_multisite;

    /**
     * A helper function to log data
     *
     * @deprecated use mwp_logger() instead
     *
     * @param mixed $mixed
     */
    function _log($mixed)
    {
        if ((defined('MWP_SHOW_LOG') && MWP_SHOW_LOG == true) || get_option('mwp_debug_enable')) {
            if (is_array($mixed)) {
                $mixed = print_r($mixed, 1);
            } else {
                if (is_object($mixed)) {
                    ob_start();
                    var_dump($mixed);
                    $mixed = ob_get_clean();
                }
            }

            $md5 = get_option('mwp_log_md5');
            if ($md5 === false) {
                $md5 = md5(date('jS F Y h:i:s A'));
                update_option('mwp_log_md5', $md5);
            }
            $handle = fopen(dirname(__FILE__).'/log_'.$md5, 'a');
            fwrite($handle, $mixed.PHP_EOL);
            fclose($handle);
        }
    }

    /**
     * Initializes the file system
     */
    function init_filesystem()
    {
        global $wp_filesystem;

        if (!$wp_filesystem || !is_object($wp_filesystem)) {
            WP_Filesystem();
        }

        if (!is_object($wp_filesystem)) {
            return false;
        }

        return true;
    }

    function mmb_get_user_info($user_info = false, $info = 'login')
    {

        if ($user_info === false) {
            return false;
        }

        if (strlen(trim($user_info)) == 0) {
            return false;
        }

        return get_user_by($info, $user_info);
    }

    /**
     * Call action item filters
     */
    function mmb_parse_action_params($key = '', $params = null, $call_object = null)
    {

        global $_mmb_item_filter;
        $call_object = $call_object !== null ? $call_object : $this;
        $return      = array();

        if (isset($_mmb_item_filter[$key]) && !empty($_mmb_item_filter[$key])) {
            if (isset($params['item_filter']) && !empty($params['item_filter'])) {
                foreach ($params['item_filter'] as $_items) {
                    if (!empty($_items)) {
                        foreach ($_items as $_item) {
                            if (isset($_item[0]) && in_array($_item[0], $_mmb_item_filter[$key])) {
                                $_item[1] = isset($_item[1]) ? $_item[1] : array();
                                $return   = call_user_func(array(&$call_object, 'get_'.$_item[0]), $return, $_item[1]);
                            }
                        }
                    }
                }
            }
        }

        return $return;
    }

    /**
     * Check if function exists or not on `suhosin` black list
     */
    function mmb_function_exists($function_callback)
    {

        if (!function_exists($function_callback)) {
            return false;
        }

        $disabled = explode(', ', @ini_get('disable_functions'));
        if (in_array($function_callback, $disabled)) {
            return false;
        }

        if (extension_loaded('suhosin')) {
            $suhosin = @ini_get("suhosin.executor.func.blacklist");
            if (empty($suhosin) == false) {
                $suhosin   = explode(',', $suhosin);
                $blacklist = array_map('trim', $suhosin);
                $blacklist = array_map('strtolower', $blacklist);
                if (in_array($function_callback, $blacklist)) {
                    return false;
                }
            }
        }

        return true;
    }

    function mmb_get_transient($option_name)
    {
        if (trim($option_name) == '') {
            return false;
        }
        if (!empty($this->mmb_multisite)) {
            return $this->mmb_get_sitemeta_transient($option_name);
        }

        global $wp_version;

        if (version_compare($wp_version, '2.7.9', '<=')) {
            return get_option($option_name);
        } else {
            if (version_compare($wp_version, '2.9.9', '<=')) {
                $transient = get_option('_transient_'.$option_name);

                return apply_filters("transient_".$option_name, $transient);
            } else {
                $transient = get_option('_site_transient_'.$option_name);

                return apply_filters("site_transient_".$option_name, $transient);
            }
        }
    }

    function mmb_delete_transient($option_name)
    {
        if (trim($option_name) == '') {
            return;
        }

        global $wp_version;

        if (version_compare($wp_version, '2.7.9', '<=')) {
            delete_option($option_name);
        } else {
            if (version_compare($wp_version, '2.9.9', '<=')) {
                delete_option('_transient_'.$option_name);
            } else {
                delete_option('_site_transient_'.$option_name);
            }
        }
    }

    function mmb_get_sitemeta_transient($option_name)
    {
        /** @var wpdb $wpdb */
        global $wpdb;
        $option_name = '_site_transient_'.$option_name;

        $result = $wpdb->get_var($wpdb->prepare("SELECT `meta_value` FROM `{$wpdb->sitemeta}` WHERE meta_key = '%s' AND `site_id` = '%s'", $option_name, $this->mmb_multisite));
        $result = maybe_unserialize($result);

        return $result;
    }

    function mmb_set_sitemeta_transient($option_name, $option_value)
    {
        /** @var wpdb $wpdb */
        global $wpdb;
        $option_name = '_site_transient_'.$option_name;

        if ($this->mmb_get_sitemeta_transient($option_name)) {
            $result = $wpdb->update(
                $wpdb->sitemeta,
                array(
                    'meta_value' => maybe_serialize($option_value)
                ),
                array(
                    'meta_key' => $option_name,
                    'site_id'  => $this->mmb_multisite
                )
            );
        } else {
            $result = $wpdb->insert(
                $wpdb->sitemeta,
                array(
                    'meta_key'   => $option_name,
                    'meta_value' => maybe_serialize($option_value),
                    'site_id'    => $this->mmb_multisite
                )
            );
        }

        return $result;
    }

    function delete_temp_dir($directory)
    {
        if (substr($directory, -1) == "/") {
            $directory = substr($directory, 0, -1);
        }
        if (!file_exists($directory) || !is_dir($directory)) {
            return false;
        } elseif (!is_readable($directory)) {
            return false;
        } else {
            $directoryHandle = opendir($directory);

            while ($contents = readdir($directoryHandle)) {
                if ($contents != '.' && $contents != '..') {
                    $path = $directory."/".$contents;

                    if (is_dir($path)) {
                        $this->delete_temp_dir($path);
                    } else {
                        unlink($path);
                    }
                }
            }
            closedir($directoryHandle);
            rmdir($directory);

            return true;
        }
    }

    function set_worker_message_id($message_id = false)
    {
        if ($message_id) {
            add_option('_action_message_id', $message_id) or update_option('_action_message_id', $message_id);

            return $message_id;
        }

        return false;
    }

    function get_worker_message_id()
    {
        return (int) get_option('_action_message_id');
    }

    function set_master_public_key($public_key = false)
    {
        if ($public_key && !get_option('_worker_public_key')) {
            add_option('_worker_public_key', base64_encode($public_key));

            return true;
        }

        return false;
    }

    function get_master_public_key()
    {
        if (!get_option('_worker_public_key')) {
            return false;
        }

        return base64_decode(get_option('_worker_public_key'));
    }

    function get_random_signature()
    {
        if (!get_option('_worker_nossl_key')) {
            return false;
        }

        return base64_decode(get_option('_worker_nossl_key'));
    }

    function set_random_signature($random_key = false)
    {
        if ($random_key && !get_option('_worker_nossl_key')) {
            add_option('_worker_nossl_key', base64_encode($random_key));

            return true;
        }

        return false;
    }

    function authenticate_message($data = false, $signature = false, $message_id = false)
    {
        if (!$data && !$signature) {
            return array(
                'error' => 'Authentication failed.'
            );
        }
        $nonce = new MWP_Security_HashNonce();
        $nonce->setValue($message_id);
        if (!$nonce->verify()) {
            return array(
                'error' => 'Invalid nonce used. Please try again'
            );
        }

        $pl_key = $this->get_master_public_key();
        if (!$pl_key) {
            return array(
                'error' => 'Authentication failed. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
            );
        }

        if (function_exists('openssl_verify') && !$this->get_random_signature()) {
            $verify = openssl_verify($data, $signature, $pl_key);
            if ($verify == 1) {
                //$this->set_worker_message_id($message_id);

                return true;
            } else {
                if ($verify == 0) {
                    return array(
                        'error' => 'Invalid message signature. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
                    );
                } else {
                    return array(
                        'error' => 'Command not successful! Please try again.'
                    );
                }
            }
        } else {
            if ($this->get_random_signature()) {
                if (md5($data.$this->get_random_signature()) === $signature) {
                    //$this->set_worker_message_id($message_id);

                    return true;
                }

                return array(
                    'error' => 'Invalid message signature. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
                );
            } // no rand key - deleted in get_stat maybe
            else {
                return array(
                    'error' => 'Invalid message signature. Deactivate and activate the ManageWP Worker plugin on this site, then re-add it to your ManageWP account.'
                );
            }
        }
    }

    function get_secure_hash()
    {

        $pl_key = $this->get_master_public_key();
        if (empty($pl_key) || $this->get_random_signature() !== false) {
            $pl_key = $this->get_random_signature();
        }

        if (!empty($pl_key)) {
            return md5(base64_encode($pl_key));
        }

        return false;
    }

    function _secure_data($data = false)
    {
        if ($data == false) {
            return false;
        }

        $pl_key = $this->get_master_public_key();
        if (!$pl_key) {
            return false;
        }

        $secure = '';
        if (function_exists('openssl_public_decrypt') && !$this->get_random_signature()) {
            if (is_array($data) && !empty($data)) {
                foreach ($data as $input) {
                    openssl_public_decrypt($input, $decrypted, $pl_key);
                    $secure .= $decrypted;
                }
            } else {
                if (is_string($data)) {
                    openssl_public_decrypt($data, $decrypted, $pl_key);
                    $secure = $decrypted;
                } else {
                    $secure = $data;
                }
            }

            return $secure;
        }

        return false;

    }

    function encrypt_data($data = false)
    {
        if (empty($data)) {
            return $data;
        }

        $pl_key = $this->get_master_public_key();
        if (!$pl_key) {
            return false;
        }

        $data    = serialize($data);
        $crypted = '';
        if (function_exists('openssl_public_encrypt') && !$this->get_random_signature()) {
            $length = strlen($data);
            if ($length > 100) {
                for ($i = 0; $i <= $length + 100; $i = $i + 100) {
                    $input = substr($data, $i, 100);
                    openssl_public_encrypt($input, $crypt, $pl_key);
                    $crypted .= base64_encode($crypt).'::';
                }
            } else {
                openssl_public_encrypt($data, $crypted, $pl_key);
            }
        } else {
            $crypted = base64_encode($data);
        }

        return $crypted;

    }

    function check_if_user_exists($username = false)
    {
        global $wpdb;

        if (empty($username)) {
            return false;
        }

        if (!function_exists('username_exists')) {
            require_once ABSPATH.WPINC.'/registration.php';
        }

        require_once ABSPATH.'wp-includes/pluggable.php';

        if (username_exists($username) == null) {
            return false;
        }

        $user = (array) $this->mmb_get_user_info($username);
        if (
            (isset($user[$wpdb->prefix.'user_level']) && $user[$wpdb->prefix.'user_level'] == 10)
            || isset($user[$wpdb->prefix.'capabilities']['administrator'])
            || (isset($user['caps']['administrator']) && $user['caps']['administrator'] == 1)
        ) {
            return true;
        }

        return false;
    }

    function refresh_updates()
    {
        if (rand(1, 3) == '2') {
            require_once(ABSPATH.WPINC.'/update.php');
            wp_update_plugins();
            wp_update_themes();
            wp_version_check();
        }
    }

    function remove_http($url = '')
    {
        if ($url == 'http://' OR $url == 'https://') {
            return $url;
        }

        return preg_replace('/^(http|https)\:\/\/(www.)?/i', '', $url);

    }

    function mmb_get_error($error_object)
    {
        if (!is_wp_error($error_object)) {
            return $error_object != '' ? $error_object : '';
        } else {
            $errors = array();
            if (!empty($error_object->error_data)) {
                foreach ($error_object->error_data as $error_key => $error_string) {
                    $errors[] = str_replace('_', ' ', ucfirst($error_key)).': '.$error_string;
                }
            } elseif (!empty($error_object->errors)) {
                foreach ($error_object->errors as $error_key => $err) {
                    $errors[] = 'Error: '.str_replace('_', ' ', strtolower($error_key));
                }
            }

            return implode('<br />', $errors);
        }
    }

    function is_server_writable()
    {

        if ((!defined('FTP_HOST') || !defined('FTP_USER')) && (get_filesystem_method(array(), false) != 'direct')) {
            return false;
        } else {
            return true;
        }
    }

    function return_bytes($val)
    {
        $val  = trim($val);
        $last = strtolower($val[strlen($val) - 1]);
        switch ($last) {
            // The 'G' modifier is available since PHP 5.1.0
            case 'g':
                $val *= 1024;
            case 'm':
                $val *= 1024;
            case 'k':
                $val *= 1024;
        }

        return $val;
    }

    function w3tc_flush()
    {
    	 // if (function_exists('w3tc_pgcache_flush'))
       //	 w3tc_pgcache_flush();

       // if (function_exists('w3tc_dbcache_flush'))
      // 	 w3tc_dbcache_flush();

        if (function_exists('w3tc_objectcache_flush'))
         w3tc_objectcache_flush();
    }

    protected function notifyMyself($functionName, $args = array())
    {
        $nonce         = substr(wp_hash(wp_nonce_tick().'mmb-fork-nonce'. 0, 'nonce'), -12, 10);
        $cron_url      = site_url('index.php');
        $public_key    = get_option('_worker_public_key');
        $args          = array(
            'body'      => array(
                'mwp_forked_action' => $functionName,
                'args'               => json_encode($args),
                'mmb_fork_nonce'   => $nonce,
                'public_key'         => $public_key,
            ),
            'timeout'   => 0.01,
            'blocking'  => false,
            'sslverify' => apply_filters('https_local_ssl_verify', true)
        );
        wp_remote_post($cron_url, $args);
    }
}


text:
<?php

?>

TEC

X

        <img id="tecImage" src="<?=base_url()?>js/OudenardeTECFinal.jpg">

redpajama_set_name: RedPajamaGithub


text:
package ch.sentric.hbase.table;

/**
 *
 */
import org.apache.hadoop.hbase.util.Bytes;

public class ReportTable {
    public static final byte[] NAME = Bytes.toBytes("report");
    public static final byte[] DOC_FAMILIY = Bytes.toBytes("doc");
    public static final byte[] DOC_QUALIFIER = Bytes.toBytes("id");

}


text:
module Cabal2Nix.Generate ( cabal2nix, cabal2nix' ) where

import Cabal2Nix.Flags
import Cabal2Nix.License
import Cabal2Nix.Normalize
import Cabal2Nix.PostProcess
import Data.Maybe
import Distribution.Compiler
import Distribution.Nixpkgs.Haskell
import qualified Distribution.Package as Cabal
import qualified Distribution.PackageDescription as Cabal
import Distribution.PackageDescription.Configuration
import Distribution.System
import qualified Data.Set as Set

cabal2nix :: Cabal.FlagAssignment -> Cabal.GenericPackageDescription -> Derivation
cabal2nix flags' cabal = drv { cabalFlags = flags }
  where drv = cabal2nix' descr
        flags = normalizeCabalFlags (flags' ++ configureCabalFlags (Cabal.package (Cabal.packageDescription cabal)))
        Right (descr, _) = finalizePackageDescription
                            flags
                            (const True)
                            (Platform X86_64 Linux)                 -- shouldn't be hardcoded
                            (unknownCompilerInfo (CompilerId GHC (Version [7,10,1] [])) NoAbiTag)
                            []
                            cabal

cabal2nix' :: Cabal.PackageDescription -> Derivation
cabal2nix' tpkg = normalize $ postProcess $ normalize MkDerivation
  { pname          = let Cabal.PackageName x = Cabal.pkgName pkg in x
  , version        = Cabal.pkgVersion pkg
  , revision       = maybe 0 read (lookup "x-revision" xfields)
  , src            = error "cabal2nix left the src field undefined"
  , isLibrary      = isJust (Cabal.library tpkg)
  , isExecutable   = not (null (Cabal.executables tpkg))
  , extraFunctionArgs = Set.empty
  , buildDepends   = Set.fromList $ map unDep deps
  , testDepends    = Set.fromList $ map unDep tstDeps ++ concatMap Cabal.extraLibs tests
  , buildTools     = Set.fromList $ map unDep tools
  , extraLibs      = Set.fromList libs
  , pkgConfDeps    = Set.fromList pcs
  , configureFlags = Set.empty
  , cabalFlags     = configureCabalFlags pkg
  , runHaddock     = True
  , jailbreak      = False
  , doCheck        = True
  , testTarget     = ""
  , hyperlinkSource = True
  , enableSplitObjs = True
  , phaseOverrides = ""
  , editedCabalFile= if isJust (lookup "x-revision" xfields) then fromJust (lookup "x-cabal-file-hash" xfields) else ""
  , metaSection    = Meta
                   { homepage       = Cabal.homepage tpkg
                   , description    = Cabal.synopsis tpkg
                   , license        = fromCabalLicense (Cabal.license tpkg)
                   , platforms      = Set.empty
                   , hydraPlatforms = Set.empty
                   , maintainers    = Set.empty
                   , broken         = False
                   }
  }
  where
    xfields = Cabal.customFieldsPD tpkg
    pkg     = Cabal.package tpkg
    deps    = Cabal.buildDepends tpkg
    tests   = map Cabal.testBuildInfo (Cabal.testSuites tpkg)
    libDeps = map Cabal.libBuildInfo (maybeToList (Cabal.library tpkg))
    exeDeps = map Cabal.buildInfo (Cabal.executables tpkg)
    tstDeps = concatMap Cabal.buildTools tests ++ concatMap Cabal.pkgconfigDepends tests ++
              concatMap Cabal.targetBuildDepends tests
    tools   = concatMap Cabal.buildTools (libDeps ++ exeDeps)
    libs    = concatMap Cabal.extraLibs (libDeps ++ exeDeps)
    pcs     = map unDep (concatMap Cabal.pkgconfigDepends (libDeps ++ exeDeps))

unDep :: Cabal.Dependency -> String
unDep (Cabal.Dependency (Cabal.PackageName x) _) = x


text:
StatusIconWin::StatusIconWin(StatusTrayWin* tray,
                             UINT id,
                             HWND window,
                             UINT message)
    : tray_(tray), icon_id_(id), window_(window), message_id_(message) {
  NOTIFYICONDATA icon_data;
  InitIconData(&icon_data);
  icon_data.uFlags = NIF_MESSAGE;
  icon_data.uCallbackMessage = message_id_;
  BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
  // This can happen if the explorer process isn't running when we try to
  // create the icon for some reason (for example, at startup).
  if (!result)
    LOG(WARNING) << "Unable to create status tray icon.";
}

StatusIconWin::~StatusIconWin() {
  // Remove our icon.
  NOTIFYICONDATA icon_data;
  InitIconData(&icon_data);
  Shell_NotifyIcon(NIM_DELETE, &icon_data);
}

void StatusIconWin::HandleClickEvent(const gfx::Point& cursor_pos,
                                     bool left_mouse_click) {
  // Pass to the observer if appropriate.
  if (left_mouse_click && HasObservers()) {
    DispatchClickEvent();
    return;
  }

  if (!menu_model_)
    return;

  // Set our window as the foreground window, so the context menu closes when
  // we click away from it.
  if (!SetForegroundWindow(window_))
    return;

  menu_runner_ = std::make_unique<views::MenuRunner>(
      menu_model_, views::MenuRunner::HAS_MNEMONICS);
  menu_runner_->RunMenuAt(nullptr, nullptr, gfx::Rect(cursor_pos, gfx::Size()),
                          views::MenuAnchorPosition::kTopLeft,
                          ui::MENU_SOURCE_MOUSE);
}

void StatusIconWin::HandleBalloonClickEvent() {
  if (HasObservers())
    DispatchBalloonClickEvent();
}

void StatusIconWin::ResetIcon() {
  NOTIFYICONDATA icon_data;
  InitIconData(&icon_data);
  // Delete any previously existing icon.
  Shell_NotifyIcon(NIM_DELETE, &icon_data);
  InitIconData(&icon_data);
  icon_data.uFlags = NIF_MESSAGE;
  icon_data.uCallbackMessage = message_id_;
  icon_data.hIcon = icon_.get();
  // If we have an image, then set the NIF_ICON flag, which tells
  // Shell_NotifyIcon() to set the image for the status icon it creates.
  if (icon_data.hIcon)
    icon_data.uFlags |= NIF_ICON;
  // Re-add our icon.
  BOOL result = Shell_NotifyIcon(NIM_ADD, &icon_data);
  if (!result)
    LOG(WARNING) << "Unable to re-create status tray icon.";
}

void StatusIconWin::SetImage(const gfx::ImageSkia& image) {
  // Create the icon.
  NOTIFYICONDATA icon_data;
  InitIconData(&icon_data);
  icon_data.uFlags = NIF_ICON;
  icon_ = IconUtil::CreateHICONFromSkBitmap(*image.bitmap());
  icon_data.hIcon = icon_.get();
  BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
  if (!result)
    LOG(WARNING) << "Error setting status tray icon image";
}

void StatusIconWin::SetToolTip(const std::u16string& tool_tip) {
  // Create the icon.
  NOTIFYICONDATA icon_data;
  InitIconData(&icon_data);
  icon_data.uFlags = NIF_TIP;
  wcscpy_s(icon_data.szTip, base::as_wcstr(tool_tip));
  BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
  if (!result)
    LOG(WARNING) << "Unable to set tooltip for status tray icon";
}

void StatusIconWin::DisplayBalloon(
    const gfx::ImageSkia& icon,
    const std::u16string& title,
    const std::u16string& contents,
    const message_center::NotifierId& notifier_id) {
  NOTIFYICONDATA icon_data;
  InitIconData(&icon_data);
  icon_data.uFlags = NIF_INFO;
  icon_data.dwInfoFlags = NIIF_INFO;
  wcscpy_s(icon_data.szInfoTitle, base::as_wcstr(title));
  wcscpy_s(icon_data.szInfo, base::as_wcstr(contents));
  icon_data.uTimeout = 0;

  if (!icon.isNull()) {
    balloon_icon_ = IconUtil::CreateHICONFromSkBitmap(*icon.bitmap());
    icon_data.hBalloonIcon = balloon_icon_.get();
    icon_data.dwInfoFlags = NIIF_USER | NIIF_LARGE_ICON;
  }

  BOOL result = Shell_NotifyIcon(NIM_MODIFY, &icon_data);
  if (!result)
    LOG(WARNING) << "Unable to create status tray balloon.";
}

void StatusIconWin::ForceVisible() {
  tray_->UpdateIconVisibilityInBackground(this);
}

////////////////////////////////////////////////////////////////////////////////
// StatusIconWin, private:

void StatusIconWin::UpdatePlatformContextMenu(StatusIconMenuModel* menu) {
  // |menu_model_| is about to be destroyed. Destroy the menu (which closes it)
  // so that it doesn't attempt to continue using |menu_model_|.
  menu_runner_.reset();
  DCHECK(menu);
  menu_model_ = menu;
}

void StatusIconWin::InitIconData(NOTIFYICONDATA* icon_data) {
  memset(icon_data, 0, sizeof(NOTIFYICONDATA));
  icon_data->cbSize = sizeof(NOTIFYICONDATA);

  icon_data->hWnd = window_;
  icon_data->uID = icon_id_;
}


text:
package main

import (
	"fmt"
	"log"
	"strconv"
	"strings"

	"github.com/evalphobia/adventofcode/lib"
)

func main() {
	lib.ParseFlag()

	value := lib.GetValue()
	if value == "" {
		log.Fatal("cannot get value")
	}

	switch {
	case lib.GetPart() == 2:
		runPart2(value)
	default:
		runPart1(value)
	}
}

func runPart1(value string) {
	result := solvePart1(value)
	fmt.Printf("Answer: %d\n", result)
}

func solvePart1(val string) int {
	lines := strings.Split(val, "\n")
	var literalCount, memoryCount int
	for _, line := range lines {
		literalCount += len(line)
		memoryCount += getInMemoryCount(line)
	}
	return literalCount - memoryCount
}

func runPart2(value string) {
	result := solvePart2(value)
	fmt.Printf("Answer: %d\n", result)
}

func solvePart2(val string) int {
	lines := strings.Split(val, "\n")
	var literalCount, escapedCount int
	for _, line := range lines {
		literalCount += len(line)
		escapedCount += getEscapedCount(line)
	}
	return escapedCount - literalCount
}

func getInMemoryCount(text string) int {
	converted, err := strconv.Unquote(text)
	if err != nil {
		log.Fatal("cannot convert text: %s, error=%s", text, err.Error())
	}
	return len(converted)
}

func getEscapedCount(text string) int {
	converted := strconv.Quote(text)
	return len(converted)
}


text:
.list-inline {
  list-style: none;
}

.list-inline > li {
  display: inline-block;
  padding-left: 5px;
  padding-right: 5px;
}


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

<title>SQLite Release 3.6.7 On 2008 Dec 16 (3.6.7)</title>

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

Small. Fast. Reliable.
Choose any three.

    About
    Sitemap
    Documentation
    Download
    License
    News
    Developers
    Support

SQLite Release 3.6.7 On 2008 Dec 16 (3.6.7)

Changes associated with this release include the following:

Reorganize the Unix interface in os_unix.c

Added support for "Proxy Locking" on MacOSX.

Changed the prototype of the sqlite3_auto_extension() interface in a
    way that is backwards compatible but which might cause warnings in new
    builds of applications that use that interface.

Changed the signature of the xDlSym method of the sqlite3_vfs object
    in a way that is backwards compatible but which might cause
    compiler warnings.

Added superfluous casts and variable initializations in order
    to suppress nuisance compiler warnings.

Fixes for various minor bugs.

A complete list of SQLite releases
      in a single pages is also available.  A detailed history of every
      check-in is available at

      http://www.sqlite.org/cvstrac/timeline.

This page last modified 2009/05/06 15:52:25 UTC


text:
package ca.uhn.fhir.jpa.cache;

import ca.uhn.fhir.jpa.model.sched.HapiJob;
import ca.uhn.fhir.jpa.model.sched.ISchedulerService;
import ca.uhn.fhir.jpa.model.sched.ScheduledJobDefinition;
import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
import com.google.common.annotations.VisibleForTesting;
import org.apache.commons.lang3.time.DateUtils;
import org.hl7.fhir.instance.model.api.IIdType;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * This service refreshes the {@link IResourceChangeListenerCache} caches and notifies their listener when
 * those caches change.
 *
 * Think of it like a Ferris Wheel that completes a full rotation once every 10 seconds.
 * Every time a chair passes the bottom it checks to see if it's time to refresh that seat.  If so,
 * the Ferris Wheel stops, removes the riders, and loads a fresh cache for that chair, and calls the listener
 * if any entries in the new cache are different from the last time that cache was loaded.
 */
@Service
public class ResourceChangeListenerCacheRefresherImpl implements IResourceChangeListenerCacheRefresher {
	private static final Logger ourLog = LoggerFactory.getLogger(ResourceChangeListenerCacheRefresherImpl.class);

	/**
	 * All cache entries are checked at this interval to see if they need to be refreshed
	 */
	static long LOCAL_REFRESH_INTERVAL_MS = 10 * DateUtils.MILLIS_PER_SECOND;

	@Autowired
	private ISchedulerService mySchedulerService;
	@Autowired
	private IResourceVersionSvc myResourceVersionSvc;
	@Autowired
	private ResourceChangeListenerRegistryImpl myResourceChangeListenerRegistry;

	@PostConstruct
	public void start() {
		ScheduledJobDefinition jobDetail = new ScheduledJobDefinition();
		jobDetail.setId(getClass().getName());
		jobDetail.setJobClass(Job.class);
		mySchedulerService.scheduleLocalJob(LOCAL_REFRESH_INTERVAL_MS, jobDetail);
	}

	public static class Job implements HapiJob {
		@Autowired
		private IResourceChangeListenerCacheRefresher myTarget;

		@Override
		public void execute(JobExecutionContext theContext) {
			myTarget.refreshExpiredCachesAndNotifyListeners();
		}
	}

	@Override
	public ResourceChangeResult refreshExpiredCachesAndNotifyListeners() {
		ResourceChangeResult retval = new ResourceChangeResult();
		Iterator<ResourceChangeListenerCache> iterator = myResourceChangeListenerRegistry.iterator();
		while (iterator.hasNext()) {
			ResourceChangeListenerCache entry = iterator.next();
			retval = retval.plus(entry.refreshCacheIfNecessary());
		}
		return retval;
	}

	@VisibleForTesting
	public ResourceChangeResult forceRefreshAllCachesForUnitTest() {
		ResourceChangeResult retval = new ResourceChangeResult();
		Iterator<ResourceChangeListenerCache> iterator = myResourceChangeListenerRegistry.iterator();
		while (iterator.hasNext()) {
			IResourceChangeListenerCache entry = iterator.next();
			retval = retval.plus(entry.forceRefresh());
		}
		return retval;
	}

	@VisibleForTesting
	public void setSchedulerService(ISchedulerService theSchedulerService) {
		mySchedulerService = theSchedulerService;
	}

	@VisibleForTesting
	public void setResourceChangeListenerRegistry(ResourceChangeListenerRegistryImpl theResourceChangeListenerRegistry) {
		myResourceChangeListenerRegistry = theResourceChangeListenerRegistry;
	}

	@VisibleForTesting
	public void setResourceVersionSvc(IResourceVersionSvc theResourceVersionSvc) {
		myResourceVersionSvc = theResourceVersionSvc;
	}

	@Override
	public ResourceChangeResult refreshCacheAndNotifyListener(IResourceChangeListenerCache theCache) {
		ResourceChangeResult retVal = new ResourceChangeResult();
		if (mySchedulerService.isStopping()) {
			ourLog.info("Scheduler service is stopping, aborting cache refresh");
			return retVal;
		}
		if (!myResourceChangeListenerRegistry.contains(theCache)) {
			ourLog.warn("Requesting cache refresh for unregistered listener {}.  Aborting.", theCache);
			return retVal;
		}
		SearchParameterMap searchParamMap = theCache.getSearchParameterMap();
		ResourceVersionMap newResourceVersionMap = myResourceVersionSvc.getVersionMap(theCache.getResourceName(), searchParamMap);
		retVal = retVal.plus(notifyListener(theCache, newResourceVersionMap));

		return retVal;
	}

	/**
	 * Notify a listener with all matching resources if it hasn't been initialized yet, otherwise only notify it if
	 * any resources have changed
	 * @param theCache
	 * @param theNewResourceVersionMap the measured new resources
	 * @return the list of created, updated and deleted ids
	 */
	ResourceChangeResult notifyListener(IResourceChangeListenerCache theCache, ResourceVersionMap theNewResourceVersionMap) {
		ResourceChangeResult retval;
		ResourceChangeListenerCache cache = (ResourceChangeListenerCache) theCache;
		IResourceChangeListener resourceChangeListener = cache.getResourceChangeListener();
		if (theCache.isInitialized()) {
			retval = compareLastVersionMapToNewVersionMapAndNotifyListenerOfChanges(resourceChangeListener, cache.getResourceVersionCache(), theNewResourceVersionMap);
		} else {
			cache.getResourceVersionCache().initialize(theNewResourceVersionMap);
			resourceChangeListener.handleInit(theNewResourceVersionMap.getSourceIds());
			retval = ResourceChangeResult.fromCreated(theNewResourceVersionMap.size());
			cache.setInitialized(true);
		}
		return retval;
	}

	private ResourceChangeResult compareLastVersionMapToNewVersionMapAndNotifyListenerOfChanges(IResourceChangeListener theListener, ResourceVersionCache theOldResourceVersionCache, ResourceVersionMap theNewResourceVersionMap) {
		// If the new ResourceVersionMap does not have the old key - delete it
		List<IIdType> deletedIds = new ArrayList<>();
		theOldResourceVersionCache.keySet()
			.forEach(id -> {
				if (!theNewResourceVersionMap.containsKey(id)) {
					deletedIds.add(id);
				}
			});
		deletedIds.forEach(theOldResourceVersionCache::removeResourceId);

		List<IIdType> createdIds = new ArrayList<>();
		List<IIdType> updatedIds = new ArrayList<>();

		for (IIdType id : theNewResourceVersionMap.keySet()) {
			Long previousValue = theOldResourceVersionCache.put(id, theNewResourceVersionMap.get(id));
			IIdType newId = id.withVersion(theNewResourceVersionMap.get(id).toString());
			if (previousValue == null) {
				createdIds.add(newId);
			} else if (!theNewResourceVersionMap.get(id).equals(previousValue)) {
				updatedIds.add(newId);
			}
		}

		IResourceChangeEvent resourceChangeEvent = ResourceChangeEvent.fromCreatedUpdatedDeletedResourceIds(createdIds, updatedIds, deletedIds);
		if (!resourceChangeEvent.isEmpty()) {
			theListener.handleChange(resourceChangeEvent);
		}
		return ResourceChangeResult.fromResourceChangeEvent(resourceChangeEvent);
	}
}


text:
'use strict';

var Firebase = require('firebase');

var transitRef = new Firebase('https://publicdata-transit.firebaseio.com/');

/**
* Get the public transportation route vehicles
*/
function transitLine(line) {
  line = line || 'lametro-rail';
  return transitRef.child(line + '/vehicles');
}

/**
* When user selects new location we
* need to grab new firebase feed
*/
function updateTransitLine(line) {
  return transitRef.child(line + '/vehicles');
}

module.exports = {
  transitLine: transitLine,
  updateTransitLine: updateTransitLine
}


text:
package matrix4j.core;

import java.util.Arrays;

public class Vector {
    private double[] vector;

    //'no copying' as default
    public Vector(double[] vector) {
        this(vector, false);
    }

    //create the vector object
    //copy: whether copying given array
    public Vector(double[] vector, boolean copy) {
        if(!copy) {
            this.vector = vector;
            return;
        }

        this.vector = ArrayUtils.copy(vector);
    }

    //create an empty vector
    public Vector(int length) {
        this.vector = new double[length];
    }

    //copy the self object
    public Vector copy() {
        return new Vector(this.vector, true);
    }

    //Returns the elements of self as an array
    public double[] toArray() {
        return ArrayUtils.copy(this.vector);
    }

    //the number of elements
    public int length() {
        return this.vector.length;
    }

    public double max() {
        if(this.length() == 0) {
            throw new IllegalArgumentException(
                "Max for an empty vector can not be defined.");
        }

        double max = Double.NEGATIVE_INFINITY;
        for(double e: this.vector) {
            if(e > max) {
                max = e;
            }
        }
        return max;
    }

    public int argmax() {
        if(this.length() == 0) {
            throw new IllegalArgumentException(
                "Argmax for an empty vector can not be defined.");
        }

        double max = Double.NEGATIVE_INFINITY;
        int argmax = 0;
        for(int i = 0; i < this.length(); i++) {
            double e = this.get(i);
            if(e > max) {
                argmax = i;
                max = e;
            }
        }
        return argmax;
    }

    public Vector abs() {
        int length = this.length();
        double[] abs = new double[length];
        for(int i = 0; i < length; i++) {
            abs[i] = java.lang.Math.abs(this.get(i));
        }
        return new Vector(abs);
    }

    public Vector slice(int begin, int end) {
        throwExceptionIfRangeOutOfBounds(begin, end);
        double[] sliced = Arrays.copyOfRange(this.vector, begin, end);
        return new Vector(sliced);
    }

    public double sum() {
        double s = 0;
        for(double e: this.vector) {
            s += e;
        }
        return s;
    }

    private void throwExceptionIfRangeOutOfBounds(int begin, int end) {
        if(begin < 0 || this.length() < end) {
            throw new IndexOutOfBoundsException(
                String.format("Range [%d, %d) is out of bounds.", begin, end));
        }
    }
    //throw an exception if either of indices is out of bounds
    private void throwExceptionIfIndexOutOfBounds(int index) {
        int length = this.length();
        if(index < 0 || length <= index) {
            throw new IndexOutOfBoundsException(
                String.format(
                    "Index %d is out of bounds for vector with length %d.",
                    length, length));
        }
    }

    //return an element at index
    public double get(int index) {
        throwExceptionIfIndexOutOfBounds(index);
        return this.vector[index];
    }

    // set element at index
    public void set(int index, double e) {
        throwExceptionIfIndexOutOfBounds(index);
        this.vector[index] = e;
    }

    public String toString() {
        int n = this.length();

        if(n == 0) {
            return "[]";
        }

        String s = "[";
        for(int i = 0; i < n-1; i++) {
            s += String.format("% 7.3f ", this.get(i));
        }
        s += String.format("% 7.3f]", this.get(n-1));
        return s;
    }

    //regard the given matrix same as self if it satisfies:
    //  another object has the same number of elements
    //  all elements are same as self's ones
    public boolean equals(Vector another) {
        if(this.length() != another.length()) {
            return false;
        }

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

            //casting into float for avoiding the rouding error
            float a = (float)this.get(i);
            float b = (float)another.get(i);
            if(a != b) {
                return false;
            }
        }
        return true;
    }
}


text:
'use strict';

var assert = require('assert');
var formatError = require('graphql/error').formatError;
var RelayQLPrinter = require('./RelayQLPrinter');
var parser = require('graphql/language/parser');
var Source = require('graphql/language/source').Source;
var validate = require('graphql/validation/validate').validate;
var util = require('util');

function RelayQLTransformer(schema /*: GraphQLSchema */) {
  this.schema = schema;
}

RelayQLTransformer.prototype.transformQuery = function(
  queryAndSubstitutions,
  documentName, /*: string */
  tagName /*: string */
) /*: string */ {
  var queryDocument =
    this.parseDocument(queryAndSubstitutions.text, documentName);
  var printer = new RelayQLPrinter(this.schema, tagName);
  return printer.getCode(queryDocument, queryAndSubstitutions.substitutions);
};

RelayQLTransformer.prototype.parseDocument = function(
  query, /*: string */
  documentName /*: string */
) /*: string */ {
  var match = /^(fragment|mutation|query)\s*(\w*)?([\s\S]*)/.exec(query)
  assert(
    match,
    util.format(
      'GraphQL: expected query `%s...` to start with a document type. ' +
      'Specify `fragment`, `mutation`, or `query`.',
      query.substr(0, 20)
    )
  );
  var type = match[1];
  var name = match[2] || documentName;
  var rest = match[3];

  if (type === 'fragment' && name === 'on') {
    // Allow `fragment on User {...}`
    rest = 'on' + rest;
    name = documentName;
  }

  name = this.getName(name);
  var queryText = type + ' ' + name + ' ' + rest;
  return parse(type, queryText, this.schema).definitions[0];
};

RelayQLTransformer.prototype.getName = function(
  documentName /*: string */
) /*: string */ {
  if (!documentName || !documentName.length) {
    throw new Error('RelayQLTransformer: expected document to have a name.');
  }
  return documentName[0].toUpperCase() + documentName.slice(1);
};

/**
 * Parses a query document into an AST, returning the AST plus any validation
 * errors.
 */
function parse(
  type, /*: string */
  text, /*: string */
  schema /*: GraphQLSchema */
) /*: any */ {
  var source = new Source(text, 'GraphQL Document');
  var documentAST = parser.parse(source);
  var rules = [
    require(
      'graphql/validation/rules/ArgumentsOfCorrectType'
    ).ArgumentsOfCorrectType,
    require(
      'graphql/validation/rules/DefaultValuesOfCorrectType'
    ).DefaultValuesOfCorrectType,
    require(
      'graphql/validation/rules/FieldsOnCorrectType'
    ).FieldsOnCorrectType,
    require(
      'graphql/validation/rules/FragmentsOnCompositeTypes'
    ).FragmentsOnCompositeTypes,
    require(
      'graphql/validation/rules/KnownArgumentNames'
    ).KnownArgumentNames,
    require(
      'graphql/validation/rules/KnownTypeNames'
    ).KnownTypeNames,
    require(
      'graphql/validation/rules/PossibleFragmentSpreads'
    ).PossibleFragmentSpreads,
    require(
      'graphql/validation/rules/PossibleFragmentSpreads'
    ).PossibleFragmentSpreads,
    require(
      'graphql/validation/rules/VariablesInAllowedPosition'
    ).VariablesInAllowedPosition,
  ];
  if (type !== 'mutation') {
    rules.push(
      require(
        'graphql/validation/rules/ProvidedNonNullArguments'
      ).ProvidedNonNullArguments
    );
  }
  var validationErrors = validate(schema, documentAST, rules);
  if (validationErrors && validationErrors.length > 0) {
    validationErrors = validationErrors.map(formatError);
    var error = new Error('This document is invalid');
    error.validationErrors = validationErrors;
    error.sourceText = text;
    throw error;
  }
  return documentAST;
}

module.exports = RelayQLTransformer;