text:
package drt.shared

import upickle.default._

case class FeatureFlags(useApiPaxNos: Boolean,
                        displayWaitTimesToggle: Boolean,
                        displayRedListInfo: Boolean)

object FeatureFlags {
  implicit val rw: ReadWriter[FeatureFlags] = macroRW
}

redpajama_set_name: RedPajamaGithub


text:
from datetime import date

from flask import render_template as flask_render_template
from conditional.models.models import EvalSettings

from conditional.util.ldap import ldap_is_active
from conditional.util.ldap import ldap_is_alumni
from conditional.util.ldap import ldap_is_eboard
from conditional.util.ldap import ldap_is_financial_director
from conditional.util.ldap import ldap_is_eval_director
from conditional.util.ldap import ldap_is_intromember
from conditional.util.ldap import ldap_is_rtp
from conditional.util.ldap import ldap_get_member

from conditional.models.models import CommitteeMeeting
from conditional.models.models import TechnicalSeminar

from conditional import db

def render_template(request, template_name, **kwargs):
    user_name = request.headers.get('x-webauth-user')

    # TODO maybe use the webauth request decorator

    if EvalSettings.query.first() is None:
        db.session.add(EvalSettings())
        db.session.flush()
        db.session.commit()
    account = ldap_get_member(user_name)
    lockdown = EvalSettings.query.first().site_lockdown
    accepting_dues = EvalSettings.query.first().accept_dues_until > date.today()
    is_active = ldap_is_active(account)
    is_alumni = ldap_is_alumni(account)
    is_eboard = ldap_is_eboard(account)
    is_financial = ldap_is_financial_director(account)
    is_eval = ldap_is_eval_director(account)
    is_intromember = ldap_is_intromember(account)
    is_rtp = ldap_is_rtp(account)

    cm_review = len(CommitteeMeeting.query.filter(
        CommitteeMeeting.approved == False).all()) # pylint: disable=singleton-comparison
    ts_review = len(TechnicalSeminar.query.filter(
        TechnicalSeminar.approved == False).all()) # pylint: disable=singleton-comparison

    if is_eboard:
        lockdown = False

    return flask_render_template(
        template_name,
        lockdown=lockdown,
        accepting_dues=accepting_dues,
        is_active=is_active,
        is_alumni=is_alumni,
        is_eboard=is_eboard,
        is_eval_director=is_eval,
        is_financial_director=is_financial,
        is_intromember=is_intromember,
        is_rtp=is_rtp,
        pending_review=(cm_review + ts_review),
        **kwargs)


text:
<?xml version="1.0" encoding="UTF-8"?>
<config>
	<attribute name="name" value="Elementary"/>
	<attribute name="description" value="Elementary OS theme"/>
</config>


text:
package cbs

import (
	"os"

	"github.com/dbdd4us/qcloudapi-sdk-go/common"
)

const (
	CbsHost = "cbs.api.qcloud.com"
	CbsPath = "/v2/index.php"
)

type Client struct {
	*common.Client
}

func NewClient(credential common.CredentialInterface, opts common.Opts) (*Client, error) {
	if opts.Host == "" {
		opts.Host = CbsHost
	}
	if opts.Path == "" {
		opts.Path = CbsPath
	}

	client, err := common.NewClient(credential, opts)
	if err != nil {
		return &Client{}, err
	}
	return &Client{client}, nil
}

func NewClientFromEnv() (*Client, error) {

	secretId := os.Getenv("QCloudSecretId")
	secretKey := os.Getenv("QCloudSecretKey")
	region := os.Getenv("QCloudCbsAPIRegion")
	host := os.Getenv("QCloudCbsAPIHost")
	path := os.Getenv("QCloudCbsAPIPath")

	return NewClient(
		common.Credential{
			secretId,
			secretKey,
		},
		common.Opts{
			Region: region,
			Host:   host,
			Path:   path,
		},
	)
}


text:
// This file is automatically generated.

package adila.db;

/*
 * Lenovo A2105
 *
 * DEVICE: Lenovo_A2105
 * MODEL: Lenovo_A2105
 */
final class lenovo5fa2105_lenovo5fa2105 {
    public static final String DATA = "Lenovo|A2105|";
}


text:
var $ = require('jquery');
var _ = require('underscore');
var Vue = require('vue');
require('retina.js');
// modernizr tests
require('browsernizr/test/svg');
var Modernizr = require('browsernizr');
require('./modules/fontawesome-fallback.js');
// enable hack when bootstrap functions are required
//window.jQuery = $;
//window.$ = $;
//require('bootstrap');

console.log('start hacking!');


text:
from .convolution import CFConv
from .dense import Dense
from .embedding import Embedding
from .pooling import PoolSegments
from .rbf import RBFExpansion
from .module import Module
from .distances import EuclideanDistances


text:
"""
WSGI config for hopeblog project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "hopeblog.settings")

application = get_wsgi_application()


text:
MainVisitor::MainVisitor(
        CompilerInstance& compilerInstance, ASTContext& context, bool fix)
    : _compilerInstance(compilerInstance), _context(context),
     _fix(fix), _fixed(false), _barrierTypeDefined(false)
{
    if (_fix)
    {
        _rewriter.setSourceMgr(compilerInstance.getSourceManager(),
                               compilerInstance.getLangOpts());
    }
}

bool MainVisitor::VisitCXXRecordDecl(CXXRecordDecl* recordDecl)
{
    if (Log::GetLevel() < Log::LogLevel::Info)
    {
        return true; // At least Info level, otherwise this not needed
    }

    std::string typeName = recordDecl->getQualifiedNameAsString();

    // Ignore (system/non-GC types) before seeing "Memory::NoWriteBarrierField"
    if (!_barrierTypeDefined)
    {
        if (typeName != "Memory::NoWriteBarrierField")
        {
            return true;
        }

        _barrierTypeDefined = true;
    }

    if (!recordDecl->hasDefinition())
    {
        return true;
    }

    bool hasUnbarrieredPointer = false;
    bool hasBarrieredField = false;

    for (auto field : recordDecl->fields())
    {
        const QualType qualType = field->getType();
        const Type* type = qualType.getTypePtr();

        auto fieldTypeName = qualType.getAsString();
        if (StartsWith(fieldTypeName, "typename WriteBarrierFieldTypeTraits") ||
            StartsWith(fieldTypeName, "const typename WriteBarrierFieldTypeTraits"))
        {
            // Note this only indicates the class is write-barrier annotated
            hasBarrieredField = true;
        }
        else if (type->isPointerType())
        {
            hasUnbarrieredPointer = true;
        }
        else if (type->isCompoundType())
        {
            // If the field is a compound type,
            // check if it is a fully barriered type or
            // has unprotected pointer fields
            if (Contains(_pointerClasses, fieldTypeName))
            {
                hasUnbarrieredPointer = true;
            }
            else if (Contains(_barrieredClasses, fieldTypeName))
            {
                hasBarrieredField = true;
            }
        }
    }

    if (hasUnbarrieredPointer)
    {
        _pointerClasses.insert(typeName);
    }
    else if (hasBarrieredField)
    {
        _barrieredClasses.insert(typeName);
    }

    return true;
}

template <class PushFieldType>
void MainVisitor::ProcessUnbarrieredFields(
    CXXRecordDecl* recordDecl, const PushFieldType& pushFieldType)
{
    std::string typeName = recordDecl->getQualifiedNameAsString();
    if (typeName == "Memory::WriteBarrierPtr")
    {
        return;  // Skip WriteBarrierPtr itself
    }

    const auto& sourceMgr = _compilerInstance.getSourceManager();
    DiagnosticsEngine& diagEngine = _context.getDiagnostics();
    const unsigned diagID = diagEngine.getCustomDiagID(
        DiagnosticsEngine::Error,
        "Unbarriered field, see "
        "https://github.com/microsoft/ChakraCore/wiki/Software-Write-Barrier#coding-rules");

    for (auto field : recordDecl->fields())
    {
        const QualType qualType = field->getType();
        string fieldTypeName = qualType.getAsString();
        string fieldName = field->getNameAsString();

        if (StartsWith(fieldTypeName, "WriteBarrierPtr<") || // WriteBarrierPtr fields
            Contains(fieldTypeName, "_no_write_barrier_policy, ")) // FieldNoBarrier
        {
            continue; // skip
        }

        // If an annotated field type is struct/class/union (RecordType), the
        // field type in turn should likely be annoatated.
        if (fieldTypeName.back() != '*'  // not "... *"
            &&
            (
                StartsWith(fieldTypeName, "typename WriteBarrierFieldTypeTraits") ||
                StartsWith(fieldTypeName, "WriteBarrierFieldTypeTraits") ||
                StartsWith(fieldTypeName, "const typename WriteBarrierFieldTypeTraits") ||
                StartsWith(fieldTypeName, "const WriteBarrierFieldTypeTraits") ||
                fieldName.length() == 0  // anonymous union/struct
            ))
        {
            auto originalType = qualType->getUnqualifiedDesugaredType();
            if (auto arrayType = dyn_cast<ArrayType>(originalType))
            {
                originalType = arrayType->getElementType()->getUnqualifiedDesugaredType();
            }

            string originalTypeName = QualType(originalType, 0).getAsString();
            if (isa<RecordType>(originalType) &&
                !StartsWith(originalTypeName, "class Memory::WriteBarrierPtr<"))
            {
                if (pushFieldType(originalType))
                {
                    Log::outs() << "Queue field type: " << originalTypeName
                        << " (" << typeName << "::" << fieldName << ")\n";
                }
            }
        }
        else
        {
            SourceLocation location = field->getLocStart();
            if (this->_fix)
            {
                const char* begin = sourceMgr.getCharacterData(location);
                const char* end = begin;

                if (MatchType(fieldTypeName, begin, &end))
                {
                    _rewriter.ReplaceText(
                        location, end - begin,
                        GetFieldTypeAnnotation(qualType) + string(begin, end) +
                             (*end == ' ' ? ")" : ") "));
                    _fixed = true;
                    continue;
                }

                Log::errs() << "Fail to fix: " << fieldTypeName << " "
                            << fieldName << "\n";
            }

            diagEngine.Report(location, diagID);
        }
    }
}

static bool SkipSpace(const char*& p)
{
    if (*p == ' ')
    {
        ++p;
        return true;
    }

    return false;
}

template <size_t N>
static bool SkipPrefix(const char*& p, const char (&prefix)[N])
{
    if (StartsWith(p, prefix))
    {
        p += N - 1; // skip
        return true;
    }

    return false;
}

static bool SkipPrefix(const char*& p, const string& prefix)
{
    if (StartsWith(p, prefix))
    {
        p += prefix.length(); // skip
        return true;
    }

    return false;
}

static bool SkipTemplateParameters(const char*& p)
{
    if (*p == '<')
    {
        ++p;
        int left = 1;

        while (left && *p)
        {
            switch (*p++)
            {
                case '<': ++left; break;
                case '>': --left; break;
            }
        }

        return true;
    }

    return false;
}

bool MainVisitor::MatchType(const string& type, const char* source, const char** pSourceEnd)
{
    // try match type in source directly (clang "bool" type is "_Bool")
    if (SkipPrefix(source, type) || (type == "_Bool" && SkipPrefix(source, "bool")))
    {
        *pSourceEnd = source;
        return true;
    }

    const char* p = type.c_str();
    while (*p && *source)
    {
        if (SkipSpace(p) || SkipSpace(source))
        {
            continue;
        }

#define SKIP_EITHER_PREFIX(prefix) \
            (SkipPrefix(p, prefix) || SkipPrefix(source, prefix))
        if (SKIP_EITHER_PREFIX("const ") ||
            SKIP_EITHER_PREFIX("class ") ||
            SKIP_EITHER_PREFIX("struct ") ||
            SKIP_EITHER_PREFIX("union ") ||
            SKIP_EITHER_PREFIX("enum "))
        {
            continue;
        }
#undef SKIP_EITHER_PREFIX

        // type may contain [...] array specifier, while source has it after field name
        if (*p == '[')
        {
            while (*p && *p++ != ']');
            continue;
        }

        // skip <...> in both
        if (SkipTemplateParameters(p) || SkipTemplateParameters(source))
        {
            continue;
        }

        // type may contain fully qualified name but source may or may not
        const char* pSkipScopeType = strstr(p, "::");
        if (pSkipScopeType && !memchr(p, ' ', pSkipScopeType - p))
        {
            pSkipScopeType += 2;
            if (strncmp(source, p, pSkipScopeType - p) == 0)
            {
                source += pSkipScopeType - p;
            }
            p = pSkipScopeType;
            continue;
        }

        if (*p == *source)
        {
            while (*p && *source && *p == *source && !strchr("<>", *p))
            {
                ++p, ++source;
            }
            continue;
        }

        if (*p != *source)
        {
            return false;  // mismatch
        }
    }

    if (!*p && *source)  // type match completed and having remaining source
    {
        while (*(source - 1) == ' ') --source; // try to stop after a non-space char
        *pSourceEnd = source;
        return true;
    }

    return false;
}

const char* MainVisitor::GetFieldTypeAnnotation(QualType qtype)
{
    if (qtype->isPointerType())
    {
        auto type = qtype->getUnqualifiedDesugaredType()->getPointeeType().getTypePtr();
        const auto& i = _allocationTypes.find(type);
        if (i != _allocationTypes.end()
            && i->second == AllocationTypes::NonRecycler)
        {
            return "FieldNoBarrier(";
        }
    }

    return "Field(";
}

bool MainVisitor::VisitFunctionDecl(FunctionDecl* functionDecl)
{
    if (functionDecl->hasBody())
    {
        CheckAllocationsInFunctionVisitor visitor(this, functionDecl);

        visitor.TraverseDecl(functionDecl);
    }

    return true;
}

void MainVisitor::RecordAllocation(QualType qtype, AllocationTypes allocationType)
{
    auto type = qtype->getCanonicalTypeInternal().getTypePtr();
    _allocationTypes[type] |= allocationType;
}

void MainVisitor::RecordRecyclerAllocation(const string& allocationFunction, const string& type)
{
    _allocatorTypeMap[allocationFunction].insert(type);
}

template <class Set, class DumpItemFunc>
void MainVisitor::dump(const char* name, const Set& set, const DumpItemFunc& func)
{
    Log::outs() << "-------------------------\n\n";
    Log::outs() << name << "\n";
    Log::outs() << "-------------------------\n\n";
    for (auto item : set)
    {
        func(Log::outs(), item);
    }
    Log::outs() << "-------------------------\n\n";
}

template <class Item>
void MainVisitor::dump(const char* name, const set<Item>& set)
{
    dump(name, set, [](raw_ostream& out, const Item& item)
    {
        out << "  " << item << "\n";
    });
}

void MainVisitor::dump(const char* name, const unordered_set<const Type*> set)
{
    dump(name, set, [&](raw_ostream& out, const Type* type)
    {
        out << "  " << QualType(type, 0).getAsString() << "\n";
    });
}

void MainVisitor::Inspect()
{
#define Dump(coll) dump(#coll, _##coll)
    Dump(pointerClasses);
    Dump(barrieredClasses);

    Log::outs() << "Recycler allocations\n";
    for (auto item : _allocatorTypeMap)
    {
        dump(item.first.c_str(), item.second);
    }

    std::queue<const Type*> queue;  // queue of types to check
    std::unordered_set<const Type*> barrierTypes;  // set of types queued
    auto pushBarrierType = [&](const Type* type) -> bool
    {
        if (barrierTypes.insert(type).second)
        {
            queue.push(type);
            return true;
        }
        return false;
    };

    for (auto item : _allocationTypes)
    {
        if (item.second & AllocationTypes::WriteBarrier)
        {
            pushBarrierType(item.first);
        }
    }
    dump("WriteBarrier allocation types", barrierTypes);

    // Examine all barrierd types. They should be fully wb annotated.
    while (!queue.empty())
    {
        auto type = queue.front();
        queue.pop();

        auto r = type->getCanonicalTypeInternal()->getAsCXXRecordDecl();
        if (r)
        {
            auto typeName = r->getQualifiedNameAsString();
            ProcessUnbarrieredFields(r, pushBarrierType);

            // queue the type's base classes
            for (const auto& base: r->bases())
            {
                if (pushBarrierType(base.getType().getTypePtr()))
                {
                    Log::outs() << "Queue base type: " << base.getType().getAsString()
                        << " (base of " << typeName << ")\n";
                }
            }
        }
    }

#undef Dump
}

bool MainVisitor::ApplyFix()
{
    return _fixed ? _rewriter.overwriteChangedFiles() : false;
}

static AllocationTypes CheckAllocationType(const CXXStaticCastExpr* castNode)
{
    QualType targetType = castNode->getTypeAsWritten();
    if (const IdentifierInfo* info = targetType.getBaseTypeIdentifier())
    {
        return info->getName().equals("Recycler") ?
                AllocationTypes::Recycler : AllocationTypes::NonRecycler;
    }
    else
    {
        // Unknown template dependent allocator types
        return AllocationTypes::Unknown;
    }
}

template <class A0, class A1, class T>
void CheckAllocationsInFunctionVisitor::VisitAllocate(
    const A0& getArg0, const A1& getArg1, const T& getAllocType)
{
    const Expr* firstArgNode = getArg0();

    // Check if the first argument (to new or AllocateArray) is a static cast
    // AllocatorNew/AllocateArray in Chakra always does a static_cast to the AllocatorType
    const CXXStaticCastExpr* castNode = nullptr;
    if (firstArgNode != nullptr &&
        (castNode = dyn_cast<CXXStaticCastExpr>(firstArgNode)))
    {
        QualType allocatedType = getAllocType();
        string allocatedTypeStr = allocatedType.getAsString();

        auto allocationType = CheckAllocationType(castNode);
        if (allocationType == AllocationTypes::Recycler)  // Recycler allocation
        {
            const Expr* secondArgNode = getArg1();

            // Chakra has two types of allocating functions- throwing and non-throwing
            // However, recycler allocations are always throwing, so the second parameter
            // should be the address of the allocator function
            auto unaryNode = cast<UnaryOperator>(secondArgNode);
            if (unaryNode != nullptr && unaryNode->getOpcode() == UnaryOperatorKind::UO_AddrOf)
            {
                Expr* subExpr = unaryNode->getSubExpr();
                if (DeclRefExpr* declRef = cast<DeclRefExpr>(subExpr))
                {
                    auto declNameInfo = declRef->getNameInfo();
                    auto allocationFunctionStr = declNameInfo.getName().getAsString();
                    _mainVisitor->RecordRecyclerAllocation(allocationFunctionStr, allocatedTypeStr);

                    if (!Contains(allocationFunctionStr, "Leaf"))
                    {
                        // Recycler write barrier allocation -- unless "Leaf" in allocFunc
                        allocationType = AllocationTypes::RecyclerWriteBarrier;
                    }
                }
                else
                {
                    Log::errs() << "ERROR: (internal) Expected DeclRefExpr:\n";
                    subExpr->dump();
                }
            }
            else if (auto mExpr = cast<MaterializeTemporaryExpr>(secondArgNode))
            {
                auto name = mExpr->GetTemporaryExpr()->IgnoreImpCasts()->getType().getAsString();
                if (StartsWith(name, "InfoBitsWrapper<")) // && Contains(name, "WithBarrierBit"))
                {
                    // RecyclerNewEnumClass, RecyclerNewWithInfoBits -- always have WithBarrier varients
                    allocationType = AllocationTypes::RecyclerWriteBarrier;
                }
            }
            else
            {
                Log::errs() << "ERROR: (internal) Expected unary node or MaterializeTemporaryExpr:\n";
                secondArgNode->dump();
            }
        }

        if (allocationType & AllocationTypes::WriteBarrier)
        {
            Log::outs() << "In \"" << _functionDecl->getQualifiedNameAsString() << "\"\n";
            Log::outs() << "  Allocating \"" << allocatedTypeStr << "\" in write barriered memory\n";
        }

        _mainVisitor->RecordAllocation(allocatedType, allocationType);
    }
}

bool CheckAllocationsInFunctionVisitor::VisitCXXNewExpr(CXXNewExpr* newExpr)
{
    if (newExpr->getNumPlacementArgs() > 1)
    {
        VisitAllocate(
            [=]() { return newExpr->getPlacementArg(0); },
            [=]() { return newExpr->getPlacementArg(1); },
            [=]() { return newExpr->getAllocatedType(); }
        );
    }

    return true;
}

bool CheckAllocationsInFunctionVisitor::VisitCallExpr(CallExpr* callExpr)
{
    // Check callExpr for AllocateArray
    auto callee = callExpr->getDirectCallee();
    if (callExpr->getNumArgs() == 3 &&
        callee &&
        callee->getName().equals("AllocateArray"))
    {
        VisitAllocate(
            [=]() { return callExpr->getArg(0); },
            [=]() { return callExpr->getArg(1); },
            [=]()
            {
                auto retType = callExpr->getCallReturnType(_mainVisitor->getContext());
                return QualType(retType->getAs<PointerType>()->getPointeeType());
            }
        );
    }

    return true;
}

void RecyclerCheckerConsumer::HandleTranslationUnit(ASTContext& context)
{
    MainVisitor mainVisitor(_compilerInstance, context, _fix);
    mainVisitor.TraverseDecl(context.getTranslationUnitDecl());

    mainVisitor.Inspect();
    mainVisitor.ApplyFix();
}

std::unique_ptr<ASTConsumer> RecyclerCheckerAction::CreateASTConsumer(
    CompilerInstance& compilerInstance, llvm::StringRef)
{
    return llvm::make_unique<RecyclerCheckerConsumer>(compilerInstance, _fix);
}

bool RecyclerCheckerAction::ParseArgs(
    const CompilerInstance& compilerInstance, const std::vector<std::string>& args)
{
    for (auto i = args.begin(); i != args.end(); i++)
    {
        if (*i == "-verbose")
        {
            Log::SetLevel(Log::LogLevel::Verbose);
        }
        else if (*i == "-fix")
        {
            this->_fix = true;
        }
        else
        {
            Log::errs()
                << "ERROR: Unrecognized check-recycler option: " << *i << "\n"
                << "Supported options:\n"
                << "  -fix          Fix missing write barrier annotations"
                << "  -verbose      Log verbose messages\n";
            return false;
        }
    }

    return true;
}

static FrontendPluginRegistry::Add<RecyclerCheckerAction> recyclerPlugin(
    "check-recycler", "Checks the recycler allocations");


text:
package org.spongepowered.server.launch.plugin.asm;

import static org.objectweb.asm.Opcodes.ASM5;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.spongepowered.plugin.meta.PluginMetadata;

import javax.annotation.Nullable;

public final class PluginClassVisitor extends ClassVisitor {

    private static final String PLUGIN_DESCRIPTOR = "Lorg/spongepowered/api/plugin/Plugin;";

    private String className;
    @Nullable private PluginAnnotationVisitor annotationVisitor;

    public PluginClassVisitor() {
        super(ASM5);
    }

    public String getClassName() {
        return this.className;
    }

    public PluginMetadata getMetadata() {
        return this.annotationVisitor != null ? this.annotationVisitor.getMetadata() : null;
    }

    @Override
    public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
        this.className = name;
    }

    @Override @Nullable
    public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
        if (visible && desc.equals(PLUGIN_DESCRIPTOR)) {
            return this.annotationVisitor = new PluginAnnotationVisitor(this.className);
        }

        return null;
    }

}


text:
'use strict';

var logger = require('log4js').getLogger('Unit-Test');
var telegram = require(__dirname + '/../atmessager/lib/telegram');

var nconf = require('nconf');
nconf.file('bots', __dirname + '/config/bots.json')
	.file('receviers', __dirname + '/config/receivers.json')
	.file('testconfig', __dirname + '/config/testconfig.json');

var config = {
	receivers: nconf.get('receivers'),
	bots: nconf.get('bots')
};

exports['Test send message'] = {

	'Test receiver not found': function(test) {

		var receiver = 'wrong_receiver';
		var message = 'Hello World!';
		var botname = nconf.get('message').botname;
		var password = nconf.get('message').password;

		telegram.sendMessage(config, receiver, message, botname,
			function(err, result) {

				logger.debug('Error: ', err);
				logger.debug('Message:', result);

				test.ok(err !== null, 'It should return error! ');

				test.done();
			});
	},

	'Test bot not found': function(test) {

		var receiver = nconf.get('message').receiver;
		var message = 'Hello World!';
		var botname = 'wrongbot';
		var password = nconf.get('message').password;

		telegram.sendMessage(config, receiver, message, botname,
			function(err, result) {

				logger.debug('Error: ', err);
				logger.debug('Message:', result);

				test.ok(err !== null, 'It should return error! ');

				test.done();
			});
	},

	'Test send message success': function(test) {

		var receiver = nconf.get('message').receiver;
		var message = 'Hello World!';
		var botname = nconf.get('message').botname;
		var password = nconf.get('message').password;

		telegram.sendMessage(config, receiver, message, botname,
			function(err, result) {

				logger.debug('Error: ', err);
				logger.debug('Message:', result);

				test.equal(err, null, 'It should not have any error.');
				test.ok(result !== null, 'It should return success message!');

				test.done();
			});
	},

}


text:
using System;

namespace De.Osthus.Ambeth.Objrefstore
{
    public abstract class IObjRefStoreFactory
    {
        public abstract ObjRefStore CreateObjRef();

        public abstract ObjRefStore CreateObjRef(Object id, Object version);
    }
}


text:
namespace cc {
class PaintCanvas;
}

namespace blink {
class WebRemoteFrameImpl;

class RemoteFrameClientImpl final : public RemoteFrameClient {
 public:
  explicit RemoteFrameClientImpl(WebRemoteFrameImpl*);

  void Trace(Visitor*) override;

  // FrameClient overrides:
  bool InShadowTree() const override;
  void Detached(FrameDetachType) override;
  Frame* Opener() const override;
  void SetOpener(Frame*) override;
  Frame* Parent() const override;
  Frame* Top() const override;
  Frame* NextSibling() const override;
  Frame* FirstChild() const override;
  base::UnguessableToken GetDevToolsFrameToken() const override;

  // RemoteFrameClient overrides:
  void Navigate(const ResourceRequest&,
                blink::WebLocalFrame* initiator_frame,
                bool should_replace_current_entry,
                bool is_opener_navigation,
                bool prevent_sandboxed_download,
                bool initiator_frame_is_ad,
                mojo::PendingRemote<mojom::blink::BlobURLToken>,
                const base::Optional<WebImpression>& impression) override;
  unsigned BackForwardLength() override;
  void ForwardPostMessage(MessageEvent*,
                          scoped_refptr<const SecurityOrigin> target,
                          base::Optional<base::UnguessableToken> cluster_id,
                          LocalFrame* source) const override;
  void FrameRectsChanged(const IntRect& local_frame_rect,
                         const IntRect& screen_space_rect) override;
  void UpdateRemoteViewportIntersection(
      const ViewportIntersectionState& intersection_state) override;
  void AdvanceFocus(mojom::blink::FocusType, LocalFrame*) override;
  uint32_t Print(const IntRect&, cc::PaintCanvas*) const override;

  WebRemoteFrameImpl* GetWebFrame() const { return web_frame_; }

 private:
  Member<WebRemoteFrameImpl> web_frame_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_FRAME_REMOTE_FRAME_CLIENT_IMPL_H_


text:
'use strict';

/* Parse data access layer
 * All methods use node-style callback:
 *   On success: callback(null, result obj)
 *   On error:   callback(Error/Parse-Error obj) - .message for string
 *
 * Users:
 *   login
 *   signUp
 *   logout
 *   pinProduct
 *   borrowProduct
 *
 * Products:
 *   addProduct - Create
 *   findProducts - Read, cached
 */
angular.module('parseService', [])
.factory('ParseService', function() {
  Parse.initialize('ixCXGcpZanUyXQKNMWDCSTLdEhhSeVymvE6HEH6F', 'ewTYaHPjOa73YjmHjHoBks0UO5IaPw4jKMlucghA');

  // cache stuff
  var loggedInUser;
  var productsCache;

  var Product = Parse.Object.extend('Product');

  var ParseService = {
    name: 'Parse',

    login: function login(username, password, done) {
      Parse.User.logIn(username, password, {
        success: function(user) {
          loggedInUser = user;
          done();
        },
        error: function(user, error) {
          done(error);
        }
      });
    },

    signUp: function signUp(username, password, done) {
      Parse.User.signUp(username, password, { ACL: new Parse.ACL() }, {
        success: function(user) {
          loggedInUser = user;
          done();
        },
        error: function(user, error) {
          done(error);
        }
      });
    },

    logout: function logout() {
      Parse.User.logOut();
    },

    username: function username() {
      if (Parse.User.current()) {
        return Parse.User.current().get('username');
      } else {
        return '';
      }
    },

    pinProduct: function pinProduct(pid, done) {
      Parse.User.current().addUnique('productsPinned', pid);
      Parse.User.current().save(null, {
        success: function(product) {
          done(null, product);
        },
        error: function(product, err) {
          done(err);
        }
      });
    },

    /* Set product's in-use to true and add lendee. Add pid to user's products */
    borrowProduct: function borrowProduct(pid, done) {
      if (!Parse.User.current()) {
        return done(new Error('Must be logged in to do this'));
      }

      var query = new Parse.Query('Product');
      query.equalTo('pid', pid);
      query.first()
      .then(function(product) {
        if (product.inUse) {
          throw new Error('Product has already been borrowed');
        }
        product.set('inUse', true);
        product.set('lendee', Parse.User.current().get('username'));
        return product.save();
      })
      .then(function() {
        Parse.User.current().addUnique('productsBorrowed');
        return Parse.User.current().save();
      })
      .then(function() {
        done();
      }, function(err) {
        done(err);
      });
    },

    addProduct: function addProduct(fields, done) {
      if (!Parse.User.current()) {
        return done(new Error('Must be logged in to do this'));
      }

      var product = new Product();
      ['gender', 'size', 'productId', 'category', 'imageUrl', 'description', 'name', 'company', 'imageUrl'].forEach(function(key) {
        if (fields[key]) {
          product.set(key, fields[key]);
        }
      });
      product.set('owner', Parse.User.current().get('username'));
      product.set('pid', uuid.v1());
      product.set('inUse', false);

      var productACL = new Parse.ACL();
      productACL.setPublicReadAccess(true);
      productACL.setWriteAccess(Parse.User.current().id, true);
      product.setACL(productACL);

      product.save(null, {
        success: function(product) {
          done(null, product);
        },
        error: function(product, error) {
          done(error);
        }
      });
    },

    /* filters: {field: value} equalities added to query
     * eg. I only want 'Wedding' dresses of size 'S':
     *
     *   findProducts({category: 'Wedding', size 'S'}, callback);
     */
    findProducts: function findProducts(filters, done) {
      var query = new Parse.Query(Product);
      _.forOwn(filters, function(val, key) {
        query.equalTo(key, val);
      });

      query.find({
        success: function(results) {
          productsCache = results;
          done(null, results);
        },
        error: done
      });
    },

    /* My products: products I own, have pinned, and have currently borrowed */
    findMyProducts: function findMyProducts(done) {
      var ownedQuery = new Parse.query(Product);
      ownedQuery.equalTo('owner', Parse.User.current().get('username'));
    },

    findProduct: function findProduct(pid, done) {
      if (productsCache && productsCache.length > 0) {
        var match = _.filter(productsCache, function(obj) {
          return obj.pid === pid;
        });
        if (match.length > 0) {
          done(null, match[0]);
        } else {
          return _findProductByPid(pid, done);
        }
      } else {
        return _findProductByPid(pid, done);
      }
    }
  };

  function _findProductByPid(pid, done) {
    var query = new Parse.Query(Product);
    query.equalTo('pid', pid);
    query.first().then(function(result) {
      done(null, result);
    }, done);
  }

  return ParseService;

});


text:
{% load comments i18n crispy_forms_tags fluent_comments_tags %}

{% if not form.target_object|comments_are_open %}

{% trans "Comments are closed." %}

{% else %}
  {% if not form.helper or not form.helper.form_tag %}
    <form id="comment-form-{{ form.target_object.pk }}" data-object-id="{{ form.target_object.pk }}" action="{% comment_form_target %}" method="post" class="{% block form_class %}{{ form.helper.form_class|default:'js-comments-form comments-form form-horizontal' }}{% endblock %}"
          data-ajax-action="{% url 'comments-post-comment-ajax' %}">
      {% if next %}
<input type="hidden" name="next" value="{{ next }}" />
{% endif %}
  {% endif %}

      {% block comment_form %}
        {% block form_fields %}
          {% crispy form %}
        {% endblock %}

        {% block form_actions %}
          {% if not form.helper.inputs %}

                <input type="submit" name="post" class="btn btn-primary" value="{% trans 'Post' %}" />
                <input type="submit" name="preview" class="btn btn-default" value="{% trans 'Preview' %}" />
                {% ajax_comment_tags for form.target_object %}

          {% else %}
            {% ajax_comment_tags for form.target_object %}
          {% endif %}
        {% endblock %}
      {% endblock %}

  {% if not form.helper or not form.helper.form_tag %}
    </form>
  {% endif %}
{% endif %}


text:
imports.gi.versions.Gtk = imports.gi.GLib.getenv("GTK");

(function (Gio, GLib, Gtk4, GObject) {
    'use strict';

    const extensionUtils = imports.misc.extensionUtils;
    if (!extensionUtils.gettext) {
        // backport from v41
        // https://gitlab.gnome.org/GNOME/gnome-shell/-/blob/1deb13e1aaabfd04b2641976a224b6fc2be3b9ec/js/misc/extensionUtils.js#L117
        const domain = extensionUtils.getCurrentExtension().metadata['gettext-domain'];
        extensionUtils.initTranslations(domain);
        const gettextForDomain = imports.gettext.domain(domain);
        if (gettextForDomain.gettext) {
            Object.assign(extensionUtils, gettextForDomain);
        }
        else {
            logError(new Error(`could create gettextForDomain domain=${domain}`));
        }
    }
    const _ = extensionUtils.gettext;

    var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

    function createCommonjsModule(fn, basedir, module) {
    	return module = {
    		path: basedir,
    		exports: {},
    		require: function (path, base) {
    			return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
    		}
    	}, fn(module, module.exports), module.exports;
    }

    function commonjsRequire () {
    	throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
    }

    var stringFormat = createCommonjsModule(function (module) {
    void function(global) {

      //  ValueError :: String -> Error
      function ValueError(message) {
        var err = new Error(message);
        err.name = 'ValueError';
        return err;
      }

      //  create :: Object -> String,*... -> String
      function create(transformers) {
        return function(template) {
          var args = Array.prototype.slice.call(arguments, 1);
          var idx = 0;
          var state = 'UNDEFINED';

          return template.replace(
            /([{}])\1|[{](.*?)(?:!(.+?))?[}]/g,
            function(match, literal, _key, xf) {
              if (literal != null) {
                return literal;
              }
              var key = _key;
              if (key.length > 0) {
                if (state === 'IMPLICIT') {
                  throw ValueError('cannot switch from ' +
                                   'implicit to explicit numbering');
                }
                state = 'EXPLICIT';
              } else {
                if (state === 'EXPLICIT') {
                  throw ValueError('cannot switch from ' +
                                   'explicit to implicit numbering');
                }
                state = 'IMPLICIT';
                key = String(idx);
                idx += 1;
              }

              //  1.  Split the key into a lookup path.
              //  2.  If the first path component is not an index, prepend '0'.
              //  3.  Reduce the lookup path to a single result. If the lookup
              //      succeeds the result is a singleton array containing the
              //      value at the lookup path; otherwise the result is [].
              //  4.  Unwrap the result by reducing with '' as the default value.
              var path = key.split('.');
              var value = (/^\d+$/.test(path[0]) ? path : ['0'].concat(path))
                .reduce(function(maybe, key) {
                  return maybe.reduce(function(_, x) {
                    return x != null && key in Object(x) ?
                      [typeof x[key] === 'function' ? x[key]() : x[key]] :
                      [];
                  }, []);
                }, [args])
                .reduce(function(_, x) { return x; }, '');

              if (xf == null) {
                return value;
              } else if (Object.prototype.hasOwnProperty.call(transformers, xf)) {
                return transformers[xf](value);
              } else {
                throw ValueError('no transformer named "' + xf + '"');
              }
            }
          );
        };
      }

      //  format :: String,*... -> String
      var format = create({});

      //  format.create :: Object -> String,*... -> String
      format.create = create;

      //  format.extend :: Object,Object -> ()
      format.extend = function(prototype, transformers) {
        var $format = create(transformers);
        prototype.format = function() {
          var args = Array.prototype.slice.call(arguments);
          args.unshift(this);
          return $format.apply(global, args);
        };
      };

      /* istanbul ignore else */
      {
        module.exports = format;
      }

    }.call(commonjsGlobal, commonjsGlobal);
    });

    function toTooltipText(parameters, caption = _('Parameters:')) {
        return parameters
            .reduce((arr, [key, _value, description]) => {
            arr.push(key + '\t' + description);
            return arr;
        }, [caption])
            .join('\n');
    }
    function toObject(parameters) {
        return parameters.reduce((obj, [key, value]) => {
            obj[key] = value;
            return obj;
        }, {});
    }

    function isValidTemplate(s) {
        try {
            stringFormat(s);
            return true;
        }
        catch (e) {
            return false;
        }
    }
    function parameters(v) {
        return [['f', GLib.shell_quote(v.filename), _('Filename')]];
    }
    function tooltipText() {
        return toTooltipText(parameters({ filename: '/path/to/file.png' }));
    }

    function parameters$1({ width, height }) {
        const now = new Date();
        const hostname = GLib.get_host_name();
        const padZero = (s, n) => {
            if (String(s).length < n) {
                return padZero('0' + s, n);
            }
            else {
                return s;
            }
        };
        const pad = (s) => padZero(s, 2);
        return [
            ['N', _('Screenshot'), _('Screenshot (literal)')],
            ['Y', now.getFullYear(), _('Year')],
            ['m', pad(now.getMonth() + 1), _('Month')],
            ['d', pad(now.getDate()), _('Day')],
            ['H', pad(now.getHours()), _('Hour')],
            ['M', pad(now.getMinutes()), _('Minute')],
            ['S', pad(now.getSeconds()), _('Second')],
            ['w', width, _('Width')],
            ['h', height, _('Height')],
            ['hn', hostname, _('Hostname')],
        ];
    }
    function tooltipText$1(vars) {
        return toTooltipText(parameters$1(vars));
    }
    function get(template, vars, n) {
        const basename = stringFormat(template, toObject(parameters$1(vars)));
        let sequence = '';
        if (n && n > 0) {
            sequence = '_' + String(n);
        }
        return basename + sequence + '.png';
    }
    function isValidTemplate$1(template) {
        try {
            stringFormat(template);
            return true;
        }
        catch (e) {
            return false;
        }
    }

    const KeyBackend = 'backend';
    const Backends = {
        DESKTOP_PORTAL: 'desktop-portal',
        GNOME_SCREENSHOT_CLI: 'gnome-screenshot',
    };
    const KeyEnableIndicator = 'enable-indicator';
    const KeyEnableNotification = 'enable-notification';
    const ValueShortcutSelectArea = 'shortcut-select-area';
    const ValueShortcutSelectWindow = 'shortcut-select-window';
    const ValueShortcutSelectDesktop = 'shortcut-select-desktop';
    const ValueShortcutOpenPortal = 'shortcut-open-portal';
    // See schemas/org.gnome.shell.extensions.screenshot.gschema.xml
    const KeyClickAction = 'click-action';
    const ClickActions = {
        SHOW_MENU: 'show-menu',
        SELECT_AREA: 'select-area',
        SELECT_WINDOW: 'select-window',
        SELECT_DESKTOP: 'select-desktop',
        OPEN_PORTAL: 'open-portal',
    };
    const KeySaveScreenshot = 'save-screenshot';
    const KeySaveLocation = 'save-location';
    const KeyFilenameTemplate = 'filename-template';
    // "Auto-Copy to Clipboard" action
    const KeyClipboardAction = 'clipboard-action';
    // Copy button action
    const KeyCopyButtonAction = 'copy-button-action';
    const ClipboardActions = {
        NONE: 'none',
        SET_IMAGE_DATA: 'set-image-data',
        SET_LOCAL_PATH: 'set-local-path',
        SET_REMOTE_URL: 'set-remote-url',
    };
    const KeyEnableUploadImgur = 'enable-imgur';
    const KeyImgurEnableNotification = 'imgur-enable-notification';
    const KeyImgurAutoUpload = 'imgur-auto-upload';
    const KeyImgurAutoCopyLink = 'imgur-auto-copy-link';
    const KeyImgurAutoOpenLink = 'imgur-auto-open-link';
    const KeyEffectRescale = 'effect-rescale';
    const KeyEnableRunCommand = 'enable-run-command';
    const KeyRunCommand = 'run-command';

    function prefSwitch(settingsKey) {
        return {
            type: 'Switch',
            settingsKey,
        };
    }
    function prefComboBox(options, settingsKey) {
        return {
            type: 'ComboBox',
            options,
            settingsKey,
        };
    }
    function prefFileChooser(label, settingsKey) {
        return {
            type: 'FileChooser',
            label,
            settingsKey,
        };
    }
    function prefEntry(opts, settingsKey, validate) {
        return {
            type: 'Entry',
            settingsKey,
            tooltip: opts.tooltip,
            validate,
        };
    }
    function prefPreview(settingsKey, format) {
        return {
            type: 'Preview',
            settingsKey,
            format,
        };
    }
    function enableKey(k) {
        return function (s) {
            return s.get_boolean(k);
        };
    }
    function prefRow(label, widget, { enable = () => true } = {}) {
        return {
            label,
            widget,
            enable,
        };
    }
    function prefKeybinding(label, settingsKey) {
        return { label, settingsKey };
    }
    function prefKeybindings(bindings) {
        return {
            type: 'Keybindings',
            bindings,
        };
    }
    function prefPage(label, child) {
        if (Array.isArray(child)) {
            return { label, rows: child };
        }
        return { label, widget: child };
    }

    function getBackendPrefs() {
        const comboBoxOptions = [
            [_('gnome-screenshot'), Backends.GNOME_SCREENSHOT_CLI],
            [_('Desktop Portal'), Backends.DESKTOP_PORTAL],
        ];
        return [prefRow(_('Backend'), prefComboBox(comboBoxOptions, KeyBackend))];
    }
    function getIndicatorPrefs() {
        const [optionNothing, optionImageData, optionLocalPath] = [
            [_('Nothing'), ClipboardActions.NONE],
            [_('Image Data'), ClipboardActions.SET_IMAGE_DATA],
            [_('Local Path'), ClipboardActions.SET_LOCAL_PATH],
            // TODO
            // [_("Remote URL")    , Config.ClipboardActions.SET_REMOTE_URL]
        ];
        return [
            prefRow(_('Show Indicator'), prefSwitch(KeyEnableIndicator)),
            prefRow(_('Show Notification After Capture'), prefSwitch(KeyEnableNotification)),
            prefRow(_('Primary Button'), prefComboBox([
                [_('Select Area'), ClickActions.SELECT_AREA],
                [_('Select Window'), ClickActions.SELECT_WINDOW],
                [_('Select Desktop'), ClickActions.SELECT_DESKTOP],
                [_('Open Portal'), ClickActions.OPEN_PORTAL],
                [_('Show Menu'), ClickActions.SHOW_MENU],
            ], KeyClickAction)),
            prefRow(_('Copy Button'), prefComboBox([optionImageData, optionLocalPath], KeyCopyButtonAction)),
            prefRow(_('Auto-Copy to Clipboard'), prefComboBox([optionNothing, optionImageData, optionLocalPath], KeyClipboardAction)),
        ];
    }
    function getEffectPrefs() {
        return [
            prefRow(_('Rescale'), prefComboBox([
                ['100%', 100],
                ['50%', 50],
            ], KeyEffectRescale)),
        ];
    }
    function getCommandPrefs() {
        return [
            prefRow(_('Run Command After Capture'), prefSwitch(KeyEnableRunCommand)),
            prefRow(_('Command'), prefEntry({ tooltip: tooltipText() }, KeyRunCommand, isValidTemplate), {
                enable: enableKey(KeyEnableRunCommand),
            }),
        ];
    }
    function getStoragePrefs() {
        const mockDimensions = { width: 800, height: 600 };
        return [
            prefRow(_('Auto-Save Screenshot'), prefSwitch(KeySaveScreenshot)),
            prefRow(_('Save Location'), prefFileChooser(_('Select'), KeySaveLocation), {
                enable: enableKey(KeySaveScreenshot),
            }),
            prefRow(_('Default Filename'), prefEntry({ tooltip: tooltipText$1(mockDimensions) }, KeyFilenameTemplate, isValidTemplate$1)),
            prefRow(_('Preview'), prefPreview(KeyFilenameTemplate, (settings) => {
                return get(settings.get_string(KeyFilenameTemplate), mockDimensions);
            })),
        ];
    }
    function getImgurPrefs() {
        const enableIfImgurEnabled = {
            enable: enableKey(KeyEnableUploadImgur),
        };
        return [
            prefRow(_('Enable Imgur Upload'), prefSwitch(KeyEnableUploadImgur)),
            prefRow(_('Show Upload Notification'), prefSwitch(KeyImgurEnableNotification), enableIfImgurEnabled),
            prefRow(_('Auto-Upload After Capture'), prefSwitch(KeyImgurAutoUpload), enableIfImgurEnabled),
            prefRow(_('Auto-Copy Link After Upload'), prefSwitch(KeyImgurAutoCopyLink), enableIfImgurEnabled),
            prefRow(_('Auto-Open Link After Upload'), prefSwitch(KeyImgurAutoOpenLink), enableIfImgurEnabled),
        ];
    }
    function getKeybindPrefs() {
        return prefKeybindings([
            prefKeybinding(_('Select area'), ValueShortcutSelectArea),
            prefKeybinding(_('Select window'), ValueShortcutSelectWindow),
            prefKeybinding(_('Select whole desktop'), ValueShortcutSelectDesktop),
            prefKeybinding(_('Open portal'), ValueShortcutOpenPortal),
        ]);
    }
    function getPages() {
        return [
            prefPage(_('Indicator'), getIndicatorPrefs()),
            prefPage(_('Effects'), getEffectPrefs()),
            prefPage(_('Commands'), getCommandPrefs()),
            prefPage(_('Storage'), getStoragePrefs()),
            prefPage(_('Imgur'), getImgurPrefs()),
            prefPage(_('Keybindings'), getKeybindPrefs()),
            prefPage(_('Backend'), getBackendPrefs()),
        ];
    }

    const PATH_SEPARATOR = '/';
    function join(...segments) {
        return [''].concat(segments.filter((e) => e !== '')).join(PATH_SEPARATOR);
    }
    function expandUserDir(segment) {
        switch (segment.toUpperCase()) {
            case '$PICTURES':
                const v = GLib.get_user_special_dir(GLib.UserDirectory.DIRECTORY_PICTURES);
                if (v === null) {
                    throw new Error('could not expand special dir');
                }
                return v;
            default:
                return segment;
        }
    }
    function expand(path) {
        return join(...path.split(PATH_SEPARATOR).map(expandUserDir));
    }

    function getGtkVersion() {
        const v = Gtk4.get_major_version();
        if (v === 4) {
            return v;
        }
        throw new Error('unsupported version');
    }
    function getCompatRoot(w) {
        switch (getGtkVersion()) {
            case 4:
                return w.get_root();
        }
        throw new Error('unsupported version');
    }
    function getGVariantClassName(vc) {
        for (const k of Object.keys(GLib.VariantClass)) {
            if (GLib.VariantClass[k] === vc) {
                return k;
            }
        }
        throw new Error(`unknown class ${vc}`);
    }
    function getGObjectTypeFromGVariantClass(vc) {
        switch (vc) {
            case GLib.VariantClass.INT16:
            case GLib.VariantClass.INT32:
            case GLib.VariantClass.INT64:
            case GLib.VariantClass.UINT16:
            case GLib.VariantClass.UINT32:
            case GLib.VariantClass.UINT64:
                return GObject.TYPE_INT;
            case GLib.VariantClass.STRING:
                return GObject.TYPE_STRING;
        }
        throw new Error(`unsupported GVariantClass ${getGVariantClassName(vc)}`);
    }
    function wrapGVariant(v) {
        switch (typeof v) {
            case 'boolean':
                return GLib.Variant.new_boolean(v);
            case 'number':
                return GLib.Variant.new_int32(v);
            case 'string':
                return GLib.Variant.new_string(v);
        }
        throw new Error(`could not find variant fo ${typeof v}`);
    }
    function unwrapGVariant(v) {
        switch (v.classify()) {
            case GLib.VariantClass.ARRAY:
                throw new Error('not supported');
            case GLib.VariantClass.BOOLEAN:
                return v.get_boolean();
            case GLib.VariantClass.BYTE:
                return v.get_byte();
            case GLib.VariantClass.DICT_ENTRY:
                throw new Error('not supported');
            case GLib.VariantClass.DOUBLE:
                return v.get_double();
            case GLib.VariantClass.HANDLE:
                throw new Error('not supported');
            case GLib.VariantClass.MAYBE:
                throw new Error('not supported');
            case GLib.VariantClass.INT16:
                return v.get_int16();
            case GLib.VariantClass.INT32:
                return v.get_int32();
            case GLib.VariantClass.INT64:
                return v.get_int64();
            case GLib.VariantClass.VARIANT:
                throw new Error('not supported');
            case GLib.VariantClass.STRING:
                const [str] = v.get_string();
                return str;
            case GLib.VariantClass.UINT16:
                return v.get_uint16();
            case GLib.VariantClass.UINT32:
                return v.get_uint32();
            case GLib.VariantClass.UINT64:
                return v.get_uint64();
        }
    }
    function addBoxChildren(box, children) {
        children.forEach((w) => {
            switch (getGtkVersion()) {
                case 4:
                    box.append(w);
                    return;
            }
            throw new Error(`invalid gtk version ${getGtkVersion()}`);
        });
    }
    function syncSetting(settings, key, callback) {
        settings.connect('changed::' + key, () => {
            callback(unwrapGVariant(settings.get_value(key)));
        });
        callback(unwrapGVariant(settings.get_value(key)));
    }
    class PrefBuilder {
        constructor(settings, window) {
            this.settings = settings;
            this.window = window;
        }
        getValue(key) {
            return unwrapGVariant(this.settings.get_value(key));
        }
        setValue(key, value) {
            this.settings.set_value(key, wrapGVariant(value));
        }
        getDefaultValue(key) {
            const defaultValue = this.settings.get_default_value(key);
            if (defaultValue === null) {
                throw new Error();
            }
            return unwrapGVariant(defaultValue);
        }
        buildSwitch(p) {
            const w = new Gtk4.Switch();
            syncSetting(this.settings, p.settingsKey, (v) => {
                w.set_active(v);
            });
            w.connect('notify::state', () => {
                this.setValue(p.settingsKey, w.state);
            });
            return w;
        }
        buildComboBox(p) {
            const defaultValue = this.settings.get_default_value(p.settingsKey);
            if (!defaultValue) {
                throw new Error(`settings ${p.settingsKey} needs default value`);
            }
            if (!defaultValue.classify()) {
                throw new Error(`could not classify default value for ${p.settingsKey}`);
            }
            const valueType = getGObjectTypeFromGVariantClass(defaultValue.classify());
            const model = new Gtk4.ListStore();
            const Columns = { LABEL: 0, VALUE: 1 };
            model.set_column_types([GObject.TYPE_STRING, valueType]);
            const comboBox = new Gtk4.ComboBox({ model });
            const renderer = new Gtk4.CellRendererText();
            comboBox.pack_start(renderer, true);
            comboBox.add_attribute(renderer, 'text', 0);
            for (const [label, value] of p.options) {
                const iter = model.append();
                model.set(iter, [Columns.LABEL, Columns.VALUE], [label, value]);
            }
            comboBox.connect('changed', () => {
                const [success, iter] = comboBox.get_active_iter();
                if (!success) {
                    return;
                }
                const value = model.get_value(iter, Columns.VALUE);
                this.setValue(p.settingsKey, value);
            });
            const setActiveByValue = (v) => {
                const [success, iter] = model.get_iter_first();
                if (!success) {
                    return;
                }
                for (;;) {
                    if (model.get_value(iter, Columns.VALUE) === v) {
                        comboBox.set_active_iter(iter);
                    }
                    if (!model.iter_next(iter)) {
                        return;
                    }
                }
            };
            syncSetting(this.settings, p.settingsKey, (v) => {
                setActiveByValue(v);
            });
            return comboBox;
        }
        buildEntry(p) {
            const w = new Gtk4.Entry({
                hexpand: true,
                tooltip_text: p.tooltip,
                secondary_icon_name: 'document-revert',
            });
            syncSetting(this.settings, p.settingsKey, (v) => {
                if (w.text !== v) {
                    w.text = v;
                }
            });
            w.get_buffer().connect('notify::text', ({ text }) => {
                if (p.validate(text)) {
                    this.setValue(p.settingsKey, text);
                    w.get_style_context().remove_class('error');
                }
                else {
                    w.get_style_context().add_class('error');
                }
            });
            w.connect('icon-press', () => {
                w.text = this.getDefaultValue(p.settingsKey);
            });
            return w;
        }
        buildFileChooser(p) {
            const w = new Gtk4.Button();
            syncSetting(this.settings, p.settingsKey, (path) => {
                const f = Gio.File.new_for_path(expand(path));
                w.label = f.get_basename() || p.label;
            });
            w.connect('clicked', () => {
                const d = new Gtk4.FileChooserDialog({
                    title: p.label,
                    action: Gtk4.FileChooserAction.SELECT_FOLDER,
                    transient_for: getCompatRoot(w),
                    modal: true,
                });
                d.add_button(p.label, Gtk4.ResponseType.OK);
                d.add_button(_('Cancel'), Gtk4.ResponseType.CANCEL);
                d.connect('response', (_dialog, response) => {
                    if (response === Gtk4.ResponseType.OK) {
                        const f = d.get_file();
                        if (!f) {
                            throw new Error('could not get file');
                        }
                        this.setValue(p.settingsKey, f.get_path());
                    }
                    d.close();
                });
                d.show();
            });
            return w;
        }
        buildPreview(p) {
            const w = new Gtk4.Label();
            syncSetting(this.settings, p.settingsKey, () => {
                try {
                    w.label = p.format(this.settings);
                    w.get_style_context().remove_class('error');
                }
                catch (e) {
                    w.label = 'Error';
                    w.get_style_context().add_class('error');
                }
            });
            return w;
        }
        buildPrefWidget(w) {
            switch (w.type) {
                case 'Switch':
                    return this.buildSwitch(w);
                case 'ComboBox':
                    return this.buildComboBox(w);
                case 'Entry':
                    return this.buildEntry(w);
                case 'FileChooser':
                    return this.buildFileChooser(w);
                case 'Preview':
                    return this.buildPreview(w);
            }
            throw new Error('unknown type');
        }
        buildPageRows(rows) {
            const box = new Gtk4.Box({
                orientation: Gtk4.Orientation.VERTICAL,
            });
            const gtkRows = rows.map(({ label, widget }) => {
                const hbox = new Gtk4.Box({
                    orientation: Gtk4.Orientation.HORIZONTAL,
                    margin_top: 10,
                    margin_bottom: 10,
                    margin_start: 10,
                    margin_end: 10,
                });
                addBoxChildren(hbox, [
                    new Gtk4.Label({
                        label,
                        hexpand: true,
                        xalign: 0,
                    }),
                    this.buildPrefWidget(widget),
                ]);
                return hbox;
            });
            addBoxChildren(box, gtkRows);
            function updateSensitive(settings) {
                gtkRows.forEach((gtkRow, i) => {
                    gtkRow.set_sensitive(rows[i].enable(settings));
                });
            }
            this.settings.connect('changed', () => {
                updateSensitive(this.settings);
            });
            updateSensitive(this.settings);
            return box;
        }
        buildPrefKeybindings(p) {
            const model = new Gtk4.ListStore();
            model.set_column_types([GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_INT, GObject.TYPE_INT]);
            const ColumnConfigKey = 0;
            const ColumnLabel = 1;
            const ColumnShortcutModifiers = 2;
            const ColumnShortcutKey = 3;
            for (const { label, settingsKey } of p.bindings) {
                const binding = this.settings.get_strv(settingsKey)[0];
                let key, mods;
                if (binding) {
                    switch (getGtkVersion()) {
                        case 4:
                            const [success, ...parsed] = Gtk4.accelerator_parse(binding);
                            if (!success) {
                                throw new Error(`could not parse ${binding}`);
                            }
                            [key, mods] = parsed;
                    }
                }
                else {
                    [key, mods] = [0, 0];
                }
                const row = model.append();
                model.set(row, [ColumnConfigKey, ColumnLabel, ColumnShortcutModifiers, ColumnShortcutKey], [settingsKey, label, mods, key]);
            }
            const treeview = new Gtk4.TreeView({
                hexpand: true,
                vexpand: true,
                model,
            });
            {
                const cellrend = new Gtk4.CellRendererText();
                const col = new Gtk4.TreeViewColumn({
                    title: _('Keyboard Shortcut'),
                    expand: true,
                });
                col.pack_start(cellrend, true);
                col.add_attribute(cellrend, 'text', ColumnLabel);
                treeview.append_column(col);
            }
            {
                const cellrend = new Gtk4.CellRendererAccel({
                    editable: true,
                    accel_mode: Gtk4.CellRendererAccelMode.GTK,
                });
                cellrend.connect('accel-edited', (rend, path, key, mods) => {
                    const value = Gtk4.accelerator_name(key, mods);
                    const [succ, iterator] = model.get_iter_from_string(path);
                    if (!succ) {
                        throw new Error('Error updating keybinding');
                    }
                    const name = model.get_value(iterator, ColumnConfigKey);
                    model.set(iterator, [ColumnShortcutModifiers, ColumnShortcutKey], [mods, key]);
                    if (typeof name !== 'string') {
                        throw new Error();
                    }
                    this.settings.set_strv(name, [value]);
                });
                cellrend.connect('accel-cleared', (rend, path) => {
                    const [succ, iterator] = model.get_iter_from_string(path);
                    if (!succ) {
                        throw new Error('Error clearing keybinding');
                    }
                    const name = model.get_value(iterator, ColumnConfigKey);
                    model.set(iterator, [ColumnShortcutModifiers, ColumnShortcutKey], [0, 0]);
                    if (typeof name !== 'string') {
                        throw new Error();
                    }
                    this.settings.set_strv(name, []);
                });
                const col = new Gtk4.TreeViewColumn({ title: _('Modify'), min_width: 200 });
                col.pack_end(cellrend, false);
                col.add_attribute(cellrend, 'accel-mods', ColumnShortcutModifiers);
                col.add_attribute(cellrend, 'accel-key', ColumnShortcutKey);
                treeview.append_column(col);
            }
            return treeview;
        }
    }
    function buildPrefPages(pages, settings, window) {
        const builder = new PrefBuilder(settings, window);
        const notebook = new Gtk4.Notebook();
        pages.forEach((p) => {
            const { label } = p;
            if ('rows' in p) {
                notebook.append_page(builder.buildPageRows(p.rows), new Gtk4.Label({ label }));
            }
            if ('widget' in p) {
                notebook.append_page(builder.buildPrefKeybindings(p.widget), new Gtk4.Label({ label }));
            }
        });
        return notebook;
    }

    const GioSSS = Gio.SettingsSchemaSource;
    function getSettingsSchema() {
        // Expect USER extensions to have a schemas/ subfolder, otherwise assume a
        // SYSTEM extension that has been installed in the same prefix as the shell
        const schema = 'org.gnome.shell.extensions.screenshot';
        const schemaPath = GLib.getenv('SCHEMA_DIR') || './res/schemas';
        const schemaDir = Gio.File.new_for_path(schemaPath);
        if (!schemaDir || !schemaDir.query_exists(null)) {
            throw new Error(`${schemaPath} does not exist`);
        }
        const schemaSource = GioSSS.new_from_directory(schemaDir.get_path(), GioSSS.get_default(), false);
        const schemaObj = schemaSource.lookup(schema, true);
        if (!schemaObj) {
            throw new Error(`could not lookup ${schema}`);
        }
        return schemaObj;
    }
    function getSettings() {
        const schema = getSettingsSchema();
        const settings = new Gio.Settings({ settings_schema: schema });
        if (GLib.getenv('RESET') === '1') {
            schema.list_keys().forEach((k) => {
                log(`reset ${k}`);
                settings.reset(k);
            });
        }
        return settings;
    }
    class PrefsAppWindow {
        constructor(app) {
            this.app = app;
        }
        getWindow() {
            const windowConfig = {
                application: this.app,
                default_height: 600,
                default_width: 800,
            };
            let window;
            switch (imports.gi.versions.Gtk) {
                case '4.0':
                    window = new Gtk4.ApplicationWindow(windowConfig);
                    window.set_child(buildPrefPages(getPages(), getSettings(), window));
                    break;
                default:
                    throw new Error('not supported');
            }
            return window;
        }
    }
    const application = new Gtk4.Application({
        application_id: 'org.gnome.GnomeShellScreenshot.PrefsTestApp',
        flags: Gio.ApplicationFlags.FLAGS_NONE,
    });
    application.connect('activate', (app) => {
        let activeWindow = app.active_window;
        if (!activeWindow) {
            const imageViewerWindow = new PrefsAppWindow(app);
            activeWindow = imageViewerWindow.getWindow();
        }
        activeWindow.present();
    });
    application.run(null);

}(imports.gi.Gio, imports.gi.GLib, imports.gi.Gtk, imports.gi.GObject));


text:
#include "cairo-test.h"
#include <float.h>

#define SIZE 256

/* This test is designed to test the accuracy of the rendering of mesh
 * patterns.
 *
 * Color accuracy is tested by a square patch covering the whole
 * surface with black and white corners.
 *
 * Extents accuracy is checked by a small red square patch at the
 * center of the surface which should measure 2x2 pixels.
 */

static cairo_test_status_t
draw (cairo_t *cr, int width, int height)
{
    cairo_pattern_t *pattern;
    double offset;

    cairo_test_paint_checkered (cr);

    pattern = cairo_pattern_create_mesh ();

    cairo_mesh_pattern_begin_patch (pattern);

    cairo_mesh_pattern_move_to (pattern, 0, 0);
    cairo_mesh_pattern_line_to (pattern, 1, 0);
    cairo_mesh_pattern_line_to (pattern, 1, 1);
    cairo_mesh_pattern_line_to (pattern, 0, 1);

    cairo_mesh_pattern_set_corner_color_rgb (pattern, 0, 0, 0, 0);
    cairo_mesh_pattern_set_corner_color_rgb (pattern, 1, 1, 1, 1);
    cairo_mesh_pattern_set_corner_color_rgb (pattern, 2, 0, 0, 0);
    cairo_mesh_pattern_set_corner_color_rgb (pattern, 3, 1, 1, 1);

    cairo_mesh_pattern_end_patch (pattern);

    cairo_mesh_pattern_begin_patch (pattern);

    /* A small 1x1 red patch, that should be rendered as a 2x2 red
     * square in the center of the image */

    offset = 0.5 / SIZE;

    cairo_mesh_pattern_move_to (pattern, 0.5 + offset, 0.5 + offset);
    cairo_mesh_pattern_line_to (pattern, 0.5 + offset, 0.5 - offset);
    cairo_mesh_pattern_line_to (pattern, 0.5 - offset, 0.5 - offset);
    cairo_mesh_pattern_line_to (pattern, 0.5 - offset, 0.5 + offset);

    cairo_mesh_pattern_set_corner_color_rgb (pattern, 0, 1, 0, 0);
    cairo_mesh_pattern_set_corner_color_rgb (pattern, 1, 1, 0, 0);
    cairo_mesh_pattern_set_corner_color_rgb (pattern, 2, 1, 0, 0);
    cairo_mesh_pattern_set_corner_color_rgb (pattern, 3, 1, 0, 0);

    cairo_mesh_pattern_end_patch (pattern);

    cairo_scale (cr, SIZE, SIZE);

    cairo_set_source (cr, pattern);
    cairo_paint (cr);
    cairo_pattern_destroy (pattern);

    return CAIRO_TEST_SUCCESS;
}

CAIRO_TEST (mesh_pattern_accuracy,
	    "Paint mesh pattern",
	    "mesh,pattern", /* keywords */
	    NULL, /* requirements */
	    SIZE, SIZE,
	    NULL, draw)


text:
package gui

import
(
    "time"
    "github.com/gizak/termui"
)

type chatItem struct {
    Time time.Time
    Author string
    Text string
}

type ChatView struct {
    x, y, w, h int
    scroll int
    items []*chatItem
}

func NewChatView() *ChatView {
    return &ChatView{
        items: make([]*chatItem, 0),
    }
}

func (view* ChatView) AddMessage(time time.Time, author, text string) {
    // TODO
}

func (view* ChatView) Clear() {
    view.items = make([]*chatItem, 0)
    view.scroll = 0
    RefreshGUI()
}

func (view* ChatView) ScrollUp() {
    // TODO
}

func (view* ChatView) ScrollDowm() {
    // TODO
}

func (view* ChatView) GetHeight() int {
	return view.h
}

func (view* ChatView) SetHeight(h int) {
	view.h = h
}

func (view* ChatView) SetWidth(w int) {
	view.w = w
}

func (view* ChatView) SetX(x int) {
	view.x = x
}

func (view* ChatView) SetY(y int) {
	view.y = y
}

func (view* ChatView) Buffer() []termui.Point {
    // TODO

    // Render frame

    // Render messages starting from N

    /*
Render single message:
------------------------
HH:MM:SS @username:
  MESSAGE CONTENT
  WRAPPED INTO LINES
HH:MM:SS @username:
  MESSAGE CONTENT
  WRAPPED INTO LINES
HH:MM:SS @username:
  MESSAGE CONTENT
  WRAPPED INTO LINES
HH:MM:SS @username:
  MESSAGE CONTENT
  WRAPPED INTO LINES
HH:MM:SS @username:
  MESSAGE CONTENT SINGLE LINE
HH:MM:SS @username:
  MESSAGE CONTENT SINGLE LINE
HH:MM:SS @username: MESSAGE CONTENT
  WRAPPED INTO LINES
HH:MM:SS @username: MESSAGE CONTENT
  WRAPPED INTO LINES
HH:MM:SS @username: MESSAGE CONTENT SINGLE LINE
HH:MM:SS @username: MESSAGE CONTENT SINGLE LINE
HH:MM:SS @username: MESSAGE CONTENT
  WRAPPED INTO LINES
----------------------
    */

    return make([]termui.Point, 0)
}


text:
'''
The `pillar_roots` wheel module is used to manage files under the pillar roots
directories on the master server.
'''

# Import python libs
import os

# Import salt libs
import salt.utils

def find(path, env='base'):
    '''
    Return a dict of the files located with the given path and environment
    '''
    # Return a list of paths + text or bin
    ret = []
    if env not in __opts__['pillar_roots']:
        return ret
    for root in __opts__['pillar_roots'][env]:
        full = os.path.join(root, path)
        if os.path.isfile(full):
            # Add it to the dict
            with salt.utils.fopen(full, 'rb') as fp_:
                if salt.utils.istextfile(fp_):
                    ret.append({full: 'txt'})
                else:
                    ret.append({full: 'bin'})
    return ret

def list_env(env='base'):
    '''
    Return all of the file paths found in an environment
    '''
    ret = {}
    if env not in __opts__['pillar_roots']:
        return ret
    for f_root in __opts__['pillar_roots'][env]:
        ret[f_root] = {}
        for root, dirs, files in os.walk(f_root):
            sub = ret[f_root]
            if root != f_root:
                # grab subroot ref
                sroot = root
                above = []
                # Populate the above dict
                while not os.path.samefile(sroot, f_root):
                    base = os.path.basename(sroot)
                    if base:
                        above.insert(0, base)
                    sroot = os.path.dirname(sroot)
                for aroot in above:
                    sub = sub[aroot]
            for dir_ in dirs:
                sub[dir_] = {}
            for fn_ in files:
                sub[fn_] = 'f'
    return ret

def list_roots():
    '''
    Return all of the files names in all available environments
    '''
    ret = {}
    for env in __opts__['pillar_roots']:
        ret[env] = []
        ret[env].append(list_env(env))
    return ret

def read(path, env='base'):
    '''
    Read the contents of a text file, if the file is binary then
    '''
    # Return a dict of paths + content
    ret = []
    files = find(path, env)
    for fn_ in files:
        full = fn_.keys()[0]
        form = fn_[full]
        if form == 'txt':
            with salt.utils.fopen(full, 'rb') as fp_:
                ret.append({full: fp_.read()})
    return ret

def write(data, path, env='base', index=0):
    '''
    Write the named file, by default the first file found is written, but the
    index of the file can be specified to write to a lower priority file root
    '''
    if env not in __opts__['pillar_roots']:
        return 'Named environment {0} is not present'.format(env)
    if len(__opts__['pillar_roots'][env]) <= index:
        return 'Specified index {0} in environment {1} is not present'.format(
                index, env)
    if os.path.isabs(path):
        return ('The path passed in {0} is not relative to the environment '
                '{1}').format(path, env)
    dest = os.path.join(__opts__['pillar_roots'][env][index], path)
    dest_dir = os.path.dirname(dest)
    if not os.path.isdir(dest_dir):
        os.makedirs(dest_dir)
    with salt.utils.fopen(dest, 'w+') as fp_:
        fp_.write(data)
    return 'Wrote data to file {0}'.format(dest)


text:
require "shellwords"
require "yaml"
require "socket"
require "webpacker/runner"

module Webpacker
  class DevServerRunner < Webpacker::Runner
    def run
      load_config
      detect_port!
      execute_cmd
    end

    private
      def load_config
        @config_file = File.join(@app_path, "config/webpacker.yml")
        dev_server = YAML.load_file(@config_file)[ENV["RAILS_ENV"]]["dev_server"]

        @hostname          = dev_server["host"]
        @port              = dev_server["port"]

      rescue Errno::ENOENT, NoMethodError
        $stdout.puts "webpack dev_server configuration not found in #{@config_file}."
        $stdout.puts "Please run bundle exec rails webpacker:install to install Webpacker"
        exit!
      end

      def detect_port!
        server = TCPServer.new(@hostname, @port)
        server.close

      rescue Errno::EADDRINUSE
        $stdout.puts "Another program is running on port #{@port}. Set a new port in #{@config_file} for dev_server"
        exit!
      end

      def execute_cmd
        env = { "NODE_PATH" => @node_modules_path.shellescape }
        cmd = [
          "#{@node_modules_path}/.bin/webpack-dev-server",
          "--progress",
          "--color",
          "--config", @webpack_config
        ]

        Dir.chdir(@app_path) do
          exec env, *cmd
        end
      end
  end
end